Algorithmic Trading & Indicators
Advanced
Random Forest Machine Learning Next-Day Stock Direction Classifier in Python (scikit-learn)
Train a Random Forest Classifier in Python using scikit-learn on technical features (RSI, Returns, Volatility) with strict time-series train/test split.
#pandas#numpy#scikit-learn
Problem Statement
Many ML trading tutorials accidentally shuffle time-series data (`shuffle=True`), causing severe lookahead bias. This script builds lagged return features and trains a walk-forward Random Forest classifier cleanly.
Formula / Core Logic
Features X_t = [Ret_1d, Ret_5d, Vol_10d, Price_to_SMA20]
Target y_t = 1 if Close_{t+1} > Close_t else 0
Installation
pip install pandas numpy scikit-learn
random-forest-machine-learning-stock-signal-classifier-python.py
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
def train_rf_signal_model(df):
d = df.copy()
d['Ret_1'] = d['Close'].pct_change(1)
d['Ret_5'] = d['Close'].pct_change(5)
d['Vol_10'] = d['Ret_1'].rolling(10).std()
d['SMA_Ratio'] = d['Close'] / d['Close'].rolling(20).mean()
d['Target'] = np.where(d['Close'].shift(-1) > d['Close'], 1, 0)
d = d.dropna()
features = ['Ret_1', 'Ret_5', 'Vol_10', 'SMA_Ratio']
split = int(len(d) * 0.8)
X_train, X_test = d[features].iloc[:split], d[features].iloc[split:]
y_train, y_test = d['Target'].iloc[:split], d['Target'].iloc[split:]
model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
model.fit(X_train, y_train)
preds = model.predict(X_test)
return {'Out_of_Sample_Accuracy': round(accuracy_score(y_test, preds) * 100, 2), 'Latest_Prediction': int(preds[-1])}
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: Why set `max_depth=5` in financial Random Forests?
Financial return data has a low signal-to-noise ratio; shallow trees prevent memorizing historical noise (overfitting).