CoolFace
Apppublic

kaan1233/bistelligence-api

sourceHugging Faceupdated 2mo agoView on Hugging Face
0likes
external_data.py114 linesDownload Raw Back to root
1import pandas as pd2import requests3import json4import os5import logging6from datetime import datetime, timedelta7 8logger = logging.getLogger("bistelligence.external")9 10# =======================================================11# TCMB EVDS (Makro Ekonomi) API12# =======================================================13def fetch_tcmb_macro_data(api_key=None):14    """15    TCMB EVDS API'den temel makroekonomik verileri çeker.16    Eğer API Key yoksa None döndürür.17    """18    if not api_key:19        api_key = os.getenv("EVDS_API_KEY")20        21    if not api_key:22        logger.warning("EVDS API Key bulunamadı. Makro veriler çekilemiyor.")23        return None24        25    try:26        start_date = (datetime.now() - timedelta(days=365)).strftime("%d-%m-%Y")27        end_date = datetime.now().strftime("%d-%m-%Y")28        29        # TCMB EVDS3 Yeni API Endpoint'i ve Header formatı30        url = f"https://evds3.tcmb.gov.tr/igmevdsms-dis/series=TP.DK.USD.S.YTL-TP.KTF10&startDate={start_date}&endDate={end_date}&type=json"31        headers = {'key': api_key}32        33        # Sertifika hatalarını yok saymak için verify=False ekliyoruz (TCMB sunucularında bazen olabiliyor)34        import urllib335        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)36        37        response = requests.get(url, headers=headers, timeout=10, verify=False)38        if response.status_code == 200:39            data = response.json()40            if "items" in data:41                df = pd.DataFrame(data["items"])42                df["Tarih"] = pd.to_datetime(df["Tarih"], format="%d-%m-%Y", errors='coerce')43                df = df.dropna(subset=["Tarih"])44                df.set_index("Tarih", inplace=True)45                46                df.rename(columns={47                    "TP_DK_USD_S_YTL": "USD_TRY",48                    "TP_KTF10": "TCMB_Faiz"49                }, inplace=True)50                51                for col in ["USD_TRY", "TCMB_Faiz"]:52                    df[col] = pd.to_numeric(df[col], errors='coerce')53                54                df.fillna(method='ffill', inplace=True)55                return df56                57        return None58    except Exception as e:59        logger.error(f"EVDS Macro veri çekme hatası: {e}")60        return None61 62 63# =======================================================64# İŞ YATIRIM YABANCI TAKAS ORANI65# =======================================================66def scrape_foreign_ownership():67    """68    Aracı kurumlardan yabancı takas oranını çeker.69    """70    try:71        headers = {72            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'73        }74        75        # İsYatırım Ajax Gizli API76        url = "https://www.isyatirim.com.tr/_layouts/15/IsYatirim.Website/Common/Data.aspx/YabanciOran"77        78        response = requests.get(url, headers=headers, timeout=10)79        80        if response.status_code == 200:81            try:82                data = response.json()83                if "value" in data:84                    df = pd.DataFrame(data["value"])85                    if not df.empty and "Hisse" in df.columns:86                        df["Ticker"] = df["Hisse"].astype(str) + ".IS"87                        88                        result = {}89                        for _, row in df.iterrows():90                            try:91                                # Yabancı oranı (Örn: 15.4)92                                result[row["Ticker"]] = float(row.get("YabanciOrani", 0))93                            except:94                                pass95                        return result96            except json.JSONDecodeError:97                pass98                99        logger.warning("Yabancı takas oranı çekilemedi (Endpoint değişmiş olabilir).")100        return {}101        102    except Exception as e:103        logger.error(f"Yabancı Takas veri çekme hatası: {e}")104        return {}105 106if __name__ == "__main__":107    print("Yabancı Takas Oranı Test Ediliyor...")108    yabanci_data = scrape_foreign_ownership()109    if yabanci_data:110        print(f"Başarılı! {len(yabanci_data)} hissenin yabancı takas oranı çekildi.")111        print("Örnek (THYAO.IS):", yabanci_data.get("THYAO.IS", "Bulunamadı"))112    else:113        print("Başarısız.")114