我从Yahoo Finance下载了日期为“ 12/31/2008”和“ 12/31/2018”之间的公司“ AAPL”,“ BA”,“ GS”和DJIA指数的每日调整后价格数据,以及然后根据调整将其转换为每日收益。关闭。
# 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)
Ticker_List = ['AAPL','BA','GS','^DJI']
ReturnData = getReturns(Ticker_List, start_dt, end_dt, freq='daily')
ReturnData.columns = ['AAPL','BA','GS','DJIA']
我想使用 for循环,通过每次遍历252个每日数据点并将结果保存到新变量中,来计算3种股票和DJIA的滚动年度收益。
我知道如何使用滚动功能,但是我不确定如何使用for循环来完成相同的操作。有谁知道这是怎么做到的吗?