Sagan Trade
SOTA Quantitative Finance Library: Symbolic Regression, Temporal Fusion Transformers, PINNs, Advanced Portfolio Optimization, and Institutional-Grade Backtesting
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 v2.1.0, the library natively incorporates:
- PIN/VPIN Informed Trading detection (order flow toxicity)
- Hawkes Trade Arrivals and Bates Jump-Diffusion dynamics
- 115+ research themes autonomously generated by the Autonomous Intelligence Network (AIN)
Quick Start & Installation
pip install sagan-trade
Verify the installation:
import sagan_trade
print(sagan_trade.__version__) # "2.1.0"
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 > 0.95 using basis functions (Polynomial, Fourier, Momentum, LOB Volatility Pressure).
import pandas as pd
from sagan_trade import SymbolicRegressor
regressor = SymbolicRegressor(basis_functions=['poly', 'fourier', 'momentum'])
model_id = regressor.train(target="AAPL", signals=["Close", "RSI", "Volume"])
alpha_signals, formula = regressor.predict()
print(f"Alpha Signals generated via: {formula}")
Key Capabilities:
- Completely transparent AI: Every trade is backed by a human-readable formula
- Built-in technical indicator synthesis (RSI, Volatility)
- Directly predicts continuous alpha signals mapped to Next-Day Returns
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.
from sagan_trade import analyze_portfolio, visualize_stock_insights
portfolio_df = analyze_portfolio(["AAPL", "MSFT", "GOOG"], quick_mode=True)
print(portfolio_df)
fig = visualize_stock_insights("AAPL")
Key Capabilities:
- Heterogeneous Agents: Simulates 1,000,000+ market participants with varying risk aversions
- Bootstrapping: Computes expected market-clearing prices using non-parametric distributions
3. Asymmetric Convexity Risk Engine (AsymmetricRiskEngine)
Non-linear risk management framework inspired by high-frequency market makers. Overrides raw alpha signals when downside tail risk is detected.
from sagan_trade import AsymmetricRiskEngine
risk_engine = AsymmetricRiskEngine(target_vol=0.15, max_drawdown_limit=0.075)
risk_multiplier = risk_engine.get_risk_multiplier(prices_series)
Key Capabilities:
- Downside Convexity: Exponentially scales exposure based on momentum-volatility asymmetry
- Adaptive Kelly Sizing: Drawdown-aware fractional Kelly scaling
- Asymptotic Shield: Quadratic drawdown protection creates a hard floor on portfolio risk
4. Informed Trading Detection (estimate_pin, compute_vpin)
Detect order flow toxicity using Probability of Informed Trading (PIN) and Volume-Synchronized PIN (VPIN) metrics.
from sagan_trade import estimate_pin, compute_vpin, monitor_vpin, compute_order_flow_toxicity
# Estimate PIN from buy/sell counts
pin_result = estimate_pin(buys, sells)
print(f"PIN: {pin_result.pin:.4f}, Alpha: {pin_result.alpha:.4f}")
# Compute VPIN from trade data
vpin_result = compute_vpin(prices, volumes, n_buckets=50)
print(f"VPIN: {vpin_result.vpin:.4f}")
# Real-time monitoring with alerts
status = monitor_vpin(prices, volumes, alert_threshold=0.25)
print(f"Status: {status['status']}, Recommendation: {status['recommendation']}")
# Comprehensive toxicity metrics
toxicity = compute_order_flow_toxicity(prices, volumes)
print(f"Toxicity Level: {toxicity['toxicity_level']}")
Key Capabilities:
- PIN Estimation: MLE-based EKOP model with multiple random restarts
- VPIN Computation: Volume-synchronized probability with BVC or tick rule classification
- Trade Classification: Bulk Volume Classification (BVC) and Tick Rule methods
- Real-time Monitoring: Alert thresholds for WARNING and CRITICAL toxicity levels
5. Volatility Regime Filter (VolatilityRegimeFilter)
Macroeconomic sidecar that acts as a VRP (Variance Risk Premium) proxy, shifting portfolios to cash during contagion regimes.
from sagan_trade import VolatilityRegimeFilter
vol_filter = VolatilityRegimeFilter(vol_window=20, ma_window=120)
regime_signals = vol_filter.generate_signals(prices_series)
# Returns 1.0 (Risk-On) or 0.0 (Risk-Off / Cash)
6. High-Fidelity Backtest Engine (BacktestEngine)
Enforces exact transaction fee accounting, portfolio turnover logic, and dynamically allocates positions from alpha signal overlays and risk models.
from sagan_trade import BacktestEngine
backtester = BacktestEngine(
initial_capital=1000000,
maker_fee=0.0001,
taker_fee=0.0003
)
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}%")
7. Advanced Backtesting (WalkForwardBacktester, PurgedKFoldBacktester)
Walk-Forward Analysis, Purged K-Fold CV, Combinatorial Purged CV, and Monte Carlo backtesting with joblib parallelism.
from sagan_trade import WalkForwardBacktester, BacktestConfig, run_backtest
config = BacktestConfig(train_window=252, test_window=63, n_splits=5)
result = run_backtest("walk_forward", strategy, prices, config=config)
print(result.summary())
8. Portfolio Optimization (optimize_portfolio)
Hierarchical Risk Parity, Risk Parity, Black-Litterman, Mean-Variance, Maximum Diversification, and Minimum Variance optimization.
from sagan_trade import optimize_portfolio, efficient_frontier
result = optimize_portfolio(returns, method="hrp")
print(f"Sharpe: {result.sharpe_ratio:.2f}, Diversification: {result.diversification_ratio:.2f}")
frontier = efficient_frontier(returns, n_points=50)
9. Deep Learning Models
Temporal Fusion Transformer (TemporalFusionTransformer)
Multi-horizon time series forecasting with interpretable attention weights.
from sagan_trade import create_tft_model, TFTConfig
config = TFTConfig(hidden_size=256, num_heads=4, quantiles=(0.1, 0.5, 0.9))
model = create_tft_model(num_static_vars=10, config=config)
predictions = model.predict_median(static_inputs, encoder_inputs, decoder_inputs)
Physics-Informed Neural Networks (BlackScholesPINN, HestonPINN)
Option pricing and volatility modeling with PDE-constrained neural networks.
from sagan_trade import create_bs_pinn, create_heston_pinn
bs_model = create_bs_pinn(strike=100.0, option_type="call")
heston_model = create_heston_pinn(strike=100.0, option_type="call")
10. Optimal Execution (AlmgrenChrissModel, TWAPModel, VWAPModel)
Institutional-grade execution algorithms: Almgren-Chriss, Bertsimas-Lo, Obizhaeva-Wang, Gatheral-Schied, TWAP, VWAP, POV, and Implementation Shortfall.
from sagan_trade import optimize_execution, ExecutionConfig, ExecutionModel
config = ExecutionConfig(
model=ExecutionModel.ALMGREN_CHRISS,
total_quantity=100000,
time_horizon=1.0,
volatility=0.02
)
result = optimize_execution(config)
print(f"Expected Cost: {result.expected_cost:.4f}")
11. Feature Engineering (FeatureEngine)
100+ automated features: trend, momentum, volatility, volume, microstructure, cross-sectional, and time-based.
from sagan_trade import create_feature_engine
engine = create_feature_engine()
features = engine.fit_transform(data, target=returns)
importance = engine.get_feature_importance()
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% |
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.
CLI Commands
# Backtest
sagan-backtest --method walk_forward --tickers AAPL MSFT --initial-capital 1000000
# Train deep learning models
sagan-train --model tft --tickers AAPL MSFT GOOGL --epochs 100
# Portfolio optimization
sagan-optimize --method hrp --tickers AAPL MSFT GOOGL AMZN --risk-aversion 1.0
# Serve predictions
sagan-serve --port 8080
Optional Dependencies
# Full development environment
pip install sagan-trade[dev]
# Deep learning (TFT, PINN, attention models)
pip install sagan-trade[torch]
# High-frequency trading extensions
pip install sagan-trade[hft]
# Alternative data
pip install sagan-trade[alt_data]
# Everything
pip install sagan-trade[all]
Contribution & Links
- Repository: https://github.com/That-Tech-Geek/sagan-trade
- PyPI: https://pypi.org/project/sagan-trade/
- Documentation: https://sagan-trade.vercel.app
- Author: Sambit Mishra
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
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-2.1.0-py3-none-any.whl.
File metadata
- Download URL: sagan_trade-2.1.0-py3-none-any.whl
- Upload date:
- Size: 88.2 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 |
ed5c580ab85baa776089f29be32591bd8af66137a08348d21935976252d6f059
|
|
| MD5 |
9f09cd80ceb863902607eaf44dec8b73
|
|
| BLAKE2b-256 |
ba174f62572431c79cfb059b6c964911f32b8c89568330c8f833cce8af348ed8
|