Python 3.x 计算股票回报率-到位时

Python 3.x 计算股票回报率-到位时,python-3.x,pandas,Python 3.x,Pandas,我有一个很大的日期框,上面有某只股票的回报。这只股票有时有仓位,有时没有仓位。 当没有头寸时,结果应该保持不变,只有现金 但当有头寸时,现金金额应该改变。如何在不使用循环的情况下计算此值 我用它来计算每行的股票回报率,没有头寸时为1,有以下情况时为perc_change: df['change']= np.where(df.pos>0, (df.close.pct_change() + 1), 1) 对于现金栏,我有: nomdf['cash'] = 0 nomdf.cash.iloc[

我有一个很大的日期框,上面有某只股票的回报。这只股票有时有仓位,有时没有仓位。 当没有头寸时,结果应该保持不变,只有现金

但当有头寸时,现金金额应该改变。如何在不使用循环的情况下计算此值

我用它来计算每行的股票回报率,没有头寸时为1,有以下情况时为perc_change:

df['change']= np.where(df.pos>0, (df.close.pct_change() + 1), 1)
对于现金栏,我有:

nomdf['cash'] = 0
nomdf.cash.iloc[0] = 10000
nomdf.cash.loc[1:] = nomdf.cash.shift(1) * nomdf.change
但期望的结果是这样的:

                      close  pos  change     cash
date                                             
2018-01-19 15:30:00  26.830  0.0     1.0  10000.0
2018-01-19 15:31:00  26.940  0.0     1.0  10000.0
2018-01-19 15:32:00  26.910  0.0     1.0  10000.0
2018-01-19 15:33:00  27.025  0.0     1.0  10000.0
2018-01-19 15:34:00  27.035  370.0   1.0003  10003.0
似乎我需要循环这个来让这种代码工作,这意味着我做错了什么。我该怎么办

import numpy as np
nomdf.cash = np.cumprod(nomdf.change) * 10000
输出:

                date   close    pos  change     cash
2018-01-19  15:30:00  26.830    0.0  1.0000  10000.0
2018-01-19  15:31:00  26.940    0.0  1.0000  10000.0
2018-01-19  15:32:00  26.910    0.0  1.0000  10000.0
2018-01-19  15:33:00  27.025    0.0  1.0000  10000.0
2018-01-19  15:34:00  27.035  370.0  1.0003  10003.0
当您查看nomdf.cash.shift1的输出时,代码无法工作的原因就变得很清楚了 2018-01-19南 2018-01-19 10000.0 2018-01-19 10000.0 2018-01-19 0.0 2018-01-19 0.0:它只做一次轮班,就这样。为了使代码正常工作,您需要在更新现金价值后的每个周期中进行转换

                date   close    pos  change     cash
2018-01-19  15:30:00  26.830    0.0  1.0000  10000.0
2018-01-19  15:31:00  26.940    0.0  1.0000  10000.0
2018-01-19  15:32:00  26.910    0.0  1.0000  10000.0
2018-01-19  15:33:00  27.025    0.0  1.0000  10000.0
2018-01-19  15:34:00  27.035  370.0  1.0003  10003.0