Overview
Theank-risk module provides tick-level and day-bucketed risk tracking for backtests and agent-based models.
Key features:
- Tick-level metrics in e18 units (engine-native)
- Day-bucketed metrics in USD (f64) for analytics
- Protocol-specific valuation helpers (Aave, Uniswap V3)
- Rich risk metrics: health factor, LTV, drawdown, Sharpe, Sortino, APY
Risk Accumulators
RiskAccumulator
Tick-level accumulator of portfolio risk metrics in e18 space. Callupdate() once per tick with current net equity and health factor. When the backtest ends, call finalize() to obtain a summary snapshot.
Fields
Number of
update observations (ticks).Minimum observed health factor (basis points).
Maximum observed health factor (basis points).
Maximum drawdown in e18 units, tracked over the run.
Last computed drawdown in e18 units.
Methods
Update the accumulator with the current net value (e18) and HF (bps).Parameters:
ts: Timestamp (seconds or milliseconds; ms are auto-normalized)net_value_e18: Net equity in 1e18 unitshf_bps: Health factor in basis points (higher is safer)
Finalize and produce a
RiskSummary.If timestamps were observed, annualization uses the actual horizon; otherwise, it falls back to TICKS_PER_YEAR (31,536,000 = 365 days × 86,400 seconds).RiskAccumulatorUsd
Day-bucketed risk accumulator in USD (f64) for human-scale analytics. Feed it tick-level net equity (e18) each call; it will maintain a rolling USD value, track drawdown, and close out daily bars.Fields
Minimum observed health factor (bps).
Maximum observed health factor (bps).
Last computed drawdown in USD.
Maximum drawdown in USD.
Methods
Ingest a tick at
ts with current net value (e18) and HF (bps).Returns: Current USD drawdown after the updateFinalize and produce a daily (USD)
RiskSummaryUsd.Uses daily log returns for volatility and Sharpe/Sortino, and a timestamp-based horizon for APR/APY when available.Summary Types
RiskSummary
Compact summary produced byRiskAccumulator::finalize().
Numeric identifiers and e18 amounts are wrapped in string-serialized types (U64S, U128S, I128S) so JSON/TS never lose precision.
Fields
Number of ticks observed.
Minimum observed health factor (bps).
Maximum observed health factor (bps).
Maximum drawdown in e18.
Annualized volatility (from per-tick simple returns).
Annualized Sharpe ratio (risk-free rate = 0).
Annualized Sortino ratio (risk-free rate = 0).
Terminal net equity (e18).
Initial net equity (e18).
Total PnL over the run (e18, signed).
Total return (terminal / initial − 1).
Time-based APR (linearized).
Time-based APY (compounded).
Number of up ticks.
Number of down ticks.
wins / (wins + losses).RiskSummaryUsd
Human-scale (USD, f64) summary of risk over day buckets. Produced byRiskAccumulatorUsd::finalize().
Fields
Number of distinct days observed.
Number of ticks observed.
Minimum observed health factor (bps).
Maximum observed health factor (bps).
Maximum drawdown on the USD series.
Annualized volatility from daily log returns.
Annualized Sharpe (rf = 0) from daily log returns.
Annualized Sortino (rf = 0) from daily log returns.
Initial USD equity.
Terminal USD equity.
Terminal − Initial (USD).
Total return (terminal/initial − 1).
APR (linearized, time-based).
APY (compounded, time-based).
Number of days with positive daily return.
Number of days with negative daily return.
wins / (wins + losses).RiskSnapshot
One-tick snapshot of wallet/health state (all e18 except*_bps).
Timestamp for this snapshot (seconds or ms; ms are auto-normalized).
Total wallet value in e18 (sum of assets).
Collateral/deposits value in e18.
Debt value in e18.
Net equity in e18.
Loan-to-value in basis points.
Health factor in basis points (higher is safer).
Protocol Valuation Helpers
compute_aave_values_from_views
Compute Aave-style valuation metrics from protocol views. Signature:(deposit_value_e18, debt_value_e18, ltv_bps, hf_bps)
Expected view shapes:
aave_market["reserves"][symbol]contains:"price_e18"(string or number)"liq_threshold_bps"(number)
aave_user["deposits"][symbol]and["debts"][symbol]are amounts (string/number)
compute_uniswap_values_from_views
Compute Uniswap V3-style valuation metrics from views. Signature:(total_liquidity_value_e18, fees_earned_e18, utilization_bps, position_health_bps)
Expected view shapes:
uniswap_market:"sqrt_price_x96"(string)- optionally
"token0_price_e18","token1_price_e18"overrides
uniswap_user["positions"]is an array of:tick_lower/tick_upper(i32)liquidity(string)fees_owed_0/fees_owed_1(string)
Usage Examples
Basic risk tracking
Day-bucketed USD tracking
Aave position valuation
Risk Metrics Explained
Health Factor (HF)
Measures how close a position is to liquidation. Expressed in basis points (bps):- 10,000 bps = 1.0 (liquidation threshold)
- 15,000 bps = 1.5 (healthy)
- > 20,000 bps = 2.0+ (very safe)
HF = (CollateralValue × LiquidationThreshold) / DebtValue
Loan-to-Value (LTV)
Ratio of debt to collateral, expressed in basis points:- 5,000 bps = 50% LTV
- 7,500 bps = 75% LTV
- 10,000 bps = 100% LTV (fully leveraged)
LTV = (DebtValue / CollateralValue) × 10,000
Drawdown
Peak-to-trough decline in portfolio value: Formula:Drawdown = RunningPeak - CurrentValue
Sharpe Ratio
Risk-adjusted return metric (higher is better): Formula:Sharpe = AnnualizedReturn / AnnualizedVolatility
Sortino Ratio
Like Sharpe, but only penalizes downside volatility: Formula:Sortino = AnnualizedReturn / DownsideDeviation
APR vs APY
- APR (Annual Percentage Rate): Linearized return
APR = TotalReturn / Years
- APY (Annual Percentage Yield): Compounded return
APY = exp(ln(TerminalValue / InitialValue) / Years) - 1
CSV Output Format
Risk metrics can be exported to CSV for analysis. Typical format:- All
*_e18fields are 1e18-scaled integers ltv_bpsandhf_bpsare basis points (÷ 10,000 for decimal)tsis Unix timestamp (seconds)