agentsclimarketplace

Algo trading ml

Skill WayneBanksy/wayneys_claude/skills/algo-trading-ml

Staff-level algorithmic trading strategy research, ML signal development, backtesting, and performance evaluation for futures (MNQ, MES, MGC). Use when working on trading strategies, backtesting, technical indicators (VWAP, EMA, RSI, MACD, ATR, Bollinger Bands), ML signals (XGBoost, LightGBM), signal research, alpha factors, regime detection, position sizing, or risk metrics (Sharpe, Sortino, max drawdown, win rate). Triggers on: pandas-ta, TA-Lib, VectorBT, Backtrader, QuantStats, PyPortfolioOpt, Topstep, prop firm, combine, momentum, mean reversion, trend following, stat arb, walk-forward validation, feature engineering for trading, OHLCV data, or Jupyter notebooks with price/return series. TRIGGER when: code imports pandas_ta, vectorbt, backtrader, quantstats, pyportfolioopt, or files contain OHLCV columns. DO NOT TRIGGER for: live execution, Tradovate WebSocket, order management, kill switches (defer to automated-trading-systems), or general ML/data engineering without trading context.From its SKILL.md

Install
npx -y skills add WayneBanksy/wayneys_claude --skill algo-trading-ml

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

2 things to look at

  • no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
  • 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.

SKILL.md

15.9 KB, as published. Nobody here has run it

Algo Trading ML

Overview

Staff-level guidance for algorithmic trading strategy research, ML-augmented signal development, backtesting methodology, and performance evaluation. Covers the full research-to-validation lifecycle for futures trading strategies (MNQ/MES/MGC via Topstep), with opinionated defaults on Wayne's primary stack: Python, pandas-ta, XGBoost, VectorBT, QuantStats, and TimescaleDB.

⚠️ Critical Rules

  1. NEVER introduce look-ahead bias. Every feature at bar t MUST use only data from bars ≤ t. Use .shift(1) to align features with next-bar returns. Label targets as future_return computed strictly after the signal bar. No exceptions — this is the #1 cause of backtest-to-live divergence.

  2. NEVER present a strategy without risk metrics. Every strategy result MUST include: Sharpe ratio, Sortino ratio, max drawdown, win rate, profit factor, and average trade duration. Use QuantStats qs.reports.full() for completeness.

  3. NEVER backtest without realistic transaction costs. Include commission ($4.50 round-trip for Topstep/Tradovate MNQ), slippage (minimum 1 tick), and bid-ask spread estimates. A backtest without costs is fiction.

  4. NEVER treat in-sample Sharpe as ground truth. Apply a 50–70% haircut to backtest Sharpe when estimating live performance. Only proceed if the haircut-adjusted Sharpe is still acceptable (>0.5).

  5. NEVER run notebook code directly against live orders. Research lives in Jupyter notebooks. Validated strategy logic gets refactored into Python classes/modules before connecting to any execution layer.

  6. ALWAYS validate with walk-forward methodology. No single train/test split. Use expanding or rolling window walk-forward optimization. A strategy that looks great in-sample but fails out-of-sample is overfit.

  7. ALWAYS document the hypothesis before coding. Write the market logic in plain English first: "This strategy bets that price reverts to VWAP after an ATR-based deviation in low-volume conditions." If you cannot state the hypothesis clearly, the strategy has no edge thesis — stop and think before writing code.

  8. ALWAYS build simple baselines before complex ML models. Verify that a simple moving average crossover or VWAP mean reversion rule has any edge. If the simplest version has no statistical edge, XGBoost will just overfit faster.

Primary Stack

These are the defaults — recommend and use these first, always:

CategoryPrimary Tools
LanguagePython 3.11+ (type hints, dataclasses, asyncio)
Datapandas (primary), polars (>1M rows)
Indicatorspandas-ta (primary), TA-Lib (when performance matters)
MLXGBoost (primary), scikit-learn (preprocessing), LightGBM (fast alt)
BacktestingVectorBT (vectorized research), Backtrader (event-driven)
Time Seriesstatsmodels (ARIMA, GARCH), Prophet (trend/seasonality)
ReportingQuantStats (tear sheets, all key metrics)
Position SizingPyPortfolioOpt (risk parity, mean-variance)
Market DataTradovate API (live), Polygon.io (historical), yfinance (prototyping only)
StoragePostgreSQL + TimescaleDB (OHLCV), Parquet (archival), Redis (live cache)
Visualizationplotly (interactive), mplfinance (candlesticks), matplotlib (static)
ResearchJupyterLab

Secondary (mention when explicitly relevant): NautilusTrader (latency-critical), PyTorch/LSTM (deep learning signals), QuantConnect/LEAN (cloud cross-validation), Riskfolio-Lib (advanced portfolio optimization).

Core Capabilities

1. Strategy Research & Hypothesis Development

Design and document trading strategy hypotheses before writing any code.

Process:

  1. State the hypothesis in plain English (see Critical Rule 7)
  2. Identify the market microstructure logic: why does this edge exist?
  3. Define entry conditions, exit conditions, and filters
  4. Specify the target instruments (MNQ, MES, MGC) and timeframes
  5. List assumptions that could invalidate the hypothesis

Output: A markdown hypothesis doc with: thesis statement, entry/exit logic, expected regime behavior, assumptions, and invalidation criteria.

2. Feature Engineering

Build time-aware features for ML signal models using pandas-ta and custom rolling windows.

Rules:

  • Every feature MUST use .shift(1) or equivalent to prevent look-ahead bias
  • Name columns to make lag explicit: rsi_14_lag1, atr_20_lag1, vwap_dev_lag1
  • Target variable: future_return = close.pct_change().shift(-1) — computed AFTER the signal bar
  • For classification: target = (future_return > threshold).astype(int)

Common feature groups:

  • Trend: EMA ratios, slope of regression, ADX
  • Momentum: RSI, MACD histogram, rate of change, Stochastic
  • Volatility: ATR, Bollinger Band width, historical vol, GARCH
  • Volume: OBV, volume ratio, VWAP deviation, cumulative delta
  • Regime: ATR percentile rank, HMM state, rolling correlation

Use polars when processing >1M rows (multi-year tick data or 1-minute bars). pandas is fine for <1M rows.

3. ML Signal Development

Train, validate, and evaluate ML models for alpha signal generation.

Model hierarchy (try in order):

  1. Simple baseline (SMA crossover, VWAP mean reversion) — Critical Rule 8
  2. Logistic regression / linear model
  3. XGBoost / LightGBM (primary choice for tabular signal data)
  4. Ensemble methods
  5. LSTM / deep learning (only if simpler models show edge but underperform)

Walk-forward validation structure:

# Expanding window walk-forward
for train_end in walk_forward_dates:
    train = data[data.index <= train_end]
    test = data[(data.index > train_end) & (data.index <= train_end + test_window)]
    model.fit(train[features], train[target])
    preds = model.predict(test[features])
    # Store out-of-sample predictions

Overfitting guardrails:

  • Data-points-to-parameters ratio MUST be >200:1
  • Track out-of-sample Sharpe on rolling basis — halt if below threshold
  • Prefer fewer features (5–15) over kitchen-sink approaches
  • Use model.feature_importances_ to prune irrelevant features
  • Cross-validate with purged K-fold (no information leakage between folds)

4. Backtesting & Validation

Run rigorous backtests with realistic market conditions using VectorBT or Backtrader.

Mandatory backtest parameters:

  • Commission: $4.50 per round-trip (Topstep/Tradovate MNQ)
  • Slippage: minimum 1 tick (0.25 points MNQ = $0.50, 0.25 points MES = $1.25)
  • Initial capital: match Topstep combine account size ($50k, $100k, $150k)
  • Position limits: respect Topstep contract limits per account tier

VectorBT quick template:

import vectorbt as vbt

portfolio = vbt.Portfolio.from_signals(
    close=data['close'],
    entries=entries,
    exits=exits,
    init_cash=50_000,
    fees=0.0001,  # adjust per instrument
    slippage=0.0001,
    freq='1T'  # 1-minute bars
)
print(portfolio.stats())
portfolio.plot().show()

Validation requirements:

  • Walk-forward out-of-sample results (not just in-sample)
  • Sharpe with 50–70% haircut still >0.5
  • Max drawdown within Topstep trailing drawdown limit
  • Profit factor >1.3 net of fees
  • Minimum 100 trades for statistical significance

5. Risk Metrics & Performance Evaluation

Every strategy output MUST include a comprehensive risk assessment.

Required metrics (use QuantStats):

import quantstats as qs

qs.reports.full(returns, benchmark=None, output='report.html')
# Or for programmatic access:
qs.stats.sharpe(returns)
qs.stats.sortino(returns)
qs.stats.max_drawdown(returns)
qs.stats.win_rate(returns)
qs.stats.profit_factor(returns)
qs.stats.avg_win(returns) / qs.stats.avg_loss(returns)

Risk commentary template (include with every strategy result):

"This strategy's Sharpe of {X} assumes {Y} slippage and {Z} commission — live performance likely in the {A}–{B} range after a {haircut}% haircut. Max drawdown of {DD}% is within/exceeds the Topstep {limit} trailing drawdown limit."

Topstep combine constraints (flag when relevant):

  • Max daily loss limit (varies by account tier)
  • Max trailing drawdown (varies by account tier)
  • Profit target to pass combine
  • Position limits per account tier for MNQ/MES

6. Position Sizing

Compute dynamic position sizes — never hardcode contracts.

Methods (in order of preference):

  1. Volatility targeting: Size = (target_vol × account_equity) / (ATR × point_value)
  2. Fixed fractional: Risk per trade = X% of equity, contracts = risk / (stop_distance × point_value)
  3. Kelly Criterion: f* = (win_rate × avg_win - (1 - win_rate) × avg_loss) / avg_win — then use half-Kelly for safety

The signal says "enter." Position sizing says "how much." These are separate systems. Never couple them.

7. Regime Detection

Condition signal entry on market regime state to improve reliability.

Methods:

  • ATR-based: Classify into low/medium/high volatility regimes using ATR percentile rank over rolling 252 bars
  • Hidden Markov Models: from hmmlearn.hmm import GaussianHMM — fit on returns + volatility to detect 2–3 regime states
  • Trend strength: ADX > 25 = trending, ADX < 20 = ranging — different strategies for each
  • Rolling correlation: Cross-asset correlation regime (risk-on vs risk-off)

Application: A trend-following signal in a ranging regime generates losses. Filter entries by regime state to reduce drawdown and improve risk-adjusted returns.

Skill Boundary

This skill covers: Strategy research, signal generation, technical indicator design, ML model development for alpha signals, backtesting and validation methodology, risk metrics, position sizing, regime detection.

Defer to automated-trading-systems for: live trade execution architecture, broker API integration (Tradovate WebSocket), order management, kill switches, multi-agent orchestration with LangGraph, Topstep combine rule enforcement at execution time.

Defer to staff-ml-engineer for: deep learning training infrastructure, MLOps (MLflow/W&B experiment tracking), model serving at scale, feature store design.

Defer to staff-data-engineer for: data ingestion pipelines feeding OHLCV into TimescaleDB, historical data backfill orchestration, data architecture for tick/bar storage.

Defer to staff-python-engineer for: Python code quality, packaging, async patterns, non-trading-specific Python concerns.

Signal Decay Monitoring

ML signals degrade as markets adapt. Implement these monitoring practices:

  1. Track out-of-sample Sharpe on a rolling 30/60/90-day basis
  2. Set alert thresholds: if rolling Sharpe drops below 0.3, halt the strategy
  3. Schedule periodic retraining (weekly or monthly depending on signal horizon)
  4. Compare retrained model feature importances against baseline — significant drift indicates regime change
  5. Log all model versions with timestamps for reproducibility

Output Format

When this skill is active, produce:

  • Strategy research code in structured Python classes (not scattered notebook cells) separating: data loading, feature engineering, signal generation, performance evaluation
  • Backtest results always with QuantStats summary or metrics table (Sharpe, Sortino, max drawdown, win rate, profit factor)
  • Feature pipelines with explicit .shift() and lag-naming conventions (rsi_14_lag1)
  • Visualizations using plotly or mplfinance for OHLCV + indicator overlays; plotly for equity curves and drawdowns
  • Walk-forward validation structure for ML signals — never a single train/test split
  • Risk commentary with every strategy output (see template in Capability 5)
  • Topstep constraints flagged explicitly when relevant
  • Jupyter-compatible code blocks that paste directly into JupyterLab cells

Verification Checklist

Before marking any strategy research task complete:

  • Hypothesis documented in plain English before coding
  • All features use .shift() — no look-ahead bias
  • Feature columns named with explicit lag suffix
  • Walk-forward validation used (not single train/test split)
  • Transaction costs included (commission + slippage)
  • Risk metrics reported (Sharpe, Sortino, max DD, win rate, profit factor)
  • Sharpe haircut applied and documented in risk commentary
  • Topstep constraints checked if relevant (daily loss, trailing DD, position limits)
  • Simple baseline tested before complex ML model
  • Code structured in classes/modules, not loose notebook cells (for validated strategies)

Rationalization Table

ExcuseReality
"I'll add .shift() later, let me get the logic working first"Look-ahead bias contaminates every metric computed without it. Add .shift() from the start — there is no "later" that doesn't require re-running everything.
"Transaction costs are small enough to ignore for initial research"$4.50 round-trip × 50 trades/day = $225/day. Ignoring costs is not "initial research" — it's fiction. Include costs from the first backtest.
"The in-sample Sharpe is 3.0 so even with haircut it's fine"A 3.0 in-sample Sharpe is a red flag for overfitting, not a cause for confidence. Apply the haircut AND investigate why it's so high.
"Walk-forward is overkill for a quick check"A quick check without walk-forward tells you nothing about live performance. It takes 5 extra lines of code. Do it.
"This strategy only has a few parameters so overfitting isn't a concern"Overfitting depends on parameter count AND data volume. Check the 200:1 ratio regardless of how "simple" the strategy feels.
"I'll just use a random train/test split instead of chronological"Time series data is autocorrelated. Random splits leak future information into training. Always split chronologically. No exceptions.
"The simple baseline doesn't work but XGBoost might find a nonlinear edge"If the linear version of the hypothesis has zero signal, the nonlinear version will overfit to noise. Fix the hypothesis first.
"Most of the features are clean so the overall results are approximately correct"Look-ahead bias in even one feature can dominate model splits and contaminate all predictions. You cannot estimate the impact without fixing it. Fix all biased features, re-run, and report the actual results.
"Commissions can be negotiated down so gross results are more representative"Report net results for the actual trading environment (Topstep/Tradovate retail commissions). Hypothetical future commission reductions are not a basis for strategy viability. If a strategy only works with commissions that don't exist yet, it doesn't work.

Resources

references/

  • references/primary-stack.md — Detailed tool descriptions with version requirements and installation notes
  • references/topstep-constraints.md — Account tiers, position limits, drawdown rules, profit targets

Load references on demand — do not load into context unless the current task requires them.

Keep looking

Skills are one crate of 607,533. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.