Skip to main content

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__)

[!IMPORTANT] AIN High-Fidelity Standard: As of v1.0.1, the Autonomous Intelligence Network (AIN) has autonomously enforced rigorous Google Style docstrings and exhaustive static typing across all modules (e.g. BacktestEngine, AsymmetricRiskEngine).


🔬 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

Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

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

sagan_trade-2.0.0-py3-none-any.whl (76.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: sagan_trade-2.0.0-py3-none-any.whl
  • Upload date:
  • Size: 76.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for sagan_trade-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1e6b383390dde8e671f4b440444a2dbefc2165a44077f86e57dad36d534ac7f9
MD5 18628ead66ca37c245d6226414baaa78
BLAKE2b-256 57af3a514ca12a879a7a9fcd9227535b8f595b6dfc5de0b5c652a7fcc3cec02a

See more details on using hashes here.

Provenance

The following attestation bundles were made for sagan_trade-2.0.0-py3-none-any.whl:

Publisher: publish.yml on sagan-research/sagan-trade

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

2.3.1

2 files

2.3.0

2 files

2.2.0

1 file

2.1.0

1 file

2.0.1

1 file

This release

2.0.0 This release

1 file

1.0.1

2 files

1.0.0

2 files

0.9.7

2 files

0.9.5

2 files

0.9.4

2 files

0.9.3

2 files

0.9.2

2 files

0.9.1

2 files

0.8.8

2 files

0.8.7

2 files

0.8.6

2 files

0.8.5

2 files

0.8.4

2 files

0.8.3

2 files

0.8.2

2 files

0.8.1

2 files

0.8.0

2 files

0.7.5

2 files

0.7.4

2 files

0.7.3

2 files

0.7.2

2 files

0.7.1

2 files

0.7.0

2 files

0.6.0

2 files

0.5.0

2 files

0.4.0

2 files

0.3.5

2 files

0.3.1

2 files

0.3.0

2 files

0.2.8

2 files

0.2.7

2 files

0.2.6

2 files

0.2.5

2 files

0.2.4

2 files

0.2.3

1 file

0.2.0

2 files

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page