我有一个包含3列的数据框。
Date Close pos_chg cash
2000-01-04 81.9375 0.0 10000.00
2000-01-05 69.7500 0.0 0.00
2000-01-06 65.5625 0.0 0.00
2000-01-07 69.5625 0.0 0.00
2000-01-10 69.1875 100.0 0.00
2000-01-11 66.7500 0.0 0.00
2000-01-12 63.5625 -200.0 0.00
2000-01-13 65.9375 200.0 0.00
2000-01-14 64.2500 -200.0 0.00
2000-01-18 64.1250 0.0 0.00
我想要计算什么。
Date Close pos_chg cash
2000-01-04 81.9375 0.0 10000.00
2000-01-05 69.7500 0.0 10000.00
2000-01-06 65.5625 0.0 10000.00
2000-01-07 69.5625 0.0 10000.00
2000-01-10 69.1875 100.0 3081.25
2000-01-11 66.7500 0.0 3081.25
2000-01-12 63.5625 -200.0 15793.75
2000-01-13 65.9375 200.0 2606.25
2000-01-14 64.2500 -200.0 15456.25
2000-01-18 64.1250 0.0 15456.25
我认为这段代码可行。
df['cash']=df['cash'].shift(1)-(df['pos_chg']*df['Close'])
任何帮助表示感谢。
答案 0 :(得分:1)
df['delta_cash'] = (df.Close * -df.pos_chg + df.cash).cumsum()
import pandas as pd
import numpy as np
df = pd.read_fwf(StringIO(u"""
Date Close pos_chg cash
2000-01-04 81.9375 0.0 10000.00
2000-01-05 69.7500 0.0 0.00
2000-01-06 65.5625 0.0 0.00
2000-01-07 69.5625 0.0 0.00
2000-01-10 69.1875 100.0 0.00
2000-01-11 66.7500 0.0 0.00
2000-01-12 63.5625 -200.0 0.00
2000-01-13 65.9375 200.0 0.00
2000-01-14 64.2500 -200.0 0.00
2000-01-18 64.1250 0.0 0.00"""),
skiprows=1)
df['delta_cash'] = (df.Close * -df.pos_chg + df.cash).cumsum()
print(df)
Date Close pos_chg cash delta_cash
0 2000-01-04 81.9375 0.0 10000.0 10000.00
1 2000-01-05 69.7500 0.0 0.0 10000.00
2 2000-01-06 65.5625 0.0 0.0 10000.00
3 2000-01-07 69.5625 0.0 0.0 10000.00
4 2000-01-10 69.1875 100.0 0.0 3081.25
5 2000-01-11 66.7500 0.0 0.0 3081.25
6 2000-01-12 63.5625 -200.0 0.0 15793.75
7 2000-01-13 65.9375 200.0 0.0 2606.25
8 2000-01-14 64.2500 -200.0 0.0 15456.25
9 2000-01-18 64.1250 0.0 0.0 15456.25