返回资讯中心
外部精选
软件工程
#开发者实时流

Stride: Systematic trend-following system in Python 3.12

Production-grade systematic trend-following system with quantitative volatility sizing, Kelly leverage bounding, and automated circuit breakers.

Hacker News 最新JAbarca742026/10/24 · 20 天前27 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

Production-grade systematic trend-following system with quantitative volatility sizing, Kelly leverage bounding, and automated circuit breakers.

Built with pure functional algorithms, zero look-ahead bias, and institutional risk management.

Why STRIDE? • Algorithmic Core • Architecture • Risk & Brakes • Phase 4 Trial • Quick Start • Roadmap • Star History • Contributing

⭐ If you find STRIDE insightful or useful for your quantitative research, consider giving it a star! It helps the project grow and stay maintained.

Most open-source trading bots on GitHub suffer from critical flaws: look-ahead bias, uncontrolled leverage, hard-coded credentials, or zero automated circuit breakers. STRIDE is engineered from the ground up to address these failures with institutional quantitative standards:

STRIDE operates on an institutional ETF universe once per trading day, executing trades exclusively when signals transition. Its rules synthesize decades of empirical market research:

STRIDE tracks 10 liquid instruments chosen to maximize cross-asset diversification across distinct economic regimes:

STRIDE enforces a strict unidirectional data pipeline. Strategy and risk layers are written as pure functions:

flowchart LR A["Market Data<br/>(Tiingo / FRED / Alpaca)"] --> B["Data Validation<br/>(SPEC §5 Checks)"] B --> C["Pure Strategy Engine<br/>(55/20 Breakout & Filters)"] C --> D["Pure Risk Gate<br/>(Volatility Parity & Kelly)"] D --> E["Execution Adapter<br/>(Alpaca Paper / SimBroker)"] E --> F["Reconciliation & Audit<br/>(Telegram & HTML Report)"] classDef step fill:#161b22,stroke:#30363d,color:#e6edf3 class A,B,C,D,E,F step

Loading

This functional architecture eliminates data snooping, ensures mathematical determinism, and allows any historical or edge-case state to be reproduced in sub-millisecond unit tests.

Portfolio leverage is dynamically evaluated every trading day as the mathematical minimum of five independent limits:

$$\text{Leverage}{\text{effective}} = \min \left( L{\text{Kelly}},, L_{\text{vol_target}},, L_{\text{absolute_cap}},, L_{\text{broker}},, L_{\text{capital}} \right)$$

STRIDE operates two automated safety brakes to safeguard capital against black-swan regimes and operational failure:

The $-40%$ kill switch is an automated stop-loss trigger executed at the next market open; extreme overnight market gaps can result in realized losses exceeding the trigger threshold.

🛡️ Zero Real Money by Accident: mode: live requires an explicit environment override LIVE_CONFIRM=I_UNDERSTAND_REAL_MONEY; otherwise STRIDE falls back safely to paper mode.

🔑 Pydantic SecretStr: All API tokens (Alpaca, Tiingo, Telegram) are encapsulated in secret containers that censor sensitive tokens from logs, stack traces, and serialization.

🚫 Paper Credential Lock: The paper runner rejects live Alpaca credentials to prevent accidental execution on live accounts during testing.

🧪 Invariant Testing with Hypothesis: Critical financial calculations (Kelly sizing, risk vetoes, kill-switch boundaries) are tested against millions of randomized edge cases using property-based testing.

STRIDE is actively deployed in Phase 4 Paper Forward-Testing across two distinct paper accounts (SPEC §12):

At the end of each evening run, Runner.evening() checks the accumulated history. Once an instance completes 40 stored trading days in its equity table, STRIDE automatically executes the Phase 4 Verdict Evaluator comparing strategy performance against the $SPY$ benchmark:

Check real-time trial progress or run on-demand evaluation anytime via the CLI:

Check progress & metrics on Paper Instance B

python -m stride.reporting.daily --config config.paper_b.yaml --verdict

Check progress & metrics on Paper Instance DIP

python -m stride.reporting.daily --config config.paper_dip.yaml --verdict

  1. Clone & Set Up Environment

git clone https://github.com/JAbarca74/stride.git cd stride

Create virtual environment

python -m venv .venv

Activate environment

On macOS / Linux:

source .venv/bin/activate

On Windows (PowerShell):

.venv\Scripts\Activate.ps1

Install in development mode

pip install -e ".[dev]"

  1. Run the Test Suite (Offline, Zero Keys Needed)

Validate your local environment immediately. STRIDE's 791 automated tests execute in seconds without network calls:

pytest

======================= 791 passed in 4.82s =======================

  1. Load & Validate Market Data

Copy .env.example to .env and add a free data API key (Tiingo) and paper keys (Alpaca). All market data downloads are cached incrementally in data/stride.db:

cp .env.example .env

Download or incrementally update all 10 ETF series

stride-data prices # or: python -m stride.data.update prices

Run SPEC section 5 integrity checks (anomalies, gaps, zero-volume)

stride-data validate # or: python -m stride.data.update validate

Cross-check free Alpaca closes against Tiingo

stride-data check-alpaca # or: python -m stride.data.update check-alpaca

Calibrate synthetic vs real leveraged ETFs (SPEC §7 / T21)

stride-data t21 # or: python -m stride.data.update t21

  1. Run Quantitative Backtests

Execute multi-year simulations from 2007 to the latest trading day with realistic transaction costs and slippage:

