aromidvar commited on
Commit
8146f18
·
verified ·
1 Parent(s): 1bc6936

Update core/plot.py

Browse files
Files changed (1) hide show
  1. core/plot.py +217 -26
core/plot.py CHANGED
@@ -5,49 +5,240 @@ import logging
5
 
6
  logging.basicConfig(level=logging.DEBUG, filename="debug.log", filemode="a")
7
 
 
 
 
 
 
 
 
 
8
  def plot_indicators(df, ticker):
9
  try:
10
- logging.debug(f"Plotting indicators for {ticker}, df columns: {df.columns.tolist()}")
11
- fig = go.Figure()
12
- fig.add_trace(go.Scatter(x=df['Date'], y=df['value'], mode='lines', name='Price', line=dict(color='blue')))
13
- indicators = [col for col in df.columns if col.startswith(('sma_', 'ema_', 'rsi_', 'macd_', 'bb'))]
14
- for ind in indicators:
15
- if ind in df.columns:
16
- fig.add_trace(go.Scatter(x=df['Date'], y=df[ind], mode='lines', name=ind.upper()))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  fig.update_layout(
18
  title=f"{ticker} Price and Technical Indicators",
19
- xaxis_title="Date",
20
- yaxis_title="Value",
21
- template="plotly_dark",
22
- showlegend=True
 
 
 
 
 
 
23
  )
24
- logging.info(f"Indicators plot generated for {ticker}")
25
  return fig
26
  except Exception as e:
27
- logging.error(f"Error in plot_indicators: {str(e)}")
28
- return go.Figure()
29
 
30
- def plot_predictions(result, df, ticker):
 
31
  try:
32
- logging.debug(f"Plotting predictions for {ticker}")
33
- actual = result.get('actual', [])
34
- forecast = result.get('forecast', [])
 
35
  dates = df['Date'].iloc[-len(actual):]
36
  fig = go.Figure()
37
- fig.add_trace(go.Scatter(x=dates, y=actual, mode='lines', name='Actual', line=dict(color='blue')))
38
- fig.add_trace(go.Scatter(x=dates, y=forecast, mode='lines', name='Predicted', line=dict(color='orange')))
39
  fig.update_layout(
40
- title=f"{ticker} Price Predictions",
 
 
41
  xaxis_title="Date",
42
  yaxis_title="Price",
43
- template="plotly_dark",
44
- showlegend=True
 
 
45
  )
46
- logging.info(f"Predictions plot generated for {ticker}")
47
  return fig
48
  except Exception as e:
49
- logging.error(f"Error in plot_predictions: {str(e)}")
50
- return go.Figure()
 
 
51
 
52
  def plot_metrics(result, ticker):
53
  try:
 
5
 
6
  logging.basicConfig(level=logging.DEBUG, filename="debug.log", filemode="a")
7
 
8
+ import plotly.graph_objects as go
9
+ from plotly.subplots import make_subplots
10
+ import pandas as pd
11
+ import numpy as np
12
+ import logging
13
+
14
+ logging.basicConfig(level=logging.INFO)
15
+
16
  def plot_indicators(df, ticker):
17
  try:
