Skip to content

API Reference parrot_tools.quant.toolkit

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot_tools.quant.toolkit

View source

QuantToolkit - Quantitative Risk Analysis Toolkit.

Provides agent-accessible tools for portfolio risk management, correlation analysis, fundamental scoring, volatility analytics, and stress testing.

Designed for allocation to:

  • risk_analyst: VaR, beta, drawdown, Sharpe, correlation, stress testing
  • risk_research_crew: rolling metrics, regime detection
  • equity_analyst: Piotroski F-Score, comparative risk metrics
  • sentiment_analyst: volatility cone, IV/RV spread

Alias AbstractToolkit

Re-exported from parrot_tools.toolkit.AbstractToolkit.

Alias AssetRiskInput

Re-exported from parrot_tools.quant.models.AssetRiskInput.

Alias PiotroskiInput

Re-exported from parrot_tools.quant.models.PiotroskiInput.

Alias PortfolioRiskInput

Re-exported from parrot_tools.quant.models.PortfolioRiskInput.

Class QuantToolkit

Quantitative risk analysis, portfolio metrics, and fundamental scoring toolkit.

Provides computational tools for:

  • Risk metrics (VaR, CVaR, beta, Sharpe, drawdown)
  • Correlation analysis and regime detection
  • Piotroski F-Score fundamental scoring
  • Volatility analytics (realized vol, cone, IV/RV spread)
  • Stress testing with predefined scenarios

Method QuantToolkit.compute_risk_metrics

Compute risk metrics for a single asset.

Calculates VaR, CVaR, beta, Sharpe ratio, and maximum drawdown for a given return series.

compute_risk_metrics(returns: list[float], benchmark_returns: list[float] | None = None, risk_free_rate: float = 0.04, annualization_factor: int = 252) -> dict

Parameter Type Default Description
returns list[float] Daily return series (e.g., [0.01, -0.02, 0.005, ...])
benchmark_returns list[float] | None None Benchmark returns for beta calculation (optional)
risk_free_rate float 0.04 Annualized risk-free rate (default 4%)
annualization_factor int 252 Trading days per year (252 stocks, 365 crypto)

Returns: dict — Dictionary containing: - volatility_annual: Annualized volatility - beta: Beta relative to benchmark (None if no benchmark) - sharpe_ratio: Annualized Sharpe ratio - max_drawdown: Maximum drawdown as decimal (e.g., -0.25 = -25%) - var_95: 1-day VaR at 95% confidence - var_99: 1-day VaR at 99% confidence - cvar_95: Expected shortfall at 95% confidence

Method QuantToolkit.compute_portfolio_risk

Compute portfolio-level risk metrics.

Calculates portfolio VaR, CVaR, volatility, beta, Sharpe ratio, and exposure metrics for a multi-asset portfolio.

compute_portfolio_risk(returns_data: dict[str, list[float]], weights: list[float], symbols: list[str], confidence: float = 0.95, risk_free_rate: float = 0.04, annualization_factor: int = 252, method: Literal['parametric', 'historical'] = 'parametric') -> dict

Parameter Type Default Description
returns_data dict[str, list[float]] Dict of {symbol: [daily_returns]} for each position
weights list[float] Position weights (must sum to 1.0)
symbols list[str] Symbol names matching returns_data keys
confidence float 0.95 VaR confidence level (default 0.95 for 95%)
risk_free_rate float 0.04 Annualized risk-free rate
annualization_factor int 252 Trading days per year
method Literal['parametric', 'historical'] 'parametric' VaR method - "parametric" or "historical"

Returns: dict — Dictionary containing: - var_1d_95_pct: 1-day portfolio VaR at 95% confidence - var_1d_99_pct: 1-day portfolio VaR at 99% confidence - cvar_1d_95_pct: 1-day portfolio CVaR at 95% - portfolio_volatility: Annualized portfolio volatility - portfolio_beta: Portfolio beta (None if no benchmark) - portfolio_sharpe: Annualized portfolio Sharpe ratio - max_drawdown: Maximum portfolio drawdown - net_exposure: Long - short exposure - gross_exposure: |Long| + |short| exposure

Method QuantToolkit.compute_rolling_metrics

Compute rolling risk metrics for regime detection.

Useful for identifying when volatility, risk, or correlation is changing over time.

compute_rolling_metrics(returns: list[float], window: int = 60, benchmark_returns: list[float] | None = None, risk_free_rate: float = 0.04, annualization_factor: int = 252) -> dict

Parameter Type Default Description
returns list[float] Daily return series
window int 60 Rolling window size in trading days (default 60)
benchmark_returns list[float] | None None Benchmark for beta calculation (optional)
risk_free_rate float 0.04 Annualized risk-free rate
annualization_factor int 252 Trading days per year

Returns: dict — Dictionary containing: - rolling_vol: List of rolling annualized volatilities - rolling_sharpe: List of rolling Sharpe ratios - rolling_var95: List of rolling VaR at 95% - rolling_beta: List of rolling betas (None if no benchmark)

Method QuantToolkit.compute_correlation_matrix

Compute correlation matrix for multiple assets.

IMPORTANT: Correlates returns by default (not prices) to avoid spurious correlation from random walk behavior in price series.

compute_correlation_matrix(price_data: dict[str, list[float]], method: Literal['pearson', 'spearman', 'kendall'] = 'pearson', returns_based: bool = True) -> dict

Parameter Type Default Description
price_data dict[str, list[float]] Dict of {symbol: [close_prices]} for each asset
method Literal['pearson', 'spearman', 'kendall'] 'pearson' Correlation method - "pearson", "spearman", or "kendall"
returns_based bool True If True, convert prices to returns first (recommended)

Returns: dict — Dictionary containing: - matrix: {symbol: {symbol: correlation}} nested dict - method: Correlation method used - returns_based: Whether returns were used

Method QuantToolkit.detect_correlation_regimes

Detect correlation regime changes between asset pairs.

Compares short-term vs long-term correlations and flags pairs where the deviation exceeds the z-threshold. Useful for detecting market regime changes and contagion.

detect_correlation_regimes(price_data: dict[str, list[float]], short_window: int = 20, long_window: int = 120, z_threshold: float = 2.0) -> dict

Parameter Type Default Description
price_data dict[str, list[float]] Dict of {symbol: [close_prices]} for each asset
short_window int 20 Recent window for comparison (default 20 days)
long_window int 120 Historical window for baseline (default 120 days)
z_threshold float 2.0 Standard deviations for alert trigger (default 2.0)

Returns: dict — Dictionary containing: - regime_alerts: List of {pair, short_corr, long_corr, z_score, alert} - correlation_matrix_short: Short-term correlation matrix - correlation_matrix_long: Long-term correlation matrix

Method QuantToolkit.compute_cross_asset_correlation

Compute correlation between equities and crypto with calendar alignment.

Handles different trading calendars (equity: 252 trading days/year, crypto: 365 days/year) by aligning on common dates.

compute_cross_asset_correlation(equity_prices: dict[str, list[float]], crypto_prices: dict[str, list[float]], timestamps_equity: list[str], timestamps_crypto: list[str]) -> dict

Parameter Type Default Description
equity_prices dict[str, list[float]] {symbol: [prices]} for equities (SPY, QQQ, etc.)
crypto_prices dict[str, list[float]] {symbol: [prices]} for crypto (BTC, ETH, etc.)
timestamps_equity list[str] Date strings for equity prices (YYYY-MM-DD)
timestamps_crypto list[str] Date strings for crypto prices (YYYY-MM-DD)

Returns: dict — Dictionary containing: - cross_asset_correlations: {pair: correlation} for cross-asset pairs - full_matrix: Full correlation matrix across all assets - common_dates_count: Number of dates used for correlation

Method QuantToolkit.calculate_piotroski_score

Calculate Piotroski F-Score (0-9) for fundamental quality assessment.

Evaluates company financial health using 9 accounting criteria:

  • Profitability (4 pts): positive NI, positive ROA, positive OCF, OCF > NI
  • Leverage (3 pts): lower debt ratio, higher current ratio, no dilution
  • Efficiency (2 pts): higher gross margin YoY, higher asset turnover YoY

calculate_piotroski_score(quarterly_financials: dict[str, float], prior_year_financials: dict[str, float] | None = None) -> dict

Parameter Type Default Description
quarterly_financials dict[str, float] Current quarter data including: - net_income: Net income - total_assets: Total assets - operating_cash_flow: Operating cash flow - total_debt: Total debt (optional) - current_assets: Current assets (optional) - current_liabilities: Current liabilities (optional) - shares_outstanding: Shares outstanding (optional) - revenue: Revenue (optional) - cost_of_revenue: Cost of revenue (optional)
prior_year_financials dict[str, float] | None None Prior year data for YoY comparison (optional)

Returns: dict — Dictionary containing: - total_score: F-Score (0-9) - criteria: {criterion: {score, value, threshold}} - data_completeness_pct: % of criteria that could be evaluated - interpretation: "Excellent" | "Good" | "Fair" | "Poor" - category_scores: {profitability, leverage, efficiency}

Method QuantToolkit.batch_piotroski_scores

Calculate F-Scores for multiple stocks in batch.

Efficient for comparing fundamental quality across a universe of stocks.

batch_piotroski_scores(symbols_data: dict[str, dict]) -> dict[str, dict]

