{"slug": "ml-trading-example", "title": "ML trading example", "summary": "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.", "body_md": "|  | import yfinance as yf | \n|  | import pandas as pd | \n|  | import numpy as np | \n|  | from sklearn.ensemble import GradientBoostingClassifier | \n|  | import matplotlib.pyplot as plt | \n|  | # 1. Download Historical Data | \n|  | print(\"Downloading data...\") | \n|  | df = yf.download('AAPL', start='2018-01-01', end='2024-01-01') | \n|  | # 2. Feature Engineering | \n|  | print(\"Engineering features...\") | \n|  | df['SMA_10'] = df['Close'].rolling(window=10).mean() | \n|  | df['SMA_50'] = df['Close'].rolling(window=50).mean() | \n|  | df['Volatility'] = df['Close'].rolling(window=10).std() | \n|  | df['Daily_Return'] = df['Close'].pct_change() | \n|  | # Added Momentum feature for the Gradient Booster | \n|  | df['Momentum'] = df['Close'] / df['Close'].shift(10) - 1 | \n|  | # Target: 1 if tomorrow's close is higher, else 0 | \n|  | df['Target'] = (df['Close'].shift(-1) > df['Close']).astype(int) | \n|  | df = df.dropna() | \n|  | features = ['SMA_10', 'SMA_50', 'Volatility', 'Daily_Return', 'Momentum'] | \n|  | X = df[features] | \n|  | y = df['Target'] | \n|  | # 3. Chronological Train/Test Split | \n|  | split_index = int(len(df) * 0.8) | \n|  | X_train, X_test = X.iloc[:split_index], X.iloc[split_index:] | \n|  | y_train, y_test = y.iloc[:split_index], y.iloc[split_index:] | \n|  | # 4. Train the Gradient Boosting Model | \n|  | print(\"Training Gradient Boosting model...\") | \n|  | # Gradient Boosting builds trees sequentially to correct the errors of previous trees | \n|  | model = GradientBoostingClassifier(n_estimators=100, learning_rate=0.05, max_depth=3, random_state=42) | \n|  | model.fit(X_train, y_train) | \n|  | # 5. Test the Model with a Confidence Threshold | \n|  | print(\"Testing model...\") | \n|  | # Get the raw probability of the \"1\" (Buy) class | \n|  | probabilities = model.predict_proba(X_test)[:, 1] | \n|  | # Only buy if the model is more than 55% confident in an upward move | \n|  | predictions = (probabilities > 0.55).astype(int) | \n|  | actual_returns = df['Daily_Return'].iloc[split_index:].copy() | \n|  | strategy_returns = predictions * actual_returns | \n|  | # 6. Plot the Results | \n|  | print(\"Plotting results...\") | \n|  | cumulative_market_return = (1 + actual_returns).cumprod() | \n|  | cumulative_strategy_return = (1 + strategy_returns).cumprod() | \n|  | plt.figure(figsize=(12, 6)) | \n|  | plt.plot(cumulative_market_return.index, cumulative_market_return, label='Buy and Hold (Market)', color='blue') | \n|  | plt.plot(cumulative_strategy_return.index, cumulative_strategy_return, label='Gradient Boosting Strategy (>55% Conf)', color='orange') | \n|  | plt.title('Gradient Boosting Strategy vs Buy & Hold (AAPL)') | \n|  | plt.xlabel('Date') | \n|  | plt.ylabel('Cumulative Return') | \n|  | plt.legend() | \n|  | plt.grid(True, alpha=0.3) | \n|  | plt.show() |", "url": "https://wpnews.pro/news/ml-trading-example", "canonical_source": "https://gist.github.com/sergiolucero/444e2a098721e1b2f138bebaea227f79", "published_at": "2026-10-20 09:06:01+00:00", "updated_at": "2026-10-20 09:17:45.419144+00:00", "lang": "en", "topics": ["machine-learning", "ai-tools"], "entities": ["Apple", "yfinance", "scikit-learn", "pandas", "NumPy", "matplotlib"], "also_reported_by": [], "alternates": {"html": "https://wpnews.pro/news/ml-trading-example", "markdown": "https://wpnews.pro/news/ml-trading-example.md", "text": "https://wpnews.pro/news/ml-trading-example.txt", "jsonld": "https://wpnews.pro/news/ml-trading-example.jsonld"}}