18
+ fig = make_subplots(
19
+ rows=7, cols=1, shared_xaxes=True, vertical_spacing=0.03,
20
+ subplot_titles=(
21
+ 'Price & Moving Averages', 'Volume', 'MACD & RSI',
22
+ 'Stochastic & Williams %R', 'ADX & DI', 'ATR & CCI', 'Signal Strength'
23
+ ),
24
+ row_heights=[0.4, 0.1, 0.15, 0.15, 0.15, 0.15, 0.15]
25
+ )
26
+
27
+ # Price and Moving Averages
28
+ fig.add_trace(
29
+ go.Candlestick(
30
+ x=df['Date'], open=df['Open'], high=df['High'], low=df['Low'], close=df['value'],
31
+ name='Price', increasing_line_color='#00CC96', decreasing_line_color='#EF553B'
32
+ ), row=1, col=1
33
+ )
34
+ for ma in ['sma_10', 'sma_20', 'sma_50', 'ema_12', 'ema_26', 'ema_50']:
35
+ if ma in df:
36
+ fig.add_trace(
37
+ go.Scatter(x=df['Date'], y=df[ma], name=ma.upper(), line=dict(width=1.5)),
38
+ row=1, col=1
39
+ )
40
+ if 'bbu_20_2' in df:
41
+ fig.add_trace(
42
+ go.Scatter(x=df['Date'], y=df['bbu_20_2'], name='BB Upper', line=dict(color='gray', dash='dot')),
43
+ row=1, col=1
44
+ )
45
+ fig.add_trace(
46
+ go.Scatter(x=df['Date'], y=df['bbm_20_2'], name='BB Middle', line=dict(color='gray')),
47
+ row=1, col=1
48
+ )
49
+ fig.add_trace(
50
+ go.Scatter(x=df['Date'], y=df['bbl_20_2'], name='BB Lower', line=dict(color='gray', dash='dot')),
51
+ row=1, col=1
52
+ )
53
+
54
+ # Enhanced Signal Plotting
55
+ buy_signals = df[df['Signal'] == 'Buy']
56
+ sell_signals = df[df['Signal'] == 'Sell']
57
+ hold_signals = df[df['Signal'] == 'Hold']
58
+ fig.add_trace(
59
+ go.Scatter(
60
+ x=buy_signals['Date'], y=buy_signals['value'], mode='markers+text',
61
+ name='Buy', marker=dict(symbol='triangle-up', size=12, color='green'),
62
+ text=['Buy'] * len(buy_signals), textposition='top center'
63
+ ), row=1, col=1
64
+ )
65
+ fig.add_trace(
66
+ go.Scatter(
67
+ x=sell_signals['Date'], y=sell_signals['value'], mode='markers+text',
68
+ name='Sell', marker=dict(symbol='triangle-down', size=12, color='red'),
69
+ text=['Sell'] * len(sell_signals), textposition='bottom center'
70
+ ), row=1, col=1
71
+ )
72
+ fig.add_trace(
73
+ go.Scatter(
74
+ x=hold_signals['Date'], y=hold_signals['value'], mode='markers',
75
+ name='Hold', marker=dict(symbol='circle', size=8, color='gray'),
76
+ opacity=0.5
77
+ ), row=1, col=1
78
+ )
79
+
80
+ # Position Size and Risk Annotation
81
+ if 'atr_14' in df:
82
+ atr = df['atr_14'].iloc[-1]
83
+ stop_distance = atr * 2
84
+ position_size = (10000 * 0.01) / stop_distance
85
+ fig.add_annotation(
86
+ text=f"Position Size: {position_size:.0f} shares (1% risk, ATR {atr:.2f})",
87
+ xref="paper", yref="paper", x=0.05, y=0.95, showarrow=False,
88
+ font=dict(color="black", size=12)
89
+ )
90
+
91
+ # Volume
92
+ fig.add_trace(
93
+ go.Bar(x=df['Date'], y=df['Volume'], name='Volume', marker_color='blue', opacity=0.5),
94
+ row=2, col=1
95
+ )
96
+
97
+ # MACD & RSI
98
+ if 'macd_12_26_9' in df:
99
+ fig.add_trace(
100
+ go.Scatter(x=df['Date'], y=df['macd_12_26_9'], name='MACD', line=dict(color='blue')),
101
+ row=3, col=1
102
+ )
103
+ fig.add_trace(
104
+ go.Scatter(x=df['Date'], y=df['macds_12_26_9'], name='MACD Signal', line=dict(color='orange')),
105
+ row=3, col=1
106
+ )
107
+ fig.add_trace(
108
+ go.Bar(x=df['Date'], y=df['macdh_12_26_9'], name='MACD Hist', marker_color='gray'),
109
+ row=3, col=1
110
+ )
111
+ if 'rsi_14' in df:
112
+ fig.add_trace(
113
+ go.Scatter(x=df['Date'], y=df['rsi_14'], name='RSI 14', line=dict(color='purple')),
114
+ row=3, col=1
115
+ )
116
+ fig.add_hline(y=70, line_dash="dash", line_color="red", row=3, col=1)
117
+ fig.add_hline(y=30, line_dash="dash", line_color="green", row=3, col=1)
118
+ if 'rsi_21' in df:
119
+ fig.add_trace(
120
+ go.Scatter(x=df['Date'], y=df['rsi_21'], name='RSI 21', line=dict(color='magenta', dash='dash')),
121
+ row=3, col=1
122
+ )
123
+ if 'rsi_50' in df:
124
+ fig.add_trace(
125
+ go.Scatter(x=df['Date'], y=df['rsi_50'], name='RSI 50', line=dict(color='cyan', dash='dot')),
126
+ row=3, col=1
127
+ )
128
+
129
+ # Stochastic & Williams %R
130
+ if 'stochk_14_3_3' in df:
131
+ fig.add_trace(
132
+ go.Scatter(x=df['Date'], y=df['stochk_14_3_3'], name='Stoch %K', line=dict(color='blue')),
133
+ row=4, col=1
134
+ )
135
+ fig.add_trace(
136
+ go.Scatter(x=df['Date'], y=df['stochd_14_3_3'], name='Stoch %D', line=dict(color='orange')),
137
+ row=4, col=1
138
+ )
139
+ fig.add_hline(y=80, line_dash="dash", line_color="red", row=4, col=1)
140
+ fig.add_hline(y=20, line_dash="dash", line_color="green", row=4, col=1)
141
+ if 'willr_14' in df:
142
+ fig.add_trace(
143
+ go.Scatter(x=df['Date'], y=df['willr_14'], name='Williams %R', line=dict(color='green')),
144
+ row=4, col=1
145
+ )
146
+ fig.add_hline(y=-20, line_dash="dash", line_color="red", row=4, col=1)
147
+ fig.add_hline(y=-80, line_dash="dash", line_color="green", row=4, col=1)
148
+
149
+ # ADX & DI
150
+ if 'adx_14' in df:
151
+ fig.add_trace(
152
+ go.Scatter(x=df['Date'], y=df['adx_14'], name='ADX', line=dict(color='blue')),
153
+ row=5, col=1
154
+ )
155
+ fig.add_trace(
156
+ go.Scatter(x=df['Date'], y=df.get('pdi_14'), name='+DI', line=dict(color='green')),
157
+ row=5, col=1
158
+ )
159
+ fig.add_trace(
160
+ go.Scatter(x=df['Date'], y=df.get('mdi_14'), name='-DI', line=dict(color='red')),
161
+ row=5, col=1
162
+ )
163
+ fig.add_hline(y=25, line_dash="dash", line_color="black", row=5, col=1)
164
+
165
+ # ATR & CCI
166
+ if 'atr_14' in df:
167
+ fig.add_trace(
168
+ go.Scatter(x=df['Date'], y=df['atr_14'], name='ATR', line=dict(color='orange')),
169
+ row=6, col=1
170
+ )
171
+ if 'cci_20' in df:
172
+ fig.add_trace(
173
+ go.Scatter(x=df['Date'], y=df['cci_20'], name='CCI', line=dict(color='purple')),
174
+ row=6, col=1
175
+ )
176
+ fig.add_hline(y=100, line_dash="dash", line_color="red", row=6, col=1)
177
+ fig.add_hline(y=-100, line_dash="dash", line_color="green", row=6, col=1)
178
+
179
+ # Signal Strength Plot
180
+ if all(col in df for col in ['RSI_Signal', 'MACD_Signal', 'ADX_Signal', 'Sentiment_Signal', 'Model_Signal']):
181
+ signal_strength = (
182
+ df['RSI_Signal'].abs() +
183
+ df['MACD_Signal'].abs() +
184
+ df['ADX_Signal'].abs() +
185
+ df['Sentiment_Signal'].abs() +
186
+ df['Model_Signal'].abs()
187
+ )
188
+ fig.add_trace(
189
+ go.Scatter(
190
+ x=df['Date'], y=signal_strength, name='Signal Strength',
191
+ line=dict(color='teal'), fill='tozeroy'
192
+ ), row=7, col=1
193
+ )
194
+ fig.add_hline(y=3, line_dash="dash", line_color="orange", row=7, col=1, annotation_text="Strong Signal Threshold")
195
+
196
  fig.update_layout(
197
  title=f"{ticker} Price and Technical Indicators",
198
+ template="plotly_white",
199
+ height=2400,
200
+ width=1400,
201
+ showlegend=True,
202
+ xaxis_rangeslider_visible=False,
203
+ margin=dict(l=50, r=50, t=100, b=50),
204
+ xaxis=dict(tickformat="%Y-%m-%d", minor=dict(ticks="inside", showgrid=True), gridcolor="lightgrey"),
205
+ plot_bgcolor="white",
206
+ paper_bgcolor="white",
207
+ hovermode="x unified"
208
  )
 
