mgbam commited on
Commit
1fd5d5f
·
verified ·
1 Parent(s): c8301ac

Create app/chart_generator.py

Browse files
Files changed (1) hide show
  1. app/chart_generator.py +71 -0
app/chart_generator.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generates and visualizes market data charts correlated with news events.
3
+ """
4
+ import io
5
+ import base64
6
+ import pandas as pd
7
+ import matplotlib.pyplot as plt
8
+ import matplotlib.dates as mdates
9
+
10
+ def generate_price_chart(price_data: list, event_timestamp: pd.Timestamp, entity: str) -> str:
11
+ """
12
+ Generates a base64-encoded price chart image with an event annotation.
13
+
14
+ Args:
15
+ price_data: A list of [timestamp, price] pairs from CoinGecko.
16
+ event_timestamp: The timestamp of the news event.
17
+ entity: The cryptocurrency entity (e.g., 'Bitcoin').
18
+
19
+ Returns:
20
+ A base64 encoded string of the PNG chart image.
21
+ """
22
+ if not price_data:
23
+ return ""
24
+
25
+ # Use a dark theme for the chart
26
+ plt.style.use('dark_background')
27
+
28
+ # Create a pandas DataFrame
29
+ df = pd.DataFrame(price_data, columns=['timestamp', 'price'])
30
+ df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
31
+ df = df.set_index('timestamp')
32
+
33
+ fig, ax = plt.subplots(figsize=(10, 4))
34
+
35
+ # Plot the price data
36
+ ax.plot(df.index, df['price'], color='cyan', linewidth=2)
37
+
38
+ # Annotate the event
39
+ try:
40
+ event_price = df.asof(event_timestamp)['price']
41
+ ax.axvline(event_timestamp, color='red', linestyle='--', linewidth=1.5, label=f'Event: {entity}')
42
+ ax.plot(event_timestamp, event_price, 'ro', markersize=8) # Red dot on the event
43
+ ax.annotate(f'Event',
44
+ xy=(event_timestamp, event_price),
45
+ xytext=(event_timestamp, event_price * 1.01),
46
+ ha='center',
47
+ arrowprops=dict(facecolor='white', shrink=0.05, width=1, headwidth=4),
48
+ bbox=dict(boxstyle='round,pad=0.3', fc='yellow', ec='k', lw=1, alpha=0.8),
49
+ color='black'
50
+ )
51
+ except KeyError:
52
+ # Event timestamp might be out of range
53
+ ax.axvline(event_timestamp, color='red', linestyle='--', linewidth=1.5)
54
+
55
+ # Formatting the chart
56
+ ax.set_title(f'{entity.upper()} Price Action around Event', fontsize=14)
57
+ ax.set_ylabel('Price (USD)')
58
+ ax.grid(True, linestyle='--', alpha=0.3)
59
+ fig.autofmt_xdate()
60
+ ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
61
+ ax.tick_params(axis='x', rotation=45)
62
+ plt.tight_layout()
63
+
64
+ # Save to an in-memory buffer
65
+ buf = io.BytesIO()
66
+ fig.savefig(buf, format='png', transparent=True)
67
+ buf.seek(0)
68
+ img_base64 = base64.b64encode(buf.read()).decode('utf-8')
69
+ plt.close(fig)
70
+
71
+ return f"data:image/png;base64,{img_base64}"