* feat(prod): fail-fast on missing live creds + client hardening
No more silent mock fallback — the defining hackathon→product fix.
- agent-runtime: build_data_source/build_executor now return Result and
refuse to run on mock data in LIVE mode (missing CMC_API_KEY/mcp_url,
use_mock=true, twak.mode="mock", or a network transport without base_url
all error instead of silently trading on fake data from a fake wallet).
Paper mode still degrades to mock. +3 deterministic fail-fast tests.
- twak-client: REST and MCP transports now use a 20s request timeout
(was reqwest's no-timeout default — a hung TWAK endpoint could stall
the trading loop forever).
- cmc-client: a missing/non-positive quote price now skips the asset with
a warning instead of feeding a $0 price into the strategy/risk engine.
- agent-runtime: run-report dir create failure is logged, not swallowed.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(prod): doc truth, strip hackathon scaffolding, observability (chunks 2-4)
Chunk 2 — doc↔code truth:
- Fix stale counts: 69 routes (README/API/ARCHITECTURE), 64 dashboard pages
(ARCHITECTURE), and mark the route/page tables as representative subsets.
Chunk 3 — strip hackathon scaffolding:
- Archive pure prize/judge docs to docs/archive/hackathon/ (SUBMISSION,
HACKATHON, PRIZE_MAP, PITCH, JUDGE_DEMO, TRACK2, DEMO_SCRIPT) and judge
scripts to scripts/archive/. Reframe README "Hackathon tracks" -> "Capabilities"
and fix the now-archived links. Product-relevant docs (architecture, risk,
strategy, runbook, proof/identity, CMC hub) stay.
Chunk 4 — observability + tests:
- agent-runtime: build_data_source/build_executor return a transport label;
AgentStarted payload now carries cmc_transport + twak_transport, plus a
"transports resolved" structured log — operators can see live-vs-mock at a glance.
- cmc-client: extract parse_quotes pure helper + 6 tests for the price-skip behavior.
Workspace builds green, clippy clean, tests pass, paper run verified.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): orderbook + ta-signals crates + /ta API route
Two real, pure-Rust product crates (no mocks), integrated into the workspace,
plus a real API surface exposing the indicators.
- crates/orderbook: in-memory limit order book with a price-time-priority
matching engine — limit/market orders, partial fills, multi-level market
sweeps, FIFO time priority, cancel, best bid/ask, spread, aggregated depth.
8 unit tests + a doctest.
- crates/ta-signals: technical-analysis library — SMA, EMA, RSI (Wilder),
MACD, Bollinger Bands, ATR, Stochastic, OBV, ADX (full Wilder directional
system), VWAP. Each returns an input-aligned Vec with NaN warmup; correct
algorithms with known-value tests. 24 unit tests + a doctest.
- apps/guardrail-api GET /ta: compute sma/ema/rsi/macd/bollinger over a
caller-supplied close series via ta-signals (NaN -> JSON null). Route count
-> 70; docs synced.
Workspace builds green, clippy clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): price-oracle Go microservice + README count sync
services/price-oracle: a real read-only Go microservice serving live USD
prices for the BSC universe from the free CoinGecko public API, cached behind
a TTL. No key, no chain, no writes.
- oracle/coingecko.go: real HTTP client (timeout, UA, error handling) over
/simple/price for 10 tracked symbols.
- oracle/cache.go: thread-safe TTL cache; stale-on-error graceful degradation.
- oracle/server.go: net/http (go1.22 method+path patterns) — GET /health,
/prices, /prices/{symbol}, /prices/refresh; JSON; access logging.
- main.go: PORT/ORACLE_TTL/ORACLE_HTTP_TIMEOUT env, read-header timeout.
- go vet clean, go build ok; verified live: /prices/BTC returned a real price.
docs: sync README "What's inside" counts to reality (24 crates, 70 routes,
64 pages).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): risk-analytics service (metrics engine + API + CLI)
services/risk-analytics: portfolio risk/performance metrics over the agent's
NAV curve. Pure-stdlib engine + CLI (run anywhere, no numpy); optional FastAPI
HTTP surface.
- risk_analytics/metrics.py: total/annualized return, annualized vol, max
drawdown, Sharpe, Sortino, Calmar, historical + parametric VaR (Acklam
inverse-normal), Pearson correlation matrix. Doctested formulas.
- store.py: reads the NAV series from portfolio_reconciled events in the
SQLite log. api.py: import-guarded FastAPI (POST /metrics, /correlation,
GET /metrics/live, /health). cli.py: metrics/live/demo subcommands.
- Verified: doctests pass; CLI demo + live (over the real event log) produce
correct metrics.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): 3 new dashboard pages (market-oracle, transports, journal-pro)
Real Next.js server components over the read-only API; nav links added.
- /market-oracle: renders the CMC data->capability lineage from
GET /cmc/capabilities (datasets + capabilities tables, summary).
- /transports: surfaces the running agent's resolved cmc/twak transports +
mode from the latest agent_started event, flagging live-with-mock.
- /journal-pro: GET /events with a client-side event-type filter (a small
"use client" JournalTable component).
- src/lib/types-expansion.ts holds the new types (existing types.ts untouched).
- tsc --noEmit clean. Dashboard pages -> 67.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): grctl read-only operator CLI (Go)
clients/go-cli: a dependency-free Go CLI over the read-only API.
- internal/client: net/http client (10s timeout, non-2xx errors, JSON decode).
- internal/commands: status/regime/portfolio/trades/risk/signals/proof/verify/
events/cockpit + watch (polls /regime); clean tabwriter summaries or --json.
- main.go: --api/$GUARDRAIL_API base, --json flag, help.
- go vet clean, go build ok.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): guardrail-term terminal client (TypeScript)
clients/ts-terminal: a typed, dependency-free Node CLI over the read-only API.
Uses built-in fetch; DOM lib + a tiny process shim so it typechecks with zero
deps (no @types/node).
- src/api.ts: read-only client (AbortController 10s timeout, non-2xx errors).
- src/render.ts: ANSI color + aligned kv/table helpers (no deps).
- src/index.ts: status/regime/portfolio/trades/risk/signals/proof/verify/
events/cockpit/watch; --api/$GUARDRAIL_API, --json; colored verify table.
- tsc --noEmit clean; built + ran help to verify.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): strategy parameter optimizer (Python)
python-lab/optimizer: grid + random search over the agent's strategy params,
maximizing Calmar or Sharpe. Pure stdlib (no numpy/requests).
- objective.py: calmar/sharpe/max_drawdown/annualized_return over an equity curve.
- model.py: deterministic synthetic equity surface with a hidden optimum.
- grid.py: grid_search + seeded random_search.
- runner.py: offline scorer (synthetic) + api_backtest scorer (urllib over
GET /skills/{skill}/backtest?preset=).
- cli.py: --offline/--api, --metric, --random N, --csv, --top.
- Verified: offline grid rediscovers the hidden ideal params as the top Calmar.
8/8 product-expansion components shipped (orderbook, ta-signals+/ta, price-oracle,
risk-analytics, dashboard pages, grctl, ts-terminal, optimizer).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* docs(whats-new): Phase 3 product-expansion entry + fix archived companion links
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): batch 2 — position-sizer, fee-model, notification-relay, reporting, ta-studio
Five more real components (workflow-built, integrated + verified). Workspace
builds green; new Rust crates carry unit tests.
- crates/position-sizer (Rust): fixed-fractional, vol-target, Kelly (fractional
+ cap), equal-risk-contribution weights. 39 tests + 5 doctests. forbid(unsafe).
- crates/fee-model (Rust): all-in swap cost — gas, constant-product price impact
+ linear slippage, protocol fee; CostBreakdown w/ effective price. 16 tests + doctest.
- services/notification-relay (Go): concurrent webhook fan-out (POST /notify ->
goroutine per target, per-attempt timeout + retry, 200/207/502, delivery
report), GET /health, graceful shutdown. vet + build clean.
- python-lab/reporting (Python, stdlib): reads the event log read-only + run
report, computes drawdown/return/sharpe, renders a self-contained HTML (or
text) report. Verified against the real DB.
- dashboard /ta-studio: page driving the new GET /ta endpoint (searchParams ->
indicator/series/period), NaN warmup rendered as "—"; nav link added. tsc clean.
Both new crates registered in the workspace; cargo build --workspace green.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): expose fee-model + position-sizer via GET /fees and /sizer
Two real API routes over the new crates, wiring crate -> API.
- GET /fees: all-in swap cost (gas + price-impact/slippage + protocol fee) from
fee-model; query params with sensible defaults, buy/sell side.
- GET /sizer: position sizing from position-sizer — method=fixed_fractional|
vol_target|kelly with their params; returns input + output (or a typed error).
- guardrail-api deps + modules + routes wired; build + clippy clean.
- Route count -> 72; README/API/ARCHITECTURE synced.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): /fees + /sizer dashboard pages (crate -> API -> page verticals)
Two new Next.js pages closing the verticals for the fee-model and
position-sizer crates:
- /fees: renders GET /fees cost breakdown; ?notional_usd/quantity/side drive it.
- /sizer: renders GET /sizer input+output; ?method=fixed_fractional|vol_target|
kelly + params.
Nav links added; inline types; tsc --noEmit clean. Dashboard pages -> 70;
README/ARCHITECTURE synced.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(product): Monte Carlo outcome simulator (Python)
python-lab/montecarlo: simulate strategy equity outcomes — terminal-value
distribution, max-drawdown risk, prob of loss, prob of ruin. Pure stdlib.
- sim.py: bootstrap (resample a historical return series) + GBM engines;
per-path max drawdown; percentile/ruin summary.
- cli.py: --demo/--bootstrap/--gbm, reads NAV from the event log (read-only)
with --db, configurable paths/horizon/mu/sigma/ruin.
- Verified: demo + gbm produce sensible distributions.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(sdk): TypeScript SDK methods for /ta, /fees, /sizer, /cmc/capabilities
Make the new quant endpoints consumable from the typed client:
- ta(params): compute an indicator over a close-price series.
- fees(params): all-in swap cost (camelCase -> snake_case query mapping).
- sizer(params): position sizing by method.
- cmcCapabilities(): CMC data->capability lineage.
Typed param interfaces (TaParams/FeesParams/SizerParams); tsc --noEmit clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* feat(sdk): Python client methods for /ta, /fees, /sizer, /cmc/capabilities
Parity with the TS SDK — ta(indicator, series, ...), fees(**params),
sizer(method, **params), cmc_capabilities(). Stdlib urllib; imports clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* docs: README clients count 9->11 (grctl, guardrail-term) + services list
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
212 lines
7.4 KiB
Python
212 lines
7.4 KiB
Python
"""Portfolio risk and performance metrics.
|
|
|
|
Pure standard-library Python (no numpy required), so it runs anywhere. Every
|
|
function operates on a list of floats; helpers convert an equity/NAV curve into
|
|
a return series first. Formulas are the standard finance definitions and are
|
|
covered by the doctests below.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import math
|
|
from typing import Sequence
|
|
|
|
# Trading periods per year for annualization. Crypto trades 365 days/yr; the
|
|
# agent's cycle is sub-daily, but callers can override per their sampling.
|
|
DEFAULT_PERIODS_PER_YEAR = 365.0
|
|
|
|
|
|
def returns_from_equity(equity: Sequence[float]) -> list[float]:
|
|
"""Simple period-over-period returns from an equity/NAV curve.
|
|
|
|
>>> [round(r, 4) for r in returns_from_equity([100, 110, 99])]
|
|
[0.1, -0.1]
|
|
"""
|
|
out: list[float] = []
|
|
for prev, cur in zip(equity, equity[1:]):
|
|
if prev == 0:
|
|
out.append(0.0)
|
|
else:
|
|
out.append(cur / prev - 1.0)
|
|
return out
|
|
|
|
|
|
def _mean(xs: Sequence[float]) -> float:
|
|
return sum(xs) / len(xs) if xs else 0.0
|
|
|
|
|
|
def _std(xs: Sequence[float], sample: bool = True) -> float:
|
|
n = len(xs)
|
|
if n < 2:
|
|
return 0.0
|
|
m = _mean(xs)
|
|
denom = n - 1 if sample else n
|
|
return math.sqrt(sum((x - m) ** 2 for x in xs) / denom)
|
|
|
|
|
|
def max_drawdown(equity: Sequence[float]) -> float:
|
|
"""Maximum peak-to-trough drawdown as a positive fraction (0.2 == 20%).
|
|
|
|
>>> round(max_drawdown([100, 120, 60, 80]), 4)
|
|
0.5
|
|
"""
|
|
peak = float("-inf")
|
|
mdd = 0.0
|
|
for v in equity:
|
|
peak = max(peak, v)
|
|
if peak > 0:
|
|
mdd = max(mdd, (peak - v) / peak)
|
|
return mdd
|
|
|
|
|
|
def total_return(equity: Sequence[float]) -> float:
|
|
"""Total return over the whole curve.
|
|
|
|
>>> total_return([100, 150])
|
|
0.5
|
|
"""
|
|
if len(equity) < 2 or equity[0] == 0:
|
|
return 0.0
|
|
return equity[-1] / equity[0] - 1.0
|
|
|
|
|
|
def annualized_return(equity: Sequence[float], periods_per_year: float = DEFAULT_PERIODS_PER_YEAR) -> float:
|
|
"""Geometric annualized return from an equity curve."""
|
|
n = len(equity) - 1
|
|
if n <= 0 or equity[0] <= 0 or equity[-1] <= 0:
|
|
return 0.0
|
|
growth = equity[-1] / equity[0]
|
|
return growth ** (periods_per_year / n) - 1.0
|
|
|
|
|
|
def annualized_volatility(returns: Sequence[float], periods_per_year: float = DEFAULT_PERIODS_PER_YEAR) -> float:
|
|
"""Annualized standard deviation of returns."""
|
|
return _std(returns) * math.sqrt(periods_per_year)
|
|
|
|
|
|
def sharpe(returns: Sequence[float], rf: float = 0.0, periods_per_year: float = DEFAULT_PERIODS_PER_YEAR) -> float:
|
|
"""Annualized Sharpe ratio. `rf` is the per-period risk-free rate."""
|
|
excess = [r - rf for r in returns]
|
|
sd = _std(excess)
|
|
if sd == 0:
|
|
return 0.0
|
|
return _mean(excess) / sd * math.sqrt(periods_per_year)
|
|
|
|
|
|
def sortino(returns: Sequence[float], rf: float = 0.0, periods_per_year: float = DEFAULT_PERIODS_PER_YEAR) -> float:
|
|
"""Annualized Sortino ratio — like Sharpe but penalizes only downside vol."""
|
|
excess = [r - rf for r in returns]
|
|
downside = [min(0.0, e) for e in excess]
|
|
dd = math.sqrt(sum(d * d for d in downside) / len(downside)) if downside else 0.0
|
|
if dd == 0:
|
|
return 0.0
|
|
return _mean(excess) / dd * math.sqrt(periods_per_year)
|
|
|
|
|
|
def calmar(equity: Sequence[float], periods_per_year: float = DEFAULT_PERIODS_PER_YEAR) -> float:
|
|
"""Calmar ratio: annualized return divided by max drawdown."""
|
|
mdd = max_drawdown(equity)
|
|
if mdd == 0:
|
|
return 0.0
|
|
return annualized_return(equity, periods_per_year) / mdd
|
|
|
|
|
|
def historical_var(returns: Sequence[float], confidence: float = 0.95) -> float:
|
|
"""Historical Value-at-Risk as a positive loss fraction at `confidence`.
|
|
|
|
The empirical `(1 - confidence)` quantile of the return distribution,
|
|
reported as a positive number (a loss).
|
|
"""
|
|
if not returns:
|
|
return 0.0
|
|
ordered = sorted(returns)
|
|
idx = int((1.0 - confidence) * len(ordered))
|
|
idx = min(max(idx, 0), len(ordered) - 1)
|
|
return max(0.0, -ordered[idx])
|
|
|
|
|
|
def parametric_var(returns: Sequence[float], confidence: float = 0.95) -> float:
|
|
"""Gaussian (parametric) VaR as a positive loss fraction at `confidence`."""
|
|
if len(returns) < 2:
|
|
return 0.0
|
|
# Inverse-normal CDF (Acklam's rational approximation) for the z-score.
|
|
z = _norm_ppf(1.0 - confidence)
|
|
loss = -(_mean(returns) + z * _std(returns))
|
|
return max(0.0, loss)
|
|
|
|
|
|
def correlation_matrix(series: dict[str, Sequence[float]]) -> dict[str, dict[str, float]]:
|
|
"""Pairwise Pearson correlation across named return series (equal lengths)."""
|
|
names = list(series.keys())
|
|
out: dict[str, dict[str, float]] = {a: {} for a in names}
|
|
for a in names:
|
|
for b in names:
|
|
out[a][b] = _pearson(series[a], series[b])
|
|
return out
|
|
|
|
|
|
def _pearson(xs: Sequence[float], ys: Sequence[float]) -> float:
|
|
n = min(len(xs), len(ys))
|
|
if n < 2:
|
|
return 0.0
|
|
xs, ys = xs[:n], ys[:n]
|
|
mx, my = _mean(xs), _mean(ys)
|
|
cov = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
|
|
vx = math.sqrt(sum((x - mx) ** 2 for x in xs))
|
|
vy = math.sqrt(sum((y - my) ** 2 for y in ys))
|
|
if vx == 0 or vy == 0:
|
|
return 0.0
|
|
return cov / (vx * vy)
|
|
|
|
|
|
def _norm_ppf(p: float) -> float:
|
|
"""Inverse standard-normal CDF via Acklam's rational approximation."""
|
|
if p <= 0.0:
|
|
return -math.inf
|
|
if p >= 1.0:
|
|
return math.inf
|
|
a = [-3.969683028665376e+01, 2.209460984245205e+02, -2.759285104469687e+02,
|
|
1.383577518672690e+02, -3.066479806614716e+01, 2.506628277459239e+00]
|
|
b = [-5.447609879822406e+01, 1.615858368580409e+02, -1.556989798598866e+02,
|
|
6.680131188771972e+01, -1.328068155288572e+01]
|
|
c = [-7.784894002430293e-03, -3.223964580411365e-01, -2.400758277161838e+00,
|
|
-2.549732539343734e+00, 4.374664141464968e+00, 2.938163982698783e+00]
|
|
d = [7.784695709041462e-03, 3.224671290700398e-01, 2.445134137142996e+00,
|
|
3.754408661907416e+00]
|
|
plow, phigh = 0.02425, 1 - 0.02425
|
|
if p < plow:
|
|
q = math.sqrt(-2 * math.log(p))
|
|
return (((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / \
|
|
((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)
|
|
if p > phigh:
|
|
q = math.sqrt(-2 * math.log(1 - p))
|
|
return -(((((c[0] * q + c[1]) * q + c[2]) * q + c[3]) * q + c[4]) * q + c[5]) / \
|
|
((((d[0] * q + d[1]) * q + d[2]) * q + d[3]) * q + 1)
|
|
q = p - 0.5
|
|
r = q * q
|
|
return (((((a[0] * r + a[1]) * r + a[2]) * r + a[3]) * r + a[4]) * r + a[5]) * q / \
|
|
(((((b[0] * r + b[1]) * r + b[2]) * r + b[3]) * r + b[4]) * r + 1)
|
|
|
|
|
|
def summary(equity: Sequence[float], periods_per_year: float = DEFAULT_PERIODS_PER_YEAR) -> dict[str, float]:
|
|
"""Compute the full metric suite for an equity curve."""
|
|
rets = returns_from_equity(equity)
|
|
return {
|
|
"points": len(equity),
|
|
"total_return": total_return(equity),
|
|
"annualized_return": annualized_return(equity, periods_per_year),
|
|
"annualized_volatility": annualized_volatility(rets, periods_per_year),
|
|
"max_drawdown": max_drawdown(equity),
|
|
"sharpe": sharpe(rets, 0.0, periods_per_year),
|
|
"sortino": sortino(rets, 0.0, periods_per_year),
|
|
"calmar": calmar(equity, periods_per_year),
|
|
"var_95_historical": historical_var(rets, 0.95),
|
|
"var_95_parametric": parametric_var(rets, 0.95),
|
|
}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import doctest
|
|
|
|
doctest.testmod(verbose=False)
|