-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchart_service.py
More file actions
182 lines (148 loc) · 6.95 KB
/
chart_service.py
File metadata and controls
182 lines (148 loc) · 6.95 KB
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
"""
Chart generation service using matplotlib.
"""
import io
import logging
from datetime import datetime
from typing import Optional
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
logger = logging.getLogger(__name__)
class ChartService:
def _format_price(self, price: float) -> str:
"""Format price nicely."""
if price >= 10000:
return f"${price:,.0f}"
elif price >= 100:
return f"${price:,.2f}"
elif price >= 1:
return f"${price:.4f}"
else:
return f"${price:.6f}"
def generate_price_chart(
self,
timestamps: list,
prices: list,
crypto_name: str,
timeframe: str = "24h",
hours: int = 24
) -> Optional[bytes]:
"""Generate a price chart and return as PNG bytes."""
if not timestamps or not prices or len(timestamps) < 2:
return None
try:
fig = plt.figure(figsize=(14, 8), facecolor='#0d1117')
ax = fig.add_subplot(111, facecolor='#0d1117')
dates = [datetime.fromtimestamp(ts) for ts in timestamps]
prices_arr = np.array(prices)
start_price = prices[0]
end_price = prices[-1]
change = ((end_price - start_price) / start_price) * 100
line_color = '#00d26a' if change >= 0 else '#ff4757'
ax.plot(dates, prices_arr, color=line_color, linewidth=2.5, zorder=3)
ax.fill_between(dates, prices_arr,
alpha=0.15, color=line_color, zorder=2)
ax.scatter(dates, prices_arr, color=line_color, s=30, zorder=4,
edgecolors='#0d1117', linewidths=0.5)
min_idx = np.argmin(prices_arr)
max_idx = np.argmax(prices_arr)
ax.scatter(dates[min_idx], prices_arr[min_idx], color='#ff4757',
s=100, zorder=5, marker='v', edgecolors='white', linewidths=1)
ax.scatter(dates[max_idx], prices_arr[max_idx], color='#00d26a',
s=100, zorder=5, marker='^', edgecolors='white', linewidths=1)
ax.annotate(f'LOW\n{self._format_price(prices_arr[min_idx])}',
xy=(dates[min_idx], prices_arr[min_idx]),
xytext=(10, -30), textcoords='offset points',
fontsize=8, color='#888888',
bbox=dict(boxstyle='round,pad=0.3', facecolor='#161b22',
edgecolor='#30363d', pad=0.3),
arrowprops=dict(arrowstyle='->', color='#ff4757', lw=1))
ax.annotate(f'HIGH\n{self._format_price(prices_arr[max_idx])}',
xy=(dates[max_idx], prices_arr[max_idx]),
xytext=(10, 20), textcoords='offset points',
fontsize=8, color='#888888',
bbox=dict(boxstyle='round,pad=0.3', facecolor='#161b22',
edgecolor='#30363d', pad=0.3),
arrowprops=dict(arrowstyle='->', color='#00d26a', lw=1))
ax.annotate(f'{self._format_price(end_price)}',
xy=(dates[-1], prices_arr[-1]),
xytext=(10, 0), textcoords='offset points',
fontsize=11, color=line_color, fontweight='bold',
bbox=dict(boxstyle='round,pad=0.4', facecolor='#161b22',
edgecolor=line_color, pad=0.4),
arrowprops=dict(arrowstyle='->', color=line_color, lw=1))
ax.set_title(
f'{crypto_name} | {timeframe} | {change:+.2f}%',
fontsize=16, fontweight='bold', color='white',
pad=20, loc='center'
)
ax.set_ylabel('Price (USD)', fontsize=11, color='#888888', labelpad=10)
ax.set_xlabel('Time', fontsize=11, color='#888888', labelpad=10)
ax.tick_params(colors='#888888', labelsize=9)
ax.spines['bottom'].set_color('#30363d')
ax.spines['left'].set_color('#30363d')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
if hours <= 24:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
elif hours <= 168:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d %H:%M'))
else:
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %d'))
ax.xaxis.set_major_locator(mdates.AutoDateLocator())
price_min = min(prices_arr)
price_max = max(prices_arr)
price_range = price_max - price_min
ax.set_ylim(price_min - price_range * 0.1, price_max + price_range * 0.15)
fig.autofmt_xdate()
ax.grid(True, alpha=0.1, color='#30363d', linestyle='--', zorder=1)
for spine in ax.spines.values():
spine.set_zorder(0)
buf = io.BytesIO()
plt.savefig(
buf,
format='png',
bbox_inches='tight',
facecolor='#0d1117',
edgecolor='none',
dpi=100
)
buf.seek(0)
plt.close(fig)
return buf.read()
except Exception as e:
logger.error(f"Failed to generate chart for {crypto_name}: {e}")
return None
def _downsample(self, timestamps: list, prices: list, max_points: int = 500) -> tuple:
"""Downsample data to max_points for performance."""
if len(timestamps) <= max_points:
return timestamps, prices
step = len(timestamps) // max_points
return timestamps[::step], prices[::step]
async def get_chart_bytes(
self,
db,
crypto: str,
hours: int = 24,
timeframe_str: str = None
) -> Optional[bytes]:
"""Get price history from DB and generate chart."""
limit = 1000
history = await db.get_price_history(crypto, hours=hours, limit=limit)
if not history or len(history) < 2:
return None
timestamps = [h[0] for h in history]
prices = [float(h[1]) for h in history]
if not timeframe_str:
if hours <= 24:
timeframe_str = f"{hours}h"
elif hours <= 720:
timeframe_str = f"{hours//24}d"
elif hours <= 8760:
timeframe_str = f"{hours//24}d"
else:
timeframe_str = f"{hours//720}mo"
return self.generate_price_chart(timestamps, prices, crypto.upper(), timeframe_str, hours)