diff --git a/INVENTORY.md b/INVENTORY.md index 76d6202e..490c40ad 100644 --- a/INVENTORY.md +++ b/INVENTORY.md @@ -27,7 +27,7 @@ copy's drift can be checked. | `analizy-pl-data` | Programmatic access to Polish investment fund data from analizy.pl | | `atlasetf-scraper` | Scrape ETF data from atlasetf.pl (screener of ~13k funds, per-ISIN detail, prices) via its JSON API | | `gpw-benchmark-scraper` | Scrape gpwbenchmark.pl (WIBID/WIBOR reference rates, index list with ISINs, per-index OHLC history) | -| `market-datasets` | Fetch market data from Stooq, NBP, Yahoo, FRED, Tiingo, CCXT, FinancialData | +| `market-datasets` | Fetch market data from EODHD, NBP, Yahoo, FRED, Tiingo, CCXT, FinancialData (stooq removed 2026-09-30) | | `pipeline-docs` | 4-doc pattern (instruction / dataset / methodology / reference) | ### Engineering (`engineering/`, 1) diff --git a/claude/skills/quant/market-datasets/.env.example b/claude/skills/quant/market-datasets/.env.example index f4db3ad2..077df237 100644 --- a/claude/skills/quant/market-datasets/.env.example +++ b/claude/skills/quant/market-datasets/.env.example @@ -18,13 +18,6 @@ TIINGO_API_KEY= # Get your free API key at: https://fred.stlouisfed.org/docs/api/api_key.html FRED_API_KEY= -# ============================================================================= -# FIRECRAWL (Web scraping for corporate actions) -# ============================================================================= -# Used for scraping Stooq corporate actions pages -# Get your API key at: https://www.firecrawl.dev/ -FIRECRAWL_API_KEY= - # ============================================================================= # FINANCIALDATA.NET (Stocks, fundamentals, options, insider trading) # ============================================================================= @@ -46,5 +39,6 @@ FINANCIAL_DATA_API_KEY= # IEX Cloud (US equities) # IEX_API_KEY= -# EODHD (eodhd.com) — UCITS/ETF + global multi-exchange; paid ~$20/mo for full history +# EODHD (eodhd.com) — UCITS/ETF, GPW (.WAR), indices (.INDX); auto-routed first for +# Polish instruments when set. Personal-use plans only — see references/eodhd.md EODHD_API_KEY= diff --git a/claude/skills/quant/market-datasets/SKILL.md b/claude/skills/quant/market-datasets/SKILL.md index 984e59ab..1fd96e47 100644 --- a/claude/skills/quant/market-datasets/SKILL.md +++ b/claude/skills/quant/market-datasets/SKILL.md @@ -1,6 +1,6 @@ --- name: market-datasets -description: Fetch market data, fundamentals, and financial datasets from multiple sources (EODHD, Stooq, NBP, Yahoo Finance, FRED, Tiingo, CCXT, FinancialData.Net) with intelligent routing, plus long-history construction patterns for investment research. Use when users request stock prices, indices, FX rates, economic indicators, cryptocurrency data, fundamentals, options, financial statements, or need to build multi-decade return series for backtesting. +description: Fetch market data, fundamentals, and financial datasets from multiple sources (EODHD, NBP, Yahoo Finance, FRED, Tiingo, CCXT, FinancialData.Net) with intelligent routing, plus long-history construction patterns for investment research. Use when users request stock prices, indices, FX rates, economic indicators, cryptocurrency data, fundamentals, options, financial statements, or need to build multi-decade return series for backtesting. argument-hint: "[ticker] [start-date] [end-date]" allowed-tools: Bash, Read --- @@ -20,10 +20,9 @@ Unified market data fetching with intelligent source selection, plus long-histor | Source | Best For | Auth | Coverage | |--------|----------|------|----------| -| **EODHD** | UCITS/ETF + global multi-exchange; datacenter-reachable (**opt-in** — `source='eodhd'`, paid) | API key | US/EU/GPW stocks, ETFs, indices, ISIN-keyed; splits/div-adjusted | -| **Stooq** | Polish market | Free | Stocks, indices, FX, commodities | +| **EODHD** | **Polish market (auto-routed first when the key is set)**; UCITS/ETF + global multi-exchange; datacenter-reachable (paid, personal-use plans) | API key | GPW `.WAR`, WIG-family `.INDX`, US/EU stocks, ETFs, FX, ISIN-keyed; splits/div-adjusted | | **NBP** | Official PLN FX | Free | PLN exchange rates | -| **Yahoo** | Global equities (**ad-hoc primary**) | Free | Stocks, ETFs, indices worldwide | +| **Yahoo** | Global equities (**ad-hoc primary**); Polish fallback without an EODHD key (`.WA`) | Free | Stocks, ETFs, indices, FX worldwide | | **Tiingo** | Yahoo fallback | API key | US stocks/ETFs, 30+ years | | **CCXT/Binance** | Crypto OHLCV | Free | All crypto pairs, multiple timeframes | | **CoinGecko** | Crypto price/market-cap by coin id | Free (opt-in) | Daily price, mcap, volume | @@ -36,10 +35,11 @@ Unified market data fetching with intelligent source selection, plus long-histor | Source | Price Type | Use For | |--------|------------|---------| -| Stooq | Adjusted only | Total return calculations | -| Yahoo | Both (close + adj_close) | P&L (close), returns (adj_close) | +| Yahoo | Both (`Close` raw + `Adj_Close`) | P&L (`Close`), returns (`Adj_Close`) | +| EODHD | Both (`Close` raw + `Adj_Close`) | Same — but `Adj_Close` is recomputed on every dividend | -**Key insight**: Stooq `Close` = Yahoo `adj_close` (validated 95.8% match rate). +**Key trap**: an adjusted series is rewritten backwards at each dividend, so an +incrementally APPENDED adjusted history loses dividends — chain returns instead. See [references/dividend_treatment.md](references/dividend_treatment.md). ## Core Workflow @@ -49,9 +49,10 @@ See [references/dividend_treatment.md](references/dividend_treatment.md). | Need | Approach | |------|----------| | Current/recent prices (ad-hoc) | Auto-routing via unified fetcher — **Yahoo primary** | -| ETF / UCITS / GPW-listed prices | **EODHD, opt-in** — force `source='eodhd'` (paid; confirm cost) | -| Datacenter/VPS where Stooq/Yahoo blocked | EODHD (REST, no geo-block) — force `source='eodhd'` | -| Official PLN FX rates | Force NBP source | +| Polish stocks / WIG indices / `.WA` tickers | Auto-routed: **EODHD** (`.WAR`, `.INDX`) when `EODHD_API_KEY` is set. Without the key: stocks/ETFs fall back to Yahoo (`.WA`); a WSE **index raises** — Yahoo has no history for them (keyless alternative: `gpw-benchmark-scraper`) | +| ETF / UCITS prices | **EODHD, opt-in** — force `source='eodhd'` (paid; confirm cost) | +| Datacenter/VPS where Yahoo is blocked | EODHD (REST, no geo-block) — force `source='eodhd'` | +| PLN FX rates | Auto-routed: NBP first, then Yahoo (`USDPLN=X`) | | Multi-decade backtest series | Long-history construction (see below) | | ISIN-based lookups | TickerRegistry + Yahoo Direct API | | Crypto data | CCXT/Binance routing | @@ -61,10 +62,10 @@ See [references/dividend_treatment.md](references/dividend_treatment.md). **CLI** (all scripts are self-contained with PEP 723 inline dependencies): ```bash uv run scripts/fetch_unified.py PKO 2024-01-01 2024-12-31 -uv run scripts/fetch_stooq.py WIG20 2024-01-01 +uv run scripts/fetch_eodhd.py WIG20.INDX 2024-01-01 # Polish index (EODHD) uv run scripts/fetch_nbp.py USD 2024-01-01 2024-12-31 uv run scripts/fetch_yahoo.py AAPL 2024-01-01 -uv run scripts/fetch_eodhd.py SPY 2024-01-01 # ETF/UCITS/GPW (EODHD) +uv run scripts/fetch_eodhd.py SPY 2024-01-01 # ETF/UCITS (EODHD) uv run scripts/fetch_financialdata.py AAPL 2024-01-01 2024-12-31 ``` @@ -73,7 +74,7 @@ uv run scripts/fetch_financialdata.py AAPL 2024-01-01 2024-12-31 import sys; sys.path.append('market-datasets/scripts') from fetch_unified import fetch_market_data -df = fetch_market_data('pko', start_date='2024-01-01') # Polish → Stooq +df = fetch_market_data('pko', start_date='2024-01-01') # Polish → EODHD PKO.WAR, else Yahoo PKO.WA df = fetch_market_data('AAPL', start_date='2024-01-01') # US → Yahoo df = fetch_market_data('USD', source='nbp', table='A') # FX → NBP df = fetch_market_data('BTC/USDT', start_date='2024-01-01') # Crypto → CCXT @@ -89,7 +90,7 @@ All fetchers return pandas DataFrames with standardized columns: | `Date` | datetime | | `Open`, `High`, `Low`, `Close` | OHLC prices | | `Volume` | Trading volume (if available) | -| `Adj_Close` | Adjusted close (Yahoo only) | +| `Adj_Close` | Adjusted close (Yahoo, EODHD) | Economic data (FRED, NBP): `Date`, `Value`, `Currency`/`Series_ID`. @@ -102,7 +103,7 @@ df = fetch_market_data('pko', start_date='2024-01-01', end_date='2024-12-31') # 2. Multi-source comparison from fetch_unified import UnifiedMarketDataFetcher fetcher = UnifiedMarketDataFetcher() -comparison = fetcher.compare_sources('pko', ['stooq', 'yahoo'], start_date='2024-01-01') +comparison = fetcher.compare_sources('PKO.WA', ['eodhd', 'yahoo'], start_date='2024-01-01') # 3. ISIN batch fetch from fetch_yahoo_direct import fetch_by_isin @@ -132,7 +133,7 @@ Academic data (synthetic, 1928+) ← BACKFILL: extends history | **Equity** | VFINX (yfinance) | Shiller S&P 500 price+dividends | ~1976 | | **FI_AGG** (core bonds) | VBMFX (yfinance) | Shiller 10Y yield → synthetic bond return | ~1987 | | **FI_SHORT** (short duration) | 50% SHV + 50% VFISX | 50% FRED TB3MS + 50% synthetic dur-2Y | ~1991 | -| **Commodities** (gold) | Stooq XAUUSD | Same source (1968+) | N/A | +| **Commodities** (gold) | EODHD `XAUUSD.FOREX` | From 1990-01-02 (probed 2026-09-30); `GC=F` is not on EODHD | N/A | ### Key Construction Patterns @@ -163,8 +164,8 @@ Reference implementation: `research/strategic-asset-allocation/build_asset_data_ | Source | Example | Format | |--------|---------|--------| -| Stooq | `pko`, `wig20`, `usdpln` | lowercase | -| Yahoo | `PKO.WA`, `^GSPC`, `AAPL` | uppercase, suffix/caret | +| EODHD | `PKO.WAR`, `WIG20.INDX`, `USDPLN.FOREX`, `SPY.US` | `SYMBOL.EXCHANGE` | +| Yahoo | `PKO.WA`, `^GSPC`, `AAPL`, `USDPLN=X` | uppercase, suffix/caret | | NBP | `USD`, `EUR` | 3-letter ISO | | FRED | `GDP`, `UNRATE`, `TB3MS` | exact series ID | | CCXT | `BTC/USDT`, `ETHUSDT` | pair format | @@ -191,6 +192,7 @@ fetcher = UnifiedMarketDataFetcher(cache_hours=48) # Custom TTL | FRED | `export FRED_API_KEY="..."` or `config/fred_api_key.txt` | For macro data | | Tiingo | `export TIINGO_API_KEY="..."` | For Yahoo fallback | | FinancialData.Net | `export FINANCIAL_DATA_API_KEY="..."` | For fundamentals, options, insider data | +| EODHD | `export EODHD_API_KEY="..."` | For Polish routing (else Yahoo), UCITS/ETF | See [references/api_setup.md](references/api_setup.md). @@ -213,6 +215,14 @@ except Exception as e: 4. **Batch requests** — loop with fetcher instance, don't re-instantiate 5. **Respect rate limits** — 1-2s delay between requests (built in) +## Removed Sources + +- **Stooq** — removed 2026-09-30. It blocks datacenter IPs (Hetzner, since + 2026-04-21) and serves a JavaScript browser challenge ("This site requires + JavaScript to verify your browser") to any non-browser client, so no agent or + LLM session can fetch from it. `source='stooq'` raises `ValueError` saying so; + Polish instruments now route to EODHD / Yahoo, PLN FX to NBP / Yahoo. + ## Reference Documentation Load these when needed for detailed information: diff --git a/claude/skills/quant/market-datasets/references/api_setup.md b/claude/skills/quant/market-datasets/references/api_setup.md index d2fc2103..aca70e6a 100644 --- a/claude/skills/quant/market-datasets/references/api_setup.md +++ b/claude/skills/quant/market-datasets/references/api_setup.md @@ -5,7 +5,6 @@ Configuration instructions for data sources requiring authentication or setup. ## Overview Most data sources work out-of-the-box without configuration: -- **Stooq**: No setup required - **NBP API**: No setup required - **Yahoo Finance**: No setup required (via yfinance) - **CCXT/Crypto**: No setup required (via ccxt package) @@ -484,7 +483,7 @@ If integrating into an existing project (like the performance attribution system By default, data is cached in: ``` data/cache/market_data/ -├── stooq/ +├── eodhd/ ├── nbp/ ├── yahoo/ ├── fred/ @@ -535,7 +534,7 @@ Manually clear cache: rm -rf data/cache/market_data/* # Clear specific source -rm -rf data/cache/market_data/stooq/* +rm -rf data/cache/market_data/yahoo/* ``` --- @@ -690,7 +689,7 @@ def test_all_sources(): # Test each source tests = [ - ('Stooq (Polish stock)', 'pko', 'stooq'), + ('EODHD (Polish stock)', 'PKO.WAR', 'eodhd'), ('NBP (PLN rate)', 'USD', 'nbp'), ('Yahoo (US stock)', 'AAPL', 'yahoo'), ('Tiingo (US stock)', 'MSFT', 'tiingo'), @@ -732,7 +731,6 @@ python test_config.py - **CCXT**: https://github.com/ccxt/ccxt/wiki - **yfinance**: https://github.com/ranaroussi/yfinance - **pandas-datareader**: https://pandas-datareader.readthedocs.io/ -- **Stooq**: https://stooq.pl/ - **NBP API**: http://api.nbp.pl/ ### Support @@ -744,33 +742,34 @@ For issues with: - **CCXT**: https://github.com/ccxt/ccxt/issues - **yfinance**: https://github.com/ranaroussi/yfinance/issues - **pandas-datareader**: https://github.com/pydata/pandas-datareader/issues - -## EODHD API Setup - -EODHD (eodhd.com) is the primary UCITS/ETF + global multi-exchange source — -reachable from datacenters/VPS where Stooq is geo-blocked and Yahoo is -rate-limited. - -### Step 1: Get an API key -Register at https://eodhd.com/. Free tier (~1yr history, 20 calls/day) is for -validation only; the paid EOD Historical Data plan (~$20/mo) gives full history -and 100k calls/day. - -### Step 2: Configure - -```bash -# Option 1: environment variable (recommended) -export EODHD_API_KEY="your_key" -echo 'export EODHD_API_KEY="your_key"' >> ~/.bashrc - -# Option 2: .env file at the skill/scripts root -echo 'EODHD_API_KEY=your_key' >> .env -``` - -### Step 3: Verify - -```bash -uv run scripts/fetch_eodhd.py # self-tests (US/.LSE/.WAR/.INDX) -# check account tier/limits: -curl -s "https://eodhd.com/api/user?api_token=$EODHD_API_KEY&fmt=json" -``` + +## EODHD API Setup + +EODHD (eodhd.com) is the primary UCITS/ETF + global multi-exchange source — +reachable from datacenters/VPS where Yahoo is rate-limited — and the auto-routed +first source for Polish instruments (GPW `.WAR`, WIG-family `.INDX`) once the key +is set. All eodhd.com/pricing plans are personal-use only; see eodhd.md § Licensing. + +### Step 1: Get an API key +Register at https://eodhd.com/. Free tier (~1yr history, 20 calls/day) is for +validation only; the paid EOD Historical Data plan (~$20/mo) gives full history +and 100k calls/day. + +### Step 2: Configure + +```bash +# Option 1: environment variable (recommended) +export EODHD_API_KEY="your_key" +echo 'export EODHD_API_KEY="your_key"' >> ~/.bashrc + +# Option 2: .env file at the skill/scripts root +echo 'EODHD_API_KEY=your_key' >> .env +``` + +### Step 3: Verify + +```bash +uv run scripts/fetch_eodhd.py # self-tests (US/.LSE/.WAR/.INDX) +# check account tier/limits: +curl -s "https://eodhd.com/api/user?api_token=$EODHD_API_KEY&fmt=json" +``` diff --git a/claude/skills/quant/market-datasets/references/dividend_treatment.md b/claude/skills/quant/market-datasets/references/dividend_treatment.md index 6731890e..ed4b051d 100644 --- a/claude/skills/quant/market-datasets/references/dividend_treatment.md +++ b/claude/skills/quant/market-datasets/references/dividend_treatment.md @@ -1,242 +1,134 @@ # Dividend Treatment in Market Data Sources -How different data sources handle dividend adjustments in price data. +How the price sources this skill fetches from handle dividends, and the one +trap that loses them silently. ## Quick Reference -| Source | Price Type | Dividend Adjusted | Corporate Actions Available | -|--------|------------|-------------------|----------------------------| -| **Stooq** | Adjusted only | Yes (automatic) | No API | -| **Yahoo Finance** | Both | Yes (`adj_close`) | Yes (dividends, splits) | +| Source | Raw close | Adjusted close | Corporate actions | +|--------|-----------|----------------|-------------------| +| **Yahoo Finance** | `Close` | `Adj_Close` | Yes — dividends, splits (`fetch_yahoo_direct.py`) | +| **EODHD** | `Close` | `Adj_Close` (from `adjusted_close`) | Separate endpoints (`/api/div/`, `/api/splits/`) — not wrapped by this skill | | **NBP** | N/A | N/A | N/A (FX rates only) | | **FRED** | N/A | N/A | N/A (economic data) | ---- - -## Stooq (stooq.pl) - -### Price Type: Dividend-Adjusted Only - -Stooq provides **dividend-adjusted prices**. All historical OHLC values are retroactively adjusted when dividends are paid. - -### How It Works - -When a company pays a dividend: -1. Historical prices are adjusted DOWN by a factor -2. Adjustment factor = `(price - dividend) / price` -3. All historical data is recalculated -4. Current/recent prices remain at actual trading values - -### Example: XTB Dividend (5.45 PLN, ex-div 2025-06-13) - -``` -Date Stooq Close Notes -2025-06-10 75.01 Adjusted (was ~80.58 raw) -2025-06-11 74.30 Adjusted (was ~79.82 raw) -2025-06-12 73.20 Last cum-div day, adjusted (was 78.64 raw) -2025-06-13 74.12 Ex-div day, NOT adjusted (actual trading price) -2025-06-16 73.76 NOT adjusted (current price) -``` - -### Implications - -- **Returns calculated from Stooq prices are total returns** (include dividend reinvestment effect) -- **Cannot recover raw prices** from Stooq alone -- **Multiple dividends compound** - older data has larger adjustments -- **Good for**: Performance attribution, return calculations, backtesting -- **Bad for**: Calculating actual P&L on specific trades - -### Validation Results (Jan 2025) +Both price sources give you **both** series. Pick by purpose: -Stooq prices validated against Yahoo Finance `adj_close`: -- 48 tickers tested -- 46/48 (95.8%) match within 1% tolerance -- 2 outliers: DOM (2.22% diff), ASB (1.74% diff) +| Need | Column | +|------|--------| +| Actual trading price, P&L on a trade | `Close` (raw) + dividends received, separately | +| Returns, performance attribution, backtests | `Adj_Close` — or raw `Close` chained with dividends yourself | --- -## Yahoo Finance - -### Price Types: Both Raw and Adjusted - -Yahoo Finance provides **both** price types: - -| Column | Description | Use Case | -|--------|-------------|----------| -| `close` | Raw/unadjusted price | Actual trading price, P&L calculation | -| `adj_close` | Dividend-adjusted price | Return calculation, comparison with Stooq | +## How an adjusted series is built -### Corporate Actions Data +For a dividend `D` with ex-date `t_ex`, every price **before** `t_ex` is +multiplied by -Yahoo provides explicit dividend and split data: - -```python -import yfinance as yf - -ticker = yf.Ticker('XTB.WA') - -# Get dividends -dividends = ticker.dividends -# Returns: Date, Dividend amount - -# Get splits -splits = ticker.splits -# Returns: Date, Split ratio - -# Get all actions -actions = ticker.actions -# Returns: Date, Dividends, Stock Splits ``` - -### Direct API (fetch_yahoo_direct.py) - -The skill's direct Yahoo fetcher includes: -- Prices with both `close` and `adj_close` -- Dividends via `events=div` -- Splits via `events=splits` -- Combined via `events=div,splits` - -### Adjustment Formula - -For a dividend of `D` on ex-div date: -``` -adjustment_factor = (close_price - D) / close_price -adj_close = close * adjustment_factor (for all dates before ex-div) +factor = (close[t_ex - 1] - D) / close[t_ex - 1] ``` -### Example: XTB Dividend (5.45 PLN, ex-div 2025-06-13) +Prices on and after the ex-date are untouched. Multiple dividends compound, so +older history carries larger cumulative adjustments. Returns computed from the +adjusted series are total returns (dividends reinvested on the ex-date). -``` -Date YF Close YF Adj_Close Difference -2025-06-10 80.58 75.00 5.58 (adj for dividend) -2025-06-11 79.82 74.29 5.53 (adj for dividend) -2025-06-12 78.64 73.19 5.45 (= dividend amount) -2025-06-13 74.12 74.12 0.00 (ex-div, no adjustment) -``` - -### YF adj_close vs Stooq Comparison +### Example: XTB dividend (5.45 PLN, ex-div 2025-06-13), Yahoo ``` -Date YF adj_close Stooq Close Diff -2025-06-10 75.00 75.01 0.01 -2025-06-11 74.29 74.30 0.01 -2025-06-12 73.19 73.20 0.01 -2025-06-13 74.12 74.12 0.00 +Date Close Adj_Close Difference +2025-06-10 80.58 75.00 5.58 (adjusted for the dividend) +2025-06-11 79.82 74.29 5.53 +2025-06-12 78.64 73.19 5.45 (= dividend amount, last cum-div day) +2025-06-13 74.12 74.12 0.00 (ex-div, no adjustment) ``` -**Conclusion**: YF `adj_close` matches Stooq prices within rounding tolerance. - --- -## Key Dates Terminology +## The trap: adjusted levels are rewritten backwards -### Last Cum-Dividend Date (Ostatnie notowanie z prawem do dywidendy) -- Last trading day where buying shares entitles you to the dividend -- Example: 2025-06-12 for XTB +An adjusted series is **not append-only**. On every new dividend the provider +recomputes the whole history before the ex-date. EODHD recomputes +`adjusted_close` on every dividend; Yahoo's `Adj_Close` behaves the same way. -### Ex-Dividend Date (Ex-div) -- First trading day WITHOUT dividend rights -- Usually = last_cum_div_date + 1 business day -- Example: 2025-06-13 for XTB -- Yahoo Finance reports dividend on this date +So if you store adjusted **levels** and append each day's new rows to what you +stored earlier, the old rows keep the pre-dividend scale while the new rows are +on the post-dividend scale — the ratio across the seam equals the raw price +ratio, and **the dividend disappears from your return series**. -### Payment Date (Dzień wypłaty) -- When dividend is actually paid to shareholders -- Example: 2025-06-25 for XTB +Two correct ways to keep a history incrementally: -### Record Date -- Date when company determines shareholders entitled to dividend -- Usually = ex_div_date + settlement period +1. **Chain returns, not levels.** Store daily returns computed within one fetch + (`adj.pct_change()`), append new returns, and rebuild the level from the + chained returns when needed. A return between two rows fetched together is + consistent even though both levels later get rescaled. +2. **Store raw `Close` + dividends**, and compute total return yourself: + `r_t = (close_t + D_t) / close_{t-1} - 1`, with `D_t` on the ex-date. ---- - -## Practical Guidance +Or re-fetch the full adjusted history every time and overwrite — never splice +an old adjusted fetch onto a new one. -### For Performance Attribution +--- -Use **Stooq** or **Yahoo adj_close**: -```python -# Both give dividend-adjusted returns -stooq_return = (stooq_close_t1 / stooq_close_t0) - 1 -yf_return = (yf_adj_close_t1 / yf_adj_close_t0) - 1 -# These should match -``` +## Yahoo Finance -### For P&L Calculation +`fetch_yahoo_direct.py` returns prices with both `close` and `adj_close`, plus +dividends (`events=div`), splits (`events=splits`) or both. -Use **Yahoo close** (raw prices): ```python -# Actual P&L on a position -pnl = (yf_close_sell - yf_close_buy) * shares -# Then add dividend income separately -total_return = pnl + dividends_received -``` - -### For Cross-Source Validation +import yfinance as yf -Compare Yahoo `adj_close` with Stooq: -```python -# Should match within ~1% -diff_pct = abs(yf_adj_close - stooq_close) / stooq_close * 100 -assert diff_pct < 1.0, f"Data mismatch: {diff_pct:.2f}%" +t = yf.Ticker('XTB.WA') +t.dividends # Date, amount +t.splits # Date, ratio +t.actions # Date, Dividends, Stock Splits ``` -### Handling Multiple Dividends - -Tickers with multiple dividends in a period will have larger cumulative adjustments: +## EODHD -``` -Ticker Single Div Adjustment Notes -XTB 5.45 5.45 Single dividend -TXT 1.66 6.66 ~4 dividends accumulated -BHW 10.29 13.91 Multiple dividends -``` +`fetch_eodhd.py` maps `close` → `Close` and `adjusted_close` → `Adj_Close`. +Polish listings are `.WAR` (e.g. `XTB.WAR`). Dividend amounts come from a +separate EODHD endpoint the skill does not wrap; check your plan before relying +on it. Coverage and plan limits: [eodhd.md](eodhd.md). --- -## Validation Script +## Cross-source validation -Use `scripts/claude/validate_yfinance_all.py` to validate data: +Yahoo `Adj_Close` and EODHD `Adj_Close` for the same listing should agree up to +rounding and ex-date convention. Compare **returns** over a window both fetched +at the same time, not stored levels (see the trap above): -```bash -python scripts/claude/validate_yfinance_all.py +```python +r_y = yahoo['Adj_Close'].pct_change() +r_e = eodhd['Adj_Close'].pct_change() +gap = (r_y - r_e).abs() +assert gap.max() < 0.005, f"return mismatch up to {gap.max():.4f}" ``` -Output includes: -- Per-ticker comparison of YF adj_close vs Stooq -- Mean and max differences -- Identification of problematic tickers +A persistent gap usually means a different ex-date convention or a missed +corporate action on one side. --- -## Data Quality Notes - -### Known Issues - -1. **DOM**: ~2.2% avg difference between YF and Stooq -2. **ASB**: ~1.7% avg difference between YF and Stooq - -These may be due to: -- Different ex-div date handling -- Corporate action timing differences -- Data source discrepancies - -### Recommendations +## Key dates terminology -1. **Primary source**: Stooq for Polish stocks (consistent dividend adjustment) -2. **Validation**: Cross-check with Yahoo Finance adj_close -3. **Raw prices**: Use Yahoo Finance close when needed -4. **Dividends data**: Use Yahoo Finance or BiznesRadar +- **Last cum-dividend date** (ostatnie notowanie z prawem do dywidendy) — last + trading day a buyer is entitled to the dividend (XTB: 2025-06-12). +- **Ex-dividend date** — first trading day without the right, usually the next + business day (XTB: 2025-06-13). Yahoo reports the dividend on this date. +- **Record date** — when the company fixes the entitled shareholders. +- **Payment date** (dzień wypłaty) — when cash is paid (XTB: 2025-06-25). --- ## Summary -| Need | Recommended Source | Column/Field | -|------|-------------------|--------------| -| Dividend-adjusted prices | Stooq | Close (only option) | -| Dividend-adjusted prices | Yahoo Finance | adj_close | -| Raw/unadjusted prices | Yahoo Finance | close | -| Dividend amounts | Yahoo Finance | dividends | -| Total return calculation | Either Stooq or YF adj_close | - | -| Actual P&L calculation | Yahoo Finance | close + dividends | +| Need | Source | Column / field | +|------|--------|----------------| +| Dividend-adjusted prices | Yahoo or EODHD | `Adj_Close` (re-fetch in full, never splice levels) | +| Raw prices | Yahoo or EODHD | `Close` | +| Dividend amounts | Yahoo (`fetch_yahoo_direct.py`) | dividends | +| Incrementally maintained total return | Either | chained returns, or raw `Close` + dividends | +| Actual P&L | Either | `Close` + dividends received | diff --git a/claude/skills/quant/market-datasets/references/eodhd.md b/claude/skills/quant/market-datasets/references/eodhd.md index 31941601..a32972b4 100644 --- a/claude/skills/quant/market-datasets/references/eodhd.md +++ b/claude/skills/quant/market-datasets/references/eodhd.md @@ -87,3 +87,39 @@ When building a `config_ticker → eodhd_symbol` map, classify each row and carr | `NOT_FOUND` | ISIN absent from EODHD | — | **yes** | On the 406-ETP master this yields **348 auto-usable**, 58 `needs_review`. + +## Coverage verified 2026-09-30 (Historian/EOD plan, key-probed) + +Probed with a live key on 2026-09-30. A snapshot — re-probe before relying on +an entry that matters. + +**200 OK on this plan** + +- **Polish indices**: `WIG.INDX` (from 1991-04-16), `WIG20.INDX` (from 1994), + `MWIG40.INDX` (from 2011); `SWIG80` is listed. +- **GPW Beta ETFs** as `.WAR`: `ETFBW20TR`, `ETFBTBSP`, `ETFBM40TR`, `ETFBCASH`, + each since listing. +- **US ETFs**, including the mutual funds `VEIEX`, `VBMFX`, `VWEHX`, `PREMX` + with history from the 1990s. +- **Other**: `VIX.INDX`, `BCOM.INDX`, `BTC-USD.CC`, + `EURPLN.FOREX` / `USDPLN.FOREX` / `GBPPLN.FOREX` / `JPYPLN.FOREX`, + `XAUUSD.FOREX` (from 1990-01-02). +- **Not found**: `GC=F` (use `XAUUSD.FOREX`), `WIG20TR.INDX`, the TBSP index. + +`WIG.INDX` matched stooq's historic WIG_TR series exactly (4,302 days, ratio +1.0000) — the replacement for that series when stooq was removed. + +**403 on this plan** + +- **GBOND** (government bond yields): `PL10Y.GBOND` IS listed in the GBOND + symbol list, but data needs the Fundamentals / All-in-One plan. +- **MONEY** (money-market rates): no WIBOR on any plan, per EODHD's docs. +- **Fundamentals**: and even with access, ETF fundamentals give only the + current forward P/E ("Price/Prospective Earnings") — no history. +- **macro-indicator** (World Bank, annual). + +**Licensing** + +Every plan on eodhd.com/pricing is **personal use only**. A brokerage or other +professional user needs a commercial plan: *Internal* (€399/mo) forbids +displaying the data outside the company; a *Custom* quote allows it. diff --git a/claude/skills/quant/market-datasets/references/instrument_registry_schema.yaml b/claude/skills/quant/market-datasets/references/instrument_registry_schema.yaml index 9c5cc2fd..151eb31b 100644 --- a/claude/skills/quant/market-datasets/references/instrument_registry_schema.yaml +++ b/claude/skills/quant/market-datasets/references/instrument_registry_schema.yaml @@ -121,7 +121,7 @@ columns: - yahoo_finance - binance - fred - - stooq + - eodhd - nbp - tiingo - financialdata_net @@ -214,7 +214,10 @@ columns: type: string required: false nullable: true - description: Stooq ticker. + description: >- + Legacy column, no fetcher reads it — stooq was removed as a source on + 2026-09-30 (datacenter IP block + JavaScript browser challenge). Kept so + existing registries keep their schema; do not populate for new rows. ticker_binance: type: string diff --git a/claude/skills/quant/market-datasets/references/long_history_construction.md b/claude/skills/quant/market-datasets/references/long_history_construction.md index 6cbffc3c..359772e8 100644 --- a/claude/skills/quant/market-datasets/references/long_history_construction.md +++ b/claude/skills/quant/market-datasets/references/long_history_construction.md @@ -103,25 +103,24 @@ def fetch_fred_tbill() -> pd.Series: return monthly_return.resample("ME").last().dropna() ``` -### Stooq (Gold) +### EODHD (Gold) -**URL**: `stooq.pl/q/d/l/` -**Coverage**: XAUUSD from 1968+, monthly -**Access**: Free CSV download +**Symbol**: `XAUUSD.FOREX` (spot gold in USD; `GC=F` is not on EODHD) +**Coverage**: 200 OK on the Historian/EOD plan (probed 2026-09-30); the start +date was not recorded — probe it before relying on pre-2000 history +**Access**: `EODHD_API_KEY` (see [eodhd.md](eodhd.md)) ```python -def fetch_gold_stooq() -> pd.Series: - url = "https://stooq.pl/q/d/l/?s=xauusd&d1=19680101&d2=20251231&i=m" - df = pd.read_csv(url) - df.columns = ["Date", "Open", "High", "Low", "Close"] - df["Date"] = pd.to_datetime(df["Date"]) - df = df.set_index("Date").sort_index() - gold_return = df["Close"].pct_change().dropna() - gold_return.index = gold_return.index + pd.offsets.MonthEnd(0) - return gold_return +from fetch_eodhd import fetch_eodhd + +def fetch_gold_eodhd() -> pd.Series: + df = fetch_eodhd("XAUUSD.FOREX", start_date="1968-01-01") + close = df.set_index("Date")["Close"].sort_index() + return close.resample("ME").last().pct_change().dropna() ``` -**Why Stooq for gold**: More reliable long history than Yahoo for commodities. Goes back to 1968 (end of gold standard era). +If the series starts later than you need, backfill with Damodaran's annual +gold return (loses monthly granularity). ## Construction Patterns @@ -254,9 +253,9 @@ Result: Monthly TR, 1934-2025 ### Commodities (Gold) ``` -Primary: Stooq XAUUSD monthly (1968+) +Primary: EODHD XAUUSD.FOREX, resampled monthly (start date: probe) Backfill: N/A (or Damodaran annual gold, but loses monthly granularity) -Result: Monthly price return, 1968-2025 +Result: Monthly price return from the EODHD start (Damodaran annual before it) Note: Price return only — gold has no yield ``` diff --git a/claude/skills/quant/market-datasets/references/migration.md b/claude/skills/quant/market-datasets/references/migration.md index ac1fb331..84d584fe 100644 --- a/claude/skills/quant/market-datasets/references/migration.md +++ b/claude/skills/quant/market-datasets/references/migration.md @@ -8,8 +8,8 @@ After prototyping with this skill, migrate fetchers to your production project. # List available sources uv run scripts/migrate_to_project.py --list -# Migrate Stooq fetcher to your project -uv run scripts/migrate_to_project.py stooq --target src/data_sources/ +# Migrate the EODHD fetcher to your project +uv run scripts/migrate_to_project.py eodhd --target src/data_sources/ # Migrate with utilities and .env template uv run scripts/migrate_to_project.py yahoo --target src/market_data/ --include-utils --include-env @@ -22,7 +22,7 @@ uv run scripts/migrate_to_project.py all --target src/fetchers/ --include-utils ``` src/data_sources/ # Your target directory -├── fetch_stooq.py # Self-contained with PEP 723 dependencies +├── fetch_eodhd.py # Self-contained with PEP 723 dependencies ├── utils.py # Shared utilities (if --include-utils) └── .env.example # API key template (if --include-env) ``` @@ -31,12 +31,12 @@ src/data_sources/ # Your target directory The migrated scripts work standalone: ```bash -uv run src/data_sources/fetch_stooq.py PKO 2024-01-01 2024-12-31 +uv run src/data_sources/fetch_eodhd.py PKO.WAR 2024-01-01 2024-12-31 ``` Or import in your code: ```python sys.path.insert(0, 'src/data_sources') -from fetch_stooq import fetch_stooq -df = fetch_stooq('pko', '2024-01-01') +from fetch_eodhd import fetch_eodhd +df = fetch_eodhd('PKO.WAR', '2024-01-01') ``` diff --git a/claude/skills/quant/market-datasets/references/security_master.md b/claude/skills/quant/market-datasets/references/security_master.md index 775f8b1b..39c31b87 100644 --- a/claude/skills/quant/market-datasets/references/security_master.md +++ b/claude/skills/quant/market-datasets/references/security_master.md @@ -11,7 +11,7 @@ documents the current CSV-backed skill registry and usage patterns. The security master is a single CSV file that serves as the source of truth for instrument identification and cross-source ticker mappings. It enables: - Unified lookup by any identifier (uid, ISIN, ticker) -- Cross-source ticker conversion (Yahoo, Stooq, Bloomberg, FRED) +- Cross-source ticker conversion (Yahoo, Bloomberg, FRED; EODHD symbols derive from Yahoo) - Auto-discovery of Yahoo tickers from ISINs **Location**: `.claude/skills/market-datasets/data/security_master.csv` @@ -28,7 +28,7 @@ The security master is a single CSV file that serves as the source of truth for | `exchange` | string | No | Primary exchange | `WSE` | | `ticker_bloomberg` | string | No | Bloomberg ticker | `XTB PW Equity` | | `ticker_yahoo` | string | No | Yahoo Finance ticker | `XTB.WA` | -| `ticker_stooq` | string | No | Stooq ticker (lowercase) | `xtb` | +| `ticker_stooq` | string | No | **Legacy column, no fetcher reads it** — stooq was removed 2026-09-30; kept for schema readers, round-tripped unchanged | `xtb` | | `ticker_fred` | string | No | FRED series ID | - | | `sector` | string | No | Sector classification | `Technology` | | `currency` | string | No | Trading currency | `PLN` | @@ -94,14 +94,12 @@ registry = TickerRegistry() # Lookup by any identifier security = registry.get_security('PLXTRDM00011') # By ISIN security = registry.get_security('XTB.WA') # By Yahoo ticker -security = registry.get_security('xtb') # By Stooq ticker security = registry.get_security('idx_WIG20') # By uid # Access properties print(security.name) # 'XTB' print(security.isin) # 'PLXTRDM00011' print(security.get_ticker('yahoo')) # 'XTB.WA' -print(security.get_ticker('stooq')) # 'xtb' ``` ### Ticker Conversion @@ -113,13 +111,11 @@ registry = TickerRegistry() # Convert between formats yahoo_ticker = registry.convert_ticker('PLXTRDM00011', to_source='yahoo') # 'XTB.WA' -stooq_ticker = registry.convert_ticker('XTB.WA', to_source='stooq') # 'xtb' # Convenience functions (use default registry) -from ticker_registry import isin_to_yahoo, isin_to_stooq, ticker_to_isin +from ticker_registry import isin_to_yahoo, ticker_to_isin yahoo = isin_to_yahoo('PLXTRDM00011') # 'XTB.WA' -stooq = isin_to_stooq('PLXTRDM00011') # 'xtb' isin = ticker_to_isin('XTB.WA') # 'PLXTRDM00011' ``` @@ -163,7 +159,7 @@ security = Security( instrument_type='equity', country='GB', exchange='LSE', - tickers={'yahoo': 'BA.L', 'stooq': 'ba.uk'}, + tickers={'yahoo': 'BA.L'}, mapping_source='manual', last_updated=datetime.now() ) @@ -192,7 +188,7 @@ df = registry.to_dataframe() | Source | Format | Example | |--------|--------|---------| | Yahoo Finance | Uppercase + exchange suffix | `XTB.WA`, `AAPL`, `^GSPC` | -| Stooq | Lowercase, no suffix | `xtb`, `pko`, `wig20` | +| EODHD | Derived from Yahoo by `eodhd_symbol` | `XTB.WAR`, `WIG20.INDX` | | Bloomberg | Uppercase + type suffix | `XTB PW Equity`, `MWIG40 Index` | | FRED | Series ID | `GDP`, `UNRATE` | diff --git a/claude/skills/quant/market-datasets/references/sources_overview.md b/claude/skills/quant/market-datasets/references/sources_overview.md index a463ddb0..2f511ea7 100644 --- a/claude/skills/quant/market-datasets/references/sources_overview.md +++ b/claude/skills/quant/market-datasets/references/sources_overview.md @@ -6,8 +6,7 @@ Comprehensive comparison of all supported data sources for the market-datasets s | Source | Best For | Coverage | Auth Required | Rate Limits | Cost | |--------|----------|----------|---------------|-------------|------| -| **EODHD** | UCITS/ETF + global multi-exchange, datacenter-reachable | US/EU/GPW stocks, ETFs, indices; ISIN-keyed; splits/div-adjusted | Yes (API key) | Free: 20/day, ~1yr history. Paid: 100k/day, full history | Free/Paid (~$20/mo) | -| **Stooq** | Polish stocks & indices | Polish market, some international | No | Informal (~1-2s delay) | Free | +| **EODHD** | Polish stocks & indices (auto-routed first when keyed); UCITS/ETF + global multi-exchange, datacenter-reachable | GPW `.WAR`, WIG-family `.INDX`, US/EU stocks, ETFs, FX; ISIN-keyed; splits/div-adjusted | Yes (API key) | Free: 20/day, ~1yr history. Paid: 100k/day, full history | Free/Paid (~$20/mo), personal-use plans | | **NBP API** | PLN exchange rates | Official PLN rates vs major currencies | No | None documented | Free | | **Yahoo Finance** | US stocks & global equities | Global stocks, ETFs, indices | No | Informal (~1s delay) | Free | | **Tiingo** | US stocks fallback | 86,000+ securities, 30+ years | Yes (API key) | 50/hr, 1000/day | Free | @@ -21,7 +20,6 @@ Comprehensive comparison of all supported data sources for the market-datasets s | Source | Price Type | Dividends Available | Use For | |--------|------------|---------------------|---------| | **EODHD** | Both (close + adjusted_close) | Yes (splits/div-adjusted) | P&L (close), returns (adjusted_close) | -| **Stooq** | Adjusted only | No (prices pre-adjusted) | Total return calculations | | **Yahoo Finance** | Both (close + adj_close) | Yes (via API) | P&L calc (close), returns (adj_close) | | **NBP** | N/A | N/A | FX rates only | | **FRED** | N/A | N/A | Economic data only | @@ -32,64 +30,7 @@ See `references/dividend_treatment.md` for detailed dividend handling documentat ## Detailed Source Descriptions -### 1. Stooq (stooq.pl) - -**Purpose**: Free historical market data for Polish and international securities. - -**Coverage**: -- Polish stocks (PKO, CDR, PZU, etc.) -- Polish indices (WIG20, mWIG40, WIG, sWIG80) -- International indices (^SPX, ^IXIC, ^DJI) -- Currency pairs (EURUSD, USDPLN, EURPLN) -- Some commodities - -**Data Available**: -- OHLCV (Open, High, Low, Close, Volume) -- Daily, weekly, monthly intervals -- Extensive historical data (1990s+) - -**Dividend Treatment**: ⚠️ **Adjusted prices only** -- All OHLC values are **dividend-adjusted** automatically -- When dividends paid, historical prices adjusted DOWN -- Adjustment factor: `(price - dividend) / price` -- Multiple dividends compound (older data has larger adjustments) -- **Cannot recover raw prices** from Stooq alone -- Validated: Stooq prices match Yahoo Finance `adj_close` (95.8% of 48 tickers within 1%) -- See `references/dividend_treatment.md` for details - -**Strengths**: -- Free, no registration -- Excellent Polish market coverage -- Long historical data -- Simple CSV API -- Consistent dividend adjustment methodology - -**Limitations**: -- No raw/unadjusted prices available -- No dividend amounts API -- Limited international coverage -- No real-time data -- Informal rate limits (be polite) - -**Best For**: -- Polish stock analysis -- Total return calculations -- Performance attribution (returns) -- mWIG40 portfolio tracking -- Historical backtesting (Polish market) - -**Not Suitable For**: -- Calculating actual P&L on specific trades (use Yahoo `close`) -- Getting dividend payment amounts (use Yahoo Finance) - -**Example Tickers**: -- `pko` - PKO Bank Polski -- `wig20` - WIG20 index -- `usdpln` - USD/PLN exchange rate - ---- - -### 2. NBP API (api.nbp.pl) +### 1. NBP API (api.nbp.pl) **Purpose**: Official Polish National Bank exchange rates. @@ -128,7 +69,7 @@ See `references/dividend_treatment.md` for detailed dividend handling documentat --- -### 3. Yahoo Finance (via yfinance or Direct API) +### 2. Yahoo Finance (via yfinance or Direct API) **Purpose**: Comprehensive global market data. @@ -168,7 +109,7 @@ See `references/dividend_treatment.md` for detailed dividend handling documentat **Dividend Treatment**: Both raw and adjusted prices available - `close` = Raw/unadjusted price (actual trading price) - `adj_close` = Dividend-adjusted price (for total returns) -- `adj_close` matches Stooq prices (validated 95.8% within 1%) +- `adj_close` is rewritten on every dividend — never splice stored adjusted levels (see dividend_treatment.md) - Use `close` for P&L calculations, `adj_close` for return calculations - See `references/dividend_treatment.md` for details @@ -207,7 +148,7 @@ See `references/dividend_treatment.md` for detailed dividend handling documentat --- -### 4. Tiingo (api.tiingo.com) +### 3. Tiingo (api.tiingo.com) **Purpose**: High-quality US stock data with generous free tier and 30+ years of history. @@ -259,7 +200,7 @@ df = fetch_market_data('AAPL', source='tiingo', tiingo_api_key='your_key') --- -### 5. CCXT / Binance (Cryptocurrency) +### 4. CCXT / Binance (Cryptocurrency) **Purpose**: Cryptocurrency historical OHLCV data from Binance and 100+ exchanges. @@ -325,7 +266,7 @@ df = fetcher.fetch('BTC/USD') --- -### 6. FRED API (fred.stlouisfed.org) +### 5. FRED API (fred.stlouisfed.org) **Purpose**: US economic indicators from Federal Reserve. @@ -371,7 +312,7 @@ df = fetcher.fetch('BTC/USD') --- -### 7. FinancialData.Net (financialdata.net) +### 6. FinancialData.Net (financialdata.net) **Purpose**: Comprehensive financial data API covering stocks, fundamentals, options, forex, crypto, and institutional data. @@ -455,12 +396,11 @@ df = fetcher.get_senate_trading() --- -### 8. pandas-datareader +### 7. pandas-datareader **Purpose**: Meta-source providing unified interface to multiple data providers. **Coverage**: -- Stooq (via pandas-datareader) - Yahoo Finance (via pandas-datareader) - FRED (via pandas-datareader) - Alpha Vantage (requires API key) @@ -497,12 +437,12 @@ df = fetcher.get_senate_trading() The unified fetcher automatically selects sources based on ticker patterns: 1. **Cryptocurrency** (BTC/USDT, ETHUSDT) → CCXT/Binance -2. **Polish stocks** (pko, cdr, pzu) → Stooq -3. **PLN FX rates** (USD, EUR, GBP) → NBP API +2. **Polish stocks & indices** (pko, cdr, wig20, `.WA`/`.WAR`) → EODHD (`PKO.WAR`, `WIG20.INDX`) when `EODHD_API_KEY` is set → Yahoo (`PKO.WA`) for stocks/ETFs only; a WSE index without the key raises +3. **PLN FX rates** (USD, EUR, GBP, USDPLN) → NBP API → Yahoo (`USDPLN=X`) 4. **US stocks** (AAPL, MSFT, GOOGL) → Yahoo Finance → Tiingo → FinancialData.Net (fallback) 5. **International indices** (^SPX, ^IXIC) → Yahoo Finance 6. **Economic indicators** (GDP, UNRATE) → FRED -7. **Currency pairs** (USDPLN, EURUSD) → Stooq +7. **Other currency pairs** (EURUSD) → Yahoo (`EURUSD=X`) 8. **Fundamentals/options** → FinancialData.Net (via `fd_endpoint` parameter) 9. **Fallback** → pandas-datareader @@ -511,8 +451,8 @@ The unified fetcher automatically selects sources based on ticker patterns: Force specific source when needed: ```python -# Force Stooq for specific ticker -df = fetch_market_data('pko', source='stooq') +# Force EODHD for a GPW listing +df = fetch_market_data('PKO.WAR', source='eodhd') # Force Yahoo for Polish stock df = fetch_market_data('PKO.WA', source='yahoo') @@ -526,7 +466,7 @@ df = fetch_market_data('USD', source='nbp', table='A') Compare data across sources: ```python -comparison = fetcher.compare_sources('pko', ['stooq', 'yahoo']) +comparison = fetcher.compare_sources('PKO.WA', ['eodhd', 'yahoo']) ``` --- @@ -549,7 +489,7 @@ fetcher = UnifiedMarketDataFetcher(use_cache=True, cache_hours=24) ``` Cache locations: -- `data/cache/market_data/stooq/` +- `data/cache/market_data/eodhd/` - `data/cache/market_data/nbp/` - `data/cache/market_data/yahoo/` - `data/cache/market_data/fred/` @@ -641,18 +581,18 @@ If experiencing rate limiting: | Scenario | Recommended Source | Rationale | |----------|-------------------|-----------| -| Polish fund performance attribution | Stooq | Best Polish market coverage, adjusted prices | +| Polish fund performance attribution | EODHD → Yahoo | GPW `.WAR` + `.INDX`, adjusted prices | | Official PLN rates for accounting | NBP | Official regulatory rates | | US stock portfolio tracking | Yahoo → Tiingo | Comprehensive US coverage, Tiingo as fallback | | Macro factor analysis | FRED | Authoritative economic data | | Cross-market equity comparison | Yahoo | Global reach | -| Historical Polish index data | Stooq | Long history, free access | +| Historical Polish index data | EODHD `.INDX` | `WIG.INDX` from 1991-04-16 | | Intraday US stock data | Yahoo | Supports intraday intervals | | Data validation/cross-check | Multiple via compare_sources() | Ensures accuracy | -| **Total return calculation** | Stooq or Yahoo `adj_close` | Both are dividend-adjusted | +| **Total return calculation** | Yahoo or EODHD `adj_close` | Chain returns; adjusted levels are rewritten per dividend | | **Actual P&L on trades** | Yahoo `close` | Raw prices needed | | **Dividend amounts** | Yahoo Finance or Tiingo | Via API | -| **Validate Stooq data** | Yahoo `adj_close` | Should match within 1% | +| **Validate EODHD data** | Yahoo `adj_close` returns | Compare returns fetched together, not stored levels | | **Cryptocurrency analysis** | CCXT/Binance | Free unlimited history | | **Bitcoin/ETH tracking** | CCXT | Best crypto coverage | | **Hourly crypto data** | CCXT with `timeframe='1h'` | Supports all intervals | @@ -664,13 +604,13 @@ If experiencing rate limiting: | **Institutional ownership** | FinancialData.Net | Holders, holdings, portfolio stats | | **Event calendars** | FinancialData.Net | Earnings, IPO, splits, dividends | -### 9. EODHD (eodhd.com) +### 8. EODHD (eodhd.com) End-Of-Day Historical Data — REST API best suited to **UCITS/ETF and global multi-exchange** coverage. Chosen as the primary ETF/benchmark feed because it -is **reachable from datacenters/VPS** where Stooq is geo-blocked and Yahoo is -rate-limited, and it resolves GPW-listed and EU-domiciled instruments that the -free feeds handle poorly. +is **reachable from datacenters/VPS** where Yahoo is rate-limited, and it +resolves GPW-listed and EU-domiciled instruments that the free feeds handle +poorly. Since 2026-09-30 it is also the primary source for Polish instruments. **Why EODHD** - One REST endpoint per symbol: `GET https://eodhd.com/api/eod/{SYMBOL}` → JSON OHLCV + `adjusted_close`. @@ -692,7 +632,8 @@ uv run scripts/fetch_eodhd.py ETFBW20TR.WAR 2024-01-01 # GPW Beta ETF uv run scripts/fetch_eodhd.py ^BCOM 2024-01-01 # -> BCOM.INDX ``` -Routing: EODHD is **opt-in**, not auto-routed — the default router keeps Yahoo -primary for ad-hoc to avoid burning paid calls. Reach for EODHD deliberately -via `source='eodhd'` for UCITS/ETF, GPW (`.WAR`), and datacenter hosts where -Stooq/Yahoo are blocked. +Routing: EODHD is auto-routed **first for Polish instruments only** (GPW +`.WAR`, WIG-family `.INDX`), and only when `EODHD_API_KEY` is set; everything +else keeps Yahoo primary to avoid burning paid calls. Reach for EODHD +deliberately via `source='eodhd'` for UCITS/ETF and datacenter hosts where +Yahoo is blocked. Coverage and licensing: [eodhd.md](eodhd.md). diff --git a/claude/skills/quant/market-datasets/references/ticker_formats.md b/claude/skills/quant/market-datasets/references/ticker_formats.md index 73e96fa1..6b75c6c0 100644 --- a/claude/skills/quant/market-datasets/references/ticker_formats.md +++ b/claude/skills/quant/market-datasets/references/ticker_formats.md @@ -4,48 +4,53 @@ Comprehensive guide to ticker symbol formats across all supported data sources. ## Format Conventions by Source -### Stooq +### EODHD -**Polish Stocks**: Lowercase, no suffix +**Exchange-suffixed symbols** (`SYMBOL.EXCHANGE`, one symbol per call). The +primary source for Polish instruments when `EODHD_API_KEY` is set. + +**Polish stocks and ETFs**: GPW listings end in `.WAR` ``` -pko # PKO Bank Polski -cdr # CD Projekt -pzu # PZU -pkn # PKN Orlen -kgh # KGHM -pge # PGE -lpp # LPP -orange # Orange Polska +PKO.WAR # PKO Bank Polski +CDR.WAR # CD Projekt +XTB.WAR # XTB +ETFBW20TR.WAR # Beta ETF WIG20TR +ETFBTBSP.WAR # Beta ETF TBSP (bond-index proxy; the TBSP index itself is not on EODHD) ``` -**Polish Indices**: Lowercase +**Indices**: `.INDX` ``` -wig # WIG (main index) -wig20 # WIG20 (blue chips) -mwig40 # mWIG40 (mid cap) -swig80 # sWIG80 (small cap) -wig30 # WIG30 +WIG.INDX # WIG (total return, from 1991-04-16) +WIG20.INDX # WIG20 (price) +MWIG40.INDX # mWIG40 +SWIG80.INDX # sWIG80 +GSPC.INDX # S&P 500 +BCOM.INDX # Bloomberg Commodity +VIX.INDX # VIX ``` -**International Indices**: With caret prefix +**FX, metals, crypto** ``` -^spx # S&P 500 -^ixic # NASDAQ Composite -^dji # Dow Jones Industrial Average +USDPLN.FOREX # USD/PLN (PLN per 1 USD) +EURPLN.FOREX +XAUUSD.FOREX # gold spot (GC=F is not on EODHD) +BTC-USD.CC # crypto ``` -**Currency Pairs**: 6-letter code (lowercase) +**Other exchanges** ``` -usdpln # US Dollar / Polish Zloty -eurpln # Euro / Polish Zloty -eurusd # Euro / US Dollar -gbpusd # British Pound / US Dollar +SPY.US # US ETFs/stocks (bare ticker -> .US) +IMEU.LSE # UCITS on London (Yahoo .L -> .LSE) ``` -**Important Notes**: -- Do NOT use `.pl` suffix (causes "Brak danych" error) -- Use lowercase for consistency -- Stooq ticker `pko` ≠ Yahoo ticker `PKO.WA` +Conversion from common formats (`scripts/fetch_eodhd.py::eodhd_symbol`): +- bare ticker → `.US` +- `.WA` → `.WAR` (Warsaw / GPW) +- `.L` → `.LSE` (London) +- `^IDX` → `IDX.INDX` +- already exchange-suffixed → passthrough + +What the plan covers and what it does not: [eodhd.md](eodhd.md). --- @@ -175,29 +180,29 @@ CSCICP03USM665S # Consumer Confidence Index ### Same Company, Different Formats -| Company | Stooq | Yahoo | Description | +| Company | EODHD | Yahoo | Description | |---------|-------|-------|-------------| -| PKO Bank Polski | `pko` | `PKO.WA` | Polish bank | -| CD Projekt | `cdr` | `CDR.WA` | Polish game developer | -| PZU | `pzu` | `PZU.WA` | Polish insurer | -| PKN Orlen | `pkn` | `PKN.WA` | Polish oil & gas | -| KGHM | `kgh` | `KGH.WA` | Polish mining | +| PKO Bank Polski | `PKO.WAR` | `PKO.WA` | Polish bank | +| CD Projekt | `CDR.WAR` | `CDR.WA` | Polish game developer | +| PZU | `PZU.WAR` | `PZU.WA` | Polish insurer | +| PKN Orlen | `PKN.WAR` | `PKN.WA` | Polish oil & gas | +| KGHM | `KGH.WAR` | `KGH.WA` | Polish mining | ### Indices -| Index | Stooq | Yahoo | Description | +| Index | EODHD | Yahoo | Description | |-------|-------|-------|-------------| -| S&P 500 | `^spx` | `^GSPC` | US large cap | -| NASDAQ | `^ixic` | `^IXIC` | US tech | -| WIG20 | `wig20` | `^WIG20` | Polish blue chip | +| S&P 500 | `GSPC.INDX` | `^GSPC` | US large cap | +| NASDAQ | `IXIC.INDX` | `^IXIC` | US tech | +| WIG20 | `WIG20.INDX` | — (no history on Yahoo) | Polish blue chip | ### Currency Pairs -| Pair | Stooq | NBP (component) | Yahoo | +| Pair | EODHD | NBP (component) | Yahoo | |------|-------|-----------------|-------| -| USD/PLN | `usdpln` | `USD` (vs PLN) | `USDPLN=X` | -| EUR/PLN | `eurpln` | `EUR` (vs PLN) | `EURPLN=X` | -| EUR/USD | `eurusd` | N/A | `EURUSD=X` | +| USD/PLN | `USDPLN.FOREX` | `USD` (vs PLN) | `USDPLN=X` | +| EUR/PLN | `EURPLN.FOREX` | `EUR` (vs PLN) | `EURPLN=X` | +| EUR/USD | `EURUSD.FOREX` | N/A | `EURUSD=X` | --- @@ -205,28 +210,25 @@ CSCICP03USM665S # Consumer Confidence Index ### Pattern Recognition for Routing -The unified fetcher uses these patterns to auto-route: +The unified fetcher (`fetch_unified.py::_route_ticker`) auto-routes by pattern and +translates the ticker per source (`_ticker_for_source`): + +1. **Known Polish stock or index name** (`pko`, `cdr`, `wig20`) → EODHD + (`PKO.WAR`, `WIG20.INDX`) when `EODHD_API_KEY` is set, else Yahoo for STOCKS/ETFs only (`PKO.WA`); a WSE index without the key raises (Yahoo has no history for them — `^WIG20`/`^MWIG40` return 0 rows, probed 2026-09-30) -1. **Lowercase 2-4 letters** → Likely Polish stock → Try Stooq - - Examples: `pko`, `cdr`, `pzu` +2. **`.WA` / `.WAR` suffix** → EODHD, then Yahoo (same translation) -2. **Uppercase 1-5 letters** → Likely US stock → Try Yahoo - - Examples: `AAPL`, `MSFT`, `GOOGL` +3. **3 uppercase letters (USD, EUR, etc.)** → NBP, then Yahoo (`USDPLN=X`) -3. **6 uppercase letters** → Likely currency pair → Try Stooq - - Examples: `USDPLN`, `EURUSD` +4. **6 uppercase letters** → currency pair → `…PLN`: NBP, then Yahoo; otherwise Yahoo (`EURUSD=X`) -4. **3 uppercase letters (USD, EUR, etc.)** → Likely NBP currency → Try NBP - - Examples: `USD`, `EUR`, `GBP` +5. **Short uppercase (2-10 chars)** → could be a FRED series → FRED (when keyed) -5. **Starts with ^** → Likely index → Try Yahoo - - Examples: `^GSPC`, `^IXIC` +6. **Starts with ^** → index → Yahoo -6. **Contains .XX suffix** → International stock → Try Yahoo - - Examples: `PKO.WA`, `ASML.AS` +7. **Uppercase 1-5 letters** → likely US stock → Yahoo, then Tiingo / FinancialData -7. **Short uppercase (2-10 chars)** → Could be FRED series → Try FRED - - Examples: `GDP`, `UNRATE`, `CPIAUCSL` +8. **Other `.XX` suffix** → international stock → Yahoo (`.INDX` → EODHD) --- @@ -235,8 +237,7 @@ The unified fetcher uses these patterns to auto-route: ### Polish Market - **GPW (Warsaw Stock Exchange)**: https://www.gpw.pl/spolki -- **Stooq Symbol List**: https://stooq.pl/t/?i=528 -- Search format: Company name → Stooq ticker +- **EODHD exchange symbol list**: `GET https://eodhd.com/api/exchange-symbol-list/WAR?api_token=KEY&fmt=json` ### US Market @@ -254,14 +255,14 @@ The unified fetcher uses these patterns to auto-route: ## Special Cases & Gotchas -### Polish Stocks: Stooq vs Yahoo +### Polish Stocks: EODHD vs Yahoo -**Problem**: Same company, different tickers +**Problem**: Same company, different suffixes **Solution**: -- For Stooq: Use lowercase, no suffix (`pko`) -- For Yahoo: Use uppercase + `.WA` suffix (`PKO.WA`) -- Unified fetcher handles automatically +- For EODHD: uppercase + `.WAR` (`PKO.WAR`) +- For Yahoo: uppercase + `.WA` (`PKO.WA`) +- Unified fetcher translates automatically ### Currency Pairs: Direction Matters @@ -269,19 +270,17 @@ The unified fetcher uses these patterns to auto-route: - `USD` from NBP = How many USD per PLN - Returns mid rate, bid/ask for table C -**Stooq/Yahoo**: Standard market convention +**EODHD/Yahoo**: Standard market convention - `USDPLN` = How many PLN per 1 USD - This is opposite of some NBP interpretations ### Index Symbols: Caret Prefix **With caret (^)**: -- Yahoo Finance standard: `^GSPC`, `^IXIC` -- Some Stooq indices: `^spx`, `^dji` +- Yahoo Finance standard: `^GSPC`, `^IXIC` (no WSE indices) **Without caret**: -- Polish indices on Stooq: `wig20`, `mwig40` -- Yahoo Polish indices: `^WIG20`, `^MWIG40` +- EODHD: `GSPC.INDX`, `WIG20.INDX` (`^X` → `X.INDX` via `eodhd_symbol`) ### Class Shares @@ -299,17 +298,16 @@ The unified fetcher uses these patterns to auto-route: ### Valid Formats by Source -**Stooq**: +**EODHD**: ```python # Valid -'pko' # Lowercase -'wig20' # Lowercase index -'^spx' # Index with caret -'usdpln' # Currency pair +'PKO.WAR' # GPW listing +'WIG20.INDX' # Index +'USDPLN.FOREX' # FX pair # Invalid -'pko.pl' # .pl suffix causes error -'PKO' # May work but lowercase preferred +'PKO.WA' # Yahoo suffix — eodhd_symbol converts it to .WAR +'GC=F' # Yahoo futures code, not on EODHD (use XAUUSD.FOREX) ``` **Yahoo**: @@ -356,14 +354,14 @@ The unified fetcher automatically normalizes tickers: ```python # Automatic normalization examples -# Polish stock → Lowercase for Stooq -'PKO' → 'pko' (when routed to Stooq) +# Polish stock name → per-source suffix +'pko' → 'PKO.WAR' (EODHD) / 'PKO.WA' (Yahoo) # US stock → Uppercase for Yahoo 'aapl' → 'AAPL' (when routed to Yahoo) -# Remove .pl suffix for Stooq -'pko.pl' → 'pko' +# PLN pair → NBP currency / Yahoo pair +'USDPLN' → 'USD' (NBP) / 'USDPLN=X' (Yahoo) # Currency code → Uppercase for NBP 'usd' → 'USD' (when routed to NBP) @@ -432,31 +430,12 @@ prices, dividends, splits, mapping = fetch_by_isin( | You Want | Source | Format Example | Notes | |----------|--------|----------------|-------| -| Polish stock price | Stooq | `pko` | Lowercase, no suffix | +| Polish stock price | EODHD | `PKO.WAR` | Needs `EODHD_API_KEY`; else Yahoo | | US stock price | Yahoo | `AAPL` | Uppercase | | Polish stock (Yahoo) | Yahoo | `PKO.WA` | Uppercase + .WA | | S&P 500 | Yahoo | `^GSPC` | Caret prefix | -| USD/PLN rate | Stooq or NBP | `usdpln` or `USD` | Stooq=pair, NBP=currency | +| USD/PLN rate | NBP or Yahoo | `USD` or `USDPLN=X` | NBP=currency, Yahoo=pair | | US GDP | FRED | `GDP` | Exact series ID | -| mWIG40 index | Stooq | `mwig40` | Lowercase | +| mWIG40 index | EODHD | `MWIG40.INDX` | no Yahoo fallback (keyless: gpw-benchmark-scraper) | | By ISIN | Yahoo Direct | `PLXTRDM00011` | Auto-converts to ticker | | Dividends & splits | Yahoo Direct | `XTB.WA` | Use `events=div,splits` | - -### EODHD - -Exchange-suffixed symbols (one symbol per call). ISIN lookup also supported. - -``` -SPY.US # US ETFs/stocks (bare ticker -> .US) -AGG.US # iShares Core US Aggregate Bond -IMEU.LSE # UCITS on London (Yahoo .L -> .LSE) -ETFBW20TR.WAR # GPW / Warsaw Beta ETF (Yahoo .WA -> .WAR) -BCOM.INDX # indices (^BCOM -> BCOM.INDX) -``` - -Conversion from common formats (`scripts/fetch_eodhd.py::eodhd_symbol`): -- bare ticker → `.US` -- `.WA` → `.WAR` (Warsaw / GPW) -- `.L` → `.LSE` (London) -- `^IDX` → `IDX.INDX` -- already exchange-suffixed → passthrough diff --git a/claude/skills/quant/market-datasets/references/usage_patterns.md b/claude/skills/quant/market-datasets/references/usage_patterns.md index 77df4b81..f8fdfbab 100644 --- a/claude/skills/quant/market-datasets/references/usage_patterns.md +++ b/claude/skills/quant/market-datasets/references/usage_patterns.md @@ -7,9 +7,9 @@ Complete code examples for all data fetching patterns. ```python from fetch_unified import fetch_market_data -df = fetch_market_data('pko', start_date='2024-01-01') # Polish stock → Stooq +df = fetch_market_data('pko', start_date='2024-01-01') # Polish stock → EODHD PKO.WAR (keyed), else Yahoo PKO.WA df = fetch_market_data('AAPL', start_date='2024-01-01') # US stock → Yahoo (Tiingo fallback) -df = fetch_market_data('USD', start_date='2024-01-01') # Currency → Stooq or NBP +df = fetch_market_data('USD', start_date='2024-01-01') # PLN FX → NBP, then Yahoo df = fetch_market_data('BTC/USDT', start_date='2024-01-01') # Crypto → CCXT/Binance df = fetch_market_data('GDP', start_date='2020-01-01') # Macro → FRED ``` @@ -17,7 +17,7 @@ df = fetch_market_data('GDP', start_date='2020-01-01') # Macro → FRED ## Pattern 2: Force Specific Source ```python -df = fetch_market_data('pko', source='stooq', start_date='2024-01-01') +df = fetch_market_data('PKO.WAR', source='eodhd', start_date='2024-01-01') df = fetch_market_data('PKO.WA', source='yahoo', start_date='2024-01-01') df = fetch_market_data('USD', source='nbp', table='A', start_date='2024-01-01') df = fetch_market_data('MSFT', source='tiingo', start_date='2024-01-01') @@ -32,7 +32,7 @@ from fetch_unified import UnifiedMarketDataFetcher fetcher = UnifiedMarketDataFetcher() comparison = fetcher.compare_sources( - ticker='pko', sources=['stooq', 'yahoo'], + ticker='PKO.WA', sources=['eodhd', 'yahoo'], start_date='2024-01-01', end_date='2024-01-31' ) @@ -44,8 +44,8 @@ for source, df in comparison.items(): ## Pattern 4: Direct Source Usage ```python -from fetch_stooq import fetch_stooq -df = fetch_stooq('pko', start_date='20240101', end_date='20241231', interval='d') +from fetch_eodhd import fetch_eodhd +df = fetch_eodhd('PKO.WAR', start_date='2024-01-01', end_date='2024-12-31') from fetch_nbp import fetch_nbp df = fetch_nbp('USD', start_date='20240101', table='A') @@ -95,7 +95,7 @@ save_isin_data( ## Pattern 7: TickerRegistry for ISIN/Ticker Conversion ```python -from ticker_registry import TickerRegistry, isin_to_yahoo, isin_to_stooq +from ticker_registry import TickerRegistry, isin_to_yahoo registry = TickerRegistry() @@ -107,15 +107,12 @@ security = registry.get_security('XTB.WA') # By Yahoo ticker print(security.name) # 'XTB' print(security.isin) # 'PLXTRDM00011' print(security.get_ticker('yahoo')) # 'XTB.WA' -print(security.get_ticker('stooq')) # 'xtb' # Convert between formats yahoo = registry.convert_ticker('PLXTRDM00011', to_source='yahoo') # 'XTB.WA' -stooq = registry.convert_ticker('XTB.WA', to_source='stooq') # 'xtb' # Convenience functions yahoo = isin_to_yahoo('PLXTRDM00011') # 'XTB.WA' -stooq = isin_to_stooq('PLXTRDM00011') # 'xtb' ``` ## Pattern 8: Fetch by ISIN with Unified Fetcher @@ -151,7 +148,7 @@ registry = TickerRegistry() security = Security( uid='isin_GB0002634946', isin='GB0002634946', name='BAE Systems', instrument_type='equity', country='GB', exchange='LSE', - tickers={'yahoo': 'BA.L', 'stooq': 'ba.uk'}, + tickers={'yahoo': 'BA.L'}, mapping_source='manual', last_updated=datetime.now() ) registry.register_security(security) diff --git a/claude/skills/quant/market-datasets/scripts/fetch_eodhd.py b/claude/skills/quant/market-datasets/scripts/fetch_eodhd.py index 301f490a..62634171 100644 --- a/claude/skills/quant/market-datasets/scripts/fetch_eodhd.py +++ b/claude/skills/quant/market-datasets/scripts/fetch_eodhd.py @@ -11,8 +11,11 @@ EODHD (EOD Historical Data) fetcher. Best for UCITS/ETF and global multi-exchange coverage keyed by exchange-suffixed -symbol or ISIN. REST API over HTTPS — reachable from datacenters/VPS where -Stooq/Yahoo are geo-blocked or rate-limited. Splits/dividend-adjusted EOD. +symbol or ISIN, and the primary source for Polish instruments (GPW listings as +.WAR, WIG-family indices as .INDX). REST API over HTTPS — reachable from +datacenters/VPS where Yahoo is blocked or rate-limited. Splits/dividend-adjusted +EOD; adjusted_close is recomputed on every dividend, so chain returns rather +than appending adjusted levels incrementally (references/eodhd.md). Coverage validated 2026-06-29 on a 42-instrument ETF benchmark universe: 100% resolution incl. US (.US), London UCITS (.LSE), GPW Beta ETFs (.WAR), and diff --git a/claude/skills/quant/market-datasets/scripts/fetch_pandas_datareader.py b/claude/skills/quant/market-datasets/scripts/fetch_pandas_datareader.py index 85511445..4ab6cc19 100644 --- a/claude/skills/quant/market-datasets/scripts/fetch_pandas_datareader.py +++ b/claude/skills/quant/market-datasets/scripts/fetch_pandas_datareader.py @@ -11,10 +11,10 @@ Meta-fetcher that provides access to multiple data sources through pandas-datareader. -Supported sources: stooq, yahoo, fred, av-daily (Alpha Vantage), iex, etc. +Supported sources: yahoo, fred, av-daily (Alpha Vantage), iex, quandl. Usage: - uv run fetch_pandas_datareader.py AAPL 2024-01-01 2024-12-31 --source stooq + uv run fetch_pandas_datareader.py AAPL 2024-01-01 2024-12-31 --source yahoo uv run fetch_pandas_datareader.py GDP 2020-01-01 --source fred uv run fetch_pandas_datareader.py # Run self-tests """ @@ -46,7 +46,6 @@ class PandasDataReaderFetcher: """Wrapper for pandas-datareader multi-source data access.""" SUPPORTED_SOURCES = [ - 'stooq', # Stooq (Polish & international stocks) 'yahoo', # Yahoo Finance 'fred', # FRED economic data 'av-daily', # Alpha Vantage (requires API key) @@ -81,7 +80,7 @@ def fetch(self, ticker: str, source: str = 'yahoo', Args: ticker: Ticker symbol (format depends on source) - source: Data source ('stooq', 'yahoo', 'fred', etc.) + source: Data source ('yahoo', 'fred', etc.) start_date: Start date (YYYY-MM-DD or YYYYMMDD) end_date: End date (YYYY-MM-DD or YYYYMMDD) **kwargs: Additional arguments passed to DataReader @@ -235,18 +234,7 @@ def fetch_pandas_datareader(ticker: str, source: str = 'yahoo', except Exception as e: print(f" Error: {e}") - # Test 2: Stooq via pandas-datareader - print("\n2. Fetching PKO from Stooq:") - try: - df = fetch_pandas_datareader('pko', source='stooq', - start_date='20240101', - end_date='20240131') - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 3: FRED via pandas-datareader + # Test 2: FRED via pandas-datareader print("\n3. Fetching GDP from FRED:") try: df = fetch_pandas_datareader('GDP', source='fred', @@ -257,6 +245,6 @@ def fetch_pandas_datareader(ticker: str, source: str = 'yahoo', except Exception as e: print(f" Error: {e}") - # Test 4: List sources - print("\n4. Supported sources:") + # Test 3: List sources + print("\n3. Supported sources:") print(" " + ", ".join(PandasDataReaderFetcher.list_sources())) diff --git a/claude/skills/quant/market-datasets/scripts/fetch_stooq.py b/claude/skills/quant/market-datasets/scripts/fetch_stooq.py deleted file mode 100644 index 1850b8bd..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_stooq.py +++ /dev/null @@ -1,240 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# ] -# /// -""" -Stooq data fetcher. - -Downloads historical market data from stooq.pl including: -- Polish stocks (PKO, CDR, PZU, etc.) -- Polish indices (WIG20, mWIG40, WIG, etc.) -- International indices (^SPX, ^IXIC, etc.) -- Currency pairs (EURUSD, USDPLN, etc.) -- Commodities - -Usage: - uv run fetch_stooq.py PKO 2024-01-01 2024-12-31 - uv run fetch_stooq.py WIG20 2024-01-01 - uv run fetch_stooq.py # Run self-tests -""" - -import pandas as pd -import requests -from typing import Optional -from io import StringIO -from datetime import datetime, date - -from utils import ( - get_cache_manager, - get_rate_limiter, - normalize_date, - standardize_dataframe, - create_identifier, - handle_api_error -) - - -class StooqFetcher: - """Fetcher for stooq.pl market data.""" - - BASE_URL = "https://stooq.pl/q/d/l/" - - def __init__(self, use_cache: bool = True, cache_hours: int = 24): - """ - Initialize Stooq fetcher. - - Args: - use_cache: Whether to use caching - cache_hours: Cache validity in hours - """ - self.use_cache = use_cache - self.cache_hours = cache_hours - self.cache = get_cache_manager() - self.rate_limiter = get_rate_limiter() - - def fetch(self, ticker: str, start_date: Optional[str] = None, - end_date: Optional[str] = None, interval: str = 'd') -> pd.DataFrame: - """ - Fetch data from Stooq. - - Args: - ticker: Stock ticker (e.g., 'pko', 'wig20', '^spx', 'eurusd') - start_date: Start date (YYYY-MM-DD or YYYYMMDD), None for all history - end_date: End date (YYYY-MM-DD or YYYYMMDD), None for all history - interval: Data interval - 'd' (daily), 'w' (weekly), 'm' (monthly) - - Returns: - DataFrame with columns: Date, Open, High, Low, Close, Volume - - Raises: - ValueError: If ticker returns no data - requests.RequestException: If request fails - """ - # Normalize ticker - ticker = self._normalize_ticker(ticker) - - # Create cache identifier - start_norm = normalize_date(start_date) if start_date else None - end_norm = normalize_date(end_date) if end_date else None - cache_id = create_identifier(ticker, start_norm, end_norm, interval) - - # Try cache first - if self.use_cache: - cached = self.cache.get('stooq', cache_id, max_age_hours=self.cache_hours) - if cached is not None: - print(f"[Stooq] Using cached data for {ticker}") - return cached - - # Build URL - url = self._build_url(ticker, start_norm, end_norm, interval) - - try: - # Rate limiting - self.rate_limiter.wait('stooq') - - # Fetch data - print(f"[Stooq] Fetching {ticker} from {start_norm or 'earliest'} to {end_norm or 'latest'}") - response = requests.get(url, timeout=30) - response.raise_for_status() - - # Check for "Brak danych" (No data) - if response.text.strip() == "Brak danych": - raise ValueError(f"No data available for ticker: {ticker}") - - # Parse CSV - df = pd.read_csv(StringIO(response.text)) - - if df.empty: - raise ValueError(f"Empty data returned for ticker: {ticker}") - - # Standardize DataFrame - df = standardize_dataframe(df, 'stooq') - - # Cache result - if self.use_cache: - self.cache.set('stooq', cache_id, df) - - return df - - except Exception as e: - handle_api_error('Stooq', e, ticker) - raise - - def _normalize_ticker(self, ticker: str) -> str: - """ - Normalize ticker for Stooq API. - - Args: - ticker: Raw ticker - - Returns: - Normalized ticker - """ - # Remove any .pl suffix (causes "Brak danych") - if ticker.lower().endswith('.pl'): - ticker = ticker[:-3] - - # Lowercase (except for ^ prefix) - if not ticker.startswith('^'): - ticker = ticker.lower() - - return ticker - - def _build_url(self, ticker: str, start_date: Optional[str] = None, - end_date: Optional[str] = None, interval: str = 'd') -> str: - """ - Build Stooq API URL. - - Args: - ticker: Normalized ticker - start_date: Start date (YYYYMMDD) - end_date: End date (YYYYMMDD) - interval: Interval code - - Returns: - Complete URL - """ - url = f"{self.BASE_URL}?s={ticker}&i={interval}" - - if start_date: - url += f"&d1={start_date}" - if end_date: - url += f"&d2={end_date}" - - return url - - -def fetch_stooq(ticker: str, start_date: Optional[str] = None, - end_date: Optional[str] = None, interval: str = 'd', - use_cache: bool = True) -> pd.DataFrame: - """ - Convenience function to fetch data from Stooq. - - Args: - ticker: Stock ticker - start_date: Start date - end_date: End date - interval: Data interval ('d', 'w', 'm') - use_cache: Whether to use caching - - Returns: - DataFrame with market data - """ - fetcher = StooqFetcher(use_cache=use_cache) - return fetcher.fetch(ticker, start_date, end_date, interval) - - -if __name__ == '__main__': - import sys - - # CLI mode: uv run fetch_stooq.py TICKER START_DATE [END_DATE] - if len(sys.argv) > 1: - ticker = sys.argv[1] - start_date = sys.argv[2] if len(sys.argv) > 2 else None - end_date = sys.argv[3] if len(sys.argv) > 3 else None - - print(f"Fetching {ticker} from Stooq...") - df = fetch_stooq(ticker, start_date=start_date, end_date=end_date) - print(f"\nRetrieved {len(df)} rows") - print(f"Date range: {df['Date'].min()} to {df['Date'].max()}") - print(f"\nFirst 5 rows:") - print(df.head()) - print(f"\nLast 5 rows:") - print(df.tail()) - else: - # Self-tests - print("Running Stooq fetcher self-tests...") - - # Test 1: Polish stock - print("\n1. Fetching PKO (Polish stock):") - try: - df = fetch_stooq('pko', start_date='20240101', end_date='20240131') - assert len(df) > 15, f"Expected ~20 trading days, got {len(df)}" - assert 'Close' in df.columns, "Missing Close column" - print(f" Retrieved {len(df)} rows") - except Exception as e: - print(f" Error: {e}") - - # Test 2: Polish index - print("\n2. Fetching WIG20 (Polish index):") - try: - df = fetch_stooq('wig20', start_date='20240101', end_date='20240131') - assert len(df) > 15, f"Expected ~20 trading days, got {len(df)}" - print(f" Retrieved {len(df)} rows") - except Exception as e: - print(f" Error: {e}") - - # Test 3: Currency - print("\n3. Fetching USDPLN (Currency):") - try: - df = fetch_stooq('usdpln', start_date='20240101', end_date='20240131') - assert len(df) > 15, f"Expected ~20 trading days, got {len(df)}" - print(f" Retrieved {len(df)} rows") - except Exception as e: - print(f" Error: {e}") - - print("\nAll Stooq fetcher tests passed!") diff --git a/claude/skills/quant/market-datasets/scripts/fetch_stooq_corporate_actions.py b/claude/skills/quant/market-datasets/scripts/fetch_stooq_corporate_actions.py deleted file mode 100644 index 4c1d4021..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_stooq_corporate_actions.py +++ /dev/null @@ -1,384 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# "beautifulsoup4>=4.12", -# ] -# /// -""" -Stooq Corporate Actions Fetcher - -Fetches corporate actions data from stooq.pl including: -- Dividends (Dywidenda) -- Subscription rights (Prawo Poboru) -- Acquisition rights (Prawo Nabycia) -- Allotment rights (Prawo Objęcia) -- Stock splits (Split) -- Denominations (Denominacja) - -URL Pattern: https://stooq.pl/q/m/?s={ticker}&l=0 - -Usage: - uv run fetch_stooq_corporate_actions.py PKO - uv run fetch_stooq_corporate_actions.py CDR - uv run fetch_stooq_corporate_actions.py # Run self-tests -""" - -import pandas as pd -import requests -from bs4 import BeautifulSoup -from typing import Optional, Dict -from datetime import datetime -import re -from io import StringIO - -from utils import ( - get_cache_manager, - get_rate_limiter, - create_identifier, - handle_api_error -) - - -class StooqCorporateActionsFetcher: - """Fetcher for stooq.pl corporate actions data.""" - - BASE_URL = "https://stooq.pl/q/m/" - - # Event type mapping (Polish to English) - EVENT_TYPES = { - 'Dywidenda': 'Dividend', - 'Prawo Poboru': 'Subscription Rights', - 'Prawo Nabycia': 'Acquisition Rights', - 'Prawo Objęcia': 'Allotment Rights', - 'Split': 'Stock Split', - 'Denominacja': 'Denomination' - } - - def __init__(self, use_cache: bool = True, cache_hours: int = 168): # 1 week cache - """ - Initialize corporate actions fetcher. - - Args: - use_cache: Whether to use caching - cache_hours: Cache validity (default 168h = 1 week) - """ - self.use_cache = use_cache - self.cache_hours = cache_hours - self.cache = get_cache_manager() - self.rate_limiter = get_rate_limiter() - - def fetch(self, ticker: str) -> pd.DataFrame: - """ - Fetch corporate actions for a ticker. - - Args: - ticker: Stock ticker (e.g., 'pko', 'cdr', 'pzu') - - Returns: - DataFrame with columns: - - Date: Action date - - Event: Event type (English) - - Event_PL: Event type (Polish) - - Nominal: Nominal value - - Divisor: Adjustment divisor - - Pct: Percentage (if available in event name) - - Raises: - ValueError: If ticker returns no data - requests.RequestException: If request fails - """ - # Normalize ticker - ticker = self._normalize_ticker(ticker) - - # Create cache identifier - cache_id = create_identifier(ticker, 'corporate_actions') - - # Try cache first - if self.use_cache: - cached = self.cache.get('stooq_ca', cache_id, max_age_hours=self.cache_hours) - if cached is not None: - print(f"[Stooq CA] Using cached data for {ticker}") - return cached - - # Build URL - url = f"{self.BASE_URL}?s={ticker}&l=0" # l=0 means show all - - try: - # Rate limiting - self.rate_limiter.wait('stooq') - - # Fetch data - print(f"[Stooq CA] Fetching corporate actions for {ticker}...") - response = requests.get(url, timeout=30) - response.raise_for_status() - - # Parse HTML - soup = BeautifulSoup(response.text, 'html.parser') - - # Find the operations table - table = soup.find('table') - if not table: - print(f"[Stooq CA] No corporate actions found for {ticker}") - return pd.DataFrame(columns=['Date', 'Event', 'Event_PL', 'Nominal', 'Divisor', 'Pct']) - - # Parse table - rows = [] - for tr in table.find_all('tr')[1:]: # Skip header - cells = tr.find_all('td') - if len(cells) >= 4: - date_str = cells[0].get_text(strip=True) - event_str = cells[1].get_text(strip=True) - nominal_str = cells[2].get_text(strip=True) - divisor_str = cells[3].get_text(strip=True) - - # Parse date (e.g., "pon, 4 sie 2025") - date = self._parse_polish_date(date_str) - - # Parse event type and percentage - event_pl, pct = self._parse_event(event_str) - event_en = self.EVENT_TYPES.get(event_pl, event_pl) - - # Parse numerical values - try: - nominal = float(nominal_str.replace(',', '.')) - except: - nominal = None - - try: - divisor = float(divisor_str.replace(',', '.')) - except: - divisor = None - - rows.append({ - 'Date': date, - 'Event': event_en, - 'Event_PL': event_pl, - 'Nominal': nominal, - 'Divisor': divisor, - 'Pct': pct - }) - - if not rows: - print(f"[Stooq CA] No corporate actions parsed for {ticker}") - df = pd.DataFrame(columns=['Date', 'Event', 'Event_PL', 'Nominal', 'Divisor', 'Pct']) - else: - df = pd.DataFrame(rows) - df = df.sort_values('Date').reset_index(drop=True) - - print(f"[Stooq CA] Found {len(df)} corporate actions for {ticker}") - print(f" Types: {df['Event'].value_counts().to_dict()}") - - # Cache result - if self.use_cache: - self.cache.set('stooq_ca', cache_id, df) - - return df - - except Exception as e: - handle_api_error('Stooq CA', e, ticker) - raise - - def _normalize_ticker(self, ticker: str) -> str: - """Normalize ticker for Stooq (lowercase, no .pl)""" - if ticker.lower().endswith('.pl'): - ticker = ticker[:-3] - return ticker.lower() - - def _parse_polish_date(self, date_str: str) -> pd.Timestamp: - """ - Parse Polish date string. - - Examples: - "pon, 4 sie 2025" -> 2025-08-04 - "śro, 7 sie 2024" -> 2024-08-07 - """ - # Polish month abbreviations - months = { - 'sty': 1, 'lut': 2, 'mar': 3, 'kwi': 4, 'maj': 5, 'cze': 6, - 'lip': 7, 'sie': 8, 'wrz': 9, 'paź': 10, 'lis': 11, 'gru': 12 - } - - # Extract day, month, year - # Pattern: "day_name, day month year" - parts = date_str.split(',')[1].strip().split() - if len(parts) == 3: - day = int(parts[0]) - month_str = parts[1] - year = int(parts[2]) - - month = months.get(month_str, 1) - - return pd.Timestamp(year=year, month=month, day=day) - else: - raise ValueError(f"Cannot parse date: {date_str}") - - def _parse_event(self, event_str: str) -> tuple: - """ - Parse event string to extract type and percentage. - - Examples: - "Dywidenda 6.75%" -> ("Dywidenda", 6.75) - "Prawo Poboru 7.72%" -> ("Prawo Poboru", 7.72) - "Split" -> ("Split", None) - """ - # Extract percentage if present - pct_match = re.search(r'(\d+\.?\d*)\s*%', event_str) - pct = float(pct_match.group(1)) if pct_match else None - - # Remove percentage from event type - event_type = re.sub(r'\s+\d+\.?\d*\s*%', '', event_str).strip() - - return event_type, pct - - def calculate_adjusted_prices(self, prices: pd.DataFrame, ticker: str) -> pd.DataFrame: - """ - Calculate adjusted prices using corporate actions. - - Args: - prices: DataFrame with Date and Close columns - ticker: Stock ticker - - Returns: - DataFrame with additional Close_Adj column - - Methodology: - - Stooq divisors are cumulative adjustment factors - - To adjust: Price_Adjusted = Price_Raw / Cumulative_Divisor - - We need to build cumulative divisor from all events - """ - print(f"\n[Stooq CA] Calculating adjusted prices for {ticker}...") - - # Fetch corporate actions - ca = self.fetch(ticker) - - if ca.empty: - print(f" No corporate actions, returning unadjusted prices") - prices['Close_Adj'] = prices['Close'] - return prices - - # Ensure dates are datetime - prices = prices.copy() - prices['Date'] = pd.to_datetime(prices['Date']) - ca['Date'] = pd.to_datetime(ca['Date']) - - # Sort by date - ca = ca.sort_values('Date') - - # Calculate cumulative divisor for each date - # Start with 1.0 (no adjustment for latest data) - # Work backwards: older data needs more adjustment - - # Get all unique dates - all_dates = pd.DataFrame({'Date': sorted(set(prices['Date'].tolist() + ca['Date'].tolist()))}) - - # Merge corporate actions - all_dates = all_dates.merge(ca[['Date', 'Divisor']], on='Date', how='left') - - # Forward fill divisors (divisor applies from event date forward) - all_dates['Divisor'] = all_dates['Divisor'].fillna(1.0) - - # Calculate cumulative divisor from LATEST date backwards - # This ensures latest prices are not adjusted, older prices are - all_dates = all_dates.sort_values('Date', ascending=False) - all_dates['Cumulative_Divisor'] = all_dates['Divisor'].cumprod() - all_dates = all_dates.sort_values('Date') - - # Merge with prices - result = prices.merge(all_dates[['Date', 'Cumulative_Divisor']], on='Date', how='left') - - # Fill missing cumulative divisors - result['Cumulative_Divisor'] = result['Cumulative_Divisor'].fillna(1.0) - - # Calculate adjusted close - result['Close_Adj'] = result['Close'] / result['Cumulative_Divisor'] - - print(f" Applied {len(ca)} corporate actions") - print(f" Adjustment range: {result['Cumulative_Divisor'].min():.6f} to {result['Cumulative_Divisor'].max():.6f}") - - return result[['Date', 'Open', 'High', 'Low', 'Close', 'Close_Adj', 'Volume']] - - -def fetch_corporate_actions(ticker: str, use_cache: bool = True) -> pd.DataFrame: - """ - Convenience function to fetch corporate actions. - - Args: - ticker: Stock ticker - use_cache: Whether to use caching - - Returns: - DataFrame with corporate actions - """ - fetcher = StooqCorporateActionsFetcher(use_cache=use_cache) - return fetcher.fetch(ticker) - - -def calculate_adjusted_prices(prices: pd.DataFrame, ticker: str, use_cache: bool = True) -> pd.DataFrame: - """ - Convenience function to calculate adjusted prices. - - Args: - prices: DataFrame with Date, Close columns - ticker: Stock ticker - use_cache: Whether to use caching - - Returns: - DataFrame with Close_Adj column added - """ - fetcher = StooqCorporateActionsFetcher(use_cache=use_cache) - return fetcher.calculate_adjusted_prices(prices, ticker) - - -if __name__ == '__main__': - import sys - sys.path.insert(0, '.') - from fetch_stooq import fetch_stooq - - print("Testing Stooq Corporate Actions Fetcher...") - - # Test 1: Fetch corporate actions - print("\n" + "="*80) - print("TEST 1: Fetch Corporate Actions for PKO") - print("="*80) - - try: - ca = fetch_corporate_actions('pko') - print(f"\nFetched {len(ca)} corporate actions:") - print(ca.to_string()) - except Exception as e: - print(f"Error: {e}") - - # Test 2: Calculate adjusted prices - print("\n" + "="*80) - print("TEST 2: Calculate Adjusted Prices") - print("="*80) - - try: - # Fetch raw prices - prices = fetch_stooq('pko', start_date='20200101', end_date='20241231') - print(f"\nFetched {len(prices)} days of price data") - - # Calculate adjusted prices - fetcher = StooqCorporateActionsFetcher() - adjusted = fetcher.calculate_adjusted_prices(prices, 'pko') - - print(f"\nAdjusted prices calculated:") - print(adjusted[['Date', 'Close', 'Close_Adj']].head(10).to_string()) - print("...") - print(adjusted[['Date', 'Close', 'Close_Adj']].tail(10).to_string()) - - # Compare - print(f"\nAdjustment Impact:") - print(f" Latest (unadjusted): {adjusted.iloc[-1]['Close']:.2f}") - print(f" Latest (adjusted): {adjusted.iloc[-1]['Close_Adj']:.2f}") - print(f" Oldest (unadjusted): {adjusted.iloc[0]['Close']:.2f}") - print(f" Oldest (adjusted): {adjusted.iloc[0]['Close_Adj']:.2f}") - print(f" Total adjustment factor: {adjusted.iloc[0]['Close'] / adjusted.iloc[0]['Close_Adj']:.4f}") - - except Exception as e: - print(f"Error: {e}") - import traceback - traceback.print_exc() diff --git a/claude/skills/quant/market-datasets/scripts/fetch_stooq_corporate_actions_firecrawl.py b/claude/skills/quant/market-datasets/scripts/fetch_stooq_corporate_actions_firecrawl.py deleted file mode 100644 index 400d58ad..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_stooq_corporate_actions_firecrawl.py +++ /dev/null @@ -1,373 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# ] -# /// -""" -Stooq Corporate Actions Fetcher using Firecrawl - -Efficiently fetches corporate actions data from stooq.pl using Firecrawl MCP. -This is the RECOMMENDED method - simple, reliable, and uses existing infrastructure. - -Requires FIRECRAWL_API_KEY environment variable or .env file. - -Usage: - uv run fetch_stooq_corporate_actions_firecrawl.py PKO - uv run fetch_stooq_corporate_actions_firecrawl.py # Run self-tests - -Module usage: - from fetch_stooq_corporate_actions_firecrawl import fetch_corporate_actions, calculate_adjusted_prices - - # Fetch corporate actions - ca = fetch_corporate_actions('pko') - - # Calculate adjusted prices - adjusted = calculate_adjusted_prices(prices_df, 'pko') -""" - -import pandas as pd -import re -from datetime import datetime -from typing import Optional -from pathlib import Path -import pickle - - -class StooqCorporateActionsFirecrawl: - """Fetcher for stooq.pl corporate actions using Firecrawl MCP.""" - - # Event type mapping (Polish to English) - EVENT_TYPES = { - 'Dywidenda': 'Dividend', - 'Prawo Poboru': 'Subscription Rights', - 'Prawo Nabycia': 'Acquisition Rights', - 'Prawo Objęcia': 'Allotment Rights', - 'Split': 'Stock Split', - 'Denominacja': 'Denomination' - } - - def __init__(self, use_cache: bool = True, cache_hours: int = 168): - """ - Initialize fetcher. - - Args: - use_cache: Whether to cache results (default True) - cache_hours: Cache validity in hours (default 168 = 1 week) - """ - self.use_cache = use_cache - self.cache_hours = cache_hours - self.cache_dir = Path('data/cache/corporate_actions') - self.cache_dir.mkdir(parents=True, exist_ok=True) - - def fetch(self, ticker: str, firecrawl_scrape_func) -> pd.DataFrame: - """ - Fetch corporate actions for a ticker. - - Args: - ticker: Stock ticker (e.g., 'pko', 'cdr') - firecrawl_scrape_func: The firecrawl scraping function to use - - Returns: - DataFrame with columns: - - Date: Action date - - Event: Event type (English) - - Event_PL: Event type (Polish) - - Nominal: Nominal value - - Divisor: Adjustment divisor - - Pct: Percentage (from event name) - """ - # Normalize ticker - ticker = self._normalize_ticker(ticker) - - # Check cache first - if self.use_cache: - cached = self._load_from_cache(ticker) - if cached is not None: - print(f"[Stooq CA] Using cached data for {ticker}") - return cached - - # Fetch from Firecrawl - url = f"https://stooq.pl/q/m/?s={ticker}" - - print(f"[Stooq CA] Fetching corporate actions for {ticker} via Firecrawl...") - - try: - result = firecrawl_scrape_func(url, formats=['markdown']) - markdown = result.get('markdown', '') - - # Parse markdown table - df = self._parse_markdown_table(markdown) - - if df.empty: - print(f"[Stooq CA] No corporate actions found for {ticker}") - else: - print(f"[Stooq CA] Found {len(df)} corporate actions for {ticker}") - print(f" Types: {df['Event'].value_counts().to_dict()}") - - # Cache result - if self.use_cache: - self._save_to_cache(ticker, df) - - return df - - except Exception as e: - print(f"[Stooq CA] Error fetching {ticker}: {e}") - return pd.DataFrame(columns=['Date', 'Event', 'Event_PL', 'Nominal', 'Divisor', 'Pct']) - - def _parse_markdown_table(self, markdown: str) -> pd.DataFrame: - """ - Parse corporate actions table from markdown. - - Expected format: - | Data | Zdarzenie | Nominalnie | Dzielnik | - | pon, 4 sie 2025 | Dywidenda 6.75% | 5.48 | 1.07241015 | - """ - rows = [] - - # Find all table rows with pipe separators - lines = markdown.split('\n') - in_table = False - - for line in lines: - # Skip header and separator lines - if '| Data |' in line or '| --- |' in line or '|---' in line: - in_table = True - continue - - if not in_table: - continue - - # Parse data row - if line.strip().startswith('|') and line.count('|') >= 4: - parts = [p.strip() for p in line.split('|')] - - # Filter empty parts - parts = [p for p in parts if p] - - if len(parts) >= 4: - date_str = parts[0] - event_str = parts[1] - nominal_str = parts[2] - divisor_str = parts[3] - - # Skip if this looks like a header - if 'Data' in date_str or 'Zdarzenie' in event_str: - continue - - try: - # Parse date - date = self._parse_polish_date(date_str) - - # Parse event type and percentage - event_pl, pct = self._parse_event(event_str) - event_en = self.EVENT_TYPES.get(event_pl, event_pl) - - # Parse numeric values - nominal = float(nominal_str.replace(',', '.')) if nominal_str and nominal_str != '-' else None - divisor = float(divisor_str.replace(',', '.')) if divisor_str and divisor_str != '-' else None - - rows.append({ - 'Date': date, - 'Event': event_en, - 'Event_PL': event_pl, - 'Nominal': nominal, - 'Divisor': divisor, - 'Pct': pct - }) - except Exception as e: - print(f"[Stooq CA] Warning: Could not parse row: {parts[:2]} - {e}") - continue - - if not rows: - return pd.DataFrame(columns=['Date', 'Event', 'Event_PL', 'Nominal', 'Divisor', 'Pct']) - - df = pd.DataFrame(rows) - df = df.sort_values('Date').reset_index(drop=True) - return df - - def _parse_polish_date(self, date_str: str) -> pd.Timestamp: - """ - Parse Polish date string. - - Examples: - "pon, 4 sie 2025" -> 2025-08-04 - "śro, 7 sie 2024" -> 2024-08-07 - """ - # Polish month abbreviations - months = { - 'sty': 1, 'lut': 2, 'mar': 3, 'kwi': 4, 'maj': 5, 'cze': 6, - 'lip': 7, 'sie': 8, 'wrz': 9, 'paź': 10, 'paz': 10, 'lis': 11, 'gru': 12 - } - - # Extract day, month, year: "day_name, day month year" - parts = date_str.split(',') - if len(parts) >= 2: - date_parts = parts[1].strip().split() - if len(date_parts) >= 3: - day = int(date_parts[0]) - month_str = date_parts[1] - year = int(date_parts[2]) - - month = months.get(month_str, 1) - - return pd.Timestamp(year=year, month=month, day=day) - - raise ValueError(f"Cannot parse date: {date_str}") - - def _parse_event(self, event_str: str) -> tuple: - """ - Parse event string to extract type and percentage. - - Examples: - "Dywidenda 6.75%" -> ("Dywidenda", 6.75) - "Prawo Poboru 7.72%" -> ("Prawo Poboru", 7.72) - "Split" -> ("Split", None) - """ - # Extract percentage if present - pct_match = re.search(r'(\d+\.?\d*)\s*%', event_str) - pct = float(pct_match.group(1)) if pct_match else None - - # Remove percentage from event type - event_type = re.sub(r'\s+\d+\.?\d*\s*%', '', event_str).strip() - - return event_type, pct - - def _normalize_ticker(self, ticker: str) -> str: - """Normalize ticker (lowercase, no .pl suffix)""" - if ticker.lower().endswith('.pl'): - ticker = ticker[:-3] - return ticker.lower() - - def _load_from_cache(self, ticker: str) -> Optional[pd.DataFrame]: - """Load corporate actions from cache if fresh enough""" - cache_file = self.cache_dir / f'{ticker}.pkl' - - if not cache_file.exists(): - return None - - # Check age - age_hours = (datetime.now() - datetime.fromtimestamp(cache_file.stat().st_mtime)).total_seconds() / 3600 - - if age_hours > self.cache_hours: - return None - - try: - with open(cache_file, 'rb') as f: - return pickle.load(f) - except Exception as e: - print(f"[Stooq CA] Warning: Cache read error for {ticker}: {e}") - return None - - def _save_to_cache(self, ticker: str, df: pd.DataFrame): - """Save corporate actions to cache""" - cache_file = self.cache_dir / f'{ticker}.pkl' - - try: - with open(cache_file, 'wb') as f: - pickle.dump(df, f) - except Exception as e: - print(f"[Stooq CA] Warning: Cache write error for {ticker}: {e}") - - def calculate_adjusted_prices(self, prices: pd.DataFrame, ticker: str, - firecrawl_scrape_func) -> pd.DataFrame: - """ - Calculate adjusted prices using corporate actions. - - Args: - prices: DataFrame with Date and Close columns - ticker: Stock ticker - firecrawl_scrape_func: Firecrawl scraping function - - Returns: - DataFrame with Close_Adj column added - - Methodology: - - Fetch corporate actions - - Apply divisors cumulatively from latest to earliest - - Adjusted_Price(t) = Unadjusted_Price(t) / Cumulative_Divisor(t) - """ - print(f"\n[Stooq CA] Calculating adjusted prices for {ticker}...") - - # Fetch corporate actions - ca = self.fetch(ticker, firecrawl_scrape_func) - - if ca.empty: - print(f" No corporate actions, returning unadjusted prices") - prices = prices.copy() - prices['Close_Adj'] = prices['Close'] - return prices - - # Ensure dates are datetime - prices = prices.copy() - prices['Date'] = pd.to_datetime(prices['Date']) - ca['Date'] = pd.to_datetime(ca['Date']) - - # Get all unique dates - all_dates = pd.DataFrame({ - 'Date': sorted(set(prices['Date'].tolist() + ca['Date'].tolist())) - }) - - # Merge corporate actions - all_dates = all_dates.merge(ca[['Date', 'Divisor']], on='Date', how='left') - - # Fill missing divisors with 1.0 (no adjustment) - all_dates['Divisor'] = all_dates['Divisor'].fillna(1.0) - - # Calculate cumulative divisor from LATEST date backwards - # This ensures latest prices remain unadjusted - all_dates = all_dates.sort_values('Date', ascending=False) - all_dates['Cumulative_Divisor'] = all_dates['Divisor'].cumprod() - all_dates = all_dates.sort_values('Date') - - # Merge with prices - result = prices.merge(all_dates[['Date', 'Cumulative_Divisor']], on='Date', how='left') - - # Fill any missing cumulative divisors - result['Cumulative_Divisor'] = result['Cumulative_Divisor'].fillna(1.0) - - # Calculate adjusted close - result['Close_Adj'] = result['Close'] / result['Cumulative_Divisor'] - - print(f" Applied {len(ca)} corporate actions") - print(f" Adjustment range: {result['Cumulative_Divisor'].min():.6f} to {result['Cumulative_Divisor'].max():.6f}") - - # Return with standard columns - return result[['Date', 'Open', 'High', 'Low', 'Close', 'Close_Adj', 'Volume']] - - -# Convenience functions for use in other scripts - -def fetch_corporate_actions(ticker: str, firecrawl_scrape_func, use_cache: bool = True) -> pd.DataFrame: - """ - Fetch corporate actions for a ticker. - - Args: - ticker: Stock ticker (e.g., 'pko') - firecrawl_scrape_func: Firecrawl scraping function - use_cache: Whether to use caching - - Returns: - DataFrame with corporate actions - """ - fetcher = StooqCorporateActionsFirecrawl(use_cache=use_cache) - return fetcher.fetch(ticker, firecrawl_scrape_func) - - -def calculate_adjusted_prices(prices: pd.DataFrame, ticker: str, - firecrawl_scrape_func, use_cache: bool = True) -> pd.DataFrame: - """ - Calculate adjusted prices using corporate actions. - - Args: - prices: DataFrame with Date, Close columns - ticker: Stock ticker - firecrawl_scrape_func: Firecrawl scraping function - use_cache: Whether to use caching - - Returns: - DataFrame with Close_Adj column added - """ - fetcher = StooqCorporateActionsFirecrawl(use_cache=use_cache) - return fetcher.calculate_adjusted_prices(prices, ticker, firecrawl_scrape_func) diff --git a/claude/skills/quant/market-datasets/scripts/fetch_unified.py b/claude/skills/quant/market-datasets/scripts/fetch_unified.py index bb1e69f6..b0099924 100644 --- a/claude/skills/quant/market-datasets/scripts/fetch_unified.py +++ b/claude/skills/quant/market-datasets/scripts/fetch_unified.py @@ -17,6 +17,11 @@ - Security master registry (ISIN lookup, ticker conversion) - Fallback logic if primary source fails +Polish instruments route to EODHD first (``.WAR`` listings, ``.INDX`` +indices) when EODHD_API_KEY is set, else Yahoo (``.WA``); PLN FX goes to NBP +first, then Yahoo. Stooq was removed as a source on 2026-09-30 (see +REMOVED_SOURCES) — asking for it raises ValueError. + Usage: uv run fetch_unified.py PKO 2024-01-01 2024-12-31 uv run fetch_unified.py PLXTRDM00011 2024-01-01 # ISIN lookup @@ -37,14 +42,27 @@ except ImportError: REGISTRY_AVAILABLE = False -# Import all fetchers -try: - from fetch_stooq import StooqFetcher +# Sources that existed once and were deliberately removed. Asking for one is an +# error with the reason, never a silent reroute to another source. +REMOVED_SOURCES = { + "stooq": ( + "stooq was removed from market-datasets on 2026-09-30: it blocks " + "datacenter IPs (Hetzner, since 2026-04-21) and serves a JavaScript " + "browser challenge to any non-browser client, so no agent or LLM " + "session can fetch from it. Use source='eodhd' (GPW '.WAR', indices " + "'.INDX') or source='yahoo' ('.WA') for Polish instruments, and " + "source='nbp' for PLN FX." + ), +} - STOOQ_AVAILABLE = True -except ImportError: - STOOQ_AVAILABLE = False +def _reject_removed_source(source: Optional[str]) -> None: + """Raise ValueError naming why a removed source is gone.""" + if source and source.lower() in REMOVED_SOURCES: + raise ValueError(REMOVED_SOURCES[source.lower()]) + + +# Import all fetchers try: from fetch_nbp import NBPFetcher @@ -100,12 +118,19 @@ def is_crypto_symbol(s): FINANCIALDATA_AVAILABLE = False try: - from fetch_eodhd import EODHDFetcher + from fetch_eodhd import EODHDFetcher, eodhd_symbol EODHD_AVAILABLE = True except ImportError: EODHD_AVAILABLE = False + def eodhd_symbol(ticker): + """Fallback if fetch_eodhd is not importable (only used when routed).""" + t = ticker.strip() + if t.startswith("^"): + return t[1:] + ".INDX" + return t[:-3] + ".WAR" if t.endswith(".WA") else t + try: from fetch_coingecko import CoinGeckoFetcher @@ -133,10 +158,9 @@ class UnifiedMarketDataFetcher: "dnp", "cps", "jsw", - "pzu", "tpe", "mil", - "orange", + "opl", ] # Polish indices @@ -211,9 +235,6 @@ def __init__( # Initialize available fetchers self.fetchers = {} - if STOOQ_AVAILABLE: - self.fetchers["stooq"] = StooqFetcher(use_cache, cache_hours) - if NBP_AVAILABLE: self.fetchers["nbp"] = NBPFetcher(use_cache, cache_hours) @@ -254,10 +275,10 @@ def __init__( "[Unified] FinancialData.Net API key not configured, FinancialData unavailable" ) - # Initialize EODHD (requires API key). OPT-IN, not auto-routed: keep - # Yahoo primary for ad-hoc to avoid burning paid EODHD calls. Use it - # deliberately via source='eodhd' — it's the right call for UCITS/ETF, - # GPW (.WAR), and datacenter hosts where Stooq/Yahoo are blocked. + # Initialize EODHD (requires API key). Auto-routed FIRST for Polish + # instruments only (GPW '.WAR', indices '.INDX'); everything else keeps + # Yahoo primary to avoid burning paid calls — use source='eodhd' + # deliberately for UCITS/ETF and datacenter hosts where Yahoo is blocked. if EODHD_AVAILABLE: try: self.fetchers["eodhd"] = EODHDFetcher(eodhd_api_key, use_cache, cache_hours) @@ -302,6 +323,8 @@ def fetch( Raises: ValueError: If no suitable source found or data retrieval fails """ + _reject_removed_source(source) + # Try to resolve identifier via registry security = None if self.registry: @@ -325,7 +348,7 @@ def fetch( sources, ticker_map = self._route_security(security) else: sources = self._route_ticker(identifier) - ticker_map = {s: identifier for s in sources} + ticker_map = {s: self._ticker_for_source(identifier, s) for s in sources} print(f"[Unified] Routing '{identifier}' -> {', '.join(sources)}") @@ -360,31 +383,29 @@ def _route_security(self, security) -> Tuple[List[str], dict]: instrument_type = security.instrument_type - # Define source priority based on instrument type and geography - if instrument_type == "equity": - if security.country == "PL": - # Polish stocks: Stooq has best coverage, Yahoo as fallback - priority = ["stooq", "yahoo", "pdr"] - else: - # International stocks: Yahoo first - priority = ["yahoo", "stooq", "pdr"] - - elif instrument_type == "index": - if security.country == "PL": - priority = ["stooq", "yahoo", "pdr"] - else: - priority = ["yahoo", "stooq", "pdr"] + # Define source priority based on instrument type and geography. + # A GPW listing (country PL, or any instrument on the WSE) goes to + # EODHD first — skipped when no key is set, since the fetcher is then + # absent — and falls back to Yahoo. + polish = security.country == "PL" or security.exchange == "WSE" + if instrument_type == "index" and polish: + # EODHD only: Yahoo serves no history for WSE indices (see + # _route_ticker). With no key the source list is empty and the + # fetch fails loudly rather than returning Yahoo's empty frame. + priority = ["eodhd"] + elif instrument_type in ("equity", "etf") and polish: + priority = ["eodhd", "yahoo", "pdr"] elif instrument_type == "currency": - # FX pairs: NBP for PLN rates, Stooq for others + # FX pairs: NBP for PLN rates, then Yahoo if security.uid and "PLN" in security.uid: - priority = ["nbp", "stooq", "yahoo"] + priority = ["nbp", "yahoo"] else: - priority = ["stooq", "yahoo", "pdr"] + priority = ["yahoo", "pdr"] else: - # Default priority - priority = ["yahoo", "stooq", "pdr"] + # International stocks, indices and everything else: Yahoo first + priority = ["yahoo", "pdr"] # Build source list and ticker map based on available tickers for src in priority: @@ -392,6 +413,13 @@ def _route_security(self, security) -> Tuple[List[str], dict]: continue ticker = security.get_ticker(src) + if not ticker and src == "eodhd" and security.get_ticker("yahoo"): + # No EODHD column in the registry: derive it from the Yahoo + # ticker (XTB.WA -> XTB.WAR, ^WIG20 -> WIG20.INDX). + ticker = eodhd_symbol(security.get_ticker("yahoo")) + if not ticker and src == "yahoo" and security.instrument_type == "currency": + if security.uid and security.uid.startswith("fx_"): + ticker = f"{security.uid[3:]}=X" # fx_USDPLN -> USDPLN=X if ticker: sources.append(src) ticker_map[src] = ticker @@ -403,6 +431,13 @@ def _route_security(self, security) -> Tuple[List[str], dict]: sources.append(src) ticker_map[src] = currency + if not sources and instrument_type == "index" and polish: + raise ValueError( + f"Polish index {security.uid!r} needs EODHD (set EODHD_API_KEY) - Yahoo " + "serves no history for WSE indices. Keyless alternative: the " + "gpw-benchmark-scraper skill (GPW Benchmark chart-json)." + ) + # If no tickers found, fallback to ISIN or uid if not sources: sources = list(self.fetchers.keys()) @@ -428,26 +463,43 @@ def _route_ticker(self, ticker: str) -> List[str]: if is_crypto_symbol(ticker) and "ccxt" in self.fetchers: return ["ccxt"] - # Check for Polish stocks + # A WSE index may arrive as ``^WIG20`` or ``WIG20.INDX`` too; normalise + # before the check so no spelling slips through to the ``^`` -> Yahoo branch. + index_key = self._polish_index_key(ticker_lower) + + # Polish INDICES: EODHD only. Yahoo has no history for them (probed + # 2026-09-30: ^WIG20 / ^MWIG40 return 0 rows, WIG20.WA / WIG.WA one + # row), and stooq is gone, so without an EODHD key this raises rather + # than returning an empty frame that reads like "no data for the range". + if index_key in self.POLISH_INDICES: + if "eodhd" not in self.fetchers: + raise ValueError( + f"Polish index {ticker!r} needs EODHD ({index_key.upper()}.INDX; set " + "EODHD_API_KEY) - Yahoo serves no history for WSE indices. Keyless " + "alternative: the gpw-benchmark-scraper skill (GPW Benchmark " + "chart-json, about 1 year per request)." + ) + return ["eodhd"] + + # Polish stocks: EODHD first (when a key is set), Yahoo (.WA) as the + # keyless fallback. Tickers are translated per source by + # _ticker_for_source. if ticker_lower in self.POLISH_STOCKS: - # Stooq is best for Polish stocks, Tiingo as fallback for dividends - sources = ["stooq", "yahoo"] + sources = self._polish_sources() if "tiingo" in self.fetchers: sources.append("tiingo") sources.append("pdr") return sources - # Check for Polish indices - if ticker_lower in self.POLISH_INDICES: - return ["stooq", "yahoo", "pdr"] - # Check for NBP currency request (direct 3-letter code) if ticker_upper in self.NBP_CURRENCIES and NBP_AVAILABLE: - return ["nbp", "stooq", "yahoo"] + return ["nbp", "yahoo"] # Check for currency pairs (e.g., USDPLN, EURUSD) if re.match(r"^[A-Z]{6}$", ticker_upper): # 6-letter currency pair - return ["stooq", "yahoo", "pdr"] + if ticker_upper.endswith("PLN") and "nbp" in self.fetchers: + return ["nbp", "yahoo", "pdr"] + return ["yahoo", "pdr"] # Check for FRED series for pattern in self.FRED_PATTERNS: @@ -457,7 +509,7 @@ def _route_ticker(self, ticker: str) -> List[str]: # Check for international indices (^SPX, ^IXIC, ^BCOM, etc.) if ticker.startswith("^"): - return ["yahoo", "stooq", "pdr"] + return ["yahoo", "pdr"] # Check for US stocks / ETFs (all caps, short). if ticker.isupper() and 1 <= len(ticker) <= 5: @@ -466,22 +518,23 @@ def _route_ticker(self, ticker: str) -> List[str]: sources.append("tiingo") if "financialdata" in self.fetchers: sources.append("financialdata") - sources.extend(["pdr", "stooq"]) + sources.append("pdr") return sources - # Check for explicit market suffix (.WA, .US, .L, .LSE, etc.) + # Check for explicit market suffix (.WA, .WAR, .US, .L, .LSE, etc.) if "." in ticker: suffix = ticker.split(".")[-1].upper() - if suffix == "WA": # Warsaw Stock Exchange - return ["yahoo", "stooq", "pdr"] - else: - sources = ["yahoo"] - if "tiingo" in self.fetchers: - sources.append("tiingo") - if "financialdata" in self.fetchers: - sources.append("financialdata") - sources.extend(["pdr", "stooq"]) - return sources + if suffix in ("WA", "WAR"): # Warsaw Stock Exchange + return self._polish_sources() + ["pdr"] + if suffix == "INDX" and "eodhd" in self.fetchers: + return ["eodhd"] + sources = ["yahoo"] + if "tiingo" in self.fetchers: + sources.append("tiingo") + if "financialdata" in self.fetchers: + sources.append("financialdata") + sources.append("pdr") + return sources # Default fallback order (Yahoo first, Tiingo and FinancialData as backup). sources = ["yahoo"] @@ -489,9 +542,72 @@ def _route_ticker(self, ticker: str) -> List[str]: sources.append("tiingo") if "financialdata" in self.fetchers: sources.append("financialdata") - sources.extend(["stooq", "pdr"]) + sources.append("pdr") return sources + @staticmethod + def _polish_index_key(ticker_lower: str) -> str: + """Every spelling of a WSE index reduced to its bare name. + + ``^WIG20``, ``WIG20.INDX``, ``WIG20.WA`` and ``WIG20.WAR`` all mean the + index; left unnormalised, the caret or suffix spellings slip past the + index check into the ``^`` / ``.WA`` branches and reach Yahoo, which has + no history for WSE indices. + """ + key = ticker_lower.strip().lower().lstrip("^") + for suffix in (".indx", ".war", ".wa"): + if key.endswith(suffix): + return key[: -len(suffix)] + return key + + def _polish_sources(self) -> List[str]: + """EODHD first when its key is configured, then Yahoo.""" + return (["eodhd"] if "eodhd" in self.fetchers else []) + ["yahoo"] + + def _ticker_for_source(self, identifier: str, source: str) -> str: + """Translate a bare/suffixed identifier into ``source``'s ticker format. + + - Polish stock ``pko`` / ``PKO.WA`` / ``PKO.WAR`` -> EODHD ``PKO.WAR``, + Yahoo ``PKO.WA`` + - Polish index ``wig20`` -> EODHD ``WIG20.INDX`` (EODHD only, see _route_ticker) + - FX pair ``USDPLN`` -> NBP ``USD``, Yahoo ``USDPLN=X`` (``EURUSD=X``) + Anything else passes through unchanged. + """ + t = identifier.strip() + low, up = t.lower(), t.upper() + + if self._polish_index_key(low) in self.POLISH_INDICES: + low = self._polish_index_key(low) + up = low.upper() + if source == "eodhd": + return f"{up}.INDX" + if source in ("yahoo", "pdr"): + return f"^{up}" + return t + if low in self.POLISH_STOCKS: + if source == "eodhd": + return f"{up}.WAR" + if source in ("yahoo", "tiingo", "pdr"): + return f"{up}.WA" + return t + if up.endswith(".WAR"): + if source in ("yahoo", "pdr"): + return t[:-4] + ".WA" + return t + if up.endswith(".WA"): + if source == "eodhd": + return eodhd_symbol(t) + return t + if re.match(r"^[A-Z]{6}$", up): # FX pair + if source == "nbp" and up.endswith("PLN"): + return up[:3] + if source == "yahoo": + return f"{up}=X" + return t + if up in self.NBP_CURRENCIES and source == "yahoo": + return f"{up}PLN=X" + return t + def _fetch_from_source( self, source: str, @@ -513,6 +629,7 @@ def _fetch_from_source( Returns: DataFrame with market data """ + _reject_removed_source(source) if source not in self.fetchers: raise ValueError(f"Source '{source}' not available") @@ -540,7 +657,7 @@ def _fetch_from_source( return fetcher.fetch(ticker, start_date, end_date, endpoint=endpoint, **kwargs) else: - # Standard fetchers (stooq, yahoo, fred, tiingo) + # Standard fetchers (yahoo, eodhd, fred, tiingo) return fetcher.fetch(ticker, start_date, end_date, **kwargs) def compare_sources( @@ -641,7 +758,7 @@ def fetch_market_data( print(f"Registry loaded: {len(fetcher.registry._securities)} securities") print() - # Test 1: Polish stock (should route to Stooq) + # Test 1: Polish stock (should route to EODHD with a key, else Yahoo) print("1. Fetching PKO (Polish stock by ticker):") try: df = fetcher.fetch("pko", start_date="20240101", end_date="20240131") @@ -677,7 +794,7 @@ def fetch_market_data( except Exception as e: print(f" Error: {e}") - # Test 5: Index (should route to Yahoo or Stooq) + # Test 5: Index (should route to Yahoo) print("\n5. Fetching ^GSPC (S&P 500):") try: df = fetcher.fetch("^GSPC", start_date="20240101", end_date="20240131") @@ -701,7 +818,7 @@ def fetch_market_data( print("\n7. Comparing PKO from different sources:") try: comparison = fetcher.compare_sources( - "pko", ["stooq", "yahoo"], start_date="20240115", end_date="20240119" + "PKO.WA", ["eodhd", "yahoo"], start_date="20240115", end_date="20240119" ) for source, df in comparison.items(): if df is not None: diff --git a/claude/skills/quant/market-datasets/scripts/migrate_to_project.py b/claude/skills/quant/market-datasets/scripts/migrate_to_project.py index 252a9b4b..660950fe 100644 --- a/claude/skills/quant/market-datasets/scripts/migrate_to_project.py +++ b/claude/skills/quant/market-datasets/scripts/migrate_to_project.py @@ -12,7 +12,7 @@ making them available for production use. Usage: - uv run migrate_to_project.py stooq --target src/data_sources/ + uv run migrate_to_project.py eodhd --target src/data_sources/ uv run migrate_to_project.py yahoo --target src/market_data/ --include-utils uv run migrate_to_project.py all --target src/fetchers/ --include-utils --include-env uv run migrate_to_project.py --list # List available sources @@ -28,8 +28,7 @@ # Source to file mapping SOURCE_MAP: Dict[str, List[str]] = { - 'stooq': ['fetch_stooq.py'], - 'stooq-corporate': ['fetch_stooq_corporate_actions.py', 'fetch_stooq_corporate_actions_firecrawl.py'], + 'eodhd': ['fetch_eodhd.py'], 'yahoo': ['fetch_yahoo.py'], 'yahoo-direct': ['fetch_yahoo_direct.py'], 'nbp': ['fetch_nbp.py'], @@ -41,7 +40,7 @@ 'unified': ['fetch_unified.py'], 'all': [ 'fetch_unified.py', - 'fetch_stooq.py', + 'fetch_eodhd.py', 'fetch_yahoo.py', 'fetch_yahoo_direct.py', 'fetch_nbp.py', @@ -58,8 +57,8 @@ ENV_KEYS: Dict[str, List[str]] = { 'tiingo': ['TIINGO_API_KEY'], 'fred': ['FRED_API_KEY'], - 'stooq-corporate': ['FIRECRAWL_API_KEY'], - 'all': ['TIINGO_API_KEY', 'FRED_API_KEY', 'FIRECRAWL_API_KEY'], + 'eodhd': ['EODHD_API_KEY'], + 'all': ['TIINGO_API_KEY', 'FRED_API_KEY', 'EODHD_API_KEY'], } diff --git a/claude/skills/quant/market-datasets/scripts/ticker_registry.py b/claude/skills/quant/market-datasets/scripts/ticker_registry.py index ab74f35f..7fbfc9ec 100644 --- a/claude/skills/quant/market-datasets/scripts/ticker_registry.py +++ b/claude/skills/quant/market-datasets/scripts/ticker_registry.py @@ -10,11 +10,12 @@ Ticker Registry - Security master and cross-source ticker mapping service. Provides unified lookup for converting between different ticker formats -across data sources (Bloomberg, Yahoo, Stooq, FRED, NBP). +across data sources (Bloomberg, Yahoo, FRED, NBP; EODHD symbols are derived +from the Yahoo ticker by fetch_eodhd.eodhd_symbol). Usage: uv run ticker_registry.py lookup PLXTRDM00011 - uv run ticker_registry.py convert XTB.WA stooq + uv run ticker_registry.py convert XTB.WA bloomberg uv run ticker_registry.py discover PLXTRDM00011 US0378331005 uv run ticker_registry.py # Run self-tests @@ -28,7 +29,7 @@ yahoo_ticker = registry.isin_to_ticker('PLXTRDM00011', source='yahoo') # 'XTB.WA' # Convert any ticker to another format - stooq_ticker = registry.convert_ticker('PKO.WA', to_source='stooq') # 'pko' + bbg_ticker = registry.convert_ticker('^MWIG40', to_source='bloomberg') # 'MWIG40 Index' # Auto-discover missing Yahoo tickers discovered = registry.discover_missing_yahoo_tickers(['PLXTRDM00011']) @@ -42,7 +43,13 @@ import csv # Type definitions -SourceType = Literal['bloomberg', 'yahoo', 'stooq', 'fred', 'nbp'] +SourceType = Literal['bloomberg', 'yahoo', 'fred', 'nbp'] + +# Columns the CSV schema keeps for other readers but no fetcher uses: loaded +# into Security.legacy and written back unchanged, never indexed or routed. +# ticker_stooq: legacy column — stooq was removed as a source on 2026-09-30. +LEGACY_COLUMNS = ('ticker_stooq',) + InstrumentType = Literal['equity', 'index', 'currency', 'bond', 'commodity', 'etf'] @@ -59,6 +66,7 @@ class Security: metadata: Dict[str, str] = field(default_factory=dict) last_updated: Optional[datetime] = None mapping_source: str = "unknown" + legacy: Dict[str, str] = field(default_factory=dict) # LEGACY_COLUMNS, pass-through @property def primary_key(self) -> str: @@ -80,7 +88,7 @@ def to_dict(self) -> dict: 'exchange': self.exchange, 'ticker_bloomberg': self.tickers.get('bloomberg', ''), 'ticker_yahoo': self.tickers.get('yahoo', ''), - 'ticker_stooq': self.tickers.get('stooq', ''), + **{col: self.legacy.get(col, '') for col in LEGACY_COLUMNS}, 'ticker_fred': self.tickers.get('fred', ''), 'sector': self.metadata.get('sector', ''), 'currency': self.metadata.get('currency', ''), @@ -92,7 +100,7 @@ def to_dict(self) -> dict: def from_dict(cls, d: dict) -> 'Security': """Create Security from dictionary (CSV row).""" tickers = {} - for source in ['bloomberg', 'yahoo', 'stooq', 'fred']: + for source in ['bloomberg', 'yahoo', 'fred']: key = f'ticker_{source}' if d.get(key): tickers[source] = d[key] @@ -120,7 +128,8 @@ def from_dict(cls, d: dict) -> 'Security': tickers=tickers, metadata=metadata, last_updated=last_updated, - mapping_source=d.get('mapping_source', 'csv') + mapping_source=d.get('mapping_source', 'csv'), + legacy={col: d[col] for col in LEGACY_COLUMNS if d.get(col)}, ) @@ -135,7 +144,7 @@ class TickerRegistry: - Single CSV file as both master and cache """ - # CSV columns in order + # CSV columns in order — the schema other repos read; see LEGACY_COLUMNS CSV_COLUMNS = [ 'uid', 'isin', 'name', 'instrument_type', 'country', 'exchange', 'ticker_bloomberg', 'ticker_yahoo', 'ticker_stooq', 'ticker_fred', @@ -194,11 +203,6 @@ def get_security(self, identifier: str) -> Optional[Security]: if primary_key: return self._securities.get(primary_key) - # Try lowercase for Stooq - primary_key = self._ticker_index.get(identifier.lower()) - if primary_key: - return self._securities.get(primary_key) - return None def convert_ticker( @@ -355,8 +359,6 @@ def register_security(self, security: Security) -> None: for source, ticker in security.tickers.items(): if ticker: self._ticker_index[ticker.upper()] = uid - if source == 'stooq': - self._ticker_index[ticker.lower()] = uid def add_ticker_mapping( self, @@ -544,11 +546,6 @@ def isin_to_yahoo(isin: str) -> Optional[str]: return get_default_registry().isin_to_ticker(isin, source='yahoo') -def isin_to_stooq(isin: str) -> Optional[str]: - """Convert ISIN to Stooq ticker.""" - return get_default_registry().isin_to_ticker(isin, source='stooq') - - def ticker_to_isin(ticker: str) -> Optional[str]: """Get ISIN for any ticker.""" return get_default_registry().ticker_to_isin(ticker) diff --git a/claude/skills/quant/market-datasets/scripts/utils.py b/claude/skills/quant/market-datasets/scripts/utils.py index fc451e07..3997d687 100644 --- a/claude/skills/quant/market-datasets/scripts/utils.py +++ b/claude/skills/quant/market-datasets/scripts/utils.py @@ -74,7 +74,7 @@ def get_cache_path(self, source: str, identifier: str, format: str = "csv") -> P Get cache file path for a data request. Args: - source: Data source name (stooq, nbp, yahoo, fred) + source: Data source name (nbp, yahoo, eodhd, fred, ...) identifier: Unique identifier (e.g., ticker_start_end) format: File format (csv, json) @@ -243,13 +243,6 @@ def standardize_dataframe(df: pd.DataFrame, source: str) -> pd.DataFrame: # Column mapping from various sources column_mapping = { - # Stooq (Polish) - "Data": "Date", - "Otwarcie": "Open", - "Najwyzszy": "High", - "Najnizszy": "Low", - "Zamkniecie": "Close", - "Wolumen": "Volume", # Common English "date": "Date", "open": "Open", diff --git a/docs/playbooks/investment-research-workflow.md b/docs/playbooks/investment-research-workflow.md index 75d3aa09..de17547e 100644 --- a/docs/playbooks/investment-research-workflow.md +++ b/docs/playbooks/investment-research-workflow.md @@ -36,7 +36,7 @@ what the question needs before any code: ### Phase 2: Gather Data Fetch relevant data using `market-datasets`: -- Price data from Stooq/Yahoo/CCXT +- Price data from EODHD/Yahoo/CCXT - Fundamentals from relevant sources - Fund data from analizy.pl if Polish funds @@ -87,7 +87,7 @@ Promote from `scratch/` to `research/{study-name}/` with co-located scripts, dat ``` 1. /research line momentum-pl (qute-research) -2. Fetch 5-year monthly returns from Stooq for WIG components +2. Fetch 5-year monthly returns from EODHD (`.WAR`) for WIG components 3. Fetch fund NAVs from analizy.pl for equity funds 4. /paper-reading on Jegadeesh & Titman (1993), local momentum studies 5. Build factor portfolios in scratch/momentum-pl/ diff --git a/docs/playbooks/research-to-production.md b/docs/playbooks/research-to-production.md index fdbe6782..3a3173a9 100644 --- a/docs/playbooks/research-to-production.md +++ b/docs/playbooks/research-to-production.md @@ -69,7 +69,7 @@ Auto-routes to the right source: | Pattern | Source | Coverage | |---------|--------|----------| | US tickers | Yahoo Finance | Stocks, ETFs, indices | -| `.PL` suffix | Stooq | Warsaw Stock Exchange | +| `.WA` / `.WAR` suffix | EODHD (`.WAR`), Yahoo (`.WA`) for stocks | Warsaw Stock Exchange (stooq removed 2026-09-30 — unreachable from datacenters) | | Macro series | FRED | GDP, CPI, rates, employment | | Crypto pairs | Binance | Spot and futures | | Fundamentals | FinancialData.Net | Financials, ratios, options, insider | @@ -93,7 +93,7 @@ backfill_part = shiller[shiller.index < splice_date] equity = pd.concat([backfill_part, vfinx]).sort_index() ``` -Standard proxies: VFINX (equity), VBMFX (bonds), Stooq XAUUSD (gold). See `references/long_history_construction.md` in the skill for splice methodology and validation. +Standard proxies: VFINX (equity), VBMFX (bonds), EODHD `XAUUSD.FOREX` (gold, from 1990). See `references/long_history_construction.md` in the skill for splice methodology and validation. ### 4. Explore