209
  return fig
210
  except Exception as e:
211
+ logging.error(f"Plot indicators error: {e}")
212
+ return None
213
 
214
+ # Other plotting functions remain unchanged
215
+ def plot_forecast(result, df):
216
  try:
217
+ actual = result.get("actual", [])
218
+ forecast = result.get("forecast", [])
219
+ if not actual or not forecast:
220
+ return None
221
  dates = df['Date'].iloc[-len(actual):]
222
  fig = go.Figure()
223
+ fig.add_trace(go.Scatter(x=dates, y=actual, name='Actual', line=dict(color='blue')))
224
+ fig.add_trace(go.Scatter(x=dates, y=forecast, name='Forecast', line=dict(color='orange')))
225
  fig.update_layout(
226
+ title="Backtest: Actual vs Forecast",
227
+ template="plotly_white",
228
+ height=600,
229
  xaxis_title="Date",
230
  yaxis_title="Price",
231
+ xaxis=dict(tickformat="%Y-%m-%d", minor=dict(ticks="inside", showgrid=True), gridcolor="lightgrey"),
232
+ yaxis=dict(gridcolor="lightgrey"),
233
+ plot_bgcolor="white",
234
+ paper_bgcolor="white"
235
  )
 
236
  return fig
237
  except Exception as e:
238
+ logging.error(f"Plot forecast error: {e}")
239
+ return None
240
+
241
+ # ... (other plotting functions like plot_future_forecast, plot_metrics_r2, etc., remain as provided)
242
 
243
  def plot_metrics(result, ticker):
244
  try: