ML trading example A developer published a Python walkthrough that trains a GradientBoostingClassifier on Apple (AAPL) daily price data from 2018 to 2024, using simple moving averages, volatility, daily returns and a 10-day momentum feature to predict whether the next close will be higher. The model trades only when its predicted probability of an up move exceeds 55%, and the script plots cumulative strategy returns against a buy-and-hold benchmark. | | import yfinance as yf | | | import pandas as pd | | | import numpy as np | | | from sklearn.ensemble import GradientBoostingClassifier | | | import matplotlib.pyplot as plt | | | 1. Download Historical Data | | | print "Downloading data..." | | | df = yf.download 'AAPL', start='2018-01-01', end='2024-01-01' | | | 2. Feature Engineering | | | print "Engineering features..." | | | df 'SMA 10' = df 'Close' .rolling window=10 .mean | | | df 'SMA 50' = df 'Close' .rolling window=50 .mean | | | df 'Volatility' = df 'Close' .rolling window=10 .std | | | df 'Daily Return' = df 'Close' .pct change | | | Added Momentum feature for the Gradient Booster | | | df 'Momentum' = df 'Close' / df 'Close' .shift 10 - 1 | | | Target: 1 if tomorrow's close is higher, else 0 | | | df 'Target' = df 'Close' .shift -1 df 'Close' .astype int | | | df = df.dropna | | | features = 'SMA 10', 'SMA 50', 'Volatility', 'Daily Return', 'Momentum' | | | X = df features | | | y = df 'Target' | | | 3. Chronological Train/Test Split | | | split index = int len df 0.8 | | | X train, X test = X.iloc :split index , X.iloc split index: | | | y train, y test = y.iloc :split index , y.iloc split index: | | | 4. Train the Gradient Boosting Model | | | print "Training Gradient Boosting model..." | | | Gradient Boosting builds trees sequentially to correct the errors of previous trees | | | model = GradientBoostingClassifier n estimators=100, learning rate=0.05, max depth=3, random state=42 | | | model.fit X train, y train | | | 5. Test the Model with a Confidence Threshold | | | print "Testing model..." | | | Get the raw probability of the "1" Buy class | | | probabilities = model.predict proba X test :, 1 | | | Only buy if the model is more than 55% confident in an upward move | | | predictions = probabilities 0.55 .astype int | | | actual returns = df 'Daily Return' .iloc split index: .copy | | | strategy returns = predictions actual returns | | | 6. Plot the Results | | | print "Plotting results..." | | | cumulative market return = 1 + actual returns .cumprod | | | cumulative strategy return = 1 + strategy returns .cumprod | | | plt.figure figsize= 12, 6 | | | plt.plot cumulative market return.index, cumulative market return, label='Buy and Hold Market ', color='blue' | | | plt.plot cumulative strategy return.index, cumulative strategy return, label='Gradient Boosting Strategy 55% Conf ', color='orange' | | | plt.title 'Gradient Boosting Strategy vs Buy & Hold AAPL ' | | | plt.xlabel 'Date' | | | plt.ylabel 'Cumulative Return' | | | plt.legend | | | plt.grid True, alpha=0.3 | | | plt.show |