Recipes (wraquant.recipes)

Pre-built quantitative finance workflows that chain wraquant modules into complete analysis pipelines. Recipes are thin orchestration layers – the real logic lives in individual modules; recipes sequence the calls, align data, and assemble outputs.

Quick Example

import wraquant as wq

# The "just give me everything" function
result = wq.analyze(daily_returns)

# Descriptive statistics
print(result['descriptive'])

# Risk metrics (Sharpe, Sortino, max drawdown)
print(result['risk'])

# Distribution fit (normal params + KS test)
print(result['distribution'])

# Stationarity test (ADF)
print(result['stationarity'])

# With a benchmark for relative metrics
result = wq.analyze(daily_returns, benchmark=spy_returns)
print(f"Information ratio: {result['benchmark']['information_ratio']:.4f}")
print(f"Beta: {result['benchmark']['beta']:.4f}")

See also

  • The Getting Started guide for an introduction to analyze

  • wraquant.compose for the newer composable workflow system

API Reference

Pre-built quantitative finance workflows that chain wraquant modules.

These recipes show how the library’s modules work together as a cohesive framework rather than independent tools. Each recipe is a complete pipeline that wires data through several wraquant subsystems and returns a consolidated result dictionary.

Recipes are intentionally thin orchestration layers. The real logic lives in the individual modules; recipes just sequence the calls, align data, and assemble the outputs.

Example

>>> import wraquant as wq
>>> result = wq.analyze(daily_returns)
>>> print(result["risk"]["sharpe"])
analyze(returns, benchmark=None)[source]

Quick comprehensive analysis of a return series.

The “just give me everything” function. Runs relevant analyses from stats, risk, vol, regimes, and ts modules and returns a comprehensive report.

Pipeline: returns -> descriptive stats -> risk metrics -> distribution fit -> stationarity test -> (optional) regime detection -> (optional) GARCH volatility -> (optional) benchmark-relative metrics.

Chains: stats -> risk -> ts -> regimes -> vol.

Parameters:
  • returns (Series | DataFrame) – Return series or multi-asset DataFrame. If a DataFrame is provided, the first column is used as the primary series.

  • benchmark (Series | None, default: None) – Optional benchmark return series for relative metrics (information ratio, beta).

Returns:

  • descriptive – mean, std, skew, kurtosis, min, max, count.

  • risk – sharpe, sortino, max_drawdown.

  • distribution – fitted normal params + KS test.

  • stationarity – ADF test statistic, p-value, is_stationary.

  • regime (optional, requires >= 100 obs) – current regime, probabilities, n_regimes.

  • volatility (optional, requires >= 200 obs) – GARCH persistence, half-life, current conditional vol.

  • relative (only when benchmark provided) – information ratio, beta.

Return type:

dict[str, Any]

Example

>>> import pandas as pd, numpy as np
>>> np.random.seed(42)
>>> rets = pd.Series(np.random.normal(0.0005, 0.01, 500))
>>> report = analyze(rets)
>>> sorted(report.keys())
['descriptive', 'distribution', 'risk', 'stationarity']
regime_aware_backtest(prices, n_regimes=2, bull_weight=1.0, bear_weight=0.0, vol_target=0.15)[source]

Full regime-aware backtest pipeline.

Pipeline: prices -> returns -> detect regimes -> compute regime stats -> size positions by regime -> generate strategy returns -> tearsheet + risk metrics.

Chains: data -> regimes -> backtest -> risk.

Parameters:
  • prices (Series) – Price series (e.g. adjusted close).

  • n_regimes (int, default: 2) – Number of market regimes (default 2: bull/bear).

  • bull_weight (float, default: 1.0) – Portfolio weight in the low-volatility (bull) regime. 1.0 = fully invested.

  • bear_weight (float, default: 0.0) – Portfolio weight in the high-volatility (bear) regime. 0.0 = flat.

  • vol_target (float, default: 0.15) – Annual volatility target for position sizing (informational; not used for scaling in this recipe).

Returns:

  • regime_resultRegimeResult dataclass from wraquant.regimes.base.

  • strategy_returns – pd.Series of regime-weighted strategy returns.

  • tearsheet – comprehensive tearsheet dict from wraquant.backtest.tearsheet.

  • regime_stats – per-regime summary DataFrame.

  • risk_metrics – dict with sharpe, sortino, max_drawdown.

Return type:

dict[str, Any]

Example

