How do I modify this function to use a percentage risk instead of current fixed risk_per_trade
of 50?
I would like to start with 1000 and use 5 percent.
Function to modify:
def tradingStats(win_loss_series,risk_per_trade):
df = pd.DataFrame(win_loss_series, columns=["win"])
df.loc[df["win"] == True, "win_loss_amount"] = risk_per_trade
df.loc[df["win"] == False, "win_loss_amount"] = -risk_per_trade
df["Cumulative"] = df.win_loss_amount.cumsum()
return df
Args the updated function should accept:
def tradingStats(win_loss_series,risk_percent_per_trade=5,starting_amount=1000):
Example data
np.random.seed(9)
win_loss_series = pd.Series(
np.random.choice([True,False], 20),
index=pd.date_range("2022-01-01", "2022-01-30", freq="B")
)
tradingStats(win_loss_series,50).head(8)
win win_loss_amount Cumulative
2022-01-03 True 50.0 50.0
2022-01-04 True 50.0 100.0
2022-01-05 True 50.0 150.0
2022-01-06 False -50.0 100.0
2022-01-07 True 50.0 150.0
2022-01-10 True 50.0 200.0
2022-01-11 False -50.0 150.0
2022-01-12 True 50.0 200.0
Ideally the Cumulative gains would be compounded but I can ask in another question if it's too difficult.
CodePudding user response:
Just change the column to a multiplier rather than an additive amount, and use cumprod()
.
e.g.
def tradingStats(win_loss_series, risk_percent_per_trade=5, starting_amount=1000):
df = pd.DataFrame(win_loss_series, columns=["win"])
df.loc[df["win"] == True, "win_loss_mult"] = 1 risk_percent_per_trade / 100
df.loc[df["win"] == False, "win_loss_mult"] = 1 - risk_percent_per_trade / 100
df["Cumulative"] = df["win_loss_mult"].cumprod() * starting_amount
return df
Output:
win win_loss_mult Cumulative
2022-01-03 True 1.05 1050.000000
2022-01-04 True 1.05 1102.500000
2022-01-05 True 1.05 1157.625000
2022-01-06 False 0.95 1099.743750
2022-01-07 True 1.05 1154.730938
2022-01-10 True 1.05 1212.467484
2022-01-11 False 0.95 1151.844110
2022-01-12 True 1.05 1209.436316