计算股票收益率-入仓时

时间:2019-07-18 12:58:48

标签: 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[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      0.0
2018-01-19 15:33:00  27.025  0.0     1.0      0.0
2018-01-19 15:34:00  27.035  370.0     1.0003      0.0

但是期望的结果是这样的:

                      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

似乎我需要循环此操作才能使这种代码正常工作,这意味着我做错了什么。我该怎么办?

1 个答案:

答案 0 :(得分:1)

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.shift(1) 2018-01-19 NaN 2018-01-19 10000.0 2018-01-19 10000.0 2018-01-19 0.0 2018-01-19 0.0的输出时,您的代码无法正常工作的原因就很清楚了:它执行了一个移位,仅此而已。为了使代码正常工作,您需要在现金价值更新后的每个周期内进行转换。