Skip to main content
Glama
riskprism

riskprism

by wanxinwanxin

riskprism

Разложите риск портфеля американских акций на его факторный спектр.

Обозреватель: https://risk-prism-production.up.railway.app · Карточка модели для агентов: /model.md

Открытая фундаментальная факторная модель риска в стиле Barra, созданная так, чтобы быть готовой к использованию ИИ-агентами из коробки: библиотека Python, MCP-сервер и еженедельно публикуемые артефакты модели, покрывающие большинство ликвидных обыкновенных акций США.

  • 7 стилевых факторов (размер, стоимость, моментум, волатильность, ликвидность, качество, леверидж) + 12 отраслей (схема Fama-French) + рыночный фактор

  • Бесплатная, свободно распространяемая цепочка данных: фундаментальные показатели и SIC-коды из SEC EDGAR (общественное достояние), цены от подключаемых провайдеров

  • Гибридное распространение: предвычисленные артефакты (экспозиции, ковариация факторов, специфический риск) публикуются еженедельно, а полный конвейер открыт, так что любой может воспроизвести или расширить их

Отказ от ответственности: исследовательское программное обеспечение, предоставляется как есть. Ничто здесь не является инвестиционной рекомендацией.

Для ИИ-агентов (MCP)

{
  "mcpServers": {
    "riskprism": {
      "command": "riskprism-mcp",
      "env": { "RISKPRISM_ARTIFACTS": "/path/to/artifacts" }
    }
  }
}

Предоставляемые инструменты: get_model_info, get_portfolio_risk, get_factor_exposures, stress_test, check_coverage. Веса — это веса портфеля (короткие позиции отрицательны); волатильности — годовые, в виде десятичных дробей.

Related MCP server: Portfolio Rotation MCP Server

Для людей (Python)

from riskprism import RiskModel

model = RiskModel.load("artifacts")
report = model.portfolio_risk({"AAPL": 0.4, "MSFT": 0.3, "XOM": 0.3})
print(report["total_vol"], report["factor_var_contributions"])

model.stress_test({"AAPL": 1.0}, {"market": -0.10, "momentum": -0.05})

Соберите модель самостоятельно

pip install -e ".[dev]"
export RISKPRISM_EDGAR_UA="your-project (you@example.com)"   # SEC fair-access policy
riskprism-build --max-names 3000 --out artifacts             # yahoo prices, no key needed
riskprism-build --prior artifacts_prev --out artifacts       # append new weeks to a prior build
riskprism-build --provider tiingo ...                        # licensed data, needs TIINGO_API_KEY

Еженедельный GitHub Action выполняет именно это и публикует каталог артефактов; см. .github/workflows/build-model.yml.

Обозреватель

Статический сайт без бэкенда (размещается на Railway, пересобирается при каждой еженедельной сборке) для изучения модели: кумулятивная доходность факторов, факторная волатильность и корреляции, клиентская песочница для оценки риска портфеля с ползунками стресс-теста, факторные профили отдельных акций и визуальное пошаговое описание методологии. Вся математика выполняется в браузере на встроенных артефактах.

Агенты получают зеркало каждой сборки в простом Markdown по адресу /model.md (индексируется через /llms.txt): карточка модели, определения факторов, корреляции и полный список покрытия — без необходимости разбирать DOM.

Соберите всё локально:

riskprism-site --artifacts artifacts --out site   # index.html + model.md + llms.txt

Сводка модели

Компонент

Выбор

Горизонт

Средний (недельная доходность, годовые выходные показатели)

Оценивание

Перекрёстный WLS (веса √cap), отраслевое ограничение с весами по капитализации

Ковариация факторов

EWMA — период полураспада волатильности 13 нед., корреляции 26 нед., с PSD-восстановлением

Специфический риск

Остаточная волатильность EWMA, смешанная со структурным (на основе характеристик) априорным распределением в зависимости от длины истории

Универсум

Оценивание: цена ≥ $2, ADV ≥ $1M, история ≥ 26 нед. · Покрытие: все живые акции ≥ $1, пробелы заполняются априорными оценками

История

Capture-forward: еженедельные сборки дополняют предыдущий релиз; делистинги импутируются, смещение выжившего затухает

Полная методология — в docs/METHODOLOGY.md; проектные решения и их обоснование — в docs/DECISIONS.md.

Лицензия

