This is a comprehensive request asking me to:
- Fetch OHLC data using yfinance
- Verify/plot with mplfinance
- Create a custom interactive candlestick chart with Plotly
- Add Bollinger Bands overlay using pandas rolling standard deviation
I'll create a complete, production-ready solution that demonstrates all these components.
Let me structure this:
- Install required packages
- Fetch data with yfinance
- Calculate technical indicators (SMA and Bollinger Bands)
- Create static plot with mplfinance for verification
- Create interactive Plotly candlestick chart with Bollinger Bands
- Add proper error handling and documentation
Here's my comprehensive solution:
Complete Stock Analysis with OHLC Data, mplfinance Verification, and Interactive Plotly Charts
Here's a production-ready solution that fetches data, creates verification plots, and renders interactive candlestick charts with Bollinger Bands:
import yfinance as yf
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import mplfinance as mpf
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
class StockAnalyzer:
"""
Comprehensive stock analysis with technical indicators
"""
def __init__(self, ticker, period='3mo', interval='1d'):
"""
Initialize stock analyzer
Args:
ticker (str): Stock ticker symbol
period (str): Data period (e.g., '3mo', '1y')
interval (str): Data interval (e.g., '1d', '1h')
"""
self.ticker = ticker.upper()
self.period = period
self.interval = interval
self.df = None
self.stock_info = None
def fetch_data(self):
"""Fetch OHLC data from yfinance"""
try:
print(f"📊 Fetching {self.ticker} data for {self.period}...")
self.df = yf.download(
self.ticker,
period=self.period,
interval=self.interval,
progress=False
)
# Reset index to make date a column
self.df.reset_index(inplace=True)
# Get stock info
self.stock_info = yf.Ticker(self.ticker)
print(f"✅ Successfully fetched {len(self.df)} records")
print(f"\nData Summary:")
print(f"Date Range: {self.df['Date'].min().date()} to {self.df['Date'].max().date()}")
print(f"Price Range: ${self.df['Close'].min():.2f} - ${self.df['Close'].max():.2f}")
print(f"\nFirst few rows:")
print(self.df.head())
return self.df
except Exception as e:
print(f"❌ Error fetching data: {e}")
return None
def calculate_bollinger_bands(self, window=20, num_std=2):
"""
Calculate Bollinger Bands using pandas rolling functions
Args:
window (int): Rolling window size (default 20)
num_std (float): Number of standard deviations (default 2)
Returns:
pd.DataFrame: DataFrame with BB columns added
"""
# Calculate 20-day SMA (middle band)
self.df['SMA_20'] = self.df['Close'].rolling(window=window).mean()
# Calculate standard deviation
self.df['STD_20'] = self.df['Close'].rolling(window=window).std()
# Upper and Lower Bands
self.df['BB_Upper'] = self.df['SMA_20'] + (self.df['STD_20'] * num_std)
self.df['BB_Lower'] = self.df['SMA_20'] - (self.df['STD_20'] * num_std)
# Bollinger Band Position (0 to 1, where 1 is at upper band)
self.df['BB_Position'] = (
(self.df['Close'] - self.df['BB_Lower']) /
(self.df['BB_Upper'] - self.df['BB_Lower'])
)
# Percentage difference from middle band
self.df['BB_Pct_Diff'] = (
(self.df['Close'] - self.df['SMA_20']) / self.df['SMA_20'] * 100
)
print(f"✅ Bollinger Bands calculated (period={window}, std={num_std})")
print(f"Columns added: SMA_20, STD_20, BB_Upper, BB_Lower, BB_Position, BB_Pct_Diff")
return self.df
def calculate_rsi(self, window=14):
"""Calculate Relative Strength Index"""
delta = self.df['Close'].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
rs = gain / loss
self.df['RSI'] = 100 - (100 / (1 + rs))
return self.df
def calculate_macd(self, fast=12, slow=26, signal=9):
"""Calculate MACD"""
ema_fast = self.df['Close'].ewm(span=fast).mean()
ema_slow = self.df['Close'].ewm(span=slow).mean()
self.df['MACD'] = ema_fast - ema_slow
self.df['MACD_Signal'] = self.df['MACD'].ewm(span=signal).mean()
self.df['MACD_Histogram'] = self.df['MACD'] - self.df['MACD_Signal']
return self.df
def plot_with_mplfinance(self, save_path='stock_chart_mplfinance.png'):
"""Create static verification chart with mplfinance"""
try:
# Prepare dataframe for mplfinance
plot_df = self.df.set_index('Date').copy()
# Create additional plots
apds = [
mpf.make_addplot(plot_df['BB_Upper'], color='orange', width=1.5),
mpf.make_addplot(plot_df['SMA_20'], color='blue', width=1.5),
mpf.make_addplot(plot_df['BB_Lower'], color='orange', width=1.5),
mpf.make_addplot(plot_df['RSI'], panel=2, color='purple', ylabel='RSI'),
mpf.make_addplot(plot_df['MACD'], panel=3, color='red', ylabel='MACD'),
mpf.make_addplot(plot_df['MACD_Signal'], panel=3, color='blue'),
mpf.make_addplot(plot_df['MACD_Histogram'], panel=3,
type='bar', color='gray', alpha=0.3),
]
# Create style
style = mpf.make_mpf_style(
base_mpl_style='default',
gridstyle=':',
facecolor='#f0f0f0'
)
print(f"\n📈 Creating mplfinance verification chart...")
mpf.plot(
plot_df[['Open', 'High', 'Low', 'Close', 'Volume']],
type='candle',
style=style,
addplot=apds,
title=f'{self.ticker} - Stock Analysis with Bollinger Bands, RSI, MACD',
ylabel='Price ($)',
volume=True,
figsize=(14, 10),
savefig=save_path
)
print(f"✅ Chart saved: {save_path}")
except Exception as e:
print(f"❌ Error creating mplfinance chart: {e}")
def plot_interactive_plotly(self, save_path='stock_chart_plotly.html'):
"""
Create interactive candlestick chart with Plotly and Bollinger Bands
"""
try:
print(f"\n🎨 Creating interactive Plotly chart...")
# Create figure with secondary y-axis
fig = go.Figure()
# Add candlestick
fig.add_trace(go.Candlestick(
x=self.df['Date'],
open=self.df['Open'],
high=self.df['High'],
low=self.df['Low'],
close=self.df['Close'],
name='OHLC',
yaxis='y1',
increasing_line_color='green',
decreasing_line_color='red'
))
# Add SMA (Middle Band)
fig.add_trace(go.Scatter(
x=self.df['Date'],
y=self.df['SMA_20'],
name='SMA 20',
line=dict(color='blue', width=2),
yaxis='y1',
hovertemplate='<b>SMA 20</b><br>%{y:.2f}<extra></extra>'
))
# Add Upper Bollinger Band
fig.add_trace(go.Scatter(
x=self.df['Date'],
y=self.df['BB_Upper'],
name='BB Upper',
line=dict(color='orange', width=1, dash='dash'),
yaxis='y1',
hovertemplate='<b>BB Upper</b><br>%{y:.2f}<extra></extra>'
))
# Add Lower Bollinger Band
fig.add_trace(go.Scatter(
x=self.df['Date'],
y=self.df['BB_Lower'],
name='BB Lower',
line=dict(color='orange', width=1, dash='dash'),
yaxis='y1',
hovertemplate='<b>BB Lower</b><br>%{y:.2f}<extra></extra>'
))
# Add filled area between bands
fig.add_trace(go.Scatter(
x=self.df['Date'].tolist() + self.df['Date'].tolist()[::-1],
y=self.df['BB_Upper'].tolist() + self.df['BB_Lower'].tolist()[::-1],
fill='toself',
name='BB Band',
fillcolor='rgba(255, 165, 0, 0.1)',
line=dict(color='rgba(255,255,255,0)'),
yaxis='y1',
hoverinfo='skip',
showlegend=True
))
# Add RSI on secondary axis
fig.add_trace(go.Scatter(
x=self.df['Date'],
y=self.df['RSI'],
name='RSI (14)',
line=dict(color='purple', width=2),
yaxis='y2',
hovertemplate='<b>RSI</b><br>%{y:.2f}<extra></extra>'
))
# Add RSI levels
fig.add_hline(y=70, line_dash="dash", line_color="red",
yref="y2", name="RSI OB", row="all",
annotation_text="Overbought (70)")
fig.add_hline(y=30, line_dash="dash", line_color="green",
yref="y2", name="RSI OS",
annotation_text="Oversold (30)")
# Update layout
fig.update_layout(
title=f'<b>{self.ticker} - Stock Price Analysis</b><br>' +
f'<sub>Period: {self.df["Date"].min().date()} to {self.df["Date"].max().date()}</sub>',
yaxis=dict(
title='Price ($)',
yaxis_name='y1',
side='left',
showgrid=True,
gridwidth=1,
gridcolor='lightgray'
),
yaxis2=dict(
title='RSI',
side='right',
showgrid=False,
range=[0, 100]
),
xaxis=dict(
title='Date',
rangeslider=dict(visible=False),
type='date',
showgrid=True,
gridwidth=1,
gridcolor='lightgray'
),
hovermode='x unified',
plot_bgcolor='#f8f9fa',
paper_bgcolor='white',
width=1400,
height=700,
showlegend=True,
legend=dict(
orientation="v",
yanchor="top",
y=0.99,
xanchor="left",
x=0.01,
bgcolor="rgba(255, 255, 255, 0.7)",
bordercolor="gray",
borderwidth=1
),
margin=dict(r=100)
)
# Update x-axis with range slider
fig.update_xaxes(
rangeslider=dict(visible=False),
rangeselector=dict(
buttons=list([
dict(count=1, label="1m", step="month", stepmode="backward"),
dict(count=3, label="3m", step="month", stepmode="backward"),
dict(count=6, label="6m", step="month", stepmode="backward"),
dict(step="all", label="All")
])
)
)
# Save and display
fig.write_html(save_path)
print(f"✅ Interactive chart saved: {save_path}")
return fig
except Exception as e:
print(f"❌ Error creating Plotly chart: {e}")
return None
def generate_statistics(self):
"""Generate and display statistical analysis"""
stats = {
'Ticker': self.ticker,
'Current Price': f"${self.df['Close'].iloc[-1]:.2f}",
'Highest': f"${self.df['High'].max():.2f}",
'Lowest': f"${self.df['Low'].min():.2f}",
'Average': f"${self.df['Close'].mean():.2f}",
'Std Dev': f"${self.df['Close'].std():.2f}",
'52-Week Change': f"{((self.df['Close'].iloc[-1] / self.df['Close'].iloc[0]) - 1) * 100:.2f}%",
'RSI': f"{self.df['RSI'].iloc[-1]:.2f}",
'BB Position': f"{self.df['BB_Position'].iloc[-1]:.2%}",
'MACD': f"{self.df['MACD'].iloc[-1]:.4f}",
}
print("\n📊 Statistical Summary:")
print("=" * 50)
for key, value in stats.items():
print(f"{key:.<30} {value:>15}")
print("=" * 50)
return stats
def main():
"""Main execution function"""
# Configuration
TICKER = 'AAPL'
PERIOD = '1y'
INTERVAL = '1d'
print("=" * 60)
print(f"Stock Analysis Tool - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("=" * 60)
# Initialize analyzer
analyzer = StockAnalyzer(TICKER, period=PERIOD, interval=INTERVAL)
# Fetch data
analyzer.fetch_data()
if analyzer.df is not None:
# Calculate technical indicators
analyzer.calculate_bollinger_bands(window=20, num_std=2)
analyzer.calculate_rsi(window=14)
analyzer.calculate_macd()
# Generate statistics
analyzer.generate_statistics()
# Create verification chart with mplfinance
analyzer.plot_with_mplfinance()
# Create interactive chart
analyzer.plot_interactive_plotly()
print("\n✨ Analysis complete!")
print(f"Open 'stock_chart_plotly.html' in your browser for interactive chart")
if __name__ == "__main__":
main()
Advanced Interactive Dashboard with Multiple Indicators
Here's an enhanced version with a full dashboard:
import yfinance as yf
import pandas as pd
import plotly.subplots as sp
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np
class AdvancedStockDashboard:
"""Advanced stock analysis dashboard with multiple indicators"""
def __init__(self, ticker, period='1y'):
self.ticker = ticker.upper()
self.period = period
self.df = yf.download(ticker, period=period, progress=False)
self.df.reset_index(inplace=True)
self._calculate_all_indicators()
def _calculate_all_indicators(self):
"""Calculate all technical indicators"""
# Bollinger Bands
self.df['SMA_20'] = self.df['Close'].rolling(20).mean()
self.df['BB_Upper'] = self.df['SMA_20'] + (self.df['Close'].rolling(20).std() * 2)
self.df['BB_Lower'] = self.df['SMA_20'] - (self.df['Close'].rolling(20).std() * 2)
# RSI
delta = self.df['Close'].diff()
gain = delta.where(delta > 0, 0).rolling(14).mean()
loss = -delta.where(delta < 0, 0).rolling(14).mean()
self.df['RSI'] = 100 - (100 / (1 + gain / loss))
# MACD
ema12 = self.df['Close'].ewm(span=12).mean()
ema26 = self.df['Close'].ewm(span=26).mean()
self.df['MACD'] = ema12 - ema26
self.df['MACD_Signal'] = self.df['MACD'].ewm(span=9).mean()
self.df['MACD_Hist'] = self.df['MACD'] - self.df['MACD_Signal']
# ATR (Average True Range)
high_low = self.df['High'] - self.df['Low']
high_close = abs(self.df['High'] - self.df['Close'].shift())
low_close = abs(self.df['Low'] - self.df['Close'].shift())
tr = pd.concat([high_low, high_close, low_close], axis=1).max(axis=1)
self.df['ATR'] = tr.rolling(14).mean()
# Volume SMA
self.df['Volume_SMA'] = self.df['Volume'].rolling(20).mean()
def create_dashboard(self, save_path='dashboard.html'):
"""Create comprehensive multi-panel dashboard"""
# Create subplots with shared x-axis
fig = make_subplots(
rows=4, cols=1,
shared_xaxes=True,
vertical_spacing=0.05,
row_heights=[0.5, 0.2, 0.15, 0.15],
specs=[
[{"secondary_y": True}],
[{"secondary_y": False}],
[{"secondary_y": False}],
[{"secondary_y": False}]
]
)
# Row 1: Candlestick + Bollinger Bands
fig.add_trace(
go.Candlestick(
x=self.df['Date'],
open=self.df['Open'],
high=self.df['High'],
low=self.df['Low'],
close=self.df['Close'],
name='OHLC'
),
row=1, col=1, secondary_y=False
)
# Add Bollinger Bands
fig.add_trace(
go.Scatter(x=self.df['Date'], y=self.df['BB_Upper'],
name='BB Upper', line=dict(color='rgba(255,165,0,0.5)')),
row=1, col=1, secondary_y=False
)
fig.add_trace(
go.Scatter(x=self.df['Date'], y=self.df['SMA_20'],
name='SMA 20', line=dict(color='blue')),
row=1, col=1, secondary_y=False
)
fig.add_trace(
go.Scatter(x=self.df['Date'], y=self.df['BB_Lower'],
name='BB Lower', line=dict(color='rgba(255,165,0,0.5)')),
row=1, col=1, secondary_y=False
)
# Row 2: Volume
colors = ['red' if self.df['Close'].iloc[i] < self.df['Open'].iloc[i]
else 'green' for i in range(len(self.df))]
fig.add_trace(
go.Bar(x=self.df['Date'], y=self.df['Volume'],
name='Volume', marker_color=colors, opacity=0.5),
row=2, col=1
)
fig.add_trace(
go.Scatter(x=self.df['Date'], y=self.df['Volume_SMA'],
name='Volume SMA', line=dict(color='red')),
row=2, col=1
)
# Row 3: RSI
fig.add_trace(
go.Scatter(x=self.df['Date'], y=self.df['RSI'],
name='RSI', line=dict(color='purple')),
row=3, col=1
)
fig.add_hline(y=70, line_dash="dash", line_color="red", row=3, col=1)
fig.add_hline(y=30, line_dash="dash", line_color="green", row=3, col=1)
# Row 4: MACD
fig.add_trace(
go.Scatter(x=self.df['Date'], y=self.df['MACD'],
name='MACD', line=dict(color='red')),
row=4, col=1
)
fig.add_trace(
go.Scatter(x=self.df['Date'], y=self.df['MACD_Signal'],
name='Signal', line=dict(color='blue')),
row=4, col=1
)
colors_macd = ['green' if x > 0 else 'red' for x in self.df['MACD_Hist']]
fig.add_trace(
go.Bar(x=self.df['Date'], y=self.df['MACD_Hist'],
name='MACD Hist', marker_color=colors_macd, opacity=0.3),
row=4, col=1
)
# Update layout
fig.update_layout(
title_text=f"<b>{self.ticker} - Advanced Trading Dashboard</b>",
height=1200,
width=1400,
hovermode='x unified',
plot_bgcolor='#f8f9fa',
xaxis_rangeslider_visible=False,
showlegend=True
)
# Update y-axes labels
fig.update_yaxes(title_text="Price ($)", row=1, col=1)
fig.update_yaxes(title_text="Volume", row=2, col=1)
fig.update_yaxes(title_text="RSI", row=3, col=1)
fig.update_yaxes(title_text="MACD", row=4, col=1)
fig.write_html(save_path)
print(f"✅ Dashboard saved to {save_path}")
return fig
# Usage
if __name__ == "__main__":
dashboard = AdvancedStockDashboard('MSFT', period='6mo')
dashboard.create_dashboard('advanced_dashboard.html')
Installation Requirements
pip install yfinance pandas numpy plotly mplfinance
Key Features
| Feature | Description |
|---|
| OHLC Data | Fetches Open, High, Low, Close via yfinance |
| Bollinger Bands | Calculated using pandas rolling mean/std |
| RSI | Relative Strength Index (14-period) |
| MACD | Moving Average Convergence Divergence |
| mplfinance | Static verification charts |
| Plotly | Interactive candlestick charts with zoom/pan |
| Dashboard | Multi-panel technical analysis |
| Statistics | Performance metrics and analysis |
This solution provides production-ready stock analysis with full flexibility for customization!