Metadata-Version: 2.4
Name: pytradex-krm
Version: 0.1.0
Summary: Enterprise Quantitative Trading Ecosystem for Indian Markets (NSE/BSE/MCX)
Author-email: PyTradeX Core Team <dev@pytradex.org>
License-Expression: MIT
Project-URL: Homepage, https://github.com/pytradex/pytradex
Project-URL: Documentation, https://pytradex.readthedocs.io
Project-URL: Repository, https://github.com/pytradex/pytradex.git
Project-URL: Bug Tracker, https://github.com/pytradex/pytradex/issues
Keywords: trading,algorithmic-trading,quantitative-finance,nse,bse,indian-markets,backtesting,polars,numba
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Investment
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.5.0
Requires-Dist: pydantic-settings>=2.1.0
Requires-Dist: polars>=0.20.0
Requires-Dist: numba>=0.58.0
Requires-Dist: numpy>=1.24.0
Requires-Dist: structlog>=23.2.0
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: httpx>=0.25.0
Requires-Dist: duckdb>=0.9.0
Requires-Dist: pyarrow>=14.0.0
Requires-Dist: pyotp>=2.9.0
Requires-Dist: scipy>=1.11.0
Requires-Dist: scikit-learn>=1.3.0
Requires-Dist: xgboost>=2.0.0
Requires-Dist: lightgbm>=4.1.0
Requires-Dist: optuna>=3.4.0
Requires-Dist: joblib>=1.3.0
Requires-Dist: typer>=0.9.0
Requires-Dist: rich>=13.7.0
Requires-Dist: fastapi>=0.104.0
Requires-Dist: uvicorn>=0.24.0
Requires-Dist: plotly>=5.18.0
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-httpx>=0.26.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: hypothesis>=6.100.0; extra == "dev"
Requires-Dist: ruff>=0.1.5; extra == "dev"
Requires-Dist: mypy>=1.7.0; extra == "dev"
Requires-Dist: pip-audit>=2.6.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Dynamic: license-file

# PyTradeX — Enterprise Quantitative Trading Ecosystem for Indian Markets

