Metadata-Version: 2.4
Name: sagan-trade
Version: 0.9.7
Summary: Strategic High-Throughput Predictive Trading Engine with iterative R2 fitting and SaganLLM discovery.
Home-page: https://github.com/That-Tech-Geek/sagan-trade
Author: Sambit Mishra
Author-email: Sagan Labs <hello@sagan-docs.vercel.app>
License: MIT
Project-URL: Repository, https://github.com/That-Tech-Geek/sagan-trade
Project-URL: Homepage, https://sagan-trade.vercel.app
Project-URL: Documentation, https://sagan-trade.vercel.app
Project-URL: Source, https://github.com/That-Tech-Geek/sagan-trade
Project-URL: Bug Tracker, https://github.com/That-Tech-Geek/sagan-trade/issues
Project-URL: Changelog, https://sagan-trade.vercel.app/changelog
Project-URL: PyPI, https://pypi.org/project/sagan-trade/
Keywords: trading,quantitative-finance,machine-learning,explainable-ai,pinn,temporal-fusion-transformer,mean-reversion,ensemble,deep-learning
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: tensorflow>=2.10
Requires-Dist: pandas>=1.5
Requires-Dist: numpy>=1.23
Requires-Dist: yfinance>=0.2
Requires-Dist: scikit-learn>=1.1
Requires-Dist: streamlit>=1.25
Requires-Dist: plotly>=5.15
Requires-Dist: cryptography
Requires-Dist: typer
Requires-Dist: snaptrade-python-sdk
Requires-Dist: schedule
Requires-Dist: requests
Requires-Dist: matplotlib
Requires-Dist: seaborn
Provides-Extra: dev
Requires-Dist: pytest>=7.4; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff>=0.4; extra == "dev"
Requires-Dist: mypy>=1.5; extra == "dev"
Requires-Dist: build>=1.0; extra == "dev"
Requires-Dist: twine>=4.0; extra == "dev"
Requires-Dist: pyinstaller>=6.0; extra == "dev"
Requires-Dist: mkdocs-material>=9.5; extra == "dev"
Requires-Dist: mkdocstrings[python]>=0.24; extra == "dev"
Provides-Extra: ci
Requires-Dist: pytest>=7.4; extra == "ci"
Requires-Dist: pytest-cov>=4.0; extra == "ci"
Requires-Dist: ruff>=0.4; extra == "ci"
Requires-Dist: mypy>=1.5; extra == "ci"
Requires-Dist: pandas>=1.5; extra == "ci"
Requires-Dist: numpy>=1.23; extra == "ci"
Requires-Dist: scikit-learn>=1.1; extra == "ci"
Requires-Dist: yfinance>=0.2; extra == "ci"
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.24; extra == "docs"
Requires-Dist: mkdocs-git-revision-date-localized-plugin>=1.2; extra == "docs"
Dynamic: author
Dynamic: home-page
Dynamic: requires-python

# Sagan Trade

> **High-fidelity symbolic mathematical engine and quantitative architecture for institutional alpha generation.**

[![Python](https://img.shields.io/badge/python-3.9%2B-blue)](https://python.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![PyPI](https://img.shields.io/pypi/v/sagan-trade.svg)](https://pypi.org/project/sagan-trade/)
[![GitHub repo](https://img.shields.io/badge/GitHub-That--Tech--Geek%2Fsagan--trade-brightgreen)](https://github.com/That-Tech-Geek/sagan-trade)

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

```bash
pip install sagan-trade
```

**Verify the installation:**
```python
import sagan_trade
print(sagan_trade.__version__)
```

---

## 🔬 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:**
```python
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:**
```python
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:**
```python
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:**
```python
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:**
```python
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](https://github.com/That-Tech-Geek/sagan-trade)
- **PyPI**: [https://pypi.org/project/sagan-trade/](https://pypi.org/project/sagan-trade/)
- **Author**: Sambit Mishra

## License
[MIT](LICENSE) © 2024 Sagan Labs / Sambit Mishra
