Initial public release
This commit is contained in:
@@ -0,0 +1,178 @@
|
||||
"""Build data/processed/global_daily_returns.parquet from the EODHD cache.
|
||||
|
||||
Reads the latest global universe parquet (from build_global_universe.py),
|
||||
iterates each ticker's cached `data/raw/eodhd/eod/{ticker}.json`, concatenates
|
||||
into a long-format daily-returns panel, and persists.
|
||||
|
||||
Schema (matches the US data/processed/daily_returns.parquet for compatibility
|
||||
with existing hygiene detectors at src/data/data_hygiene.py):
|
||||
date, ticker, open, high, low, close, adjusted_close, volume, ret_d
|
||||
|
||||
Reasonable to re-run any time the universe parquet is rebuilt or OHLCV cache
|
||||
is refreshed via scripts/live/warm_ohlcv_cache.py.
|
||||
|
||||
Usage:
|
||||
.venv/Scripts/python.exe scripts/data/build_global_daily_returns.py
|
||||
.venv/Scripts/python.exe scripts/data/build_global_daily_returns.py --from 2020-01-01
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from src.data.hard_excluded_tickers import apply_hard_exclusion_mask
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
|
||||
datefmt="%Y-%m-%dT%H:%M:%S",
|
||||
)
|
||||
logger = logging.getLogger("build_global_daily_returns")
|
||||
|
||||
_UNIVERSE_DIR = Path("data/universe")
|
||||
_CACHE_DIR = Path("data/raw/eodhd/eod")
|
||||
_OUT_PATH = Path("data/processed/global_daily_returns.parquet")
|
||||
|
||||
|
||||
def _latest_universe_parquet() -> Path:
|
||||
files = sorted(_UNIVERSE_DIR.glob("global_msci_world_imi_*.parquet"))
|
||||
if not files:
|
||||
raise FileNotFoundError(
|
||||
f"No universe parquet in {_UNIVERSE_DIR} — run build_global_universe.py first"
|
||||
)
|
||||
return files[-1]
|
||||
|
||||
|
||||
def _load_one_ticker(ticker: str) -> pd.DataFrame | None:
|
||||
cache_path = _CACHE_DIR / f"{ticker}.json"
|
||||
if not cache_path.is_file():
|
||||
return None
|
||||
try:
|
||||
raw = json.loads(cache_path.read_text(encoding="utf-8"))
|
||||
except (json.JSONDecodeError, OSError) as exc:
|
||||
logger.warning("Bad cache for %s: %s", ticker, exc)
|
||||
return None
|
||||
if not raw:
|
||||
return None
|
||||
|
||||
df = pd.DataFrame(raw)
|
||||
if df.empty or "date" not in df.columns:
|
||||
return None
|
||||
|
||||
rename = {"adjustedClose": "adjusted_close"}
|
||||
df = df.rename(columns=rename)
|
||||
required = {"date", "close", "adjusted_close", "volume"}
|
||||
missing = required - set(df.columns)
|
||||
if missing:
|
||||
logger.warning("%s missing required columns %s — skipping", ticker, missing)
|
||||
return None
|
||||
|
||||
df["date"] = pd.to_datetime(df["date"])
|
||||
df = df.sort_values("date").reset_index(drop=True)
|
||||
df["ticker"] = ticker
|
||||
# Remove manually verified bad-data `(ticker, date)` rows before the code
|
||||
# calculates `ret_d`.
|
||||
# This order prevents false returns across two ticker eras for a reused symbol.
|
||||
# The first retained row from the second era therefore has a NaN `pct_change`.
|
||||
# For example, see the first GMIN.TO era through 2024-04-04 in
|
||||
# `src/data/hard_excluded_tickers.py`.
|
||||
#
|
||||
# With `bounded_ranges_only=True`, the live path applies only finite
|
||||
# historical ranges.
|
||||
# The live path skips permanent, date-bounded, and open-ended exclusions.
|
||||
# Those exclusions block a current index member when that member reuses an old symbol.
|
||||
# A finite manual range removes rows only within its start and end dates.
|
||||
# The backtest path in `src/universe.py` applies the full registry.
|
||||
excl = apply_hard_exclusion_mask(df, bounded_ranges_only=True)
|
||||
if excl.any():
|
||||
df = df[~excl].reset_index(drop=True)
|
||||
if df.empty:
|
||||
return None
|
||||
df["ret_d"] = df["adjusted_close"].pct_change()
|
||||
# The output uses the standard column order and includes `open`, `high`, and
|
||||
# `low` when those columns exist in the input.
|
||||
cols = ["date", "ticker", "open", "high", "low", "close", "adjusted_close", "volume", "ret_d"]
|
||||
out = df[[c for c in cols if c in df.columns]]
|
||||
return out
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--from-date", dest="from_date", default=None,
|
||||
help="Filter rows to date >= from_date (YYYY-MM-DD)")
|
||||
parser.add_argument("--to-date", dest="to_date", default=None,
|
||||
help="Filter rows to date <= to_date (YYYY-MM-DD)")
|
||||
parser.add_argument("--out", default=str(_OUT_PATH),
|
||||
help=f"Output parquet path (default: {_OUT_PATH})")
|
||||
args = parser.parse_args()
|
||||
|
||||
universe_path = _latest_universe_parquet()
|
||||
universe = pd.read_parquet(universe_path)
|
||||
tickers = sorted(universe["eodhd_ticker"].dropna().unique().tolist())
|
||||
logger.info("Universe %s: %d tickers", universe_path.name, len(tickers))
|
||||
|
||||
frames: list[pd.DataFrame] = []
|
||||
n_loaded = 0
|
||||
n_missing = 0
|
||||
start = time.monotonic()
|
||||
for i, ticker in enumerate(tickers, 1):
|
||||
df = _load_one_ticker(ticker)
|
||||
if df is None:
|
||||
n_missing += 1
|
||||
continue
|
||||
frames.append(df)
|
||||
n_loaded += 1
|
||||
if i % 500 == 0:
|
||||
elapsed = time.monotonic() - start
|
||||
logger.info("[%d/%d] loaded=%d missing=%d (%.1f s)",
|
||||
i, len(tickers), n_loaded, n_missing, elapsed)
|
||||
|
||||
if not frames:
|
||||
logger.error("No frames loaded — refusing to write empty panel")
|
||||
sys.exit(1)
|
||||
|
||||
logger.info("Concatenating %d frames ...", len(frames))
|
||||
panel = pd.concat(frames, ignore_index=True)
|
||||
|
||||
if args.from_date:
|
||||
panel = panel[panel["date"] >= args.from_date]
|
||||
if args.to_date:
|
||||
panel = panel[panel["date"] <= args.to_date]
|
||||
|
||||
out_path = Path(args.out)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = out_path.with_suffix(".tmp")
|
||||
panel.to_parquet(tmp, index=False)
|
||||
tmp.replace(out_path)
|
||||
|
||||
elapsed = time.monotonic() - start
|
||||
logger.info("=" * 72)
|
||||
logger.info("Saved %d rows × %d tickers to %s in %.1f s",
|
||||
len(panel), panel["ticker"].nunique(), out_path, elapsed)
|
||||
logger.info(
|
||||
"Date range: %s -> %s | first ret_d: %s | tickers missing from cache: %d",
|
||||
panel["date"].min().date(), panel["date"].max().date(),
|
||||
panel["ret_d"].first_valid_index() is not None, n_missing,
|
||||
)
|
||||
by_region_top = (
|
||||
universe.merge(
|
||||
pd.DataFrame({"eodhd_ticker": panel["ticker"].unique()}),
|
||||
on="eodhd_ticker",
|
||||
)
|
||||
.groupby("region_bucket")
|
||||
.size()
|
||||
.sort_index()
|
||||
)
|
||||
logger.info("Panel tickers per region: %s", by_region_top.to_dict())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Generate data/processed/global_excluded_ticker_dates.parquet.
|
||||
|
||||
Runs the same three data-hygiene detectors as scripts/data/build_exclusion_table.py
|
||||
(US) but against the global daily-returns panel built by
|
||||
scripts/data/build_global_daily_returns.py.
|
||||
|
||||
Detectors (parameters mirror US build for consistency; threshold sensitivity
|
||||
for non-US regimes — particularly Japan low-vol — may warrant review later):
|
||||
- detect_frozen_runs (min_length=5)
|
||||
- detect_combined_evidence_corruption (Tier 1)
|
||||
- detect_round_trip_spikes (Tier 2; up_threshold=5.0, down_threshold=-0.90,
|
||||
recovery_calendar_days=10)
|
||||
|
||||
Output:
|
||||
data/processed/global_excluded_ticker_dates.parquet
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # noqa: E402
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from src.data.data_hygiene import ( # noqa: E402
|
||||
detect_combined_evidence_corruption,
|
||||
detect_frozen_runs,
|
||||
detect_round_trip_spikes,
|
||||
save_exclusion_ranges,
|
||||
)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
|
||||
datefmt="%Y-%m-%dT%H:%M:%S",
|
||||
)
|
||||
logger = logging.getLogger("build_global_exclusion_table")
|
||||
|
||||
_DAILY_PATH = Path("data/processed/global_daily_returns.parquet")
|
||||
_OUT_PATH = Path("data/processed/global_excluded_ticker_dates.parquet")
|
||||
|
||||
# The detector window covers backtest and live dates from 2000 onward.
|
||||
# Momentum signals use pre-2000 data only for the warmup period.
|
||||
_FROM_DATE = "2000-01-01"
|
||||
_TO_DATE = pd.Timestamp.today().strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logger.info("Loading %s ...", _DAILY_PATH)
|
||||
daily = pd.read_parquet(
|
||||
_DAILY_PATH,
|
||||
columns=["date", "ticker", "close", "adjusted_close", "volume", "ret_d"],
|
||||
)
|
||||
daily["date"] = pd.to_datetime(daily["date"])
|
||||
pre_window = len(daily)
|
||||
daily = daily[(daily["date"] >= _FROM_DATE) & (daily["date"] <= _TO_DATE)]
|
||||
logger.info(
|
||||
"Window %s..%s: %d rows (%d filtered out), %d tickers",
|
||||
_FROM_DATE, _TO_DATE, len(daily), pre_window - len(daily), daily["ticker"].nunique(),
|
||||
)
|
||||
|
||||
all_ranges: list[pd.DataFrame] = []
|
||||
|
||||
logger.info("Running detect_frozen_runs (min_length=5) ...")
|
||||
frozen = detect_frozen_runs(daily, min_length=5)
|
||||
all_ranges.append(frozen)
|
||||
logger.info(" -> %d frozen-run ranges", len(frozen))
|
||||
|
||||
logger.info("Running detect_combined_evidence_corruption (Tier 1) ...")
|
||||
combined = detect_combined_evidence_corruption(daily, frozen_runs=frozen)
|
||||
all_ranges.append(combined[["ticker", "start_date", "end_date", "reason"]])
|
||||
logger.info(" -> %d combined-evidence ranges", len(combined))
|
||||
|
||||
logger.info("Running detect_round_trip_spikes (Tier 2) ...")
|
||||
round_trips = detect_round_trip_spikes(
|
||||
daily, up_threshold=5.0, down_threshold=-0.90, recovery_calendar_days=10,
|
||||
)
|
||||
all_ranges.append(round_trips)
|
||||
logger.info(" -> %d round-trip-spike ranges", len(round_trips))
|
||||
|
||||
out = pd.concat(all_ranges, ignore_index=True)
|
||||
out["start_date"] = pd.to_datetime(out["start_date"])
|
||||
out["end_date"] = pd.to_datetime(out["end_date"])
|
||||
out = out.sort_values(["ticker", "start_date"]).reset_index(drop=True)
|
||||
|
||||
logger.info("=" * 72)
|
||||
logger.info("Combined exclusion table: %d ranges across %d unique tickers",
|
||||
len(out), out["ticker"].nunique())
|
||||
logger.info("By reason: %s", out["reason"].value_counts().to_dict())
|
||||
|
||||
# Join the latest universe table to summarize exclusion ranges by region.
|
||||
universe_files = sorted(Path("data/universe").glob("global_msci_world_imi_*.parquet"))
|
||||
if universe_files:
|
||||
universe = pd.read_parquet(universe_files[-1], columns=["eodhd_ticker", "region_bucket"])
|
||||
out_with_region = out.merge(
|
||||
universe, left_on="ticker", right_on="eodhd_ticker", how="left",
|
||||
)
|
||||
by_region = (
|
||||
out_with_region.groupby("region_bucket").size().sort_index().to_dict()
|
||||
)
|
||||
logger.info("Exclusion ranges by region: %s", by_region)
|
||||
|
||||
save_exclusion_ranges(out, _OUT_PATH)
|
||||
logger.info("Saved global exclusion table -> %s", _OUT_PATH)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Build data/processed/regional_benchmarks_daily.parquet.
|
||||
|
||||
For each gated region, loads the benchmark price series from the EODHD cache
|
||||
and computes daily returns. The benchmark per region is used downstream as:
|
||||
- input to Goulding turning-point weight (monthly resampled benchmark returns)
|
||||
- market series for BAB beta regression (daily benchmark returns)
|
||||
- market series for CMR residual-momentum (daily benchmark returns)
|
||||
|
||||
Output schema (long format):
|
||||
[date, region, benchmark_symbol, close, ret_d]
|
||||
|
||||
Regions and benchmarks (per cross-geography live push plan):
|
||||
US -> GSPC.INDX (S&P 500)
|
||||
EU -> SXXP.INDX (STOXX Europe 600)
|
||||
JP -> N225.INDX (Nikkei 225)
|
||||
CA -> GSPTSE.INDX (S&P/TSX Composite) -- informational only, not gated
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from src.data.eodhd_client import EODHDClient
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
|
||||
datefmt="%Y-%m-%dT%H:%M:%S",
|
||||
)
|
||||
logger = logging.getLogger("build_regional_benchmarks")
|
||||
|
||||
_REGION_BENCHMARKS = {
|
||||
"US": "GSPC.INDX",
|
||||
"EU": "SXXP.INDX",
|
||||
"JP": "N225.INDX",
|
||||
"CA": "GSPTSE.INDX",
|
||||
}
|
||||
_OUT_PATH = Path("data/processed/regional_benchmarks_daily.parquet")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = EODHDClient()
|
||||
frames: list[pd.DataFrame] = []
|
||||
for region, symbol in _REGION_BENCHMARKS.items():
|
||||
df = client.get_eod_prices(symbol)
|
||||
if df.empty:
|
||||
logger.error("No EOD data for %s — aborting", symbol)
|
||||
sys.exit(1)
|
||||
df = df.sort_values("date").reset_index(drop=True)
|
||||
df["region"] = region
|
||||
df["benchmark_symbol"] = symbol
|
||||
df["ret_d"] = df["adjusted_close"].pct_change()
|
||||
out = df[["date", "region", "benchmark_symbol", "adjusted_close", "ret_d"]].rename(
|
||||
columns={"adjusted_close": "close"}
|
||||
)
|
||||
frames.append(out)
|
||||
logger.info(
|
||||
"%s (%s): %d rows, %s -> %s",
|
||||
region, symbol, len(out), out["date"].min().date(), out["date"].max().date(),
|
||||
)
|
||||
|
||||
panel = pd.concat(frames, ignore_index=True)
|
||||
_OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = _OUT_PATH.with_suffix(".tmp")
|
||||
panel.to_parquet(tmp, index=False)
|
||||
tmp.replace(_OUT_PATH)
|
||||
logger.info("Saved %d rows -> %s", len(panel), _OUT_PATH)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Live QMJ fundamentals fetch — rebuild-pipeline step (resumable, incremental).
|
||||
|
||||
Fetches EODHD fundamentals JSON for every ticker in the live global universe
|
||||
(the scored cross-section in data/processed/global_daily_returns.parquet) that
|
||||
is NOT already cached. Becomes step ~3.5 of the signal_long_global rebuild so
|
||||
each monthly cycle only pays for newly-added names.
|
||||
|
||||
Behaviour:
|
||||
- cache-skip: a name with an existing data/raw/eodhd/fundamentals/{t}.json is skipped.
|
||||
- 4xx / not-found: an empty-dict sentinel is written so the call is never re-paid.
|
||||
- transient (429/5xx): left uncached so the next run retries it.
|
||||
|
||||
Run: python scripts/data/fetch_live_qmj_fundamentals.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # Add the repository root so Python imports `src`.
|
||||
|
||||
import pandas as pd # noqa: E402
|
||||
|
||||
from src.data.eodhd_client import EODHDClient, EODHDError # noqa: E402
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(message)s",
|
||||
stream=sys.stderr,
|
||||
)
|
||||
logger = logging.getLogger("fetch_live_qmj_fundamentals")
|
||||
|
||||
_UNIVERSE_PATH = Path("data/processed/global_daily_returns.parquet")
|
||||
_CACHE_DIR = Path("data/raw/eodhd/fundamentals")
|
||||
|
||||
|
||||
def _live_universe() -> list[str]:
|
||||
if not _UNIVERSE_PATH.is_file():
|
||||
logger.error("Missing %s — run the global rebuild pipeline first.", _UNIVERSE_PATH)
|
||||
sys.exit(2)
|
||||
tickers = pd.read_parquet(_UNIVERSE_PATH, columns=["ticker"])["ticker"].astype(str)
|
||||
return sorted(tickers.unique())
|
||||
|
||||
|
||||
def main() -> None:
|
||||
universe = _live_universe()
|
||||
_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
to_fetch = [t for t in universe if not (_CACHE_DIR / f"{t}.json").is_file()]
|
||||
n = len(to_fetch)
|
||||
logger.info(
|
||||
"Live QMJ fundamentals: %d universe tickers, %d already cached, %d to fetch (~%d credits)",
|
||||
len(universe), len(universe) - n, n, n * 10,
|
||||
)
|
||||
if n == 0:
|
||||
logger.info("Nothing to fetch — fundamentals cache is current.")
|
||||
return
|
||||
|
||||
client = EODHDClient()
|
||||
fetched = empty = errors = 0
|
||||
for i, ticker in enumerate(to_fetch, 1):
|
||||
cache_file = _CACHE_DIR / f"{ticker}.json"
|
||||
try:
|
||||
data = client.get_fundamentals(ticker, use_cache=True)
|
||||
if data:
|
||||
fetched += 1
|
||||
else:
|
||||
empty += 1
|
||||
except EODHDError as exc:
|
||||
if exc.status_code is not None and 400 <= exc.status_code < 500:
|
||||
cache_file.write_text("{}", encoding="utf-8") # Store an empty-response sentinel for an HTTP 4xx error.
|
||||
empty += 1
|
||||
else:
|
||||
errors += 1
|
||||
logger.warning("Transient error for %s: %s (will retry next run)", ticker, exc)
|
||||
|
||||
if i % 100 == 0:
|
||||
logger.info("progress %d/%d fetched=%d empty=%d err=%d", i, n, fetched, empty, errors)
|
||||
|
||||
logger.info(
|
||||
"DONE %d tickers: fetched=%d empty/sentinel=%d errors=%d",
|
||||
n, fetched, empty, errors,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Force-refresh per-exchange EODHD symbol-list cache.
|
||||
|
||||
The TickerResolver and USD-returns builder both read from
|
||||
``data/raw/eodhd/symbols/{EX}_active.json`` to map (a) BR tickers -> EODHD
|
||||
codes and (b) tickers -> trading currency. ``EODHDClient.get_exchange_symbols``
|
||||
uses ``use_cache=True`` in every production call site, which means once those
|
||||
JSONs are on disk they are NEVER refetched — a new index constituent (IPO,
|
||||
listing change) that postdates the cache silently drops out of the universe
|
||||
and/or the USD panel.
|
||||
|
||||
This script bypasses the cache and refetches every gated exchange. Cheap:
|
||||
19 exchanges × 1 API call each, ~10 s wall-clock and a trivial quota hit.
|
||||
Invoked as step 1/9 of the monthly orchestrator so the cache is always
|
||||
current at signal time.
|
||||
|
||||
Output: ``data/raw/eodhd/symbols/{EX}_active.json`` (overwritten in place).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # noqa: E402
|
||||
|
||||
from src.data import GATED_EXCHANGES
|
||||
from src.data.eodhd_client import EODHDClient, EODHDError
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
|
||||
datefmt="%Y-%m-%dT%H:%M:%S",
|
||||
)
|
||||
logger = logging.getLogger("refresh_symbol_cache")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = EODHDClient()
|
||||
total = 0
|
||||
for ex in GATED_EXCHANGES:
|
||||
try:
|
||||
df = client.get_exchange_symbols(ex, delisted=False, use_cache=False)
|
||||
except EODHDError as exc:
|
||||
logger.error("Refresh failed for %s: %s", ex, exc)
|
||||
sys.exit(1)
|
||||
n = len(df)
|
||||
total += n
|
||||
logger.info("Refreshed %s: %d symbols", ex, n)
|
||||
logger.info(
|
||||
"Refreshed %d exchanges, %d total symbol rows", len(GATED_EXCHANGES), total
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user