熊猫:如何累积收益-预测价格

时间:2019-10-31 13:49:24

标签: python pandas numpy return finance

我有一个按日期(月数据)索引的熊猫股价数据框。我要计算以下内容:从1983年1月31日的100只股票开始,价值4100美元(每只股票41.00),如果我可以准确预测下个月的收盘价,那么2012年3月的股票最大绝对价值是多少。

  • 如果下个月的收盘价高于本月的收盘价:以全额现金购买股票并完全参与股票回报
  • 如果下个月的收盘价低于本月的收盘价:卖出所有股票并在月初收取现金(不参与股票损失)

enter image description here

以下是一些示例数据:

df = pd.DataFrame({
    'Date': ['1983-01-01','1983-02-28','1983-03-31','1983-04-30','1983-05-31'],
    'Month End Price': [41.00,46.75,44.25,50.00,59.25]
}).set_index('Date')

df.index = pd.to_datetime(df.index)

例如,1983年2月,股价从41.00增加到46.75,当月回报率为14.02%。因此,我的股票最初价值4100美元,到1983年2月底将升至4100美元*((1 + 14.02%)= $ 4675)。

3月83日,回报为负(价格从46.75跌至44.25)。知道下跌之后,我将在2月底卖出所有价值$ 4675的股票(不包括亏损),然后在1983年4月开始进行再投资。

在1983年4月,股票的表现为+ 12.99%(50.00 / 44.25 -1),所以我的身价将从$ 4675增至$ 4675 *(1 + 12.99%)= 5282.5美元,直到1983年4月结束。

1 个答案:

答案 0 :(得分:1)

您可以更紧凑地执行此操作,但是我将设置一些中间列,以便使逻辑清晰。首先,我将建立一个具有一些起伏的示例数据集。

import pandas as pd

prices = [50.00,46.75,44.25,50.00,59.25,66.50,
          29.25,44.25,59.25,61.00,64.25,65.25]
dates = pd.date_range('01-31-1983','12-31-1983', freq='m')

df = pd.DataFrame({'Month End Price':prices}, index=dates)

这将产生一个如下所示的数据框:

           Month End Price
1983-01-31            50.00
1983-02-28            46.75
1983-03-31            44.25
1983-04-30            50.00
1983-05-31            59.25
1983-06-30            66.50
1983-07-31            29.25
1983-08-31            44.25
1983-09-30            59.25
1983-10-31            61.00
1983-11-30            64.25
1983-12-31            65.25

这: enter image description here

您可以将月度价格波动计算为:

df['Monthly Returns'] = df['Month End Price'].diff()/df['Month End Price']

根据我的理解,我们希望实现所有收益并避免所有损失。我设置了一个乘数列,该列在应该避免损失的月份中等于1,而在有收益的月份中基本上为1 + df['Monthly Returns']。然后我计算一个Cash列,作为Multiplier列的乘积乘以$ 41,这就是我们的本金。这里有一种使用for循环的诱惑,但是使用Pandas时,只要您看到for,通常就会有更快的内置cumprod

df['Multiplier'] = df['Monthly Returns'].apply(lambda x: max(x, 0)) + 1
df['Cash'] = df['Multiplier'].cumprod() * 41

完成所有操作后,我们将看到以下内容:

           Month End Price  Monthly Returns  Multiplier        Cash
1983-01-31            50.00              NaN         NaN   41.000000
1983-02-28            46.75        -0.069519    1.000000   41.000000
1983-03-31            44.25        -0.056497    1.000000   41.000000
1983-04-30            50.00         0.115000    1.115000   45.715000
1983-05-31            59.25         0.156118    1.156118   52.851941
1983-06-30            66.50         0.109023    1.109023   58.613995
1983-07-31            29.25        -1.273504    1.000000   58.613995
1983-08-31            44.25         0.338983    1.338983   78.483145
1983-09-30            59.25         0.253165    1.253165   98.352296
1983-10-31            61.00         0.028689    1.028689  101.173878
1983-11-30            64.25         0.050584    1.050584  106.291623
1983-12-31            65.25         0.015326    1.015326  107.920614

位置值如下:

enter image description here