Python Pandas 数据框:投资组合回测在不同日期的现金流
假设我们有一个关于收益的数据表:
import numpy as np
import pandas as pd
import pandas.io.data as web
data = web.DataReader(['AAPL','GOOG'],data_source='google')
returns = data['Close'].pct_change()
现在假设我想对这两个资产进行回测投资,并且假设现金流不是同时投资的:
positions = {}
positions['APPL'] = {returns.index[10]: 20000.0}
positions['GOOG'] = {returns.index[20]: 80000.0}
wealth = pd.DataFrame.from_dict(positions).reindex(returns.index).fillna(0.0)
我的问题是:有没有一种Python的方式,让在苹果上获得的2万美元和在谷歌上获得的8万美元的正现金流,按照它们各自的每日收益来增长呢?
目前我是在逐个位置(列)和每一行进行循环:
wealth.ix[i] = wealth.ix[i-1] * (1 + returns[i])
但我知道在Python和Pandas中,通常可以避免这种循环。
感谢你花时间来帮助我。
西蒙
1 个回答
1
首先,你需要把你的状态改成“向前填充”,因为你要继续持有这项投资。
pos = pd.DataFrame.from_dict(positions).reindex(returns.index).fillna(method="ffill")
然后你需要用到 cumprod
这个函数。
wealth = pos.shift() * (1+returns).cumprod(axis=0)
使用 shift
是必要的,因为你在第一天是没有收益的。