Spaces:
Build error
Build error
Download src/ui/app.py from leovean/Forex-AI-Analyst: direct link, hf CLI and curl.
- Browser
- Download file 16 kB
-
https://huggingface.co/spaces/leovean/Forex-AI-Analyst/resolve/main/src/ui/app.py
- Command line
-
hf download hf://spaces/leovean/Forex-AI-Analyst/src/ui/app.py
-
curl -L -o app.py https://huggingface.co/spaces/leovean/Forex-AI-Analyst/resolve/main/src/ui/app.py
16 kB
| # src/ui/app.py | |
| import os | |
| import gradio as gr | |
| import numpy as np | |
| import pandas as pd | |
| from PIL import Image | |
| import cv2 | |
| from typing import Optional, Tuple | |
| import torch | |
| import xgboost as xgb | |
| import joblib | |
| import traceback | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| from ..vision.pattern_detector import PatternDetector | |
| from ..models.transformer_lstm import TransformerLSTMHybrid | |
| from ..models.ensemble import SuperLearnerEnsemble | |
| from ..analysis.signal_generator import TradeSignalGenerator | |
| from ..data.fetcher import DataFetcher | |
| class ForexAIAnalyst: | |
| """Main application class that ties everything together.""" | |
| def __init__(self): | |
| print("π Initializing Forex AI Analyst...") | |
| if not os.getenv("DERIV_APP_ID") or not os.getenv("DERIV_API_TOKEN"): | |
| print("β οΈ Deriv API credentials not found. Synthetic indices will not load data.") | |
| print(" Set DERIV_APP_ID and DERIV_API_TOKEN in .env file to enable.") | |
| self.pattern_detector = PatternDetector() | |
| self.data_fetcher = DataFetcher() | |
| self.transformer_lstm = self._initialize_transformer_lstm() | |
| self.ensemble = self._initialize_ensemble() | |
| self.signal_generator = TradeSignalGenerator( | |
| transformer_lstm_model=self.transformer_lstm, | |
| ensemble_model=self.ensemble, | |
| pattern_detector=self.pattern_detector | |
| ) | |
| print("β AI Analyst ready!") | |
| def _initialize_transformer_lstm(self) -> Optional[TransformerLSTMHybrid]: | |
| try: | |
| model = TransformerLSTMHybrid( | |
| input_dim=20, d_model=128, nhead=8, num_encoder_layers=3, | |
| lstm_hidden_dim=128, lstm_num_layers=2, dropout=0.1, output_dim=1 | |
| ) | |
| try: | |
| model.load_state_dict(torch.load('models/transformer_lstm.pth', map_location='cpu')) | |
| model.eval() | |
| print("π¦ Loaded pre-trained Transformer-LSTM model") | |
| except Exception: | |
| print("β οΈ Using untrained Transformer-LSTM model (random weights)") | |
| return model | |
| except Exception as e: | |
| print(f"β οΈ Could not initialize Transformer-LSTM: {e}") | |
| return None | |
| def _initialize_ensemble(self) -> SuperLearnerEnsemble: | |
| ensemble = SuperLearnerEnsemble() | |
| try: | |
| ensemble.load("models/ensemble_fold0") | |
| print("π¦ Loaded pre-trained Super-Learner Ensemble") | |
| except Exception: | |
| print("β οΈ Using untrained Super-Learner Ensemble") | |
| return ensemble | |
| def analyze_trade( | |
| self, | |
| pair: str, | |
| chart_4h: Optional[np.ndarray], | |
| chart_1h: Optional[np.ndarray], | |
| chart_15m: Optional[np.ndarray] | |
| ) -> Tuple[pd.DataFrame, str, Image.Image, pd.DataFrame]: | |
| if chart_4h is None and chart_1h is None and chart_15m is None: | |
| return self._empty_result("Please upload at least one chart image.") | |
| try: | |
| print(f"π Fetching data for {pair}...") | |
| df_4h = self.data_fetcher.fetch_data(pair, period="3mo", interval="4h") | |
| df_1h = self.data_fetcher.fetch_data(pair, period="1mo", interval="1h") | |
| df_15m = self.data_fetcher.fetch_data(pair, period="7d", interval="15m") | |
| if df_4h.empty: | |
| return self._empty_result(f"Could not fetch data for {pair}. Check credentials or network.") | |
| primary_chart = None | |
| if chart_4h is not None: | |
| primary_chart = chart_4h | |
| elif chart_1h is not None: | |
| primary_chart = chart_1h | |
| elif chart_15m is not None: | |
| primary_chart = chart_15m | |
| if primary_chart is None: | |
| primary_chart = np.zeros((100, 100, 3), dtype=np.uint8) | |
| print("π§ Analyzing patterns and generating signals...") | |
| analysis = self.signal_generator.analyze_charts( | |
| chart_4h=chart_4h if chart_4h is not None else np.zeros((100, 100, 3), dtype=np.uint8), | |
| chart_1h=chart_1h if chart_1h is not None else np.zeros((100, 100, 3), dtype=np.uint8), | |
| chart_15m=chart_15m if chart_15m is not None else np.zeros((100, 100, 3), dtype=np.uint8), | |
| pair=pair, | |
| historical_data=df_4h | |
| ) | |
| summary_df = self._create_summary_dataframe(analysis) | |
| risk_df = self._create_risk_dataframe(analysis) | |
| annotated_chart = self._create_annotated_chart(primary_chart, analysis) | |
| detailed_text = self._generate_detailed_analysis(analysis) | |
| return summary_df, detailed_text, annotated_chart, risk_df | |
| except Exception as e: | |
| error_msg = f"Error during analysis: {str(e)}\n\n{traceback.format_exc()}" | |
| print(error_msg) | |
| return self._empty_result(error_msg) | |
| def _create_summary_dataframe(self, analysis: dict) -> pd.DataFrame: | |
| setup = analysis.get('trade_setup', {}) | |
| confidence = analysis.get('confidence', {}) | |
| pattern = analysis.get('pattern_analysis', {}) | |
| trend = analysis.get('trend', {}) | |
| additional = analysis.get('additional_features', {}) | |
| data = { | |
| 'Metric': [ | |
| 'Pair', 'Direction', 'Entry Price', 'Stop Loss', 'Take Profit', | |
| 'Risk/Reward', 'Win Probability', 'Pattern Sentiment', | |
| 'Primary Trend', 'Volatility State', 'Market Regime' | |
| ], | |
| 'Value': [ | |
| analysis.get('pair', 'N/A'), | |
| setup.get('direction', 'NEUTRAL'), | |
| f"{setup.get('entry', 0):.5f}", | |
| f"{setup.get('stop_loss', 0):.5f}", | |
| f"{setup.get('take_profit', 0):.5f}", | |
| f"1:{setup.get('risk_reward_ratio', 0):.1f}", | |
| f"{confidence.get('overall_probability', 0):.1f}%", | |
| pattern.get('sentiment', 'NEUTRAL'), | |
| trend.get('primary_trend', 'NEUTRAL'), | |
| additional.get('volatility_state', 'NORMAL'), | |
| additional.get('market_regime', 'UNKNOWN') | |
| ] | |
| } | |
| return pd.DataFrame(data) | |
| def _create_risk_dataframe(self, analysis: dict) -> pd.DataFrame: | |
| risk = analysis.get('risk_analysis', {}) | |
| data = { | |
| 'Risk Metric': [ | |
| 'Probability (Take Profit)', 'Probability (Stop Loss)', | |
| 'Probability (Neutral)', 'Expected Return', | |
| 'Value at Risk (95%)', 'Expected Shortfall (95%)', | |
| 'Sharpe Estimate', 'Confidence Score' | |
| ], | |
| 'Value': [ | |
| f"{risk.get('probability_take_profit', 0)*100:.1f}%", | |
| f"{risk.get('probability_stop_loss', 0)*100:.1f}%", | |
| f"{risk.get('probability_neutral', 0)*100:.1f}%", | |
| f"{risk.get('expected_return_pct', 0):.2f}%", | |
| f"{risk.get('value_at_risk_95', 0):.2f}%", | |
| f"{risk.get('expected_shortfall_95', 0):.2f}%", | |
| f"{risk.get('sharpe_estimate', 0):.3f}", | |
| f"{risk.get('confidence_score', 0):.1f}%" | |
| ] | |
| } | |
| return pd.DataFrame(data) | |
| def _create_annotated_chart(self, image: np.ndarray, analysis: dict) -> Optional[Image.Image]: | |
| if image is None or image.size == 0: | |
| return None | |
| img_copy = image.copy() | |
| h, w = img_copy.shape[:2] | |
| setup = analysis.get('trade_setup', {}) | |
| direction = setup.get('direction', 'NEUTRAL') | |
| y_entry = int(h * 0.5) | |
| y_sl = int(h * 0.6) if "BULLISH" in direction else int(h * 0.4) | |
| y_tp = int(h * 0.4) if "BULLISH" in direction else int(h * 0.6) | |
| cv2.line(img_copy, (0, y_entry), (w, y_entry), (255, 255, 0), 2) | |
| cv2.line(img_copy, (0, y_sl), (w, y_sl), (0, 0, 255), 2) | |
| cv2.line(img_copy, (0, y_tp), (w, y_tp), (0, 255, 0), 2) | |
| font = cv2.FONT_HERSHEY_SIMPLEX | |
| cv2.putText(img_copy, f"Entry: {setup.get('entry', 0):.5f}", (10, y_entry-10), | |
| font, 0.5, (255, 255, 0), 1) | |
| cv2.putText(img_copy, f"SL: {setup.get('stop_loss', 0):.5f}", (10, y_sl-10), | |
| font, 0.5, (0, 0, 255), 1) | |
| cv2.putText(img_copy, f"TP: {setup.get('take_profit', 0):.5f}", (10, y_tp-10), | |
| font, 0.5, (0, 255, 0), 1) | |
| title = f"{analysis.get('pair', 'Unknown')} - {direction} (R:R 1:{setup.get('risk_reward_ratio', 0):.1f})" | |
| cv2.putText(img_copy, title, (10, 30), font, 0.7, (255, 255, 255), 2) | |
| return Image.fromarray(cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB)) | |
| def _generate_detailed_analysis(self, analysis: dict) -> str: | |
| try: | |
| setup = analysis.get('trade_setup', {}) | |
| trend = analysis.get('trend', {}) | |
| pattern = analysis.get('pattern_analysis', {}) | |
| additional = analysis.get('additional_features', {}) | |
| risk = analysis.get('risk_analysis', {}) | |
| confidence = analysis.get('confidence', {}) | |
| pair = analysis.get('pair', 'Unknown') | |
| direction = setup.get('direction', 'NEUTRAL') | |
| entry = setup.get('entry', 0.0) | |
| stop_loss = setup.get('stop_loss', 0.0) | |
| take_profit = setup.get('take_profit', 0.0) | |
| rr_ratio = setup.get('risk_reward_ratio', 0.0) | |
| primary_trend = trend.get('primary_trend', 'NEUTRAL') | |
| long_term = trend.get('long_term', 'N/A') | |
| medium_term = trend.get('medium_term', 'N/A') | |
| short_term = trend.get('short_term', 'N/A') | |
| market_structure = additional.get('market_structure', {}) | |
| structure = market_structure.get('structure', 'UNKNOWN') | |
| sentiment = pattern.get('sentiment', 'NEUTRAL') | |
| strength = pattern.get('strength', 0.0) * 100 | |
| patterns_found = pattern.get('patterns_found', []) | |
| patterns_str = ', '.join(patterns_found) if patterns_found else 'None' | |
| highest_pattern = pattern.get('highest_confidence_pattern') | |
| pattern_name = highest_pattern.get('pattern', 'N/A') if isinstance(highest_pattern, dict) else 'N/A' | |
| prob_tp = risk.get('probability_take_profit', 0.0) * 100 | |
| prob_sl = risk.get('probability_stop_loss', 0.0) * 100 | |
| expected_return = risk.get('expected_return_pct', 0.0) | |
| var_95 = risk.get('value_at_risk_95', 0.0) | |
| confidence_score = risk.get('confidence_score', 0.0) | |
| support_resistance = additional.get('support_resistance', {}) | |
| support = support_resistance.get('support', []) | |
| resistance = support_resistance.get('resistance', []) | |
| support_str = ', '.join([f'{s:.5f}' for s in support]) if support else 'N/A' | |
| resistance_str = ', '.join([f'{r:.5f}' for r in resistance]) if resistance else 'N/A' | |
| volatility_state = additional.get('volatility_state', 'NORMAL') | |
| key_levels = additional.get('key_levels', {}) | |
| prev_high = key_levels.get('previous_day_high', 0.0) | |
| prev_low = key_levels.get('previous_day_low', 0.0) | |
| overall_prob = confidence.get('overall_probability', 0.0) | |
| pattern_conf = confidence.get('pattern_confidence', 0.0) | |
| model_conf = confidence.get('model_confidence', 0.0) | |
| sentiment_score = additional.get('sentiment_score', 0.0) | |
| market_regime = additional.get('market_regime', 'UNKNOWN') | |
| sentiment_text = "Bullish" if sentiment_score > 0.1 else "Bearish" if sentiment_score < -0.1 else "Neutral" | |
| risk_pct = abs(entry - stop_loss) / entry * 100 if entry != 0 else 0.0 | |
| reward_pct = abs(take_profit - entry) / entry * 100 if entry != 0 else 0.0 | |
| text = f""" | |
| π TRADE ANALYSIS FOR {pair} | |
| {'='*50} | |
| π― TRADE SETUP | |
| Direction: {direction} | |
| Entry: {entry:.5f} | |
| Stop Loss: {stop_loss:.5f} (Risk: {risk_pct:.2f}%) | |
| Take Profit: {take_profit:.5f} (Reward: {reward_pct:.2f}%) | |
| Risk/Reward: 1:{rr_ratio:.1f} | |
| π TREND ANALYSIS | |
| Primary Trend: {primary_trend} | |
| Long-term: {long_term} | |
| Medium-term: {medium_term} | |
| Short-term: {short_term} | |
| Market Structure: {structure} | |
| π PATTERN RECOGNITION | |
| Sentiment: {sentiment} (Strength: {strength:.1f}%) | |
| Patterns Detected: {patterns_str} | |
| Highest Confidence Pattern: {pattern_name} | |
| π° MARKET SENTIMENT & REGIME | |
| Sentiment Score: {sentiment_score:.2f} ({sentiment_text}) | |
| Market Regime: {market_regime} | |
| βοΈ RISK ASSESSMENT | |
| Win Probability: {prob_tp:.1f}% | |
| Loss Probability: {prob_sl:.1f}% | |
| Expected Return: {expected_return:.2f}% | |
| Value at Risk (95%): {var_95:.2f}% | |
| Confidence Score: {confidence_score:.1f}% | |
| π KEY LEVELS | |
| Support: {support_str} | |
| Resistance: {resistance_str} | |
| Volatility: {volatility_state} | |
| Previous Day High: {prev_high:.5f} | |
| Previous Day Low: {prev_low:.5f} | |
| π‘ AI CONFIDENCE | |
| Overall Probability: {overall_prob:.1f}% | |
| Pattern Confidence: {pattern_conf:.1f}% | |
| Model Confidence: {model_conf:.1f}% | |
| β οΈ DISCLAIMER: This is AI-generated analysis for educational purposes only. | |
| """ | |
| return text | |
| except Exception as e: | |
| return f"Error generating analysis text: {str(e)}" | |
| def _empty_result(self, message: str) -> Tuple[pd.DataFrame, str, None, pd.DataFrame]: | |
| empty_df = pd.DataFrame({'Status': [message]}) | |
| return empty_df, message, None, empty_df | |
| def create_ui(): | |
| analyst = ForexAIAnalyst() | |
| with gr.Blocks(title="Forex AI Analyst", theme=gr.themes.Soft()) as demo: | |
| gr.Markdown(""" | |
| # π Forex AI Analyst (Enhanced) | |
| ### Advanced AI-Powered Trading Analysis System | |
| Upload your chart screenshots (4H, 1H, 15M) and get instant trade analysis. | |
| Now with Super-Learner Ensemble, Market Regime Detection, and Sentiment Analysis. | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| pair_dropdown = gr.Dropdown( | |
| choices=DataFetcher.get_available_pairs(), | |
| label="Select Trading Pair", | |
| value="EUR/USD" | |
| ) | |
| chart_4h = gr.Image(label="Upload 4H Chart", type="numpy") | |
| chart_1h = gr.Image(label="Upload 1H Chart", type="numpy") | |
| chart_15m = gr.Image(label="Upload 15M Chart", type="numpy") | |
| analyze_btn = gr.Button("π Analyze Trade", variant="primary", size="lg") | |
| with gr.Column(scale=2): | |
| with gr.Tab("Trade Summary"): | |
| summary_df = gr.Dataframe(label="Trade Setup", wrap=True) | |
| with gr.Tab("Detailed Analysis"): | |
| analysis_text = gr.Textbox(label="Full Analysis", lines=22, max_lines=30) | |
| with gr.Tab("Risk Metrics"): | |
| risk_df = gr.Dataframe(label="Monte Carlo Risk Analysis") | |
| with gr.Tab("Annotated Chart"): | |
| annotated_chart = gr.Image(label="Chart with Trade Levels") | |
| analyze_btn.click( | |
| fn=analyst.analyze_trade, | |
| inputs=[pair_dropdown, chart_4h, chart_1h, chart_15m], | |
| outputs=[summary_df, analysis_text, annotated_chart, risk_df] | |
| ) | |
| gr.Markdown(""" | |
| --- | |
| ### π How to Use | |
| 1. Select your trading pair from the dropdown. | |
| 2. Upload clear screenshots of your charts (4H, 1H, 15M). | |
| 3. Click "Analyze Trade". | |
| 4. Review the AI-generated analysis, including sentiment and regime context. | |
| """) | |
| return demo | |
| if __name__ == "__main__": | |
| demo = create_ui() | |
| demo.launch(share=True) |