{"spec_id":"indicator-rsi","library":"matplotlib","language":"python","code":"\"\"\" anyplot.ai\nindicator-rsi: RSI Technical Indicator Chart\nLibrary: matplotlib 3.10.9 | Python 3.13.13\nQuality: 94/100 | Updated: 2026-05-16\n\"\"\"\n\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n\n# Theme tokens\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\nINK_MUTED = \"#6B6A63\" if THEME == \"light\" else \"#A8A79F\"\n\nBRAND = \"#009E73\"  # Okabe-Ito position 1\n\n# Data - Generate synthetic stock price data and calculate RSI\nnp.random.seed(42)\nn_periods = 120\n\n# Create trending market with volatility spikes to showcase full RSI range\ndates = pd.date_range(\"2024-01-01\", periods=n_periods, freq=\"D\")\ntrend = np.linspace(0, 0.15, n_periods)\nvolatility = np.concatenate(\n    [\n        np.full(30, 0.015),  # Low volatility\n        np.full(30, 0.035),  # High volatility\n        np.full(30, 0.025),  # Medium\n        np.full(30, 0.04),  # Very high\n    ]\n)\nreturns = np.random.normal(0.0005, 1, n_periods) * volatility + trend / n_periods\nprices = 100 * np.cumprod(1 + returns)\n\n# Calculate RSI using 14-period lookback\nperiod = 14\ndelta = np.diff(prices)\ngains = np.where(delta > 0, delta, 0)\nlosses = np.where(delta < 0, -delta, 0)\n\navg_gain = np.zeros(len(delta))\navg_loss = np.zeros(len(delta))\navg_gain[period - 1] = np.mean(gains[:period])\navg_loss[period - 1] = np.mean(losses[:period])\n\nfor i in range(period, len(delta)):\n    avg_gain[i] = (avg_gain[i - 1] * (period - 1) + gains[i]) / period\n    avg_loss[i] = (avg_loss[i - 1] * (period - 1) + losses[i]) / period\n\nrs = np.divide(avg_gain, avg_loss, out=np.ones_like(avg_gain), where=avg_loss != 0)\nrsi = 100 - (100 / (1 + rs))\nrsi = rsi[period - 1 :]\nrsi_dates = dates[period:]\n\ndf = pd.DataFrame({\"date\": rsi_dates, \"rsi\": rsi})\n\n# Plot\nfig, ax = plt.subplots(figsize=(16, 9), facecolor=PAGE_BG)\nax.set_facecolor(PAGE_BG)\n\n# Shade overbought zone (70-100) — imprint red, semantic danger\nax.fill_between(df[\"date\"], 70, 100, alpha=0.12, color=\"#AE3030\")\n\n# Shade oversold zone (0-30)\nax.fill_between(df[\"date\"], 0, 30, alpha=0.12, color=\"#4467A3\")\n\n# Plot RSI line using brand color\nax.plot(df[\"date\"], df[\"rsi\"], color=BRAND, linewidth=3, label=\"RSI (14-period)\")\n\n# Add horizontal reference lines\nax.axhline(y=70, color=INK_SOFT, linestyle=\"--\", linewidth=2, alpha=0.5)\nax.axhline(y=30, color=INK_SOFT, linestyle=\"--\", linewidth=2, alpha=0.5)\nax.axhline(y=50, color=INK_SOFT, linestyle=\":\", linewidth=1.5, alpha=0.3)\n\n# Set fixed y-axis from 0 to 100\nax.set_ylim(0, 100)\nax.set_xlim(df[\"date\"].min(), df[\"date\"].max())\n\n# Labels and styling\nax.set_xlabel(\"Date\", fontsize=20, color=INK)\nax.set_ylabel(\"RSI Value\", fontsize=20, color=INK)\nax.set_title(\"indicator-rsi · matplotlib · anyplot.ai\", fontsize=24, fontweight=\"medium\", color=INK)\nax.tick_params(axis=\"both\", labelsize=16, colors=INK_SOFT, labelcolor=INK_SOFT)\n\n# Add text annotations for threshold levels\nax.text(df[\"date\"].iloc[-1], 72, \"Overbought\", fontsize=13, color=INK_SOFT, ha=\"right\", va=\"bottom\")\nax.text(df[\"date\"].iloc[-1], 28, \"Oversold\", fontsize=13, color=INK_SOFT, ha=\"right\", va=\"top\")\n\n# Grid and legend\nax.grid(True, alpha=0.1, linewidth=0.8, color=INK)\nax.yaxis.grid(True, alpha=0.1, linewidth=0.8, color=INK)\nax.xaxis.grid(False)\n\nleg = ax.legend(fontsize=16, loc=\"upper left\")\nif leg:\n    leg.get_frame().set_facecolor(ELEVATED_BG)\n    leg.get_frame().set_edgecolor(INK_SOFT)\n    leg.get_frame().set_alpha(0.95)\n    plt.setp(leg.get_texts(), color=INK_SOFT)\n\n# Spine styling\nfor s in (\"left\", \"bottom\"):\n    ax.spines[s].set_color(INK_SOFT)\nax.spines[\"top\"].set_visible(False)\nax.spines[\"right\"].set_visible(False)\n\nplt.tight_layout()\nplt.savefig(f\"plot-{THEME}.png\", dpi=300, bbox_inches=\"tight\", facecolor=PAGE_BG)\n"}