Spaces:
Sleeping
Sleeping
File size: 16,588 Bytes
b8086d5 f27fbb4 b8086d5 f27fbb4 b8086d5 c267b11 b8086d5 f27fbb4 b8086d5 f27fbb4 b8086d5 37bd4d6 b8086d5 c267b11 b8086d5 f27fbb4 e3e2069 b8086d5 c267b11 e3e2069 dc6c2a4 f27fbb4 e3e2069 f27fbb4 cf14392 f27fbb4 c267b11 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 82ba2cc 6d4f83e 6eb2763 6d4f83e 6eb2763 82ba2cc 6eb2763 82ba2cc 6eb2763 8a9810a 6eb2763 82ba2cc 6eb2763 67ebd57 6eb2763 8a9810a 6eb2763 8a9810a 6eb2763 c267b11 6eb2763 37bd4d6 b8086d5 f27fbb4 c267b11 f27fbb4 c267b11 f27fbb4 c267b11 37bd4d6 1ff5d0c c267b11 4b7c0ae f27fbb4 4b7c0ae 37bd4d6 f27fbb4 37bd4d6 4b7c0ae c267b11 4b7c0ae c267b11 f27fbb4 c267b11 4b7c0ae 1ff5d0c f27fbb4 37bd4d6 f27fbb4 1ff5d0c 4b7c0ae f27fbb4 c267b11 f27fbb4 c267b11 4b7c0ae f27fbb4 1ff5d0c f27fbb4 4b7c0ae 6d4f83e 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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
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
# Global instances
data_processor = DataProcessor()
sentiment_analyzer = SentimentAnalyzer()
model_handler = ModelHandler()
trading_logic = TradingLogic()
# Asset mapping
asset_map = {
"Gold Futures (GC=F)": "GC=F",
"Bitcoin USD (BTC-USD)": "BTC-USD"
}
def create_chart_analysis(interval, asset_name):
"""Create chart with technical indicators using mplfinance"""
try:
ticker = asset_map[asset_name]
df = data_processor.get_asset_data(ticker, interval)
if df.empty:
# Return error plot instead of string
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
# Calculate indicators
df = data_processor.calculate_indicators(df)
# Create main candlestick chart with mplfinance
# Prepare additional plots for indicators
ap = []
# Add moving averages (last 100 data points)
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'))
# Add Bollinger Bands
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'))
# Create figure
try:
fig, axes = mpf.plot(
df[-100:], # Show last 100 candles
type='candle',
style='yahoo',
title=f'{asset_name} - {interval}',
ylabel='Price (USD)',
volume=True,
addplot=ap,
figsize=(12, 8),
returnfig=True,
warn_too_much_data=200,
tight_layout=True
)
# Adjust layout
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')
# Prepare data for Chronos
prepared_data = data_processor.prepare_for_chronos(df)
# Generate predictions
predictions = model_handler.predict(prepared_data, horizon=10)
current_price = df['Close'].iloc[-1]
# Get signal
signal, confidence = trading_logic.generate_signal(
predictions, current_price, df
)
# Calculate TP/SL
tp, sl = trading_logic.calculate_tp_sl(
current_price, df['ATR'].iloc[-1] if 'ATR' in df.columns else 10, signal
)
# Create metrics display
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"
}
# Create prediction chart using matplotlib
pred_fig, ax = plt.subplots(figsize=(10, 4), facecolor='white')
pred_fig.patch.set_facecolor('white')
# Plot historical prices (last 30 points)
hist_data = df['Close'].iloc[-30:]
hist_dates = df.index[-30:]
ax.plot(hist_dates, hist_data, color='#4169E1', linewidth=2, label='Historical')
# Plot predictions
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')
# Connect historical to prediction
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:
# Return error plot instead of string
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):
"""Analyze market sentiment for selected asset"""
try:
ticker = asset_map[asset_name]
# FIX PENTING: Memanggil fungsi yang benar dari sentiment_analyzer.py
sentiment_score, news_summary = sentiment_analyzer.analyze_market_sentiment(ticker)
# --- Implementasi Matplotlib Gauge (Sesuai Gambar Referensi) ---
# Create sentiment gauge using matplotlib
fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
fig.patch.set_facecolor('white')
# Setup Gauge limits
ax.set_xlim(-1.1, 1.1)
ax.set_ylim(-0.2, 1.1)
ax.set_aspect('equal')
# Draw gauge background arc (light gray container)
theta = np.linspace(np.pi, 0, 100)
x, y = np.cos(theta), np.sin(theta)
# Draw full light gray arc (Outer ring)
ax.plot(x, y, color='lightgray', linewidth=10, solid_capstyle='round', zorder=1)
# Segments (Matching the image)
# 1. Red: -1.0 to -0.5
ax.fill_between(x[75:], y[75:], 0, where=x[75:]<=-0.5, color='#F08080', alpha=0.9, linewidth=0, zorder=2)
# 2. Yellow/Orange: -0.5 to 0.0
ax.fill_between(x[50:75], y[50:75], 0, where=x[50:75]<0, color='#FFD700', alpha=0.9, linewidth=0, zorder=2)
# 3. Light Gray: 0.0 to 0.5 (Neutral)
ax.fill_between(x[25:50], y[25:50], 0, where=x[25:50]>0, color='#D3D3D3', alpha=0.9, linewidth=0, zorder=2)
# 4. Light Green: 0.5 to 1.0
ax.fill_between(x[:25], y[:25], 0, where=x[:25]>=0.5, color='#90EE90', alpha=0.9, linewidth=0, zorder=2)
# Draw Needle (Pointer)
needle_angle = np.pi * (1 - (sentiment_score + 1) / 2)
needle_x = 0.8 * np.cos(needle_angle)
needle_y = 0.8 * np.sin(needle_angle)
# Draw the Yellow/Gold needle/pointer
ax.plot([0, needle_x], [0, needle_y], color='gold', linewidth=6, solid_capstyle='round', zorder=5)
# Draw the black cap on the arc (untuk tampilan jarum)
ax.plot([needle_x], [needle_y], marker='|', color='black', markersize=15, markeredgewidth=2, zorder=6)
# Center black point
ax.plot([0], [0], marker='o', color='black', markersize=8, zorder=7)
# Draw score number (seperti gambar)
score_color = 'red' if sentiment_score < 0 else 'green' if sentiment_score > 0 else 'black'
# Score label: e.g., -0.123 (Font besar di tengah)
ax.text(0, -0.05, f"{sentiment_score:+.3f}", ha='center', va='center',
fontsize=28, color=score_color, weight='bold', zorder=7)
# Trend indicator (panah bawah/atas kecil di bawah skor)
trend_arrow = '▲' if sentiment_score > 0.0 else '▼' if sentiment_score < 0.0 else ''
# Text di bawah score (misalnya ▼-0.123)
ax.text(0.0, -0.18, f"{trend_arrow}{abs(sentiment_score):.3f}", ha='center', va='center',
fontsize=14, color=score_color, zorder=7)
# Add labels for the scale
ax.text(-1, 0, "-1", ha='center', va='top', fontsize=10, color='black')
ax.text(-0.5, 0.5, "-0.5", ha='center', va='center', fontsize=10, color='black')
ax.text(0, 1.05, "0", ha='center', va='bottom', fontsize=10, color='black')
ax.text(0.5, 0.5, "0.5", ha='center', va='center', fontsize=10, color='black')
ax.text(1, 0, "1", ha='center', va='top', fontsize=10, color='black')
# Add Title
ax.set_title(f'{ticker} Market Sentiment (Simulated)', color='black', pad=20)
# Remove axes
ax.axis('off')
return fig, news_summary
except Exception as e:
# Return error plot
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):
"""Get fundamental analysis data"""
try:
ticker = asset_map[asset_name]
fundamentals = data_processor.get_fundamental_data(ticker)
# Create fundamentals table
table_data = []
for key, value in fundamentals.items():
table_data.append([key, value])
df = pd.DataFrame(table_data, columns=['Metric', 'Value'])
# Create fundamentals gauge chart
fig, ax = plt.subplots(figsize=(6, 4), facecolor='white')
fig.patch.set_facecolor('white')
strength_index = fundamentals.get('Strength Index', 50)
# Create horizontal bar gauge
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:
# Return error plot
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()
# Create Gradio interface
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:
# Header with anycoder link
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"):
with gr.Row():
with gr.Column(scale=2):
chart_plot = gr.Plot(label="Price Chart")
with gr.Column(scale=1):
metrics_output = gr.JSON(label="Trading Metrics")
with gr.Row():
pred_plot = gr.Plot(label="Price Predictions")
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
)
# Event handlers
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
) |