File size: 13,114 Bytes
b8086d5
 
f27fbb4
 
 
b8086d5
 
 
 
f27fbb4
 
476299e
b8086d5
f27fbb4
 
 
 
 
d8b4363
 
 
 
 
f27fbb4
b8086d5
f27fbb4
 
b8086d5
37bd4d6
 
 
 
 
 
 
 
 
b8086d5
 
 
f27fbb4
 
e3e2069
 
 
 
b8086d5
e3e2069
 
 
dc6c2a4
e3e2069
 
d8b4363
e3e2069
 
 
 
 
 
d8b4363
e3e2069
 
d8b4363
 
e3e2069
 
 
 
 
 
 
 
 
 
 
 
 
 
f27fbb4
cf14392
f27fbb4
cf14392
b8086d5
 
c267b11
 
 
b8086d5
c267b11
e3e2069
c267b11
b8086d5
 
f27fbb4
c267b11
b8086d5
f27fbb4
 
e3e2069
 
 
b8086d5
 
f27fbb4
 
 
 
 
 
b8086d5
f27fbb4
cf14392
 
 
f27fbb4
 
cf14392
f27fbb4
 
 
 
 
 
 
 
 
 
c267b11
 
 
 
37bd4d6
 
 
 
 
 
 
 
 
 
c267b11
f27fbb4
c267b11
c699178
476299e
 
 
 
 
 
 
 
 
 
 
 
d8b4363
 
 
476299e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c267b11
 
 
 
37bd4d6
 
 
 
 
 
b8086d5
f27fbb4
c267b11
f27fbb4
 
c267b11
 
 
 
 
 
 
f27fbb4
 
 
 
 
 
 
 
 
 
 
 
 
 
c267b11
 
 
 
37bd4d6
 
 
 
 
 
1ff5d0c
4b7c0ae
f27fbb4
 
4b7c0ae
37bd4d6
f27fbb4
 
 
 
 
 
 
37bd4d6
 
4b7c0ae
 
 
 
c267b11
f27fbb4
 
c267b11
4b7c0ae
 
1ff5d0c
 
f27fbb4
 
 
 
 
 
 
 
 
 
37bd4d6
f27fbb4
 
 
 
 
 
 
1ff5d0c
4b7c0ae
f27fbb4
c267b11
67151a2
 
4b7c0ae
f27fbb4
67151a2
 
 
1ff5d0c
f27fbb4
4b7c0ae
476299e
 
1ff5d0c
f27fbb4
4b7c0ae
f27fbb4
 
 
 
 
 
 
 
4b7c0ae
f27fbb4
 
 
 
c267b11
 
 
4b7c0ae
c267b11
f27fbb4
1ff5d0c
c267b11
 
 
1ff5d0c
 
 
 
c267b11
f27fbb4
1ff5d0c
c267b11
 
 
1ff5d0c
 
 
 
4b7c0ae
 
 
 
c267b11
e3e2069
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import gradio as gr
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mplfinance as mpf
from data_processor import DataProcessor
from sentiment_analyzer import SentimentAnalyzer
from model_handler import ModelHandler
from trading_logic import TradingLogic
import io
import base64
import plotly.graph_objects as go

asset_map = {
    "Gold Futures (GC=F)": "GC=F",
    "Bitcoin USD (BTC-USD)": "BTC-USD"
}

data_processor = DataProcessor()
sentiment_analyzer = SentimentAnalyzer()
model_handler = ModelHandler()
trading_logic = TradingLogic()

