Is there a better way (performance-wise) for doing the following loop in pandas (assuming df is a 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
I will be grateful for any advices because I just started going through Pandas route and, obviously, may miss something crucial.
Source CSV data:
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
Desired output:
Date,sp500,sp500 MA,UNRATE,UNRATE MA,signal,position
2000-01-01,,,4.0,4.191666666666665,1,0.02
2000-01-02,,,4.0,4.191666666666665,1,0.04
2000-01-03,102.93,95.02135,4.0,4.191666666666665,1,0.06
2000-01-04,98.91,95.0599,4.0,4.191666666666665,1,0.08
2000-01-05,99.08,95.11245000000001,4.0,4.191666666666665,1,0.1
2000-01-06,97.49,95.15450000000001,4.0,4.191666666666665,1,0.12
2000-01-07,103.15,95.21575000000001,4.0,4.191666666666665,1,0.14
2000-01-08,103.15,95.21575000000001,4.0,4.191666666666665,1,0.16
2000-01-09,103.15,95.21575000000001,4.0,4.191666666666665,1,0.18
Update All the answers below (by the moment I am writing this) produce constant position 0.02 value which differs from my naive loop approach.
In other words I am looking for a solution which would give 0.02, 0.04, 0.06, 0.08 etc for the position column.