RiskEngine.RiskCalculator (risk_engine v0.1.0)

Copy Markdown View Source

Pure risk math — no process, no state, no side effects.

Given a portfolio's trade history and running exposure figures, computes the two risk metrics tracked per portfolio: volatility/1 and drawdown/2. Both are called from RiskEngine.Portfolio.Server after every trade.

Summary

Functions

Computes the percentage pullback of magnitude from peak.

Computes the volatility of a portfolio's most recent trades, as the standard deviation of their signed notional values (qty * price, negated for sells).

Functions

drawdown(magnitude, peak)

@spec drawdown(magnitude :: number(), peak :: number()) :: float()

Computes the percentage pullback of magnitude from peak.

peak is expected to be the highest exposure magnitude a portfolio has ever reached, and magnitude its current exposure magnitude — so a return value of 20.0 means the portfolio has given back 20% of its peak exposure. Returns 0.0 when peak is 0.0, to avoid dividing by zero before a portfolio has any exposure.

volatility(trades)

@spec volatility([RiskEngine.TradeIngestion.trade()]) :: float()

Computes the volatility of a portfolio's most recent trades, as the standard deviation of their signed notional values (qty * price, negated for sells).

Only the most recent trades are considered, up to a configured window size (default 10):

config :risk_engine, RiskEngine.RiskCalculator, window: 10

trades is expected to be ordered most-recent-first, which is how RiskEngine.Portfolio.Server maintains its trade history.

Returns 0.0 for an empty list or a single trade, since standard deviation is undefined (or trivially zero) below two data points.