QuantStats

repository·main·Indexed 27 days ago

https://github.com/ranaroussi/quantstats

A Python library for portfolio profiling and analytics. QuantStats provides risk metrics, performance visualizations, and automated HTML report generation for quants and portfolio managers. It features a wide range of statistics (e.g., Sharpe ratio, Sortino ratio, CAGR), Monte Carlo simulations for probabilistic risk analysis, and the ability to extend pandas Series and DataFrame objects with financial analytics methods.

Tokens
14.2K
Snippets
61
Records
92
Agent score
92%

What's inside quantstats

  1. Use Monte Carlo with Pandas extension

    main

    By calling qs.extend_pandas(), you can attach Monte Carlo functionality directly to pandas Series objects.

    qs.extend_pandas()
    
    # run simulation directly on a returns Series
    mc = returns.montecarlo(sims=1000, bust=-0.15, goal=0.30)
    
    # plot directly
    returns.plot_montecarlo(sims=500)
  2. Quick Start with QuantStats

    main

    To use QuantStats, import the library and call qs.extend_pandas() to add performance metrics directly to pandas Series objects. You can then download returns using qs.utils.download_returns() and calculate metrics like the Sharpe ratio.

    %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 using the stats module
    qs.stats.sharpe(stock)
    
    # or using the extended pandas method
    stock.sharpe()
  3. Extend pandas with QuantStats methods

    main
    Call extend_pandas() to inject a wide range of financial analytics, utility, and plotting methods directly into pandas Series and DataFrame objects. Once extended, you can call methods like .sharpe(), .cagr(), or .plot_snapshot() directly on your pandas objects.
  4. Run Monte Carlo Simulations

    main

    QuantStats includes built-in Monte Carlo simulations for probabilistic risk analysis. Use qs.stats.montecarlo() to run simulations and analyze bust and goal probabilities.

    import quantstats as qs
    
    # returns is a pandas Series of daily returns
    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()
  5. Visualize Monte Carlo simulations

    main

    You can visualize simulation results using qs.plots or directly from a MonteCarloResult object.

    • Plot all paths: Use qs.plots.montecarlo(returns, sims=500) or mc.plot().
    • Plot terminal distribution: Use qs.plots.montecarlo_distribution(returns, sims=500) to see the distribution of final values.
    # Plot all simulation paths
    qs.plots.montecarlo(returns, sims=500, seed=42)
    # or from an existing result
    mc.plot()
    
    # Plot terminal value distribution
    qs.plots.montecarlo_distribution(returns, sims=500, seed=42)
  6. Visualize Stock Performance with Snapshots

    main

    Use qs.plots.snapshot() to create a comprehensive visual summary of stock performance. This can also be called directly on a pandas Series if qs.extend_pandas() has been used.

    import quantstats as qs
    
    # Using the plots module
    qs.plots.snapshot(stock, title='Facebook Performance', show=True)
    
    # Or using the extended pandas method
    stock.plot_snapshot(title='Facebook Performance', show=True)
  7. Analyze Max Drawdown and Confidence Bands

    main

    The MonteCarloResult object provides tools to analyze risk across paths:

    • Max Drawdown Distribution: Access mc.maxdd for a dictionary of statistics (min, max, mean, median, std, percentiles) regarding the maximum drawdown of each path.
    • Confidence Bands: Use mc.confidence_band(level) to get the lower and upper bounds for a given confidence level (e.g., 0.95).
    • Percentile Paths: Use mc.percentile(p) to retrieve a specific percentile path (e.g., mc.percentile(10) for the 10th percentile).
    # Max drawdown distribution
    print(mc.maxdd)
    
    # 95% confidence band
    lower, upper = mc.confidence_band(0.95)
    
    # specific percentile path
    p10 = mc.percentile(10)
  8. Run Monte Carlo simulations with `qs.stats.montecarlo`

    main

    Perform probabilistic risk analysis by shuffling historical returns to simulate thousands of possible outcomes. Use qs.stats.montecarlo to generate a MonteCarloResult object containing terminal statistics, drawdown distributions, and path data.

    import quantstats as qs
    
    # fetch daily returns
    returns = qs.utils.download_returns('SPY')
    
    # run Monte Carlo simulation with 1000 paths
    mc = qs.stats.montecarlo(returns, sims=1000, seed=42)
    
    # view terminal value statistics
    print(mc.stats)
  9. Calculate Bust and Goal probabilities

    main

    When running a simulation, you can specify bust (a drawdown threshold) and goal (a return threshold) to calculate the probability of hitting these specific levels during the simulated paths.

    # Set bust threshold at -20% drawdown, goal at +50% return
    mc = qs.stats.montecarlo(returns, sims=1000, bust=-0.20, goal=0.50, seed=42)
    
    print(f"Probability of bust: {mc.bust_probability:.1%}")
    print(f"Probability of reaching goal: {mc.goal_probability:.1%}")
  10. Get distributions for Sharpe, Drawdown, and CAGR

    main

    QuantStats provides helper functions to get the distribution of key performance metrics across all simulated paths.

    # Sharpe ratio distribution
    sharpe_dist = qs.stats.montecarlo_sharpe(returns, sims=1000)
    
    # Max drawdown distribution
    dd_dist = qs.stats.montecarlo_drawdown(returns, sims=1000)
    
    # CAGR distribution
    cagr_dist = qs.stats.montecarlo_cagr(returns, sims=1000)