Optimal Portfolio and Trading Strategy Using Machine Learning

Log in to collect

Onsite backtest IDE

Quant Buffet native backtest IDE

Edit and run Quant Buffet Python for Optimal Portfolio and Trading Strategy Using Machine Learning in the browser. Results update live with equity, drawdown, and metrics charts. Allowed: backtest.data, backtest.engine, backtest.metrics, numpy, pandas. Define ASSETS and make_on_day(prices). Shortcut: Ctrl+Enter. API docs →

Ready — edit code, then Run backtest.
IDE · 50 lines
Quant Buffet syntax cheat sheet (copy / insert)

Paste these fragments into the editor. The sandbox rejects QuantConnect, os, and network libraries.

Required imports
Only these libraries are allowed in the sandbox.
from __future__ import annotations

import numpy as np
import pandas as pd

from backtest.data import load_daily_prices
from backtest.engine import EngineConfig, PortfolioEngine
from backtest.metrics import compute_metrics
ASSETS list (whitelisted ETFs)
Module-level list. Tickers must be in the Quant Buffet whitelist.
ASSETS = ["SPY", "QQQ", "TLT", "GLD", "BIL"]
make_on_day contract
Must return (on_day, ready). on_day calls engine.set_target_weights.
def make_on_day(prices: pd.DataFrame):
    cols = [c for c in ASSETS if c in prices.columns]
    sma = prices[cols].rolling(200, min_periods=200).mean()
    state = {"last": None}

    def on_day(engine: PortfolioEngine, dt: pd.Timestamp) -> None:
        if sma.loc[dt].isna().all():
            return
        key = (dt.year, dt.month)
        if state["last"] == key:
            return
        state["last"] = key
        long = [
            s for s in cols
            if pd.notna(prices.at[dt, s]) and pd.notna(sma.at[dt, s])
            and prices.at[dt, s] > sma.at[dt, s]
        ]
        weights = {} if not long else {s: 1.0 / len(long) for s in long}
        engine.set_target_weights(dt, weights)

    ready = sma.dropna(how="all").index.min() if sma.notna().any().any() else None
    return on_day, ready
Set target weights
Weights should sum to about 1.0. Empty dict = 100% cash.
engine.set_target_weights(dt, {"SPY": 0.60, "BIL": 0.40})

Live backtest performance

CAGR
7.14%
Sharpe
0.42
Max DD
-39.60%
Vol
22.14%
Sortino
0.64
Beta
0.73

Showing saved draft baseline until you re-run.

Equity curve (indexed = 100)

Accent = strategy · dashed grey = buy-and-hold benchmark

2001-012026-0894066
Drawdown
Worst -30.4%-30%
Metrics bar chart
CAGRSharpeSortinoVol|DD|Grey = baseline · Accent = live run
Monthly returns
2020-092026-08 · last 24 months

Export to your platform

Transform Quant Buffet lab code (ASSETS + make_on_day / PortfolioEngine) into native classes for a third-party IDE — then copy and paste.

Run in: QuantConnect Cloud or LEAN CLI · QCAlgorithm with Equity securities and monthly rebalance.

Detected pattern: Absolute momentumAssets: SPY, TLT, GLD, BIL
# Generated from Quant Buffet → QuantConnect LEAN
# Strategy: Optimal Portfolio and Trading Strategy Using Machine Learning
# Detected pattern: Absolute momentum
# Source uses Quant Buffet lab APIs (ASSETS + make_on_day / PortfolioEngine).
# Review fees, data, and risk before live trading — educational export only.

from AlgorithmImports import *


class QuantBuffetExport(QCAlgorithm):
    def Initialize(self):
        self.SetStartDate(2010, 1, 1)
        self.SetCash(100000)
        tickers = ["SPY", "TLT", "GLD", "BIL"]
        self.symbols = []
        for t in tickers:
            if "-" in t:  # crypto proxy e.g. BTC-USD
                self.symbols.append(self.AddCrypto(t.replace("-USD", ""), Resolution.Daily).Symbol)
            else:
                self.symbols.append(self.AddEquity(t, Resolution.Daily).Symbol)
        self.Schedule.On(
            self.DateRules.MonthStart(self.symbols[0]),
            self.TimeRules.AfterMarketOpen(self.symbols[0], 30),
            self.Rebalance,
        )
        # Logic: Long assets with positive 252-day return; equal-weight; monthly.

    def Rebalance(self):
        # Pattern: abs_momentum — Long assets with positive 252-day return; equal-weight; monthly.
        # Default: equal-weight. Port your make_on_day weights here via SetHoldings.
        w = 1.0 / len(self.symbols) if self.symbols else 0.0
        for symbol in self.symbols:
            self.SetHoldings(symbol, w)

Exported code uses the platform’s native classes and libraries. Install dependencies in your third-party IDE, then run. Validate before live trading.

Academic paper

Optimal Portfolio and Trading Strategy Using Machine Learning

AuthorsKarim Ouazzane; Kai Tang; Mohamed Chahine Ghanem

InstituteLondon Metropolitan University

Teaser

Pick the best absolute/relative momentum asset; fall back to T-bills when momentum is negative. Universe: XLB, XLE, XLF, XLI, XLK, XLP, XLU, XLV, XLY, XLC, XLRE, BIL. Parameters: lookback=252; rebalance=monthly. Rebalanced on the engine's template schedule with 5 bps commission and 2 bps slippage. Because the paper's primary signal (ML, sentiment, or proprietary data) is not available in our public ETF engine, this draft uses a liquid ETF rule that preserves the paper's economic theme rather tha

Strategy in a nutshell

This research presents machine learning models for forecasting the future returns of a portfolio from NASDAQ semiconductors assets by financial analysis, optimization, and technical analysis to form a trading strategy. The performance of the portfolio is evaluated by back-testing. Data were collected from 2011 to 2019 for the sector of semiconductor companies listed on Nasdaq. The project consists of 4 sub-tasks. The first sub-task is to use the annual financial ratios of each company under the sector of semiconductors from 2011 to 2018 to project the company returns in 2019 using machine learning algorithms. Then, the top 5 highest-return assets would be selected to form a portfolio. After the optimization of the portfolio by Monte Carlo simulation, the classifiers adopt the technical ind

Economic rationale

Relative momentum captures cross-sectional continuation; absolute momentum gates risk when the trend is negative, shifting to cash. Related evidence from “Optimal Portfolio and Trading Strategy Using Machine Learning”: This research presents machine learning models for forecasting the future returns of a portfolio from NASDAQ semiconductors assets by financial analysis, optimization, and technical analysis to form a trading strategy. The performance of the portfolio is evaluated by back-testing. Data were collected from 2011 to 2019 for the sector of semiconductor companies listed on Nasdaq. The project consists of 4 sub-tasks. The first sub-task is to use the annual financial ratios of each company under the

Backtest performance

Annualised return7.14%
Volatility22.14%
Beta0.73
Sharpe ratio0.42
Sortino ratio0.64
Maximum drawdown-39.60%