def create_chart_analysis(interval, asset_name):
    try:
        ticker = asset_map[asset_name]
        df = data_processor.get_asset_data(ticker, interval)
        if df.empty:
            fig, ax = plt.subplots(figsize=(12, 8), facecolor='white')
            fig.patch.set_facecolor('white')
            ax.text(0.5, 0.5, f'No data available for {asset_name}\nPlease try a different interval', 
                   ha='center', va='center', transform=ax.transAxes, fontsize=14, color='red')
            ax.set_title('Data Error', color='black')
            ax.axis('off')
            pred_fig = plt.figure(figsize=(10, 4), facecolor='white')
            pred_fig.patch.set_facecolor('white')
            return fig, {}, pred_fig
        
        df = data_processor.calculate_indicators(df)
        
        ap = []
        
        if 'SMA_20' in df.columns:
            ap.append(mpf.make_addplot(df['SMA_20'].iloc[-100:], color='#FFA500', width=1.5, label='SMA 20'))
        if 'SMA_50' in df.columns:
            ap.append(mpf.make_addplot(df['SMA_50'].iloc[-100:], color='#FF4500', width=1.5, label='SMA 50'))
        
        if 'BB_upper' in df.columns and 'BB_lower' in df.columns:
            ap.append(mpf.make_addplot(df['BB_upper'].iloc[-100:], color='#4169E1', width=1, linestyle='dashed', label='BB Upper'))
            ap.append(mpf.make_addplot(df['BB_lower'].iloc[-100:], color='#4169E1', width=1, linestyle='dashed', label='BB Lower'))
        
        try:
            fig, axes = mpf.plot(
                df[-100:],
                type='candle',
                style='yahoo',
                title=f'{asset_name} - {interval}',
                ylabel='Price (USD)',
                volume=True,
                addplot=ap,
                figsize=(15, 9),
                returnfig=True,
                warn_too_much_data=200,
                # MENGGUNAKAN scale_padding UNTUK MEMBERI RUANG PADA SUMBU Y KANAN
                scale_padding={'right': 1.0, 'left': 0.1}
            )
            
            fig.patch.set_facecolor('white')
            if axes:
                axes[0].set_facecolor('white')
                axes[0].grid(True, alpha=0.3)
        except Exception as plot_error:
            print(f"Mplfinance plot error: {plot_error}")
            fig, axes = plt.subplots(figsize=(12, 8), facecolor='white')
            fig.patch.set_facecolor('white')
            axes.text(0.5, 0.5, f'Chart Plot Error: {str(plot_error)}', ha='center', va='center', 
                     transform=axes.transAxes, fontsize=14, color='red')
            axes.set_title('Plot Generation Error', color='black')
            axes.axis('off')
        
        prepared_data = data_processor.prepare_for_chronos(df)
        
        predictions = model_handler.predict(prepared_data, horizon=10)
        current_price = df['Close'].iloc[-1]
        
        signal, confidence = trading_logic.generate_signal(
            predictions, current_price, df
        )
        
        tp, sl = trading_logic.calculate_tp_sl(
            current_price, df['ATR'].iloc[-1] if 'ATR' in df.columns else 10, signal
        )
        
        metrics = {
            "Current Price": f"${current_price:,.2f}",
            "Signal": signal.upper(),
            "Confidence": f"{confidence:.1%}",
            "Take Profit": f"${tp:,.2f}" if tp else "N/A",
            "Stop Loss": f"${sl:,.2f}" if sl else "N/A",
            "RSI": f"{df['RSI'].iloc[-1]:.1f}" if 'RSI' in df.columns else "N/A",
            "MACD": f"{df['MACD'].iloc[-1]:.4f}" if 'MACD' in df.columns else "N/A",
            "Volume": f"{df['Volume'].iloc[-1]:,.0f}" if 'Volume' in df.columns else "N/A"
        }
        
        pred_fig, ax = plt.subplots(figsize=(10, 4), facecolor='white')
        pred_fig.patch.set_facecolor('white')
        
        hist_data = df['Close'].iloc[-30:]
        hist_dates = df.index[-30:]
        ax.plot(hist_dates, hist_data, color='#4169E1', linewidth=2, label='Historical')
        
        if predictions.any() and len(predictions) > 0:
            future_dates = pd.date_range(
                start=df.index[-1], periods=len(predictions), freq='D'
            )
            ax.plot(future_dates, predictions, color='#FF6600', linewidth=2, 
                   marker='o', markersize=4, label='Predictions')
            
            ax.plot([hist_dates[-1], future_dates[0]], 
                   [hist_data.iloc[-1], predictions[0]], 
                   color='#FF6600', linewidth=1, linestyle='--')
        
        ax.set_title('Price Prediction (Next 10 Periods)', fontsize=12, color='black')
        ax.set_xlabel('Date', color='black')
        ax.set_ylabel('Price (USD)', color='black')
        ax.legend()
        ax.grid(True, alpha=0.3)
        ax.tick_params(colors='black')
        
        return fig, metrics, pred_fig
        
    except Exception as e:
        fig, ax = plt.subplots(figsize=(12, 8), facecolor='white')
        fig.patch.set_facecolor('white')
        ax.text(0.5, 0.5, f'Error: {str(e)}', ha='center', va='center', 
               transform=ax.transAxes, fontsize=14, color='red')
        ax.set_title('Chart Generation Error', color='black')
        ax.axis('off')
        
        pred_fig = plt.figure(figsize=(10, 4), facecolor='white')
        pred_fig.patch.set_facecolor('white')
        return fig, {}, pred_fig

def analyze_sentiment(asset_name):
    try:
        ticker = asset_map[asset_name]
        sentiment_score, news_summary = sentiment_analyzer.analyze_market_sentiment(ticker)
        
        fig = go.Figure(go.Indicator(
            mode="gauge+number+delta",
            value=sentiment_score,
            domain={'x': [0, 1], 'y': [0, 1]},
            title={'text': f"{ticker} Market Sentiment (Simulated)"},
            delta={'reference': 0},
            gauge={
                'axis': {'range': [-1, 1]},
                'bar': {'color': "#FFD700"},
                'steps': [
                    {'range': [-1, -0.5], 'color': "rgba(255,0,0,0.5)"},
                    {'range': [-0.5, 0.5], 'color': "rgba(100,100,100,0.3)"},
                    {'range': [0.5, 1], 'color': "rgba(0,255,0,0.5)"}
                ],
                'threshold': {
                    'line': {'color': "black", 'width': 4},
                    'thickness': 0.75,
                    'value': 0
                }
            }
        ))
        
        fig.update_layout(
            template='plotly_white',
            height=300,
            paper_bgcolor='white', 
            plot_bgcolor='white',
            font=dict(color='black')
        )
        
        return fig, news_summary
        
    except Exception as e:
        fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
        fig.patch.set_facecolor('white')
        ax.text(0.5, 0.5, f'Sentiment Error: {str(e)}', ha='center', va='center', 
               transform=ax.transAxes, fontsize=12, color='red')
        ax.axis('off')
        return fig, f"<p>Error analyzing sentiment: {str(e)}</p>"

def get_fundamentals(asset_name):
    try:
        ticker = asset_map[asset_name]
        fundamentals = data_processor.get_fundamental_data(ticker)
        
        table_data = []
        for key, value in fundamentals.items():
            table_data.append([key, value])
        
        df = pd.DataFrame(table_data, columns=['Metric', 'Value'])
        
        fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
        fig.patch.set_facecolor('white')
        
        strength_index = fundamentals.get('Strength Index', 50)
        
        ax.barh([0], [strength_index], height=0.3, color='gold', alpha=0.7)
        ax.set_xlim(0, 100)
        ax.set_ylim(-0.5, 0.5)
        ax.set_title(f'{asset_name} Strength Index', color='black')
        ax.set_xlabel('Index Value', color='black')
        ax.text(strength_index, 0, f'{strength_index:.1f}', 
               ha='left', va='center', fontsize=12, color='black', weight='bold')
        ax.grid(True, alpha=0.3)
        ax.tick_params(colors='black')
        
        return fig, df
        
    except Exception as e:
        fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
        fig.patch.set_facecolor('white')
        ax.text(0.5, 0.5, f'Fundamentals Error: {str(e)}', ha='center', va='center', 
               transform=ax.transAxes, fontsize=12, color='red')
        ax.axis('off')
        return fig, pd.DataFrame()