Parameter Type Default Description
symbols_data dict[str, dict] Dict mapping symbol to financial data: {symbol: { "quarterly_financials": {...}, "prior_year_financials": {...} }}

Returns: dict[str, dict] — Dict mapping symbol to score result: {symbol: {total_score, criteria, interpretation, ...}}

Method QuantToolkit.compute_realized_volatility

Compute rolling realized volatility using various estimators.

Methods compared:

  • close_to_close: Standard deviation of returns (most common)
  • parkinson: Uses high-low range (~5x more efficient than close-to-close)
  • garman_klass: Uses full OHLC data (most efficient estimator)

compute_realized_volatility(returns: list[float], window: int = 20, annualization: int = 252, method: Literal['close_to_close', 'parkinson', 'garman_klass'] = 'close_to_close', ohlc_data: dict[str, list[float]] | None = None) -> list[float]

Parameter Type Default Description
returns list[float] Daily return series (for close_to_close method)
window int 20 Rolling window size in days (default 20)
annualization int 252 Trading days per year (252 stocks, 365 crypto)
method Literal['close_to_close', 'parkinson', 'garman_klass'] 'close_to_close' Volatility estimator to use
ohlc_data dict[str, list[float]] | None None Required for parkinson/garman_klass methods: {"high": [], "low": [], "open": [], "close": []}

Returns: list[float] — List of rolling annualized volatility values

Method QuantToolkit.compute_volatility_cone

Compute percentile ranks of current volatility across multiple windows.

Answers: "Is current 20-day vol high or low relative to history?" Useful for identifying elevated or suppressed volatility regimes.

compute_volatility_cone(returns: list[float], windows: list[int] | None = None, annualization: int = 252) -> dict

Parameter Type Default Description
returns list[float] Daily return series
windows list[int] | None None List of lookback windows (default [10, 20, 30, 60, 90, 120])
annualization int 252 Trading days per year

Returns: dict — Dict with structure {window: {current, percentile, min, max, median}}: - current: Current window volatility - percentile: Percentile rank (0-100) vs history - min: Historical minimum volatility - max: Historical maximum volatility - median: Historical median volatility

Method QuantToolkit.compute_iv_rv_spread

Compute IV vs RV spread for options sentiment analysis.

Compares implied volatility (from options prices) to realized volatility to identify fear/complacency regimes:

  • IV >> RV: Fear premium elevated (contrarian buy signal, sell premium)
  • IV << RV: Complacency (buy protection, vol likely to spike)
  • IV ≈ RV: Normal regime

compute_iv_rv_spread(implied_vol: float, realized_vol_series: list[float], window: int = 20) -> dict

Parameter Type Default Description
implied_vol float Current implied volatility (annualized, from options)
realized_vol_series list[float] Historical realized volatility series
window int 20 Window for current RV calculation (default 20)

Returns: dict — Dictionary containing: - implied_vol: Input IV - realized_vol: Current RV (windowed average) - spread: IV - RV - spread_pct: (IV - RV) / RV * 100 - percentile: Historical percentile of current spread - regime: "fear_premium" | "complacent" | "normal"

Method QuantToolkit.stress_test_portfolio

Apply stress scenarios to a portfolio and estimate potential losses.

Predefined scenarios available:

  • covid_crash_2020: March 2020 COVID market crash
  • rate_hike_shock: Aggressive interest rate increase
  • crypto_winter: Severe crypto bear market (2022-style)
  • black_swan: Generic severe market stress event
  • stagflation: High inflation + low growth scenario

stress_test_portfolio(portfolio_values: dict[str, float], scenario_names: list[str] | None = None, custom_scenarios: list[dict] | None = None) -> dict

Parameter Type Default Description
portfolio_values dict[str, float] {symbol: current_market_value} for each position
scenario_names list[str] | None None List of predefined scenario names to apply
custom_scenarios list[dict] | None None Custom scenarios as list of: [{"name": str, "asset_shocks": {symbol: shock_pct}, "description": str}] where shock_pct is decimal (e.g., -0.34 = -34%)

Returns: dict — Dictionary containing: - scenario_results: {scenario_name: { portfolio_loss_pct, portfolio_loss_usd, position_impacts, worst_position, best_position }} - worst_scenario: Name of scenario with largest loss - max_loss_pct: Maximum portfolio loss across all scenarios

Alias StressScenario

Re-exported from parrot_tools.quant.models.StressScenario.

Alias correlation

Re-exported from parrot_tools.quant.correlation.

Alias piotroski

Re-exported from parrot_tools.quant.piotroski.

Alias risk_metrics

Re-exported from parrot_tools.quant.risk_metrics.

Alias stress_testing

Re-exported from parrot_tools.quant.stress_testing.

Alias volatility

Re-exported from parrot_tools.quant.volatility.

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally