Visualization (wraquant.viz)¶
Interactive Plotly-based visualizations for portfolio analysis, risk monitoring, regime dashboards, candlestick charts, tearsheets, and correlation networks.
Submodules:
Charts – line, scatter, histogram, heatmap utilities
Candlestick – OHLC candlestick charts with indicator overlays
Dashboard – comprehensive multi-panel dashboards
Portfolio – allocation, efficient frontier, rebalancing visualization
Risk – VaR, drawdown, risk decomposition charts
Returns – equity curves, monthly heatmaps, distribution plots
Time Series – decomposition, forecast, and ACF/PACF plots
Advanced – correlation networks, vol surfaces, regime maps
Quick Example¶
from wraquant.viz import charts, candlestick, portfolio, risk
# Candlestick chart with volume
fig = candlestick.plot(ohlcv)
# Equity curve with drawdown overlay
fig = risk.equity_drawdown_chart(strategy_returns)
# Portfolio allocation pie chart
fig = portfolio.allocation_chart(weights, asset_names)
# Monthly returns heatmap
fig = charts.monthly_heatmap(returns)
See also
Backtesting (wraquant.backtest) – Tearsheet generation includes visualization
Risk Management (wraquant.risk) – Risk analysis outputs that can be visualized
API Reference¶
Financial visualizations for wraquant.
Provides publication-quality charts and interactive dashboards for every stage of the quant research workflow: returns analysis, portfolio diagnostics, regime overlays, risk reporting, technical analysis, vol surfaces, correlation networks, and full strategy tearsheets. Offers both static matplotlib plots and interactive dark-themed Plotly figures.
Requires the viz optional dependency group:
pdm install -G viz
Key sub-modules:
Returns (
returns) –plot_cumulative_returns,plot_drawdowns,plot_return_distribution,plot_rolling_returns,plot_monthly_heatmap.Portfolio (
portfolio) –plot_weights,plot_efficient_frontier,plot_risk_contribution,plot_correlation_matrix.Time series (
timeseries) –plot_series,plot_regime_overlay,plot_decomposition.Risk (
risk) –plot_var_backtest,plot_rolling_volatility,plot_tail_distribution.Interactive Plotly (
interactive,advanced) –plotly_returns,plotly_drawdown,plotly_rolling_stats,plotly_correlation_heatmap,plotly_efficient_frontier,plotly_vol_surface,plotly_network_graph,plotly_regime_overlay,plotly_treemap,plotly_radar.Candlestick (
candlestick) –plotly_candlestick,plotly_heikin_ashi,plotly_renko,plotly_market_profile.Dashboards (
dashboard) – Multi-panel Plotly dashboards:portfolio_dashboard,regime_dashboard,risk_dashboard,technical_dashboard.Rich charts (
charts) – Standalone analysis charts:plot_backtest_tearsheet,plot_distribution_analysis,plot_correlation_network,plot_vol_surface.auto_plot – Auto-detects data type and chooses the appropriate visualization.
Themes (
themes) –set_wraquant_style,apply_theme,COLORSpalette.
Example
>>> from wraquant.viz import plotly_returns, portfolio_dashboard
>>> fig = plotly_returns(returns, title="Strategy Returns")
>>> dash = portfolio_dashboard(weights, returns, benchmark)
Use wraquant.viz for all visualization needs. It integrates with
wraquant.risk (risk dashboards), wraquant.regimes (regime
overlays), wraquant.backtest (tearsheets), and wraquant.opt
(efficient frontiers). For a full interactive Streamlit application,
see wraquant.dashboard.
- set_wraquant_style()[source]¶
Apply a clean, professional dark-on-white matplotlib style via rcParams.
This modifies the global matplotlib rcParams so that all subsequent plots use the wraquant house style. Call once at the start of a session or notebook.
- Return type:
- Returns:
None
- apply_theme(fig, ax)[source]¶
Apply the wraquant visual theme to an existing figure and axes.
- Parameters:
fig (
Figure) – The matplotlib Figure to style.ax (
Axes) – The matplotlib Axes to style.
- Return type:
- Returns:
None
- plot_cumulative_returns(returns, benchmark=None, title=None, ax=None)[source]¶
Plot cumulative return line chart with optional benchmark overlay.
- Parameters:
returns (pd.Series) – Simple return series (not cumulative).
benchmark (pd.Series | None, default:
None) – Optional benchmark return series for comparison.title (str | None, default:
None) – Plot title. Defaults to"Cumulative Returns".ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_drawdowns(returns, top_n=5, ax=None)[source]¶
Plot underwater chart showing drawdown periods.
- Parameters:
returns (pd.Series) – Simple return series.
top_n (int, default:
5) – Number of largest drawdowns to shade.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_return_distribution(returns, bins=50, fit_normal=True, ax=None)[source]¶
Plot histogram of returns with optional normal distribution fit overlay.
- Parameters:
returns (pd.Series) – Simple return series.
bins (int, default:
50) – Number of histogram bins.fit_normal (bool, default:
True) – If True, overlay a fitted normal PDF.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_rolling_returns(returns, window=252, ax=None)[source]¶
Plot rolling annualized returns.
- Parameters:
returns (pd.Series) – Simple return series.
window (int, default:
252) – Rolling window in periods (default 252 for 1 year of daily data).ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_monthly_heatmap(returns, ax=None)[source]¶
Plot a month-by-year heatmap of returns.
- Parameters:
returns (pd.Series) – Simple return series with a
DatetimeIndex.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_weights(weights, names=None, ax=None)[source]¶
Plot portfolio weights as a horizontal bar chart.
- Parameters:
weights (pd.Series | npt.NDArray[np.floating]) – Portfolio weight vector (pandas Series or numpy array).
names (list[str] | None, default:
None) – Asset names. If weights is a Series its index is used by default; otherwise sequential integers are used.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_efficient_frontier(returns_range, vol_range, sharpe_range=None, optimal_point=None, ax=None)[source]¶
Plot the efficient frontier as a scatter/line plot.
- Parameters:
returns_range (npt.NDArray[np.floating]) – Array of expected returns for each portfolio.
vol_range (npt.NDArray[np.floating]) – Array of volatilities for each portfolio.
sharpe_range (npt.NDArray[np.floating] | None, default:
None) – Optional array of Sharpe ratios used to color the scatter points.optimal_point (tuple[float, float] | None, default:
None) – Optional(volatility, return)tuple marking the optimal portfolio.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_risk_contribution(contributions, names=None, ax=None)[source]¶
Plot risk contributions as a stacked bar chart.
- Parameters:
contributions (pd.Series | npt.NDArray[np.floating]) – Risk contribution per asset (pandas Series or array).
names (list[str] | None, default:
None) – Asset names. If contributions is a Series its index is used by default.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_correlation_matrix(corr_matrix, labels=None, ax=None)[source]¶
Plot correlation matrix as an annotated heatmap.
- Parameters:
corr_matrix (pd.DataFrame | npt.NDArray[np.floating]) – Square correlation matrix (DataFrame or 2-D array).
labels (list[str] | None, default:
None) – Axis labels. If corr_matrix is a DataFrame its columns are used by default.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_series(data, title=None, ylabel=None, ax=None)[source]¶
Plot a basic time series line chart.
- Parameters:
data (pd.Series | pd.DataFrame) – Time series data. A Series produces a single line; a DataFrame plots one line per column.
title (str | None, default:
None) – Plot title.ylabel (str | None, default:
None) – Y-axis label.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_regime_overlay(data, regimes, ax=None)[source]¶
Plot a time series with colored background regions for regimes.
- Parameters:
data (pd.Series) – Time series to plot as a line.
regimes (pd.Series) – Integer or categorical series of the same index indicating the regime at each point.
ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_decomposition(trend, seasonal, residual, ax=None)[source]¶
Plot a 3-panel decomposition (trend, seasonal, residual).
- Parameters:
trend (pd.Series) – Trend component series.
seasonal (pd.Series) – Seasonal component series.
residual (pd.Series) – Residual component series.
ax (matplotlib.axes.Axes | None, default:
None) – Ignored. A new 3-panel figure is always created.
- Return type:
matplotlib.figure.Figure
- Returns:
The matplotlib Figure containing the three-panel plot.
- plot_var_backtest(returns, var_level, confidence=0.95, ax=None)[source]¶
Plot returns with a VaR threshold line, highlighting breaches.
- Parameters:
returns (pd.Series) – Simple return series.
var_level (pd.Series | float) – Value-at-Risk threshold. Pass a scalar for a constant threshold or a Series for a time-varying VaR.
confidence (float, default:
0.95) – VaR confidence level (used only for the title).ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_rolling_volatility(returns, window=21, annualize=True, ax=None)[source]¶
Plot rolling volatility line chart.
- Parameters:
returns (pd.Series) – Simple return series.
window (int, default:
21) – Rolling window in periods (default 21 for ~1 month daily).annualize (bool, default:
True) – Whether to annualize (multiply by sqrt(252)).ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_tail_distribution(returns, threshold_percentile=5, ax=None)[source]¶
Plot distribution tails, zoomed into the left tail.
- Parameters:
returns (pd.Series) – Simple return series.
threshold_percentile (float, default:
5) – Percentile below which tails are highlighted.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plotly_returns(returns, benchmark=None, title=None)[source]¶
Interactive cumulative returns chart with hover tooltips.
Hover shows date, cumulative return, and current drawdown at each point.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_drawdown(returns)[source]¶
Interactive underwater chart with recovery periods highlighted.
Shades the drawdown area and annotates the deepest drawdown.
- Parameters:
returns (
Series) – Simple return series.- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_rolling_stats(returns, window=63)[source]¶
Rolling Sharpe, volatility, and beta in vertically-stacked subplots.
- plotly_distribution(returns, bins=50, overlay_normal=True)[source]¶
Interactive histogram with KDE and optional fitted normal overlay.
- plotly_correlation_heatmap(returns_df)[source]¶
Interactive correlation matrix heatmap with hierarchical clustering.
Reorders assets by hierarchical clustering so that correlated groups appear together. Hover shows the pair and correlation value.
- Parameters:
returns_df (
DataFrame) – DataFrame of asset returns (columns = assets).- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_efficient_frontier(expected_returns, cov_matrix, n_portfolios=5000)[source]¶
Interactive efficient frontier with hover showing portfolio weights.
Generates random portfolios and plots the risk-return cloud. The efficient frontier is highlighted. Hovering over points reveals the weight vector.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_risk_return_scatter(returns_df)[source]¶
Risk-return scatter plot with asset labels and clickable points.
Annualizes both risk and return assuming 252 trading days.
- Parameters:
returns_df (
DataFrame) – DataFrame of asset returns (columns = assets).- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_regime_overlay(prices, regime_labels)[source]¶
Price chart with colored background bands for market regimes.
- plotly_vol_surface(strikes, expiries, implied_vols)[source]¶
3-D implied volatility surface.
- Parameters:
strikes (
ndarray[tuple[Any,...],dtype[floating]]) – 1-D array of strike prices.expiries (
ndarray[tuple[Any,...],dtype[floating]]) – 1-D array of expiries (e.g. days to expiry or years).implied_vols (
ndarray[tuple[Any,...],dtype[floating]]) – 2-D array of shape(len(expiries), len(strikes))containing implied volatilities.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith a 3-D surface.
- plotly_term_structure(maturities, yields, dates=None)[source]¶
Animated yield curve through time.
Each row of yields is a snapshot of the yield curve at one date. The animation steps through dates.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith animation frames.
- plotly_copula_scatter(u, v, copula_type='empirical')[source]¶
Copula scatter plot with marginal histograms.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith marginal histograms.
- plotly_network_graph(correlation_matrix, threshold=0.5)[source]¶
Asset correlation network graph.
Draws edges between assets whose absolute correlation exceeds threshold. Node size is proportional to the number of edges.
- plotly_sankey_flow(sectors, allocations_before, allocations_after)[source]¶
Sankey diagram showing portfolio rebalancing flows.
Left side shows before weights, right side shows after weights. Flows connect each sector’s allocation change.
- plotly_treemap(weights, sectors, returns)[source]¶
Portfolio treemap with tiles sized by weight and colored by return.
- plotly_candlestick(ohlcv_df, overlays=None, indicators=None)[source]¶
Full-featured interactive candlestick chart.
Supports optional overlays (moving averages, Bollinger Bands) and a secondary volume bar chart.
- Parameters:
ohlcv_df (
DataFrame) – DataFrame with columnsopen, high, low, closeand optionallyvolume. Column names are case-insensitive.overlays (
list[str] |None, default:None) – List of overlay names to draw. Supported values:"sma20","sma50","sma200","ema20","bb"(Bollinger Bands, 20-period, 2 std).indicators (
list[str] |None, default:None) – Reserved for future sub-chart indicators.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_market_profile(ohlcv_df)[source]¶
Market / volume profile chart.
Shows a horizontal histogram of volume at each price level alongside a candlestick chart.
- Parameters:
ohlcv_df (
DataFrame) – DataFrame withopen, high, low, close, volumecolumns.- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_heikin_ashi(ohlcv_df)[source]¶
Heikin-Ashi candlestick chart.
Computes Heikin-Ashi OHLC values from the raw data and plots them as an interactive candlestick chart.
- Parameters:
ohlcv_df (
DataFrame) – DataFrame withopen, high, low, closecolumns.- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- portfolio_dashboard(returns, benchmark=None, rolling_window=63, title='Portfolio Performance Dashboard')[source]¶
Create a comprehensive multi-panel portfolio performance dashboard.
Produces a six-panel figure with cumulative returns, drawdowns, rolling risk-adjusted ratios, return distributions, a monthly returns heatmap, and an annotation box of key performance metrics.
- Parameters:
returns (
Series) – Simple (non-cumulative) daily return series with aDatetimeIndex.benchmark (
Series|None, default:None) – Optional benchmark return series for comparison. Must share the same index or a compatible date range.rolling_window (
int, default:63) – Window in trading days for rolling Sharpe and Sortino calculations. Defaults to 63 (~1 quarter).title (
str, default:'Portfolio Performance Dashboard') – Dashboard title displayed at the top.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith six subplots.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=504) >>> rets = pd.Series(np.random.normal(0.0004, 0.015, 504), ... index=dates, name="Strategy") >>> fig = portfolio_dashboard(rets) >>> fig.show()
- regime_dashboard(returns, states, probabilities=None, transition_matrix=None, title='Regime Analysis Dashboard')[source]¶
Create a multi-panel regime analysis dashboard.
Combines price/returns with regime overlays, probability series, per-regime distribution comparisons, and an optional transition matrix heatmap.
- Parameters:
returns (
Series) – Simple daily return series with aDatetimeIndex.states (
Series) – Integer series (same index as returns) indicating the detected regime at each observation (e.g. 0, 1, 2).probabilities (
DataFrame|None, default:None) – Optional DataFrame where each column is the probability of being in a given regime at each time step. Columns should be regime labels or integers.transition_matrix (
ndarray[tuple[Any,...],dtype[floating]] |None, default:None) – Optional square array of regime transition probabilities. Shape(n_regimes, n_regimes).title (
str, default:'Regime Analysis Dashboard') – Dashboard title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith up to five panels.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=504) >>> rets = pd.Series(np.random.normal(0.0004, 0.015, 504), index=dates) >>> states = pd.Series(np.random.choice([0, 1], 504), index=dates) >>> fig = regime_dashboard(rets, states) >>> fig.show()
- risk_dashboard(returns, var_confidence=0.95, rolling_window=63, stress_scenarios=None, title='Risk Monitoring Dashboard')[source]¶
Create a multi-panel risk monitoring dashboard.
Displays rolling VaR/CVaR with breach markers, an animated correlation heatmap snapshot, stress test scenario comparison bars, and a risk contribution breakdown.
- Parameters:
returns (
DataFrame) – DataFrame of daily returns with one column per asset. If a single-column DataFrame or Series is passed, some panels (correlation, risk contribution) are simplified.var_confidence (
float, default:0.95) – Confidence level for VaR/CVaR (default 0.95).rolling_window (
int, default:63) – Window in trading days for rolling risk metrics (default 63).stress_scenarios (
dict[str,float] |None, default:None) – Optional dict mapping scenario names to portfolio-level return shocks for bar comparison. Example:{"2008 Crisis": -0.38, "COVID Crash": -0.34}.title (
str, default:'Risk Monitoring Dashboard') – Dashboard title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=504) >>> df = pd.DataFrame(np.random.normal(0.0003, 0.015, (504, 4)), ... index=dates, columns=["A", "B", "C", "D"]) >>> fig = risk_dashboard(df) >>> fig.show()
- technical_dashboard(ohlcv, indicators=None, title='Technical Analysis Dashboard')[source]¶
Create a multi-panel technical analysis chart with indicators.
Combines a candlestick chart with volume bars, overlay indicators (moving averages, Bollinger Bands), and subplot oscillators (RSI, MACD).
- Parameters:
ohlcv (
DataFrame) – DataFrame with columnsopen, high, low, closeand optionallyvolume. Column names are case-insensitive.indicators (
list[str] |None, default:None) –List of indicator names to display. Supported values:
Overlays (drawn on price chart): -
"sma20","sma50","sma200"– Simple moving averages -"ema12","ema20","ema26"– Exponential moving averages -"bb"– Bollinger Bands (20-period, 2 std)Oscillators (drawn in sub-panels): -
"rsi"– 14-period Relative Strength Index -"macd"– MACD (12, 26, 9)Defaults to
["sma20", "sma50", "bb", "rsi", "macd"]when None.title (
str, default:'Technical Analysis Dashboard') – Dashboard title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=252) >>> close = 100 * np.exp(np.cumsum(np.random.normal(0.0005, 0.02, 252))) >>> df = pd.DataFrame({ ... "open": close * 0.99, "high": close * 1.02, ... "low": close * 0.98, "close": close, ... "volume": np.random.randint(1e6, 1e7, 252), ... }, index=dates) >>> fig = technical_dashboard(df, indicators=["sma20", "bb", "rsi", "macd"]) >>> fig.show()
- plot_multi_asset(returns_df, rolling_corr_window=63, title='Multi-Asset Comparison')[source]¶
Multi-asset comparison chart with normalized performance and correlations.
Creates a three-panel figure showing rebased (base-100) performance lines, a correlation matrix heatmap, and rolling pairwise correlation time series.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith three subplots.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=504) >>> df = pd.DataFrame(np.random.normal(0.0003, 0.015, (504, 3)), ... index=dates, columns=["SPY", "AGG", "GLD"]) >>> fig = plot_multi_asset(df) >>> fig.show()
- plot_vol_surface(strikes, maturities, implied_vols, title='Implied Volatility Surface')[source]¶
3-D implied volatility surface with interactive rotation.
Renders a Plotly Surface plot with strike on the x-axis, maturity on the y-axis, and implied volatility on the z-axis. A color gradient encodes the volatility level.
- Parameters:
strikes (
ndarray[tuple[Any,...],dtype[floating]]) – 1-D array of strike prices.maturities (
ndarray[tuple[Any,...],dtype[floating]]) – 1-D array of maturities (years or days to expiry).implied_vols (
ndarray[tuple[Any,...],dtype[floating]]) – 2-D array of shape(len(maturities), len(strikes))containing implied volatilities.title (
str, default:'Implied Volatility Surface') – Chart title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith a 3-D surface.
Example
>>> import numpy as np >>> strikes = np.linspace(80, 120, 25) >>> mats = np.array([0.1, 0.25, 0.5, 1.0, 2.0]) >>> iv = 0.2 + 0.05 * np.random.randn(len(mats), len(strikes)) >>> fig = plot_vol_surface(strikes, mats, iv) >>> fig.show()
- plot_regime_overlay_probs(prices, regime_probs, title='Price with Regime Probability Overlay')¶
Price chart with smooth regime probability shown as background shading.
Unlike a discrete regime label overlay, this function uses the continuous probability of each regime to determine background opacity, producing a gradient-like shading effect.
- Parameters:
prices (
Series) – Price or level time series.regime_probs (
DataFrame) – DataFrame where each column is the probability of a given regime at each time step. Columns are used as regime names. Probabilities should sum to 1 per row.title (
str, default:'Price with Regime Probability Overlay') – Chart title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=252) >>> prices = pd.Series(100 * np.exp(np.cumsum( ... np.random.normal(0.0005, 0.02, 252))), index=dates, name="SPY") >>> probs = pd.DataFrame({"Bull": 0.7, "Bear": 0.3}, ... index=dates) >>> fig = plot_regime_overlay(prices, probs) >>> fig.show()
- plot_distribution_analysis(returns, bins=60, title='Return Distribution Analysis')[source]¶
Rich distribution analysis with histogram, KDE, normal overlay, QQ plot, and stats.
Creates a two-panel figure. The main panel shows a histogram with KDE and a fitted normal distribution overlay. A secondary inset displays a QQ plot. Key statistics (mean, std, skew, kurtosis, Jarque-Bera test) are annotated.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> rets = pd.Series(np.random.normal(0.0004, 0.015, 504), ... name="Strategy") >>> fig = plot_distribution_analysis(rets) >>> fig.show()
- plot_correlation_network(returns_df, threshold=0.3, show_mst=False, title='Asset Correlation Network')[source]¶
Interactive correlation network graph.
Assets are drawn as nodes in a circular layout. Edges connect pairs whose absolute correlation exceeds threshold. Edge thickness scales with correlation strength, and edges are colored green (positive) or red (negative).
Optionally overlays the minimum spanning tree (MST) of the correlation-derived distance matrix.
- Parameters:
returns_df (
DataFrame) – DataFrame of daily returns (columns = assets).threshold (
float, default:0.3) – Minimum absolute correlation to draw an edge (default 0.3).show_mst (
bool, default:False) – If True, overlay the MST as thicker edges.title (
str, default:'Asset Correlation Network') – Chart title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=252) >>> df = pd.DataFrame(np.random.normal(0.0003, 0.015, (252, 6)), ... index=dates, ... columns=["A", "B", "C", "D", "E", "F"]) >>> fig = plot_correlation_network(df, threshold=0.2, show_mst=True) >>> fig.show()
- plot_backtest_tearsheet(returns, trades=None, benchmark=None, title='Backtest Tearsheet')[source]¶
Full backtest analysis tearsheet figure.
Produces a multi-panel figure with an equity curve and drawdown bands, a monthly returns calendar heatmap, a trade analysis scatter (if trades are provided), rolling metrics, and a summary statistics table.
- Parameters:
returns (
Series) – Simple daily return series with aDatetimeIndex.trades (
DataFrame|None, default:None) – Optional DataFrame of trade results with at least apnlcolumn (profit/loss per trade). May also includeentry_dateandexit_datecolumns.benchmark (
Series|None, default:None) – Optional benchmark return series for comparison.title (
str, default:'Backtest Tearsheet') – Tearsheet title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=504) >>> rets = pd.Series(np.random.normal(0.0004, 0.015, 504), ... index=dates, name="Strategy") >>> fig = plot_backtest_tearsheet(rets) >>> fig.show()
- auto_plot(data, kind=None, **kwargs)[source]¶
Automatically choose the best visualization for the data.
Detects the data type and calls the appropriate viz function, bridging
vizwithrisk,regimes, andbacktestwithout requiring the caller to know which plot function to use.Detection logic:
pd.Series of returns (values in [-1, 1] range, name contains ‘return’ or ‘ret’) – distribution plot + cumulative returns.
pd.DataFrame of returns – correlation heatmap + multi-asset cumulative returns.
RegimeResult (from
wraquant.regimes.base) – regime overlay dashboard showing states, probabilities, and statistics.dict with ‘equity_curve’ key (backtest result) – backtest tearsheet with drawdowns, rolling Sharpe, etc.
kind=’distribution’ – force distribution analysis.
kind=’correlation’ – force correlation heatmap.
- Parameters:
data – The data to visualize. Can be a pd.Series, pd.DataFrame, RegimeResult, or backtest result dict.
kind (default:
None) – Force a specific visualization type. Options:'distribution','correlation','cumulative','regime','tearsheet'. If None, auto-detects from the data type.**kwargs – Additional keyword arguments forwarded to the underlying plot function.
- Returns:
The plot object (matplotlib Figure or Plotly Figure) from the underlying visualization function.
Example
>>> import pandas as pd, numpy as np >>> returns = pd.Series(np.random.randn(252) * 0.01, name='returns') >>> fig = auto_plot(returns) # auto-detects returns, plots distribution
See also
plot_return_distribution: Returns distribution plot. plot_cumulative_returns: Cumulative returns chart. plotly_correlation_heatmap: Correlation heatmap. regime_dashboard: Regime analysis dashboard. plot_backtest_tearsheet: Backtest tearsheet.
Charts¶
Rich individual Plotly charts for financial analysis.
Standalone chart functions for multi-asset comparison, volatility surfaces,
regime overlays, distribution analysis, correlation networks, and backtest
tearsheets. Each returns a plotly.graph_objects.Figure styled with the
plotly_dark template.
Example
>>> from wraquant.viz.charts import plot_distribution_analysis
>>> fig = plot_distribution_analysis(returns)
>>> fig.show()
- plot_multi_asset(returns_df, rolling_corr_window=63, title='Multi-Asset Comparison')[source]¶
Multi-asset comparison chart with normalized performance and correlations.
Creates a three-panel figure showing rebased (base-100) performance lines, a correlation matrix heatmap, and rolling pairwise correlation time series.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith three subplots.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=504) >>> df = pd.DataFrame(np.random.normal(0.0003, 0.015, (504, 3)), ... index=dates, columns=["SPY", "AGG", "GLD"]) >>> fig = plot_multi_asset(df) >>> fig.show()
- plot_vol_surface(strikes, maturities, implied_vols, title='Implied Volatility Surface')[source]¶
3-D implied volatility surface with interactive rotation.
Renders a Plotly Surface plot with strike on the x-axis, maturity on the y-axis, and implied volatility on the z-axis. A color gradient encodes the volatility level.
- Parameters:
strikes (
ndarray[tuple[Any,...],dtype[floating]]) – 1-D array of strike prices.maturities (
ndarray[tuple[Any,...],dtype[floating]]) – 1-D array of maturities (years or days to expiry).implied_vols (
ndarray[tuple[Any,...],dtype[floating]]) – 2-D array of shape(len(maturities), len(strikes))containing implied volatilities.title (
str, default:'Implied Volatility Surface') – Chart title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith a 3-D surface.
Example
>>> import numpy as np >>> strikes = np.linspace(80, 120, 25) >>> mats = np.array([0.1, 0.25, 0.5, 1.0, 2.0]) >>> iv = 0.2 + 0.05 * np.random.randn(len(mats), len(strikes)) >>> fig = plot_vol_surface(strikes, mats, iv) >>> fig.show()
- plot_regime_overlay(prices, regime_probs, title='Price with Regime Probability Overlay')[source]¶
Price chart with smooth regime probability shown as background shading.
Unlike a discrete regime label overlay, this function uses the continuous probability of each regime to determine background opacity, producing a gradient-like shading effect.
- Parameters:
prices (
Series) – Price or level time series.regime_probs (
DataFrame) – DataFrame where each column is the probability of a given regime at each time step. Columns are used as regime names. Probabilities should sum to 1 per row.title (
str, default:'Price with Regime Probability Overlay') – Chart title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=252) >>> prices = pd.Series(100 * np.exp(np.cumsum( ... np.random.normal(0.0005, 0.02, 252))), index=dates, name="SPY") >>> probs = pd.DataFrame({"Bull": 0.7, "Bear": 0.3}, ... index=dates) >>> fig = plot_regime_overlay(prices, probs) >>> fig.show()
- plot_distribution_analysis(returns, bins=60, title='Return Distribution Analysis')[source]¶
Rich distribution analysis with histogram, KDE, normal overlay, QQ plot, and stats.
Creates a two-panel figure. The main panel shows a histogram with KDE and a fitted normal distribution overlay. A secondary inset displays a QQ plot. Key statistics (mean, std, skew, kurtosis, Jarque-Bera test) are annotated.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> rets = pd.Series(np.random.normal(0.0004, 0.015, 504), ... name="Strategy") >>> fig = plot_distribution_analysis(rets) >>> fig.show()
- plot_correlation_network(returns_df, threshold=0.3, show_mst=False, title='Asset Correlation Network')[source]¶
Interactive correlation network graph.
Assets are drawn as nodes in a circular layout. Edges connect pairs whose absolute correlation exceeds threshold. Edge thickness scales with correlation strength, and edges are colored green (positive) or red (negative).
Optionally overlays the minimum spanning tree (MST) of the correlation-derived distance matrix.
- Parameters:
returns_df (
DataFrame) – DataFrame of daily returns (columns = assets).threshold (
float, default:0.3) – Minimum absolute correlation to draw an edge (default 0.3).show_mst (
bool, default:False) – If True, overlay the MST as thicker edges.title (
str, default:'Asset Correlation Network') – Chart title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=252) >>> df = pd.DataFrame(np.random.normal(0.0003, 0.015, (252, 6)), ... index=dates, ... columns=["A", "B", "C", "D", "E", "F"]) >>> fig = plot_correlation_network(df, threshold=0.2, show_mst=True) >>> fig.show()
- plot_backtest_tearsheet(returns, trades=None, benchmark=None, title='Backtest Tearsheet')[source]¶
Full backtest analysis tearsheet figure.
Produces a multi-panel figure with an equity curve and drawdown bands, a monthly returns calendar heatmap, a trade analysis scatter (if trades are provided), rolling metrics, and a summary statistics table.
- Parameters:
returns (
Series) – Simple daily return series with aDatetimeIndex.trades (
DataFrame|None, default:None) – Optional DataFrame of trade results with at least apnlcolumn (profit/loss per trade). May also includeentry_dateandexit_datecolumns.benchmark (
Series|None, default:None) – Optional benchmark return series for comparison.title (
str, default:'Backtest Tearsheet') – Tearsheet title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=504) >>> rets = pd.Series(np.random.normal(0.0004, 0.015, 504), ... index=dates, name="Strategy") >>> fig = plot_backtest_tearsheet(rets) >>> fig.show()
Candlestick¶
Interactive OHLCV candlestick and alternative chart types.
Full-featured candlestick with overlays, market/volume profile, Renko charts, and Heikin-Ashi candlesticks — all as interactive Plotly figures.
- plotly_candlestick(ohlcv_df, overlays=None, indicators=None)[source]¶
Full-featured interactive candlestick chart.
Supports optional overlays (moving averages, Bollinger Bands) and a secondary volume bar chart.
- Parameters:
ohlcv_df (
DataFrame) – DataFrame with columnsopen, high, low, closeand optionallyvolume. Column names are case-insensitive.overlays (
list[str] |None, default:None) – List of overlay names to draw. Supported values:"sma20","sma50","sma200","ema20","bb"(Bollinger Bands, 20-period, 2 std).indicators (
list[str] |None, default:None) – Reserved for future sub-chart indicators.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_market_profile(ohlcv_df)[source]¶
Market / volume profile chart.
Shows a horizontal histogram of volume at each price level alongside a candlestick chart.
- Parameters:
ohlcv_df (
DataFrame) – DataFrame withopen, high, low, close, volumecolumns.- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_heikin_ashi(ohlcv_df)[source]¶
Heikin-Ashi candlestick chart.
Computes Heikin-Ashi OHLC values from the raw data and plots them as an interactive candlestick chart.
- Parameters:
ohlcv_df (
DataFrame) – DataFrame withopen, high, low, closecolumns.- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Dashboard¶
Multi-panel interactive dashboards for financial analysis.
Comprehensive Plotly dashboards that combine multiple chart types into single rich figures for portfolio analysis, regime detection, risk monitoring, and technical trading.
All functions return plotly.graph_objects.Figure objects styled with
the plotly_dark template. Users can call .show() or save to HTML.
Example
>>> from wraquant.viz.dashboard import portfolio_dashboard
>>> fig = portfolio_dashboard(returns, benchmark=benchmark)
>>> fig.show()
- portfolio_dashboard(returns, benchmark=None, rolling_window=63, title='Portfolio Performance Dashboard')[source]¶
Create a comprehensive multi-panel portfolio performance dashboard.
Produces a six-panel figure with cumulative returns, drawdowns, rolling risk-adjusted ratios, return distributions, a monthly returns heatmap, and an annotation box of key performance metrics.
- Parameters:
returns (
Series) – Simple (non-cumulative) daily return series with aDatetimeIndex.benchmark (
Series|None, default:None) – Optional benchmark return series for comparison. Must share the same index or a compatible date range.rolling_window (
int, default:63) – Window in trading days for rolling Sharpe and Sortino calculations. Defaults to 63 (~1 quarter).title (
str, default:'Portfolio Performance Dashboard') – Dashboard title displayed at the top.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith six subplots.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=504) >>> rets = pd.Series(np.random.normal(0.0004, 0.015, 504), ... index=dates, name="Strategy") >>> fig = portfolio_dashboard(rets) >>> fig.show()
- regime_dashboard(returns, states, probabilities=None, transition_matrix=None, title='Regime Analysis Dashboard')[source]¶
Create a multi-panel regime analysis dashboard.
Combines price/returns with regime overlays, probability series, per-regime distribution comparisons, and an optional transition matrix heatmap.
- Parameters:
returns (
Series) – Simple daily return series with aDatetimeIndex.states (
Series) – Integer series (same index as returns) indicating the detected regime at each observation (e.g. 0, 1, 2).probabilities (
DataFrame|None, default:None) – Optional DataFrame where each column is the probability of being in a given regime at each time step. Columns should be regime labels or integers.transition_matrix (
ndarray[tuple[Any,...],dtype[floating]] |None, default:None) – Optional square array of regime transition probabilities. Shape(n_regimes, n_regimes).title (
str, default:'Regime Analysis Dashboard') – Dashboard title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith up to five panels.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=504) >>> rets = pd.Series(np.random.normal(0.0004, 0.015, 504), index=dates) >>> states = pd.Series(np.random.choice([0, 1], 504), index=dates) >>> fig = regime_dashboard(rets, states) >>> fig.show()
- risk_dashboard(returns, var_confidence=0.95, rolling_window=63, stress_scenarios=None, title='Risk Monitoring Dashboard')[source]¶
Create a multi-panel risk monitoring dashboard.
Displays rolling VaR/CVaR with breach markers, an animated correlation heatmap snapshot, stress test scenario comparison bars, and a risk contribution breakdown.
- Parameters:
returns (
DataFrame) – DataFrame of daily returns with one column per asset. If a single-column DataFrame or Series is passed, some panels (correlation, risk contribution) are simplified.var_confidence (
float, default:0.95) – Confidence level for VaR/CVaR (default 0.95).rolling_window (
int, default:63) – Window in trading days for rolling risk metrics (default 63).stress_scenarios (
dict[str,float] |None, default:None) – Optional dict mapping scenario names to portfolio-level return shocks for bar comparison. Example:{"2008 Crisis": -0.38, "COVID Crash": -0.34}.title (
str, default:'Risk Monitoring Dashboard') – Dashboard title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=504) >>> df = pd.DataFrame(np.random.normal(0.0003, 0.015, (504, 4)), ... index=dates, columns=["A", "B", "C", "D"]) >>> fig = risk_dashboard(df) >>> fig.show()
- technical_dashboard(ohlcv, indicators=None, title='Technical Analysis Dashboard')[source]¶
Create a multi-panel technical analysis chart with indicators.
Combines a candlestick chart with volume bars, overlay indicators (moving averages, Bollinger Bands), and subplot oscillators (RSI, MACD).
- Parameters:
ohlcv (
DataFrame) – DataFrame with columnsopen, high, low, closeand optionallyvolume. Column names are case-insensitive.indicators (
list[str] |None, default:None) –List of indicator names to display. Supported values:
Overlays (drawn on price chart): -
"sma20","sma50","sma200"– Simple moving averages -"ema12","ema20","ema26"– Exponential moving averages -"bb"– Bollinger Bands (20-period, 2 std)Oscillators (drawn in sub-panels): -
"rsi"– 14-period Relative Strength Index -"macd"– MACD (12, 26, 9)Defaults to
["sma20", "sma50", "bb", "rsi", "macd"]when None.title (
str, default:'Technical Analysis Dashboard') – Dashboard title.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Example
>>> import pandas as pd, numpy as np >>> dates = pd.bdate_range("2020-01-01", periods=252) >>> close = 100 * np.exp(np.cumsum(np.random.normal(0.0005, 0.02, 252))) >>> df = pd.DataFrame({ ... "open": close * 0.99, "high": close * 1.02, ... "low": close * 0.98, "close": close, ... "volume": np.random.randint(1e6, 1e7, 252), ... }, index=dates) >>> fig = technical_dashboard(df, indicators=["sma20", "bb", "rsi", "macd"]) >>> fig.show()
Interactive¶
Core Plotly interactive chart wrappers for financial analysis.
Cumulative returns, drawdowns, rolling statistics, distributions, correlation heatmaps, efficient frontier, and risk-return scatters — all as interactive Plotly figures with hover tooltips and rich formatting.
- plotly_returns(returns, benchmark=None, title=None)[source]¶
Interactive cumulative returns chart with hover tooltips.
Hover shows date, cumulative return, and current drawdown at each point.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_drawdown(returns)[source]¶
Interactive underwater chart with recovery periods highlighted.
Shades the drawdown area and annotates the deepest drawdown.
- Parameters:
returns (
Series) – Simple return series.- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_rolling_stats(returns, window=63)[source]¶
Rolling Sharpe, volatility, and beta in vertically-stacked subplots.
- plotly_distribution(returns, bins=50, overlay_normal=True)[source]¶
Interactive histogram with KDE and optional fitted normal overlay.
- plotly_correlation_heatmap(returns_df)[source]¶
Interactive correlation matrix heatmap with hierarchical clustering.
Reorders assets by hierarchical clustering so that correlated groups appear together. Hover shows the pair and correlation value.
- Parameters:
returns_df (
DataFrame) – DataFrame of asset returns (columns = assets).- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_efficient_frontier(expected_returns, cov_matrix, n_portfolios=5000)[source]¶
Interactive efficient frontier with hover showing portfolio weights.
Generates random portfolios and plots the risk-return cloud. The efficient frontier is highlighted. Hovering over points reveals the weight vector.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
- plotly_risk_return_scatter(returns_df)[source]¶
Risk-return scatter plot with asset labels and clickable points.
Annualizes both risk and return assuming 252 trading days.
- Parameters:
returns_df (
DataFrame) – DataFrame of asset returns (columns = assets).- Return type:
Figure- Returns:
A
plotly.graph_objects.Figure.
Portfolio¶
Portfolio-related visualizations.
Portfolio weight charts, efficient frontier, risk contributions, and correlation matrix heatmaps.
- plot_weights(weights, names=None, ax=None)[source]¶
Plot portfolio weights as a horizontal bar chart.
- Parameters:
weights (pd.Series | npt.NDArray[np.floating]) – Portfolio weight vector (pandas Series or numpy array).
names (list[str] | None, default:
None) – Asset names. If weights is a Series its index is used by default; otherwise sequential integers are used.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_efficient_frontier(returns_range, vol_range, sharpe_range=None, optimal_point=None, ax=None)[source]¶
Plot the efficient frontier as a scatter/line plot.
- Parameters:
returns_range (npt.NDArray[np.floating]) – Array of expected returns for each portfolio.
vol_range (npt.NDArray[np.floating]) – Array of volatilities for each portfolio.
sharpe_range (npt.NDArray[np.floating] | None, default:
None) – Optional array of Sharpe ratios used to color the scatter points.optimal_point (tuple[float, float] | None, default:
None) – Optional(volatility, return)tuple marking the optimal portfolio.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_risk_contribution(contributions, names=None, ax=None)[source]¶
Plot risk contributions as a stacked bar chart.
- Parameters:
contributions (pd.Series | npt.NDArray[np.floating]) – Risk contribution per asset (pandas Series or array).
names (list[str] | None, default:
None) – Asset names. If contributions is a Series its index is used by default.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_correlation_matrix(corr_matrix, labels=None, ax=None)[source]¶
Plot correlation matrix as an annotated heatmap.
- Parameters:
corr_matrix (pd.DataFrame | npt.NDArray[np.floating]) – Square correlation matrix (DataFrame or 2-D array).
labels (list[str] | None, default:
None) – Axis labels. If corr_matrix is a DataFrame its columns are used by default.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
Returns¶
Return-related visualizations.
Cumulative returns, drawdowns, return distributions, rolling returns, and monthly heatmaps.
- plot_cumulative_returns(returns, benchmark=None, title=None, ax=None)[source]¶
Plot cumulative return line chart with optional benchmark overlay.
- Parameters:
returns (pd.Series) – Simple return series (not cumulative).
benchmark (pd.Series | None, default:
None) – Optional benchmark return series for comparison.title (str | None, default:
None) – Plot title. Defaults to"Cumulative Returns".ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_drawdowns(returns, top_n=5, ax=None)[source]¶
Plot underwater chart showing drawdown periods.
- Parameters:
returns (pd.Series) – Simple return series.
top_n (int, default:
5) – Number of largest drawdowns to shade.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_return_distribution(returns, bins=50, fit_normal=True, ax=None)[source]¶
Plot histogram of returns with optional normal distribution fit overlay.
- Parameters:
returns (pd.Series) – Simple return series.
bins (int, default:
50) – Number of histogram bins.fit_normal (bool, default:
True) – If True, overlay a fitted normal PDF.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_rolling_returns(returns, window=252, ax=None)[source]¶
Plot rolling annualized returns.
- Parameters:
returns (pd.Series) – Simple return series.
window (int, default:
252) – Rolling window in periods (default 252 for 1 year of daily data).ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_monthly_heatmap(returns, ax=None)[source]¶
Plot a month-by-year heatmap of returns.
- Parameters:
returns (pd.Series) – Simple return series with a
DatetimeIndex.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
Risk¶
Risk visualizations.
VaR backtests, rolling volatility, and tail distribution plots.
- plot_var_backtest(returns, var_level, confidence=0.95, ax=None)[source]¶
Plot returns with a VaR threshold line, highlighting breaches.
- Parameters:
returns (pd.Series) – Simple return series.
var_level (pd.Series | float) – Value-at-Risk threshold. Pass a scalar for a constant threshold or a Series for a time-varying VaR.
confidence (float, default:
0.95) – VaR confidence level (used only for the title).ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_rolling_volatility(returns, window=21, annualize=True, ax=None)[source]¶
Plot rolling volatility line chart.
- Parameters:
returns (pd.Series) – Simple return series.
window (int, default:
21) – Rolling window in periods (default 21 for ~1 month daily).annualize (bool, default:
True) – Whether to annualize (multiply by sqrt(252)).ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_tail_distribution(returns, threshold_percentile=5, ax=None)[source]¶
Plot distribution tails, zoomed into the left tail.
- Parameters:
returns (pd.Series) – Simple return series.
threshold_percentile (float, default:
5) – Percentile below which tails are highlighted.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
Time Series¶
Time series visualizations.
Basic time series line plots, regime overlay, and seasonal decomposition panels.
- plot_series(data, title=None, ylabel=None, ax=None)[source]¶
Plot a basic time series line chart.
- Parameters:
data (pd.Series | pd.DataFrame) – Time series data. A Series produces a single line; a DataFrame plots one line per column.
title (str | None, default:
None) – Plot title.ylabel (str | None, default:
None) – Y-axis label.ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_regime_overlay(data, regimes, ax=None)[source]¶
Plot a time series with colored background regions for regimes.
- Parameters:
data (pd.Series) – Time series to plot as a line.
regimes (pd.Series) – Integer or categorical series of the same index indicating the regime at each point.
ax (matplotlib.axes.Axes | None, default:
None) – Matplotlib axes to plot on. A new figure is created when None.
- Return type:
matplotlib.axes.Axes
- Returns:
The matplotlib Axes containing the plot.
- plot_decomposition(trend, seasonal, residual, ax=None)[source]¶
Plot a 3-panel decomposition (trend, seasonal, residual).
- Parameters:
trend (pd.Series) – Trend component series.
seasonal (pd.Series) – Seasonal component series.
residual (pd.Series) – Residual component series.
ax (matplotlib.axes.Axes | None, default:
None) – Ignored. A new 3-panel figure is always created.
- Return type:
matplotlib.figure.Figure
- Returns:
The matplotlib Figure containing the three-panel plot.
Advanced¶
Advanced and unconventional Plotly financial visualizations.
Regime overlays, 3-D volatility surfaces, animated yield curves, copula scatters, network graphs, Sankey rebalancing flows, treemaps, and radar charts — the wacky side of quant viz.
- plotly_regime_overlay(prices, regime_labels)[source]¶
Price chart with colored background bands for market regimes.
- plotly_vol_surface(strikes, expiries, implied_vols)[source]¶
3-D implied volatility surface.
- Parameters:
strikes (
ndarray[tuple[Any,...],dtype[floating]]) – 1-D array of strike prices.expiries (
ndarray[tuple[Any,...],dtype[floating]]) – 1-D array of expiries (e.g. days to expiry or years).implied_vols (
ndarray[tuple[Any,...],dtype[floating]]) – 2-D array of shape(len(expiries), len(strikes))containing implied volatilities.
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith a 3-D surface.
- plotly_term_structure(maturities, yields, dates=None)[source]¶
Animated yield curve through time.
Each row of yields is a snapshot of the yield curve at one date. The animation steps through dates.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith animation frames.
- plotly_copula_scatter(u, v, copula_type='empirical')[source]¶
Copula scatter plot with marginal histograms.
- Parameters:
- Return type:
Figure- Returns:
A
plotly.graph_objects.Figurewith marginal histograms.
- plotly_network_graph(correlation_matrix, threshold=0.5)[source]¶
Asset correlation network graph.
Draws edges between assets whose absolute correlation exceeds threshold. Node size is proportional to the number of edges.
- plotly_sankey_flow(sectors, allocations_before, allocations_after)[source]¶
Sankey diagram showing portfolio rebalancing flows.
Left side shows before weights, right side shows after weights. Flows connect each sector’s allocation change.
- plotly_treemap(weights, sectors, returns)[source]¶
Portfolio treemap with tiles sized by weight and colored by return.
Themes¶
Consistent theming for wraquant visualizations.
Provides a clean, professional dark-on-white style and a named color palette used across all plotting functions.