Download app.py from EmpFahad/Forex: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/spaces/EmpFahad/Forex/resolve/main/app.py
- Command line
-
hf download hf://spaces/EmpFahad/Forex/app.py
-
curl -L -o app.py https://huggingface.co/spaces/EmpFahad/Forex/resolve/main/app.py
11.4 kB
| import streamlit as st | |
| import pandas as pd | |
| import numpy as np | |
| import plotly.graph_objects as go | |
| from plotly.subplots import make_subplots | |
| import yfinance as yf | |
| from datetime import datetime, timedelta | |
| import warnings | |
| warnings.filterwarnings('ignore') | |
| # Page configuration | |
| st.set_page_config( | |
| page_title="Forex AI Signals - Frank Miller Supply & Demand", | |
| page_icon="π", | |
| layout="wide" | |
| ) | |
| # Custom CSS | |
| st.markdown(""" | |
| <style> | |
| .main { padding: 0rem 1rem; } | |
| .buy-signal { | |
| background-color: #00ff0020; | |
| border-left: 4px solid #00ff00; | |
| padding: 1rem; | |
| border-radius: 0.5rem; | |
| margin: 0.5rem 0; | |
| } | |
| .sell-signal { | |
| background-color: #ff000020; | |
| border-left: 4px solid #ff0000; | |
| padding: 1rem; | |
| border-radius: 0.5rem; | |
| margin: 0.5rem 0; | |
| } | |
| .neutral-signal { | |
| background-color: #ffff0020; | |
| border-left: 4px solid #ffff00; | |
| padding: 1rem; | |
| border-radius: 0.5rem; | |
| margin: 0.5rem 0; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| class SupplyDemandAnalyzer: | |
| def __init__(self, data): | |
| self.data = data | |
| def find_supply_zones(self, window=20, tolerance=0.002): | |
| supply_zones = [] | |
| highs = self.data['High'].values | |
| for i in range(window, len(highs) - window): | |
| zone_high = max(highs[i-window:i+window]) | |
| touch_count = 0 | |
| for j in range(max(0, i-50), i): | |
| if abs(self.data['High'].iloc[j] - zone_high) / zone_high < tolerance: | |
| touch_count += 1 | |
| if touch_count >= 2: | |
| supply_zones.append({ | |
| 'level': zone_high, | |
| 'strength': touch_count, | |
| 'type': 'supply' | |
| }) | |
| return supply_zones | |
| def find_demand_zones(self, window=20, tolerance=0.002): | |
| demand_zones = [] | |
| lows = self.data['Low'].values | |
| for i in range(window, len(lows) - window): | |
| zone_low = min(lows[i-window:i+window]) | |
| touch_count = 0 | |
| for j in range(max(0, i-50), i): | |
| if abs(self.data['Low'].iloc[j] - zone_low) / zone_low < tolerance: | |
| touch_count += 1 | |
| if touch_count >= 2: | |
| demand_zones.append({ | |
| 'level': zone_low, | |
| 'strength': touch_count, | |
| 'type': 'demand' | |
| }) | |
| return demand_zones | |
| def calculate_rsi(self, period=14): | |
| delta = self.data['Close'].diff() | |
| gain = (delta.where(delta > 0, 0)).rolling(window=period).mean() | |
| loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean() | |
| rs = gain / loss | |
| rsi = 100 - (100 / (1 + rs)) | |
| return rsi | |
| def calculate_macd(self): | |
| exp1 = self.data['Close'].ewm(span=12, adjust=False).mean() | |
| exp2 = self.data['Close'].ewm(span=26, adjust=False).mean() | |
| macd = exp1 - exp2 | |
| signal = macd.ewm(span=9, adjust=False).mean() | |
| histogram = macd - signal | |
| return macd, signal, histogram | |
| def fetch_data(symbol, period='2d', interval='5m'): | |
| try: | |
| ticker = yf.Ticker(symbol) | |
| data = ticker.history(period=period, interval=interval) | |
| return data | |
| except Exception as e: | |
| st.error(f"Error: {str(e)}") | |
| return None | |
| def generate_signals(analyzer): | |
| signals = [] | |
| current_price = analyzer.data['Close'].iloc[-1] | |
| # RSI Signal | |
| rsi = analyzer.calculate_rsi().iloc[-1] | |
| if rsi < 30: | |
| signals.append({'indicator': 'RSI', 'signal': 'BUY', 'strength': 0.8, 'value': f'{rsi:.2f}'}) | |
| elif rsi > 70: | |
| signals.append({'indicator': 'RSI', 'signal': 'SELL', 'strength': 0.8, 'value': f'{rsi:.2f}'}) | |
| else: | |
| signals.append({'indicator': 'RSI', 'signal': 'NEUTRAL', 'strength': 0.3, 'value': f'{rsi:.2f}'}) | |
| # MACD Signal | |
| macd, signal, hist = analyzer.calculate_macd() | |
| if macd.iloc[-1] > signal.iloc[-1]: | |
| signals.append({'indicator': 'MACD', 'signal': 'BUY', 'strength': 0.7, 'value': 'Bullish'}) | |
| else: | |
| signals.append({'indicator': 'MACD', 'signal': 'SELL', 'strength': 0.7, 'value': 'Bearish'}) | |
| # Supply/Demand Zones | |
| supply_zones = analyzer.find_supply_zones() | |
| demand_zones = analyzer.find_demand_zones() | |
| for zone in supply_zones: | |
| if abs(current_price - zone['level']) / current_price < 0.005: | |
| signals.append({'indicator': 'Supply Zone', 'signal': 'SELL', 'strength': 0.9, 'value': f'${zone["level"]:.4f}'}) | |
| for zone in demand_zones: | |
| if abs(current_price - zone['level']) / current_price < 0.005: | |
| signals.append({'indicator': 'Demand Zone', 'signal': 'BUY', 'strength': 0.9, 'value': f'${zone["level"]:.4f}'}) | |
| # Calculate final signal | |
| buy_strength = sum(s['strength'] for s in signals if s['signal'] == 'BUY') | |
| sell_strength = sum(s['strength'] for s in signals if s['signal'] == 'SELL') | |
| if buy_strength > sell_strength: | |
| final_signal = 'BUY' | |
| confidence = (buy_strength / (buy_strength + sell_strength)) * 100 | |
| elif sell_strength > buy_strength: | |
| final_signal = 'SELL' | |
| confidence = (sell_strength / (buy_strength + sell_strength)) * 100 | |
| else: | |
| final_signal = 'NEUTRAL' | |
| confidence = 50 | |
| return final_signal, confidence, signals | |
| def main(): | |
| st.title("π€ AI Forex Signals - Frank Miller Supply & Demand") | |
| st.markdown("### Real-time Analysis with Supply/Demand Zones") | |
| # Sidebar | |
| with st.sidebar: | |
| st.header("βοΈ Settings") | |
| symbol = st.selectbox( | |
| "Trading Pair", | |
| ["GC=F", "XAUUSD=X", "EURUSD=X", "GBPUSD=X", "USDJPY=X"], | |
| help="GC=F = Gold Futures" | |
| ) | |
| interval = st.selectbox( | |
| "Timeframe", | |
| ["5m", "15m", "30m", "1h", "4h", "1d"], | |
| index=0 | |
| ) | |
| auto_refresh = st.checkbox("Auto-refresh (30 seconds)", value=False) | |
| if st.button("π Refresh"): | |
| st.rerun() | |
| # Map intervals | |
| interval_map = {"5m": "5m", "15m": "15m", "30m": "30m", "1h": "1h", "4h": "1h", "1d": "1d"} | |
| period_map = {"5m": "1d", "15m": "2d", "30m": "3d", "1h": "5d", "4h": "1mo", "1d": "3mo"} | |
| period = period_map.get(interval, "2d") | |
| yf_interval = interval_map.get(interval, "5m") | |
| # Fetch data | |
| with st.spinner("Loading market data..."): | |
| data = fetch_data(symbol, period=period, interval=yf_interval) | |
| if data is not None and not data.empty: | |
| analyzer = SupplyDemandAnalyzer(data) | |
| final_signal, confidence, signals = generate_signals(analyzer) | |
| # Display current price | |
| current_price = data['Close'].iloc[-1] | |
| prev_price = data['Close'].iloc[-2] | |
| change = current_price - prev_price | |
| change_pct = (change / prev_price) * 100 | |
| col1, col2, col3, col4 = st.columns(4) | |
| with col1: | |
| st.metric("Current Price", f"${current_price:.4f}", f"{change:+.4f} ({change_pct:+.2f}%)") | |
| with col2: | |
| st.metric("24h High", f"${data['High'].tail(24).max():.4f}") | |
| with col3: | |
| st.metric("24h Low", f"${data['Low'].tail(24).min():.4f}") | |
| with col4: | |
| st.metric("Volume", f"{data['Volume'].iloc[-1]:.0f}") | |
| # Signal Display | |
| if final_signal == 'BUY': | |
| st.markdown(f""" | |
| <div class="buy-signal"> | |
| <h2 style="color: #00ff00; margin: 0;">π BUY SIGNAL</h2> | |
| <p style="font-size: 1.2rem;">Confidence: {confidence:.1f}%</p> | |
| <hr> | |
| <h4>Signal Details:</h4> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| elif final_signal == 'SELL': | |
| st.markdown(f""" | |
| <div class="sell-signal"> | |
| <h2 style="color: #ff0000; margin: 0;">π SELL SIGNAL</h2> | |
| <p style="font-size: 1.2rem;">Confidence: {confidence:.1f}%</p> | |
| <hr> | |
| <h4>Signal Details:</h4> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| else: | |
| st.markdown(f""" | |
| <div class="neutral-signal"> | |
| <h2 style="color: #ffff00; margin: 0;">β‘οΈ NEUTRAL SIGNAL</h2> | |
| <p style="font-size: 1.2rem;">Wait for clearer setup</p> | |
| <hr> | |
| <h4>Signal Details:</h4> | |
| </div> | |
| """, unsafe_allow_html=True) | |
| # Display individual signals | |
| for sig in signals: | |
| color = "#00ff00" if sig['signal'] == 'BUY' else "#ff0000" if sig['signal'] == 'SELL' else "#ffff00" | |
| st.markdown(f"**{sig['indicator']}:** <span style='color:{color}'>{sig['signal']}</span> - {sig['value']}", unsafe_allow_html=True) | |
| # Create chart | |
| st.subheader("π Live Chart") | |
| fig = go.Figure() | |
| fig.add_trace(go.Candlestick( | |
| x=data.index, | |
| open=data['Open'], | |
| high=data['High'], | |
| low=data['Low'], | |
| close=data['Close'], | |
| name='Price' | |
| )) | |
| # Add supply/demand zones | |
| supply_zones = analyzer.find_supply_zones() | |
| demand_zones = analyzer.find_demand_zones() | |
| for zone in supply_zones[:3]: | |
| fig.add_hline(y=zone['level'], line_dash="dash", line_color="red", | |
| annotation_text=f"Supply (S{zone['strength']})") | |
| for zone in demand_zones[:3]: | |
| fig.add_hline(y=zone['level'], line_dash="dash", line_color="green", | |
| annotation_text=f"Demand (D{zone['strength']})") | |
| fig.update_layout( | |
| title=f"{symbol} - Live Price with Supply/Demand Zones", | |
| yaxis_title="Price", | |
| xaxis_title="Time", | |
| template="plotly_dark", | |
| height=500 | |
| ) | |
| st.plotly_chart(fig, use_container_width=True) | |
| # Display zones in columns | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.subheader("π΄ Supply Zones (Resistance)") | |
| if supply_zones: | |
| for zone in supply_zones[:5]: | |
| st.info(f"Level: ${zone['level']:.4f} | Strength: {zone['strength']} touches") | |
| else: | |
| st.info("No supply zones detected") | |
| with col2: | |
| st.subheader("π’ Demand Zones (Support)") | |
| if demand_zones: | |
| for zone in demand_zones[:5]: | |
| st.success(f"Level: ${zone['level']:.4f} | Strength: {zone['strength']} touches") | |
| else: | |
| st.info("No demand zones detected") | |
| # Auto-refresh | |
| if auto_refresh: | |
| import time | |
| time.sleep(30) | |
| st.rerun() | |
| else: | |
| st.error("Failed to load data. Please check your connection and try again.") | |
| # Footer | |
| st.markdown("---") | |
| st.caption("β οΈ Disclaimer: For educational purposes only. Trading involves substantial risk.") | |
| st.caption(f"Last updated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") | |
| if __name__ == "__main__": | |
| main() |