|
| 1 | +"""pyplots.ai |
| 2 | +indicator-bollinger: Bollinger Bands Indicator Chart |
| 3 | +Library: seaborn | Python 3.13 |
| 4 | +Quality: pending | Created: 2026-01-07 |
| 5 | +""" |
| 6 | + |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +import numpy as np |
| 9 | +import pandas as pd |
| 10 | +import seaborn as sns |
| 11 | + |
| 12 | + |
| 13 | +# Data - Generate realistic stock price data with Bollinger Bands |
| 14 | +np.random.seed(42) |
| 15 | +n_days = 120 |
| 16 | + |
| 17 | +# Generate cumulative price movement (random walk with drift) |
| 18 | +dates = pd.date_range(start="2025-07-01", periods=n_days, freq="B") # Business days |
| 19 | +returns = np.random.normal(0.0005, 0.015, n_days) # Small positive drift, realistic volatility |
| 20 | +price_base = 150.0 |
| 21 | +close = price_base * np.cumprod(1 + returns) |
| 22 | + |
| 23 | +# Calculate Bollinger Bands (20-period SMA, 2 standard deviations) |
| 24 | +window = 20 |
| 25 | +df = pd.DataFrame({"date": dates, "close": close}) |
| 26 | +df["sma"] = df["close"].rolling(window=window).mean() |
| 27 | +df["std"] = df["close"].rolling(window=window).std() |
| 28 | +df["upper_band"] = df["sma"] + 2 * df["std"] |
| 29 | +df["lower_band"] = df["sma"] - 2 * df["std"] |
| 30 | + |
| 31 | +# Drop NaN values from rolling calculations |
| 32 | +df = df.dropna().reset_index(drop=True) |
| 33 | + |
| 34 | +# Plot |
| 35 | +fig, ax = plt.subplots(figsize=(16, 9)) |
| 36 | + |
| 37 | +# Fill between upper and lower bands |
| 38 | +ax.fill_between( |
| 39 | + df["date"], df["lower_band"], df["upper_band"], alpha=0.25, color="#306998", label="Bollinger Bands (±2σ)" |
| 40 | +) |
| 41 | + |
| 42 | +# Plot the bands and price using seaborn |
| 43 | +sns.lineplot(data=df, x="date", y="upper_band", ax=ax, color="#306998", linewidth=2, linestyle="-", label="Upper Band") |
| 44 | +sns.lineplot(data=df, x="date", y="lower_band", ax=ax, color="#306998", linewidth=2, linestyle="-", label="Lower Band") |
| 45 | +sns.lineplot(data=df, x="date", y="sma", ax=ax, color="#FFD43B", linewidth=2.5, linestyle="--", label="20-day SMA") |
| 46 | +sns.lineplot(data=df, x="date", y="close", ax=ax, color="#1a1a2e", linewidth=3, label="Close Price") |
| 47 | + |
| 48 | +# Styling |
| 49 | +ax.set_xlabel("Date", fontsize=20) |
| 50 | +ax.set_ylabel("Price ($)", fontsize=20) |
| 51 | +ax.set_title("indicator-bollinger · seaborn · pyplots.ai", fontsize=24) |
| 52 | +ax.tick_params(axis="both", labelsize=16) |
| 53 | +ax.grid(True, alpha=0.3, linestyle="--") |
| 54 | + |
| 55 | +# Legend |
| 56 | +ax.legend(loc="upper left", fontsize=14, framealpha=0.9) |
| 57 | + |
| 58 | +# Format x-axis dates |
| 59 | +fig.autofmt_xdate(rotation=30) |
| 60 | + |
| 61 | +plt.tight_layout() |
| 62 | +plt.savefig("plot.png", dpi=300, bbox_inches="tight") |
0 commit comments