Standard backtest with dynamic Kelly leverage ($100 initial capital)

python -m stride.backtest.run

Fixed leverage comparison (SPEC §9 benchmark)

python -m stride.backtest.run --fixed-leverage 2

Export visual interactive HTML performance report

python -m stride.backtest.run --report reports/backtest.html

Run institutional validation protocol (sensitivity & parameter stability)

python -m stride.backtest.validation

  1. Automated Daily Orchestration

python -m stride.run_daily manages forward paper execution across the 4 daily trading windows (New York time):

Production runner: automatically detects active trading phase

python -m stride.run_daily --config config.paper_b.yaml --phase auto

Run an individual phase manually

python -m stride.run_daily --config config.paper_b.yaml --phase evening

Shadow simulation mode on historical stored prices

python -m stride.run_daily --config config.paper_b.yaml --mode backtest

Automated Windows Task Scheduler Setup (Click to expand)

To automate STRIDE on Windows 10/11:

cd C:\path\to\stride powershell -ExecutionPolicy Bypass -File scripts\install_task.ps1 Get-ScheduledTask -TaskName "STRIDE paper"

The task triggers scripts\run_stride.ps1 every 15 minutes, wakes the PC if asleep (when wake timers are enabled in Power Options), catches up on missed starts, and creates automated rolling SQLite backups via scripts\backup_db.ps1.

Monitor live execution logs: Get-Content data\logs\scheduler.log -Tail 30

STRIDE adheres to strict software engineering standards to maintain bank-grade code reliability:

Run complete test suite

pytest

Ruff linting & auto-formatting validation

ruff check . && ruff format --check .

Strict type checking across src/ and tests/

mypy src tests

Repository Structure

stride/ ├── config.yaml # Baseline strategy and risk configuration ├── config.paper_b.yaml # Paper Instance B configuration (QQQ core + dip) ├── config.paper_dip.yaml # Paper Instance DIP configuration (SPY core + dip) ├── docs/ # Specifications, architecture, and SVG assets │ ├── SPEC.md # Technical specification (single source of truth) │ ├── CONFIG.md # Complete parameter reference for config.yaml │ └── assets/ # Vector diagrams, animated SVGs, and previews ├── src/stride/ │ ├── data/ # Market data ingestion, validation, SQLite storage │ ├── strategy/ # Pure signal generation (55/20 Turtles, 200 SMA) │ ├── risk/ # Pure risk engine (Kelly bounds, 1N sizing, brakes) │ ├── execution/ # Broker adapters (Alpaca paper, SimBroker) │ ├── backtest/ # Event-driven backtesting engine & performance metrics │ ├── reporting/ # HTML reports, Telegram alerts, Phase 4 verdict │ └── run_daily.py # Daily job runner & phase orchestrator ├── tests/ # 791 unit, integration, and Hypothesis property tests └── scripts/ # Automated Windows & Linux deployment scripts

STRIDE progresses through strict sequential phases. No phase begins until the previous phase completely satisfies its quantitative exit criteria:

flowchart LR P1["1 · Foundations<br/>Data & Ingestion"]:::done --> P2["2 · Strategy & Risk<br/>Pure Functions"]:::done P2 --> P3["3 · Backtest<br/>Costs & Metrics"]:::done P3 --> P4["4 · Paper Trading<br/>40-Day Live Trial"]:::now P4 --> P5["5 · Live Trading<br/>12 Months ($100 + $20/mo)"] P5 -.-> P6["6 · C++ Core<br/>High Performance"] classDef done fill:#1a7f37,stroke:#1a7f37,color:#ffffff classDef now fill:#1f6feb,stroke:#1f6feb,color:#ffffff

Loading

Phase Milestone Exit Criterion Status

Phase 1 Foundations Data for 10 assets loaded (2007–present) with 100% SPEC §5 validations passing

Completed ✅

Phase 2 Strategy & Risk Test coverage $\ge 90%$ in strategy/ and risk/, anti-look-ahead tests passing

Completed ✅

Phase 3 Backtesting Out-of-sample Sharpe exceeding $SPY$ and $\le 1.5$, stable sensitivity analysis

Completed ✅

Phase 4 Paper Forward-Testing 40 consecutive trading days without errors, clean reconciliation, outperforming $SPY$

In Progress 🔄 (Automated evaluator active)

Phase 5 Live Production 12-month live capital trial ($100 initial + $20/month deposit); hypotheses H1–H3 evaluated Planned ⏳

Phase 6 C++ Core High-performance C++20 engine module for ultra-fast vector backtesting Backlog 💡

If you appreciate institutional-grade open-source quantitative finance, please leave a star! ⭐

Contributions, bug reports, and quantitative discussions are warmly welcomed!

Security reports are handled with the highest priority. If you discover a potential vulnerability or suspect an exposed key:

If you reference or utilize STRIDE in your quantitative research, academic papers, or portfolio projects, please cite it:

@software{stride2026, author = {Jefferson Abarca}, title = {STRIDE: Systematic Trend & Risk-Integrated Daily Execution}, year = {2026}, url = {https://github.com/JAbarca74/stride}, version = {0.1.0}, license = {MIT} }

License

This project is licensed under the MIT License — see the LICENSE file for details.

This software is provided strictly for educational and quantitative research purposes. Nothing contained herein constitutes investment advice, financial recommendations, or a trading solicitation. Systematic trading involves substantial risk of capital loss, and leveraged instruments compound volatility. The author and contributors assume no liability for financial losses incurred through the use of this code.

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →