Data visualization is crucial in financial analysis for identifying trends, analyzing stock prices, monitoring portfolio performance, and detecting market patterns. Python provides powerful libraries like Matplotlib, Seaborn, Plotly, and Bokeh for financial data visualization.
Key Topics Covered
✔ Plotting stock market data
✔ Visualizing moving averages and Bollinger Bands
✔ Portfolio performance analysis
✔ Candlestick charting
✔ Interactive dashboards
1. Installing Required Libraries
pip install pandas matplotlib seaborn plotly yfinance mplfinance
2. Fetching Financial Data Using yfinance
We use yfinance
to get stock price data.
import pandas as pd
import yfinance as yf
# Fetch historical stock data for Apple (AAPL)
df = yf.download("AAPL", start="2023-01-01", end="2024-01-01")
# Display first 5 rows
print(df.head())
✔ Includes Open, High, Low, Close, Adjusted Close, and Volume
3. Visualizing Stock Prices with Matplotlib
A basic closing price trend plot.
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 6))
plt.plot(df.index, df['Close'], label='AAPL Closing Price', color='blue')
plt.xlabel("Date")
plt.ylabel("Stock Price (USD)")
plt.title("Apple Stock Price Trend")
plt.legend()
plt.show()
✔ Helps spot trends and price fluctuations
4. Moving Averages & Bollinger Bands
Moving Averages smooth out price fluctuations.
Bollinger Bands measure volatility using a 20-day SMA and standard deviation.
df['SMA_50'] = df['Close'].rolling(window=50).mean()
df['SMA_200'] = df['Close'].rolling(window=200).mean()
df['Upper_Band'] = df['SMA_50'] + 2 * df['Close'].rolling(50).std()
df['Lower_Band'] = df['SMA_50'] - 2 * df['Close'].rolling(50).std()
plt.figure(figsize=(12, 6))
plt.plot(df.index, df['Close'], label='Close Price', color='blue')
plt.plot(df.index, df['SMA_50'], label='50-day SMA', color='red')
plt.plot(df.index, df['Upper_Band'], label='Upper Bollinger Band', linestyle='dashed', color='green')
plt.plot(df.index, df['Lower_Band'], label='Lower Bollinger Band', linestyle='dashed', color='green')
plt.title("Stock Price with Bollinger Bands")
plt.legend()
plt.show()
✔ Used for trend identification and volatility analysis
5. Candlestick Chart with mplfinance
Candlestick charts display open, high, low, and close prices.
import mplfinance as mpf
mpf.plot(df, type='candle', style='charles', volume=True, title="Apple Candlestick Chart")
✔ Used by traders for market trend analysis
6. Correlation Analysis Between Stocks
Analyze the relationship between different stocks.
stocks = ['AAPL', 'MSFT', 'GOOGL', 'AMZN']
data = yf.download(stocks, start="2023-01-01", end="2024-01-01")['Close']
# Compute correlation
corr_matrix = data.corr()
import seaborn as sns
plt.figure(figsize=(8, 6))
sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', linewidths=0.5)
plt.title("Stock Correlation Heatmap")
plt.show()
✔ Helpful for portfolio diversification
7. Interactive Dashboard with Plotly
Create an interactive stock price chart.
import plotly.graph_objects as go
fig = go.Figure()
fig.add_trace(go.Scatter(x=df.index, y=df['Close'], mode='lines', name='Close Price'))
fig.update_layout(title="Apple Stock Price Interactive Chart",
xaxis_title="Date",
yaxis_title="Stock Price (USD)",
template="plotly_dark")
fig.show()
✔ Improves data exploration and insights
8. Portfolio Performance Visualization
Monitor cumulative portfolio returns.
# Simulate portfolio with equal investments in AAPL, MSFT, GOOGL, AMZN
weights = [0.25, 0.25, 0.25, 0.25]
portfolio_returns = (data.pct_change().dropna() @ weights).cumsum()
plt.figure(figsize=(12, 6))
plt.plot(portfolio_returns, label='Portfolio Cumulative Returns', color='purple')
plt.xlabel("Date")
plt.ylabel("Cumulative Returns")
plt.title("Portfolio Performance Over Time")
plt.legend()
plt.show()
✔ Tracks portfolio growth over time