|
| 1 | +import matplotlib |
| 2 | +matplotlib.use('Agg') |
| 3 | +import talib |
| 4 | +import pandas as pd |
| 5 | +import matplotlib.pyplot as plt |
| 6 | +import talib |
| 7 | +import numpy as np |
| 8 | +from langchain_core.tools import tool |
| 9 | +from typing import Annotated |
| 10 | +import mplfinance as mpf |
| 11 | +import base64 |
| 12 | +import io |
| 13 | +import mplfinance as mpf |
| 14 | +import color_style as color |
| 15 | + |
| 16 | + |
| 17 | +def generate_kline_image(kline_data) -> dict: |
| 18 | + """ |
| 19 | + Generate a candlestick (K-line) chart from OHLCV data, save it locally, and return a base64-encoded image. |
| 20 | +
|
| 21 | + Args: |
| 22 | + kline_data (dict): Dictionary with keys including 'Datetime', 'Open', 'High', 'Low', 'Close'. |
| 23 | + filename (str): Name of the file to save the image locally (default: 'kline_chart.png'). |
| 24 | +
|
| 25 | + Returns: |
| 26 | + dict: Dictionary containing base64-encoded image string and local file path. |
| 27 | + """ |
| 28 | + |
| 29 | + df = pd.DataFrame(kline_data) |
| 30 | + # take recent 40 |
| 31 | + df = df.tail(40) |
| 32 | + |
| 33 | + df.to_csv("record.csv", index=False, date_format="%Y-%m-%d %H:%M:%S") |
| 34 | + try: |
| 35 | + # df.index = pd.to_datetime(df["Datetime"]) |
| 36 | + df.index = pd.to_datetime(df["Datetime"], format="%Y-%m-%d %H:%M:%S") |
| 37 | + |
| 38 | + except ValueError: |
| 39 | + print("ValueError at graph_util.py\n") |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | + # Save image locally |
| 44 | + fig, axlist = mpf.plot( |
| 45 | + df[["Open", "High", "Low", "Close"]], |
| 46 | + type="candle", |
| 47 | + style=color.my_color_style, |
| 48 | + figsize=(12, 6), |
| 49 | + returnfig=True, |
| 50 | + block=False, |
| 51 | + |
| 52 | + ) |
| 53 | + axlist[0].set_ylabel('Price', fontweight='normal') |
| 54 | + axlist[0].set_xlabel('Datetime', fontweight='normal') |
| 55 | + |
| 56 | + fig.savefig( |
| 57 | + fname="kline_chart.png", |
| 58 | + dpi=600, |
| 59 | + bbox_inches="tight", |
| 60 | + pad_inches=0.1, |
| 61 | + ) |
| 62 | + plt.close(fig) |
| 63 | + # ---------- Encode to base64 ----------------- |
| 64 | + buf = io.BytesIO() |
| 65 | + fig.savefig(buf, format="png", dpi=600, bbox_inches="tight", pad_inches=0.1) |
| 66 | + plt.close(fig) # release memory |
| 67 | + |
| 68 | + buf.seek(0) |
| 69 | + img_b64 = base64.b64encode(buf.read()).decode("utf-8") |
| 70 | + |
| 71 | + return { |
| 72 | + "pattern_image": img_b64, |
| 73 | + "pattern_image_description": "Candlestick chart saved locally and returned as base64 string." |
| 74 | + } |
| 75 | + |
| 76 | +from graph_util import * |
| 77 | +def generate_trend_image(kline_data) -> dict: |
| 78 | + """ |
| 79 | + Generate a candlestick chart with trendlines from OHLCV data, |
| 80 | + save it locally as 'trend_graph.png', and return a base64-encoded image. |
| 81 | +
|
| 82 | + Returns: |
| 83 | + dict: base64 image and description |
| 84 | + """ |
| 85 | + data = pd.DataFrame(kline_data) |
| 86 | + candles = data.iloc[-50:].copy() |
| 87 | + |
| 88 | + candles["Datetime"] = pd.to_datetime(candles["Datetime"]) |
| 89 | + candles.set_index("Datetime", inplace=True) |
| 90 | + |
| 91 | + # Trendline fit functions assumed to be defined outside this scope |
| 92 | + support_coefs_c, resist_coefs_c = fit_trendlines_single(candles['Close']) |
| 93 | + support_coefs, resist_coefs = fit_trendlines_high_low(candles['High'], candles['Low'], candles['Close']) |
| 94 | + |
| 95 | + # Trendline values |
| 96 | + support_line_c = support_coefs_c[0] * np.arange(len(candles)) + support_coefs_c[1] |
| 97 | + resist_line_c = resist_coefs_c[0] * np.arange(len(candles)) + resist_coefs_c[1] |
| 98 | + support_line = support_coefs[0] * np.arange(len(candles)) + support_coefs[1] |
| 99 | + resist_line = resist_coefs[0] * np.arange(len(candles)) + resist_coefs[1] |
| 100 | + |
| 101 | + # Convert to time-anchored coordinates |
| 102 | + s_seq = get_line_points(candles, support_line) |
| 103 | + r_seq = get_line_points(candles, resist_line) |
| 104 | + s_seq2 = get_line_points(candles, support_line_c) |
| 105 | + r_seq2 = get_line_points(candles, resist_line_c) |
| 106 | + |
| 107 | + s_segments = split_line_into_segments(s_seq) |
| 108 | + r_segments = split_line_into_segments(r_seq) |
| 109 | + s2_segments = split_line_into_segments(s_seq2) |
| 110 | + r2_segments = split_line_into_segments(r_seq2) |
| 111 | + |
| 112 | + all_segments = s_segments + r_segments + s2_segments + r2_segments |
| 113 | + colors = ['white'] * len(s_segments) + ['white'] * len(r_segments) + ['blue'] * len(s2_segments) + ['red'] * len(r2_segments) |
| 114 | + |
| 115 | + # Create addplot lines for close-based support/resistance |
| 116 | + apds = [ |
| 117 | + mpf.make_addplot(support_line_c, color='blue', width=1, label="Close Support"), |
| 118 | + mpf.make_addplot(resist_line_c, color='red', width=1, label="Close Resistance") |
| 119 | + ] |
| 120 | + |
| 121 | + # Generate figure with legend and save locally |
| 122 | + fig, axlist = mpf.plot( |
| 123 | + candles, |
| 124 | + type='candle', |
| 125 | + style=color.my_color_style, |
| 126 | + addplot=apds, |
| 127 | + alines=dict(alines=all_segments, colors=colors, linewidths=1), |
| 128 | + returnfig=True, |
| 129 | + figsize=(12, 6), |
| 130 | + block=False, |
| 131 | + ) |
| 132 | + |
| 133 | + axlist[0].set_ylabel('Price', fontweight='normal') |
| 134 | + axlist[0].set_xlabel('Datetime', fontweight='normal') |
| 135 | + |
| 136 | + #save fig locally |
| 137 | + fig.savefig( |
| 138 | + "trend_graph.png", |
| 139 | + format="png", |
| 140 | + dpi=600, |
| 141 | + bbox_inches="tight", |
| 142 | + pad_inches=0.1 |
| 143 | + ) |
| 144 | + plt.close(fig) |
| 145 | + |
| 146 | + # Add legend manually |
| 147 | + axlist[0].legend(loc='upper left') |
| 148 | + |
| 149 | + # Save to base64 |
| 150 | + buf = io.BytesIO() |
| 151 | + fig.savefig(buf, format="png") |
| 152 | + buf.seek(0) |
| 153 | + img_b64 = base64.b64encode(buf.read()).decode("utf-8") |
| 154 | + plt.close(fig) |
| 155 | + |
| 156 | + return { |
| 157 | + "trend_image": img_b64, |
| 158 | + "trend_image_description": "Trend-enhanced candlestick chart with support/resistance lines." |
| 159 | + } |
0 commit comments