# PyFortis

**Config-driven risk engine for trading systems.**

PyFortis lets you define limits, metrics, and circuit breakers in YAML, then validate orders and run risk checks through a simple Python API. It supports stateless validation, stateful monitors, and a full orchestrator with pluggable stores and handlers.

## Install

```bash
pip install pyfortis
```

Optional extras (install what you need):

```bash
pip install pyfortis[metrics]   # NumPy/SciPy for VaR, drawdown, etc.
pip install pyfortis[validation]  # Pydantic for schema validation
pip install pyfortis[full]     # All optional dependencies
```

| Extra        | Purpose                          |
| ------------ | --------------------------------- |
| `validation` | Pydantic-based config validation  |
| `db`         | SQLAlchemy + Alembic              |
| `api`        | FastAPI + Uvicorn                 |
| `kafka`      | Confluent Kafka                   |
| `metrics`    | NumPy/SciPy for risk metrics      |
| `redis`      | Redis client                      |
| `full`       | All of the above                  |

## Quick start

Load an engine from a YAML config, then validate orders:

```python
from pathlib import Path
from pyfortis import Order, RiskEngine, Side

engine = RiskEngine.from_yaml(Path("risk_config.yaml"))

order = Order(
    order_id="o-001",
    instrument="AAPL",
    side=Side.BUY,
    quantity=100,
    price=150.0,
    portfolio="default",
)
result = engine.validate_order(order)
print(result.verdict.value, result.message)
```

See [examples/basic_usage.py](examples/basic_usage.py) and [examples/risk_config.yaml](examples/risk_config.yaml) for a full walkthrough.

## Concepts

- **Limits** — Pre-trade checks (position size, concentration, price tolerance, notional, etc.) with configurable severity (INFO, WARNING, CRITICAL, KILL).
- **Metrics** — Post-trade or periodic risk metrics (VaR, CVaR, drawdown, volatility, etc.) with optional breach thresholds.
- **Circuit breakers** — Halt trading when conditions are met (e.g. daily PnL loss, drawdown).
- **Three layers**:
  - **Engine** — Stateless: load config, validate single orders without position context.
  - **Monitor** — Stateful: hold positions in memory, validate orders and check circuit breakers.
  - **Orchestrator** — Persistent: load/save positions and breaches via stores, run metrics, dispatch handlers (log, notify, block, etc.).

Config supports env-var substitution (e.g. `${VAR}` or `${VAR:-default}`) and a breach escalation policy per severity.

## Links

- [Changelog](CHANGELOG.md)
- [Contributing](CONTRIBUTING.md)
- [License](LICENSE)