with gr.Blocks(
    theme=gr.themes.Default(primary_hue="blue", secondary_hue="blue"),
    title="Trading Analysis & Prediction",
    css="""
        .gradio-container {background-color: #FFFFFF !important; color: #000000 !important}
        .gr-button-primary {background-color: #4169E1 !important; color: #FFFFFF !important}
        .gr-button-secondary {border-color: #4169E1 !important; color: #4169E1 !important}
        .gr-tab button {color: #000000 !important}
        .gr-tab button.selected {background-color: #4169E1 !important; color: #FFFFFF !important}
        .gr-highlighted {background-color: #F0F0F0 !important}
        .anycoder-link {color: #4169E1 !important; text-decoration: none; font-weight: bold}
        .gr-json {background-color: #FFFFFF !important; color: #000000 !important}
        .gr-json label {color: #000000 !important}
        .gr-textbox, .gr-dropdown, .gr-number {background-color: #FFFFFF !important; color: #000000 !important}
    """
) as demo:
    
    gr.HTML("""
        <div style="text-align: center; padding: 20px;">
            <h1 style="color: #4169E1;">Trading Analysis & Prediction</h1>
            <p>Advanced AI-powered analysis for Gold and Bitcoin</p>
            <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" class="anycoder-link">Built with anycoder</a>
        </div>
    """)
    
    with gr.Row():
        with gr.Column(scale=1):
            asset_dropdown = gr.Dropdown(
                choices=list(asset_map.keys()),
                value="Gold Futures (GC=F)",
                label="Select Asset",
                info="Choose trading pair"
            )
        with gr.Column(scale=1):
            interval_dropdown = gr.Dropdown(
                choices=[
                    "5m", "15m", "30m", "1h", "1d", "1wk", "1mo", "3mo"
                ],
                value="1d",
                label="Time Interval",
                info="Select analysis timeframe"
            )
        with gr.Column(scale=1):
            refresh_btn = gr.Button("Refresh Data", variant="primary")
    
    with gr.Tabs():
        with gr.TabItem("Chart Analysis"):
            
            chart_plot = gr.Plot(label="Price Chart")
            
            with gr.Row():
                pred_plot = gr.Plot(label="Price Predictions")
            
            with gr.Row():
                metrics_output = gr.JSON(label="Trading Metrics")
        
        with gr.TabItem("Sentiment Analysis"):
            with gr.Row():
                sentiment_gauge = gr.Plot(label="Sentiment Score")
                news_display = gr.HTML(label="Market News")
        
        with gr.TabItem("Fundamentals"):
            with gr.Row():
                with gr.Column(scale=1):
                    fundamentals_gauge = gr.Plot(label="Strength Index")
                with gr.Column(scale=1):
                    fundamentals_table = gr.Dataframe(
                        headers=["Metric", "Value"],
                        label="Key Fundamentals",
                        interactive=False
                    )
    
    def update_all(interval, asset):
        chart, metrics, pred = create_chart_analysis(interval, asset)
        sentiment, news = analyze_sentiment(asset)
        fund_gauge, fund_table = get_fundamentals(asset)
        
        return chart, metrics, pred, sentiment, news, fund_gauge, fund_table
    
    refresh_btn.click(
        fn=update_all,
        inputs=[interval_dropdown, asset_dropdown],
        outputs=[
            chart_plot, metrics_output, pred_plot,
            sentiment_gauge, news_display,
            fundamentals_gauge, fundamentals_table
        ]
    )
    
    demo.load(
        fn=update_all,
        inputs=[interval_dropdown, asset_dropdown],
        outputs=[
            chart_plot, metrics_output, pred_plot,
            sentiment_gauge, news_display,
            fundamentals_gauge, fundamentals_table
        ]
    )

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_api=True
    )