matrix - Rolling Mean of Rolling Correlation dataframe in Python? -
python beginner here.
what i've done far:
imported price data yahoo finance list of stocks.
between stocks (every combination), computed 20 day rolling correlation dataframe.
i to:
1) calculate 200 day simple moving average each of 20 day rolling correlations.
2) report 200 day moving average results in matrix.
how in python/pandas? thanks, me out ton!
here have far...
import pandas pd pandas import dataframe import datetime import pandas.io.data web pandas.io.data import datareader stocks = ['spy', 'gld', 'uso'] start = datetime.datetime(2014,1,1) end = datetime.datetime(2015,1,1) f = web.datareader(stocks, 'yahoo', start, end) adj_close_df = f['adj close'] correls = pd.rolling_corr(adj_close_df, 20) means = pd.rolling_mean(correls, 200) #<---- error message here!
this start answers questions 1-3 (you should have 1 question per post).
import pandas.io.data web import datetime dt import pandas pd end_date = dt.datetime.now().date() start_date = end_date - pd.dateoffset(years=5) symbols = ['aapl', 'ibm', 'gm'] prices = web.get_data_yahoo(symbols=symbols, start=start_date, end=end_date)['adj close'] returns = prices.pct_change() rolling_corr = pd.rolling_corr_pairwise(returns, window=20)
getting rolling mean of rolling correlation relatively simple single stock against others. example:
pd.rolling_mean(rolling_corr.major_xs('aapl').t, 200).tail() out[34]: aapl gm ibm date 2015-05-08 1 0.313391 0.324728 2015-05-11 1 0.315561 0.327537 2015-05-12 1 0.317844 0.330375 2015-05-13 1 0.320137 0.333189 2015-05-14 1 0.322119 0.335659
to view correlation matrix recent 200 day window:
>>> rolling_corr.iloc[-200:].mean(axis=0) aapl gm ibm aapl 1.000000 0.322119 0.335659 gm 0.322119 1.000000 0.383672 ibm 0.335659 0.383672 1.000000
Comments
Post a Comment