avatarFS Ndzomga

Summary

The web content provides a comprehensive guide on using Python and the yfinance library to evaluate financial portfolios through various analyses, including performance benchmarking, portfolio diversification, risk assessment, technical analysis, and sector and industry performance analysis.

Abstract

The article on the undefined website offers an in-depth exploration of financial portfolio analysis using Python. It emphasizes the power of Python, particularly when combined with the yfinance library, for conducting financial analysis. The author outlines a series of analyses that can be performed, starting with performance benchmarking, which compares the performance of stocks or portfolios against benchmarks or indices. The article also covers portfolio diversification analysis, detailing how to calculate portfolio variance, standard deviation, and the correlation matrix of assets to understand the risk and diversification of a portfolio. Risk analysis is another key topic, with the article explaining how to calculate Value at Risk (VaR) and Conditional Value at Risk (CVaR) to assess the risk of a portfolio or stock. Additionally, the author provides insights into implementing and analyzing technical analysis indicators such as RSI, MACD, and Bollinger Bands to inform trading decisions. Lastly, the article touches on sector and industry analysis, suggesting methods for aggregating data by sector or industry to analyze overall performance and trends. Throughout the article, code snippets are provided to demonstrate how to perform these analyses, and the results are interpreted to give readers a clearer understanding of portfolio evaluation.

Opinions

  • The author believes that Python, with the yfinance library, is a robust toolkit for financial analysis.
  • It is suggested that benchmarking performance against indices like the S&P 500 Index is a common and effective practice.
  • The article implies that a well-diversified portfolio typically exhibits lower risk, as measured by variance and standard deviation.
  • The author posits that moderate correlations between portfolio assets are beneficial for diversification, but also suggests that including assets with lower or negative correlations can further reduce risk.
  • The calculation of VaR and CVaR is presented as crucial for understanding potential losses and managing the risk of financial portfolios.
  • The use of technical analysis indicators is advocated as a means to analyze stock prices and make informed trading decisions.
  • The author emphasizes the importance of sector and industry analysis in understanding market trends and performance, although they acknowledge that yfinance requires a predefined list of ticker symbols categorized by sectors for such analysis.

How To Evaluate Your Financial Portfolio Using Python

Photo by Kanchanara on Unsplash

Python, coupled with the yfinance library, offers a powerful toolkit for conducting financial analysis. Here's a list of financial analyses you can perform using Python and yfinance:

  1. Performance Benchmarking: Compare the performance of stocks or portfolios against benchmarks or indices to evaluate relative performance.
  2. Portfolio Diversification Analysis: Analyze the diversification of a portfolio by calculating portfolio variance, standard deviation, and the correlation matrix of the assets.
  3. Risk Analysis: Assess the risk of a portfolio or stock by calculating metrics like Value at Risk (VaR) and Conditional Value at Risk (CVaR).
  4. Technical Analysis Indicators: Implement and analyze technical indicators such as RSI (Relative Strength Index), MACD (Moving Average Convergence Divergence), Bollinger Bands, and others to make informed trading decisions.
  5. Sector and Industry Analysis: Aggregate data by sector or industry to analyze overall performance, trends, and to identify leading or lagging sectors.

In this article, I will provide code snippets to show you how to perform these analysis.

Performance Benchmarking

For an example of performance benchmarking, let’s compare the performance of a specific stock (e.g., Apple Inc. with the ticker symbol “AAPL”) against a benchmark index (e.g., the S&P 500 Index, with the ticker symbol “^GSPC”) over the past year. We’ll use Python and yfinance to fetch the historical data, calculate daily returns, and then compare the cumulative returns of both the stock and the index.

First, ensure you have yfinance installed. If not, you can install it using pip:

pip install yfinance

Here’s how you can perform the analysis:

This code does the following:

  • It imports necessary libraries: yfinance for data fetching, pandas for data manipulation, and matplotlib.pyplot for plotting.
  • It defines the ticker symbols for both the stock (AAPL) and the benchmark index (^GSPC).
  • It fetches historical closing prices for both the stock and the benchmark from the start of 2023 to the start of 2024.
  • It calculates daily returns and cumulative returns for both the stock and the benchmark.
  • Finally, it plots the cumulative returns over time, allowing for a visual comparison of their performance.

