ranaroussi/quantstats: Portfolio Analytics with Monte Carlo Simulations
Building a trading strategy is only half the battle. The harder part—especially for quants and portfolio managers—is understanding whether that performance is robust, how much risk you're actually taking, and what happens when markets turn against you. Most Python↗ Bright Coding Blog libraries give you basic returns calculations. Few give you production-ready tear sheets, rolling risk metrics, and built-in Monte Carlo simulations without forcing you into a heavy framework.
ranaroussi/quantstats fills that gap. With 7,444 GitHub stars and an active maintenance record (last commit June 19, 2026), it's a focused Python library for portfolio profiling that extends pandas with quantitative metrics, visualization tools, and probabilistic risk analysis. This article walks through what it does, how it works, and where it fits in your analytics stack.
What is ranaroussi/quantstats?
ranaroussi/quantstats is an open-source Python library maintained by Ran Aroussi, also known for the widely-used yfinance package. Licensed under Apache 2.0 and requiring Python 3.10+, the library is purpose-built for one thing: helping quantitative developers and portfolio managers understand performance through deep analytics and risk metrics.
The repository's structure reflects this focus. Rather than sprawling into unrelated domains, quantstats organizes functionality into three tightly-scoped modules: quantstats.stats for calculations, quantstats.plots for visualization, and quantstats.reports for generating comprehensive tear sheets. This modular design matters because it lets you pull in only what you need—compute a quick Sharpe ratio without importing plotting dependencies, or generate a full HTML report with a single call.
The library's relevance comes from its position in the Python quant ecosystem. pandas and numpy handle data manipulation; scipy provides statistical foundations; but quantstats bridges the gap between raw returns data and actionable portfolio intelligence. It does this by extending pandas DataFrames and Series with quant-specific methods via qs.extend_pandas(), letting you call .sharpe() directly on a returns series rather than wrangling function signatures.
With 1,215 forks indicating active community engagement and PyPI distribution for straightforward installation, quantstats sits in the practical middle ground—more capable than rolling your own metrics, lighter than institutional platforms like Bloomberg's BQuant or Quantopian's former stack.
Key Features
Extended pandas functionality. The qs.extend_pandas() method patches quant-specific methods directly onto pandas objects. This isn't monkey-patching for its own sake—it eliminates boilerplate. After extension, a returns Series gains methods like .sharpe(), .sortino(), .max_drawdown(), and .monthly_returns() without explicit imports.
Comprehensive metric coverage. The quantstats.stats module exposes over 40 calculation functions, from standard measures (Sharpe ratio, volatility, CAGR) to specialized risk metrics (conditional value-at-risk, ulcer index, tail ratio, gain-to-pain ratio). The README explicitly lists these, making the API surface transparent.
Visualization suite. quantstats.plots provides 18 plotting functions including snapshot overviews, drawdown analysis, rolling statistics (beta, Sharpe, Sortino, volatility), distribution histograms, and monthly return heatmaps. The snapshot plot combines equity curve, drawdown, and rolling metrics in a single figure—useful for quick strategy health checks.
Report generation. The quantstats.reports module generates seven distinct tear sheet types, from basic metrics-only outputs to full HTML reports with embedded plots. The HTML output is self-contained and suitable for sharing with stakeholders who don't run Python.
Monte Carlo simulations. A newer addition, the Monte Carlo module runs probabilistic risk analysis on return series. You can simulate thousands of paths, calculate bust and goal probabilities, and visualize outcome distributions. This moves beyond historical backtesting into forward-looking risk assessment.
Flexible data integration. The qs.utils.download_returns() function fetches data via yfinance (also maintained by Aroussi), but the core functions accept any pandas Series of returns—daily, weekly, or monthly. This decouples analytics from data sourcing.
Use Cases
Algorithmic strategy validation. Systematic traders running daily-rebalanced strategies need period-based metrics that match their execution frequency. quantstats' return-series approach aligns naturally: Sharpe ratios, win rates, and consecutive loss counts all operate on the same daily intervals as the strategy itself. The Monte Carlo simulation adds stress-testing—simulating whether a strategy that performed well historically has acceptable risk of catastrophic drawdown.
Portfolio manager reporting. The HTML tear sheet generation addresses a real workflow friction. Rather than stitching together matplotlib figures and metric tables in Jupyter, qs.reports.html(stock, "SPY") produces a single distributable file with benchmark comparison. For managers reporting to allocators or internal committees, this cuts preparation time significantly.
Risk committee dashboards. Rolling statistics plots—particularly rolling beta, Sharpe, and volatility—surface regime changes that static metrics hide. A strategy with a 1.5 historical Sharpe might show deteriorating rolling Sharpe over the last six months, flagging potential alpha decay before it appears in annual numbers.
Educational quant finance. The library's transparent API and comprehensive metric list make it suitable for teaching. Students can compare their manual Sharpe calculations against qs.stats.sharpe(), inspect drawdown periods against qs.stats.drawdown_details(), and build intuition for how different risk measures relate.
Benchmark-relative analysis. The explicit benchmark parameter in reporting functions supports relative performance analysis. Comparing a strategy against SPY (or any ticker or Series) is built-in, not an afterthought requiring manual alignment and subtraction.
Installation & Setup
quantstats supports both pip and conda installation. The pip installation command from the README:
$ pip install quantstats --upgrade --no-cache-dir
The --upgrade flag ensures you get the latest version; --no-cache-dir forces a fresh download rather than using a potentially stale local wheel. For conda users:
$ conda install -c ranaroussi quantstats
The channel specification -c ranaroussi points to the author's personal channel rather than conda-forge.
Core dependencies are substantial but standard in scientific Python:
- Python >= 3.10
- pandas >= 1.5.0
- numpy >= 1.24.0
- scipy >= 1.11.0
- matplotlib >= 3.7.0
- seaborn >= 0.13.0
- tabulate >= 0.9.0
- yfinance >= 0.2.40
Optional dependency for Plotly output:
- plotly >= 5.0.0 (required only for
plots.to_plotly())
The Python 3.10+ requirement is notable—this excludes older LTS distributions still shipping 3.8 or 3.9. If you're on Ubuntu 20.04 or similar, you'll need a newer Python build or container environment.
After installation, verify with:
import quantstats as qs
print(qs.__version__) # check import succeeds
Real Code Examples
The README provides three primary code patterns. Here's the first, demonstrating basic metric calculation with pandas extension:
%matplotlib inline
import quantstats as qs
# extend pandas functionality with metrics, etc.
qs.extend_pandas()
# fetch the daily returns for a stock
stock = qs.utils.download_returns('META')
# show sharpe ratio
qs.stats.sharpe(stock)
# or using extend_pandas() :)
stock.sharpe()
The %matplotlib inline magic is Jupyter-specific; omit in scripts. qs.extend_pandas() modifies pandas' namespace globally for the session—convenient, though be aware if you're running multiple libraries with conflicting extensions. The download_returns('META') call fetches Meta Platforms' daily returns through yfinance. Both qs.stats.sharpe(stock) and stock.sharpe() return 0.7604779884378278 in the README's example—identical results, different calling conventions.
For visualization, the snapshot plot:
qs.plots.snapshot(stock, title='Facebook Performance', show=True)
# can also be called via:
# stock.plot_snapshot(title='Facebook Performance', show=True)
This generates a composite figure with equity curve, underwater plot, and rolling metrics. The show=True parameter displays interactively; in batch scripts, you'd typically pass savefig={'filename': 'meta_snapshot.png'} instead. Note the README's known issue: seaborn-based heatmaps may display even when saving—plan your workflow accordingly if generating reports unattended.
For comprehensive reporting:
# benchmark can be a pandas Series or ticker
qs.reports.html(stock, "SPY")
This produces a self-contained HTML file with full metrics, plots, and benchmark comparison. The benchmark parameter accepts either a ticker string (fetched via yfinance) or a pre-aligned pandas Series of returns. The output matches the demonstration tearsheet linked in the README.
The Monte Carlo simulation, highlighted in the tweet angle:
mc = qs.stats.montecarlo(returns, sims=1000, bust=-0.20, goal=0.50)
print(f"Bust probability: {mc.bust_probability:.1%}")
print(f"Goal probability: {mc.goal_probability:.1%}")
mc.plot()
Here returns is your historical return series, sims=1000 specifies path count, bust=-0.20 defines the drawdown threshold for "failure," and goal=0.50 the return threshold for "success." The resulting object exposes probabilities and a plot() method for distribution visualization. This extends historical backtesting with forward-looking risk quantification—particularly valuable for strategies with limited live history.
Advanced Usage & Best Practices
Understand the period-based semantics. The README explicitly warns that quantstats operates on return series, not discrete trades. A single multi-day position appears as multiple daily returns. This is correct and standard for systematic strategies, but discretionary traders should interpret win rates and consecutive counts accordingly. Don't expect trade-level statistics without preprocessing.
Pre-align benchmarks before reporting. While qs.reports.html() accepts ticker strings, production workflows should fetch and align benchmark data explicitly. This prevents timezone and trading-day mismatches that automatic fetching might gloss over.
Cache yfinance downloads. The download_returns() helper is convenient but hits Yahoo Finance on every call. For reproducible research, save returned Series to Parquet and load from disk. [INTERNAL_LINK: data-pipeline-best-practices]
Handle the seaborn display quirk. The documented issue where monthly heatmaps display during save operations means unattended report generation may hang or produce unwanted output. Consider running under matplotlib.use('Agg') for headless environments, or patch around the specific heatmap functions.
Validate Monte Carlo assumptions. The simulation uses historical return resampling or parametric assumptions (check implementation details in source). Like all Monte Carlo methods, outputs are only as good as the input distribution—fat-tailed or regime-switching strategies may need custom simulation logic beyond the built-in defaults.
Comparison with Alternatives
| Tool | Scope | Key Difference | Trade-off |
|---|---|---|---|
| ranaroussi/quantstats | Portfolio metrics, visualization, reporting | Lightweight, pandas-native, HTML tear sheets | Fewer asset-class specifics than pyfolio; less institutional polish than commercial tools |
| pyfolio (Quantopian) | Full backtest analytics | Integrated with Zipline backtester | Project maintenance uncertain; heavier dependencies |
| empyrical (Quantopian) | Risk/return metrics only | Similar metric focus, lighter than pyfolio | No visualization or reporting; stale development |
| PerformanceAnalytics (R) | Comprehensive R metrics | Mature, extensive metric library | R ecosystem; steeper learning curve for Python shops |
quantstats occupies a practical niche: more complete than empyrical (which lacks plots and reports), more maintainable than pyfolio's uncertain status, and more accessible than R alternatives for Python-native teams. The Monte Carlo addition narrows the gap with commercial risk platforms for basic probabilistic analysis.
FAQ
What Python versions does quantstats support? Python 3.10 and above, per the requirements list.
Can I use quantstats without yfinance?
Yes. Core functions accept any pandas Series of returns; yfinance is only needed for qs.utils.download_returns().
Is quantstats free for commercial use? Yes, under Apache License 2.0. No usage restrictions beyond attribution.
How do I get help with a bug or feature request? Open an issue on GitHub. Issues marked "help wanted" are explicitly open for community contribution.
Does quantstats support intraday data? The README specifies daily, weekly, or monthly returns. Intraday would require resampling to these frequencies first.
What's the difference between basic and full reports? Basic reports show reduced metric sets and core plots; full reports include extended analytics like rolling Greeks and detailed drawdown analysis.
Why does my saved plot still display? Known seaborn issue with monthly heatmaps. The README acknowledges this; use headless matplotlib backends as a workaround.
Conclusion
ranaroussi/quantstats delivers focused, practical portfolio analytics for Python developers who need more than basic returns calculations but less than a full institutional platform. Its three-module architecture—stats, plots, reports—keeps the API coherent, while pandas extension reduces friction for exploratory analysis. The addition of Monte Carlo simulations extends its utility from historical description to forward-looking risk assessment.
This is a library best suited for: systematic strategy developers needing quick metric validation, portfolio managers producing regular stakeholder reports, and quantitative researchers building analysis pipelines where lightweight integration matters more than comprehensive asset-class coverage.
With active maintenance, straightforward installation, and transparent open-source licensing, quantstats merits evaluation if your current workflow involves stitching together matplotlib, manual metric calculations, and report templates. The repository and full documentation are available at https://github.com/ranaroussi/quantstats.