Python pandas-计算具有循环依赖项的两个序列的更有效方法
我有一个表示股票回报的Python pandas-计算具有循环依赖项的两个序列的更有效方法,python,pandas,Python,Pandas,我有一个表示股票回报的DataFrame。要分割调整收盘价,我有以下方法: def returns(ticker, start=None, end=None): p = historical_prices(ticker, start, end, data='d', convert=True) d = historical_prices(ticker, start, end, data='v', convert=True) p['Dividends'] = d['Divi
DataFrame
。要分割调整收盘价,我有以下方法:
def returns(ticker, start=None, end=None):
p = historical_prices(ticker, start, end, data='d', convert=True)
d = historical_prices(ticker, start, end, data='v', convert=True)
p['Dividends'] = d['Dividends']
p['Dividends'].fillna(value=0, inplace=True)
p['DivFactor'] = 1.
p['SAClose'] = p['Close']
records, fields = p.shape
for t in range(1, records):
p['SAClose'][t] = p['Adj Close'][t] / p['DivFactor'][t-1] + \
p['Dividends'][t-1]
p['DivFactor'][t] = p['DivFactor'][t-1] * \
(1 - p['Dividends'][t-1] / p['SAClose'][t])
p['Lagged SAClose'] = p['SAClose'].shift(periods=-1)
p['Cash Return'] = p['Dividends'] / p['Lagged SAClose']
p['Price Return'] = p['SAClose'] / p['Lagged SAClose'] - 1
return p.sort_index()
注意SAClose
(即拆分调整后的关闭)如何取决于滞后的DivFactor
值。反过来,DivFactor
取决于滞后的DivFactor
值以及当前的SAClose
值
上面的方法可以工作,但在循环部分速度非常慢。有没有更有效的方法让我在熊猫身上这样做?考虑到“循环”依赖性(考虑到滞后,我不确定如何进行常规系列数学运算或使用常规移位运算(例如,我对现金回报的处理)。您可以尝试一次性创建累积调整系数系列,然后不必循环:
(p['Dividends'].fillna(1.) + 1.).cumprod()
你把我推向了正确的方向。。。DivFactor不需要与SAClose循环。也就是说,它似乎有一个表单(请参见编辑)不容易传递到
cumprod
。有什么想法吗?