Week 8: Data Visualization with Matplotlib and Seaborn

Master financial data visualization techniques using Python's powerful plotting libraries

Learning Objectives

Core Topics

1. Market Data Visualization

import matplotlib.pyplot as plt
import yfinance as yf
import seaborn as sns

# Download stock data
stock = yf.download('AAPL', start='2023-01-01')

# Create figure with secondary y-axis
fig, ax1 = plt.subplots(figsize=(12,6))
ax2 = ax1.twinx()

# Plot price and volume
ax1.plot(stock.index, stock['Close'], 'b-', label='Price')
ax2.bar(stock.index, stock['Volume'], alpha=0.3, color='gray', label='Volume')

plt.title('AAPL Price and Volume Analysis')
plt.show()

2. Treasury Yield Curve Inversion and Recession Indicator

The yield curve "inverts" when short-term rates become higher than long-term rates. This is often considered a recession warning signal.

import pandas_datareader as pdr
import matplotlib.pyplot as plt
import numpy as np

# Get Treasury rates data from FRED
# 10-year minus 2-year spread is a common recession predictor
rates = pd.DataFrame()
rates['10YR'] = pdr.get_data_fred('DGS10')  # 10-year rate
rates['2YR'] = pdr.get_data_fred('DGS2')    # 2-year rate
rates['Spread'] = rates['10YR'] - rates['2YR']  # Yield curve spread

# Get recession data
recession = pdr.get_data_fred('USREC')

# Create figure with two subplots
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10), height_ratios=[2, 1])

# Plot 1: Treasury Rates
ax1.plot(rates.index, rates['10YR'], 'b-', label='10-Year Treasury')
ax1.plot(rates.index, rates['2YR'], 'r-', label='2-Year Treasury')

# Highlight recession periods in both plots
for i in range(len(recession)-1):
    if recession['USREC'].iloc[i] == 1:
        ax1.axvspan(recession.index[i], recession.index[i+1], 
                   color='gray', alpha=0.2)
        ax2.axvspan(recession.index[i], recession.index[i+1], 
                   color='gray', alpha=0.2)

ax1.set_title('Treasury Rates: 10-Year vs 2-Year')
ax1.set_ylabel('Yield (%)')
ax1.grid(True)
ax1.legend()

# Plot 2: Yield Curve Spread
ax2.plot(rates.index, rates['Spread'], 'g-', label='10Y-2Y Spread')
ax2.axhline(y=0, color='r', linestyle='--', alpha=0.5)  # Add zero line
ax2.fill_between(rates.index, rates['Spread'], 0, 
                 where=(rates['Spread'] < 0),
                 color='r', alpha=0.3,
                 label='Yield Curve Inversion')

ax2.set_title('Yield Curve Spread (10Y-2Y)')
ax2.set_ylabel('Spread (%)')
ax2.grid(True)
ax2.legend()

plt.tight_layout()
plt.show()

# Let's also show a typical yield curve shape
# Get current Treasury rates for different maturities
maturities = ['1MO', '3MO', '6MO', '1YR', '2YR', '5YR', '10YR', '30YR']
tickers = ['DGS1MO', 'DGS3MO', 'DGS6MO', 'DGS1', 'DGS2', 'DGS5', 'DGS10', 'DGS30']
current_rates = pd.DataFrame()

for ticker in tickers:
    current_rates[ticker] = pdr.get_data_fred(ticker)

# Plot current yield curve
plt.figure(figsize=(10, 6))
plt.plot(range(len(maturities)), current_rates.iloc[-1], 'bo-', label='Current')

# Add labels
plt.title('Current Treasury Yield Curve Shape')
plt.xlabel('Maturity')
plt.ylabel('Yield (%)')
plt.xticks(range(len(maturities)), maturities, rotation=45)
plt.grid(True)

# Add annotation about curve shape
if current_rates.iloc[-1]['DGS2'] > current_rates.iloc[-1]['DGS10']:
    plt.text(0.6, 0.9, 'Inverted Yield Curve\n(Potential Recession Signal)', 
             transform=plt.gca().transAxes, 
             bbox=dict(facecolor='red', alpha=0.2))
else:
    plt.text(0.6, 0.9, 'Normal Yield Curve', 
             transform=plt.gca().transAxes, 
             bbox=dict(facecolor='green', alpha=0.2))

plt.legend()
plt.tight_layout()
plt.show()

Understanding the Plots:

  • Normal Yield Curve: Long-term rates (10Y) higher than short-term rates (2Y)
  • Inverted Yield Curve: Short-term rates higher than long-term rates (spread goes negative)
  • Gray areas show historical recession periods
  • Red shading shows periods of yield curve inversion

3. Economic Indicators

# Create recession highlighting
import pandas_datareader as pdr
from datetime import datetime

# Get GDP data
gdp = pdr.get_data_fred('GDP', start='2000-01-01')
recession = pdr.get_data_fred('USREC', start='2000-01-01')

# Plot GDP with recession highlighting
plt.figure(figsize=(12,6))
plt.plot(gdp.index, gdp['GDP'], 'b-', label='GDP')

# Highlight recession periods
for i in range(len(recession)):
    if recession['USREC'].iloc[i] == 1:
        plt.axvspan(recession.index[i], recession.index[i+1], 
                   color='gray', alpha=0.2)

plt.title('US GDP with Recession Periods')
plt.legend()
plt.show()

4. Advanced Market Analysis

# Create sector performance treemap
import squarify

sizes = [30, 25, 20, 15, 10, 8, 7, 6, 5, 4, 3]
labels = ['Tech', 'Finance', 'Healthcare', 'Consumer', 'Industry',
          'Energy', 'Materials', 'Utilities', 'Real Estate', 'Telecom']
colors = sns.color_palette('RdYlBu', len(sizes))

plt.figure(figsize=(12,8))
squarify.plot(sizes=sizes, label=labels, color=colors, alpha=0.8)
plt.title('Market Sector Performance')
plt.axis('off')
plt.show()

Exercises

Basic Exercises:

  1. Create a stock price chart with volume and moving averages
  2. Plot a current yield curve using Treasury data
  3. Visualize inflation data with recession highlighting

Optional: Intermediate Exercises:

  1. Build a yield curve animation showing changes over time
  2. Create a sector rotation analysis dashboard
  3. Develop a bond price sensitivity visualization tool

Optional:Advanced Exercises:

  1. Create a comprehensive market dashboard combining multiple indicators
  2. Build an interactive yield curve analysis tool
  3. Develop a real-time market breadth visualization system

💡 ChatGPT Learning Tips

Use these prompts to enhance your understanding of financial data visualization:

  1. "Create a Python code example that plots a stock's price and volume using matplotlib"
  2. "Explain how to create a Treasury yield curve visualization using Python and FRED data"
  3. "Show me how to highlight recession periods in a financial time series plot"
  4. "Write code to create an interactive financial dashboard using matplotlib"
  5. "What are the best practices for visualizing financial market data?"

📚 Research Tip: Use Perplexity.ai to search for "financial data visualization examples Python" or "Treasury yield curve analysis Python"

Additional Resources

← Previous Week | Next Week →
← Back to Home