A previous release had provenance metadata, but this release does not. View details.
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
Metadata
Release files for sagan-trade 2.3.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Loss of provenance
These files do not have provenance metadata, despite files in a prior release including this data.
We recommend further investigation before installing these files. View details.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| sagan_trade-2.3.1.tar.gz | 206.0 kB | Without provenance | Details for sagan_trade-2.3.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| sagan_trade-2.3.1-py3-none-any.whl | Python 3 | none | any | Details for sagan_trade-2.3.1-py3-none-any.whl |
Total release size: 302.8 kB
Release files / sagan_trade-2.3.1.tar.gz
Loss of provenance
This file belongs to a release without provenance metadata, despite a prior release including this data.
We recommend further investigation before installing this file. View details.
| Download URL | sagan_trade-2.3.1.tar.gz |
|---|---|
| Size | 206.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
ea28faa40f026ab2e941398f595bba448f5e8fa6ee4e54410b3c1727249f1772
|
|
BLAKE2b-256 checksum How to use checksums |
b5903eb579d023fee49ff86bc7119873e5a4a9ebbd76134e544b611efe15241f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.14
|
Release files / sagan_trade-2.3.1-py3-none-any.whl
Loss of provenance
This file belongs to a release without provenance metadata, despite a prior release including this data.
We recommend further investigation before installing this file. View details.
| Download URL | sagan_trade-2.3.1-py3-none-any.whl |
|---|---|
| Size | 96.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4077c4a9e24b15cf5bfee1313a1bd62f20c62e037e23bba947873fc1bf239d5d
|
|
BLAKE2b-256 checksum How to use checksums |
7123d6b8e61f13b261fc3fb18ba9edee31d0bd1489c5091e57eea4e4a706272f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.13.14
|
Security for sagan-trade 2.3.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Loss of provenance
A previous release of these files had provenance metadata, but this release does not.
While this could reflect a routine change by the project maintainers, it may also indicate that the release files have been compromised.
Release comparison
- Removed 2.0.1 1 file With provenance
- Added 2.3.1 2 files Without provenance
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.