Portfolio Analysis with YFinance and Discrete Laplacian

Using YFinance and the Discrete Laplacian for Portfolio Analysis

Using YFinance and the Discrete Laplacian for Portfolio Analysis

Analyzing a portfolio’s structure is crucial for understanding risks, correlations, and diversification. The **Discrete Laplacian**, a mathematical tool from graph theory, helps us understand how interconnected assets in a portfolio influence each other. Combined with real market data fetched using **YFinance**, we can visualize correlations, compute risk metrics, and identify diversification opportunities.

What is the Discrete Laplacian?

The Discrete Laplacian is a mathematical operator that analyzes how values at a point (or node) compare to those at its neighbors in a network. It is commonly used in physics, image processing, and network analysis. In investing, the Discrete Laplacian can:

  • Highlight clusters of highly correlated assets, enabling better diversification.
  • Reveal outliers, such as assets that deviate significantly from portfolio trends.
  • Model how shocks propagate through a network of assets.

Mathematically, the Discrete Laplacian \( L \) is computed as:

\( L = D – A \)

Where:

  • D: Degree matrix (captures the number of connections for each node).
  • A: Adjacency matrix (captures the strength of connections between nodes).

Objective

In this article, we will:

  • Fetch historical market data for selected stocks using YFinance.
  • Calculate the correlation matrix and construct a portfolio graph.
  • Compute the Discrete Laplacian to analyze clusters and diversification.
  • Visualize the graph structure and interpret eigenvalues of the Laplacian.

Python Code

Below is the Python code that performs the analysis:

import numpy as np
import yfinance as yf
import networkx as nx
import matplotlib.pyplot as plt

# Define the tickers of the assets (stocks, ETFs, etc.)
tickers = ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"]

# Fetch historical market data using yfinance
data = yf.download(tickers, start="2020-01-01", end="2023-01-01")["Adj Close"]

# Calculate daily returns
returns = data.pct_change().dropna()

# Compute the correlation matrix
correlation_matrix = returns.corr().values

# Create the adjacency matrix by thresholding correlations (e.g., > 0.5)
threshold = 0.5
adj_matrix = (correlation_matrix > threshold).astype(int)

# Create a graph from the adjacency matrix
G = nx.Graph()
for i, ticker1 in enumerate(tickers):
    for j, ticker2 in enumerate(tickers):
        if adj_matrix[i, j] and i != j:  # Avoid self-loops
            G.add_edge(ticker1, ticker2, weight=correlation_matrix[i, j])

# Compute the degree matrix and Laplacian matrix
degree_matrix = np.diag(np.sum(adj_matrix, axis=1))
laplacian_matrix = degree_matrix - adj_matrix

# Print the matrices
print("Adjacency Matrix:")
print(adj_matrix)
print("\nDegree Matrix:")
print(degree_matrix)
print("\nLaplacian Matrix:")
print(laplacian_matrix)

# Visualize the graph
pos = nx.spring_layout(G, seed=42)
plt.figure(figsize=(10, 6))
nx.draw(G, pos, with_labels=True, node_color="lightblue", edge_color="gray", node_size=2000, font_size=10)
labels = nx.get_edge_attributes(G, "weight")
nx.draw_networkx_edge_labels(G, pos, edge_labels={k: f"{v:.2f}" for k, v in labels.items()})
plt.title("Portfolio Correlation Graph")
plt.show()

# Analyze clusters using the eigenvalues of the Laplacian matrix
eigenvalues, eigenvectors = np.linalg.eig(laplacian_matrix)

# Plot the eigenvalues
plt.figure(figsize=(8, 5))
plt.bar(range(len(eigenvalues)), sorted(eigenvalues), color="blue", alpha=0.7)
plt.title("Eigenvalues of the Laplacian Matrix")
plt.xlabel("Index")
plt.ylabel("Eigenvalue")
plt.grid(True)
plt.show()

# Interpret eigenvalues
print("\nEigenvalues of the Laplacian Matrix (sorted):")
print(sorted(eigenvalues))
        

Graph Visualization

Correlation

Table of Matrices

Matrix Data

Matrix Data

Adjacency Matrix

1 1 1 1 1
1 1 1 1 0
1 1 1 1 0
1 1 1 1 1
1 0 0 1 1

Degree Matrix

5 0 0 0 0
0 4 0 0 0
0 0 4 0 0
0 0 0 5 0
0 0 0 0 3

Laplacian Matrix

4 -1 -1 -1 -1
-1 3 -1 -1 0
-1 -1 3 -1 0
-1 -1 -1 4 -1
-1 0 0 -1 2

Eigenvalues Analysis

Correlation

Conclusion

By combining **YFinance** for real market data with the **Discrete Laplacian**, we can analyze portfolio structures in a novel way. This method provides insights into correlations, diversification, and risk propagation, enabling smarter investment decisions. Try running the Python code above to visualize your own portfolio and uncover actionable insights!

Understanding Correlation Graphs and Eigenvalue Plots in Portfolio Analysis

Understanding Correlation Graphs and Eigenvalue Plots in Portfolio Analysis

Analyzing your portfolio’s structure and risk is essential for smart investing. Two powerful tools—the **correlation graph** and the **eigenvalue plot**—can provide deep insights into how your assets interact and help you optimize diversification. Let’s break down what these tools mean and how you can use them to make informed investment decisions.

The Correlation Graph

The correlation graph visually represents relationships between the assets in your portfolio. Each node represents an asset, and the edges (lines) between nodes show correlations based on historical price movements.

What It Represents

  • Nodes: Each node is an asset (e.g., a stock or ETF).
  • Edges: The lines between nodes represent significant correlations. Thicker edges indicate stronger correlations.

What to Look For

  • Highly Connected Nodes: Assets with many edges are highly correlated with others. These assets may not add much diversification.
  • Clusters: Groups of tightly connected nodes represent assets that behave similarly. These clusters often belong to the same industry or sector.

Practical Insights

  • Diversification: A well-diversified portfolio has a mix of connected and unconnected nodes.
  • Sector Analysis: Clusters highlight sectors dominating your portfolio, helping you manage concentration risks.

The Eigenvalue Plot

The eigenvalue plot, derived from the Laplacian matrix of the graph, provides a quantitative way to analyze the structure of your portfolio’s correlation network.

What Are Eigenvalues?

Eigenvalues measure how connected or clustered the graph is. In investing terms, they describe how risk or relationships are distributed across your portfolio.

What the Plot Shows

  • Small Eigenvalues (Close to Zero): Indicate weak connections or independent clusters in the graph. A zero eigenvalue represents a completely disconnected group of assets.
  • Large Eigenvalues: Suggest strong connections within the graph, which could lead to concentrated risks.

Practical Insights

  • Clustering: Spread-out eigenvalues indicate a mix of tightly connected and independent assets, which is ideal for diversification.
  • Diversification: Many small eigenvalues suggest better diversification because assets are less connected.
  • Risk Propagation: Higher eigenvalues might signal areas where risks could spread quickly through the portfolio.

Example Interpretation

Correlation Graph

Imagine your portfolio contains five assets:

  • AAPL (Apple), MSFT (Microsoft), GOOGL (Google): These assets are tightly connected, indicating similar behavior.
  • AMZN (Amazon): Fewer connections suggest it’s less correlated, providing some diversification.
  • TSLA (Tesla): An isolated node shows it moves independently of the other assets, which is great for diversification.

This graph suggests your portfolio might be overly concentrated in tech stocks (AAPL, MSFT, GOOGL). Adding less connected assets like TSLA or stocks from different sectors could improve diversification.

Eigenvalue Plot

– **Small Eigenvalues:** Suggest independent clusters or unconnected assets, which indicate good diversification.
– **Large Eigenvalues:** Show highly connected clusters, which could lead to systemic risks if those clusters dominate the portfolio.

Key Takeaways

  • Correlation Graph: Visualize relationships between assets and identify clusters or sectors dominating your portfolio.
  • Eigenvalue Plot: Quantify the degree of diversification and connectivity in your portfolio to manage risks effectively.

By combining these tools, you can build a well-diversified portfolio, reduce concentration risks, and understand how assets interact in your investments. These insights help you make more informed and strategic financial decisions.