Project 16: Stock Sparkline Dashboard 📈¶
Difficulty: 🟡 Intermediate
Run cells top to bottom. Each step builds on the previous one and saves real files under outputs/stock_sparkline_dashboard/.
Description¶
Simulate stock price data and build a sparkline dashboard — learn time series without needing a live API.
Libraries & Modules¶
pandas— time series,date_rangenumpy— random walkmatplotlib.pyplot
Python Concepts You'll Practice¶
Time series, random walks, subplots, moving averages
🎛️ Parameter Variations¶
DAYS— 30 vs 365 trading daysSTART_PRICE,VOLATILITY— market characterTICKER— display nameSHOW_MA— moving average window (0 to disable)
In [1]:
# Install dependencies for this project (safe to re-run)
import sys
!{sys.executable} -m pip install pillow numpy matplotlib wordcloud qrcode[pil] python-barcode fpdf2 jinja2 folium plotly pandas scipy ipywidgets -q
Skipping pip install (already installed)
In [2]:
# Interactive Jupyter setup — run this cell first
%matplotlib inline
from pathlib import Path
from IPython.display import display, Image as IPImage, HTML, Markdown, Audio, IFrame
OUTPUT_DIR = Path("outputs") / "stock_sparkline_dashboard"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
print(f"✅ Outputs folder: {OUTPUT_DIR.resolve()}")
✅ Outputs folder: C:\Users\Hansel Yan\Projects\CodeItAll\outputs\stock_sparkline_dashboard
Step 1 — Simulate price history¶
In [3]:
import numpy as np
import pandas as pd
# 🎛️ TWEAK THESE
TICKER = "PYTH"
DAYS = 90
START_PRICE = 100.0
VOLATILITY = 0.02
SEED = 7
np.random.seed(SEED)
returns = np.random.normal(0.0005, VOLATILITY, DAYS)
prices = START_PRICE * np.cumprod(1 + returns)
dates = pd.date_range(end=pd.Timestamp.today(), periods=DAYS, freq="B")
df = pd.DataFrame({"date": dates, "close": prices})
df["ma20"] = df["close"].rolling(20, min_periods=1).mean()
df.tail()
Out[3]:
| date | close | ma20 | |
|---|---|---|---|
| 85 | 2026-07-07 20:05:34.537374 | 93.277238 | 92.550143 |
| 86 | 2026-07-08 20:05:34.537374 | 92.764752 | 92.634169 |
| 87 | 2026-07-09 20:05:34.537374 | 95.217239 | 92.934182 |
| 88 | 2026-07-10 20:05:34.537374 | 98.177695 | 93.406771 |
| 89 | 2026-07-13 20:05:34.537374 | 99.541222 | 94.050012 |
Step 2 — Sparkline dashboard¶
In [4]:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# 🎛️ TWEAK THESE
SHOW_MA = 20
COLOR_UP = "#00b894"
COLOR_MA = "#fdcb6e"
fig, axes = plt.subplots(2, 1, figsize=(12, 6), gridspec_kw={"height_ratios": [3, 1]})
# Main price chart
ax1 = axes[0]
ax1.plot(df["date"], df["close"], color=COLOR_UP, linewidth=2, label="Close")
if SHOW_MA:
ax1.plot(df["date"], df["ma20"], color=COLOR_MA, linewidth=1.5, linestyle="--", label=f"MA{SHOW_MA}")
ax1.fill_between(df["date"], df["close"], alpha=0.15, color=COLOR_UP)
ax1.set_title(f"{TICKER} — Stock Sparkline Dashboard (CodeItAll)", fontsize=14)
ax1.legend()
ax1.grid(alpha=0.3)
# Daily returns sparkline
daily_ret = df["close"].pct_change().fillna(0)
colors = ["#d63031" if r < 0 else "#00b894" for r in daily_ret]
axes[1].bar(df["date"], daily_ret * 100, color=colors, width=0.8)
axes[1].set_ylabel("Return %")
axes[1].xaxis.set_major_formatter(mdates.DateFormatter("%b %d"))
plt.tight_layout()
out = OUTPUT_DIR / "stock_sparkline.png"
fig.savefig(out, dpi=120)
plt.show()
csv_out = OUTPUT_DIR / "stock_data.csv"
df.to_csv(csv_out, index=False)
print(f"Chart: {out}\nData: {csv_out}")
Chart: outputs\stock_sparkline_dashboard\stock_sparkline.png Data: outputs\stock_sparkline_dashboard\stock_data.csv