我有一个带有时间序列索引的pandas Dataframe。 一列包含买入信号,另一列包含卖出信号。
buy 0 0 1 0 1 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0
sell 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0
我想在这个简单化的模型中添加一个州:任何时候最多可以有1个股票:只有当你什么都没有时买入,并且当你有股票时卖出。
buy 0 0 1 0 1 1 0 1 1 1 0 1 0 0 0 0 0 0 0 0
sell 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 0
wallet 0 0 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0
如何根据df['wallet']
和df['buy']
创建df['sell']
列?
答案 0 :(得分:3)
这不是最漂亮的解决方案,但我相信它可以实现您所寻找的目标。
import pandas as pd
df = pd.DataFrame({ 'buy': [0,0,0,1,0,1,1,1,1,1,0,0,0,0,0,0],
'sell': [0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1] })
df['wallet'] = pd.np.where(df['buy'] - df['sell'] < 0, 0, df['buy'].cumsum().count() - df['sell'].cumsum())
df.loc[df['wallet'] > 1, 'wallet'] = 1
答案 1 :(得分:2)
import pandas as pd
wallet = 0
def create_wallet(df_line):
global wallet
if df_line['buy']:
wallet = 1
elif df_line['sell']:
wallet = 0
return wallet
df = pd.DataFrame(
{'buy': [0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], 'sell': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]})
df['wallet'] = df.apply(create_wallet, axis=1)