Question
Calculate Rolling Return/Moving Average in Python I download daily adjusted price data for the companies 'AAPL','BA','GS', and the DJIA index from yahoo finance between the
Calculate Rolling Return/Moving Average in Python
I download daily adjusted price data for the companies 'AAPL','BA','GS', and the DJIA index from yahoo finance between the date '12/31/2008' and '12/31/2018' and then convert into daily returns based on Adj. Close.
# Download price data import pandas as pd from pandas_datareader import data as pdr import fix_yahoo_finance as yf yf.pdr_override() import datetime start_dt = datetime.datetime(2008, 12, 31) end_dt = datetime.datetime(2018, 12, 31) def getDataBatch(tickers, startdate, enddate): def getData(ticker): return (pdr.get_data_yahoo(ticker, start=startdate, end=enddate)) datas = map(getData, tickers) return(pd.concat(datas, keys=tickers, names=['Ticker', 'Date'])) data_AAPL = pdr.get_data_yahoo('AAPL', start=start_dt, end=end_dt) data_BA = pdr.get_data_yahoo('BA', start=start_dt, end=end_dt) data_GS = pdr.get_data_yahoo('GS', start=start_dt, end=end_dt) data_DJIA = pdr.get_data_yahoo('^DJI', start=start_dt, end=end_dt) #Convert into daily return def getReturns(tickers, start_dt, end_dt, freq): px_data = getDataBatch(tickers, start_dt, end_dt) px = px_data[['Adj Close']].reset_index().pivot(index='Date', columns='Ticker', values='Adj Close') if (freq=='daily'): px = px.resample('D').last() ret = px.pct_change().dropna() ret.columns = tickers return(ret) ReturnData = getReturns(Ticker_List, start_dt, end_dt, freq='daily') ReturnData.columns = ['AAPL','BA','GS','DJIA']
a) Calculate rolling annual returns for the 3 stocks and DJIA using a for loop by looping through 252 daily data points each time and saving the results into a new variable. Not using the rolling function)
b) Use Boolean indexing to calculate the conditional annual mean of returns of the stocks when DJIA returns are (1) positive and (2) negative
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started