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.
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
- Repository: https://github.com/That-Tech-Geek/sagan-trade
- PyPI: https://pypi.org/project/sagan-trade/
- Author: Sambit Mishra
License
MIT © 2024 Sagan Labs / Sambit Mishra
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file sagan_trade-1.0.1.tar.gz.
File metadata
- Download URL: sagan_trade-1.0.1.tar.gz
- Upload date:
- Size: 34.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6cfb21de7a1c1780b695880d32515c6f83fe4b9fe348fd2d407f31bb5f9268fe
|
|
| MD5 |
3a54213240d9713e6039c245caf8c318
|
|
| BLAKE2b-256 |
a2779bee5743c15b493f0d48c6065cba9008549c4039a3894c44b6bfd5098997
|
File details
Details for the file sagan_trade-1.0.1-py3-none-any.whl.
File metadata
- Download URL: sagan_trade-1.0.1-py3-none-any.whl
- Upload date:
- Size: 33.7 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cdc18dbfe667f7d39ee13eda650b76b01a3df83cd384188108ab27303078f783
|
|
| MD5 |
aa3f01279f5ba0ce6506695eb6cd3dca
|
|
| BLAKE2b-256 |
3e1eb2c6a07d9de631c7cb9f0dbb1e8e63e9d5cf1a72740b8086c51d3edb1848
|