Skip to main content
 首页 » 编程设计

Python Pandas 数据框 : portfolio backtesting investing cashflows on different dates

2025年05月04日10davidwang456

假设有以下返回数据帧:

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() 

现在假设我想对两种 Assets 的投资进行回测,同时假设现金流量不同时进行投资:

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) 

我的问题是:是否有一种 pythonic 方法可以让 Apple 的 20,000 美元正现金流和 Google 的 80,000 美元根据各自的每日返回增长?

目前我正在对每个位置(列)进行迭代,然后对第 i 行进行迭代:

wealth.ix[i] = wealth.ix[i-1] * (1 + returns[i]) 

但我知道使用 Python 和 Pandas 通常可以避免这种迭代。

感谢您为此付出的时间。

link to iPython Notebook

西蒙

请您参考如下方法:

首先,您需要将头寸更改为远期填充,因为您保留了投资。

pos = pd.DataFrame.from_dict(positions).reindex(returns.index).fillna(method="ffill") 

然后你需要cumprod

wealth = pos.shift() * (1+returns).cumprod(axis=0) 

shift 是必需的,因为您不会在第一天获得返回。