This example demonstrates how to benchmark the performance of Apple Inc. against the S&P 500 Index, which is a common practice to evaluate how well a stock is performing relative to the broader market.

Stock vs Benchmark Cumulative Returns

Portfolio Diversification Analysis

To demonstrate portfolio diversification analysis, we’ll consider a simple portfolio consisting of three stocks. We’ll analyze the diversification by calculating the portfolio variance, standard deviation, and the correlation matrix of the assets. For this example, let’s assume our portfolio consists of Apple Inc. (AAPL), Microsoft Corp. (MSFT), and Amazon.com Inc. (AMZN).

We’ll first fetch the historical data for these stocks using yfinance, then calculate the daily returns, and finally compute the portfolio metrics mentioned above.

Here’s the Python code to perform the portfolio diversification analysis:

This code performs the following steps:

  1. It defines the stock tickers for the portfolio.
  2. It fetches the adjusted close prices for these stocks over the specified period.
  3. It calculates the daily percentage returns for each stock.
  4. It specifies the investment weights for each stock in the portfolio.
  5. It calculates the daily returns for the portfolio based on these weights.
  6. It computes the annualized portfolio variance and standard deviation (volatility) using the daily returns covariance matrix, scaled by the number of trading days (usually 252 days).
  7. It calculates the correlation matrix of the daily returns to show how the returns of the stocks are related to each other.

These calculations provide insights into the portfolio’s risk characteristics and the degree of diversification. A well-diversified portfolio will typically have lower risk (standard deviation) and stocks that are not perfectly correlated with each other.

Results:

Portfolio Variance: 0.044045860368199276
Portfolio Standard Deviation (Volatility): 0.20987105652804838
Correlation Matrix of the Returns:
Ticker      AAPL      AMZN      MSFT
Ticker                              
AAPL    1.000000  0.441678  0.547988
AMZN    0.441678  1.000000  0.575928
MSFT    0.547988  0.575928  1.000000

The results of the portfolio diversification analysis can be interpreted as follows:

Portfolio Variance

The portfolio variance is 0.0440.044. This metric measures the dispersion of the portfolio returns from their mean. A higher variance indicates a higher level of risk, as it suggests greater volatility in the portfolio’s returns. In the context of portfolio management, variance is crucial for understanding the risk involved. The variance of 0.0440.044 signifies that the returns of this portfolio can deviate from the expected returns, but without a benchmark or comparison, it’s hard to categorize it as high or low risk directly.

Portfolio Standard Deviation (Volatility)

The portfolio’s standard deviation is 0.2100.210 (rounded from 0.209871056528048380.20987105652804838). This value is the square root of the variance and represents the volatility of the portfolio. Volatility is a direct measure of risk; the higher the volatility, the riskier the portfolio. A standard deviation of 0.2100.210 means that, on average, the portfolio’s returns are expected to deviate from the mean return by 21% in either direction. This provides a clearer picture of the risk level to investors; a 21% deviation can be significant depending on an investor’s risk tolerance.

Correlation Matrix of the Returns

The correlation matrix shows how the returns of the individual stocks in the portfolio are related to each other:

  • AAPL and AMZN have a correlation of 0.4420.442 (rounded from 0.4416780.441678), indicating a moderate positive correlation. This means that when Apple’s stock returns go up, Amazon’s returns tend to go up as well, but not perfectly.
  • AAPL and MSFT have a correlation of 0.5480.548 (rounded from 0.5479880.547988), which is also a moderate positive correlation. This suggests that the returns of Apple and Microsoft move in the same direction more strongly than Apple’s and Amazon’s.
  • AMZN and MSFT have a correlation of 0.5760.576 (rounded from 0.5759280.575928), indicating a slightly stronger positive correlation than the other pairs. This implies that Amazon and Microsoft’s stock returns are more closely related to each other.