>>> import pandas as pd, numpy as np
>>> np.random.seed(42)
>>> prices = pd.Series(
...     np.cumprod(1 + np.random.normal(0.0003, 0.01, 500)),
...     index=pd.bdate_range("2020-01-01", periods=500),
... )
>>> result = regime_aware_backtest(prices)
>>> "strategy_returns" in result
True
garch_risk_pipeline(returns, vol_model='GJR', dist='t', var_alpha=0.05)[source]

GARCH volatility -> VaR/CVaR -> stress testing pipeline.

Pipeline: returns -> fit GARCH -> conditional vol -> time-varying VaR -> news impact curve -> stress scenarios -> risk report.

Chains: vol -> risk -> stress.

Parameters:
  • returns (Series) – Simple return series (daily).

  • vol_model (str, default: 'GJR') – GARCH variant – "GARCH", "GJR", or "EGARCH".

  • dist (str, default: 't') – Error distribution for the GARCH model. "normal", "t" (Student-t), or "skewt" (skewed Student-t).

  • var_alpha (float, default: 0.05) – Significance level for VaR (0.05 = 95% VaR).

Returns:

  • garch – fitted GARCH result dict (params, conditional vol, diagnostics).

  • var – time-varying VaR/CVaR result dict.

  • news_impact – news impact curve dict.

  • diagnostics – summary dict with persistence, half_life, current_vol, breach_rate.

Return type:

dict[str, Any]

Example

>>> import pandas as pd, numpy as np
>>> np.random.seed(42)
>>> rets = pd.Series(np.random.normal(0.0003, 0.01, 500))
>>> result = garch_risk_pipeline(rets)
>>> "garch" in result and "var" in result
True
ml_alpha_pipeline(prices_df, target_col, model='gradient_boost', walk_forward_windows=5)[source]

ML alpha research pipeline.

Pipeline: prices -> features -> walk-forward train/predict -> evaluate -> feature importance.

Chains: ml/features -> ml/pipeline -> ml/advanced -> risk.

Parameters:
  • prices_df (DataFrame) – Multi-asset price DataFrame (columns = tickers).

  • target_col (str) – Column name of the target asset to predict.

  • model (str, default: 'gradient_boost') – Model type. Currently uses sklearn’s GradientBoostingClassifier under the hood.

  • walk_forward_windows (int, default: 5) – Not used in current implementation (walk-forward uses fixed train/test sizes).

Returns:

  • walk_forward – walk-forward backtest result dict (predictions, actuals, pnl, sharpe, hit_rate, equity_curve).

  • feature_importance – random forest importance ranking (or None if too few samples).

  • hit_rate – out-of-sample directional accuracy.

  • sharpe – out-of-sample Sharpe ratio.

Return type:

dict[str, Any]

Example

>>> import pandas as pd, numpy as np
>>> np.random.seed(42)
>>> prices = pd.DataFrame({
...     "SPY": np.cumprod(1 + np.random.normal(0.0003, 0.01, 600)),
...     "TLT": np.cumprod(1 + np.random.normal(0.0001, 0.005, 600)),
... })
>>> result = ml_alpha_pipeline(prices, target_col="SPY")
>>> "walk_forward" in result
True
portfolio_construction_pipeline(returns_df, method='risk_parity', regime_aware=True, n_regimes=2)[source]

Full portfolio construction pipeline.

Pipeline: returns -> covariance estimation -> optimize -> (optional) regime adjust -> risk decomposition -> betas.

Chains: stats -> opt -> regimes -> risk/portfolio_analytics.

Parameters:
  • returns_df (DataFrame) – Multi-asset return DataFrame (columns = tickers, rows = daily returns).

  • method (str, default: 'risk_parity') – Optimization method. "risk_parity" (default) or "mean_variance".

  • regime_aware (bool, default: True) – If True, adjust weights by current regime probability (scales down in high-vol regimes).

  • n_regimes (int, default: 2) – Number of regimes for the optional regime adjustment.

Returns:

  • weights – dict mapping asset name to weight.

  • optimizationOptimizationResult dataclass.

  • component_var – per-asset VaR contribution (pd.Series).

  • diversification_ratio – portfolio diversification ratio.

  • betas – dict mapping asset name to rolling beta vs first asset.

  • regime_adjusted – bool indicating whether regime scaling was applied.

Return type:

dict[str, Any]

Example

>>> import pandas as pd, numpy as np
>>> np.random.seed(42)
>>> rets = pd.DataFrame(
...     np.random.randn(252, 3) * np.array([0.01, 0.02, 0.005]),
...     columns=["Bonds", "Equity", "Gold"],
... )
>>> result = portfolio_construction_pipeline(rets, regime_aware=False)
>>> sum(result["weights"].values())
1.0...