Train, re-train, and validate Machine Learning models on rolling historical windows.
Unlike static backtests, Walk-Forward ML simulates the reality of live trading where models are retrained as new data arrives. RLX automates this cycle by partitioning data into rolling segments where each test window is preceded by a fresh training phase.
Inherit from BaseMLStrategy and implement the train and generate_signals methods.
from rlxbt.ml import BaseMLStrategy, WalkForwardML
from sklearn.ensemble import RandomForestRegressor
class MyMLStrategy(BaseMLStrategy):
def __init__(self):
super().__init__(model=RandomForestRegressor())
def train(self, data):
# data is your training slice
X, y = self.prepare_features(data)
self.model.fit(X, y)
def generate_signals(self, data):
X, _ = self.prepare_features(data)
preds = self.model.predict(X)
# Return signal DataFrame (-1, 0, 1)
return preds_to_signals The WalkForwardML trainer orchestrates the entire process and consolidates results into a single report.
bt = Backtester(initial_capital=100000)
wf_trainer = WalkForwardML(backtester=bt)
results = wf_trainer.run(
strategy_class=MyMLStrategy,
data=df,
train_size=5000, # Retrain window
test_size=500, # Trading window
step_size=500 # Shift size
)
print(f"Consolidated Return: {results['total_return']:.2%}")Instead of fixed parameters, you can use Optuna to find the optimal settings for each walk-forward window automatically.
optuna_config = {
"n_trials": 20,
"param_space": {
"n_estimators": ("int", 50, 200),
"max_depth": ("int", 3, 10),
"lr": ("float", 1e-4, 1e-1, True) # Log scale
}
}
results = wf_trainer.run(
strategy_class=MyMLStrategy,
data=df,
optuna_config=optuna_config,
# ... other window params ...
)