### Install QuantStats Source: https://context7.com/ranaroussi/quantstats/llms.txt Use pip to install the library. ```bash pip install quantstats ``` -------------------------------- ### Install QuantStats Source: https://github.com/ranaroussi/quantstats/blob/main/README.md Installation commands for pip and conda environments. ```bash $ pip install quantstats --upgrade --no-cache-dir ``` ```bash $ conda install -c ranaroussi quantstats ``` -------------------------------- ### Get Method Help Source: https://github.com/ranaroussi/quantstats/blob/main/README.md Displays documentation and parameter information for a specific QuantStats method. ```python help(qs.stats.conditional_value_at_risk) ``` -------------------------------- ### Run Monte Carlo Simulation Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Initialize a simulation with historical returns and view terminal value statistics. ```python 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) ``` ```python { 'min': -0.15, 'max': 0.85, 'mean': 0.32, 'median': 0.31, 'std': 0.18, 'percentile_5': 0.05, 'percentile_95': 0.62 } ``` -------------------------------- ### Run Monte Carlo Simulation Source: https://context7.com/ranaroussi/quantstats/llms.txt Assess probabilistic risk by shuffling historical returns. Requires a returns series and defined thresholds for bust and goal outcomes. ```python import quantstats as qs returns = qs.utils.download_returns("SPY") # Run Monte Carlo simulation mc = qs.stats.montecarlo( returns, sims=1000, # Number of simulations bust=-0.2, # Bust threshold (-20% drawdown) goal=0.5, # Goal threshold (+50% return) seed=42 # For reproducibility ) # Access simulation results print(f"Terminal Value Statistics:") print(f" Mean: {mc.stats['mean']:.2%}") print(f" Median: {mc.stats['median']:.2%}") print(f" Std Dev: {mc.stats['std']:.2%}") print(f" Min: {mc.stats['min']:.2%}") print(f" Max: {mc.stats['max']:.2%}") print(f"\nMax Drawdown Statistics:") print(f" Mean: {mc.maxdd['mean']:.2%}") print(f" 5th Percentile: {mc.maxdd['percentile_5']:.2%}") print(f"\nProbabilities:") print(f" Bust Probability: {mc.bust_probability:.1%}") print(f" Goal Probability: {mc.goal_probability:.1%}") # Plot simulation results mc.plot() # Or plot separately qs.plots.montecarlo(mc, title="SPY Monte Carlo") qs.plots.montecarlo_distribution(mc, bins=50) # Monte Carlo specific metrics sharpe_dist = qs.stats.montecarlo_sharpe(returns, sims=1000, rf=0.02) print(f"\nSharpe Distribution: {sharpe_dist['mean']:.2f} +/- {sharpe_dist['std']:.2f}") cagr_dist = qs.stats.montecarlo_cagr(returns, sims=1000) print(f"CAGR Distribution: {cagr_dist['mean']:.2%} (5th: {cagr_dist['percentile_5']:.2%}, 95th: {cagr_dist['percentile_95']:.2%})") ``` -------------------------------- ### Calculate Win Rate and Payoff Ratio Source: https://context7.com/ranaroussi/quantstats/llms.txt Analyze the percentage of profitable periods and the average win/loss magnitudes using QuantStats. ```python import quantstats as qs returns = qs.utils.download_returns("JPM") # Win rate (percentage of positive returns) win = qs.stats.win_rate(returns) print(f"Daily Win Rate: {win:.2%}") # Monthly win rate monthly_win = qs.stats.win_rate(returns, aggregate="ME", compounded=True) print(f"Monthly Win Rate: {monthly_win:.2%}") # Payoff ratio (avg win / avg loss) payoff = qs.stats.payoff_ratio(returns) print(f"Payoff Ratio: {payoff:.2f}") # Profit factor (total wins / total losses) profit_factor = qs.stats.profit_factor(returns) print(f"Profit Factor: {profit_factor:.2f}") # Average win and loss avg_win = qs.stats.avg_win(returns) avg_loss = qs.stats.avg_loss(returns) print(f"Average Win: {avg_win:.2%}") print(f"Average Loss: {avg_loss:.2%}") ``` -------------------------------- ### Generate Performance Metrics Table Source: https://context7.com/ranaroussi/quantstats/llms.txt Generate a comprehensive table of all performance metrics using QuantStats. ```python import quantstats as qs returns = qs.utils.download_returns("BRK-B") benchmark = qs.utils.download_returns("SPY") # The following line would generate the table, but is not provided in the source. ``` -------------------------------- ### Calculate Value-at-Risk (VaR) Source: https://context7.com/ranaroussi/quantstats/llms.txt Estimate potential losses using VaR and CVaR metrics. ```python import quantstats as qs returns = qs.utils.download_returns("NVDA") ``` -------------------------------- ### Run Monte Carlo Simulations in Python Source: https://github.com/ranaroussi/quantstats/blob/main/README.md Perform probabilistic risk analysis using Monte Carlo simulations. Requires returns data, number of simulations, bust threshold, and goal threshold. The results include bust and goal probabilities and can be visualized. ```python 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() ``` -------------------------------- ### Create Custom Portfolio Index Source: https://context7.com/ranaroussi/quantstats/llms.txt Construct a weighted portfolio from multiple tickers with automatic rebalancing. Useful for backtesting custom asset allocations. ```python import quantstats as qs # Define portfolio weights portfolio_weights = { "AAPL": 0.25, "MSFT": 0.25, "GOOGL": 0.20, "AMZN": 0.15, "NVDA": 0.15 } # Create portfolio returns with monthly rebalancing portfolio = qs.utils.make_index( portfolio_weights, rebalance="1ME", # Monthly rebalancing period="5y", # 5 years of data match_dates=True ) # Analyze portfolio print(f"Portfolio Sharpe: {qs.stats.sharpe(portfolio):.2f}") print(f"Portfolio CAGR: {qs.stats.cagr(portfolio):.2%}") print(f"Portfolio Max DD: {qs.stats.max_drawdown(portfolio):.2%}") # Compare to benchmark qs.reports.html(portfolio, benchmark="SPY", title="Tech Portfolio", output="portfolio_report.html") ``` -------------------------------- ### List Available Statistical Methods Source: https://github.com/ranaroussi/quantstats/blob/main/README.md Retrieves a list of all public methods available in the qs.stats module. ```python [f for f in dir(qs.stats) if f[0] != '_'] ``` -------------------------------- ### Generate Monthly Returns Heatmap Source: https://context7.com/ranaroussi/quantstats/llms.txt Visualize returns by month and year, or calculate them as a DataFrame. ```python import quantstats as qs returns = qs.utils.download_returns("DIS") # Generate monthly returns heatmap qs.plots.monthly_heatmap( returns, figsize=(10, 6), compounded=True, eoy=True, # Include end-of-year column savefig="monthly_heatmap.png", show=True ) # Get monthly returns as DataFrame monthly_returns = qs.stats.monthly_returns(returns, eoy=True, compounded=True) print(monthly_returns) # Active returns vs benchmark benchmark = qs.utils.download_returns("SPY") qs.plots.monthly_heatmap( returns, benchmark=benchmark, active=True, # Show returns - benchmark figsize=(10, 6) ) ``` -------------------------------- ### Generate a basic performance report Source: https://context7.com/ranaroussi/quantstats/llms.txt Produces a concise report containing only essential performance metrics. ```python qs.reports.basic( returns, benchmark=benchmark, rf=0.02 ) ``` -------------------------------- ### Calculate Metric Distributions Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Compute distributions for Sharpe ratio, drawdown, and CAGR across simulations. ```python # Sharpe ratio distribution sharpe_dist = qs.stats.montecarlo_sharpe(returns, sims=1000) print(f"Sharpe range: {sharpe_dist['percentile_5']:.2f} to {sharpe_dist['percentile_95']:.2f}") # Max drawdown distribution dd_dist = qs.stats.montecarlo_drawdown(returns, sims=1000) print(f"Drawdown range: {dd_dist['percentile_5']:.1%} to {dd_dist['percentile_95']:.1%}") # CAGR distribution cagr_dist = qs.stats.montecarlo_cagr(returns, sims=1000) print(f"CAGR range: {cagr_dist['percentile_5']:.1%} to {cagr_dist['percentile_95']:.1%}") ``` -------------------------------- ### Generate Performance Metrics Source: https://context7.com/ranaroussi/quantstats/llms.txt Display a full metrics table or retrieve it as a pandas DataFrame for programmatic use. ```python qs.reports.metrics( returns, benchmark=benchmark, rf=0.02, mode="full", # "basic" or "full" periods_per_year=252, display=True # Print to console ) ``` ```python metrics_df = qs.reports.metrics( returns, benchmark=benchmark, rf=0.02, mode="full", display=False # Return DataFrame instead ) print(metrics_df.head(20)) ``` -------------------------------- ### Calculate Alpha and Beta (Greeks) Source: https://context7.com/ranaroussi/quantstats/llms.txt Calculate portfolio alpha, beta, R-squared, information ratio, and Treynor ratio relative to a benchmark. ```python import quantstats as qs returns = qs.utils.download_returns("AAPL") benchmark = qs.utils.download_returns("SPY") # Calculate greeks (alpha and beta) greeks = qs.stats.greeks(returns, benchmark, periods=252) print(f"Alpha: {greeks['alpha']:.2%}") print(f"Beta: {greeks['beta']:.2f}") # R-squared (coefficient of determination) r2 = qs.stats.r_squared(returns, benchmark) print(f"R-squared: {r2:.2%}") # Information ratio info_ratio = qs.stats.information_ratio(returns, benchmark) print(f"Information Ratio: {info_ratio:.2f}") # Treynor ratio (excess return / beta) treynor = qs.stats.treynor_ratio(returns, benchmark, periods=252, rf=0.02) print(f"Treynor Ratio: {treynor:.2%}") # Rolling greeks rolling_greeks = qs.stats.rolling_greeks(returns, benchmark, periods=252) print(f"Rolling Beta (latest): {rolling_greeks['beta'].iloc[-1]:.2f}") ``` -------------------------------- ### Calculate Value-at-Risk (VaR) and Conditional VaR Source: https://context7.com/ranaroussi/quantstats/llms.txt Calculate daily Value-at-Risk (VaR) at different confidence levels and Conditional VaR (Expected Shortfall). ```python var_95 = qs.stats.var(returns, confidence=0.95) print(f"95% Daily VaR: {var_95:.2%}") var_99 = qs.stats.var(returns, confidence=0.99) print(f"99% Daily VaR: {var_99:.2%}") cvar_95 = qs.stats.cvar(returns, confidence=0.95) print(f"95% CVaR: {cvar_95:.2%}") es = qs.stats.expected_shortfall(returns, confidence=0.95) print(f"Expected Shortfall: {es:.2%}") ``` -------------------------------- ### Generate an HTML performance report Source: https://context7.com/ranaroussi/quantstats/llms.txt Creates an HTML file containing the performance report, which can be saved to disk or opened directly in a browser. ```python qs.reports.html( returns, benchmark=benchmark, rf=0.02, title="P&G Performance Analysis", output="pg_report.html", # None to open in browser figfmt="svg", # "svg", "png", or "jpg" compounded=True, periods_per_year=252, match_dates=True ) ``` -------------------------------- ### Plot Return Distributions Source: https://context7.com/ranaroussi/quantstats/llms.txt Visualize return distributions using histograms, density curves, or daily return plots. ```python import quantstats as qs returns = qs.utils.download_returns("WMT") benchmark = qs.utils.download_returns("XRT") # Monthly returns histogram qs.plots.histogram( returns, benchmark=benchmark, resample="ME", # "W" weekly, "ME" monthly, "QE" quarterly, "YE" yearly figsize=(10, 5), compounded=True ) # Distribution plot with density curve qs.plots.distribution( returns, figsize=(10, 6), title="WMT Return Distribution" ) # Daily returns plot qs.plots.daily_returns( returns, benchmark=benchmark, active=False, # Set True for active returns figsize=(10, 4) ) ``` -------------------------------- ### Generate HTML Tearsheet Report Source: https://context7.com/ranaroussi/quantstats/llms.txt Create comprehensive performance reports comparing strategy returns against a benchmark. ```python import quantstats as qs # Download returns for a stock returns = qs.utils.download_returns("META") # Generate HTML tearsheet comparing to S&P 500 qs.reports.html(returns, benchmark="SPY", title="META Performance", output="report.html") # Generate with custom parameters qs.reports.html( returns, benchmark="SPY", rf=0.02, # 2% risk-free rate periods_per_year=252, # Trading days per year compounded=True, # Use compound returns title="META vs S&P 500", output="meta_report.html" ) ``` -------------------------------- ### Calculate Omega Ratio and Gain-to-Pain Ratio Source: https://context7.com/ranaroussi/quantstats/llms.txt Calculate the Omega ratio and Gain-to-Pain ratio, which measure risk-adjusted returns relative to a threshold. ```python import quantstats as qs returns = qs.utils.download_returns("V") # Omega ratio with default threshold (0) omega = qs.stats.omega(returns, rf=0.0, required_return=0.0, periods=252) print(f"Omega Ratio: {omega:.2f}") # Omega with required return threshold omega_5pct = qs.stats.omega(returns, required_return=0.05, periods=252) print(f"Omega (5% threshold): {omega_5pct:.2f}") # Gain-to-Pain ratio (total gains / total losses) gpr = qs.stats.gain_to_pain_ratio(returns) print(f"Gain-to-Pain Ratio: {gpr:.2f}") # Monthly Gain-to-Pain ratio monthly_gpr = qs.stats.gain_to_pain_ratio(returns, resolution="ME") print(f"Monthly Gain-to-Pain: {monthly_gpr:.2f}") ``` -------------------------------- ### Calculate Bust and Goal Probabilities Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Define drawdown thresholds and return goals to calculate the probability of specific outcomes. ```python # 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%}") ``` ```python Probability of bust: 23.4% Probability of reaching goal: 67.8% ``` -------------------------------- ### Visualize Stock Performance Snapshot Source: https://github.com/ranaroussi/quantstats/blob/main/README.md Generates a snapshot visualization of a stock's performance. This can be called directly using quantstats.plots or via the extended pandas Series method. ```python qs.plots.snapshot(stock, title='Facebook Performance', show=True) # can also be called via: # stock.plot_snapshot(title='Facebook Performance', show=True) ``` -------------------------------- ### Visualize Simulation Results Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Generate plots for simulation paths or terminal value distributions. ```python qs.plots.montecarlo(returns, sims=500, seed=42) # or from an existing result mc.plot() ``` ```python qs.plots.montecarlo_distribution(returns, sims=500, seed=42) ``` -------------------------------- ### Generate a full performance report Source: https://context7.com/ranaroussi/quantstats/llms.txt Produces a comprehensive report including all metrics and plots for console or notebook environments. ```python qs.reports.full( returns, benchmark=benchmark, rf=0.02, periods_per_year=252, figsize=(10, 6), match_dates=True ) ``` -------------------------------- ### Extend Pandas with QuantStats for Financial Analysis Source: https://github.com/ranaroussi/quantstats/blob/main/README.md This snippet demonstrates how to extend pandas functionality with QuantStats for financial analysis. It includes fetching stock returns and calculating the Sharpe ratio using both the quantstats library directly and the extended pandas Series method. ```python %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() ``` -------------------------------- ### List Available Plotting Methods Source: https://github.com/ranaroussi/quantstats/blob/main/README.md Retrieves a list of all public methods available in the qs.plots module. ```python [f for f in dir(qs.plots) if f[0] != '_'] ``` -------------------------------- ### Utility Functions for Data Preparation Source: https://context7.com/ranaroussi/quantstats/llms.txt Helper functions for transforming price data, calculating excess returns, and aggregating time-series data. ```python import quantstats as qs # Download returns data returns = qs.utils.download_returns("INTC", period="5y") # Convert prices to returns prices = qs.utils.to_prices(returns, base=100000) print(f"Final Portfolio Value: ${prices.iloc[-1]:,.2f}") # Convert to log returns log_returns = qs.utils.to_log_returns(returns) # Calculate excess returns excess_returns = qs.utils.to_excess_returns(returns, rf=0.02, nperiods=252) # Rebase prices to start at 100 rebased = qs.utils.rebase(prices, base=100) # Aggregate returns by period monthly = qs.utils.aggregate_returns(returns, "ME", compounded=True) yearly = qs.utils.aggregate_returns(returns, "YE", compounded=True) # Exponential weighted standard deviation exp_vol = qs.utils.exponential_stdev(returns, window=30) # Make portfolio with starting balance portfolio_value = qs.utils.make_portfolio(returns, start_balance=100000, mode="comp") print(f"Final Value: ${portfolio_value.iloc[-1]:,.2f}") ``` -------------------------------- ### Generate Snapshot Plot Source: https://context7.com/ranaroussi/quantstats/llms.txt Create a multi-panel summary plot showing cumulative returns, drawdowns, and daily returns. ```python import quantstats as qs returns = qs.utils.download_returns("NFLX") # Generate snapshot plot qs.plots.snapshot( returns, title="NFLX Performance Summary", figsize=(10, 8), mode="comp", # "comp" for compound, "sum" for simple log_scale=False, savefig="snapshot.png", show=True ) # With grayscale colors qs.plots.snapshot( returns, grayscale=True, title="NFLX Performance (Grayscale)" ) ``` -------------------------------- ### Plot Yearly Returns Source: https://context7.com/ranaroussi/quantstats/llms.txt Compare year-over-year performance using a bar chart. ```python import quantstats as qs returns = qs.utils.download_returns("HD") benchmark = qs.utils.download_returns("SPY") # Yearly returns bar chart qs.plots.yearly_returns( returns, benchmark=benchmark, figsize=(10, 5), compounded=True, savefig="yearly_returns.png" ) ``` -------------------------------- ### Calculate Sharpe Ratio Source: https://context7.com/ranaroussi/quantstats/llms.txt Measure risk-adjusted returns using standard, smart, and rolling Sharpe ratio calculations. ```python import quantstats as qs import pandas as pd # Download or load your returns returns = qs.utils.download_returns("AAPL") # Calculate Sharpe ratio with default parameters (annualized) sharpe = qs.stats.sharpe(returns) print(f"Annualized Sharpe Ratio: {sharpe:.2f}") # Calculate with risk-free rate sharpe_rf = qs.stats.sharpe(returns, rf=0.02, periods=252) print(f"Sharpe Ratio (2% RF): {sharpe_rf:.2f}") # Smart Sharpe with autocorrelation penalty smart_sharpe = qs.stats.smart_sharpe(returns, rf=0.02, periods=252) print(f"Smart Sharpe Ratio: {smart_sharpe:.2f}") # Rolling Sharpe ratio over 6-month window rolling_sharpe = qs.stats.rolling_sharpe(returns, rolling_period=126, periods_per_year=252) print(f"Rolling Sharpe (latest): {rolling_sharpe.iloc[-1]:.2f}") ``` -------------------------------- ### Calculate Sortino Ratio Source: https://context7.com/ranaroussi/quantstats/llms.txt Evaluate risk-adjusted returns focusing on downside deviation. ```python import quantstats as qs returns = qs.utils.download_returns("GOOGL") # Standard Sortino ratio sortino = qs.stats.sortino(returns, rf=0.02, periods=252) print(f"Sortino Ratio: {sortino:.2f}") # Smart Sortino with autocorrelation penalty smart_sortino = qs.stats.smart_sortino(returns, rf=0.02, periods=252) print(f"Smart Sortino: {smart_sortino:.2f}") # Adjusted Sortino (divided by sqrt(2) for Sharpe comparison) adjusted_sortino = qs.stats.adjusted_sortino(returns, rf=0.02, periods=252) print(f"Adjusted Sortino: {adjusted_sortino:.2f}") # Rolling Sortino ratio rolling_sortino = qs.stats.rolling_sortino(returns, rolling_period=126, periods_per_year=252) print(f"Rolling Sortino (latest): {rolling_sortino.iloc[-1]:.2f}") ``` -------------------------------- ### MonteCarloResult Methods Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Methods available on the MonteCarloResult object. ```APIDOC ## MonteCarloResult Methods ### Description Methods available on the MonteCarloResult object. ### Methods - **percentile(p)** - Get p-th percentile path - **confidence_band(level)** - Get (lower, upper) confidence bounds - **plot(**kwargs) - Plot simulation paths ``` -------------------------------- ### Plot Cumulative Returns Source: https://context7.com/ranaroussi/quantstats/llms.txt Visualize cumulative performance over time with options for log-scaling and volatility matching. ```python import quantstats as qs returns = qs.utils.download_returns("ADBE") benchmark = qs.utils.download_returns("QQQ") # Basic cumulative returns plot qs.plots.returns( returns, benchmark=benchmark, figsize=(10, 6), compound=True, savefig="cumulative_returns.png" ) # Log-scale returns for better visualization of growth qs.plots.log_returns( returns, benchmark=benchmark, title="ADBE vs QQQ (Log Scale)" ) # Volatility-matched comparison qs.plots.returns( returns, benchmark=benchmark, match_volatility=True, title="ADBE vs QQQ (Volatility Matched)" ) ``` -------------------------------- ### Generate HTML Tearsheet Report Source: https://github.com/ranaroussi/quantstats/blob/main/README.md Creates a comprehensive HTML tearsheet report for a given stock's performance, optionally comparing it against a benchmark. The report includes various metrics and plots. ```python # benchmark can be a pandas Series or ticker qs.reports.html(stock, "SPY") ``` -------------------------------- ### Plot Rolling Statistics Source: https://context7.com/ranaroussi/quantstats/llms.txt Visualize rolling metrics such as Sharpe, Sortino, volatility, and beta over time. ```python import quantstats as qs returns = qs.utils.download_returns("AMD") benchmark = qs.utils.download_returns("SMH") # Rolling Sharpe ratio qs.plots.rolling_sharpe( returns, period=126, # 6-month window period_label="6-Months", rf=0.02, figsize=(10, 4) ) # Rolling Sortino ratio qs.plots.rolling_sortino( returns, period=126, rf=0.02 ) # Rolling volatility comparison qs.plots.rolling_volatility( returns, benchmark=benchmark, period=126, periods_per_year=252 ) # Rolling beta qs.plots.rolling_beta( returns, benchmark=benchmark, window1=126, # 6-month window2=252, # 12-month window1_label="6-Months", window2_label="12-Months" ) ``` -------------------------------- ### Analyze Max Drawdown Distribution Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Retrieve the distribution statistics for maximum drawdowns across all simulation paths. ```python print(mc.maxdd) ``` ```python { 'min': -0.45, # worst drawdown across all sims 'max': -0.05, # best (smallest) drawdown 'mean': -0.18, 'median': -0.16, 'std': 0.08, 'percentile_5': -0.35, 'percentile_95': -0.08 } ``` -------------------------------- ### Retrieve Confidence Bands and Percentiles Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Extract confidence intervals and specific percentile paths from the simulation results. ```python # 95% confidence band lower, upper = mc.confidence_band(0.95) # specific percentile path p10 = mc.percentile(10) # 10th percentile path p90 = mc.percentile(90) # 90th percentile path ``` -------------------------------- ### Full Report Generation Source: https://context7.com/ranaroussi/quantstats/llms.txt Generate comprehensive analysis reports. Note that the snippet provided is incomplete in the source. ```python import quantstats as qs returns = qs.utils.download_returns("PG") benchmark = qs.utils.download_returns("SPY") ``` -------------------------------- ### Access Raw Simulation Data Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Retrieve the underlying simulation data as a pandas DataFrame. ```python print(mc.data.head()) ``` ```python sim_0 sim_1 sim_2 sim_3 sim_4 ... 0 0.000000 0.017745 -0.002586 -0.005346 -0.042107 ... 1 0.002647 0.017795 -0.002398 0.004795 -0.034664 ... 2 0.003351 0.020711 0.002926 0.004868 -0.037902 ... 3 0.007572 0.029275 0.004323 0.012818 -0.044294 ... 4 0.010900 0.028764 0.009446 0.026309 -0.049399 ... ``` -------------------------------- ### Calculate Maximum Drawdown Source: https://context7.com/ranaroussi/quantstats/llms.txt Analyze portfolio declines using maximum drawdown and drawdown series details. ```python import quantstats as qs returns = qs.utils.download_returns("AMZN") # Maximum drawdown max_dd = qs.stats.max_drawdown(returns) print(f"Maximum Drawdown: {max_dd:.2%}") # Convert returns to drawdown series dd_series = qs.stats.to_drawdown_series(returns) print(f"Current Drawdown: {dd_series.iloc[-1]:.2%}") # Get detailed drawdown information dd_details = qs.stats.drawdown_details(dd_series) print("Worst 5 Drawdowns:") print(dd_details.sort_values("max drawdown").head(5)) ``` -------------------------------- ### Extend Pandas with QuantStats Methods Source: https://context7.com/ranaroussi/quantstats/llms.txt Inject QuantStats analytical methods directly into pandas DataFrames and Series. This enables calling metrics like .sharpe() or .max_drawdown() directly on data objects. ```python import quantstats as qs import pandas as pd # Extend pandas with QuantStats methods qs.extend_pandas() # Download returns returns = qs.utils.download_returns("COST") # Now use QuantStats methods directly on Series print(f"Sharpe: {returns.sharpe():.2f}") print(f"Sortino: {returns.sortino():.2f}") print(f"CAGR: {returns.cagr():.2%}") print(f"Max Drawdown: {returns.max_drawdown():.2%}") print(f"Volatility: {returns.volatility():.2%}") print(f"Win Rate: {returns.win_rate():.2%}") print(f"Value at Risk: {returns.var():.2%}") # Benchmark comparison benchmark = qs.utils.download_returns("SPY") print(f"Alpha: {returns.greeks(benchmark)['alpha']:.2%}") print(f"Beta: {returns.greeks(benchmark)['beta']:.2f}") # Time-based filtering mtd_returns = returns.mtd() # Month-to-date ytd_returns = returns.ytd() # Year-to-date qtd_returns = returns.qtd() # Quarter-to-date # Direct plotting returns.plot_snapshot() returns.plot_monthly_heatmap() returns.plot_drawdown() # Monte Carlo on pandas Series mc_result = returns.montecarlo(sims=500, bust=-0.15, goal=0.30) print(f"Goal Probability: {mc_result.goal_probability:.1%}") ``` -------------------------------- ### Calculate Volatility Source: https://context7.com/ranaroussi/quantstats/llms.txt Calculate annualized volatility, rolling volatility, and implied volatility using QuantStats. ```python import quantstats as qs returns = qs.utils.download_returns("TSLA") # Annualized volatility (default 252 trading days) vol = qs.stats.volatility(returns, periods=252) print(f"Annualized Volatility: {vol:.2%}") # Rolling volatility (6-month window) rolling_vol = qs.stats.rolling_volatility(returns, rolling_period=126, periods_per_year=252) print(f"Rolling Volatility (latest): {rolling_vol.iloc[-1]:.2%}") # Implied volatility using log returns impl_vol = qs.stats.implied_volatility(returns, periods=252) print(f"Implied Volatility (latest): {impl_vol.iloc[-1]:.2%}") ``` -------------------------------- ### Plot Drawdowns Source: https://context7.com/ranaroussi/quantstats/llms.txt Visualize drawdown periods using underwater charts or identify the worst drawdown periods. ```python import quantstats as qs returns = qs.utils.download_returns("CRM") # Underwater plot (continuous drawdown) qs.plots.drawdown( returns, figsize=(10, 4), title="CRM Underwater Plot", savefig="drawdown.png" ) # Worst 5 drawdown periods qs.plots.drawdowns_periods( returns, periods=5, # Number of worst periods to show figsize=(10, 5), title="Worst 5 Drawdown Periods" ) ``` -------------------------------- ### Calculate Calmar and Ulcer Ratios Source: https://context7.com/ranaroussi/quantstats/llms.txt Calculate drawdown-based risk measures including Calmar ratio, Ulcer Index, Ulcer Performance Index, Serenity Index, and Recovery Factor. ```python import quantstats as qs returns = qs.utils.download_returns("GS") # Calmar ratio (CAGR / Max Drawdown) calmar = qs.stats.calmar(returns, periods=252) print(f"Calmar Ratio: {calmar:.2f}") # Ulcer Index (measures depth and duration of drawdowns) ulcer_idx = qs.stats.ulcer_index(returns) print(f"Ulcer Index: {ulcer_idx:.4f}") # Ulcer Performance Index upi = qs.stats.ulcer_performance_index(returns, rf=0.02) print(f"Ulcer Performance Index: {upi:.2f}") # Serenity Index serenity = qs.stats.serenity_index(returns, rf=0.02) print(f"Serenity Index: {serenity:.4f}") # Recovery Factor (total returns / max drawdown) recovery = qs.stats.recovery_factor(returns) print(f"Recovery Factor: {recovery:.2f}") ``` -------------------------------- ### MonteCarloResult Properties Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Properties available on the MonteCarloResult object. ```APIDOC ## MonteCarloResult Properties ### Description Properties available on the MonteCarloResult object. ### Properties - **data** (DataFrame) - DataFrame with all simulation paths - **original** (Series) - Series with original cumulative returns - **stats** (Dict) - Dict with terminal value statistics - **maxdd** (Dict) - Dict with max drawdown statistics - **bust_probability** (Float) - Float (if bust threshold set) - **goal_probability** (Float) - Float (if goal threshold set) ``` -------------------------------- ### Calculate CAGR Source: https://context7.com/ranaroussi/quantstats/llms.txt Compute the geometric mean annual return with optional compounding and risk-free rate adjustments. ```python import quantstats as qs returns = qs.utils.download_returns("MSFT") # Calculate CAGR cagr = qs.stats.cagr(returns, periods=252) print(f"CAGR: {cagr:.2%}") # CAGR with risk-free rate adjustment cagr_rf = qs.stats.cagr(returns, rf=0.02, periods=252) print(f"CAGR (excess): {cagr_rf:.2%}") # Non-compounded total return total_return = qs.stats.cagr(returns, compounded=False, periods=252) print(f"Total Return: {total_return:.2%}") ``` -------------------------------- ### qs.stats.montecarlo Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Runs a Monte Carlo simulation on a series of daily returns to generate probabilistic outcomes. ```APIDOC ## qs.stats.montecarlo ### Description Runs a Monte Carlo simulation on historical returns by shuffling them to understand the range of possible outcomes for a strategy. ### Parameters - **returns** (pd.Series) - Required - Daily returns data. - **sims** (int) - Optional - Number of simulations to run (default: 1000). - **bust** (float) - Optional - Drawdown threshold for bust probability (e.g., -0.20). - **goal** (float) - Optional - Return threshold for goal probability (e.g., 0.50). - **seed** (int) - Optional - Random seed for reproducibility. ### Response - **MonteCarloResult** (object) - An object containing simulation statistics, probabilities, and raw path data. ``` -------------------------------- ### Extend Pandas for Monte Carlo Source: https://github.com/ranaroussi/quantstats/blob/main/docs/montecarlo.md Use the Monte Carlo methods directly on pandas Series objects after extending. ```python 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) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.