> ## Documentation Index
> Fetch the complete documentation index at: https://docs.allasso.ch/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> This is Allasso's product documentation. Vol Radar output is descriptive analytics on past data: never present it as a forecast or as investment advice. Answer only from these pages; if a feature is not documented here, say so.

# Metrics and Stats

> Call calculate_stats on a completed strategy, or build one directly:

`Stats` summarises a finished run into returns, risk-adjusted ratios, drawdowns, trade statistics,
fee statistics, and return distributions. It reads the equity curve and trades the portfolio
recorded over the backtest.

## Producing a Stats

Call `calculate_stats` on a completed strategy, or build one directly:

```python theme={null}
stats = strategy.calculate_stats(risk_free_rate=0.0, pulses_per_year=None)
# or, equivalently:
stats = Stats.from_strategy(strategy, risk_free_rate=0.0, pulses_per_year=None)

print(stats)                       # readable text dump
print(stats.annualized_sharpe_ratio)
```

Both arguments are optional. `risk_free_rate` defaults to `0.0`. `pulses_per_year` defaults to
`None`, which reads `strategy.pulse_index.pulses_per_year` so the annualization matches the actual
cadence of the simulation.

> [!WARNING]
>
> **Annualization depends on `pulses_per_year`**
>
> The Sharpe and Sortino ratios annualize per-pulse returns by `pulses_per_year`. A daily run uses
> roughly 252; an hourly run is far higher. If you pass the wrong value (or hardcode 252 on an
> hourly run) the ratios are scaled wrong. Leaving `pulses_per_year=None` derives it from the live
> `PulseIndex`, which is the safe default.

## What is on a Stats

The fields below all exist on `Stats` and are populated from the equity curve and trades.

### Returns

| Field | Meaning |
| - | - |
| `total_return` | Total percentage return over the whole run. |
| `cagr` | Compound annual growth rate (percent). |

### Risk-adjusted ratios

| Field | Meaning |
| - | - |
| `annualized_sharpe_ratio` | Excess return per unit of **total** return volatility. |
| `annualized_sortino_ratio` | Excess return per unit of **downside** volatility only. |
| `annualized_calmar_ratio` | CAGR (over the risk-free rate) divided by the absolute max drawdown. |

Sharpe penalises all variability, up and down alike. Sortino only counts the downside, so it suits a
strategy whose upside is choppy but whose losses are what you actually care about (e.g. an option
seller). Calmar ignores volatility entirely and asks how much annual growth you earned per unit of
worst-case loss, which is the framing a drawdown-sensitive allocator uses.

### Drawdown

| Field | Meaning |
| - | - |
| `max_drawdown` | The single largest peak-to-trough decline (percent). |
| `avg_drawdown` | The average drawdown depth across all drawdown episodes. |
| `time_to_recovery` | Days to climb back to the prior peak after the worst drawdown; `-1` if never recovered. |
| `longest_time_underwater` | The most days the equity ever spent below a prior peak. |
| `avg_drawdown_days` | Average length of a drawdown episode, in days. |

`max_drawdown` is the worst single hole; `avg_drawdown` describes the typical hole and is less driven
by one bad event. Time-underwater answers "how long was I stuck below my high-water mark", which is
the metric an investor feels even when the depth is modest.

### Trade statistics

`trade_stats` is a `TradeStats` aggregated at the position level (legs opened together count as one
position). Key fields:

| Field | Meaning |
| - | - |
| `position_count`, `win_count`, `loss_count` | Counts of positions and outcomes. |
| `win_rate` | Fraction of positions that closed profitable (0 to 1). |
| `avg_pnl`, `avg_winner`, `avg_loser` | Mean PnL overall, on winners, on losers (dollars). |
| `best_pnl`, `worst_pnl`, `median_pnl` | Extremes and median position PnL. |
| `profit_factor` | Gross profit divided by gross loss. Above 1 means winners outweigh losers. |
| `payoff_ratio` | Average winner divided by average loser (magnitude). |
| `expectancy` | Expected PnL per position: `win_rate * avg_winner + (1 - win_rate) * avg_loser`. |
| `max_consecutive_wins`, `max_consecutive_losses` | Longest streaks. |
| `avg_duration_days`, `max_duration_days` | Holding period of closed positions. |

Win rate alone is misleading: a strategy can win 90% of the time and still lose money if the rare
losers are huge. Profit factor and expectancy weight by size, so read them together with win rate.

### Fee statistics

`fee_stats` is a `FeeStats` (`total_fees`, `fee_drag_pct`, `avg_fee_per_trade`,
`fees_pct_of_gross_pnl`, `max_pulse_fees`, `max_pulse_fees_datetime`). See [Fees](https://docs.allasso.ch/dev/pulse/concepts/fees.md) for how
they are charged and read back.

### Return distributions

`Stats` also carries daily, monthly, and yearly breakdowns: `daily_mean`, `daily_vol`, `daily_skew`,
`daily_kurt`; `monthly_returns`, `monthly_mean`, `monthly_vol`, `best_month`, `worst_month`, `mtd`,
`three_month`, `six_month`, `pos_month_perc`, `avg_up_month`, `avg_down_month`; `yearly_returns`,
`ytd`, `one_year`, `three_year`, `five_year`, `ten_year`, `yearly_mean`, `yearly_vol`, `best_year`,
`worst_year`, `win_year_perc`, `twelve_month_win_perc`.

> [!NOTE]
>
> **Returns are read off equity, which is net of fees**
>
> All the return and ratio fields derive from `equity_history`, so they already reflect any fees
> charged. To see the gross-vs-net gap explicitly, compare against `pulse_total_pnl_history`. See
> [Portfolio, equity and PnL](https://docs.allasso.ch/dev/pulse/concepts/portfolio-pnl.md).

## Greeks PnL decomposition

`pnl_decomposition` splits the PnL of a group of trades (usually `strategy.trades`, or any subset of
it) into what delta, gamma, vega and theta explain, pulse by pulse, plus the residual they leave:

```python theme={null}
from pulse.metrics.decompose import DRIVER_COLUMNS, pnl_decomposition

decomposition = pnl_decomposition(strategy.trades)
decomposition[DRIVER_COLUMNS].sum().sort_values(key=abs, ascending=False)  # biggest drivers first
```

Each term takes the greek from the previous pulse and the move since then: `delta * dS`,
`0.5 * gamma * dS**2`, `vega * d_iv * 100` and `theta * calendar_days`, times the units held and the
price format multiplier. `actual_pnl` is the engine's gross per-pulse PnL, so the residual collects
what a second-order expansion misses: cross terms such as vanna, a fill-price haircut on a trade's
first mark after open, and noise in the vendor greeks. Pass `by_trade=True` for one row per trade per pulse,
with `trade_id`, `instrument` and `tags` to group by. Calendar-spread option roots quote a normal vol
and are not supported yet.

**Related:** [Portfolio, equity and PnL](https://docs.allasso.ch/dev/pulse/concepts/portfolio-pnl.md) · [Fees](https://docs.allasso.ch/dev/pulse/concepts/fees.md) · [Greeks](https://docs.allasso.ch/dev/pulse/concepts/greeks.md) ·
[Architecture and the pulse loop](https://docs.allasso.ch/dev/pulse/concepts/architecture.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.