[![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12-blue.svg)](https://www.python.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![PyPI version](https://img.shields.io/pypi/v/pytradex.svg)](https://pypi.org/project/pytradex/)

> **Zero-cost, institutional-grade quantitative trading framework built for NSE/BSE/MCX.**
> Polars + Numba + asyncio — built for high-frequency Indian market research.

---

## ✨ Key Features

| Module | Description |
|--------|-------------|
| **EventBus** | Min-heap priority async event bus, O(log N) dispatch, 10k backpressure, DLQ with 3× retry |
| **IndianCostEngine** | Exact FY 2024-25 STT, GST (18%), SEBI fee, stamp duty, exchange charges — verified to ₹0.01 |
| **Numba Kernels** | JIT-compiled RSI, EMA, ATR, SuperTrend, Black-Scholes IV solver (<1 ms) |
| **NLP Strategy Parser** | Plain-English rules → AST-whitelisted safe lambdas; `eval()` on pre-compiled bytecode only |
| **VectorizedBacktester** | Polars LazyFrame engine, <2 s on 1 M bars, Bonferroni-corrected multi-strategy testing |
| **EventDrivenBacktester** | Zero-lookahead guarantee: signal at bar *t* executes at bar *t+1* open |
| **OMS FSM** | Strict PENDING→SUBMITTED→ACK→FILLED state machine, rejects illegal transitions |
| **Risk Controllers** | Max-drawdown circuit breaker, daily loss cap, Prim's MST correlation reducer |
| **HTML Reports** | Self-contained Plotly + Tailwind reports, no server required |

---

## 📦 Installation

```bash
pip install pytradex
```

**With all dev/test dependencies:**
```bash
pip install "pytradex[dev]"
```

**Requirements:** Python ≥ 3.11, NumPy, Polars, Numba, Pydantic v2.

---

## 🚀 Quick Start (5 lines)

```python
from pytradex.core.config import get_config
from pytradex.backtest.vectorized import VectorizedBacktester
from pytradex.reporting.report import generate_html_report
import polars as pl

# 1. Load configuration (reads PYTRADEX_* env vars or .env file)
cfg = get_config()

# 2. Load your OHLCV data as a Polars DataFrame with a 'signal' column
df = pl.read_parquet("reliance_ohlcv.parquet")   # must have: timestamp, open, high, low, close, volume, signal

# 3. Run vectorized backtest
bt = VectorizedBacktester(initial_capital=cfg.backtest.initial_capital)
result = bt.run(df, strategy_name="MyStrategy")

# 4. Print summary (includes Indian tax breakdown)
print(result.summary())

# 5. Generate interactive HTML report
generate_html_report(result, "report.html")
```

---

## 🏦 Indian Tax Engine

PyTradeX computes **exact FY 2024-25 statutory charges** on every fill:

| Charge | Rate | Applied On |
|--------|------|-----------|
| STT (Equity Delivery) | 0.1% buy + 0.1% sell | Both sides |
| STT (Intraday) | 0.025% | Sell side only |
| STT (Futures) | 0.02% | Sell side only |
| STT (Options) | 0.0625% on premium | Sell side only |
| GST | 18% | Brokerage + Exchange charge |
| SEBI Turnover Fee | ₹10 / crore | Total turnover |
| Stamp Duty (Delivery) | 0.015% | Buy side |
| Stamp Duty (Intraday) | 0.003% | Buy side |
| Exchange Charge (NSE Equity) | 0.00345% | Total turnover |

```python
from pytradex.backtest.indian_costs import IndianCostEngine

engine = IndianCostEngine(broker="zerodha")
breakdown = engine.calculate_costs(
    buy_price=2500.0, sell_price=2600.0,
    quantity=100, segment="equity_delivery"
)
print(f"Net PnL after tax: ₹{breakdown.net_pnl_after_tax:,.2f}")
print(f"Total statutory drag: ₹{breakdown.total_tax_and_charges:,.2f}")
```

---

## 🔐 Security

- The NLP strategy parser **never calls `eval()` on raw user strings**. All expressions are parsed into an AST, validated against an explicit node whitelist, compiled to bytecode, and only then evaluated in a sandboxed namespace with `__builtins__: None`.
- API keys and broker credentials are read exclusively from environment variables (prefix: `PYTRADEX_`) or a `.env` file — never hardcoded.
- Run `pip-audit` before deploying to check for known CVEs in the dependency tree.

---

## ⚙️ Configuration

PyTradeX uses a thread-safe Pydantic v2 singleton. All settings are overridable via environment variables:

```bash
# Example .env
PYTRADEX_BROKER__DEFAULT_BROKER=zerodha
PYTRADEX_BROKER__API_KEY=your_api_key_here
PYTRADEX_BACKTEST__INITIAL_CAPITAL=2000000
PYTRADEX_DATA__DEFAULT_PROVIDER=yahoo
```

Or from a YAML file:

```python
from pytradex.core.config import PyTradeXConfig
cfg = PyTradeXConfig.load_from_yaml("config.yaml")
```

---

## 🧪 Running Tests

```bash
# Install dev dependencies
pip install "pytradex[dev]" pytest-asyncio pytest-cov hypothesis

# Run all tests with coverage
pytest tests/ --cov=pytradex --cov-report=term-missing --cov-fail-under=85

# Run with Numba JIT disabled for accurate coverage
NUMBA_DISABLE_JIT=1 pytest tests/ --cov=pytradex --cov-report=term-missing
```

---

## 📊 Supported Brokers

| Broker | Brokerage Model | Live Trading |
|--------|----------------|-------------|
| **Shoonya (Finvasia)** | ₹0 flat | ✅ WebSocket + REST |
| **Zerodha / Upstox** | ₹20 flat (F&O, Intraday) | ✅ Kite Connect v3 |
| **Angel One** | ₹20 flat | 🔧 Planned |
| **Paper** | ₹0 | ✅ Built-in simulator |

---

## 📄 License

MIT License — see [LICENSE](LICENSE) file.

Copyright © 2024 PyTradeX Core Team

---

## 🤝 Contributing

1. Fork the repo and create a feature branch.
2. Add tests (L1 unit + L3 E2E) for every new public function.
3. Run `ruff check --fix pytradex/` and `mypy --strict pytradex/` before pushing.
4. Open a PR — CI must be green before merge.

Full documentation: [https://pytradex.readthedocs.io](https://pytradex.readthedocs.io)
