Portfolio Analysis in Python - Risk and Performance

By NeuralNine

Share:

Portfolio Analysis with Pyfolio: A Detailed Summary

Key Concepts:

  • Pyfolio: A Python library for performance and risk analysis of portfolios. (Note: The original Pyfolio is no longer maintained; Pyfolio-reloaded is the current fork.)
  • Y Finance: A Python package used to retrieve financial data from Yahoo Finance.
  • Returns: The percentage change in asset price over a given period, used to calculate portfolio performance.
  • Benchmark: A standard against which portfolio performance is measured (e.g., S&P 500).
  • Volatility: A measure of price fluctuations; higher volatility indicates greater risk.
  • Sharpe Ratio: Risk-adjusted return; measures excess return per unit of risk.
  • Max Drawdown: The largest peak-to-trough decline during a specific period.
  • Annual Return: The average yearly gain or loss over a specified time period.
  • Cumulative Return: The total return over the entire investment period.
  • In-Sample vs. Out-of-Sample: Backtesting period versus live trading period.
  • Portfolio Weights: The proportion of the total portfolio value invested in each asset.

1. Environment Setup & Package Installation

The video begins with setting up a Python environment for portfolio analysis. The presenter demonstrates using uv (a Python environment manager) but clarifies that pip or pip3 can be used equivalently. The following packages are installed:

  • Y Finance (yfinance): Used to download historical stock data (Open, High, Low, Close, Volume) from Yahoo Finance via its API.
  • Pyfolio-reloaded: A maintained fork of the original Pyfolio library, essential for performance and risk analysis. The original Pyfolio is no longer actively developed.
  • JupyterLab: An interactive Python notebook environment for code execution and visualization.

2. Data Acquisition & Preparation

The presenter uses yfinance to retrieve historical price data for Goldman Sachs (GS) and the S&P 500 (SPY) as a benchmark. The history() function is used with max as the time frame to obtain the complete available data. The data is stored in Pandas DataFrames.

  • Data Structure: The resulting DataFrame contains columns for Open, High, Low, Close prices, and Volume for each trading day.
  • Return Calculation: Portfolio returns are calculated using the pct_change() method on the 'Close' price column. This computes the percentage change in price from one day to the next.
  • Data Alignment: Since the historical data for GS and SPY may not cover the same date range, the align() function is used to ensure both datasets have matching dates. The join='inner' argument ensures only dates present in both datasets are included. dropna() is then used to remove any resulting NaN values.

3. Portfolio Construction & Return Aggregation

The presenter demonstrates how to analyze a portfolio consisting of three stocks: Nvidia (NVDA), Goldman Sachs (GS), and Microsoft (MSFT).

  • Portfolio Weights: A Pandas Series is created to define the proportion of the portfolio allocated to each asset (40% NVDA, 40% GS, 20% MSFT).
  • Combined Price Data: Historical price data for all three stocks is retrieved using yfinance and combined into a single DataFrame.
  • Weighted Returns: The percentage change in price for each stock is calculated, then multiplied by its corresponding portfolio weight. These weighted returns are then summed column-wise to calculate the overall portfolio return for each day.

4. Performance & Risk Analysis with Pyfolio

The core of the analysis involves using Pyfolio-reloaded to generate performance and risk metrics.

  • PF.create_returns_tear_sheet(): This function is used to generate a comprehensive tear sheet report.
  • live_start_date: A crucial parameter specifying the date when the strategy transitions from backtesting to live trading. This separates the in-sample (backtesting) and out-of-sample (live) periods.
  • Benchmark Returns: The returns of the S&P 500 (SPY) are provided as a benchmark for comparison.

5. Tear Sheet Report & Key Metrics

The tear sheet report generated by Pyfolio provides a wealth of information, including:

  • Cumulative Returns: The total return of the portfolio over the entire investment period.
  • Annual Return: The average yearly return.
  • Annual Volatility: A measure of price fluctuations.
  • Sharpe Ratio: Measures risk-adjusted return. A higher Sharpe ratio indicates better performance relative to risk.
  • Calmar Ratio: Measures return relative to the maximum drawdown.
  • Omega Ratio: Compares the probability of gains to the probability of losses.
  • Sortino Ratio: Similar to Sharpe, but only considers downside volatility.
  • Max Drawdown: The largest peak-to-trough decline in portfolio value.
  • Alpha & Beta: Measures of portfolio performance relative to the benchmark. Alpha represents excess return, while Beta measures sensitivity to market movements.
  • Drawdown Periods: Details of the worst drawdown periods, including peak date, lowest point, and recovery date.

6. Visualization & Interpretation

Pyfolio generates several visualizations to aid in analysis:

  • Cumulative Returns Chart: Shows the growth of the portfolio over time, with shaded areas representing expected paths.
  • Returns Distribution: Displays the distribution of daily returns.
  • Rolling Portfolio Beta: Shows how the portfolio's beta (sensitivity to market movements) changes over time.
  • Rolling Volatility: Displays the portfolio's volatility over time.
  • Drawdown Chart: Visualizes the drawdown periods.
  • Heatmaps & Box Plots: Provide insights into monthly and annual returns.

7. Important Considerations & Disclaimer

The presenter emphasizes:

  • Strategy Specificity: The return calculations must accurately reflect the portfolio's actual trading strategy. Simply accumulating individual asset returns is only valid for a buy-and-hold strategy.
  • Financial Expertise: The presenter is a tech professional, not a financial advisor, and the information provided should not be considered financial advice.

Synthesis/Conclusion:

This video provides a practical guide to performing portfolio analysis using Pyfolio-reloaded and Y Finance in Python. It demonstrates the entire process, from environment setup and data acquisition to performance and risk metric calculation and visualization. The presenter highlights the importance of understanding the underlying financial concepts and cautions against relying solely on the tool without proper financial expertise. The key takeaway is that Pyfolio-reloaded is a powerful tool for evaluating portfolio performance, but its results must be interpreted with a solid understanding of finance and investment strategies.

Chat with this Video

AI-Powered

Hi! I can answer questions about this video "Portfolio Analysis in Python - Risk and Performance". What would you like to know?

Chat is based on the transcript of this video and may not be 100% accurate.

Related Videos

Ready to summarize another video?

Summarize YouTube Video