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.8.4+, the library natively incorporates mathematical discoveries autonomously generated by the Autonomous Intelligence Network (AIN), including Hawkes Trade Arrivals and Bates Jump-Diffusion dynamics.


🏛️ 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.


🚀 Installation

pip install sagan-trade

For the latest source code, you can clone the repository from GitHub:

git clone https://github.com/That-Tech-Geek/sagan-trade.git
cd sagan-trade
pip install -e .

📚 Comprehensive Documentation

1. Hawkes Limit Order Book (LOB) Simulator (simulator.py)

Accurate quantitative modeling requires realistic microstructure data. The HawkesLOBSimulator generates tick-by-tick order book updates using a continuous-time Bates Jump-Diffusion process paired with self-exciting Hawkes trade intensity.

  • NIFTY50 & Multi-Asset Support: Comes pre-configured with exact market-maker profiles for major indices like NIFTY50, handling specific tick sizes, base depths, and tick volatility.
  • Microstructural Realism: Simulates realistic bid, ask, bid_size, ask_size, and dynamic structural features such as Order Flow Imbalance (OFI) and depth_imbalance.
from simulator import HawkesLOBSimulator

sim = HawkesLOBSimulator()
# Simulate 5000 high-frequency ticks for NIFTY50
df = sim.simulate_ticks("NIFTY50", num_ticks=5000)

2. Sagan Mixture-of-Experts (MoE) Architecture (moe_model.py)

To predict ultra-short latency order book dynamics, Sagan Trade uses a Temporal Convolutional Network (TCN) embedded inside a PyTorch Mixture of Experts network.

  • Zero Future Leakage: Uses causal dilated convolutions to ensure predictions strictly use historical data.
  • State-Dependent Routing: An internal gating network routes market regimes (e.g., flash crashes vs. quiet sessions) to 3 different mathematical "Expert" modules.
import torch
from moe_model import SaganMoEModel

device = 'cuda' if torch.cuda.is_available() else 'cpu'
sagan_model = SaganMoEModel(num_features=5, state_dim=5, num_experts=3).to(device)

3. High-Frequency Backtester & Inventory Control (backtester.py)

Legacy backtesters assume you get filled at the mid-price. The Sagan HighFrequencyBacktester enforces rigid queue priority, latency delays, and exact exchange fee structures (STT, Exchange Transaction Charges, SEBI fees).

  • Passive vs. Aggressive: Determines if a trade should cross the spread aggressively (paying taker fees) or wait passively in the queue (earning maker rebates).
  • Statutory Friction: Automatically calculates round-trip trading frictions to prevent "suicidal" arbitrage algorithms that lose money on taxes.
from backtester import HighFrequencyBacktester

bt = HighFrequencyBacktester(latency_ticks=2)
results = bt.run_backtest(df_test, sagan_preds, "NIFTY50")

print(f"Net Realized Fees: {results['metrics']['fees_paid']}")

4. Symbolic Regressor & AIN Volatility Filters

Instead of weight matrices, Sagan discovers market invariants in the form of mathematical expressions using FunctionGemma.

  • Explainability: Every trade is backed by a human-readable formula, e.g., (Close * 0.5) + log(Volume).
  • Hawkes-Bates VRP Proxy: Autonomously discovered through the AIN, this macroeconomic sidecar shifts portfolios to cash during contagion regimes.

5. Quantitative Strategies (approved_strategies/)

Sagan-Trade now includes standalone quantitative research models integrated directly into the library.

  • PEAD Technical Elasticity (pead_technical_elasticity.py): Explores Post-Earnings Announcement Drift conditioned on structural momentum and 20-day historical volatility. This model produces a massive 195% R² improvement and an out-of-sample Net Spread of 23.62% with a Sharpe ratio of 0.40.

🛠️ Complete Workflow Example

This comprehensive quickstart demonstrates the full lifecycle: Symbolic Discovery, Volatility Filtering, Risk Management, and Backtest Execution.

import pandas as pd
import torch
from sagan_trade import (
    SymbolicRegressor, 
    AsymmetricRiskEngine, 
    VolatilityRegimeFilter,
    BacktestEngine
)

# 1. Fetch Market Data
data = pd.DataFrame({
    'Close': [...],
    'Volume': [...],
    'RSI': [...]
})

# 2. Symbolic Discovery
regressor = SymbolicRegressor(basis_functions=['poly', 'fourier'])
model_id = regressor.train(target="AAPL", signals=["Close", "RSI", "Volume"])
predicted_signal, formula = regressor.predict()
print(f"Discovered Alpha: {formula}")

# 3. Macro Regime Filtering
vol_filter = VolatilityRegimeFilter(vol_window=20, ma_window=120)
regime_signals = vol_filter.generate_signals(data['Close'])
print(f"Current Market Regime (1=Risk-On, 0=Cash): {regime_signals.iloc[-1]}")

# 4. Initialize Asymmetric Convexity Risk Engine
risk_engine = AsymmetricRiskEngine(target_vol=0.15, max_drawdown_limit=0.075)

# 5. Execute End-to-End Backtest
backtester = BacktestEngine(
    initial_capital=1000000,
    maker_fee=0.0001,
    taker_fee=-0.0003
)

results = backtester.run(
    prices=data['Close'],
    alpha_signals=predicted_signal,
    regime_filter=regime_signals,
    risk_model=risk_engine
)

print(f"Backtest Sharpe: {results.sharpe_ratio}")
print(f"Backtest Max Drawdown: {results.max_drawdown}")

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-0.9.4.tar.gz (24.3 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-0.9.4-py3-none-any.whl (20.8 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for sagan_trade-0.9.4.tar.gz
Algorithm Hash digest
SHA256 cd33dea752922452aaf3a85713652b4a13ebd43f0b4f22018ef34e02c3ac4a66
MD5 0ca347014ec25c92804b12f0d440c55e
BLAKE2b-256 3c8f2a9b6cd1678782c61133bd56226dd17ae7e0b5bbbd9785265ca906f49a08

See more details on using hashes here.

File details

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

File metadata

  • Download URL: sagan_trade-0.9.4-py3-none-any.whl
  • Upload date:
  • Size: 20.8 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-0.9.4-py3-none-any.whl
Algorithm Hash digest
SHA256 5530ff289717b46f9de107d2b7c35625e8948fe60364ebe4b1094272727a9407
MD5 ad954bf7a11afbdfc30ae7afc4edfab0
BLAKE2b-256 5902aaed8f98785ca7115a4bef2ebb0bcbd6b8574d27093e10ca5ac28d575968

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