Created
May 3, 2026 20:48
-
-
Save quantra-go-algo/98df903e120c8ef88477a91f730b022a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def make_positions(df_feat: pd.DataFrame, regime: pd.Series, params: dict) -> pd.Series: | |
| """ | |
| Same logic as before, with parameters chosen by WFO. | |
| """ | |
| z_thr = params["z_thr"] | |
| range_size = params["range_size"] | |
| lowvol_size = params["lowvol_size"] | |
| highvol_size = params["highvol_size"] | |
| pos = pd.Series(0.0, index=df_feat.index) | |
| trend = df_feat["trend_20"].fillna(0.0) | |
| z = df_feat["z_20"].fillna(0.0) | |
| for t in pos.index: | |
| r = str(regime.loc[t]) if t in regime.index else "UNCERTAIN" | |
| if r == "TREND_UP": | |
| pos.loc[t] = +MAX_LEVERAGE | |
| elif r == "TREND_DOWN": | |
| pos.loc[t] = -MAX_LEVERAGE | |
| elif r == "LOW_VOL": | |
| pos.loc[t] = float(np.sign(trend.loc[t])) * (lowvol_size * MAX_LEVERAGE) | |
| elif r == "HIGH_VOL": | |
| pos.loc[t] = highvol_size * MAX_LEVERAGE | |
| elif r == "RANGE": | |
| if z.loc[t] > z_thr: | |
| pos.loc[t] = -(range_size * MAX_LEVERAGE) | |
| elif z.loc[t] < -z_thr: | |
| pos.loc[t] = +(range_size * MAX_LEVERAGE) | |
| else: | |
| pos.loc[t] = 0.0 | |
| else: | |
| pos.loc[t] = 0.0 | |
| # Trade next bar (no lookahead) | |
| return pos.shift(1).fillna(0.0) | |
| def backtest(df_feat: pd.DataFrame, pos: pd.Series) -> pd.DataFrame: | |
| bt = pd.DataFrame(index=df_feat.index) | |
| bt["ret_log"] = df_feat["ret"].fillna(0.0) | |
| bt["pos"] = pos.reindex(bt.index).fillna(0.0) | |
| bt["gross"] = bt["pos"] * bt["ret_log"] | |
| bt["cost"] = (COST_BPS / 10000.0) * bt["pos"].diff().abs().fillna(0.0) | |
| bt["net"] = bt["gross"] - bt["cost"] | |
| bt["log_equity"] = bt["net"].cumsum() | |
| bt["equity"] = np.exp(bt["log_equity"]) | |
| return bt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment