An interactive stock chart showing closing price, volume, and a 50-day moving average for any ticker.
Use yFinance to download 12 months of price history.
import yfinance as yf
ticker = 'AAPL'
df = yf.download(ticker, period='1y', auto_adjust=True)
print(df.tail())
Open High Low Close Volume Date 2024-08-05 198.23 199.10 196.04 196.35 57285400 ...
Calculate the 50-day rolling mean on the Close column.
df['MA50'] = df['Close'].rolling(window=50).mean()
print(df[['Close','MA50']].tail())
Create a two-panel chart: price on top, volume on the bottom.
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 7), gridspec_kw={'height_ratios': [3, 1]}, sharex=True)
ax1.plot(df.index, df['Close'], label='Close', linewidth=1.5, color='#4f46e5')
ax1.plot(df.index, df['MA50'], label='50-day MA', linewidth=1.2, color='#f59e0b', linestyle='--')
ax1.set_title(f'{ticker} — 12-Month Price Chart')
ax1.set_ylabel('Price (USD)')
ax1.legend()
ax1.grid(alpha=0.3)
ax2.bar(df.index, df['Volume'], color='#64748b', alpha=0.5)
ax2.set_ylabel('Volume')
ax2.grid(alpha=0.3)
plt.tight_layout()
plt.savefig(f'{ticker}_chart.png', dpi=150)
print("Chart saved!")
Chart saved!
You can now pull and chart live stock data with three lines of code. Try comparing two tickers on the same axis using twin axes.
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.