omniverse1 commited on
Commit
d8b4363
·
verified ·
1 Parent(s): 05e53ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -52
app.py CHANGED
@@ -11,25 +11,21 @@ import io
11
  import base64
12
  import plotly.graph_objects as go
13
 
14
- # Global instances
15
- data_processor = DataProcessor()
16
- sentiment_analyzer = SentimentAnalyzer()
17
- model_handler = ModelHandler()
18
- trading_logic = TradingLogic()
19
-
20
- # Asset mapping
21
  asset_map = {
22
  "Gold Futures (GC=F)": "GC=F",
23
  "Bitcoin USD (BTC-USD)": "BTC-USD"
24
  }
25
 
 
 
 
 
 
26
  def create_chart_analysis(interval, asset_name):
27
- """Create chart with technical indicators using mplfinance"""
28
  try:
29
  ticker = asset_map[asset_name]
30
  df = data_processor.get_asset_data(ticker, interval)
31
  if df.empty:
32
- # Return error plot instead of string
33
  fig, ax = plt.subplots(figsize=(12, 8), facecolor='white')
34
  fig.patch.set_facecolor('white')
35
  ax.text(0.5, 0.5, f'No data available for {asset_name}\nPlease try a different interval',
@@ -40,45 +36,35 @@ def create_chart_analysis(interval, asset_name):
40
  pred_fig.patch.set_facecolor('white')
41
  return fig, {}, pred_fig
42
 
43
- # Calculate indicators
44
  df = data_processor.calculate_indicators(df)
45
 
46
- # Create main candlestick chart with mplfinance
47
- # Prepare additional plots for indicators
48
  ap = []
49
 
50
- # Add moving averages (last 100 data points)
51
  if 'SMA_20' in df.columns:
52
  ap.append(mpf.make_addplot(df['SMA_20'].iloc[-100:], color='#FFA500', width=1.5, label='SMA 20'))
53
  if 'SMA_50' in df.columns:
54
  ap.append(mpf.make_addplot(df['SMA_50'].iloc[-100:], color='#FF4500', width=1.5, label='SMA 50'))
55
 
56
- # Add Bollinger Bands
57
  if 'BB_upper' in df.columns and 'BB_lower' in df.columns:
58
  ap.append(mpf.make_addplot(df['BB_upper'].iloc[-100:], color='#4169E1', width=1, linestyle='dashed', label='BB Upper'))
59
  ap.append(mpf.make_addplot(df['BB_lower'].iloc[-100:], color='#4169E1', width=1, linestyle='dashed', label='BB Lower'))
60
 
61
- # Create figure
62
  try:
63
  fig, axes = mpf.plot(
64
- df[-100:], # Show last 100 candles
65
  type='candle',
66
  style='yahoo',
67
  title=f'{asset_name} - {interval}',
68
  ylabel='Price (USD)',
69
  volume=True,
70
  addplot=ap,
71
- figsize=(15, 9), # DITINGKATKAN
72
  returnfig=True,
73
  warn_too_much_data=200,
74
- tight_layout=True
 
75
  )
76
 
77
- # Perbaikan untuk mencegah pemotongan label sumbu Y di Gradio
78
- if fig:
79
- plt.subplots_adjust(right=0.95) # Tambahkan margin kanan
80
-
81
- # Adjust layout
82
  fig.patch.set_facecolor('white')
83
  if axes:
84
  axes[0].set_facecolor('white')
@@ -92,24 +78,19 @@ def create_chart_analysis(interval, asset_name):
92
  axes.set_title('Plot Generation Error', color='black')
93
  axes.axis('off')
94
 
95
- # Prepare data for Chronos
96
  prepared_data = data_processor.prepare_for_chronos(df)
97
 
98
- # Generate predictions
99
  predictions = model_handler.predict(prepared_data, horizon=10)
100
  current_price = df['Close'].iloc[-1]
101
 
102
- # Get signal
103
  signal, confidence = trading_logic.generate_signal(
104
  predictions, current_price, df
105
  )
106
 
107
- # Calculate TP/SL
108
  tp, sl = trading_logic.calculate_tp_sl(
109
  current_price, df['ATR'].iloc[-1] if 'ATR' in df.columns else 10, signal
110
  )
111
 
112
- # Create metrics display
113
  metrics = {
114
  "Current Price": f"${current_price:,.2f}",
115
  "Signal": signal.upper(),
@@ -121,16 +102,13 @@ def create_chart_analysis(interval, asset_name):
121
  "Volume": f"{df['Volume'].iloc[-1]:,.0f}" if 'Volume' in df.columns else "N/A"
122
  }
123
 
124
- # Create prediction chart using matplotlib
125
  pred_fig, ax = plt.subplots(figsize=(10, 4), facecolor='white')
126
  pred_fig.patch.set_facecolor('white')
127
 
128
- # Plot historical prices (last 30 points)
129
  hist_data = df['Close'].iloc[-30:]
130
  hist_dates = df.index[-30:]
131
  ax.plot(hist_dates, hist_data, color='#4169E1', linewidth=2, label='Historical')
132
 
133
- # Plot predictions
134
  if predictions.any() and len(predictions) > 0:
135
  future_dates = pd.date_range(
136
  start=df.index[-1], periods=len(predictions), freq='D'
@@ -138,7 +116,6 @@ def create_chart_analysis(interval, asset_name):
138
  ax.plot(future_dates, predictions, color='#FF6600', linewidth=2,
139
  marker='o', markersize=4, label='Predictions')
140
 
141
- # Connect historical to prediction
142
  ax.plot([hist_dates[-1], future_dates[0]],
143
  [hist_data.iloc[-1], predictions[0]],
144
  color='#FF6600', linewidth=1, linestyle='--')
@@ -153,7 +130,6 @@ def create_chart_analysis(interval, asset_name):
153
  return fig, metrics, pred_fig
154
 
155
  except Exception as e:
156
- # Return error plot instead of string
157
  fig, ax = plt.subplots(figsize=(12, 8), facecolor='white')
158
  fig.patch.set_facecolor('white')
159
  ax.text(0.5, 0.5, f'Error: {str(e)}', ha='center', va='center',
@@ -166,14 +142,10 @@ def create_chart_analysis(interval, asset_name):
166
  return fig, {}, pred_fig
167
 
168
  def analyze_sentiment(asset_name):
169
- """Analyze market sentiment for selected asset"""
170
  try:
171
  ticker = asset_map[asset_name]
172
- # FIX: Menggunakan fungsi yang benar dari sentiment_analyzer.py
173
  sentiment_score, news_summary = sentiment_analyzer.analyze_market_sentiment(ticker)
174
 
175
- # --- Implementasi Plotly Gauge (sesuai referensi pengguna) ---
176
-
177
  fig = go.Figure(go.Indicator(
178
  mode="gauge+number+delta",
179
  value=sentiment_score,
@@ -184,9 +156,9 @@ def analyze_sentiment(asset_name):
184
  'axis': {'range': [-1, 1]},
185
  'bar': {'color': "#FFD700"},
186
  'steps': [
187
- {'range': [-1, -0.5], 'color': "rgba(255,0,0,0.5)"}, # Merah (Bearish)
188
- {'range': [-0.5, 0.5], 'color': "rgba(100,100,100,0.3)"}, # Abu-abu (Neutral)
189
- {'range': [0.5, 1], 'color': "rgba(0,255,0,0.5)"} # Hijau (Bullish)
190
  ],
191
  'threshold': {
192
  'line': {'color': "black", 'width': 4},
@@ -207,7 +179,6 @@ def analyze_sentiment(asset_name):
207
  return fig, news_summary
208
 
209
  except Exception as e:
210
- # Return error plot (menggunakan Matplotlib untuk error fallback)
211
  fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
212
  fig.patch.set_facecolor('white')
213
  ax.text(0.5, 0.5, f'Sentiment Error: {str(e)}', ha='center', va='center',
@@ -216,25 +187,21 @@ def analyze_sentiment(asset_name):
216
  return fig, f"<p>Error analyzing sentiment: {str(e)}</p>"
217
 
218
  def get_fundamentals(asset_name):
219
- """Get fundamental analysis data"""
220
  try:
221
  ticker = asset_map[asset_name]
222
  fundamentals = data_processor.get_fundamental_data(ticker)
223
 
224
- # Create fundamentals table
225
  table_data = []
226
  for key, value in fundamentals.items():
227
  table_data.append([key, value])
228
 
229
  df = pd.DataFrame(table_data, columns=['Metric', 'Value'])
230
 
231
- # Create fundamentals gauge chart
232
  fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
233
  fig.patch.set_facecolor('white')
234
 
235
  strength_index = fundamentals.get('Strength Index', 50)
236
 
237
- # Create horizontal bar gauge
238
  ax.barh([0], [strength_index], height=0.3, color='gold', alpha=0.7)
239
  ax.set_xlim(0, 100)
240
  ax.set_ylim(-0.5, 0.5)
@@ -248,7 +215,6 @@ def get_fundamentals(asset_name):
248
  return fig, df
249
 
250
  except Exception as e:
251
- # Return error plot
252
  fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
253
  fig.patch.set_facecolor('white')
254
  ax.text(0.5, 0.5, f'Fundamentals Error: {str(e)}', ha='center', va='center',
@@ -256,7 +222,6 @@ def get_fundamentals(asset_name):
256
  ax.axis('off')
257
  return fig, pd.DataFrame()
258
 
259
- # Create Gradio interface
260
  with gr.Blocks(
261
  theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue"),
262
  title="Trading Analysis & Prediction",
@@ -274,7 +239,6 @@ with gr.Blocks(
274
  """
275
  ) as demo:
276
 
277
- # Header with anycoder link
278
  gr.HTML("""
279
  <div style="text-align: center; padding: 20px;">
280
  <h1 style="color: #4169E1;">Trading Analysis & Prediction</h1>
@@ -306,14 +270,11 @@ with gr.Blocks(
306
  with gr.Tabs():
307
  with gr.TabItem("Chart Analysis"):
308
 
309
- # Price Chart (Full Width)
310
  chart_plot = gr.Plot(label="Price Chart")
311
 
312
- # Price Predictions (Full Width)
313
  with gr.Row():
314
  pred_plot = gr.Plot(label="Price Predictions")
315
 
316
- # Trading Metrics (Full Width, dipindahkan ke bawah)
317
  with gr.Row():
318
  metrics_output = gr.JSON(label="Trading Metrics")
319
 
@@ -333,7 +294,6 @@ with gr.Blocks(
333
  interactive=False
334
  )
335
 
336
- # Event handlers
337
  def update_all(interval, asset):
338
  chart, metrics, pred = create_chart_analysis(interval, asset)
339
  sentiment, news = analyze_sentiment(asset)
 
11
  import base64
12
  import plotly.graph_objects as go
13
 
 
 
 
 
 
 
 
14
  asset_map = {
15
  "Gold Futures (GC=F)": "GC=F",
16
  "Bitcoin USD (BTC-USD)": "BTC-USD"
17
  }
18
 
19
+ data_processor = DataProcessor()
20
+ sentiment_analyzer = SentimentAnalyzer()
21
+ model_handler = ModelHandler()
22
+ trading_logic = TradingLogic()
23
+
24
  def create_chart_analysis(interval, asset_name):
 
25
  try:
26
  ticker = asset_map[asset_name]
27
  df = data_processor.get_asset_data(ticker, interval)
28
  if df.empty:
 
29
  fig, ax = plt.subplots(figsize=(12, 8), facecolor='white')
30
  fig.patch.set_facecolor('white')
31
  ax.text(0.5, 0.5, f'No data available for {asset_name}\nPlease try a different interval',
 
36
  pred_fig.patch.set_facecolor('white')
37
  return fig, {}, pred_fig
38
 
 
39
  df = data_processor.calculate_indicators(df)
40
 
 
 
41
  ap = []
42
 
 
43
  if 'SMA_20' in df.columns:
44
  ap.append(mpf.make_addplot(df['SMA_20'].iloc[-100:], color='#FFA500', width=1.5, label='SMA 20'))
45
  if 'SMA_50' in df.columns:
46
  ap.append(mpf.make_addplot(df['SMA_50'].iloc[-100:], color='#FF4500', width=1.5, label='SMA 50'))
47
 
 
48
  if 'BB_upper' in df.columns and 'BB_lower' in df.columns:
49
  ap.append(mpf.make_addplot(df['BB_upper'].iloc[-100:], color='#4169E1', width=1, linestyle='dashed', label='BB Upper'))
50
  ap.append(mpf.make_addplot(df['BB_lower'].iloc[-100:], color='#4169E1', width=1, linestyle='dashed', label='BB Lower'))
51
 
 
52
  try:
53
  fig, axes = mpf.plot(
54
+ df[-100:],
55
  type='candle',
56
  style='yahoo',
57
  title=f'{asset_name} - {interval}',
58
  ylabel='Price (USD)',
59
  volume=True,
60
  addplot=ap,
61
+ figsize=(15, 9),
62
  returnfig=True,
63
  warn_too_much_data=200,
64
+ # MENGGUNAKAN scale_padding UNTUK MEMBERI RUANG PADA SUMBU Y KANAN
65
+ scale_padding={'right': 1.0, 'left': 0.1}
66
  )
67
 
 
 
 
 
 
68
  fig.patch.set_facecolor('white')
69
  if axes:
70
  axes[0].set_facecolor('white')
 
78
  axes.set_title('Plot Generation Error', color='black')
79
  axes.axis('off')
80
 
 
81
  prepared_data = data_processor.prepare_for_chronos(df)
82
 
 
83
  predictions = model_handler.predict(prepared_data, horizon=10)
84
  current_price = df['Close'].iloc[-1]
85
 
 
86
  signal, confidence = trading_logic.generate_signal(
87
  predictions, current_price, df
88
  )
89
 
 
90
  tp, sl = trading_logic.calculate_tp_sl(
91
  current_price, df['ATR'].iloc[-1] if 'ATR' in df.columns else 10, signal
92
  )
93
 
 
94
  metrics = {
95
  "Current Price": f"${current_price:,.2f}",
96
  "Signal": signal.upper(),
 
102
  "Volume": f"{df['Volume'].iloc[-1]:,.0f}" if 'Volume' in df.columns else "N/A"
103
  }
104
 
 
105
  pred_fig, ax = plt.subplots(figsize=(10, 4), facecolor='white')
106
  pred_fig.patch.set_facecolor('white')
107
 
 
108
  hist_data = df['Close'].iloc[-30:]
109
  hist_dates = df.index[-30:]
110
  ax.plot(hist_dates, hist_data, color='#4169E1', linewidth=2, label='Historical')
111
 
 
112
  if predictions.any() and len(predictions) > 0:
113
  future_dates = pd.date_range(
114
  start=df.index[-1], periods=len(predictions), freq='D'
 
116
  ax.plot(future_dates, predictions, color='#FF6600', linewidth=2,
117
  marker='o', markersize=4, label='Predictions')
118
 
 
119
  ax.plot([hist_dates[-1], future_dates[0]],
120
  [hist_data.iloc[-1], predictions[0]],
121
  color='#FF6600', linewidth=1, linestyle='--')
 
130
  return fig, metrics, pred_fig
131
 
132
  except Exception as e:
 
133
  fig, ax = plt.subplots(figsize=(12, 8), facecolor='white')
134
  fig.patch.set_facecolor('white')
135
  ax.text(0.5, 0.5, f'Error: {str(e)}', ha='center', va='center',
 
142
  return fig, {}, pred_fig
143
 
144
  def analyze_sentiment(asset_name):
 
145
  try:
146
  ticker = asset_map[asset_name]
 
147
  sentiment_score, news_summary = sentiment_analyzer.analyze_market_sentiment(ticker)
148
 
 
 
149
  fig = go.Figure(go.Indicator(
150
  mode="gauge+number+delta",
151
  value=sentiment_score,
 
156
  'axis': {'range': [-1, 1]},
157
  'bar': {'color': "#FFD700"},
158
  'steps': [
159
+ {'range': [-1, -0.5], 'color': "rgba(255,0,0,0.5)"},
160
+ {'range': [-0.5, 0.5], 'color': "rgba(100,100,100,0.3)"},
161
+ {'range': [0.5, 1], 'color': "rgba(0,255,0,0.5)"}
162
  ],
163
  'threshold': {
164
  'line': {'color': "black", 'width': 4},
 
179
  return fig, news_summary
180
 
181
  except Exception as e:
 
182
  fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
183
  fig.patch.set_facecolor('white')
184
  ax.text(0.5, 0.5, f'Sentiment Error: {str(e)}', ha='center', va='center',
 
187
  return fig, f"<p>Error analyzing sentiment: {str(e)}</p>"
188
 
189
  def get_fundamentals(asset_name):
 
190
  try:
191
  ticker = asset_map[asset_name]
192
  fundamentals = data_processor.get_fundamental_data(ticker)
193
 
 
194
  table_data = []
195
  for key, value in fundamentals.items():
196
  table_data.append([key, value])
197
 
198
  df = pd.DataFrame(table_data, columns=['Metric', 'Value'])
199
 
 
200
  fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
201
  fig.patch.set_facecolor('white')
202
 
203
  strength_index = fundamentals.get('Strength Index', 50)
204
 
 
205
  ax.barh([0], [strength_index], height=0.3, color='gold', alpha=0.7)
206
  ax.set_xlim(0, 100)
207
  ax.set_ylim(-0.5, 0.5)
 
215
  return fig, df
216
 
217
  except Exception as e:
 
218
  fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
219
  fig.patch.set_facecolor('white')
220
  ax.text(0.5, 0.5, f'Fundamentals Error: {str(e)}', ha='center', va='center',
 
222
  ax.axis('off')
223
  return fig, pd.DataFrame()
224
 
 
225
  with gr.Blocks(
226
  theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue"),
227
  title="Trading Analysis & Prediction",
 
239
  """
240
  ) as demo:
241
 
 
242
  gr.HTML("""
243
  <div style="text-align: center; padding: 20px;">
244
  <h1 style="color: #4169E1;">Trading Analysis & Prediction</h1>
 
270
  with gr.Tabs():
271
  with gr.TabItem("Chart Analysis"):
272
 
 
273
  chart_plot = gr.Plot(label="Price Chart")
274
 
 
275
  with gr.Row():
276
  pred_plot = gr.Plot(label="Price Predictions")
277
 
 
278
  with gr.Row():
279
  metrics_output = gr.JSON(label="Trading Metrics")
280
 
 
294
  interactive=False
295
  )
296
 
 
297
  def update_all(interval, asset):
298
  chart, metrics, pred = create_chart_analysis(interval, asset)
299
  sentiment, news = analyze_sentiment(asset)