A correlation of 1 would mean the stocks move perfectly in sync with each other, while a correlation of 0 indicates no relationship. Correlations less than 1 but greater than 0 suggest that the stocks do move in the same direction to some extent, but not perfectly. This is beneficial for diversification purposes, as it reduces the risk that all assets will perform poorly at the same time. However, the correlations here are moderate, indicating that while the portfolio is diversified, the diversification could be improved by including assets with lower or negative correlations to further reduce risk.

Overall Interpretation

The portfolio has a moderate level of risk, as indicated by a standard deviation of 0.2100.210. The stocks within the portfolio are moderately correlated, suggesting some level of diversification. However, the diversification could potentially be enhanced by including assets with lower correlations to each other. This would help in further spreading out the risk and potentially lowering the portfolio’s overall volatility. Investors should consider their risk tolerance, investment horizon, and financial goals when evaluating whether this portfolio aligns with their investment strategy.

Risk Analysis

For this example, we’ll demonstrate how to calculate the Value at Risk (VaR) and Conditional Value at Risk (CVaR), also known as Expected Shortfall, for a portfolio consisting of multiple stocks. We’ll use historical stock data fetched with yfinance. The VaR provides a measure of the maximum expected loss over a specified time period at a certain confidence level, while CVaR gives the expected loss exceeding the VaR.

Let’s consider a simple portfolio with two stocks for illustration: Apple Inc. (AAPL) and Microsoft Corp. (MSFT). We’ll calculate the 95% VaR and CVaR for this portfolio based on historical daily returns.

Here’s the Python code to perform the risk analysis:

Explanation:

  • Historical Data: The script fetches historical closing prices for AAPL and MSFT for the year 2022.
  • Daily Returns: It calculates the daily returns for each stock.
  • Portfolio Returns: It computes the daily returns of the portfolio based on the specified weights (50% AAPL, 50% MSFT).
  • Value at Risk (VaR): The 95% VaR is calculated by finding the 5th percentile of the historical daily returns distribution. This value represents the maximum expected loss with a 95% confidence level.
  • Conditional Value at Risk (CVaR): The CVaR at the 95% confidence level is calculated by taking the average of the returns that fall below the 95% VaR threshold. This metric provides an estimate of the expected loss on days when the VaR is exceeded.

This example gives a basic illustration of how to assess the risk of a portfolio using VaR and CVaR. These metrics are crucial for understanding potential losses in adverse market conditions and can help investors make informed decisions about risk management.

Results:

95% Value at Risk (VaR): -3.58%
95% Conditional Value at Risk (CVaR): -4.34%

The results from the risk analysis provide insights into the potential losses for the portfolio consisting of Apple Inc. (AAPL) and Microsoft Corp. (MSFT) stocks, based on historical data. Here’s how to interpret the provided metrics:

95% Value at Risk (VaR): -3.58%

The 95% VaR of -3.58% indicates that there is a 95% confidence level that the portfolio will not lose more than 3.58% of its value in a single day. In other words, there is a 5% chance that the portfolio’s daily loss could exceed 3.58%. This metric is used to estimate the maximum expected loss under normal market conditions over a specified time frame (in this case, one day).

95% Conditional Value at Risk (CVaR): -4.34%

The 95% CVaR of -4.34% goes a step further than VaR by estimating the average loss that will occur on the worst 5% of days. In practical terms, this means that if losses exceed the 3.58% threshold established by the VaR, the expected average loss on those days will be about 4.34%. CVaR provides a more comprehensive picture of the tail risk, capturing the severity of losses in the worst-case scenarios beyond the VaR cutoff.

Interpretation

Both VaR and CVaR are critical measures for understanding and managing the risk of financial portfolios. The VaR gives a threshold for expected maximum losses, offering a clear benchmark for risk tolerance. However, it doesn’t describe what happens beyond that threshold. That’s where CVaR becomes valuable, as it provides an estimate of the average loss in the worst-case scenarios, giving investors a sense of the potential severity of losses beyond the VaR limit.

In this context, the results suggest that while the portfolio is relatively well-positioned to withstand normal market fluctuations, there’s still a non-negligible risk of significant loss. Investors should consider these metrics in the context of their overall investment strategy and risk tolerance. For instance, a highly risk-averse investor might find a 3.58% potential daily loss unacceptable, while a more risk-tolerant investor might be comfortable with this level of risk given the potential for higher returns.

Furthermore, these risk metrics can inform risk management strategies, such as setting stop-loss orders at certain thresholds, diversifying the portfolio further to mitigate potential losses, or adjusting the portfolio’s composition to align with an investor’s risk tolerance.

Technical Analysis Indicators

For this example, we’ll implement three popular technical analysis indicators using Python: the Relative Strength Index (RSI), the Moving Average Convergence Divergence (MACD), and Bollinger Bands. These indicators are widely used to analyze stock prices and make informed trading decisions. We’ll use historical stock data for Apple Inc. (AAPL) as our example.

Explanation:

  • RSI (Relative Strength Index): This momentum indicator measures the speed and change of price movements. RSI values range from 0 to 100. Traditionally, an RSI above 70 indicates a stock is overbought, while an RSI below 30 indicates it’s oversold.
  • MACD (Moving Average Convergence Divergence): This trend-following momentum indicator shows the relationship between two moving averages of a stock’s price. The MACD is calculated by subtracting the 26-period Exponential Moving Average (EMA) from the 12-period EMA. The “Signal Line” is then a 9-period EMA of the MACD. A crossover of these two lines can signal potential buy or sell opportunities.
  • Bollinger Bands: This indicator consists of a middle band being a 20-day simple moving average (SMA), an upper band at two standard deviations above the SMA, and a lower band at two standard deviations below the SMA. Bollinger Bands expand and contract with volatility. Prices touching the upper band might indicate overbuying, and touching the lower band might indicate overselling.

This script plots the Adjusted Close Price of AAPL along with the calculated Bollinger Bands, MACD and Signal Line, and RSI over a specified period. These indicators can help identify potential buy or sell signals based on historical price movements and volatility.

Sector and Industry Analysis

To perform a sector and industry analysis using Python and yfinance, we first need a list of companies across various sectors. Then, we can fetch their historical data, aggregate it by sector, and analyze the overall performance and trends. However, yfinance does not directly provide a way to fetch all companies by sector. Instead, you'll typically need a predefined list of ticker symbols categorized by their sectors.

For this example, let’s analyze three sectors: Technology, Healthcare, and Consumer Discretionary. We’ll select a few companies from each sector, fetch their year-to-date (YTD) performance, and then compare the average performance of each sector.

Here’s a simplified example of how you might perform this analysis:

Explanation:

  • This script organizes stocks into three sectors: Technology, Healthcare, and Consumer Discretionary.
  • For each sector, it fetches the year-to-date (YTD) adjusted close prices for each stock.
  • It calculates the YTD return for each stock by taking the percentage change and summing it up.
  • It then calculates the average YTD return for the stocks in each sector to represent the sector’s performance.
  • Finally, it prints out the average YTD return for each sector.

Please note, this example uses a simple method to calculate YTD returns and averages them to get a sector performance. Real-world analysis might include more complex metrics, consider dividends, or use weighted averages based on market capitalization.

This example provides a basic framework for sector analysis. Depending on your specific needs, you might want to include more sectors, a larger selection of stocks, or use more detailed performance metrics.

Visit us at DataDrivenInvestor.com

Subscribe to DDIntel here.

Have a unique story to share? Submit to DDIntel here.

Join our creator ecosystem here.

DDIntel captures the more notable pieces from our main site and our popular DDI Medium publication. Check us out for more insightful work from our community.

DDI Official Telegram Channel: https://t.me/+tafUp6ecEys4YjQ1

Follow us on LinkedIn, Twitter, YouTube, and Facebook.

Python
Finance
Stocks
Stock Market
Recommended from ReadMedium
avatarMystic Wealth. RA in the Indian secondary markets
Barbell strategy and Drawdowns

asset allocation, Drawdowns, Barbell, Uncle Point.

3 min read