omniverse1's picture
Deploy Gradio app with multiple files
b8086d5 verified
raw
history blame
10.6 kB
import gradio as gr
import pandas as pd
import plotly.graph_objects as go
from data_processor import DataProcessor
from sentiment_analyzer import SentimentAnalyzer
from model_handler import ModelHandler
from trading_logic import TradingLogic
import numpy as np
# Global instances
data_processor = DataProcessor()
sentiment_analyzer = SentimentAnalyzer()
model_handler = ModelHandler()
trading_logic = TradingLogic()
def create_chart_analysis(interval):
"""Create chart with technical indicators"""
try:
df = data_processor.get_gold_data(interval)
if df.empty:
return "No data available", None, None
# Calculate indicators
df = data_processor.calculate_indicators(df)
# Create candlestick chart
fig = go.Figure(data=[
go.Candlestick(
x=df.index,
open=df['Open'],
high=df['High'],
low=df['Low'],
close=df['Close'],
name='Gold Price'
)
])
# Add Bollinger Bands
fig.add_trace(go.Scatter(
x=df.index, y=df['BB_upper'],
line=dict(color='rgba(255,255,255,0.3)', width=1),
name='BB Upper', showlegend=False
))
fig.add_trace(go.Scatter(
x=df.index, y=df['BB_lower'],
line=dict(color='rgba(255,255,255,0.3)', width=1),
fill='tonexty', fillcolor='rgba(255,255,255,0.1)',
name='BB Lower', showlegend=False
))
# Add moving averages
fig.add_trace(go.Scatter(
x=df.index, y=df['SMA_20'],
line=dict(color='#FFD700', width=2),
name='SMA 20'
))
fig.add_trace(go.Scatter(
x=df.index, y=df['SMA_50'],
line=dict(color='#FFA500', width=2),
name='SMA 50'
))
fig.update_layout(
title=f'Gold Futures (GC=F) - {interval}',
yaxis_title='Price (USD)',
xaxis_title='Date',
template='plotly_dark',
height=500,
margin=dict(l=50, r=50, t=50, b=50),
xaxis_rangeslider_visible=False,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font=dict(color='white')
)
# Generate predictions
predictions = model_handler.predict(df, 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], 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}",
"MACD": f"{df['MACD'].iloc[-1]:.4f}",
"Volume": f"{df['Volume'].iloc[-1]:,.0f}"
}
# Create prediction chart
pred_fig = go.Figure()
future_dates = pd.date_range(
start=df.index[-1], periods=len(predictions), freq='D'
)
pred_fig.add_trace(go.Scatter(
x=future_dates, y=predictions,
mode='lines+markers',
line=dict(color='#FFD700', width=3),
marker=dict(size=6),
name='Predictions'
))
pred_fig.add_trace(go.Scatter(
x=[df.index[-1], future_dates[0]],
y=[current_price, predictions[0]],
mode='lines',
line=dict(color='rgba(255,215,0,0.5)', width=2, dash='dash'),
showlegend=False
))
pred_fig.update_layout(
title='Price Prediction (Next 10 Periods)',
yaxis_title='Price (USD)',
xaxis_title='Date',
template='plotly_dark',
height=300,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font=dict(color='white')
)
return fig, metrics, pred_fig
except Exception as e:
return str(e), None, None
def analyze_sentiment():
"""Analyze gold market sentiment"""
try:
sentiment_score, news_summary = sentiment_analyzer.analyze_gold_sentiment()
# Create sentiment gauge
fig = go.Figure(go.Indicator(
mode="gauge+number+delta",
value=sentiment_score,
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': "Gold Market Sentiment"},
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(255,255,255,0.3)"},
{'range': [0.5, 1], 'color': "rgba(0,255,0,0.5)"}
],
'threshold': {
'line': {'color': "white", 'width': 4},
'thickness': 0.75,
'value': 0
}
}
))
fig.update_layout(
template='plotly_dark',
height=300,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font=dict(color='white')
)
return fig, news_summary
except Exception as e:
return str(e), None
def get_fundamentals():
"""Get fundamental analysis data"""
try:
fundamentals = data_processor.get_fundamental_data()
# 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 = go.Figure(go.Indicator(
mode="gauge+number",
value=fundamentals.get('Gold Strength Index', 50),
title={'text': "Gold Strength Index"},
gauge={
'axis': {'range': [0, 100]},
'bar': {'color': "#FFD700"},
'steps': [
{'range': [0, 30], 'color': "rgba(255,0,0,0.5)"},
{'range': [30, 70], 'color': "rgba(255,255,255,0.3)"},
{'range': [70, 100], 'color': "rgba(0,255,0,0.5)"}
]
}
))
fig.update_layout(
template='plotly_dark',
height=300,
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(0,0,0,0)',
font=dict(color='white')
)
return fig, df
except Exception as e:
return str(e), None
# Create Gradio interface
with gr.Blocks(
theme=gr.themes.Default(primary_hue="yellow", secondary_hue="yellow"),
title="Gold Trading Analysis & Prediction",
css="""
.gradio-container {background-color: #000000; color: #FFFFFF}
.gr-button-primary {background-color: #FFD700 !important; color: #000000 !important}
.gr-button-secondary {border-color: #FFD700 !important; color: #FFD700 !important}
.gr-tab button {color: #FFFFFF !important}
.gr-tab button.selected {background-color: #FFD700 !important; color: #000000 !important}
.gr-highlighted {background-color: #1a1a1a !important}
.anycoder-link {color: #FFD700 !important; text-decoration: none; font-weight: bold}
"""
) as demo:
# Header with anycoder link
gr.HTML("""
<div style="text-align: center; padding: 20px;">
<h1 style="color: #FFD700;">Gold Trading Analysis & Prediction</h1>
<p>Advanced AI-powered analysis for Gold Futures (GC=F)</p>
<a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" class="anycoder-link">Built with anycoder</a>
</div>
""")
with gr.Row():
interval_dropdown = gr.Dropdown(
choices=[
"5m", "15m", "30m", "1h", "4h", "1d", "1wk", "1mo", "3mo"
],
value="1d",
label="Time Interval",
info="Select analysis timeframe"
)
refresh_btn = gr.Button("๐Ÿ”„ Refresh Data", variant="primary")
with gr.Tabs():
with gr.TabItem("๐Ÿ“Š Chart Analysis"):
with gr.Row():
chart_plot = gr.Plot(label="Price Chart")
pred_plot = gr.Plot(label="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():
fundamentals_gauge = gr.Plot(label="Strength Index")
fundamentals_table = gr.Dataframe(
headers=["Metric", "Value"],
label="Key Fundamentals",
interactive=False
)
# Event handlers
def update_all(interval):
chart, metrics, pred = create_chart_analysis(interval)
sentiment, news = analyze_sentiment()
fund_gauge, fund_table = get_fundamentals()
return chart, metrics, pred, sentiment, news, fund_gauge, fund_table
refresh_btn.click(
fn=update_all,
inputs=interval_dropdown,
outputs=[
chart_plot, metrics_output, pred_plot,
sentiment_gauge, news_display,
fundamentals_gauge, fundamentals_table
]
)
demo.load(
fn=update_all,
inputs=interval_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
)