Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files4 unmodified lines5678910130 unmodified lines14114214314414514614728 unmodified lines1761771781791801811821831841851861871881891901911921931941951967 unmodified lines2042052062072082092109 unmodified lines2202212222232242252262272281 unmodified line23023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131215 unmodified lines3283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823838 unmodified lines3923933943953963973983994004014022 unmodified lines4054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374387 unmodified lines44644744844945045145267 unmodified lines52052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258335 unmodified lines61962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065112 unmodified lines6646656666676686696706 unmodified lines677678679680681682683684685686687688689690691692693694695696697125 unmodified lines82382482582682782882982 unmodified lines912913914915916917918174 unmodified lines1093109410951096109710981099423 unmodified lines152315241525152615271528152920 unmodified lines155015511552155315541555155617 unmodified lines157415751576157715781579158012 unmodified lines15931594159515961597159815994 unmodified lines16041605160616071608160916101611161216131614161516161617161816191620162116224 unmodified linesimport zipfileimport urllib.requestimport xml.etree.ElementTree as ETfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom datetime import datetime, timezone, timedelta130 unmodified linesdef repair_fx_daily_df(df_d1: pd.DataFrame, yf_symbol: str, latest_close: float | None = None, dec: int = 5) -> pd.DataFrame:"""يصلح خلل Yahoo Finance في شموع D1 للفوركس (حيث يساوي الإغلاق الافتتاح)."""if df_d1 is None or df_d1.empty or not (yf_symbol or "").upper().endswith("=X"):return df_d1df = df_d1.copy().reset_index(drop=True)28 unmodified linesreturn df.resample(rule).agg(agg).dropna(subset=["Open", "High", "Low", "Close"])def fetch_with_retry(yf_symbol: str, period: str, interval: str, retries: int = 4):for attempt in range(1, retries + 1):try:if attempt <= 2:hist = yf.Ticker(yf_symbol).history(period=period, interval=interval, timeout=20)else:hist = yf.download(yf_symbol, period=period, interval=interval,progress=False, auto_adjust=False, threads=False)if hist is not None and not hist.empty:return histexcept Exception:passtime.sleep(1.1 * attempt)return None7 unmodified linesreturn format_yf_dataframe(resample_ohlcv(raw, "4h"), asset, yf_symbol).tail(count)tf_map = {"MN1": ("1mo", "max"), "W1": ("1wk", "max"), "D1": ("1d", "max"),"H1": ("1h", "730d" if count > 300 else "180d"),"M15": ("15m", "60d" if count > 250 else "15d"),"M5": ("5m", "60d" if count > 288 else "5d"),9 unmodified lines# ==========================================# 3. الأخبار الاقتصادية والحسابات الكمية للـ AI# ==========================================_CALENDAR_CACHE = {"ts": 0.0, "events": []}def fetch_economic_calendar_events(include_medium: bool = True, include_next_week: bool = True) -> list:1 unmodified linetarget_ccys = {"USD", "EUR", "GBP", "JPY", "AUD", "CAD", "CHF"}allowed_imp = {"High", "Medium"} if include_medium else {"High"}if _CALENDAR_CACHE["events"] and (now_ts - _CALENDAR_CACHE["ts"]) < 1200:return [ev for ev in _CALENDAR_CACHE["events"] if ev["impact"] in allowed_imp]headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36","Accept": "application/json, application/xml, text/xml, */*",}json_urls = ["https://nfs.faireconomy.media/ff_calendar_thisweek.json"]if include_next_week:json_urls.append("https://nfs.faireconomy.media/ff_calendar_nextweek.json")events, seen = [], set()for url in json_urls:try:req = urllib.request.Request(url, headers=headers)with urllib.request.urlopen(req, timeout=7) as resp:data = json.loads(resp.read().decode("utf-8"))for ev in data:imp = ev.get("impact", "")ccy = ev.get("country", "")dstr = ev.get("date", "")title = ev.get("title", "")if imp not in {"High", "Medium"} or ccy not in target_ccys or not dstr:continueev_dt = datetime.fromisoformat(dstr).astimezone(timezone.utc)key = (ev_dt.isoformat(), ccy, title)if key in seen:continueseen.add(key)events.append({"dt_utc": ev_dt, "currency": ccy, "impact": imp, "title": title,"forecast": ev.get("forecast") or "-", "previous": ev.get("previous") or "-",})except Exception:continueif not events:xml_urls = ["https://nfs.faireconomy.media/ff_calendar_thisweek.xml"]if include_next_week:xml_urls.append("https://nfs.faireconomy.media/ff_calendar_nextweek.xml")for url in xml_urls:try:req = urllib.request.Request(url, headers=headers)with urllib.request.urlopen(req, timeout=7) as resp:root = ET.fromstring(resp.read())for item in root.findall("event"):imp = (item.findtext("impact") or "").strip()ccy = (item.findtext("country") or "").strip()d_part = (item.findtext("date") or "").strip()t_part = (item.findtext("time") or "").strip()title = (item.findtext("title") or "").strip()if imp not in {"High", "Medium"} or ccy not in target_ccys or not d_part:continuetry:dt_str = f"{d_part} {t_part}" if t_part and ("am" in t_part.lower() or "pm" in t_part.lower()) else f"{d_part} 12:00am"ev_dt = datetime.strptime(dt_str, "%m-%d-%Y %I:%M%p").replace(tzinfo=timezone.utc)except Exception:continuekey = (ev_dt.isoformat(), ccy, title)if key in seen:continueseen.add(key)events.append({"dt_utc": ev_dt, "currency": ccy, "impact": imp, "title": title,"forecast": (item.findtext("forecast") or "").strip() or "-","previous": (item.findtext("previous") or "").strip() or "-",})except Exception:continueevents.sort(key=lambda x: x["dt_utc"])if events:_CALENDAR_CACHE["ts"] = now_ts_CALENDAR_CACHE["events"] = eventsreturn [ev for ev in events if ev["impact"] in allowed_imp]def get_session_status_summary(now_utc: datetime) -> str:15 unmodified linesdef compute_asset_quant_metrics(df: pd.DataFrame, asset_name: str, yf_symbol: str) -> dict:dec = get_asset_decimals(asset_name, yf_symbol)close, high, low = df["close"].astype(float), df["high"].astype(float), df["low"].astype(float)last_close = float(close.iloc[-1])pct_chg = ((last_close - float(close.iloc[-2])) / float(close.iloc[-2]) * 100.0) if len(close) >= 2 else 0.0rsi_str = "N/A"if len(close) >= 15:d = close.diff()gain = d.clip(lower=0).ewm(alpha=1 / 14, min_periods=14, adjust=False).mean()loss = (-d.clip(upper=0)).ewm(alpha=1 / 14, min_periods=14, adjust=False).mean()rsi_val = (100 - (100 / (1 + gain / loss.replace(0, np.nan)))).iloc[-1]if pd.notna(rsi_val):rsi_str = f"{float(rsi_val):.1f}"atr_str = "N/A"if len(close) >= 15:tr = pd.concat([high - low, (high - close.shift()).abs(), (low - close.shift()).abs()], axis=1).max(axis=1)atr_val = tr.ewm(alpha=1 / 14, min_periods=14, adjust=False).mean().iloc[-1]if pd.notna(atr_val):atr_str = fmt_num(atr_val, dec)ema20 = fmt_num(close.ewm(span=20, adjust=False).mean().iloc[-1], dec) if len(close) >= 20 else "N/A"ema50 = fmt_num(close.ewm(span=50, adjust=False).mean().iloc[-1], dec) if len(close) >= 50 else "N/A"ema200 = fmt_num(close.ewm(span=200, adjust=False).mean().iloc[-1], dec) if len(close) >= 150 else "N/A"lb50 = df.tail(50)h50, l50 = float(lb50["high"].max()), float(lb50["low"].min())mid50 = (h50 + l50) / 2.0pos50 = ((last_close - l50) / (h50 - l50) * 100.0) if h50 > l50 else 50.0vol_str = "N/A"if "tick_volume" in df.columns:vols = df["tick_volume"].astype(float)if vols.tail(20).sum() > 0:avg20 = float(vols.tail(21).iloc[:-1].mean()) if len(vols) >= 21 else float(vols.mean())if avg20 > 0:vol_str = f"{float(vols.iloc[-1]) / avg20:.2f}x"return {"last_time": str(df["time"].iloc[-1])[:16], "last_close": fmt_num(last_close, dec),"pct_chg": f"{pct_chg:+.2f}%", "rsi14": rsi_str, "atr14": atr_str,"ema20": ema20, "ema50": ema50, "ema200": ema200,"h50": fmt_num(h50, dec), "l50": fmt_num(l50, dec), "mid50": fmt_num(mid50, dec),"pos50": f"{pos50:.1f}%", "vol_ratio": vol_str,}def extract_daily_levels(tfs: dict, asset_name: str, yf_symbol: str) -> dict:dec = get_asset_decimals(asset_name, yf_symbol)daily_df = tfs["D1"].copy() if ("D1" in tfs and len(tfs["D1"]) >= 2) else Noneif daily_df is None:src = tfs.get("H1") if "H1" in tfs else (tfs.get("H4") if "H4" in tfs else tfs.get("M15"))if src is not None and not src.empty:8 unmodified linesif daily_df is None or len(daily_df) < 2:return {"pdh": "N/A", "pdl": "N/A", "pdc": "N/A", "cdh": "N/A", "cdl": "N/A"}valid_days = daily_df[daily_df["high"].astype(float) > daily_df["low"].astype(float)]if len(valid_days) >= 2:daily_df = valid_daysprev_d, curr_d = daily_df.iloc[-2], daily_df.iloc[-1]return {"pdh": fmt_num(prev_d["high"], dec), "pdl": fmt_num(prev_d["low"], dec),"pdc": fmt_num(prev_d["close"], dec), "cdh": fmt_num(curr_d["high"], dec),2 unmodified linesdef compute_aligned_correlation(frames_dict: dict, window: int = 60, tf_name: str = "H1"):"""يوحّد طوابع الوقت (:00 و :30) ويحسب الارتباط على ساعات التداول المشتركة الحقيقية فقط."""freq_map = {"M5": "5min", "M15": "15min", "H1": "1h", "H4": "4h", "D1": "1D"}freq = freq_map.get(tf_name, "1h")series_map = {}for asset, df in frames_dict.items():if df is None or len(df) < 15:continuetmp = df[["time", "close"]].copy()tmp["time"] = pd.to_datetime(tmp["time"])if freq == "1D":tmp["time"] = (tmp["time"] + pd.Timedelta(hours=2)).dt.floor("1D")else:tmp["time"] = tmp["time"].dt.floor(freq)series_map[asset] = tmp.groupby("time")["close"].last().astype(float)if len(series_map) < 2:return Nonealigned = pd.DataFrame(series_map).sort_index()returns = aligned.pct_change(fill_method=None)tail_n = window * 3 if freq in ("1h", "15min", "5min") else windowreturns = returns.tail(tail_n)corr = returns.corr(min_periods=8).round(2)return corr if not corr.empty else Nonedef build_ai_precomputed_section(collected_data: dict, ordered_assets: list, symbols_map: dict) -> str:now_utc = datetime.now(timezone.utc)now_local = now_utc + timedelta(hours=2)saved_count = sum(len(collected_data.get(a, {})) for a in ordered_assets)7 unmodified lines"", "---", "## 1. Upcoming Economic Calendar (High & Medium Impact)",]events = fetch_economic_calendar_events(include_medium=True, include_next_week=True)today_date = now_utc.date()upcoming = [ev for ev in events67 unmodified lines# ==========================================# 4. محرك السحب المتوازي والتصدير# ==========================================def _fetch_single_asset_worker(folder_name: str, yf_symbol: str, configs: list, need_h4: bool, h4_count: int, want_m15_fallback: bool, m15_count: int):asset_frames, asset_logs = {}, []h1_raw, m5_raw, m15_saved = None, None, Falsedec = get_asset_decimals(folder_name, yf_symbol)for tf_name, interval, period, count, save_this in configs:hist = fetch_with_retry(yf_symbol, period, interval)time.sleep(0.22)if hist is None or hist.empty:if save_this:asset_logs.append(f"[فشل] {folder_name}_{tf_name}")continueif tf_name == "H1":h1_raw = hist.copy()elif tf_name == "M5":m5_raw = hist.copy()elif tf_name == "M15":m15_saved = Trueif save_this:df = format_yf_dataframe(hist, folder_name, yf_symbol).tail(count)asset_frames[tf_name] = dfasset_logs.append(f"[تم] {folder_name}_{tf_name} ({len(df)} شمعة | {dec}d | UTC)")if want_m15_fallback and not m15_saved and m5_raw is not None and not m5_raw.empty:try:df_m15 = format_yf_dataframe(resample_ohlcv(m5_raw, "15min"), folder_name, yf_symbol).tail(m15_count)asset_frames["M15"] = df_m15asset_logs.append(f"[تم - من M5] {folder_name}_M15 ({len(df_m15)} شمعة | {dec}d | UTC)")except Exception as e:asset_logs.append(f"[خطأ] {folder_name}_M15: {e}")if need_h4:if h1_raw is not None and not h1_raw.empty:try:df_h4 = format_yf_dataframe(resample_ohlcv(h1_raw, "4h"), folder_name, yf_symbol).tail(h4_count)asset_frames["H4"] = df_h4asset_logs.append(f"[تم] {folder_name}_H4 ({len(df_h4)} شمعة | {dec}d | UTC)")except Exception as e:asset_logs.append(f"[خطأ] {folder_name}_H4: {e}")else:asset_logs.append(f"[فشل] {folder_name}_H4 (تعذر جلب H1)")if "D1" in asset_frames and yf_symbol.upper().endswith("=X"):latest_c = Nonefor ref_tf in ("M5", "M15", "H1", "H4", "W1"):if ref_tf in asset_frames and not asset_frames[ref_tf].empty:latest_c = float(asset_frames[ref_tf]["close"].iloc[-1])breakasset_frames["D1"] = repair_fx_daily_df(asset_frames["D1"], yf_symbol, latest_close=latest_c, dec=dec)return folder_name, asset_frames, asset_logsdef package_output(collected_data: dict, ordered_assets: list, symbols_map: dict, logs: list, root_folder: str, base_filename: str, output_format: str):saved_count = sum(len(collected_data.get(a, {})) for a in ordered_assets)precomputed = build_ai_precomputed_section(collected_data, ordered_assets, symbols_map)md_parts = [precomputed]for asset in ordered_assets:35 unmodified linesh4_cnt, m15_fb = (250, 250) if is_update else (300, 0)ordered = list(symbols.keys())collected, logs = {}, []progress(0, desc="جاري الاتصال المتوازي...")with ThreadPoolExecutor(max_workers=4) as ex:futs = {}for name, sym in symbols.items():if is_update:cfgs = [("H1", "1h", "180d", 250, True), ("M15", "15m", "15d", 250, True)]if name in ("EURUSD", "GBPUSD"):cfgs.append(("M5", "5m", "5d", 250, True))else:cfgs = [("MN1", "1mo", "max", 100, True), ("W1", "1wk", "max", 700, True),("D1", "1d", "max", 700, True), ("H1", "1h", "180d", 300, True),]futs[ex.submit(_fetch_single_asset_worker, name, sym, cfgs, True, h4_cnt, is_update, m15_fb)] = namedone = 0for fut in as_completed(futs):a_name, frames, a_logs = fut.result()collected[a_name] = frameslogs.extend(a_logs)done += 1progress(done / len(ordered), desc=f"اكتمل {a_name} ({done}/{len(ordered)})")progress(0.95, desc="جاري حساب المؤشرات وسحب الأخبار القادمة...")return package_output(collected, ordered, symbols, logs, root_folder, base_name, output_format)def fetch_custom_data(selected_assets, extra_tickers_str, selected_timeframes, candle_count, output_format, progress=gr.Progress()):12 unmodified linescnt = max(10, int(candle_count or 250))today_str = datetime.now().strftime("%Y-%m-%d")tf_map = {"MN1": ("1mo", "max"), "W1": ("1wk", "max"), "D1": ("1d", "max"),"H1": ("1h", "730d" if cnt > 300 else "180d"),"M15": ("15m", "60d" if cnt > 250 else "15d"),"M5": ("5m", "60d" if cnt > 288 else "5d"),6 unmodified linescfgs = [(tf, tf_map[tf][0], tf_map[tf][1], cnt, tf in selected_timeframes) for tf in direct]ordered = list(assets_map.keys())collected, logs = {}, []progress(0, desc="جاري سحب البيانات المخصصة...")with ThreadPoolExecutor(max_workers=4) as ex:futs = {ex.submit(_fetch_single_asset_worker, n, s, cfgs, need_h4, cnt, want_m15, cnt): n for n, s in assets_map.items()}done = 0for fut in as_completed(futs):a_name, frames, a_logs = fut.result()collected[a_name] = frameslogs.extend(a_logs)done += 1progress(done / len(ordered), desc=f"اكتمل {a_name} ({done}/{len(ordered)})")progress(0.95, desc="جاري حساب المؤشرات وسحب الأخبار القادمة...")return package_output(collected, ordered, assets_map, logs, f"داتا_مخصصة_{today_str}", f"custom_data_{today_str}", output_format)# ==========================================125 unmodified linesdef compute_correlation_and_adr(timeframe: str, window: int):win = max(20, min(300, int(window or 60)))assets = list(ALL_SYMBOLS.keys())with ThreadPoolExecutor(max_workers=5) as ex:futs = {ex.submit(get_asset_tf_df, a, timeframe, win + 5): a for a in assets}d1_futs = {ex.submit(get_asset_tf_df, a, "D1", 25): a for a in assets}tf_data = {futs[f]: f.result() for f in as_completed(futs)}82 unmodified linestry:tickers = list(ALL_SYMBOLS.values()) + [v[0] for v in FX_RATES_SYMBOLS.values()]try:raw = yf.download(tickers, period="5d", interval="1d", group_by="ticker", progress=False, threads=False, timeout=15)except Exception:raw = None174 unmodified lines.section-heading { font-size:1.04rem; font-weight:800; color:#f8fafc!important; margin-bottom:8px; display:flex; align-items:center; gap:8px; }.landing-split-row { gap:14px!important; align-items:flex-start!important; width:100%!important; }/* رادار الجلسات */.fx-widget-card { background:linear-gradient(180deg,rgba(15,23,42,.95),rgba(10,15,28,.98)); border:1px solid rgba(99,102,241,.32); border-radius:16px; padding:15px; width:100%; max-width:100%; overflow:hidden; }.fx-top-bar { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; padding-bottom:12px; border-bottom:1px solid rgba(148,163,184,.16); margin-bottom:12px; }.fx-widget-title { font-size:.96rem; font-weight:800; color:#f8fafc!important; }423 unmodified linesraw_md_buffer = gr.Textbox(elem_id="raw-md-buffer", elem_classes="hidden-copy-buffer", interactive=False)# 1) الصفحة الرئيسية (اللاند��ج بيج)with gr.Column(visible=True, min_width=0) as page_landing:landing_ticker = gr.HTML('<div class="ticker-outer"><div class="ticker-strip"><span class="t-sym">جاري تحميل الأسعار...</span></div></div>')with gr.Row(elem_classes="landing-split-row"):20 unmodified lineswith gr.Column(scale=6, min_width=0):gr.HTML(_build_radar_html())# 2) الجلب المخصصwith gr.Column(visible=False, min_width=0) as page_custom:with gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">🎯 الجلب المخصص والقوالب السريعة</div>')17 unmodified linescustom_file_out = gr.File(label="📥 الملف المخصص الجاهز للتنزيل")custom_log_out = gr.Textbox(label="📋 سجل الجلب المخصص", lines=8)# 3) الشارتات والمقارنةwith gr.Column(visible=False, min_width=0) as page_charts:with gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">📈 محرك الشارتات والمقارنة المتزامنة (UTC)</div>')12 unmodified lineschart_plot = gr.Plot(label="الشارت التفاعلي")snapshot_file = gr.File(label="🖼️ لقطة الشارت المجمّعة (PNG)")# 4) الارتباط والـ ADRwith gr.Column(visible=False, min_width=0) as page_quant:with gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">🔥 مصفوفة الارتباط الكمي وماسح المدى اليومي (ADR)</div>')4 unmodified linescorr_plot = gr.Plot(label="مصفوفة الارتباط")adr_html_out = gr.HTML('<div class="adr-card">اضغط على زر التحديث لعرض جدول الـ ADR...</div>')# 5) أسعار الصرف والأخبارwith gr.Column(visible=False, min_width=0) as page_fx:with gr.Row(elem_classes="action-btn-row"):btn_refresh_fx = gr.Button("🔄 تحديث أسعار الصرف والأخبار الحية الآن", variant="primary")full_fx_board = gr.HTML('<div class="rates-board-wrapper">جاري تحميل أسعار الصرف...</div>')# 6) حاسبة المخاطرةwith gr.Column(visible=False, min_width=0) as page_risk:with gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">🛡️ حاسبة إدارة المخاطر وحجم العقد</div>')gr.HTML(RISK_CALC_HTML)# ربط الأحداثnav_outs = [page_landing, page_custom, page_charts, page_quant, page_fx, page_risk,nav_landing, nav_custom, nav_charts, nav_quant, nav_fx, nav_risk,4 unmodified lines567891011130 unmodified lines14214314414514614728 unmodified lines1761771781791801811821831841851861871881891901917 unmodified lines1992002012022032042052062079 unmodified lines2172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962971 unmodified line29930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635715 unmodified lines3733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604618 unmodified lines4704714724734744754764774784794804814822 unmodified lines4854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255267 unmodified lines53453553653753853954067 unmodified lines60860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869935 unmodified lines73573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576612 unmodified lines7797807817827837847857867876 unmodified lines794795796797798799800801802803804805806807808809810811812125 unmodified lines93893994094194294394482 unmodified lines1027102810291030103110321033174 unmodified lines120812091210121112121213423 unmodified lines16371638163916401641164220 unmodified lines16631664166516661667166817 unmodified lines16861687168816891690169112 unmodified lines1704170517061707170817094 unmodified lines17141715171617171718171917201721172217231724172517261727172817294 unmodified linesimport zipfileimport urllib.requestimport xml.etree.ElementTree as ETfrom email.utils import parsedate_to_datetimefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom datetime import datetime, timezone, timedelta130 unmodified linesdef repair_fx_daily_df(df_d1: pd.DataFrame, yf_symbol: str, latest_close: float | None = None, dec: int = 5) -> pd.DataFrame:if df_d1 is None or df_d1.empty or not (yf_symbol or "").upper().endswith("=X"):return df_d1df = df_d1.copy().reset_index(drop=True)28 unmodified linesreturn df.resample(rule).agg(agg).dropna(subset=["Open", "High", "Low", "Close"])def fetch_with_retry(yf_symbol: str, period: str, interval: str, retries: int = 2):for attempt in range(1, retries + 1):try:hist = yf.Ticker(yf_symbol).history(period=period, interval=interval, timeout=8)if hist is not None and not hist.empty:return histexcept Exception:passif attempt < retries:time.sleep(0.3 * attempt)return None7 unmodified linesreturn format_yf_dataframe(resample_ohlcv(raw, "4h"), asset, yf_symbol).tail(count)tf_map = {"MN1": ("1mo", "10y"),"W1": ("1wk", "10y"),"D1": ("1d", "3y" if count <= 750 else "5y"),"H1": ("1h", "730d" if count > 300 else "180d"),"M15": ("15m", "60d" if count > 250 else "15d"),"M5": ("5m", "60d" if count > 288 else "5d"),9 unmodified lines# ==========================================# 3. تسريع سحب الأخبار وحساب المؤشرات (كاش + مهلة قصيرة + NumPy)# ==========================================_CALENDAR_CACHE = {"ts": 0.0, "events": []}_QUANT_CACHE = {}_CORR_CACHE = {}def _http_get_text(url: str, headers: dict, timeout: float = 2.5) -> str:req = urllib.request.Request(url, headers=headers)with urllib.request.urlopen(req, timeout=timeout) as resp:return resp.read().decode("utf-8", errors="ignore")def _parse_ff_json(url: str, headers: dict) -> list:out = []data = json.loads(_http_get_text(url, headers, timeout=2.5))for ev in data:imp = ev.get("impact", "")ccy = (ev.get("country") or "").strip().upper()dstr = ev.get("date", "")title = (ev.get("title") or "").strip()if imp not in {"High", "Medium"} or not ccy or not dstr or not title:continueev_dt = datetime.fromisoformat(dstr).astimezone(timezone.utc)out.append({"dt_utc": ev_dt, "currency": ccy, "impact": imp, "title": title,"forecast": ev.get("forecast") or "-", "previous": ev.get("previous") or "-",})return outdef _parse_ff_xml(url: str, headers: dict) -> list:out = []root = ET.fromstring(_http_get_text(url, headers, timeout=2.5))for item in root.findall("event"):imp = (item.findtext("impact") or "").strip()ccy = (item.findtext("country") or "").strip().upper()d_part = (item.findtext("date") or "").strip()t_part = (item.findtext("time") or "").strip()title = (item.findtext("title") or "").strip()if imp not in {"High", "Medium"} or not ccy or not d_part or not title:continuetry:dt_str = f"{d_part} {t_part}" if t_part and ("am" in t_part.lower() or "pm" in t_part.lower()) else f"{d_part} 12:00am"ev_dt = datetime.strptime(dt_str, "%m-%d-%Y %I:%M%p").replace(tzinfo=timezone.utc)except Exception:continueout.append({"dt_utc": ev_dt, "currency": ccy, "impact": imp, "title": title,"forecast": (item.findtext("forecast") or "").strip() or "-","previous": (item.findtext("previous") or "").strip() or "-",})return outdef _parse_rss_events(url: str, headers: dict, target_ccys: set) -> list:out = []root = ET.fromstring(_http_get_text(url, headers, timeout=2.5))for item in root.findall(".//item")[:25]:title = (item.findtext("title") or "").strip()pub = (item.findtext("pubDate") or "").strip()if not title:continuematched_ccy = next((c for c in target_ccys if c in title.upper()), None)if not matched_ccy:continuetry:ev_dt = parsedate_to_datetime(pub).astimezone(timezone.utc)except Exception:ev_dt = datetime.now(timezone.utc)out.append({"dt_utc": ev_dt, "currency": matched_ccy, "impact": "Medium","title": title[:110], "forecast": "-", "previous": "-",})return outdef fetch_economic_calendar_events(include_medium: bool = True, include_next_week: bool = True) -> list:1 unmodified linetarget_ccys = {"USD", "EUR", "GBP", "JPY", "AUD", "CAD", "CHF"}allowed_imp = {"High", "Medium"} if include_medium else {"High"}if _CALENDAR_CACHE["events"] and (now_ts - _CALENDAR_CACHE["ts"]) < 1800:return [ev for ev in _CALENDAR_CACHE["events"] if ev["impact"] in allowed_imp]headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36","Accept": "application/json, application/xml, text/xml, */*",}base = "https://nfs.faireconomy.media"jobs = [("json", f"{base}/ff_calendar_thisweek.json"),("xml", f"{base}/ff_calendar_thisweek.xml"),]if include_next_week:jobs.extend([("json", f"{base}/ff_calendar_nextweek.json"),("xml", f"{base}/ff_calendar_nextweek.xml"),])jobs.extend([("rss", "https://www.fxstreet.com/rss/news"),("rss", "https://www.investing.com/rss/news_25.rss"),])events, seen = [], set()with ThreadPoolExecutor(max_workers=6) as ex:futs = [ex.submit(_parse_ff_json if kind == "json" else (_parse_ff_xml if kind == "xml" else _parse_rss_events),*((url, headers, target_ccys) if kind == "rss" else (url, headers)))for kind, url in jobs]for fut in as_completed(futs, timeout=3.0):try:batch = fut.result(timeout=0.5)except Exception:continuefor ev in batch:if ev["currency"] not in target_ccys:continuekey = (ev["dt_utc"].isoformat(), ev["currency"], ev["title"])if key in seen:continueseen.add(key)events.append(ev)events.sort(key=lambda x: x["dt_utc"])if events:_CALENDAR_CACHE["ts"] = now_ts_CALENDAR_CACHE["events"] = eventsreturn [ev for ev in events if ev["impact"] in allowed_imp]return [ev for ev in _CALENDAR_CACHE["events"] if ev["impact"] in allowed_imp]def get_session_status_summary(now_utc: datetime) -> str:15 unmodified linesdef compute_asset_quant_metrics(df: pd.DataFrame, asset_name: str, yf_symbol: str) -> dict:cache_key = (asset_name, len(df), str(df["time"].iloc[-1]), float(df["close"].iloc[-1]))if cache_key in _QUANT_CACHE:return _QUANT_CACHE[cache_key]dec = get_asset_decimals(asset_name, yf_symbol)close = df["close"].to_numpy(dtype=np.float64)high = df["high"].to_numpy(dtype=np.float64)low = df["low"].to_numpy(dtype=np.float64)n = len(close)last_close = float(close[-1])pct_chg = ((last_close - float(close[-2])) / float(close[-2]) * 100.0) if n >= 2 and close[-2] != 0 else 0.0rsi_str = "N/A"if n >= 15:deltas = np.diff(close)gains = np.where(deltas > 0, deltas, 0.0)losses = np.where(deltas < 0, -deltas, 0.0)avg_g = float(np.mean(gains[:14]))avg_l = float(np.mean(losses[:14]))for i in range(14, len(deltas)):avg_g = (avg_g * 13.0 + float(gains[i])) / 14.0avg_l = (avg_l * 13.0 + float(losses[i])) / 14.0if avg_l == 0.0:rsi_str = "100.0"else:rs = avg_g / avg_lrsi_str = f"{100.0 - (100.0 / (1.0 + rs)):.1f}"atr_str = "N/A"if n >= 15:prev_c = close[:-1]tr = np.maximum(high[1:] - low[1:], np.maximum(np.abs(high[1:] - prev_c), np.abs(low[1:] - prev_c)))atr_val = float(np.mean(tr[:14]))for i in range(14, len(tr)):atr_val = (atr_val * 13.0 + float(tr[i])) / 14.0atr_str = fmt_num(atr_val, dec)def _ema_last(span: int) -> str:if n < span:return "N/A"alpha = 2.0 / (span + 1.0)ema = float(np.mean(close[:span]))for val in close[span:]:ema = alpha * float(val) + (1.0 - alpha) * emareturn fmt_num(ema, dec)ema20 = _ema_last(20)ema50 = _ema_last(50)ema200 = _ema_last(200) if n >= 150 else "N/A"lb_slice = slice(max(0, n - 50), n)h50 = float(np.max(high[lb_slice]))l50 = float(np.min(low[lb_slice]))mid50 = (h50 + l50) / 2.0pos50 = ((last_close - l50) / (h50 - l50) * 100.0) if h50 > l50 else 50.0vol_str = "N/A"if "tick_volume" in df.columns:vols = df["tick_volume"].to_numpy(dtype=np.float64)if n >= 2 and np.sum(vols[max(0, n - 20):n]) > 0:start_idx = max(0, n - 21)hist_vols = vols[start_idx:n - 1] if n >= 21 else vols[:n - 1]avg20 = float(np.mean(hist_vols)) if len(hist_vols) > 0 else 0.0if avg20 > 0:vol_str = f"{float(vols[-1]) / avg20:.2f}x"res = {"last_time": str(df["time"].iloc[-1])[:16], "last_close": fmt_num(last_close, dec),"pct_chg": f"{pct_chg:+.2f}%", "rsi14": rsi_str, "atr14": atr_str,"ema20": ema20, "ema50": ema50, "ema200": ema200,"h50": fmt_num(h50, dec), "l50": fmt_num(l50, dec), "mid50": fmt_num(mid50, dec),"pos50": f"{pos50:.1f}%", "vol_ratio": vol_str,}if len(_QUANT_CACHE) > 500:_QUANT_CACHE.clear()_QUANT_CACHE[cache_key] = resreturn resdef extract_daily_levels(tfs: dict, asset_name: str, yf_symbol: str) -> dict:dec = get_asset_decimals(asset_name, yf_symbol)daily_df = tfs["D1"] if ("D1" in tfs and len(tfs["D1"]) >= 2) else Noneif daily_df is None:src = tfs.get("H1") if "H1" in tfs else (tfs.get("H4") if "H4" in tfs else tfs.get("M15"))if src is not None and not src.empty:8 unmodified linesif daily_df is None or len(daily_df) < 2:return {"pdh": "N/A", "pdl": "N/A", "pdc": "N/A", "cdh": "N/A", "cdl": "N/A"}tail_d = daily_df.tail(15)valid_days = tail_d[tail_d["high"].to_numpy(dtype=np.float64) > tail_d["low"].to_numpy(dtype=np.float64)]if len(valid_days) >= 2:prev_d, curr_d = valid_days.iloc[-2], valid_days.iloc[-1]else:prev_d, curr_d = daily_df.iloc[-2], daily_df.iloc[-1]return {"pdh": fmt_num(prev_d["high"], dec), "pdl": fmt_num(prev_d["low"], dec),"pdc": fmt_num(prev_d["close"], dec), "cdh": fmt_num(curr_d["high"], dec),2 unmodified linesdef compute_aligned_correlation(frames_dict: dict, window: int = 60, tf_name: str = "H1"):freq_map = {"M5": "5min", "M15": "15min", "H1": "1h", "H4": "4h", "D1": "1D"}freq = freq_map.get(tf_name, "1h")tail_n = window * 3 if freq in ("1h", "15min", "5min") else windowlookback_rows = max(120, tail_n * 4)sig = tuple((a, len(df), str(df["time"].iloc[-1]), float(df["close"].iloc[-1]))for a, df in frames_dict.items() if df is not None and len(df) >= 15)cache_key = (freq, window, sig)if cache_key in _CORR_CACHE:return _CORR_CACHE[cache_key]series_map = {}for asset, df in frames_dict.items():if df is None or len(df) < 15:continuesub = df.tail(lookback_rows)[["time", "close"]].copy()t_idx = pd.to_datetime(sub["time"])t_idx = (t_idx + pd.Timedelta(hours=2)).dt.floor("1D") if freq == "1D" else t_idx.dt.floor(freq)s = pd.Series(sub["close"].to_numpy(dtype=np.float64), index=t_idx)series_map[asset] = s.groupby(level=0).last()if len(series_map) < 2:return Nonealigned = pd.DataFrame(series_map).sort_index()corr = aligned.pct_change(fill_method=None).tail(tail_n).corr(min_periods=8).round(2)res = corr if not corr.empty else Noneif len(_CORR_CACHE) > 200:_CORR_CACHE.clear()_CORR_CACHE[cache_key] = resreturn resdef build_ai_precomputed_section(collected_data: dict, ordered_assets: list, symbols_map: dict, prefetched_events: list | None = None) -> str:now_utc = datetime.now(timezone.utc)now_local = now_utc + timedelta(hours=2)saved_count = sum(len(collected_data.get(a, {})) for a in ordered_assets)7 unmodified lines"", "---", "## 1. Upcoming Economic Calendar (High & Medium Impact)",]events = prefetched_events if prefetched_events is not None else fetch_economic_calendar_events(include_medium=True, include_next_week=True)today_date = now_utc.date()upcoming = [ev for ev in events67 unmodified lines# ==========================================# 4. محرك السحب السريع المتوازي (الجلب أولاً ثم الحساب دفعة واحدة)# ==========================================def _fetch_one_tf_job(asset: str, yf_symbol: str, tf_name: str, interval: str, period: str):hist = fetch_with_retry(yf_symbol, period, interval)return asset, tf_name, histdef collect_frames_fast(symbols_map: dict, per_asset_specs: dict, need_h4: bool, h4_count: int, want_m15_fallback: bool, m15_count: int, progress=None):raw_store = {a: {} for a in symbols_map}logs = []jobs = []for asset, sym in symbols_map.items():for tf_name, interval, period, count, save_this in per_asset_specs.get(asset, []):jobs.append((asset, sym, tf_name, interval, period, count, save_this))total = max(1, len(jobs))completed = 0with ThreadPoolExecutor(max_workers=8) as ex:fut_map = {ex.submit(_fetch_one_tf_job, a, s, tf, iv, pr): (a, s, tf, cnt, sv)for (a, s, tf, iv, pr, cnt, sv) in jobs}for fut in as_completed(fut_map):asset, sym, tf_name, count, save_this = fut_map[fut]completed += 1if progress:progress(min(0.85, completed / total * 0.85), desc=f"جلب {asset}_{tf_name} ({completed}/{total})")try:_, _, hist = fut.result()except Exception:hist = Noneif hist is None or hist.empty:if save_this:logs.append(f"[فشل] {asset}_{tf_name}")continueraw_store[asset][tf_name] = histcollected = {}for asset, sym in symbols_map.items():dec = get_asset_decimals(asset, sym)frames = {}raw_tfs = raw_store.get(asset, {})for tf_name, _, _, count, save_this in per_asset_specs.get(asset, []):hist = raw_tfs.get(tf_name)if save_this and hist is not None and not hist.empty:frames[tf_name] = format_yf_dataframe(hist, asset, sym).tail(count)logs.append(f"[تم] {asset}_{tf_name} ({len(frames[tf_name])} شمعة | {dec}d | UTC)")if want_m15_fallback and "M15" not in frames and "M5" in raw_tfs and not raw_tfs["M5"].empty:try:frames["M15"] = format_yf_dataframe(resample_ohlcv(raw_tfs["M5"], "15min"), asset, sym).tail(m15_count)logs.append(f"[تم - من M5] {asset}_M15 ({len(frames['M15'])} شمعة | {dec}d | UTC)")except Exception as e:logs.append(f"[خطأ] {asset}_M15: {e}")if need_h4:h1_raw = raw_tfs.get("H1")if h1_raw is not None and not h1_raw.empty:try:frames["H4"] = format_yf_dataframe(resample_ohlcv(h1_raw, "4h"), asset, sym).tail(h4_count)logs.append(f"[تم] {asset}_H4 ({len(frames['H4'])} شمعة | {dec}d | UTC)")except Exception as e:logs.append(f"[خطأ] {asset}_H4: {e}")else:logs.append(f"[فشل] {asset}_H4 (تعذر جلب H1)")if "D1" in frames and sym.upper().endswith("=X"):latest_c = next((float(frames[r]["close"].iloc[-1]) for r in ("M5", "M15", "H1", "H4", "W1") if r in frames and not frames[r].empty),None)frames["D1"] = repair_fx_daily_df(frames["D1"], sym, latest_close=latest_c, dec=dec)collected[asset] = framesreturn collected, logsdef package_output(collected_data: dict, ordered_assets: list, symbols_map: dict, logs: list, root_folder: str, base_filename: str, output_format: str, prefetched_events: list | None = None):saved_count = sum(len(collected_data.get(a, {})) for a in ordered_assets)precomputed = build_ai_precomputed_section(collected_data, ordered_assets, symbols_map, prefetched_events=prefetched_events)md_parts = [precomputed]for asset in ordered_assets:35 unmodified linesh4_cnt, m15_fb = (250, 250) if is_update else (300, 0)ordered = list(symbols.keys())per_asset_specs = {}for name in ordered:if is_update:cfgs = [("H1", "1h", "180d", 250, True), ("M15", "15m", "15d", 250, True)]if name in ("EURUSD", "GBPUSD"):cfgs.append(("M5", "5m", "5d", 250, True))else:cfgs = [("MN1", "1mo", "10y", 100, True),("W1", "1wk", "10y", 700, True),("D1", "1d", "3y", 700, True),("H1", "1h", "180d", 300, True),]per_asset_specs[name] = cfgsprogress(0, desc="جاري جلب البيانات والأخبار بالتوازي...")with ThreadPoolExecutor(max_workers=2) as news_ex:news_fut = news_ex.submit(fetch_economic_calendar_events, True, True)collected, logs = collect_frames_fast(symbols, per_asset_specs, True, h4_cnt, is_update, m15_fb, progress)try:prefetched_events = news_fut.result(timeout=5)except Exception:prefetched_events = []progress(0.92, desc="جاري حساب ��لمؤشرات والارتباط بعد اكتمال الجلب...")return package_output(collected, ordered, symbols, logs, root_folder, base_name, output_format, prefetched_events=prefetched_events)def fetch_custom_data(selected_assets, extra_tickers_str, selected_timeframes, candle_count, output_format, progress=gr.Progress()):12 unmodified linescnt = max(10, int(candle_count or 250))today_str = datetime.now().strftime("%Y-%m-%d")tf_map = {"MN1": ("1mo", "10y" if cnt <= 120 else "max"),"W1": ("1wk", "10y" if cnt <= 520 else "max"),"D1": ("1d", "3y" if cnt <= 750 else "max"),"H1": ("1h", "730d" if cnt > 300 else "180d"),"M15": ("15m", "60d" if cnt > 250 else "15d"),"M5": ("5m", "60d" if cnt > 288 else "5d"),6 unmodified linescfgs = [(tf, tf_map[tf][0], tf_map[tf][1], cnt, tf in selected_timeframes) for tf in direct]ordered = list(assets_map.keys())per_asset_specs = {n: cfgs for n in ordered}progress(0, desc="جاري سحب البيانات المخصصة والأخبار بالتوازي...")with ThreadPoolExecutor(max_workers=2) as news_ex:news_fut = news_ex.submit(fetch_economic_calendar_events, True, True)collected, logs = collect_frames_fast(assets_map, per_asset_specs, need_h4, cnt, want_m15, cnt, progress)try:prefetched_events = news_fut.result(timeout=5)except Exception:prefetched_events = []progress(0.92, desc="جاري حساب المؤشرات والارتباط بعد الجلب...")return package_output(collected, ordered, assets_map, logs, f"داتا_مخصصة_{today_str}", f"custom_data_{today_str}", output_format, prefetched_events=prefetched_events)# ==========================================125 unmodified linesdef compute_correlation_and_adr(timeframe: str, window: int):win = max(20, min(300, int(window or 60)))assets = list(ALL_SYMBOLS.keys())with ThreadPoolExecutor(max_workers=6) as ex:futs = {ex.submit(get_asset_tf_df, a, timeframe, win + 5): a for a in assets}d1_futs = {ex.submit(get_asset_tf_df, a, "D1", 25): a for a in assets}tf_data = {futs[f]: f.result() for f in as_completed(futs)}82 unmodified linestry:tickers = list(ALL_SYMBOLS.values()) + [v[0] for v in FX_RATES_SYMBOLS.values()]try:raw = yf.download(tickers, period="5d", interval="1d", group_by="ticker", progress=False, threads=True, timeout=10)except Exception:raw = None174 unmodified lines.section-heading { font-size:1.04rem; font-weight:800; color:#f8fafc!important; margin-bottom:8px; display:flex; align-items:center; gap:8px; }.landing-split-row { gap:14px!important; align-items:flex-start!important; width:100%!important; }.fx-widget-card { background:linear-gradient(180deg,rgba(15,23,42,.95),rgba(10,15,28,.98)); border:1px solid rgba(99,102,241,.32); border-radius:16px; padding:15px; width:100%; max-width:100%; overflow:hidden; }.fx-top-bar { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:10px; padding-bottom:12px; border-bottom:1px solid rgba(148,163,184,.16); margin-bottom:12px; }.fx-widget-title { font-size:.96rem; font-weight:800; color:#f8fafc!important; }423 unmodified linesraw_md_buffer = gr.Textbox(elem_id="raw-md-buffer", elem_classes="hidden-copy-buffer", interactive=False)with gr.Column(visible=True, min_width=0) as page_landing:landing_ticker = gr.HTML('<div class="ticker-outer"><div class="ticker-strip"><span class="t-sym">جاري تحميل الأسعار...</span></div></div>')with gr.Row(elem_classes="landing-split-row"):20 unmodified lineswith gr.Column(scale=6, min_width=0):gr.HTML(_build_radar_html())with gr.Column(visible=False, min_width=0) as page_custom:with gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">🎯 الجلب المخصص والقوالب السريعة</div>')17 unmodified linescustom_file_out = gr.File(label="📥 الملف المخصص الجاهز للتنزيل")custom_log_out = gr.Textbox(label="📋 سجل الجلب المخصص", lines=8)with gr.Column(visible=False, min_width=0) as page_charts:with gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">📈 محرك الشارتات والمقارنة المتزامنة (UTC)</div>')12 unmodified lineschart_plot = gr.Plot(label="الشارت التفاعلي")snapshot_file = gr.File(label="🖼️ لقطة الشارت المجمّعة (PNG)")with gr.Column(visible=False, min_width=0) as page_quant:with gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">🔥 مصفوفة الارتباط الكمي وماسح المدى اليومي (ADR)</div>')4 unmodified linescorr_plot = gr.Plot(label="مصفوفة الارتباط")adr_html_out = gr.HTML('<div class="adr-card">اضغط على زر التحديث لعرض جدول الـ ADR...</div>')with gr.Column(visible=False, min_width=0) as page_fx:with gr.Row(elem_classes="action-btn-row"):btn_refresh_fx = gr.Button("🔄 تحديث أسعار الصرف والأخبار الحية الآن", variant="primary")full_fx_board = gr.HTML('<div class="rates-board-wrapper">جاري تحميل أسعار الصرف...</div>')with gr.Column(visible=False, min_width=0) as page_risk:with gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">🛡️ حاسبة إدارة المخاطر وحجم العقد</div>')gr.HTML(RISK_CALC_HTML)nav_outs = [page_landing, page_custom, page_charts, page_quant, page_fx, page_risk,nav_landing, nav_custom, nav_charts, nav_quant, nav_fx, nav_risk,
app.py+323-216