Source code · Python

market_data.py

107 lines · Part of ES trading: edge and risk · All code · Read only; the files run as published

"""Market data for the study: daily index, futures and VIX bars, and FOMC dates.     S&P 500 index (^GSPC), E-mini S&P 500 continuous (ES=F), VIX (^VIX)        daily bars from Yahoo Finance's chart endpoint, cached locally.    FOMC meeting dates        the Federal Reserve's meeting calendars: fomccalendars.htm for recent        years and fomchistoricalYYYY.htm before them. Parsed into        data/fomc_dates.csv, which is committed with each date's source page. Raw downloads stay in the cache folder and are not published."""import csvimport jsonimport reimport timeimport urllib.requestfrom pathlib import Path import pandas as pd HERE = Path(__file__).resolve().parentFOMC_CSV = HERE / "data" / "fomc_dates.csv"UA = {"User-Agent": "Mozilla/5.0 (chip-street-capital research script)"}FED = "https://www.federalreserve.gov/monetarypolicy/"MONTHS = {m: i for i, m in enumerate(    ["January", "February", "March", "April", "May", "June", "July", "August",     "September", "October", "November", "December"], 1)}SHORT = {k[:3]: v for k, v in MONTHS.items()}  def _get(url: str, path: Path) -> Path:    if not path.exists():        req = urllib.request.Request(url, headers=UA)        with urllib.request.urlopen(req, timeout=60) as r:            path.write_bytes(r.read())    return path  def daily_bars(symbol: str, cache: Path) -> pd.DataFrame:    """Daily open, high, low, close, indexed by New York trading date."""    cache.mkdir(parents=True, exist_ok=True)    name = symbol.replace("^", "").replace("=", "_")    url = ("https://query1.finance.yahoo.com/v8/finance/chart/"           f"{urllib.request.quote(symbol)}?period1=946684800&period2={int(time.time())}&interval=1d")    raw = json.loads(_get(url, cache / f"{name}.json").read_text())["chart"]["result"][0]    q = raw["indicators"]["quote"][0]    idx = (pd.to_datetime(raw["timestamp"], unit="s").tz_localize("UTC")           .tz_convert("America/New_York").normalize().tz_localize(None))    bars = pd.DataFrame({k: q[k] for k in ["open", "high", "low", "close"]}, index=idx).dropna()    return bars[~bars.index.duplicated(keep="last")].sort_index()  def _month(token: str) -> int:    token = token.strip()    return MONTHS.get(token) or SHORT[token[:3]]  def _last_day(year: int, months: str, days: str) -> pd.Timestamp:    """The statement day (last day) of a meeting written like 'April/May', '30-1'."""    last_month = _month(re.split(r"[/-]", months)[-1])    last = int(days.split("-")[-1])    return pd.Timestamp(year, last_month, last)  def fomc_dates(cache: Path) -> pd.DataFrame:    """Scheduled FOMC statement days, 2000 onward. Unscheduled meetings,    conference calls, notation votes and the cancelled March 2020 meeting are    left out: the trading filter skips the scheduled calendar."""    cache.mkdir(parents=True, exist_ok=True)    rows = []    recent = _get(FED + "fomccalendars.htm", cache / "fomccalendars.htm").read_text()    for block in re.split(r'<h4><a id="\d+">', recent)[1:]:        year = int(block[:4])        for m, d in re.findall(r'fomc-meeting__month[^>]*><strong>([^<]*)</strong>.*?fomc-meeting__date[^>]*>([^<]*)<', block, re.S):            if re.search(r"unscheduled|notation|cancel", d, re.I):                continue            days = re.match(r"\s*(\d{1,2}(?:-\d{1,2})?)", d).group(1)            rows.append((_last_day(year, m, days), "*" in d, "fomccalendars.htm"))    first_recent = min(r[0].year for r in rows)    for year in range(2000, first_recent):        page = f"fomchistorical{year}.htm"        html = _get(FED + page, cache / page).read_text()        for label in re.findall(r"<h5[^>]*>([^<]*)</h5>", html):            if "Meeting" not in label or re.search(r"unscheduled|cancel", label, re.I):                continue            # 'March 17-18 Meeting - 2015', 'Jan/Feb 31-1 Meeting - 2017',            # 'July 31-August 1  Meeting - 2012'            text = label.split(" Meeting")[0].strip()            mm = re.match(r"([A-Za-z]+)(?:/([A-Za-z]+))? (\d{1,2})(?:-([A-Za-z]+ )?(\d{1,2}))?$", text)            first_m, slash_m, d1, dash_m, d2 = mm.groups()            last_m = _month(slash_m or (dash_m or first_m))            rows.append((pd.Timestamp(year, last_m, int(d2 or d1)), None, page))    out = pd.DataFrame(rows, columns=["date", "projections", "source"]).drop_duplicates("date").sort_values("date")    # A meeting listed as two entries on consecutive days (September 15 and 16,    # 2003) has one statement day, the later one.    out = out[~(out["date"].shift(-1) - out["date"]).le(pd.Timedelta(days=2))]    return out.reset_index(drop=True)  def write_fomc_csv(dates: pd.DataFrame) -> None:    FOMC_CSV.parent.mkdir(exist_ok=True)    with FOMC_CSV.open("w", newline="") as f:        w = csv.writer(f)        w.writerow(["statement_date", "source"])        for r in dates.itertuples():            w.writerow([r.date.date().isoformat(), FED + r.source])