是否有更好的方法(在性能方面)在熊猫中执行以下循环(假设df为DataFrame)?
for i in range(len(df)):
if df['signal'].iloc[i] == 0: # if the signal is negative
if df['position'].iloc[i - 1] - 0.02 < -1: # if the row above - 0.1 < -1 set the value of current row to -1
df['position'].iloc[i] = -1
else: # if the new col value above -0.1 is > -1 then subtract 0.1 from that value
df['position'].iloc[i] = df['position'].iloc[i - 1] - 0.02
elif df['signal'].iloc[i] == 1: # if the signal is positive
if df['position'].iloc[i - 1] + 0.02 > 1: # if the value above + 0.1 > 1 set the current row to 1
df['position'].iloc[i] = 1
else: # if the row above + 0.1 < 1 then add 0.1 to the value of the current row
df['position'].iloc[i] = df['position'].iloc[i - 1] + 0.02
我将不胜感激,因为我刚开始走熊猫路,很显然,可能会错过一些关键的事情。
源CSV数据:
Date,sp500,sp500 MA,UNRATE,UNRATE MA,signal,position
2000-01-01,,,4.0,4.191666666666665,1,0
2000-01-02,,,4.0,4.191666666666665,1,0
2000-01-03,102.93,95.02135,4.0,4.191666666666665,1,0
2000-01-04,98.91,95.0599,4.0,4.191666666666665,1,0
2000-01-05,99.08,95.11245000000001,4.0,4.191666666666665,1,0
2000-01-06,97.49,95.15450000000001,4.0,4.191666666666665,1,0
2000-01-07,103.15,95.21575000000001,4.0,4.191666666666665,1,0
2000-01-08,103.15,95.21575000000001,4.0,4.191666666666665,1,0
2000-01-09,103.15,95.21575000000001,4.0,4.191666666666665,1,0
更新下面的所有答案(在撰写本文时)产生的position0.02常数与我的幼稚循环方法不同。换句话说,我要寻找这样会给一个解决方案0.02,0.04,0.06,0.08等为position列。
回首忆惘然
慕森卡
汪汪一只猫
相关分类