"""news_feed.py — RSS haber taraması + SVG grafikler (ek bağımlılık yok). app.py'den: build_news_panel(classify, detect_assets, asset, timeframe) classify(text) -> (label: "Bullish"|"Neutral"|"Bearish", score: -1..1) """ import re import time import html import hashlib import sqlite3 import urllib.request from urllib.parse import quote import xml.etree.ElementTree as ET from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone from email.utils import parsedate_to_datetime FEEDS = { "CoinDesk": "https://www.coindesk.com/arc/outboundfeeds/rss/", "Cointelegraph": "https://cointelegraph.com/rss", "Decrypt": "https://decrypt.co/feed", "Bitcoin Magazine": "https://bitcoinmagazine.com/.rss/full/", "The Block": "https://www.theblock.co/rss.xml", "CryptoSlate": "https://cryptoslate.com/feed/", "CryptoPotato": "https://cryptopotato.com/feed/", "NewsBTC": "https://www.newsbtc.com/feed/", "Bitcoinist": "https://bitcoinist.com/feed/", "U.Today": "https://u.today/rss", "BeInCrypto": "https://beincrypto.com/feed/", "CoinGape": "https://coingape.com/feed/", "AMBCrypto": "https://ambcrypto.com/feed/", "Crypto.News": "https://crypto.news/feed/", "The Daily Hodl": "https://dailyhodl.com/feed/", "Blockworks": "https://blockworks.co/feed", "CryptoNews": "https://cryptonews.com/news/feed/", "Bitcoin.com": "https://news.bitcoin.com/feed/", "Cointelegraph Markets": "https://cointelegraph.com/rss/tag/market-analysis", "Crypto Briefing": "https://cryptobriefing.com/feed/", "Protos": "https://protos.com/feed/", "DL News": "https://www.dlnews.com/arc/outboundfeeds/rss/", "CoinJournal": "https://coinjournal.net/feed/", "Bitcoin Sistemi (EN)": "https://bitcoinsistemi.com/en/feed/", } # Varlıktan bağımsız genel Google News aramaları (makro, regülasyon, ETF...) GENERAL_QUERIES = [ "crypto market", "bitcoin ETF", "crypto regulation SEC", "crypto hack exploit", "stablecoin", "crypto whale", "Federal Reserve bitcoin", "altcoin rally", "ethereum ETF", "crypto exchange listing", "token unlock", "crypto liquidations", "memecoin", "DeFi", "crypto lawsuit", "crypto airdrop", ] MAX_CLASSIFY = 24 # tek taramada LLM ile etiketlenecek en fazla haber (kalanlar sonraki taramada) MAX_BULK_CLASSIFY = 40 # toplu taramada varsayılan LLM etiketleme bütçesi DEFAULT_LIMIT = {"Günlük": 30, "Aylık": 50} # regex -> ağırlık (önem puanı) KEYWORDS = { r"\betf": 3, r"\bsec\b": 3, r"\bhack": 3, r"\bexploit": 3, r"\bliquidat": 3, r"\bbankrupt": 3, r"\bfed\b": 3, r"\brate (cut|hike)": 3, r"\bcpi\b": 2, r"\bhalving": 3, r"\bcrash": 3, r"\bplunge": 3, r"\bsurge": 2, r"\brall(y|ies)": 2, r"all-time high|\bath\b": 3, r"\blawsuit|\bsued?\b": 2, r"\bban(s|ned)?\b": 2, r"\bapprov": 2, r"\bregulat": 2, r"\bwhale": 2, r"\binflow|\boutflow": 2, r"\bblackrock": 2, r"\bdelist": 2, r"\bstablecoin": 1, r"\btether|\busdt": 1, r"\bbinance": 1, r"\bbreakout|\bbreakdown": 2, r"\bsettle|\bfine[sd]?\b": 1, } _KW = [(re.compile(k), w) for k, w in KEYWORDS.items()] # ------------------------------------------------------------------ VARLIK KAYIT DEFTERİ # (sembol, [tam adlar], ci) # ci=True -> sembol küçük/büyük harf fark etmeden eşleşir (btc, Btc, BTC) # ci=False -> sembol yalnızca BÜYÜK harfle ya da $sembol olarak eşleşir; "link", "dot", # "near", "sol" gibi sıradan kelimelerden kaynaklanan yanlış eşleşmeyi önler. # Yeni parite eklemek için bu listeye bir satır eklemek yeterli. ASSETS_DEF = [ ("BTC", ["bitcoin"], True), ("ETH", ["ethereum"], True), ("BNB", ["binance coin", "bnb chain"], True), ("SOL", ["solana"], False), ("XRP", ["ripple", "xrp ledger"], True), ("ADA", ["cardano"], False), ("DOGE", ["dogecoin"], True), ("AVAX", ["avalanche"], True), ("LINK", ["chainlink"], False), ("DOT", ["polkadot"], False), ("TON", ["toncoin", "the open network"], False), ("TRX", ["tron", "tronix"], True), ("SHIB", ["shiba inu"], True), ("LTC", ["litecoin"], True), ("BCH", ["bitcoin cash"], True), ("NEAR", ["near protocol"], False), ("UNI", ["uniswap"], False), ("ATOM", ["cosmos hub"], False), ("XLM", ["stellar lumens", "stellar network"], True), ("ETC", ["ethereum classic"], False), ("HBAR", ["hedera"], True), ("APT", ["aptos"], False), ("ARB", ["arbitrum"], False), ("OP", ["op mainnet", "optimism chain"], False), ("SUI", ["sui network", "sui blockchain"], False), ("INJ", ["injective"], False), ("FIL", ["filecoin"], False), ("ICP", ["internet computer"], False), ("AAVE", ["aave"], True), ("MKR", ["makerdao", "maker dao"], False), ("PEPE", ["pepe coin", "pepecoin"], True), ("TIA", ["celestia"], False), ("SEI", ["sei network"], False), ("RENDER", ["render network", "render token", "rndr"], False), ("ALGO", ["algorand"], False), ("VET", ["vechain"], False), ("XMR", ["monero"], True), ("FET", ["fetch.ai", "artificial superintelligence alliance"], False), ("HYPE", ["hyperliquid"], False), ("ENA", ["ethena"], False), ] ASSET_LIST = [a[0] for a in ASSETS_DEF] MAJORS = ["BTC", "ETH", "SOL", "BNB", "XRP"] def _gq(sym, names, ci): q = " OR ".join(f'"{n}"' for n in names) return q + (f" OR {sym}" if ci else "") ASSET_QUERY = {sym: _gq(sym, names, ci) for sym, names, ci in ASSETS_DEF} # yfinance'ta "SYM-USD" biçimine uymayan sembollerin karşılıkları YF_SYMBOL = { "TON": "TON11419-USD", "UNI": "UNI7083-USD", "APT": "APT21794-USD", "ARB": "ARB11841-USD", "SUI": "SUI20947-USD", "TIA": "TIA22861-USD", "PEPE": "PEPE24478-USD", "SEI": "SEI-USD", "HYPE": "HYPE32196-USD", "ENA": "ENA36530-USD", "MKR": "MKR-USD", "RENDER": "RENDER-USD", } _ASSET_RX = [] for _sym, _names, _ci in ASSETS_DEF: _name_rx = re.compile(r"(? (saat, google 'when', recency yarı ömrü saat) PERIODS = {"Günlük": (24, "1d", 12), "Aylık": (720, "30d", 96)} NEWS_DB = "news.db" LINES = ["#f7931a", "#60a5fa", "#a78bfa", "#eab308", "#22c55e"] TIMEFRAMES = {"1G": ("2d", "15m"), "7G": ("7d", "1h"), "1A": ("1mo", "1d"), "3A": ("3mo", "1d")} COL = {"Bullish": "#22c55e", "Neutral": "#eab308", "Bearish": "#ef4444"} _news_cache = {} _price_cache = {} _cls_cache = {} NEWS_TTL = 300 # ------------------------------------------------------------------ FETCH def _strip(s): return html.unescape(re.sub(r"<[^>]+>", " ", s or "")).strip() def _parse_feed(xml_bytes, source): root = ET.fromstring(xml_bytes) atom = "{http://www.w3.org/2005/Atom}" out = [] for it in root.iter(): tag = it.tag.replace(atom, "") if tag not in ("item", "entry"): continue def g(name): el = it.find(name) if el is None: el = it.find(atom + name) return el title = g("title") link = g("link") date = next((e for e in (g("pubDate"), g("published"), g("updated")) if e is not None), None) desc = next((e for e in (g("description"), g("summary")) if e is not None), None) href = None if link is not None: href = link.get("href") or (link.text or "").strip() ts = None if date is not None and date.text: try: ts = parsedate_to_datetime(date.text) except Exception: try: ts = datetime.fromisoformat(date.text.replace("Z", "+00:00")) except Exception: ts = None if ts is not None and ts.tzinfo is None: ts = ts.replace(tzinfo=timezone.utc) if title is not None and title.text: ttl, sname = _strip(title.text), source if source == "Google": se = g("source") if se is not None and se.text: sname = se.text.strip() if ttl.endswith(" - " + sname): ttl = ttl[: -len(sname) - 3] desc = None out.append({ "title": ttl, "link": href or "#", "source": sname, "ts": ts or datetime.now(timezone.utc), "summary": _strip(desc.text if desc is not None else "")[:300], }) return out def _fetch_one(job): name, url, hint = job try: req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 GoshawkVortex/1.0"}) with urllib.request.urlopen(req, timeout=8) as r: items = _parse_feed(r.read(), name) for i in items: i["hint"] = [hint] if hint else [] return items except Exception: return None def _gurl(asset, when): q = quote(f"({ASSET_QUERY[asset]}) crypto when:{when}") return f"https://news.google.com/rss/search?q={q}&hl=en-US&gl=US&ceid=US:en" def _gurl_general(q, when): return f"https://news.google.com/rss/search?q={quote(q + ' when:' + when)}&hl=en-US&gl=US&ceid=US:en" def fetch_news(period="Günlük", force=False): c = _news_cache.get(period) if c and not force and time.time() - c["t"] < NEWS_TTL: return c["items"], c["ok"], c["n"] when = PERIODS[period][1] jobs = [(n, u, None) for n, u in FEEDS.items()] + [("Google", _gurl(a, when), a) for a in ASSET_QUERY] \ + [("Google", _gurl_general(q, when), None) for q in GENERAL_QUERIES] with ThreadPoolExecutor(max_workers=32) as ex: results = list(ex.map(_fetch_one, jobs)) items = [i for r in results if r for i in r] ok = sum(1 for r in results if r) if items: _news_cache[period] = {"t": time.time(), "items": items, "ok": ok, "n": len(jobs)} return items, ok, len(jobs) # ------------------------------------------------------------------ DB (geçmiş birikimi) def _id(title): return hashlib.sha1(re.sub(r"\W+", " ", title.lower()).strip().encode()).hexdigest()[:20] def _db(): c = sqlite3.connect(NEWS_DB, timeout=10) c.execute("CREATE TABLE IF NOT EXISTS news(id TEXT PRIMARY KEY, title TEXT, link TEXT, source TEXT, " "ts REAL, summary TEXT, assets TEXT, label TEXT, score REAL)") c.execute("CREATE INDEX IF NOT EXISTS ix_ts ON news(ts)") return c def db_store(items): c = _db() c.executemany("INSERT OR IGNORE INTO news(id,title,link,source,ts,summary,assets) VALUES(?,?,?,?,?,?,?)", [(_id(i["title"]), i["title"], i["link"], i["source"], i["ts"].timestamp(), i["summary"], ",".join(i["assets"])) for i in items]) c.commit() c.close() def db_load(hours): c = _db() since = time.time() - hours * 3600 rows = c.execute("SELECT id,title,link,source,ts,summary,assets,label,score FROM news WHERE ts>=?", (since,)).fetchall() c.execute("DELETE FROM news WHERE ts 0.15 else "Bearish" if sc < -0.15 else "Neutral"), sc # ------------------------------------------------------------------ RANK def _tokens(t): return {w for w in re.findall(r"[a-z0-9]+", t.lower()) if len(w) > 3} def rank_news(items, limit=12, max_age_h=48, half=12): now = datetime.now(timezone.utc) items = [i for i in items if (now - i["ts"]).total_seconds() < max_age_h * 3600] items.sort(key=lambda i: i["ts"], reverse=True) clusters = [] index = {} # anahtar kelime -> küme numaraları (binlerce haberde O(n^2) taramayı önler) for it in items: tk = _tokens(it["title"]) keys = sorted(tk, key=lambda w: (-len(w), w))[:4] cand = {ci for k in keys for ci in index.get(k, ())} for ci in sorted(cand): c = clusters[ci] if tk and len(tk & c["tk"]) / len(tk | c["tk"]) >= 0.5: c["srcs"].add(it["source"]) c["n"] += 1 break else: clusters.append({"it": it, "tk": tk, "srcs": {it["source"]}, "n": 1}) for k in keys: index.setdefault(k, []).append(len(clusters) - 1) ranked = [] for c in clusters: it = c["it"] text = (it["title"] + " " + it["summary"]).lower() kw = sum(w for rx, w in _KW if rx.search(text)) age_h = (now - it["ts"]).total_seconds() / 3600 rec = 0.5 ** (age_h / half) imp = (kw + 1.5 * (len(c["srcs"]) - 1)) * (0.35 + 0.65 * rec) if kw == 0 and len(c["srcs"]) == 1: imp *= 0.3 ranked.append({**it, "srcs": sorted(c["srcs"]), "imp": min(100, imp * 10), "age_h": age_h}) ranked.sort(key=lambda r: r["imp"], reverse=True) return ranked[:limit] # ------------------------------------------------------------------ PRICE def price_series(asset, timeframe): k = (asset, timeframe) c = _price_cache.get(k) if c and time.time() - c[0] < NEWS_TTL: return c[1] rows = _price_series(asset, timeframe) _price_cache[k] = (time.time(), rows) return rows def _price_series(asset, timeframe): import yfinance as yf # lazy: sadece grafik için period, interval = TIMEFRAMES.get(timeframe, TIMEFRAMES["1A"]) df = yf.Ticker(YF_SYMBOL.get(asset, f"{asset}-USD")).history(period=period, interval=interval) rows = [] for ts, r in df.iterrows(): if r["Close"] == r["Close"]: rows.append((ts.to_pydatetime(), float(r["Open"]), float(r["High"]), float(r["Low"]), float(r["Close"]), float(r.get("Volume", 0) or 0))) return rows def _fmt(v): if v >= 1000: return f"{v:,.0f}" if v >= 1: return f"{v:,.2f}" return f"{v:.5f}" # ------------------------------------------------------------------ SVG def svg_candles(rows, asset, timeframe, marks=()): """Mum grafiği + hacim + SMA20 + son fiyat etiketi. marks: [(datetime, renk)] haber işaretleri.""" if len(rows) < 3: return "
Fiyat verisi alınamadı.
" W, H, L, R, T = 780, 380, 62, 14, 16 PB, VT, VB = 270, 286, 350 n = len(rows) lo = min(r[3] for r in rows) hi = max(r[2] for r in rows) pad = (hi - lo) * 0.06 or hi * 0.01 lo, hi = lo - pad, hi + pad vmax = max(r[5] for r in rows) or 1 cw = (W - L - R) / n px = lambda i: L + cw * (i + 0.5) py = lambda v: T + (PB - T) * (1 - (v - lo) / (hi - lo)) up = rows[-1][4] >= rows[0][1] line = "#22c55e" if up else "#ef4444" o = [f"", "" f"" f""] for k in range(6): v = lo + (hi - lo) * k / 5 y = py(v) o.append(f"") o.append(f"{_fmt(v)}") # alan dolgusu (kapanış) pts = " ".join(f"{px(i):.1f},{py(r[4]):.1f}" for i, r in enumerate(rows)) o.append(f"") # hacim + mumlar for i, (ts, op, h, l, c, v) in enumerate(rows): col = "#22c55e" if c >= op else "#ef4444" x = px(i) bw = max(1.2, cw * 0.62) vh = (VB - VT) * (v / vmax) o.append(f"") y1, y2 = py(max(op, c)), py(min(op, c)) tip = f"{ts:%d %b %H:%M} O {_fmt(op)} H {_fmt(h)} L {_fmt(l)} C {_fmt(c)}" o.append(f"{tip}" f"") # SMA20 if n >= 20: sma = [(i, sum(r[4] for r in rows[i-19:i+1]) / 20) for i in range(19, n)] o.append("") # haber işaretleri (zamana en yakın muma) for mts, mcol, mtitle in marks: try: idx = min(range(n), key=lambda i: abs((rows[i][0].replace(tzinfo=None) - mts.replace(tzinfo=None)).total_seconds())) if abs((rows[idx][0].replace(tzinfo=None) - mts.replace(tzinfo=None)).total_seconds()) > 3 * 86400: continue except Exception: continue x = px(idx) o.append(f"{html.escape(mtitle)}") # son fiyat etiketi last = rows[-1][4] y = py(last) o.append(f"") o.append(f"" f"{_fmt(last)}") # x ekseni fmt = "%H:%M" if timeframe == "1G" else "%d %b" for k in range(5): i = int((n - 1) * k / 4) o.append(f"{rows[i][0]:{fmt}}") o.append("") chg = (last / rows[0][1] - 1) * 100 head = (f"
{asset}/USD{_fmt(last)}" f"{chg:+.2f}%{timeframe} • mum + hacim + SMA20 • ▲ haber
") return head + "".join(o) def svg_donut(counts, net): tot = sum(counts.values()) or 1 r, C = 52, 2 * 3.14159265 * 52 o = ["", ""] off = 0 for k in ("Bullish", "Neutral", "Bearish"): ln = C * counts[k] / tot if ln > 0: o.append(f"") off += ln c = "#22c55e" if net > 0.05 else "#ef4444" if net < -0.05 else "#eab308" o.append(f"{net:+.2f}" "NET SKOR") return "".join(o) def svg_compare(series, timeframe): """Normalize % getiri karşılaştırması (ALL modu).""" series = {k: v for k, v in series.items() if len(v) > 3} if not series: return "
Fiyat verisi alınamadı.
" W, H, L, R, T, B = 780, 300, 52, 110, 14, 28 norm = {k: [(r[0], (r[4] / v[0][1] - 1) * 100) for r in v] for k, v in series.items()} allv = [p for v in norm.values() for _, p in v] lo, hi = min(allv + [0]), max(allv + [0]) pad = (hi - lo) * 0.08 or 1 lo, hi = lo - pad, hi + pad py = lambda v: T + (H - T - B) * (1 - (v - lo) / (hi - lo)) o = [f""] for k in range(6): v = lo + (hi - lo) * k / 5 o.append(f"" f"{v:+.0f}%") o.append(f"") first = next(iter(norm.values())) ends = [] for ci, (k, v) in enumerate(norm.items()): col = LINES[ci % len(LINES)] n = len(v) pts = " ".join(f"{L + (W-L-R)*i/(n-1):.1f},{py(p):.1f}" for i, (_, p) in enumerate(v)) o.append(f"") ends.append([py(v[-1][1]), col, f"{k} {v[-1][1]:+.1f}%"]) ends.sort() for j in range(1, len(ends)): # etiket çakışmasını önle ends[j][0] = max(ends[j][0], ends[j-1][0] + 14) for y, col, txt in ends: o.append(f"{txt}") fmt = "%H:%M" if timeframe == "1G" else "%d %b" for k in range(5): i = int((len(first) - 1) * k / 4) o.append(f"{first[i][0]:{fmt}}") o.append("") return f"
Varlık performansı{timeframe} • başlangıca göre % değişim
" + "".join(o) def svg_assets(stats, top=15): """stats: {asset: (haber_sayısı, net_skor|None)} -> yatay çubuklar.""" rows = sorted([(a, n, s) for a, (n, s) in stats.items() if n > 0], key=lambda x: -x[1])[:top] if not rows: return "
Bu dönemde varlık bazlı haber bulunamadı.
" mx = max(n for _, n, _ in rows) H = 12 + 28 * len(rows) o = [f""] for i, (a, n, sc) in enumerate(rows): y = 8 + 28 * i col = "#475569" if sc is None else "#22c55e" if sc > 0.05 else "#ef4444" if sc < -0.05 else "#eab308" w = 480 * n / mx o.append(f"{a}" f"" f"{a}: {n} haber" f"{n} haber • " f"{'skor —' if sc is None else f'skor {sc:+.2f}'}") o.append("") return "
Varlık haber yoğunluğuçubuk = haber sayısı • renk = duygu
" + "".join(o) def svg_timeline(items, hours): """Zamana göre ortalama duygu (sınıflandırılmış haberler).""" nb = 6 if hours <= 24 else 30 step = hours * 3600 / nb end = time.time() b = [[0.0, 0] for _ in range(nb)] for it in items: if it.get("label") is None: continue k = int((it["ts"].timestamp() - (end - hours * 3600)) // step) if 0 <= k < nb: b[k][0] += it["score"] b[k][1] += 1 if not any(n for _, n in b): return "" W, H, L, mid = 780, 170, 40, 78 bw = (W - L - 10) / nb o = [f"", f""] for k, (sm, n) in enumerate(b): t0 = datetime.fromtimestamp(end - hours * 3600 + k * step) if n: v = sm / n h = abs(v) * 62 col = "#22c55e" if v >= 0 else "#ef4444" y = mid - h if v >= 0 else mid o.append(f"{t0:%d %b %H:%M} • {n} haber • skor {v:+.2f}") if k % max(1, nb // 6) == 0: fmt = "%H:%M" if hours <= 24 else "%d %b" o.append(f"{t0:{fmt}}") o.append(f"+1-1") return ("
Duygu zaman çizgisisınıflandırılan haberlerin ortalaması • " "koyuluk = haber adedi
" + "".join(o)) # ------------------------------------------------------------------ PANEL NEWS_CSS = """ .nw-wrap { margin-top:12px; color:#dbeafe; } .nw-card, .nw-news { padding:18px; border-radius:18px; margin-bottom:14px; background:linear-gradient(180deg, rgba(8,18,34,.9), rgba(5,13,25,.85)); border:1px solid rgba(96,165,250,.18); box-shadow:0 14px 36px rgba(0,0,0,.25); } .nw-head { display:flex; gap:14px; align-items:baseline; flex-wrap:wrap; margin-bottom:6px; } .nw-price { font-size:26px; font-weight:800; } .nw-dim { color:#64748b; font-size:11px; margin-left:auto; } .nw-svg { width:100%; height:auto; display:block; } .nw-grid { display:grid; grid-template-columns:160px 1fr; gap:18px; align-items:center; } .nw-donut { width:150px; height:150px; } .nw-legend span { display:inline-block; margin:3px 14px 3px 0; font-size:12px; } .nw-dot { display:inline-block; width:9px; height:9px; border-radius:50%; margin-right:6px; } .nw-empty { color:#8295ad; padding:18px; } /* ---- canlı şerit (ticker) ---- */ .nw-ticker { overflow:hidden; border-radius:14px; margin-bottom:14px; padding:10px 0; background:linear-gradient(90deg, rgba(8,18,34,.95), rgba(10,28,50,.9)); border:1px solid rgba(96,165,250,.22); position:relative; } .nw-ticker:before, .nw-ticker:after { content:""; position:absolute; top:0; bottom:0; width:60px; z-index:2; pointer-events:none; } .nw-ticker:before { left:0; background:linear-gradient(90deg,#08121f,transparent); } .nw-ticker:after { right:0; background:linear-gradient(270deg,#08121f,transparent); } .nw-track { display:inline-flex; white-space:nowrap; gap:34px; padding-left:100%; animation:nwScroll 140s linear infinite; } .nw-ticker:hover .nw-track { animation-play-state:paused; } .nw-track a { color:#cbd5e1; font-size:13px; text-decoration:none; } .nw-track a:hover { color:#fff; text-decoration:underline; } .nw-live { display:inline-block; width:8px; height:8px; border-radius:50%; margin-right:8px; background:#ef4444; box-shadow:0 0 0 0 rgba(239,68,68,.7); animation:nwPing 1.6s infinite; } @keyframes nwScroll { to { transform:translateX(-100%); } } @keyframes nwPing { 70% { box-shadow:0 0 0 9px rgba(239,68,68,0); } 100% { box-shadow:0 0 0 0 rgba(239,68,68,0); } } /* ---- istatistik kutuları ---- */ .nw-stats { display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:12px; margin-bottom:14px; } .nw-stat { padding:14px 16px; border-radius:16px; position:relative; overflow:hidden; background:linear-gradient(135deg, rgba(14,30,54,.92), rgba(7,16,30,.9)); border:1px solid rgba(96,165,250,.2); transition:transform .2s, box-shadow .2s; animation:nwUp .5s ease both; } .nw-stat:hover { transform:translateY(-3px); box-shadow:0 10px 26px rgba(96,165,250,.2); } .nw-stat:after { content:""; position:absolute; right:-18px; top:-18px; width:70px; height:70px; border-radius:50%; background:var(--c,#60a5fa); opacity:.14; } .nw-stat b { display:block; font-size:28px; font-weight:800; color:var(--c,#e2e8f0); letter-spacing:-1px; } .nw-stat span { font-size:11px; letter-spacing:1.2px; color:#8295ad; text-transform:uppercase; } /* ---- filtre ---- */ .nw-filters { display:flex; gap:8px; flex-wrap:wrap; margin:6px 0 14px; } .nw-filters input { display:none; } .nw-filters label { cursor:pointer; padding:7px 16px; border-radius:99px; font-size:12px; font-weight:700; background:#0f1d33; color:#9fb0c6; border:1px solid rgba(96,165,250,.25); transition:all .15s; user-select:none; } .nw-filters label:hover { transform:translateY(-2px); color:#fff; } .nw-wrap:has(#nwf-all:checked) label[for=nwf-all], .nw-wrap:has(#nwf-bull:checked) label[for=nwf-bull], .nw-wrap:has(#nwf-neu:checked) label[for=nwf-neu], .nw-wrap:has(#nwf-bear:checked) label[for=nwf-bear], .nw-wrap:has(#nwf-hot:checked) label[for=nwf-hot] { background:#60a5fa; color:#04101f; border-color:#bfdbfe; box-shadow:0 0 16px rgba(96,165,250,.5); } .nw-wrap:has(#nwf-bull:checked) .nw-news:not([data-l=Bullish]), .nw-wrap:has(#nwf-neu:checked) .nw-news:not([data-l=Neutral]), .nw-wrap:has(#nwf-bear:checked) .nw-news:not([data-l=Bearish]), .nw-wrap:has(#nwf-hot:checked) .nw-news:not([data-hot="1"]) { display:none; } /* ---- haber kartları ---- */ .nw-list { display:grid; grid-template-columns:repeat(auto-fill,minmax(340px,1fr)); gap:12px; } .nw-news { border-left:4px solid var(--c); padding:14px 16px; margin:0; position:relative; overflow:hidden; transition:transform .2s ease, box-shadow .2s ease, border-color .2s; animation:nwUp .55s ease both; animation-delay:calc(var(--i) * 28ms); display:flex; flex-direction:column; gap:8px; } .nw-news:before { content:""; position:absolute; inset:0; pointer-events:none; opacity:0; transition:opacity .25s; background:radial-gradient(circle at 0% 0%, var(--c), transparent 55%); } .nw-news:hover { transform:translateY(-4px) scale(1.01); box-shadow:0 16px 36px rgba(0,0,0,.45), 0 0 22px color-mix(in srgb, var(--c) 40%, transparent); } .nw-news:hover:before { opacity:.12; } .nw-news a { color:#e8eef9; font-weight:650; text-decoration:none; line-height:1.4; font-size:14.5px; position:relative; } .nw-news a:hover { color:#93c5fd; } .nw-sum { color:#8b9bb3; font-size:12px; line-height:1.45; position:relative; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden; } .nw-top { display:flex; align-items:center; gap:8px; position:relative; } .nw-av { width:24px; height:24px; border-radius:8px; display:grid; place-items:center; font-size:11px; font-weight:800; color:#fff; background:hsl(var(--h),55%,38%); flex:none; } .nw-src { font-size:11.5px; color:#a9b8cf; font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } .nw-badge { margin-left:auto; font-size:10px; font-weight:800; letter-spacing:.6px; padding:2px 8px; border-radius:99px; white-space:nowrap; } .nw-hot { background:linear-gradient(90deg,#f97316,#ef4444); color:#fff; animation:nwGlow 1.8s ease-in-out infinite alternate; } .nw-new { background:#38bdf8; color:#04101f; } @keyframes nwGlow { to { box-shadow:0 0 14px rgba(249,115,22,.9); } } @keyframes nwUp { from { opacity:0; transform:translateY(14px); } to { opacity:1; transform:none; } } .nw-meta { color:#7d8ea6; font-size:11px; display:flex; gap:8px; flex-wrap:wrap; align-items:center; position:relative; } .nw-chip { padding:2px 9px; border-radius:99px; font-weight:700; font-size:11px; background:var(--c); color:#06101f; } .nw-imp { width:70px; height:6px; border-radius:9px; background:#172235; overflow:hidden; margin-left:auto; } .nw-imp i { display:block; height:100%; background:linear-gradient(90deg,#60a5fa,#f97316); } .nw-tag { padding:1px 7px; border-radius:6px; background:#1e293b; color:#93c5fd; font-weight:700; } .nw-gauge { width:100%; max-width:230px; } /* ---- toplu tarama ---- */ .nw-heat { display:grid; grid-template-columns:repeat(auto-fill,minmax(150px,1fr)); gap:10px; margin-bottom:14px; } .nw-hcell { padding:10px 12px; border-radius:14px; border:1px solid rgba(96,165,250,.2); position:relative; overflow:hidden; background:linear-gradient(135deg, color-mix(in srgb, var(--c) 28%, #0a1424), #07101e); transition:transform .15s; } .nw-hcell:hover { transform:translateY(-3px); } .nw-hcell b { font-size:15px; letter-spacing:.5px; } .nw-hcell i { font-style:normal; float:right; font-weight:800; color:var(--c); font-size:14px; } .nw-hcell span { display:block; font-size:11px; color:#8295ad; margin-top:2px; } .nw-mini { display:flex; height:5px; border-radius:9px; overflow:hidden; margin-top:6px; background:#172235; } .nw-mini u { display:block; height:100%; text-decoration:none; } .nw-ast { border-radius:14px; margin-bottom:8px; border:1px solid rgba(96,165,250,.16); border-left:4px solid var(--c); background:linear-gradient(180deg, rgba(8,18,34,.9), rgba(5,13,25,.85)); } .nw-ast > summary { cursor:pointer; list-style:none; padding:11px 14px; display:flex; gap:12px; align-items:center; flex-wrap:wrap; } .nw-ast > summary::-webkit-details-marker { display:none; } .nw-ast > summary b { min-width:62px; font-size:15px; } .nw-ast .nw-body { padding:2px 14px 12px; display:flex; flex-direction:column; gap:6px; } .nw-ast .nw-body a { color:#dbe7fb; text-decoration:none; font-size:13.5px; line-height:1.4; } .nw-ast .nw-body a:hover { color:#93c5fd; text-decoration:underline; } .nw-ast .nw-row { display:flex; gap:8px; align-items:baseline; } .nw-ast .nw-row small { color:#7d8ea6; white-space:nowrap; } @media (max-width:640px){ .nw-grid { grid-template-columns:1fr; justify-items:center; } .nw-list { grid-template-columns:1fr; } } """ def svg_gauge(net): """Yarım daire piyasa ruh hali ibresi (-1..+1).""" import math ang = math.pi * (1 - (max(-1, min(1, net)) + 1) / 2) # pi (sol) .. 0 (sağ) cx, cy, r = 100, 100, 78 nx, ny = cx + (r - 14) * math.cos(ang), cy - (r - 14) * math.sin(ang) segs = [("#ef4444", 180, 120), ("#f97316", 120, 90), ("#eab308", 90, 60), ("#84cc16", 60, 30), ("#22c55e", 30, 0)] o = [""] for col, a0, a1 in segs: x0, y0 = cx + r * math.cos(math.radians(a0)), cy - r * math.sin(math.radians(a0)) x1, y1 = cx + r * math.cos(math.radians(a1)), cy - r * math.sin(math.radians(a1)) o.append(f"") o.append(f"" f"" f"" "KORKU" "HIRS") return "".join(o) def _mood(net): return ("Aşırı iyimser" if net > .5 else "İyimser" if net > .15 else "Dengeli" if net > -.15 else "Temkinli" if net > -.5 else "Aşırı kötümser") def _ingest(detect_assets, period): """Kaynakları tara, varlıkları etiketle, DB'ye yaz; (pencere, ok, toplam, saat, yarı_ömür, taze_sayısı) döndür.""" hours, _, half = PERIODS.get(period, PERIODS["Günlük"]) fresh, ok, total = fetch_news(period) if not fresh and not db_load(hours): return None for i in fresh: i["assets"] = sorted(set(i.get("hint", [])) | set(detect_assets(i["title"]))) db_store(fresh) return db_load(hours), ok, total, hours, half, len(fresh) def build_news_panel(classify, detect_assets, asset="ALL", timeframe="1A", period="Günlük", limit=None, query=None): limit = int(limit or DEFAULT_LIMIT.get(period, 30)) got = _ingest(detect_assets, period) if got is None: return ("
Haber kaynaklarına ulaşılamadı. " "Ağ erişimini veya FEEDS adreslerini kontrol et.
") window, ok, total, hours, half, _ = got stats = {} for a in ASSET_QUERY: mine = [i for i in window if a in i["assets"]] lab = [i["score"] for i in mine if i["label"] is not None] stats[a] = (len(mine), sum(lab) / len(lab) if lab else None) pool = window if asset == "ALL" else [i for i in window if asset in i["assets"]] if query and query.strip(): qwords = [w for w in re.findall(r"[a-z0-9$]+", query.lower()) if w] pool = [i for i in pool if all(w in (i["title"] + " " + i["summary"]).lower() for w in qwords)] top = rank_news(pool, limit=limit, max_age_h=hours, half=half) # LLM ile en önemli (etiketsiz) haberleri etiketle; kalanlar için hızlı leksikon done = 0 for t in top: if t.get("label") is None: if done < MAX_CLASSIFY: try: t["label"], t["score"] = classify(t["title"] + ". " + t["summary"][:200]) except Exception: t["label"], t["score"] = "Neutral", 0.0 db_label(t["id"], t["label"], t["score"]) done += 1 for w in pool: if w["id"] == t["id"]: w["label"], w["score"] = t["label"], t["score"] else: t["label"], t["score"] = quick_sentiment(t["title"] + " " + t["summary"]) t["approx"] = True counts = {"Bullish": 0, "Neutral": 0, "Bearish": 0} wsum = nsum = 0.0 for t in top: counts[t["label"] if t["label"] in counts else "Neutral"] += 1 w = 1 + t["imp"] / 25 wsum += w nsum += w * t["score"] net = nsum / wsum if wsum else 0.0 if asset == "ALL": hot_syms = [a for a, (n, _) in sorted(stats.items(), key=lambda kv: -kv[1][0]) if n > 0][:5] syms = hot_syms if len(hot_syms) >= 3 else MAJORS with ThreadPoolExecutor(max_workers=5) as ex: res = list(ex.map(lambda a: (a, _safe_price(a, timeframe)), syms)) chart = f"
{svg_compare({a: r for a, r in res if r}, timeframe)}
" chart += f"
{svg_assets(stats)}
" else: try: rows = price_series(asset, timeframe) marks = [(t["ts"], COL.get(t["label"], "#eab308"), t["title"]) for t in top] chart = f"
{svg_candles(rows, asset, timeframe, marks)}
" except Exception as e: chart = f"
Fiyat grafiği yüklenemedi: {html.escape(str(e))[:120]}
" tl = svg_timeline(pool, hours) if tl: chart += f"
{tl}
" # ---- üst şerit + istatistik kutuları tick = "".join( f"" f"{html.escape(t['title'])}" for t in top[:15]) ticker = (f"
" f"CANLI{tick}
") if top else "" n_src = len({s for t in top for s in t["srcs"]}) hot = sum(1 for t in top if t["imp"] >= 50) bull_pct = 100 * counts["Bullish"] / max(1, len(top)) tiles = (f"
" f"
{len(pool)}Taranan haber
" f"
{n_src}Aktif kaynak
" f"
{hot}🔥 Sıcak haber
" f"
%{bull_pct:.0f}Yükseliş payı
") legend = "".join(f"{k} {counts[k]}" for k in COL) summary = (f"
{svg_donut(counts, net)}
" f"{period} haber duygu özeti • {asset} önem ağırlıklı • {len(top)}/{len(pool)} haber • " f"{ok}/{total} kaynak
{legend}
") mood = (f"
Piyasa ruh hali
" f"{svg_gauge(net)}
{_mood(net)}
") filters = ("
" "" "" "" "" "
") cards = [] for idx, t in enumerate(top): c = COL.get(t["label"], "#eab308") age = f"{t['age_h']*60:.0f} dk" if t["age_h"] < 1 else f"{t['age_h']:.0f} sa" if t["age_h"] < 48 else f"{t['age_h']/24:.0f} gün" tags = " ".join(f"{a}" for a in t["assets"][:3]) src = t["srcs"][0] if t["srcs"] else t["source"] hue = int(hashlib.md5(src.encode()).hexdigest()[:4], 16) % 360 is_hot = t["imp"] >= 50 badge = ("🔥 SICAK" if is_hot else "YENİ" if t["age_h"] < 1 else "") more = f" +{len(t['srcs'])-1}" if len(t["srcs"]) > 1 else "" summ = f"
{html.escape(t['summary'])}
" if t["summary"] else "" approx = "~" if t.get("approx") else "" cards.append( f"
" f"
{html.escape(src[:1].upper())}" f"{html.escape(src)}{more}{badge}
" f"{html.escape(t['title'])}{summ}" f"
{approx}{t['label']} {t['score']:+.1f}{tags}" f"⏱ {age} önce" f"
") if not cards: cards = ["
Bu dönem/varlık için önemli haber bulunamadı.
"] note = ("
Aylık görünüm Google News + biriken tarama geçmişinden gelir; " "zaman çizgisi uygulama çalıştıkça dolar. “~” işareti hızlı anahtar kelime tahminidir; sonraki taramalarda model etiketler.
" if hours > 24 else "
“~” işareti hızlı anahtar kelime tahminidir; sonraki taramalarda model etiketler.
") stamp = datetime.now().strftime("%H:%M:%S") return (f"
{ticker}" f"
Son tarama: {stamp} • önbellek {NEWS_TTL//60} dk • {ok}/{total} kaynak yanıt verdi
" f"{tiles}
{summary}{mood}
" f"{chart}{note}{filters}
{''.join(cards)}
") def _safe_price(a, tf): try: return price_series(a, tf) except Exception: return None # ------------------------------------------------------------------ TOPLU TARAMA BULK_SORTS = ["Haber sayısı", "En bullish", "En bearish"] def _lab_color(sc): return "#22c55e" if sc > 0.05 else "#ef4444" if sc < -0.05 else "#eab308" def build_bulk_panel(classify, detect_assets, period="Günlük", per_asset=3, budget=None, sort="Haber sayısı"): """Tüm paritelerin haberlerini tek seferde tarar; parite başına özet + ısı haritası üretir. budget: bu taramada LLM ile etiketlenecek en fazla başlık (kalanlar anahtar-kelime tahmini "~"; etiketler DB'de saklandığı için her taramada daha fazlası model etiketine dönüşür). """ per_asset = max(1, int(per_asset or 3)) budget = MAX_BULK_CLASSIFY if budget is None else max(0, int(budget)) got = _ingest(detect_assets, period) if got is None: return ("
Haber kaynaklarına ulaşılamadı. " "Ağ erişimini veya FEEDS adreslerini kontrol et.
") window, ok, total, hours, half, n_fresh = got ranked = rank_news(window, limit=10 ** 6, max_age_h=hours, half=half) # tekilleştirilmiş hikâyeler by_asset = {a: [] for a in ASSET_LIST} for t in ranked: for a in t["assets"]: if a in by_asset: by_asset[a].append(t) for a in by_asset: # her varlık için en önemli per_asset haber by_asset[a].sort(key=lambda t: t["imp"], reverse=True) # etiketleme: her paritenin en önemli haberleri, önem sırasıyla, bütçe dolana dek model ile picks, seen = [], set() for a in ASSET_LIST: for t in by_asset[a][:per_asset]: if t["id"] not in seen: seen.add(t["id"]) picks.append(t) picks.sort(key=lambda t: t["imp"], reverse=True) done = 0 for t in picks: if t.get("label") is None: if done < budget: try: t["label"], t["score"] = classify(t["title"] + ". " + t["summary"][:200]) except Exception: t["label"], t["score"] = "Neutral", 0.0 db_label(t["id"], t["label"], t["score"]) done += 1 else: t["label"], t["score"] = quick_sentiment(t["title"] + " " + t["summary"]) t["approx"] = True # parite istatistikleri (yalnızca gösterilen/etiketlenen haberlerden) rows = [] for a in ASSET_LIST: lst = by_asset[a] if not lst: continue shown = lst[:per_asset] cnt = {"Bullish": 0, "Neutral": 0, "Bearish": 0} ws = ns = 0.0 for t in shown: cnt[t["label"] if t["label"] in cnt else "Neutral"] += 1 w = 1 + t["imp"] / 25 ws += w ns += w * t["score"] rows.append({"a": a, "n": len(lst), "net": ns / ws if ws else 0.0, "cnt": cnt, "shown": shown, "hot": sum(1 for t in lst if t["imp"] >= 50)}) if sort == "En bullish": rows.sort(key=lambda r: (-r["net"], -r["n"])) elif sort == "En bearish": rows.sort(key=lambda r: (r["net"], -r["n"])) else: rows.sort(key=lambda r: (-r["n"], -r["net"])) if not rows: return "
Bu dönemde hiçbir parite için haber bulunamadı.
" uniq_total = len(ranked) tagged = sum(1 for t in ranked if t["assets"]) model_labeled = sum(1 for t in picks if not t.get("approx")) tiles = (f"
" f"
{len(window)}Taranan haber
" f"
{uniq_total}Tekil hikâye
" f"
{len(rows)}/{len(ASSET_LIST)}Haberi olan parite
" f"
{sum(r['hot'] for r in rows)}🔥 Sıcak haber
" f"
{model_labeled}/{len(picks)}Model etiketli
") heat = "".join( f"
{r['net']:+.2f}{r['a']}" f"{r['n']} haber • 🔥{r['hot']}" f"
" f"" f"
" for r in rows) details = [] for r in rows: lines = [] for t in r["shown"]: ap = "~" if t.get("approx") else "" age = (f"{t['age_h']*60:.0f} dk" if t["age_h"] < 1 else f"{t['age_h']:.0f} sa" if t["age_h"] < 48 else f"{t['age_h']/24:.0f} gün") lines.append( f"
" f"{ap}{t['label']} {t['score']:+.1f}" f"{html.escape(t['title'])}" f"{html.escape(t['srcs'][0] if t['srcs'] else t['source'])} • {age}
") details.append( f"
{r['a']}" f"net {r['net']:+.2f}" f"{r['n']} haber • 🟢{r['cnt']['Bullish']} " f"🟡{r['cnt']['Neutral']} 🔴{r['cnt']['Bearish']}" f"
{''.join(lines)}
") stamp = datetime.now().strftime("%H:%M:%S") note = ("
“~” işareti hızlı anahtar kelime tahminidir. Model etiketleri DB’de saklanır; " "her taramada daha fazla başlık modele geçer. Net skor, her paritenin en önemli haberlerinden hesaplanır.
") return (f"
" f"
{period} toplu tarama • Son tarama: {stamp} • " f"{ok}/{total} kaynak yanıt verdi • {n_fresh} taze haber • bu turda {done} başlık modelle etiketlendi
" f"{tiles}
Parite ısı haritası" f"renk = net duygu • sayı = haber adedi • çubuk = bullish/neutral/bearish
" f"
{heat}
{note}{''.join(details)}
") # ------------------------------------------------------------------ FİYAT PANOSU def price_snapshot(assets, hours=24): """Varlıklar için (sembol, son_fiyat, değişim_% , spark noktaları) döndürür.""" import yfinance as yf out = [] for a in assets: try: df = yf.Ticker(YF_SYMBOL.get(a, f"{a}-USD")).history(period="2d", interval="1h") closes = [float(c) for c in df["Close"] if c == c] if len(closes) < 2: continue win = closes[-(hours + 1):] last = win[-1] chg = (last / win[0] - 1) * 100 out.append({"asset": a, "last": last, "chg": chg, "spark": win}) except Exception: continue return out def _svg_spark(vals, w=110, h=30): if len(vals) < 2: return "" lo, hi = min(vals), max(vals) rng = (hi - lo) or (hi * 0.01 or 1) n = len(vals) pts = " ".join(f"{w * i / (n - 1):.1f},{h - 3 - (h - 6) * (v - lo) / rng:.1f}" for i, v in enumerate(vals)) col = "#22c55e" if vals[-1] >= vals[0] else "#ef4444" return (f"" f"") def build_price_board(assets, hours=24): """İzleme listesi fiyat panosu HTML'i.""" snap = price_snapshot(assets, hours) if not snap: return "
Fiyat verisi alınamadı.
" snap.sort(key=lambda s: -abs(s["chg"])) rows = [] for s in snap: col = "#22c55e" if s["chg"] >= 0 else "#ef4444" arrow = "▲" if s["chg"] >= 0 else "▼" rows.append( f"{s['asset']}/USD" f"{_fmt(s['last'])}" f"{arrow} {s['chg']:+.2f}%" f"{_svg_spark(s['spark'])}") gainers = sum(1 for s in snap if s["chg"] > 0) stamp = datetime.now().strftime("%H:%M:%S") return (f"
" f"Son güncelleme: {stamp} • {gainers}/{len(snap)} parite yükselişte • son {hours} saat
" f"
" f"" f"" f"{''.join(rows)}
PariteFiyatDeğişimTrend
") BOARD_CSS = """ .nw-board { width:100%; border-collapse:collapse; font-size:13.5px; } .nw-board th { text-align:left; color:#8295ad; font-size:11px; letter-spacing:1px; text-transform:uppercase; padding:6px 10px; border-bottom:1px solid rgba(96,165,250,.2); } .nw-board td { padding:9px 10px; border-bottom:1px solid rgba(148,163,184,.08); color:#dbeafe; } .nw-board tbody tr:hover { background:rgba(96,165,250,.07); } """ NEWS_CSS += BOARD_CSS