omniverse1 commited on
Commit
76d2e5b
·
verified ·
1 Parent(s): 5f389af

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -330
app.py DELETED
@@ -1,330 +0,0 @@
1
- import gradio as gr
2
- import pandas as pd
3
- import numpy as np
4
- import matplotlib.pyplot as plt
5
- import mplfinance as mpf
6
- from data_processor import DataProcessor
7
- from sentiment_analyzer import SentimentAnalyzer
8
- from model_handler import ModelHandler
9
- from trading_logic import TradingLogic
10
- import io
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',
32
- ha='center', va='center', transform=ax.transAxes, fontsize=14, color='red')
33
- ax.set_title('Data Error', color='black')
34
- ax.axis('off')
35
- pred_fig = plt.figure(figsize=(10, 4), facecolor='white')
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')
71
- axes[0].grid(True, alpha=0.3)
72
- except Exception as plot_error:
73
- print(f"Mplfinance plot error: {plot_error}")
74
- fig, axes = plt.subplots(figsize=(12, 8), facecolor='white')
75
- fig.patch.set_facecolor('white')
76
- axes.text(0.5, 0.5, f'Chart Plot Error: {str(plot_error)}', ha='center', va='center',
77
- transform=axes.transAxes, fontsize=14, color='red')
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(),
97
- "Confidence": f"{confidence:.1%}",
98
- "Take Profit": f"${tp:,.2f}" if tp else "N/A",
99
- "Stop Loss": f"${sl:,.2f}" if sl else "N/A",
100
- "RSI": f"{df['RSI'].iloc[-1]:.1f}" if 'RSI' in df.columns else "N/A",
101
- "MACD": f"{df['MACD'].iloc[-1]:.4f}" if 'MACD' in df.columns else "N/A",
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'
115
- )
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='--')
122
-
123
- ax.set_title('Price Prediction (Next 10 Periods)', fontsize=12, color='black')
124
- ax.set_xlabel('Date', color='black')
125
- ax.set_ylabel('Price (USD)', color='black')
126
- ax.legend()
127
- ax.grid(True, alpha=0.3)
128
- ax.tick_params(colors='black')
129
-
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',
136
- transform=ax.transAxes, fontsize=14, color='red')
137
- ax.set_title('Chart Generation Error', color='black')
138
- ax.axis('off')
139
-
140
- pred_fig = plt.figure(figsize=(10, 4), facecolor='white')
141
- pred_fig.patch.set_facecolor('white')
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,
152
- domain={'x': [0, 1], 'y': [0, 1]},
153
- title={'text': f"{ticker} Market Sentiment (Simulated)"},
154
- delta={'reference': 0},
155
- gauge={
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},
165
- 'thickness': 0.75,
166
- 'value': 0
167
- }
168
- }
169
- ))
170
-
171
- fig.update_layout(
172
- template='plotly_white',
173
- height=300,
174
- paper_bgcolor='white',
175
- plot_bgcolor='white',
176
- font=dict(color='black')
177
- )
178
-
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',
185
- transform=ax.transAxes, fontsize=12, color='red')
186
- ax.axis('off')
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)
208
- ax.set_title(f'{asset_name} Strength Index', color='black')
209
- ax.set_xlabel('Index Value', color='black')
210
- ax.text(strength_index, 0, f'{strength_index:.1f}',
211
- ha='left', va='center', fontsize=12, color='black', weight='bold')
212
- ax.grid(True, alpha=0.3)
213
- ax.tick_params(colors='black')
214
-
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',
221
- transform=ax.transAxes, fontsize=12, color='red')
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",
228
- css="""
229
- .gradio-container {background-color: #FFFFFF !important; color: #000000 !important}
230
- .gr-button-primary {background-color: #4169E1 !important; color: #FFFFFF !important}
231
- .gr-button-secondary {border-color: #4169E1 !important; color: #4169E1 !important}
232
- .gr-tab button {color: #000000 !important}
233
- .gr-tab button.selected {background-color: #4169E1 !important; color: #FFFFFF !important}
234
- .gr-highlighted {background-color: #F0F0F0 !important}
235
- .anycoder-link {color: #4169E1 !important; text-decoration: none; font-weight: bold}
236
- .gr-json {background-color: #FFFFFF !important; color: #000000 !important}
237
- .gr-json label {color: #000000 !important}
238
- .gr-textbox, .gr-dropdown, .gr-number {background-color: #FFFFFF !important; color: #000000 !important}
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>
245
- <p>Advanced AI-powered analysis for Gold and Bitcoin</p>
246
- <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" class="anycoder-link">Built with anycoder</a>
247
- </div>
248
- """)
249
-
250
- with gr.Row():
251
- with gr.Column(scale=1):
252
- asset_dropdown = gr.Dropdown(
253
- choices=list(asset_map.keys()),
254
- value="Gold Futures (GC=F)",
255
- label="Select Asset",
256
- info="Choose trading pair"
257
- )
258
- with gr.Column(scale=1):
259
- interval_dropdown = gr.Dropdown(
260
- choices=[
261
- "5m", "15m", "30m", "1h", "1d", "1wk", "1mo", "3mo"
262
- ],
263
- value="1d",
264
- label="Time Interval",
265
- info="Select analysis timeframe"
266
- )
267
- with gr.Column(scale=1):
268
- refresh_btn = gr.Button("Refresh Data", variant="primary")
269
-
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
-
281
- with gr.TabItem("Sentiment Analysis"):
282
- with gr.Row():
283
- sentiment_gauge = gr.Plot(label="Sentiment Score")
284
- news_display = gr.HTML(label="Market News")
285
-
286
- with gr.TabItem("Fundamentals"):
287
- with gr.Row():
288
- with gr.Column(scale=1):
289
- fundamentals_gauge = gr.Plot(label="Strength Index")
290
- with gr.Column(scale=1):
291
- fundamentals_table = gr.Dataframe(
292
- headers=["Metric", "Value"],
293
- label="Key Fundamentals",
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)
300
- fund_gauge, fund_table = get_fundamentals(asset)
301
-
302
- return chart, metrics, pred, sentiment, news, fund_gauge, fund_table
303
-
304
- refresh_btn.click(
305
- fn=update_all,
306
- inputs=[interval_dropdown, asset_dropdown],
307
- outputs=[
308
- chart_plot, metrics_output, pred_plot,
309
- sentiment_gauge, news_display,
310
- fundamentals_gauge, fundamentals_table
311
- ]
312
- )
313
-
314
- demo.load(
315
- fn=update_all,
316
- inputs=[interval_dropdown, asset_dropdown],
317
- outputs=[
318
- chart_plot, metrics_output, pred_plot,
319
- sentiment_gauge, news_display,
320
- fundamentals_gauge, fundamentals_table
321
- ]
322
- )
323
-
324
- if __name__ == "__main__":
325
- demo.launch(
326
- server_name="0.0.0.0",
327
- server_port=7860,
328
- share=False,
329
- show_api=True
330
- )