omniverse1 commited on
Commit
21bb68b
·
verified ·
1 Parent(s): 4c78965

Create plotter.py

Browse files
Files changed (1) hide show
  1. plotter.py +100 -0
plotter.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import mplfinance as mpf
3
+ from io import BytesIO
4
+ import base64
5
+ import matplotlib.pyplot as plt
6
+
7
+ def create_mplfinance_chart(df, ticker, predictions=None):
8
+ """
9
+ Creates a custom mplfinance candlestick chart and returns it as a base64 encoded image.
10
+ Style: white, black, with accent #f0f4f9.
11
+ """
12
+ if df.empty:
13
+ return None
14
+
15
+ # --- 1. Define Custom Style ---
16
+ mc = mpf.make_marketcolors(
17
+ up='green', down='red', # Candlestick body colors (yfinance default)
18
+ edge='inherit',
19
+ wick='black',
20
+ volume='#f0f4f9', # Accent color for volume
21
+ inherit=True
22
+ )
23
+
24
+ s = mpf.make_mpf_style(
25
+ base_mpf_style='nightclouds', # Start with a dark base
26
+ marketcolors=mc,
27
+ # Customize background and grid to achieve white/black contrast
28
+ facecolor='#f0f4f9', # Background accent color (very light gray/off-white)
29
+ edgecolor='black',
30
+ gridcolor='gray',
31
+ gridstyle=':',
32
+ figcolor='white',
33
+ rc={'axes.labelcolor': 'black',
34
+ 'xtick.color': 'black',
35
+ 'ytick.color': 'black',
36
+ 'figure.titlesize': 14,
37
+ 'axes.titlesize': 16}
38
+ )
39
+
40
+ # --- 2. Define Technical Indicators (Apanels) ---
41
+ apds = []
42
+ # MACD Subplot
43
+ apds.append(
44
+ mpf.make_addplot(df['MACD'], color='black', panel=2, title='MACD'),
45
+ )
46
+ apds.append(
47
+ mpf.make_addplot(df['MACD_signal'], color='#FFA500', panel=2),
48
+ )
49
+
50
+ # RSI Subplot
51
+ apds.append(
52
+ mpf.make_addplot(df['RSI'], color='red', panel=3, title='RSI', y_on_right=True),
53
+ )
54
+
55
+ # Overlays on Main Chart (MAs and BB)
56
+ apds.extend([
57
+ mpf.make_addplot(df['SMA_20'], color='#FFD700', linestyle='-', width=1.5),
58
+ mpf.make_addplot(df['SMA_50'], color='#FFA500', linestyle='-', width=1.5),
59
+ mpf.make_addplot(df['BB_upper'], color='grey', linestyle='--', width=0.5),
60
+ mpf.make_addplot(df['BB_lower'], color='grey', linestyle='--', width=0.5),
61
+ ])
62
+
63
+ # --- 3. Prediction Plotting (Trace as Overlay) ---
64
+ if predictions is not None and predictions.any():
65
+
66
+ # Calculate future index (assuming daily frequency for simplicity)
67
+ last_date = df.index[-1]
68
+ future_index = pd.date_range(start=last_date, periods=len(predictions) + 1, freq=df.index.freq or 'D')[1:]
69
+
70
+ # Create a series to align with the main DataFrame index for plotting
71
+ future_series = pd.Series(predictions, index=future_index)
72
+
73
+ # Create an 'scatter' addplot for the prediction line
74
+ apds.append(
75
+ mpf.make_addplot(future_series, color='blue', linestyle='-.', width=2, marker='o', markersize=5)
76
+ )
77
+
78
+ # --- 4. Plotting ---
79
+ fig, axes = mpf.plot(
80
+ df,
81
+ type='candle',
82
+ style=s,
83
+ title=f'{ticker} Price Chart and Analysis',
84
+ ylabel='Price (USD)',
85
+ volume=True,
86
+ volume_panel=1,
87
+ addplot=apds,
88
+ figratio=(16,9),
89
+ figscale=1.5,
90
+ returnfig=True
91
+ )
92
+
93
+ # --- 5. Convert to Base64 (for Gradio) ---
94
+ buf = BytesIO()
95
+ fig.savefig(buf, format='png', bbox_inches='tight')
96
+ plt.close(fig) # Close the figure to free memory
97
+ image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
98
+
99
+ # Gradio expects an HTML tag for raw HTML image display
100
+ return f'<img src="data:image/png;base64,{image_base64}" style="width: 100%; height: auto;">'