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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
from datetime import datetime, timedelta
|
| 6 |
+
import logging
|
| 7 |
+
from core.data import load_data, add_technical_indicators, add_sentiment
|
| 8 |
+
from core.model_runner import get_model
|
| 9 |
+
from core.plot import plot_forecast, plot_metrics_r2, plot_metrics_errors, plot_metrics_precision_recall, plot_metrics_risk, plot_loss_curve, plot_model_architecture, plot_future_forecast, plot_indicators, plot_signals, plot_backtest
|
| 10 |
+
import plotly.io as pio
|
| 11 |
+
from core.signals import generate_signals
|
| 12 |
+
from config import AVAILABLE_MODELS, DEFAULT_TICKERS, AVAILABLE_TIMEFRAMES, AVAILABLE_INDICATORS
|
| 13 |
+
from newsapi import NewsApiClient
|
| 14 |
+
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 15 |
+
|
| 16 |
+
log_path = "/tmp/app_log.txt"
|
| 17 |
+
os.makedirs("/tmp", exist_ok=True)
|
| 18 |
+
logging.basicConfig(
|
| 19 |
+
level=logging.DEBUG,
|
| 20 |
+
handlers=[
|
| 21 |
+
logging.FileHandler(log_path),
|
| 22 |
+
logging.StreamHandler()
|
| 23 |
+
],
|
| 24 |
+
format=\'%(asctime)s - %(levelname)s - %(message)s\'
|
| 25 |
+
)
|
| 26 |
+
analyzer = SentimentIntensityAnalyzer()
|
| 27 |
+
|
| 28 |
+
def sentiment_analysis(ticker, start_date, end_date, api_key):
|
| 29 |
+
try:
|
| 30 |
+
if not api_key:
|
| 31 |
+
return "No API key provided", None
|
| 32 |
+
newsapi = NewsApiClient(api_key=api_key)
|
| 33 |
+
start = pd.to_datetime(start_date)
|
| 34 |
+
end = pd.to_datetime(end_date)
|
| 35 |
+
articles = newsapi.get_everything(
|
| 36 |
+
q=ticker, from_param=start.strftime("%Y-%m-%d"), to=end.strftime("%Y-%m-%m"),
|
| 37 |
+
language=\'en\', sort_by=\'relevancy\'
|
| 38 |
+
)
|
| 39 |
+
sentiments = [analyzer.polarity_scores(article["title"]["compound"]) for article in articles["articles"]]
|
| 40 |
+
avg_sentiment = np.mean(sentiments) if sentiments else 0.0
|
| 41 |
+
sentiment_text = f"Average sentiment for {ticker}: {avg_sentiment:.2f}"
|
| 42 |
+
return sentiment_text, avg_sentiment
|
| 43 |
+
except Exception as e:
|
| 44 |
+
logging.error(f"Sentiment analysis failed: {str(e)}")
|
| 45 |
+
return f"Sentiment analysis failed: {str(e)}", None
|
| 46 |
+
|
| 47 |
+
def update_horizon_label(timeframe):
|
| 48 |
+
units = {\'1m\': \'minutes\', \'5m\': \'minutes\', \'15m\': \'minutes\', \'30m\': \'minutes\',
|
| 49 |
+
\'1h\': \'hours\', \'4h\': \'hours\', \'1d\': \'days\', \'1wk\': \'weeks\'}
|
| 50 |
+
return gr.update(label=f"Horizon ({units.get(timeframe, \'days\')})")
|
| 51 |
+
|
| 52 |
+
def run_dashboard(data_src, ticker, file_upload, timeframe, start_date, end_date, horizon, indicators,
|
| 53 |
+
include_sentiment, news_api_key, alpha_api_key, finnhub_api_key, twelvedata_api_key, account_size, risk_percent, model,
|
| 54 |
+
hidden_units, n_layers, epochs, learning_rate, beta1, beta2, weight_decay, dropout,
|
| 55 |
+
window_size, test_split, rsi_mid, macd_sens, adx_thr, sent_thr, vote_buy, vote_sell,
|
| 56 |
+
feat_selector, feat_threshold):
|
| 57 |
+
try:
|
| 58 |
+
logging.info(f"Running dashboard for {ticker}, timeframe: {timeframe}, model: {model}")
|
| 59 |
+
start_date = pd.to_datetime(start_date).strftime("%Y-%m-%d")
|
| 60 |
+
end_date = pd.to_datetime(end_date).strftime("%Y-%m-%d")
|
| 61 |
+
|
| 62 |
+
df = load_data(data_src=data_src, ticker=ticker, start=start_date, end=end_date,
|
| 63 |
+
interval=timeframe, file_upload=file_upload, alpha_api_key=alpha_api_key,
|
| 64 |
+
finnhub_api_key=finnhub_api_key, twelvedata_api_key=twelvedata_api_key)
|
| 65 |
+
if df.empty:
|
| 66 |
+
logging.error("Failed to load data")
|
| 67 |
+
return [None] * 12 + ["Failed to load data", None, None, None, None, "Failed to load data"]
|
| 68 |
+
|
| 69 |
+
df, valid_indicators = add_technical_indicators(df, indicators)
|
| 70 |
+
if include_sentiment and news_api_key:
|
| 71 |
+
df = add_sentiment(df, ticker, news_api_key, start_date, end_date)
|
| 72 |
+
sentiment_text, sentiment_score = sentiment_analysis(ticker, start_date, end_date, news_api_key)
|
| 73 |
+
|
| 74 |
+
features = valid_indicators # Use valid_indicators for feature
|
| 75 |
+
target = \'value\'
|
| 76 |
+
result = get_model(
|
| 77 |
+
df=df,
|
| 78 |
+
features=features,
|
| 79 |
+
target=target,
|
| 80 |
+
model_name=model,
|
| 81 |
+
horizon=horizon,
|
| 82 |
+
hidden_units=hidden_units,
|
| 83 |
+
n_layers=n_layers,
|
| 84 |
+
epochs=epochs,
|
| 85 |
+
learning_rate=learning_rate,
|
| 86 |
+
beta1=beta1,
|
| 87 |
+
beta2=beta2,
|
| 88 |
+
weight_decay=weight_decay,
|
| 89 |
+
dropout=dropout,
|
| 90 |
+
window_size=window_size,
|
| 91 |
+
test_split=test_split,
|
| 92 |
+
selector_method=feat_selector,
|
| 93 |
+
importance_threshold=feat_threshold
|
| 94 |
+
)
|
| 95 |
+
if isinstance(result, dict) and result.get("error"):
|
| 96 |
+
logging.error(f"Model training failed: {result[\'error\']})")
|
| 97 |
+
return [None] * 12 + [f"Model training failed: {result[\'error\']}", None, None, None, None, f"Model training failed: {result[\'error\']}"]
|
| 98 |
+
|
| 99 |
+
signals_df, trades_df, equity_df = generate_signals(df, result)
|
| 100 |
+
if signals_df.empty:
|
| 101 |
+
logging.error("Failed to generate signals")
|
| 102 |
+
return [None] * 12 + ["Failed to generate signals", None, None, None, None, "Failed to generate signals"]
|
| 103 |
+
|
| 104 |
+
chart_plot = plot_indicators(df, ticker)
|
| 105 |
+
signals_plot = plot_signals(signals_df, ticker)
|
| 106 |
+
backtest_plot = plot_backtest(equity_df, trades_df, ticker)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
future_plot = plot_future_forecast(df, result, indicators)
|
| 110 |
+
future_table = pd.DataFrame({
|
| 111 |
+
"Date": [df.index[-1] + timedelta(days=i+1) for i in range(horizon)],
|
| 112 |
+
"Prediction": result["latest_prediction"]
|
| 113 |
+
})
|
| 114 |
+
signals_table = signals_df.reset_index()[["Date", "Price", "Signal", "Position_Size", "Stop_Loss", "Take_Profit", "Equity"]]
|
| 115 |
+
r2_plot = plot_metrics_r2(result)
|
| 116 |
+
error_plot = plot_metrics_errors(result)
|
| 117 |
+
precision_recall_plot = plot_metrics_precision_recall(result)
|
| 118 |
+
risk_plot = plot_metrics_risk(result)
|
| 119 |
+
loss_plot = plot_loss_curve(result)
|
| 120 |
+
architecture_plot = plot_model_architecture(result)
|
| 121 |
+
|
| 122 |
+
signals_csv = f"signals_{ticker}.csv"
|
| 123 |
+
signals_df.to_csv(signals_csv)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
predictions_csv = f"predictions_{ticker}.csv"
|
| 128 |
+
pd.DataFrame({
|
| 129 |
+
"Actual": result["actual"],
|
| 130 |
+
"Forecast": result["forecast"]
|
| 131 |
+
}).to_csv(predictions_csv)
|
| 132 |
+
chart_png = f"chart_{ticker}.png"
|
| 133 |
+
pio.write_image(chart_plot, chart_png, format=\'png\')
|
| 134 |
+
|
| 135 |
+
with open(log_path, \'r\') as log_file:
|
| 136 |
+
log_output = log_file.read()
|
| 137 |
+
|
| 138 |
+
logging.info("Dashboard run completed successfully")
|
| 139 |
+
return [
|
| 140 |
+
chart_plot, sentiment_text, signals_table, backtest_plot, future_plot, future_table,
|
| 141 |
+
r2_output, error_output, precision_recall_plot, risk_output, loss_output, architecture_output,
|
| 142 |
+
"Dashboard generated successfully", chart_png, signals_csv, predictions_csv, signals_plot, log_output
|
| 143 |
+
]
|
| 144 |
+
except Exception as e:
|
| 145 |
+
logging.error(f"Dashboard error: {str(e)}")
|
| 146 |
+
return [None] * 12 + [f"Error: {str(e)}", None, None, None, None, f"Error: {str(e)}"]
|
| 147 |
+
|
| 148 |
+
def main_interface():
|
| 149 |
+
try:
|
| 150 |
+
with gr.Blocks(title="Market Prediction Pro", theme=gr.themes.Default()) as app:
|
| 151 |
+
gr.Markdown("# Market Prediction Pro")
|
| 152 |
+
with gr.Row():
|
| 153 |
+
with gr.Column(scale=1):
|
| 154 |
+
data_src = gr.Dropdown(["yahoo", "csv", "alpha_vantage", "finnhub", "twelvedata"], label="Data Source", value="yahoo")
|
| 155 |
+
ticker = gr.Dropdown(DEFAULT_TICKERS, label="Ticker", value="AAPL")
|
| 156 |
+
file_upload = gr.File(label="Upload CSV", visible=False)
|
| 157 |
+
timeframe = gr.Dropdown(AVAILABLE_TIMEFRAMES, label="Timeframe", value="1d")
|
| 158 |
+
start_date = gr.Textbox("2020-01-01", label="Start Date (YYYY-MM-DD)")
|
| 159 |
+
end_date = gr.Textbox("2023-01-01", label="End Date (YYYY-MM-DD)")
|
| 160 |
+
horizon = gr.Slider(1, 30, step=1, label="Horizon (days)", value=1)
|
| 161 |
+
indicators = gr.CheckboxGroup(AVAILABLE_INDICATORS, label="Technical Indicators", value=["rsi", "macd", "bbands"])
|
| 162 |
+
include_sentiment = gr.Checkbox(label="Include Sentiment Analysis", value=False)
|
| 163 |
+
news_api_key = gr.Textbox("a1018b32215d4c29bdfa1beae97e1f5c", label="News API Key (Optional)", type="password")
|
| 164 |
+
alpha_api_key = gr.Textbox("IUCYQSZIPF3QIB3Q", label="Alpha Vantage API Key (Optional)", type="password")
|
| 165 |
+
finnhub_api_key = gr.Textbox(label="Finnhub API Key (Optional)", type="password")
|
| 166 |
+
twelvedata_api_key = gr.Textbox(label="Twelve Data API Key (Optional)", type="password")
|
| 167 |
+
|
| 168 |
+
gr.Markdown("### Model Parameters")
|
| 169 |
+
model = gr.Dropdown(list(AVAILABLE_MODELS.keys()), label="Model", value="LSTM")
|
| 170 |
+
hidden_units = gr.Slider(10, 200, step=10, label="Hidden Units", value=50)
|
| 171 |
+
n_layers = gr.Slider(1, 5, step=1, label="Number of Layers", value=2)
|
| 172 |
+
epochs = gr.Slider(1, 100, step=1, label="Epochs", value=10)
|
| 173 |
+
learning_rate = gr.Slider(0.0001, 0.1, step=0.0001, label="Learning Rate", value=0.001)
|
| 174 |
+
beta1 = gr.Slider(0.1, 0.999, step=0.001, label="Adam Beta1", value=0.9)
|
| 175 |
+
beta2 = gr.Slider(0.1, 0.999, step=0.001, label="Adam Beta2", value=0.999)
|
| 176 |
+
weight_decay = gr.Slider(0.0, 0.1, step=0.001, label="Weight Decay", value=0.0001)
|
| 177 |
+
dropout = gr.Slider(0.0, 0.5, step=0.05, label="Dropout", value=0.2)
|
| 178 |
+
window_size = gr.Slider(5, 50, step=1, label="Window Size", value=20)
|
| 179 |
+
test_split = gr.Slider(0.1, 0.5, step=0.05, label="Test Split Ratio", value=0.2)
|
| 180 |
+
|
| 181 |
+
gr.Markdown("### Signal Generation Parameters")
|
| 182 |
+
rsi_mid = gr.Slider(30, 70, step=1, label="RSI Midpoint", value=50)
|
| 183 |
+
macd_sens = gr.Slider(5, 30, step=1, label="MACD Sensitivity", value=12)
|
| 184 |
+
adx_thr = gr.Slider(10, 50, step=1, label="ADX Threshold", value=25)
|
| 185 |
+
sent_thr = gr.Slider(-1.0, 1.0, step=0.01, label="Sentiment Threshold", value=0.05)
|
| 186 |
+
vote_buy = gr.Slider(1, 5, step=1, label="Votes to Buy", value=3)
|
| 187 |
+
vote_sell = gr.Slider(1, 5, step=1, label="Votes to Sell", value=3)
|
| 188 |
+
|
| 189 |
+
gr.Markdown("### Feature Selection Parameters")
|
| 190 |
+
feat_selector = gr.Dropdown(["none", "rfe", "sfm"], label="Feature Selector", value="none")
|
| 191 |
+
feat_threshold = gr.Slider(0.0, 1.0, step=0.01, label="Feature Importance Threshold", value=0.01)
|
| 192 |
+
|
| 193 |
+
run_button = gr.Button("Run Dashboard")
|
| 194 |
+
|
| 195 |
+
with gr.Column(scale=2):
|
| 196 |
+
output_text = gr.Textbox(label="Status", interactive=False)
|
| 197 |
+
chart_output = gr.Plot(label="Price Chart with Indicators")
|
| 198 |
+
sentiment_output = gr.Textbox(label="Sentiment Analysis", interactive=False)
|
| 199 |
+
signals_output = gr.DataFrame(label="Generated Signals")
|
| 200 |
+
backtest_output = gr.Plot(label="Backtesting Results")
|
| 201 |
+
future_forecast_output = gr.Plot(label="Future Forecast")
|
| 202 |
+
future_forecast_table = gr.DataFrame(label="Future Forecast Data")
|
| 203 |
+
r2_output = gr.Plot(label="R2 Score")
|
| 204 |
+
error_output = gr.Plot(label="Prediction Errors")
|
| 205 |
+
precision_recall_output = gr.Plot(label="Precision-Recall Curve")
|
| 206 |
+
risk_output = gr.Plot(label="Risk Metrics")
|
| 207 |
+
loss_output = gr.Plot(label="Loss Curve")
|
| 208 |
+
architecture_output = gr.Plot(label="Model Architecture")
|
| 209 |
+
log_output = gr.Textbox(label="Application Log", interactive=False, lines=10)
|
| 210 |
+
|
| 211 |
+
data_src.change(lambda x: gr.update(visible=x=="csv"), inputs=data_src, outputs=file_upload)
|
| 212 |
+
timeframe.change(update_horizon_label, inputs=timeframe, outputs=horizon)
|
| 213 |
+
|
| 214 |
+
run_button.click(
|
| 215 |
+
run_dashboard,
|
| 216 |
+
inputs=[
|
| 217 |
+
data_src, ticker, file_upload, timeframe, start_date, end_date, horizon, indicators,
|
| 218 |
+
include_sentiment, news_api_key, alpha_api_key, finnhub_api_key, twelvedata_api_key, gr.Number(value=10000, visible=False), gr.Number(value=0.01, visible=False), model,
|
| 219 |
+
hidden_units, n_layers, epochs, learning_rate, beta1, beta2, weight_decay, dropout,
|
| 220 |
+
window_size, test_split, rsi_mid, macd_sens, adx_thr, sent_thr, vote_buy, vote_sell,
|
| 221 |
+
feat_selector, feat_threshold
|
| 222 |
+
],
|
| 223 |
+
outputs=[
|
| 224 |
+
chart_output, sentiment_output, signals_output, backtest_output, future_forecast_output, future_forecast_table,
|
| 225 |
+
r2_output, error_output, precision_recall_plot, risk_output, loss_output, architecture_output,
|
| 226 |
+
output_text, gr.File(label="Chart PNG"), gr.File(label="Signals CSV"), gr.File(label="Predictions CSV"), gr.Plot(label="Signals Plot"), log_output
|
| 227 |
+
]
|
| 228 |
+
)
|
| 229 |
+
except Exception as e:
|
| 230 |
+
logging.error(f"Main interface creation failed: {str(e)}")
|
| 231 |
+
return gr.Blocks().queue().launch()
|
| 232 |
+
|
| 233 |
+
if __name__ == "__main__":
|
| 234 |
+
main_interface().queue().launch()
|