Skip to main content

risk-threshold-engine

A lightweight, zero-dependency Python library that converts factor scores into a market risk regime, deployment decision, and recommended mitigation actions.

Overview

Feed in five 0–100 risk scores (volatility, momentum, breadth, macro, drawdown), get back a structured result telling you whether to deploy capital at full pace, reduce lot sizes, pause, or rebalance.

from risk_threshold_engine import RiskThresholdEngine, FactorScores

engine = RiskThresholdEngine()

scores = FactorScores(
    volatility_score=72.0,
    momentum_score=60.0,
    breadth_score=55.0,
    macro_score=65.0,
    drawdown_score=50.0,
)

result = engine.evaluate(scores)
print(result.summary())
# [2026-05-01T...] Risk Engine Result
#   Composite Score : 61.25 / 100
#   Regime          : ELEVATED
#   Decision        : REDUCED_DCA
#   ...

Installation

pip install risk-threshold-engine

Or install from source:

git clone https://github.com/BrainScanStudios/risk-threshold-engine.git
cd risk-threshold-engine
pip install -e .

Requirements

Python 3.10+. No external dependencies — only the standard library.

Risk Regimes

Composite Score Regime Default Decision
0 – 30 LOW FULL_DCA
31 – 55 MODERATE REDUCED_DCA
56 – 75 ELEVATED REDUCED_DCA / PAUSE*
76 – 100 SEVERE REBALANCE

*ELEVATED switches to PAUSE when the portfolio's cash/bond buffer exceeds 30%.

Default Factor Weights

Factor Weight What it captures
volatility_score 25% Realised vol / VIX signal
momentum_score 20% Price momentum across assets
breadth_score 15% Market breadth (advance/decline)
macro_score 20% Rates, credit spreads, inflation
drawdown_score 20% Drawdown vs high-water mark

All weights are configurable. Scores are 0–100 where higher = more risk.

API

RiskThresholdEngine

RiskThresholdEngine(
    factor_weights: dict[str, float] | None = None,
    ticker_beta:    dict[str, float] | None = None,
    db_path:        str | None = None,
)
  • factor_weights — Override the default weight map. Must sum to 1.0.
  • ticker_beta — Map of ticker → beta coefficient. When provided, the engine generates TRIM and OPTIONS_SIGNAL actions for high-beta tickers held in the portfolio during elevated/severe regimes.
  • db_path — Optional path to a SQLite file. When set, every evaluate() call persists results to a risk_engine_results table.

evaluate(scores, portfolio=None) -> EngineResult

Runs the full evaluation pipeline.

FactorScores

FactorScores(
    volatility_score: float,   # 0–100
    momentum_score:   float,   # 0–100
    breadth_score:    float,   # 0–100
    macro_score:      float,   # 0–100
    drawdown_score:   float,   # 0–100
)

All five scores are required and must be in [0, 100]. How you produce them is up to you — any factor scoring module works.

PortfolioState (optional)

PortfolioState(
    buffer_pct:   float,              # cash/short-term bond % of portfolio
    cash_usd:   float,
    positions:  dict[str, float],   # ticker → market value in USD
)

Passing a PortfolioState enables portfolio-aware decisions (buffer checks, beta-weighted trim candidates, options signals).

EngineResult

Field Type Description
composite_score float Weighted composite (0–100)
regime RiskRegime LOW / MODERATE / ELEVATED / SEVERE
decision DeploymentDecision FULL_DCA / REDUCED_DCA / PAUSE / REBALANCE
actions list[MitigationAction] Ordered list of recommended actions
weighted_breakdown dict[str, float] Per-factor contribution to composite
notes str Contextual caveats
evaluated_at str ISO 8601 UTC timestamp
result.to_dict()    # fully serialisable dict
result.summary()    # human-readable string

Custom Configuration

engine = RiskThresholdEngine(
    factor_weights={
        "volatility_score": 0.40,
        "momentum_score":   0.20,
        "breadth_score":    0.10,
        "macro_score":      0.20,
        "drawdown_score":   0.10,
    },
    ticker_beta={
        "QQQ":  1.20,
        "SPY":  1.00,
        "TLT":  0.30,
    },
    db_path="risk_results.db",
)

Development

Clone the repo and set up an isolated environment:

git clone https://github.com/BrainScanStudios/risk-threshold-engine.git
cd risk-threshold-engine

python3 -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate

pip install -e ".[dev]"

The [dev] extra installs pytest. The library itself has no runtime dependencies beyond the standard library.

pytest
pytest -v          # verbose
pytest -k regime   # run tests matching a keyword

Project layout

src/
    risk_threshold_engine/
        __init__.py    public API surface
        engine.py      all core logic lives here
tests/
    test_engine.py     full test suite

The entire implementation is in engine.py. If you're adding a new action type or regime, the three methods to touch are _build_actions, _decide, and _contextual_notes. If you're changing the scoring model, adjust DEFAULT_FACTOR_WEIGHTS or pass custom weights at construction time.

Submitting changes

  1. Fork the repository and create a branch from main.
  2. Add or update tests for any behaviour you change — pytest must pass before opening a PR.
  3. Keep the zero-dependency constraint: no new imports outside the standard library.

License

MIT — see LICENSE.

Copyright (c) 2026 Brain Scan Studios

Metadata

Release files for risk-threshold-engine 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for risk-threshold-engine 0.2.0
File Size Uploaded Provenance Actions
risk_threshold_engine-0.2.0.tar.gz 12.5 kB With provenance Details for risk_threshold_engine-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for risk-threshold-engine 0.2.0
File Interpreter ABI Platform Actions
risk_threshold_engine-0.2.0-py3-none-any.whl Python 3 none any Details for risk_threshold_engine-0.2.0-py3-none-any.whl

Total release size: 22.5 kB

Release files / risk_threshold_engine-0.2.0.tar.gz

Download URL risk_threshold_engine-0.2.0.tar.gz
Size 12.5 kB
Tags Source
SHA-256 checksum
How to use checksums
f8ec65303129140c86b8ca4ad141ba5bf388c4ac388a56430eb475c43f40bc64
BLAKE2b-256 checksum
How to use checksums
83e09881312f2b71f0575a3739dd7590e13c351263b99c41519baed1483ff6b2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on May 26, 2026.

Transparency log

Release files / risk_threshold_engine-0.2.0-py3-none-any.whl

Download URL risk_threshold_engine-0.2.0-py3-none-any.whl
Size 10.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c7984474353ab304e5a9de445c22716e5698726ea898cb4ecf4623fb93e6314f
BLAKE2b-256 checksum
How to use checksums
761d3b4aa117b180e3bd69bf95e6150825a7c323201d7105598075586bd63cc6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.12

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on May 26, 2026.

Transparency log

Security for risk-threshold-engine 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for risk_threshold_engine-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on May 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page