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-1.0.0.tar.gz (33.8 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-1.0.0-py3-none-any.whl (32.6 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for sagan_trade-1.0.0.tar.gz
Algorithm Hash digest
SHA256 8aaeeda4cc29d0b2d33956ab108f926bc29bf83e9c981d7c4f0a8ec4e7dc8224
MD5 ffcbf3a16c16d39203f034919052d0bc
BLAKE2b-256 580d1d6749d2595c7edf78ed6e92f22ec3abd00129d7fab32dcfa3805cbbce1e

See more details on using hashes here.

File details

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

File metadata

  • Download URL: sagan_trade-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 32.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-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1ac6f6d2693cc3ed6194618c04c3f4e66ae0015ab5cf9f83227f554b8f8b2656
MD5 bebf9cea0551c39dfb0277c719bb9ccf
BLAKE2b-256 6e052a0f7efd283dfb0d1e9d43bdfafb7d3f9b279e10af9c7aa7687d60df8d47

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