Skip to main content

Strategic High-Throughput Predictive Trading Engine with iterative R2 fitting and SaganLLM discovery.

Project description

Sagan Trade

High-fidelity symbolic mathematical engine and quantitative architecture for institutional alpha generation.

Python License: MIT PyPI GitHub repo

Sagan Trade replaces black-box neural networks with transparent, human-readable mathematical equations discovered via FunctionGemma. It combines the precision of Symbolic Regression with the robustness of Asymmetric Convexity risk management and cutting-edge limit order book simulations.

As of v0.9.6+, the library natively incorporates mathematical discoveries autonomously generated by the Autonomous Intelligence Network (AIN), including Hawkes Trade Arrivals and Bates Jump-Diffusion dynamics.


🚀 Quick Start & Installation

pip install sagan-trade

Verify the installation:

import sagan_trade
print(sagan_trade.__version__)

🔬 Core Architecture & API Reference

1. Symbolic Regressor (SymbolicRegressor)

Instead of opaque weight matrices, Sagan discovers market invariants in the form of mathematical expressions. It fits variables to $R^2 > 0.95$ using basis functions (Polynomial, Fourier, Momentum, LOB Volatility Pressure).

Key Capabilities:

  • Completely transparent AI: Every trade is backed by a human-readable formula.
  • Built-in technical indicator synthesis (e.g. RSI, Volatility).
  • Directly predicts continuous alpha signals mapped to Next-Day Returns.

Usage:

import pandas as pd
from sagan_trade import SymbolicRegressor

# Initialize the regressor with desired basis families
regressor = SymbolicRegressor(basis_functions=['poly', 'fourier', 'momentum'])

# Train on a ticker (auto-downloads data if not provided)
model_id = regressor.train(target="AAPL", signals=["Close", "RSI", "Volume"])

# Predict alpha signals
alpha_signals, formula = regressor.predict()
print(f"Alpha Signals generated via: {formula}")

2. Market Microstructure Insights (simulate_price_range, analyze_portfolio)

Incorporates a Hawkes process MLE estimator combined with heterogeneous agent price expectations to simulate price ranges and generate automated buy/sell signals. This serves as a quantitative pricing engine for intraday and swing horizons.

Key Capabilities:

  • Heterogeneous Agents: Simulates 1,000,000+ market participants with varying risk aversions and subjective expectations.
  • Bootstrapping: Computes expected market-clearing prices using non-parametric distributions.

Usage:

from sagan_trade import analyze_portfolio, visualize_stock_insights

# Generate actionable signals (BUY/SELL/HOLD) for a basket of stocks
portfolio_df = analyze_portfolio(["AAPL", "MSFT", "GOOG"], quick_mode=True)
print(portfolio_df)

# Visualize price range distributions and risk-aversion interactions
fig = visualize_stock_insights("AAPL")

3. Asymmetric Convexity Risk Engine (AsymmetricRiskEngine)

Sagan utilizes a non-linear risk management framework inspired by high-frequency market makers. It overrides raw alpha signals when downside tail risk is detected.

Key Capabilities:

  • Downside Convexity: Exponentially scales exposure based on momentum-volatility asymmetry.
  • Adaptive Kelly Sizing: Drawdown-aware fractional Kelly scaling to ensure capital preservation.
  • Asymptotic Shield: Quadratic drawdown protection creates a hard floor on portfolio risk.

Usage:

from sagan_trade import AsymmetricRiskEngine

risk_engine = AsymmetricRiskEngine(target_vol=0.15, max_drawdown_limit=0.075)

# Calculate defensive risk multipliers for position sizing
risk_multiplier = risk_engine.get_risk_multiplier(prices_series)

4. Volatility Regime Filter (VolatilityRegimeFilter)

Autonomously discovered through the AIN, this macroeconomic sidecar acts as a VRP (Variance Risk Premium) proxy, shifting portfolios to cash during contagion regimes.

Usage:

from sagan_trade import VolatilityRegimeFilter

vol_filter = VolatilityRegimeFilter(vol_window=20, ma_window=120)

# Generates 1.0 (Risk-On) or 0.0 (Risk-Off / Cash) filters
regime_signals = vol_filter.generate_signals(prices_series)

5. High-Fidelity Backtest Engine (BacktestEngine)

Legacy backtesters assume you get filled at the mid-price without market impact. The Sagan BacktestEngine enforces exact transaction fee accounting, portfolio turnover logic, and dynamically allocates positions from alpha signal overlays and risk models.

Usage:

from sagan_trade import BacktestEngine

# Initialize with exact exchange and statutory fees
backtester = BacktestEngine(
    initial_capital=1000000,
    maker_fee=0.0001,
    taker_fee=0.0003
)

# Run full portfolio backtest
results = backtester.run(
    prices=data['Close'],
    alpha_signals=alpha_signals,
    regime_filter=regime_signals,
    risk_model=risk_engine
)

print(f"Sharpe Ratio: {results.sharpe_ratio}")
print(f"Max Drawdown: {results.max_drawdown}%")
print(f"Total Return: {results.total_return}%")

🏛️ Institutional Benchmarking

Sagan Trade has been rigorously tested across 5 years of historical market regimes, accounting for institutional trading fees and liquidity constraints.

Long-Term Resilience (5-Year Rolling Audit)

Benchmark: 20-Ticker Diversified Portfolio (Tech, Finance, Energy, Consumer).

Metric Gross of Fees Net of Fees (5bps) S&P 500 (B&H)
Annualized Return 33.27% 12.98% 14.50%
Sharpe Ratio 2.11 1.06 0.85
Max Drawdown -6.91% -7.30% -23.90%
Total Cumulative 426.11% 102.46% 96.80%

[!IMPORTANT] Statistical Significance: The symbolic engine achieves a p-value of 0.0182, indicating that its outperformance against legacy TFT-PINN and LSTM models is statistically significant at the 98% confidence level.


🤝 Contribution & Links

License

MIT © 2024 Sagan Labs / Sambit Mishra

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sagan_trade-0.9.7.tar.gz (31.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sagan_trade-0.9.7-py3-none-any.whl (30.6 kB view details)

Uploaded Python 3

File details

Details for the file sagan_trade-0.9.7.tar.gz.

File metadata

  • Download URL: sagan_trade-0.9.7.tar.gz
  • Upload date:
  • Size: 31.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.14

File hashes

Hashes for sagan_trade-0.9.7.tar.gz
Algorithm Hash digest
SHA256 b2f7fbc825fe8a88bda4ef381152a5171fc18461eb07f81955370ff41d5d918b
MD5 9c80405b0eeb1e8aeeb05ab99cf79f68
BLAKE2b-256 007859154c0a80af7936d804414f3c008a36f200085259f05425b640cb36a75e

See more details on using hashes here.

File details

Details for the file sagan_trade-0.9.7-py3-none-any.whl.

File metadata

  • Download URL: sagan_trade-0.9.7-py3-none-any.whl
  • Upload date:
  • Size: 30.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.14

File hashes

Hashes for sagan_trade-0.9.7-py3-none-any.whl
Algorithm Hash digest
SHA256 0529c148520edc0e18083604d17d46f6ba502f603210ebb6143c56ad3042c82d
MD5 d48ffdfc45c1d4f0fbd42d23d9a20d42
BLAKE2b-256 bef6dcbc68c53c7ae20b0a65fbe7f3753b72d5f24b8e92feaeb7c22d65298812

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page