""" TradingView-Style Chart Image Generator Generates realistic candlestick charts with indicators. """ import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.dates as mdates from matplotlib.patches import FancyBboxPatch import matplotlib.patches as mpatches import numpy as np import pandas as pd from typing import Optional, List, Dict, Any import os # TradingView color scheme TV_BG = "#0e1117" TV_FG = "#d1d4dc" TV_GRID = "#1e222d" TV_RED = "#ef5350" TV_GREEN = "#26a69a" TV_BLUE = "#2962ff" TV_ORANGE = "#ff9800" TV_PURPLE = "#ab47bc" TV_YELLOW = "#ffeb3b" TV_CYAN = "#00bcd4" def generate_chart_image( df: pd.DataFrame, symbol: str, timeframe: str, output_path: str, indicators: Optional[Dict[str, Any]] = None, show_volume: bool = True, show_sma: Optional[List[int]] = None, show_ema: Optional[List[int]] = None, show_bollinger: bool = False, show_vwap: bool = False, show_support_resistance: bool = False, support_levels: Optional[List[float]] = None, resistance_levels: Optional[List[float]] = None, show_pattern_annotation: bool = False, pattern_name: Optional[str] = None, figsize: tuple = (12, 8), dpi: int = 150, ) -> str: """ Generate a TradingView-style chart image. Returns the output file path. """ # Determine subplot layout n_subplots = 1 # Main price chart if show_volume: n_subplots += 1 if indicators and "rsi" in indicators: n_subplots += 1 if indicators and "macd" in indicators: n_subplots += 1 # Height ratios height_ratios = [3] if show_volume: height_ratios.append(0.8) if indicators and "rsi" in indicators: height_ratios.append(1.0) if indicators and "macd" in indicators: height_ratios.append(1.0) fig, axes = plt.subplots( n_subplots, 1, figsize=figsize, gridspec_kw={"height_ratios": height_ratios}, sharex=True, ) if n_subplots == 1: axes = [axes] fig.patch.set_facecolor(TV_BG) for ax in axes: ax.set_facecolor(TV_BG) ax.tick_params(colors=TV_FG, which="both") for spine in ax.spines.values(): spine.set_color(TV_GRID) ax.grid(True, alpha=0.15, color=TV_GRID) ax_main = axes[0] date_nums = mdates.date2num(df.index) # Plot candlesticks up = df["close"] >= df["open"] down = ~up width = 0.6 width2 = 0.1 # Green candles (up) ax_main.bar( date_nums[up], df["close"][up] - df["open"][up], width, bottom=df["open"][up], color=TV_GREEN, edgecolor=TV_GREEN, linewidth=0.5, ) ax_main.bar( date_nums[up], df["high"][up] - df["close"][up], width2, bottom=df["close"][up], color=TV_GREEN, edgecolor=TV_GREEN, ) ax_main.bar( date_nums[up], df["open"][up] - df["low"][up], width2, bottom=df["low"][up], color=TV_GREEN, edgecolor=TV_GREEN, ) # Red candles (down) ax_main.bar( date_nums[down], df["open"][down] - df["close"][down], width, bottom=df["close"][down], color=TV_RED, edgecolor=TV_RED, linewidth=0.5, ) ax_main.bar( date_nums[down], df["high"][down] - df["open"][down], width2, bottom=df["open"][down], color=TV_RED, edgecolor=TV_RED, ) ax_main.bar( date_nums[down], df["close"][down] - df["low"][down], width2, bottom=df["low"][down], color=TV_RED, edgecolor=TV_RED, ) # Plot moving averages if show_sma: colors = [TV_BLUE, TV_ORANGE, TV_PURPLE, TV_CYAN] for i, period in enumerate(show_sma): col = f"sma_{period}" if col in df.columns: ax_main.plot( date_nums, df[col], color=colors[i % len(colors)], linewidth=0.8, alpha=0.8, label=f"SMA {period}", ) if show_ema: colors = [TV_YELLOW, TV_CYAN, TV_ORANGE, TV_BLUE] for i, period in enumerate(show_ema): col = f"ema_{period}" if col in df.columns: ax_main.plot( date_nums, df[col], color=colors[i % len(colors)], linewidth=0.8, alpha=0.8, linestyle="--", label=f"EMA {period}", ) # Bollinger Bands if show_bollinger and "bb_upper" in df.columns: ax_main.plot(date_nums, df["bb_upper"], color=TV_BLUE, linewidth=0.5, alpha=0.5) ax_main.plot(date_nums, df["bb_lower"], color=TV_BLUE, linewidth=0.5, alpha=0.5) ax_main.fill_between( date_nums, df["bb_upper"], df["bb_lower"], color=TV_BLUE, alpha=0.05, ) # VWAP if show_vwap and "vwap" in df.columns: ax_main.plot( date_nums, df["vwap"], color=TV_PURPLE, linewidth=0.8, alpha=0.7, linestyle=":", label="VWAP", ) # Support/Resistance if show_support_resistance: if support_levels: for level in support_levels: ax_main.axhline( y=level, color=TV_GREEN, linewidth=0.8, linestyle="--", alpha=0.6, ) if resistance_levels: for level in resistance_levels: ax_main.axhline( y=level, color=TV_RED, linewidth=0.8, linestyle="--", alpha=0.6, ) # Pattern annotation if show_pattern_annotation and pattern_name: ax_main.annotate( pattern_name, xy=(date_nums[len(date_nums) // 2], df["high"].iloc[len(date_nums) // 2]), fontsize=10, color=TV_YELLOW, ha="center", va="bottom", bbox=dict(boxstyle="round,pad=0.3", facecolor=TV_BG, edgecolor=TV_YELLOW, alpha=0.8), ) # Title ax_main.set_title( f"{symbol} | {timeframe}", color=TV_FG, fontsize=12, fontweight="bold", ) # Volume subplot current_ax = 1 if show_volume: ax_vol = axes[current_ax] vol_colors = [ TV_GREEN if df["close"].iloc[i] >= df["open"].iloc[i] else TV_RED for i in range(len(df)) ] ax_vol.bar(date_nums, df["volume"], width, color=vol_colors, alpha=0.7) ax_vol.set_ylabel("Volume", color=TV_FG, fontsize=8) if "volume_sma_20" in df.columns: ax_vol.plot( date_nums, df["volume_sma_20"], color=TV_ORANGE, linewidth=0.6, alpha=0.7, ) current_ax += 1 # RSI subplot if indicators and "rsi" in indicators and "rsi_14" in df.columns: ax_rsi = axes[current_ax] ax_rsi.plot(date_nums, df["rsi_14"], color=TV_PURPLE, linewidth=0.8) ax_rsi.axhline(y=70, color=TV_RED, linewidth=0.5, linestyle="--", alpha=0.5) ax_rsi.axhline(y=30, color=TV_GREEN, linewidth=0.5, linestyle="--", alpha=0.5) ax_rsi.fill_between(date_nums, 70, 100, color=TV_RED, alpha=0.05) ax_rsi.fill_between(date_nums, 0, 30, color=TV_GREEN, alpha=0.05) ax_rsi.set_ylim(0, 100) ax_rsi.set_ylabel("RSI", color=TV_FG, fontsize=8) current_ax += 1 # MACD subplot if indicators and "macd" in indicators and "macd" in df.columns: ax_macd = axes[current_ax] ax_macd.plot(date_nums, df["macd"], color=TV_BLUE, linewidth=0.8, label="MACD") ax_macd.plot(date_nums, df["macd_signal"], color=TV_ORANGE, linewidth=0.8, label="Signal") macd_hist = df["macd_histogram"] hist_colors = [TV_GREEN if v >= 0 else TV_RED for v in macd_hist] ax_macd.bar(date_nums, macd_hist, width, color=hist_colors, alpha=0.5) ax_macd.axhline(y=0, color=TV_FG, linewidth=0.3) ax_macd.set_ylabel("MACD", color=TV_FG, fontsize=8) ax_macd.legend( loc="upper left", fontsize=7, facecolor=TV_BG, edgecolor=TV_GRID, labelcolor=TV_FG, ) current_ax += 1 # X-axis formatting ax = axes[-1] ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d")) ax.xaxis.set_major_locator(mdates.AutoDateLocator()) plt.xticks(rotation=30, ha="right") # Legend (only if there are labeled artists) handles, labels = ax_main.get_legend_handles_labels() if handles: ax_main.legend( loc="upper left", fontsize=7, facecolor=TV_BG, edgecolor=TV_GRID, labelcolor=TV_FG, ) plt.tight_layout() fig.savefig(output_path, dpi=dpi, bbox_inches="tight", facecolor=TV_BG) plt.close(fig) return output_path def generate_chart_grid( df: pd.DataFrame, symbol: str, timeframe: str, output_path: str, n_candles: int = 60, start_idx: int = 0, ) -> str: """Generate a clean chart with a specific window of candles.""" end_idx = min(start_idx + n_candles, len(df)) window = df.iloc[start_idx:end_idx] if len(window) < 20: return "" return generate_chart_image( window, symbol, timeframe, output_path, show_volume=True, show_sma=[20, 50], show_ema=[9], show_bollinger=False, show_vwap=False, )