File size: 9,305 Bytes
922bf26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""
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,
    )