MIT для кода. Публикуемые артефакты модели — это производные данные, построенные на основе SEC EDGAR (общественное достояние) и сторонних поставщиков цен; обсуждение лицензирования данных см. в docs/DECISIONS.md.

Available Tools

7 tools
check_coverageC

Which of the given tickers the current model build covers.

Inputs: tickers (required).

get_etf_riskA

Look-through risk report for one ETF or mutual fund: the latest SEC N-PORT holdings resolve to model tickers and the portfolio math runs on those weights. Reports total/factor/specific vol, factor exposures, top contributions, and the fund block with the holdings date and coverage. Returns an error dict when the ticker locates no fund, or when the model covers less than half of the holdings (bond and international funds). Needs RISKPRISM_EDGAR_UA (an identifying User-Agent, per SEC fair-access policy) for the EDGAR fetches.

Inputs: ticker (required), horizon.

get_factor_exposuresB

Per-asset factor exposures and total/factor/specific vol for each ticker.

Inputs: tickers (required), horizon.

get_model_infoA

Model version, as-of date, factor list, and asset coverage count. horizon: "medium" (default) or "short" — the responsive variant with halved risk half-lives, when available.

Inputs: horizon.

get_portfolio_riskA

Full risk report for a portfolio: total/factor/specific vol, factor exposures, top factor variance contributions, and top asset risk contributions. weights maps ticker -> portfolio weight. ETF and mutual fund tickers expand into their filed holdings before the math runs (set lookthrough=false to disable); funds the model cannot cover are reported in lookthrough.notes. Set optimized=true if the weights came from optimizing against this model: reported vols then include the Shepard second-order correction (optimizers exploit covariance estimation noise, so raw forecasts understate an optimized portfolio's risk). horizon: "medium" or "short" (responsive variant, when available).

Inputs: weights (required), horizon, optimized, lookthrough.

list_model_versionsA

Catalog of published model builds (the versioned registry): release tag, model version, publish date, available horizons, and artifact download URLs. The hosted server always serves the latest build; any historical build can be downloaded by its tag's asset URL.

Inputs: limit.

stress_testB

Estimate portfolio P&L under factor shocks (return units: -0.10 = -10%). Example: {"market": -0.10, "momentum": -0.05}. Use get_model_info for valid factor names.

Inputs: weights (required), factor_shocks (required), horizon.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.6/5.0

    Scored across 7 tools

    Disambiguation4/5

    Most tools target distinct actions: check_coverage checks ticker coverage, get_factor_exposures returns per-asset exposures, get_portfolio_risk returns a full portfolio report, and stress_test applies factor shocks. However, get_model_info also reports asset coverage count, which slightly overlaps with check_coverage, and get_portfolio_risk duplicates some get_factor_exposures output. Descriptions clarify boundaries, so misselection is unlikely.

    Naming Consistency5/5

    All names use snake_case with a verb_noun pattern (check_coverage, get_factor_exposures, list_model_versions, etc.). stress_test is the only minor deviation from the get_* prefix but still fits the verb_noun convention. Consistent and predictable throughout.

    Tool Count5/5

    Seven tools is well-scoped for a risk-model analytics server. Each tool addresses a distinct capability—coverage, exposures, metadata, versions, portfolio risk, ETF look-through, and stress testing—without redundant endpoints.

    Completeness4/5

    Core workflows are covered: coverage checks, model metadata/versions, per-asset exposures, portfolio/ETF risk, and stress testing. Minor gaps include no direct factor covariance/correlation retrieval or historical backtesting, though these are mostly available indirectly or outside the stated scope.

    Maintenance

    ActivityActive
    ResponsivenessLimited data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Portfolio risk analytics MCP server — VaR, Monte Carlo simulation, stress testing, portfolio optimization, options Greeks, and correlation analysis. Real market data via Yahoo Finance. Free tier available, Pro at $29/mo.
      10
      2
      MIT
    • F
      license
      A
      quality
      D
      maintenance
      MCP server providing portfolio analytics tools: beta to a benchmark, sector correlation, and FIFO trade matching with realized/unrealized P&L using Yahoo Finance prices.
      3
      -
    • A
      license
      A
      quality
      A
      maintenance
      MCP server exposing Interactive Brokers' portfolio risk analysis, including model greeks, implied volatility surface, what-if margin, and a local stress engine for P&L curve analysis.
      9
      MIT