diff --git a/CLAUDE.md b/CLAUDE.md index 011e30cc..0faef0d2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,109 +1,4 @@ # qute-code-kit -Tom's **personal skills & templates library** — reusable Claude Code components -under `claude/` (skills, agents, an AGENTS.md starter) and doc templates under -`templates/`. The research scaffold (pin gate, -line template, research-workflow) is qute-research's, not the kit's. Browse and copy what you need into -target repos; a copied skill carries a `PROVENANCE.yaml` stamp (source path, -source commit, each file `tracked` or `forked from , reason: …`). - -**What belongs here: generic skills only.** A skill whose content is bound to -one project lives in that project's repo, which is its master (TOM-1235, -2026-09-28: the dm-evo fund chain moved to dm-evo-lab, `backtest` and -`evo-dm-brand` to dm-evo-core, `brand-rockbridge` to robo-lab). - -**The plugins are NOT here.** `qute-essentials` and `qute-research` live in -`tomlupo/qute-plugins`, with their marketplace, release tooling and ADRs -(`docs/adr/` here is a pointer). This repo has no release cadence — do not add -plugin manifests, marketplace files, or `/ship` release wiring here. Changes to -guards, hooks, review/release regime, or plugin skills belong in qute-plugins. - -## Layout - -| Path | Contents | -|---|---| -| `claude/skills/` | Generic kit skills, grouped: `quant/`, `engineering/`, `visual/` (`/SKILL.md` + assets) | -| `claude/agents/` | Personal-kit subagents | -| `claude/root-files/` | Root-level AGENTS.md starter | -| `templates/docs/` | Doc starters (PRD, tech spec, user flows) | -| `docs/playbooks/`, `docs/cheatsheets/`, `docs/prompts/` | Workflows, references, reusable prompts | -| `docs/adr/` | Pointer to the plugin ADRs (history in git) | - -## Conventions - -- Conventional Commits with scope (e.g. `feat(skill): ...`, `docs(playbook): ...`). -- Skills are directories containing `SKILL.md`. Agents can be single `.md` files or directories with `AGENT.md`. -- No hardcoded secrets — use `${ENV_VAR}` placeholders. -- This is a curated tree, not a generated one — no build step, no manifests. - -## Adding a kit component - -1. Create the file(s) under the appropriate `claude//` directory. -2. Add a row to the relevant table in `INVENTORY.md`. -3. Commit with Conventional Commits (`feat(skill-name): ...`). - -**The kit is the incubator** (Tom, 2026-09-28). A NEW **generic** skill starts -here — not in a plugin — and is copied by hand into the repos that try it. When it has -become part of a process every repo or lab should run the same way, move it into -a plugin in **qute-plugins** (`qute-essentials`, or `qute-research` for the -research lifecycle), release it there, and delete it here — moving means moving. - -MCP server configs are not kept here (removed 2026-09-28, TOM-1235): a copied -config drifts from the server it describes, and each server's own install docs -are the authority. - -## Skill frontmatter properties - -| Property | Values | Default | Purpose | -|----------|--------|---------|---------| -| `name` | string | directory name | Skill identifier (lowercase, hyphens, max 64 chars) | -| `description` | string | first paragraph | When to use (include trigger phrases) | -| `argument-hint` | string | (none) | Hint shown during autocomplete | -| `user-invocable` | `true` / `false` | `true` | Whether users can invoke via `/skill-name` | -| `disable-model-invocation` | `true` / `false` | `false` | Prevent model from auto-invoking | -| `allowed-tools` | tool names | (all) | Restrict tools when active | -| `model` | model name | (inherit) | Model to use when active | -| `agent` | agent name (e.g. `Explore`) | (none) | Subagent type when `context: fork` is set | -| `context` | `fork` | (none) | Fork context for isolated subagent execution | -| `hooks` | hook config | (none) | Lifecycle hooks scoped to this skill | - -**When to use each:** - -- `disable-model-invocation: true` — user-initiated only (pair it with `agents/openai.yaml` `policy.allow_implicit_invocation: false` so Codex agrees). -- `user-invocable: false` — model-only skills. -- `agent: ` — search/research skills where a subagent protects the main context window. -- `context: fork` — side-output produced in parallel (e.g. memory/summarization). -- `allowed-tools` — read-only or restricted skills. -- `argument-hint` — skills invoked with arguments. - -### Skill dynamic features - -**String substitutions** in skill content: - -| Variable | Description | -|----------|-------------| -| `$ARGUMENTS` | All arguments passed when invoking the skill | -| `$ARGUMENTS[N]` | Specific argument by 0-based index | -| `$N` | Shorthand for `$ARGUMENTS[N]` | -| `${CLAUDE_SESSION_ID}` | Current session ID | - -**Dynamic context injection:** Use `` !`command` `` to run shell commands before skill content is sent to Claude. - -## Agent frontmatter properties - -| Property | Required | Description | -|----------|----------|-------------| -| `name` | Yes | Unique identifier (lowercase, hyphens) | -| `description` | Yes | When Claude should delegate to this agent | -| `tools` | No | Allowed tools (inherits all if omitted) | -| `disallowedTools` | No | Tools to deny from inherited list | -| `model` | No | `sonnet`, `opus`, `haiku`, or `inherit` | -| `permissionMode` | No | `default`, `acceptEdits`, `dontAsk`, `bypassPermissions`, `plan` | -| `skills` | No | Skills preloaded into agent context at startup | -| `hooks` | No | Lifecycle hooks scoped to this agent | - -## Hook events - -`SessionStart`, `UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `Notification`, `SubagentStart`, `SubagentStop`, `Stop`, `PreCompact`, `SessionEnd`. - -Options: `once: true` (run once per session, skills only), `async: true` (non-blocking, command hooks only). +Retired: do not add anything here. The skills, agent and templates are in `tomlupo/qute-plugins` `library/` +(`README.md` says where each went). Change them there. diff --git a/INVENTORY.md b/INVENTORY.md deleted file mode 100644 index 490c40ad..00000000 --- a/INVENTORY.md +++ /dev/null @@ -1,95 +0,0 @@ -# Kit inventory - -Full contents of `claude/` and `templates/`. Use as a map — copy the bits you -want into target repos. See [`README.md`](README.md) for the high-level intro -and copy commands. - -> **Not in this inventory.** The `qute-essentials` plugin (guards, hooks, the -> session loop, `/pr`, `/ship`) and the `qute-research` plugin (the research -> lifecycle: `research`, `finding`, `promote`, `quant-review`) live in -> `tomlupo/qute-plugins`. Skills bound to one project live in that project's -> repo, which is their master: the dm-evo fund-selection chain and -> `etf-universe-screening` in dm-evo-lab, `backtest` and `evo-dm-brand` in -> dm-evo-core, `brand-rockbridge` in robo-lab (moved out 2026-09-28, TOM-1235). - -**What belongs here:** a skill whose content is not bound to one project. -Being used by a single project today is fine; being written for one is not. -A repo that copies a kit skill stamps it with `PROVENANCE.yaml` (source path, -source commit, each file `tracked` or `forked from , reason: …`) so the -copy's drift can be checked. - -## Skills (10, grouped by directory under `claude/skills/`) - -### Quant / data (`quant/`, 5) - -| Name | Description | -|---|---| -| `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 EODHD, NBP, Yahoo, FRED, Tiingo, CCXT, FinancialData (stooq removed 2026-09-30) | -| `pipeline-docs` | 4-doc pattern (instruction / dataset / methodology / reference) | - -### Engineering (`engineering/`, 1) - -| Name | Description | -|---|---| -| `skill-assessment` | Audit every skill in one run against Anthropic's skill engineering guide: categories, a coverage matrix, gaps. The estate-wide half; `/qute-essentials:skills improve` scores and patches one skill (TOM-1126). Kept by decision, 2026-09-29 | - -### Visual / UX (`visual/`, 4) - -| Name | Description | -|---|---| -| `architecture-diagram` | Dark-themed system architecture diagrams as standalone HTML (vendored, Cocoon AI) | -| `image-generator` | Generate and edit images via Google Gemini API | -| `motion-reel` | Motion-graphics films rendered as code: one JS function of time, headless Chrome with motion blur, a numpy score from the same cue sheet, ffmpeg | -| `ui-ux-pro-max` | UI/UX design intelligence for web and mobile (vendored, nextlevelbuilder) | - -### Retired 2026-09-28 (TOM-1235) - -Unused, broken, or covered elsewhere; in git history if ever needed: -`bird-twitter`, `code-quality`, `debug-session`, `excalidraw`, `gist-report`, -`llm-external-review`, `paper-reading`, `python-patterns`, `qrd`, -`quant-review` (qute-research owns it), `sql-patterns`, the `workflow/` bundle -(`grill`, `tdd`, `triage`, `to-prd`, `to-slices`; Matt Pocock's plugin owns -them, and qute-essentials depends on it), `brand-sonte` (archived project). - -### Moved to qute-research 2026-09-28 (TOM-1221) - -`acceptance-gates`, `investment-research` (now its method protocols), -`research-refute`, `-reproduce`, `-robustness`, `-sweep`, `-bakeoff` — see the -qute-research README in `tomlupo/qute-plugins`. On 2026-09-29 the last two -followed: `investment-research-dashboard` is its `research-dashboard` skill (the -`reporting/` library and its contract tests), and `investment-research-formal`'s -METHODOLOGY skeleton, MiFID II mapping and literature note are its -`skills/research/references/methodology-document.md`. The kit carries no research -skills. - -## Agents (1) - -| Name | Description | -|---|---| -| `data-pipeline-debugger` | Debug data pipelines (input/output validation, root-cause tracing) | - -## Root-file starters (1) - -| File | Use case | -|---|---| -| `claude/root-files/AGENTS.md` | Root AGENTS.md starter | - -## Templates - -| Path | Use case | -|---|---| -| `templates/WORKFLOW.md` | Symphony/Elixir-style orchestrator contract (frontmatter + agent prompt routing Matt + qute + docs/agents) | -| `templates/docs/prd-template.md` | Product requirements doc starter | -| `templates/docs/tech-spec-template.md` | Technical specification starter | -| `templates/docs/user-flows-template.md` | User flows / journey starter | - -### Moved to the plugins 2026-09-29 (TOM-1235) - -In `tomlupo/qute-plugins`: the `research-synthesizer` agent (qute-research), -the pyproject and project-settings starters (qute-essentials `onboard`, -`references/starters/`). Deleted as second copies of what the plugins own: the -root `CLAUDE.md` starter, the ADR template, the issue-tracker binding. Retired: -`global-generic.json` (stale). All in git history. diff --git a/README.md b/README.md index 13de2949..de6b48ac 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,13 @@ -# qute-code-kit +# qute-code-kit (retired) -Tom's **personal skills & templates library** for Claude Code — a curated tree -of skills, an agent, doc templates, and playbooks -that you browse and **copy by hand** into target repos. Nothing here installs, -releases, or self-updates. +Retired 2026-11-14 (TOM-3843, TOM-3853). Its skills, agent and templates now live in +[`tomlupo/qute-plugins`](https://github.com/tomlupo/qute-plugins) under `library/`, byte-equal, and this repo +holds no second copy: -> **The plugins are not here.** `qute-essentials` (guards, hooks, the session -> loop, `/pr`, `/ship`) and `qute-research` (the research lifecycle) live in -> [`tomlupo/qute-plugins`](https://github.com/tomlupo/qute-plugins) and install -> from its marketplace; qute-essentials brings Matt Pocock's skills along as a -> dependency. This repo has **no plugin, no marketplace manifest, and no release -> cadence**. +- `claude/skills/{quant,engineering,visual}/*` → `library/skills/{quant,engineering,visual}/*` +- `claude/agents/data-pipeline-debugger.md` → `library/agents/` +- `claude/root-files/AGENTS.md`, `templates/*` → `library/templates/` -## The kit: `claude/` - -10 generic skills (quant/data, engineering, visual/UX), a subagent and an -`AGENTS.md` starter. Browse [`INVENTORY.md`](INVENTORY.md) for the -full map. A skill bound to one project does not live here: its master is that -project's repo (TOM-1235, 2026-09-28). - -**New generic skills start here** — the kit is the incubator; the rule and the -promotion path are in [`CLAUDE.md`](CLAUDE.md). - -Pick what you need and copy it by hand. A copied skill carries a -`PROVENANCE.yaml` (source path, source commit, each file `tracked` or -`forked from , reason: …`) so its drift from the kit can be checked: - -```bash -# Skill — copy the directory, then stamp PROVENANCE.yaml in the copy -cp -r ~/workspace/projects/qute-code-kit/claude/skills/quant/market-datasets ~/projects/myrepo/.claude/skills/ - -# Agent — single file -cp ~/workspace/projects/qute-code-kit/claude/agents/data-pipeline-debugger.md ~/projects/myrepo/.claude/agents/ -``` - -`pyproject.toml` and `.claude/settings.json` starters are not here: `onboard -repo` (qute-essentials) offers them where a repo has none (TOM-1235). - -## Templates: `templates/` - -Doc starters (PRD, tech spec, user flows) and a `WORKFLOW.md` orchestrator -contract. ADRs take their shape from `/decision`, and the tracker binding is -stamped by `onboard repo` — both qute-essentials. The research -scaffold — pin gate, line template, research-workflow — lives in the -qute-research plugin (`templates/research-scaffold/`), stamped by `onboard repo`. - -## Browse - -- [`INVENTORY.md`](INVENTORY.md) — full kit contents (skills / agents / templates) -- [`docs/playbooks/`](docs/playbooks/) — multi-step workflows (compound engineering, multi-agent review, investment research, session continuity, …) -- [`docs/cheatsheets/`](docs/cheatsheets/) — Claude CLI, prompt engineering, XML prompting -- [`docs/prompts/`](docs/prompts/) — reusable prompt patterns -- [`docs/playbooks/skill-router.md`](docs/playbooks/skill-router.md) — which skill, when (the discipline one-pager) -- [`docs/adr/`](docs/adr/) — pointer to the plugin ADRs (history stays in git) -- [`docs/resources.md`](docs/resources.md) — curated external links (interesting repos, tools, reading) - -See [`CLAUDE.md`](CLAUDE.md) for repo conventions. Before committing here, install -[pre-commit](https://pre-commit.com) and [gitleaks](https://github.com/gitleaks/gitleaks), then run -`pre-commit install` — this repo is public. +A repo that stamped a kit skill (`source_repo: qute-code-kit`) re-stamps it against `library/` in qute-plugins. +The plugins (qute-basic, qute-factory, qute-research) were never here. `docs/` (playbooks, prompts, cheatsheets, resources), `CONTEXT.md`, `conductor.yml`, `CHANGELOG.md` +and the history stay as they were, to be read only. The old `INVENTORY.md` is in git history. diff --git a/claude/agents/data-pipeline-debugger.md b/claude/agents/data-pipeline-debugger.md deleted file mode 100644 index 81919f82..00000000 --- a/claude/agents/data-pipeline-debugger.md +++ /dev/null @@ -1,150 +0,0 @@ ---- -name: data-pipeline-debugger -description: Use when a data pipeline produces unexpected results, silent data corruption, or needs validation. Triggered by "data looks wrong", "pipeline is broken", "unexpected output", "validate this transformation", or when debugging ETL, data processing, or analytical pipelines. -tools: ["Read", "Grep", "Glob", "Bash"] -model: sonnet ---- - -You are a data pipeline debugger specializing in tracing data flow, identifying silent corruption, and validating transformations. Your goal is to find where data goes wrong — not just that it's wrong. - -## When Invoked - -1. **Understand the pipeline** — Read the code to map the data flow from input to output -2. **Identify the symptom** — What specific output is wrong? Missing rows? Wrong values? Type errors? -3. **Trace backwards** — Start from the bad output and work back through each transformation -4. **Isolate the stage** — Find the exact step where data goes from correct to incorrect -5. **Diagnose and fix** — Determine root cause and propose a fix - -## Debugging Protocol - -### Step 1: Map the Pipeline - -``` -Input → [Stage 1] → [Stage 2] → ... → [Stage N] → Output -``` - -Read the code and identify: -- Data sources (files, databases, APIs) -- Each transformation step -- Joins, merges, aggregations -- Filters and where data can be dropped -- Output destinations - -### Step 2: Check Dimensions at Each Stage - -For each stage, verify: -- **Row count** — Are rows being unexpectedly added or dropped? -- **Column count** — Are columns missing or duplicated? -- **Data types** — Are types preserved or silently coerced? -- **Null counts** — Are NaNs appearing or disappearing? -- **Unique key counts** — Are duplicates being created by joins? - -Use inspection commands: -```python -# Pandas -df.shape, df.dtypes, df.isnull().sum(), df.duplicated().sum() -df.describe(), df.head(), df['key'].nunique() - -# SQL -SELECT COUNT(*), COUNT(DISTINCT key) FROM table; -SELECT column, COUNT(*) FROM table GROUP BY column HAVING COUNT(*) > 1; -``` - -### Step 3: Validate Transformations - -Common failure modes to check: - -**Joins** -- Inner join dropping rows unexpectedly (mismatched keys) -- Left join creating duplicates (many-to-many relationship) -- Key type mismatch (int vs string, "001" vs 1) -- Timezone-unaware datetime joins - -**Aggregations** -- Wrong groupby columns (too few → over-aggregation, too many → no aggregation) -- NaN values silently excluded from mean/sum -- Mixed types in aggregation column - -**Filters** -- Off-by-one in date ranges (inclusive vs exclusive boundaries) -- NaN not caught by comparison operators (`NaN != NaN`) -- Case sensitivity in string filters - -**Type Coercion** -- Float → int truncation (not rounding) -- String → datetime with mixed formats -- Timezone-naive vs timezone-aware comparisons -- Integer overflow in large datasets - -**Sorting & Indexing** -- Sort not stable (ties resolved differently across runs) -- Index not reset after filter (iloc vs loc confusion) -- MultiIndex alignment issues - -### Step 4: Check Data Quality - -```python -# Quick data quality check -def pipeline_checkpoint(df, stage_name): - print(f"=== {stage_name} ===") - print(f" Shape: {df.shape}") - print(f" Nulls: {df.isnull().sum().to_dict()}") - print(f" Dtypes: {df.dtypes.to_dict()}") - if 'date' in df.columns: - print(f" Date range: {df['date'].min()} to {df['date'].max()}") - print() -``` - -### Step 5: Reproduce Minimally - -- Create a minimal input that reproduces the bug -- Run each stage independently to isolate the failure -- Compare expected vs actual output at the failing stage - -## Common Root Causes (ranked by frequency) - -1. **Join key mismatch** — types differ, whitespace, case sensitivity -2. **Silent NaN propagation** — one NaN poisons an entire calculation chain -3. **Date/timezone confusion** — mixing naive and aware, wrong parse format -4. **Off-by-one in date ranges** — `< end_date` vs `<= end_date` -5. **Duplicate rows after merge** — many-to-many join not intended -6. **Column name collision** — same name in both DataFrames, suffixed `_x`/`_y` -7. **Integer division** — Python 2 legacy or numpy int behavior -8. **Sort order assumption** — code assumes sorted input but doesn't enforce it -9. **Encoding issues** — UTF-8 vs Latin-1 in CSV reads -10. **Stale cache/intermediate files** — old output being re-read - -## Output Format - -``` -PIPELINE MAP: - [source.csv] → read_csv → filter_dates → merge(prices) → calc_returns → output.parquet - -SYMPTOM: - Output has 500 rows, expected ~2000 - -DIAGNOSIS: - Stage: merge(prices) - Root cause: Inner join drops 75% of rows because price dates are business-days - only but source dates include weekends - - Evidence: - - Pre-merge: 2000 rows - - Post-merge: 500 rows - - prices table: 252 unique dates (business days) - - source table: 730 unique dates (calendar days) - -FIX: - Use left join + forward-fill for prices, or filter source to business days first - -PREVENTION: - Add row-count assertion after merge: assert len(merged) >= 0.9 * len(source) -``` - -## Guidelines - -- **Never assume the data is clean** — always verify -- **Check intermediate outputs** — don't just look at input and output -- **Quantify the problem** — "500 rows instead of 2000" not "some rows are missing" -- **Propose assertions** — suggest guards that would catch this issue in the future -- **Consider edge cases** — what happens on the first/last day? With empty input? With a single row? diff --git a/claude/root-files/AGENTS.md b/claude/root-files/AGENTS.md deleted file mode 100644 index 6968a3ca..00000000 --- a/claude/root-files/AGENTS.md +++ /dev/null @@ -1,32 +0,0 @@ -# AGENTS.md - -## Agent Instructions - -This repository uses Claude Code–style rules and skills as the primary source of agent behavior. - -All coding agents (Codex, Claude, etc.) should follow the instructions -defined in the following files: - -- `CLAUDE.md` — the behavioral contract; the canonical, always-loaded source -- `.claude/skills/*` -- `.claude/rules/*` — `paths:`-scoped rules only, when the repo carries any; an - unscoped rule file belongs in `CLAUDE.md` instead - -Treat those files as the canonical specification for: - -- coding style -- architecture conventions -- workflows -- testing and validation - -If instructions conflict, prefer `CLAUDE.md`. - -## How to work in this repo - -1. Read `CLAUDE.md` first — it carries the contract. -2. Load relevant skills from `.claude/skills/`. -3. Apply any `paths:`-scoped rules in `.claude/rules/` whose globs match the - files you are touching. Often there are none; that is normal. -4. Then explore the repository and implement changes. - -Do not invent new conventions if they are already defined in `CLAUDE.md`. \ No newline at end of file diff --git a/claude/skills/engineering/skill-assessment/SKILL.md b/claude/skills/engineering/skill-assessment/SKILL.md deleted file mode 100644 index 7ee5177c..00000000 --- a/claude/skills/engineering/skill-assessment/SKILL.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -name: skill-assessment -description: | - Audit and assess skills against best practices from Anthropic's skill engineering guide. - Use when the user says "assess skills", "audit skills", "skill review", "skill quality", - "rate my skills", or wants to evaluate skill coverage, quality, and structure. - Analyzes individual skills or the entire skill universe. -argument-hint: "[skill-name | all]" -allowed-tools: Read, Glob, Grep, Bash, Agent -user-invocable: true ---- - -# Skill Assessment Tool - -Evaluate skills against Anthropic's best practices for skill engineering. Produces a structured assessment with category classification, quality scores, gap analysis, and actionable recommendations. - -## Quick Start - -1. If `$ARGUMENTS` is a specific skill name, assess only that skill -2. If `$ARGUMENTS` is "all" or empty, assess the entire skill universe - -## Assessment Workflow - -### Phase 1: Discovery - -Scan the skill directories to build an inventory: - -```bash -ls -d .claude/skills/*/ -``` - -For each skill, read: -- `SKILL.md` (frontmatter + content) -- Directory listing (scripts/, references/, assets/, data files) -- Any supporting files referenced in the SKILL.md - -### Phase 2: Classify - -Classify each skill into one or more of the **9 skill categories** defined in `references/framework.md`. A well-focused skill fits cleanly into ONE category. Flag skills that straddle multiple categories as potentially needing refactoring. - -### Phase 3: Score - -Rate each skill on the **8 quality dimensions** from `references/framework.md`, using the scoring rubric (0-2 per dimension, max 16). Read the framework file for full criteria. - -### Phase 4: Gap Analysis - -Compare the skill universe against all 9 categories. Identify: -- **Missing categories** — no skills at all in that category -- **Thin categories** — only 1 skill, could benefit from more -- **Over-represented** — many similar skills that could be consolidated - -### Phase 5: Report - -Produce a structured report with these sections: - -#### Per-Skill Assessment Table - -| Skill | Category | Score | Top Strength | Top Issue | Priority Fix | -|-------|----------|-------|--------------|-----------|--------------| - -#### Category Coverage Matrix - -Show which of the 9 categories are covered, thin, or missing. - -#### Top 5 Recommendations - -Ranked by impact. Each recommendation should include: -- What to do -- Which skill(s) it applies to -- Expected improvement -- Effort estimate (quick / medium / significant) - -#### Skill Improvement Briefs - -For any skill scoring below 10/16, write a 3-5 line improvement brief with specific, actionable changes. - -## Scoring Interpretation - -| Range | Label | Meaning | -|-------|-------|---------| -| 14-16 | Excellent | Exemplary skill, share widely | -| 10-13 | Good | Solid skill, minor improvements possible | -| 6-9 | Needs Work | Functional but missing key best practices | -| 0-5 | Weak | Needs significant rework | - -## Important Guidelines - -- **Don't state the obvious**: Focus assessment on what Claude wouldn't know by default. A skill that just restates common knowledge should be flagged. -- **Value gotchas highly**: The presence of a well-maintained gotchas/pitfalls section is one of the strongest quality signals. -- **Reward progressive disclosure**: Skills that use folder structure (references/, scripts/, assets/) to layer information score higher than monolithic SKILL.md files. -- **Check descriptions for model-targeting**: The description field should tell the MODEL when to trigger, not just describe what the skill does to humans. -- **Assess composition potential**: Note where skills could reference or depend on each other more effectively. diff --git a/claude/skills/engineering/skill-assessment/references/framework.md b/claude/skills/engineering/skill-assessment/references/framework.md deleted file mode 100644 index eb056564..00000000 --- a/claude/skills/engineering/skill-assessment/references/framework.md +++ /dev/null @@ -1,147 +0,0 @@ -# Skill Assessment Framework - -Based on Anthropic's internal skill engineering practices (April 2025). Use this as the scoring rubric when evaluating skills. - -## The 9 Skill Categories - -### 1. Library & API Reference -Skills explaining how to use a library, CLI, or SDK correctly. Include reference snippets and gotcha lists. Best when they cover internal or poorly-documented tools. - -**Signals**: code examples, function signatures, edge cases, "don't do X" warnings. - -### 2. Product Verification -Skills describing how to test/verify code is working. Often paired with external tools (Playwright, tmux, headless browsers). High-value when they enforce programmatic assertions. - -**Signals**: test scripts, assertion patterns, verification workflows, video/screenshot capture. - -### 3. Data Fetching & Analysis -Skills connecting to data/monitoring stacks. Include credentials patterns, dashboard IDs, common query workflows. - -**Signals**: data source configs, query templates, helper libraries, fetch scripts. - -### 4. Business Process & Team Automation -Skills automating repetitive workflows into one command. Often compose other skills or MCPs. Benefit from logging previous results for consistency. - -**Signals**: workflow orchestration, log files, template outputs, multi-tool composition. - -### 5. Code Scaffolding & Templates -Skills generating framework boilerplate. Combine scripts with natural language requirements. Most useful for org-specific conventions. - -**Signals**: directory structure templates, file generators, annotation patterns, init scripts. - -### 6. Code Quality & Review -Skills enforcing code quality. May include deterministic scripts for robustness. Good candidates for running via hooks or CI. - -**Signals**: lint rules, review checklists, subagent critique patterns, style enforcement. - -### 7. CI/CD & Deployment -Skills for fetching, pushing, and deploying code. May reference other skills for data. - -**Signals**: build scripts, deploy workflows, rollback patterns, merge conflict resolution. - -### 8. Runbooks -Skills taking a symptom → walking through investigation → producing structured report. Multi-tool diagnostic workflows. - -**Signals**: symptom→tool mapping, diagnostic steps, structured output templates, escalation paths. - -### 9. Infrastructure Operations -Skills for routine maintenance and operational procedures. May involve destructive actions needing guardrails. - -**Signals**: cleanup scripts, approval workflows, cost queries, soak periods. - ---- - -## The 8 Quality Dimensions - -Score each 0-2 (0 = absent, 1 = partial, 2 = strong). - -### D1. Description Targeting (0-2) -Does the `description` field tell the **model** when to trigger, not just describe what the skill does? - -- **0**: Generic or missing description -- **1**: Describes functionality but not trigger conditions -- **2**: Includes trigger phrases, user intent patterns, and clear scope boundaries - -### D2. Progressive Disclosure (0-2) -Does the skill use folder structure to layer information? - -- **0**: Monolithic SKILL.md only, no supporting files -- **1**: Some supporting files but not well-organized or referenced -- **2**: Clear folder structure (references/, scripts/, assets/) with SKILL.md pointing to them at appropriate moments - -### D3. Gotchas & Pitfalls (0-2) -Does the skill capture failure modes, edge cases, and "don't do X" warnings? - -- **0**: No gotchas section or failure mode documentation -- **1**: Some warnings scattered in the text -- **2**: Dedicated gotchas/pitfalls section built from real failure experience, regularly updated - -### D4. Non-Obvious Knowledge (0-2) -Does the skill push Claude beyond its default behavior? Does it contain information Claude wouldn't know? - -- **0**: Mostly restates common knowledge Claude already has -- **1**: Mix of common and specialized knowledge -- **2**: Primarily contains org-specific, domain-specific, or counter-intuitive information - -### D5. Actionable Scripts & Assets (0-2) -Does the skill provide runnable scripts, templates, or data files? - -- **0**: Pure instructions, no executable assets -- **1**: Some code snippets in SKILL.md but not standalone scripts -- **2**: Standalone scripts, helper libraries, or template files that Claude can compose with - -### D6. Flexibility vs. Railroading (0-2) -Does the skill give Claude information and flexibility rather than rigid step-by-step commands? - -- **0**: Overly prescriptive, no room for adaptation -- **1**: Mostly prescriptive with some flexibility -- **2**: Provides context and constraints, lets Claude adapt to the situation - -### D7. Setup & Configuration (0-2) -Does the skill handle first-time setup gracefully? - -- **0**: Assumes everything is configured, fails silently if not -- **1**: Documents prerequisites but doesn't guide setup -- **2**: Detects missing config, guides user through setup, stores preferences (e.g., config.json pattern) - -### D8. Composition & References (0-2) -Does the skill reference or compose with other skills, tools, or MCPs? - -- **0**: Completely standalone, no awareness of ecosystem -- **1**: Mentions related tools but doesn't integrate -- **2**: Explicitly references other skills, composes workflows, or chains outputs - ---- - -## External Tools & References - -Tools that complement skill assessment or serve as exemplars for specific categories. - -### Ultimate Bug Scanner (UBS) - -**Repository**: https://github.com/Dicklesworthstone/ultimate_bug_scanner -**Category relevance**: Code Quality & Review (6), Product Verification (2) - -Static analysis tool detecting 1000+ bug patterns across 9 languages (JS/TS, Python, C/C++, Rust, Go, Java, Ruby, Swift, C#). Designed as "The AI Coding Agent's Secret Weapon" — targets bugs that commonly slip through AI-assisted development. - -**Why it matters for skill assessment**: -- Exemplar of a **Code Quality** tool that could be wrapped as a skill — meta-runner architecture, per-language modules, unified reporting -- Outputs in TOON format (token-optimized, ~50% smaller than JSON) — purpose-built for LLM consumption, a pattern worth adopting in skills that produce structured output -- Git-aware scanning (`--staged`, `--diff`) — shows how skills can be scoped to only changed code -- Baseline comparison (`--comparison=`) — demonstrates regression tracking, useful for skills that run repeatedly -- Strictness profiles (`--profile=strict|loose`) — good pattern for skills that need different modes -- `ubs doctor` self-diagnostic — exemplar for D7 (Setup & Configuration): detects broken deps, auto-repairs with `--fix` - -**Assessment integration**: When evaluating Code Quality skills, compare their coverage and sophistication against UBS patterns. A good code quality skill should at minimum support: scoped scanning (not whole repo), machine-readable output, and suppression of known issues. - ---- - -## Category Gap Assessment Guide - -When evaluating a skill universe, check coverage across all 9 categories. Common gaps in developer toolkits: - -- **Product Verification** is often missing — teams write code but don't skill-ify their testing -- **Runbooks** are usually in wikis, not skills — huge opportunity to make them actionable -- **Code Quality & Review** often exists as linter config but not as a review skill -- **Infrastructure Operations** is underserved — operations knowledge stays in people's heads -- **Business Process** skills have the highest ROI when they compose other skills diff --git a/claude/skills/quant/analizy-pl-data/SKILL.md b/claude/skills/quant/analizy-pl-data/SKILL.md deleted file mode 100644 index 32eeaec6..00000000 --- a/claude/skills/quant/analizy-pl-data/SKILL.md +++ /dev/null @@ -1,417 +0,0 @@ ---- -name: analizy-pl-data -description: This skill provides programmatic access to Polish investment fund data from analizy.pl, the leading Polish fund data aggregator. Use this skill when working with Polish investment funds, analyzing fund performance, comparing funds, downloading portfolio PDFs, or researching the Polish asset management industry. The skill covers 2,133 funds across FIO (Polish open-end), FIZ (Polish closed-end), and FZG (foreign UCITS) fund types, plus portfolio download URLs for 26 TFI providers. ---- - -# Analizy.pl Fund Data Retrieval Skill - -## Purpose - -This skill provides programmatic access to Polish investment fund data from analizy.pl, which is the leading Polish fund data aggregator. It enables retrieval of historical quotations, performance metrics, rankings, and fund metadata for 2,100+ investment funds across three product types. - -**Fund Universe** (2,133 total funds): -- **FIO** (Fundusze Inwestycyjne Otwarte) - 488 Polish open-end funds -- **FIZ** (Fundusze Inwestycyjne Zamknięte) - 187 Polish closed-end funds -- **FZG** (Fundusze Zagraniczne) - 1,272 foreign funds (Luxembourg UCITS) - -**Use this skill when:** -- Working with Polish investment fund data -- Analyzing fund performance or building rankings -- Comparing funds across peer groups -- Downloading portfolio composition PDFs from TFIs -- Mapping TFI companies to analizy.pl fund codes -- Researching Polish asset management industry -- Building fund screening or selection tools - -## Quick Start - -### Get Historical Quotations -```python -import requests - -url = "https://www.analizy.pl/api/quotation/fio/SKR54" -response = requests.get(url, timeout=60) -data = response.json() -prices = data['series'][0]['price'] # [{date, value}, ...] -``` - -### Get Performance Metrics -```python -import pandas as pd - -url = "https://www.analizy.pl/api/rate-of-return/fio/SKR54" -tables = pd.read_html(url) -performance_df = tables[0] # Fund returns, peer average, ranking -``` - -### Scrape Fund Metadata (Listing Pages) -```python -from firecrawl import Firecrawl -from dotenv import load_dotenv - -load_dotenv() -app = Firecrawl() - -result = app.scrape( - url="https://www.analizy.pl/fundusze-inwestycyjne-otwarte/notowania", - formats=['markdown'], - only_main_content=True -) -# Parse markdown to extract fund codes, names, peer groups, etc. -``` - -See `references/code-examples.md` for complete working examples. - -## Available Data Sources - -### 1. Portfolio PDF Downloads (Recommended for Holdings Data) - -**Download portfolio composition reports directly:** -``` -https://dokumenty.analizy.pl/pobierz/fi/{FUND_CODE}/SP/{DATE} -``` - -- `FUND_CODE`: Analizy.pl fund code (e.g., AIG02, PZU01, SKR01) -- `SP`: "Skład Portfela" (Portfolio Composition report type) -- `DATE`: Report date in YYYY-MM-DD format (quarter-end: 03-31, 06-30, 09-30, 12-31) - -**Example URLs:** -``` -https://dokumenty.analizy.pl/pobierz/fi/AIG02/SP/2025-09-30 # Rockbridge -https://dokumenty.analizy.pl/pobierz/fi/PZU01/SP/2025-09-30 # PZU -https://dokumenty.analizy.pl/pobierz/fi/SKR01/SP/2025-09-30 # Skarbiec -``` - -**Key insight:** Most TFIs return a single bulk PDF containing all subfunds under an umbrella code. Use `config/provider_mapping.json` for verified umbrella codes per TFI. - -**Automated download script:** -```bash -# Download all providers for a quarter -uv run python scripts/datasets/fund_holdings/download_fund_holdings.py --date 2025-12-31 - -# Download specific provider -uv run python scripts/datasets/fund_holdings/download_fund_holdings.py --provider rockbridge --date 2025-12-31 -``` - -**Related skill:** Use the `pdf-extraction` skill to parse downloaded PDFs into standardized data. - -### 2. JSON APIs (Recommended for Price/Performance Data) - -**Historical Quotations:** -- `GET https://www.analizy.pl/api/quotation/{fio|fzg}/{FUND_CODE}` -- Returns: Complete daily NAV time series (no date filtering supported) -- **Limitation**: API ignores date range params - always returns full history -- See: `references/api-reference.md` - -**Performance Metrics:** -- `GET https://www.analizy.pl/api/rate-of-return/{fio|fzg}/{FUND_CODE}` -- Returns: Fund returns, peer group average, rankings across all periods -- Periods: 1M, 3M, 6M, YTD, 12M, 24M, 36M, 48M, 60M, 120M - -### 2. Listing Pages (Recommended for Bulk Metadata) - -**Fast bulk extraction** via Firecrawl API: -- FIO: `https://www.analizy.pl/fundusze-inwestycyjne-otwarte/notowania` (49 pages) -- FIZ: `https://www.analizy.pl/fundusze-inwestycyjne-zamkniete/notowania` (19 pages) -- FZG: `https://www.analizy.pl/fundusze-zagraniczne/notowania` (146 pages) - -**Available fields:** code, name, url, peer_group, tfi_company, currency, nav_value, valuation_date, ytd_return - -See: `references/fund-type-specs.md` for complete field availability matrix - -### 3. Profile Pages (For Detailed Fund Information) - -**Individual fund pages** (HTML scraping required): -- `https://www.analizy.pl/fundusze-inwestycyjne-otwarte/{CODE}/{SLUG}` - -**Additional fields:** ISIN, inception_date, sharpe_ratio, information_ratio, std_dev, fund_manager, portfolio_holdings - -See: `references/regex-patterns.md` for HTML extraction patterns - -## Master Scraping Workflow - -### Overview - -The master scraping workflow uses **Firecrawl API v4.8.0** to efficiently extract fund metadata from listing pages. - -**Performance:** Successfully scraped 1,944 funds (FIO: 485, FIZ: 187, FZG: 1,272) with 11 core fields in ~22 minutes. - -### Firecrawl API v4.8.0 Setup - -```python -from firecrawl import Firecrawl -from dotenv import load_dotenv - -load_dotenv() # Loads FIRECRAWL_API_KEY from .env -app = Firecrawl() # Reads API key from environment - -result = app.scrape( - url=url, - formats=['markdown'], - only_main_content=True -) -markdown = result.markdown # Document object with .markdown attribute -``` - -**Environment Setup:** -```bash -# Install dependencies -uv add firecrawl-py python-dotenv pandas - -# Create .env file in project root -echo "FIRECRAWL_API_KEY=your-api-key-here" >> .env -``` - -**Rate Limiting (Critical):** -- **Free tier**: 11 requests/minute -- **Required delay**: 6.0 seconds between requests -- **Calculation**: 60s ÷ 11 req = 5.45s minimum, use 6.0s for safety - -### Implementation Pattern - -The scraping workflow is documented in `references/code-examples.md` with complete, portable code examples that can be copied and adapted for any project. - -### Performance Metrics - -| Fund Type | Pages | Time | Funds | Rate | -|-----------|-------|------|-------|------| -| FIO | 49 | ~5 min | 485 | ~10/page | -| FIZ | 19 | ~2 min | 187 | ~10/page | -| FZG | 146 | ~15 min | 1,272 | ~9/page | -| **All** | **214** | **~22 min** | **1,944** | **~9/page** | - -## Data Schema - -### Extracted Fields (11 Total) - -1. `code` - Fund code (primary key) -2. `name` - Full fund name -3. `type` - Fund type (fio/fiz/fzg) -4. `groupname` - Peer group classification (CRITICAL for analysis) -5. `tfi_company` - Management company -6. `currency` - NAV currency (PLN, EUR, USD, etc.) -7. `url` - Fund profile page URL -8. `information_source` - "analizy.pl listing scraper" -9. `nav_value` - Current NAV per unit -10. `valuation_date` - Latest valuation date (DD.MM.YYYY) -11. `valuation_frequency` - FIZ only (miesięczna/kwartalna) - -### Field Completeness (from listing pages) - -- code, name, type, url, information_source: 100% -- currency: 75.1% -- groupname: 74.0% -- valuation_date: 75.1% -- nav_value: 14.4% -- tfi_company: 9.6% (FIO/FIZ only, empty for FZG) -- valuation_frequency: 8.2% (FIZ only) - -## Data Consolidation - -After scraping separate fund types, consolidate into single dataset: - -**Process:** -1. Load FIO, FIZ, FZG CSV files -2. Normalize all to 11-field master schema -3. Rename 'group' → 'groupname' if needed (backward compatibility) -4. Concatenate and deduplicate by code -5. Validate completeness and show statistics -6. Save consolidated dataset - -See `references/code-examples.md` for complete consolidation code. - -## Working with Different Fund Types - -Each fund type has distinct characteristics and data availability. - -**FIO (Open-End Funds):** -- 488 funds, daily NAV, Polish domicile -- Best data availability (Good Practices scores, portfolio holdings) - -**FIZ (Closed-End Funds):** -- 187 funds, monthly/quarterly valuation, limited liquidity -- Unique fields: valuation_frequency (miesięczna/kwartalna) - -**FZG (Foreign Funds):** -- 1,272 funds, Luxembourg UCITS, multiple currencies/unit classes -- Code format: `{PROVIDER}{NUM}_{CLASS}_{CURRENCY}` (e.g., `FTI068_A_USD`) - -See: `references/fund-type-specs.md` for detailed specifications - -## Common Operations - -### Extract Fund Metadata from Listing Pages - -Use the parsing functions from `references/extraction-patterns.md`: - -```python -from firecrawl import Firecrawl -import time - -app = Firecrawl() -all_funds = [] - -for page in range(1, total_pages + 1): - result = app.scrape(url=page_url, formats=['markdown']) - page_funds = parse_listing_page_markdown(result.markdown, 'fio') - all_funds.extend(page_funds) - time.sleep(6.0) # CRITICAL: Rate limiting -``` - -See: `references/extraction-patterns.md` for complete parsing functions - -### Extract Metadata from Profile Pages - -For detailed metadata (ISIN, Sharpe ratio, inception date): - -```python -import re -import requests - -def extract_fund_metadata(fund_code: str, html_text: str): - """Extract metadata from profile page HTML.""" - # See references/regex-patterns.md for all patterns - peer_group_pattern = r'Nazwa\s+grupy

\s*]*class="[^"]*basicValue[^"]*"[^>]*>\s*]*>([^<]+)

' - match = re.search(peer_group_pattern, html_text) - peer_group = match.group(1).strip() if match else None - # ... extract other fields - return metadata -``` - -See: `references/regex-patterns.md` for all extraction patterns - -### Batch Processing Best Practices - -1. **Rate Limiting:** Always add delays between requests -2. **Error Handling:** Wrap in try-except, log failures -3. **Progress Tracking:** Print status for long-running operations -4. **Checkpoint Saving:** Save intermediate results every N records - -See: `references/extraction-patterns.md` for detailed batch processing examples - -## Recommended Strategy: Two-Stage Approach - -**Stage 1: Scrape Listing Pages** (~22 min for all 1,944 funds) -- Get core metadata: code, name, peer_group, currency, etc. -- Build complete fund directory - -**Stage 2: Filter & Detail Scrape** (as needed) -- Filter to funds of interest using Stage 1 data -- Scrape detail pages only for filtered subset -- Get comprehensive metadata: ISIN, Sharpe ratio, holdings - -**Example:** -```python -# Stage 1: Quick directory (22 min) -all_funds_df = scrape_all_listing_pages() - -# Stage 2: Filter and detail (2-3 min for ~50 funds) -equity_funds = all_funds_df[ - all_funds_df['groupname'].str.contains('akcji polskich', na=False) -] -detail_metadata = scrape_detail_pages(equity_funds['url'].tolist()) -``` - -See: `references/fund-type-specs.md` for field availability matrix - -## Troubleshooting - -**Common Issues:** - -1. **Firecrawl Rate Limit:** Increase DELAY_BETWEEN_PAGES to 6.0 seconds -2. **No funds extracted:** Use regex pattern with `[^\)\"]+` (handles title attributes) -3. **Unicode errors on Windows:** Use ASCII equivalents or configure UTF-8 -4. **API 404 errors:** Verify fund code and correct endpoint (fio vs fzg) -5. **Peer group extraction fails:** Use `basicValue` pattern from `references/regex-patterns.md` - -See: `references/troubleshooting.md` for complete troubleshooting guide - -## Reference Documentation - -For detailed information, consult these reference files: - -- **`references/api-reference.md`** - API endpoints, response structures, field definitions -- **`references/provider-mapping.md`** - TFI → umbrella code mapping for PDF downloads -- **`references/regex-patterns.md`** - All regex patterns for data extraction -- **`references/fund-type-specs.md`** - FIO/FIZ/FZG specifications and characteristics -- **`references/extraction-patterns.md`** - Parsing functions and batch processing patterns -- **`references/code-examples.md`** - Complete working code examples -- **`references/troubleshooting.md`** - Solutions to common issues - -## Rate Limiting & Best Practices - -1. **Add delays:** 6s for Firecrawl (listing pages), 2-4s jitter for direct HTTP (APIs) -2. **Batch pauses:** 30s rest every 50 requests for bulk downloads -3. **Cache responses:** Save API responses to avoid re-fetching -4. **Handle errors:** Use try-except blocks and log failures -5. **Set User-Agent:** Use descriptive user-agent string for HTTP requests -6. **Timeout:** Use 60+ second timeouts for large API responses -7. **Validate data:** Check field completeness and HTML entity issues - -### Smart Scraping Pattern (Bulk Quotations) - -```python -import random -import time - -BATCH_SIZE = 50 -BATCH_PAUSE = 30 # seconds - -for idx, fund in enumerate(funds, 1): - # Batch pause every 50 funds - if idx > 1 and (idx - 1) % BATCH_SIZE == 0: - print(f"Pausing {BATCH_PAUSE}s after {idx - 1} downloads...") - time.sleep(BATCH_PAUSE) - - # Fetch data - data = fetch_quotation(fund['code'], fund['type']) - save_json(fund['code'], data) - - # Random jitter (2-4s) - time.sleep(random.uniform(2, 4)) -``` - -**Estimated times:** -- 485 FIO funds: ~32 minutes -- 187 FIZ funds: ~12 minutes -- 1,272 FZG funds: ~75 minutes - -## Provider Mapping (TFI → Fund Codes) - -The `config/provider_mapping.json` file maps TFI companies to their verified umbrella fund codes: - -**Sample entries:** -| Provider | TFI Company | Umbrella Code | Notes | -|----------|-------------|---------------|-------| -| rockbridge | Rockbridge TFI | AIG02 | Rockbridge Neo umbrella | -| pzu | TFI PZU | PZU01 | Bulk report with all subfunds | -| skarbiec | Skarbiec TFI | SKR01 | SKARBIEC + BPS subfunds | -| goldmansachs | Goldman Sachs TFI | ING02 | 35 funds, 5.2MB report | -| pko | PKO TFI | PCS05 | 34 funds | -| pekao | Pekao TFI | PIO01 | 32 funds, 6.4MB report | - -**Full mapping:** See `config/provider_mapping.json` for all 26 verified providers with: -- `provider_id`: Folder name for PDFs -- `umbrella_codes[]`: Verified download codes -- `umbrella_names[]`: Fund names covered -- `download_verified`: Whether URL was tested -- `notes`: Provider-specific quirks - -## Summary - -✅ **Portfolio PDFs:** Download holdings data via documented URL pattern -✅ **Price Data API:** Historical NAV time series -✅ **Performance API:** Returns & rankings across all periods -✅ **Listing Pages:** Fast bulk metadata extraction (Firecrawl) -✅ **Profile Pages:** Detailed metadata (HTML scraping) -✅ **Provider Mapping:** 26 TFIs with verified download codes -✅ **Coverage:** 1,944 Polish investment funds, 10+ years of history -✅ **Data Quality:** Comprehensive, validated, daily updates -✅ **Master Workflow:** 22 minutes for complete fund directory - -**Key Insight:** Use listing pages for bulk extraction (Stage 1), then detail pages for selective deep analysis (Stage 2). Portfolio PDFs can be downloaded directly via the documented URL pattern. This multi-source approach provides comprehensive fund data coverage. - -**Related skills:** -- `pdf-extraction`: Parse downloaded PDFs into standardized holdings data - -**This skill is standalone and can be used in any project requiring Polish fund data.** diff --git a/claude/skills/quant/analizy-pl-data/references/api-reference.md b/claude/skills/quant/analizy-pl-data/references/api-reference.md deleted file mode 100644 index ae848d13..00000000 --- a/claude/skills/quant/analizy-pl-data/references/api-reference.md +++ /dev/null @@ -1,191 +0,0 @@ -# Analizy.pl API Reference - -This document contains detailed API endpoint specifications, response structures, and field definitions for analizy.pl data sources. - -## JSON API Endpoints - -Analizy.pl exposes several internal JSON APIs that return structured data. - -### Historical Quotations API - -Get complete historical daily NAV (Net Asset Value) time series for a fund. - -**Endpoints:** -``` -GET https://www.analizy.pl/api/quotation/fio/{FUND_CODE} -GET https://www.analizy.pl/api/quotation/fzg/{FUND_CODE} -``` - -**Parameters:** -- `{FUND_CODE}`: Fund identifier (e.g., `SKR54` for FIO, `FTI068_A_USD` for FZG) - -**Response Format:** JSON - -**Response Structure:** -```json -{ - "id": "fund_SKR54", - "label": "Fundusz", - "currency": "PLN", - "series": [ - { - "price": [ - {"date": "2025-10-27", "value": 315.43}, - {"date": "2025-10-26", "value": 307.25} - ] - } - ] -} -``` - -**Key Fields:** -- `id` (string): Fund identifier with "fund_" prefix -- `label` (string): Data series label (typically "Fundusz") -- `currency` (string): NAV currency (PLN, EUR, USD, etc.) -- `series[0].price` (array): Array of price points - - `date` (string): Quotation date in YYYY-MM-DD format - - `value` (number): NAV per unit - -**Example URLs:** -- FIO: `https://www.analizy.pl/api/quotation/fio/SKR54` -- FZG: `https://www.analizy.pl/api/quotation/fzg/FTI068_A_USD` - -**Response Size:** Large (typically 1,000-3,000+ daily observations per fund) - -**Usage Notes:** -- Response can be 50k+ tokens for funds with long history -- Save to file immediately if processing many funds -- Timeout: Use 60+ second timeout - -**Known Limitations:** -- **No date filtering**: API ignores date range parameters (`?from=`, `?dateFrom=`, `?period=`) -- **Always full history**: Returns complete time series regardless of query parameters -- **No pagination**: Single response contains all data points - -Tested parameters that do NOT filter data: `?from=`, `?dateFrom=`, `?start_date=`, `?period=`. All return identical full history. - ---- - -### Performance Metrics API - -Get performance table with returns across all periods. - -**Endpoints:** -``` -GET https://www.analizy.pl/api/rate-of-return/fio/{FUND_CODE} -GET https://www.analizy.pl/api/rate-of-return/fzg/{FUND_CODE} -``` - -**Parameters:** -- `{FUND_CODE}`: Fund identifier - -**Response Format:** HTML table (parseable with pandas) - -**Response Structure:** -HTML table with 3 rows: -- **Row 1:** Fund returns for each period (e.g., "3.3%", "29.6%") -- **Row 2:** Peer group average returns -- **Row 3:** Position in peer group (e.g., "2/58" = 2nd out of 58 funds) - -**Periods Covered:** -- 1M, 3M, 6M, YTD, 12M, 24M, 36M, 48M, 60M, 120M - -**Example URLs:** -- FIO: `https://www.analizy.pl/api/rate-of-return/fio/SKR54` -- FZG: `https://www.analizy.pl/api/rate-of-return/fzg/FTI068_A_USD` - -**Usage Notes:** -- Use pandas.read_html() to parse response -- Row indices: 0 = fund returns, 1 = group average, 2 = position - ---- - -### Yearly Returns API - -Get calendar year returns for a fund. - -**Endpoint:** -``` -GET https://www.analizy.pl/api/rate-of-return/fio/{FUND_CODE}/yearly -``` - -**Response Format:** HTML table - -**Response Structure:** -Annual performance by year (e.g., 2024: 15.2%, 2023: -2.1%, etc.) - ---- - -### Historical Rankings API - -Get historical ranking positions over time. - -**Endpoint:** -``` -GET https://www.analizy.pl/api/ranking/{FUND_CODE}/{PERIOD} -``` - -**Parameters:** -- `{FUND_CODE}`: Fund identifier -- `{PERIOD}`: `12M` or `36M` - -**Example:** -``` -https://www.analizy.pl/api/ranking/SKR54/12M -``` - ---- - -## Data Fields Reference - -### Performance Periods - -| Period Code | Meaning | Notes | -|-------------|---------|-------| -| 1M | 1 month | Last 30 days | -| 3M | 3 months | Last quarter | -| 6M | 6 months | Last half year | -| YTD | Year to date | Since Jan 1 current year | -| 12M | 12 months | Last year | -| 24M | 24 months | Last 2 years | -| 36M | 36 months | Last 3 years | -| 48M | 48 months | Last 4 years | -| 60M | 60 months | Last 5 years | -| 120M | 120 months | Last 10 years | - -### Fund Metadata Fields - -| Field | Type | Description | Source | -|-------|------|-------------|--------| -| code | string | Fund code (primary key) | Listing/Profile | -| name | string | Full fund name | Listing/Profile | -| type | string | Fund type (fio/fiz/fzg) | Listing/Profile | -| groupname | string | Peer group classification | Listing/Profile | -| tfi_company | string | Management company | Listing/Profile | -| currency | string | NAV currency | Listing/Profile | -| url | string | Fund profile page URL | Listing/Profile | -| nav_value | number | Current NAV per unit | Listing | -| valuation_date | string | Latest valuation date (DD.MM.YYYY) | Listing | -| valuation_frequency | string | FIZ only (miesięczna/kwartalna) | Listing | -| ytd_return | string | Year-to-date return (%) | Listing | -| isin | string | ISIN code | Profile only | -| inception_date | string | Fund inception date | Profile only | -| aum_mln_pln | number | Assets under management (millions PLN) | Listing/Profile | -| mgmt_fee_max | number | Maximum management fee (%) | Listing/Profile | -| risk_level | string | Risk indicator (1-7 scale) | Listing/Profile | -| sharpe_ratio | number | Risk-adjusted return | Profile only | -| information_ratio | number | Alpha / tracking error | Profile only | -| std_dev | number | Volatility measure | Profile only | - -### Polish Terminology - -| Data Point | Polish Term | Description | -|------------|-------------|-------------| -| TFI | Towarzystwo | Management company | -| AUM | Wartość aktywów | Assets under management | -| SRRI | SRRI | Synthetic Risk-Reward Indicator (1-7) | -| Sharpe Ratio | Współczynnik Sharpe'a | Risk-adjusted return | -| Std Dev | Odchylenie standardowe | Volatility measure | -| Information Ratio | Współczynnik informacyjny | Alpha / tracking error | -| Management Fee | Opłata za zarządzanie | Annual fee (%) | -| Peer Group | Nazwa grupy | Fund classification | diff --git a/claude/skills/quant/analizy-pl-data/references/code-examples.md b/claude/skills/quant/analizy-pl-data/references/code-examples.md deleted file mode 100644 index 64a7c4b7..00000000 --- a/claude/skills/quant/analizy-pl-data/references/code-examples.md +++ /dev/null @@ -1,479 +0,0 @@ -# Code Examples - -This document contains complete, working code examples for common operations with analizy.pl fund data. - -## Example 1: Get Historical Quotations for a Fund - -Download complete daily NAV history from the quotation API. - -```python -import requests -import json - -# Get historical quotations for a fund -fund_code = "SKR54" -fund_type = "fio" # or "fzg" - -url = f"https://www.analizy.pl/api/quotation/{fund_type}/{fund_code}" -response = requests.get(url, timeout=60) -data = response.json() - -# Extract price data -prices = data['series'][0]['price'] - -# Each price point has: {"date": "YYYY-MM-DD", "value": 123.45} -print(f"Total price points: {len(prices)}") -print(f"Latest: {prices[0]}") -print(f"Oldest: {prices[-1]}") - -# Save to file -with open(f"data/{fund_code}_quotations.json", 'w') as f: - json.dump(prices, f, indent=2) -``` - -**Note:** Response can be LARGE (50k+ tokens for funds with long history). Save to file immediately. - ---- - -## Example 2: Get Performance Metrics - -Retrieve calculated returns and peer rankings from the performance API. - -```python -import pandas as pd - -fund_code = "SKR54" -fund_type = "fio" - -url = f"https://www.analizy.pl/api/rate-of-return/{fund_type}/{fund_code}" -tables = pd.read_html(url) -performance_df = tables[0] - -# Table structure: -# - Columns: Period names (1M, 3M, 6M, YTD, 12M, etc.) -# - Row 0: Fund returns -# - Row 1: Peer group average -# - Row 2: Position (e.g., "2/58") - -print("Fund returns:") -print(performance_df.iloc[0]) - -print("\nGroup average:") -print(performance_df.iloc[1]) - -print("\nPosition in peer group:") -print(performance_df.iloc[2]) - -# Extract specific period -ytd_return = performance_df.iloc[0]['YTD'] -print(f"\nYTD return: {ytd_return}") -``` - ---- - -## Example 3: Scrape Fund Metadata from Listing Pages (Firecrawl) - -Extract fund metadata from listing pages using Firecrawl v4.8.0. - -```python -from firecrawl import Firecrawl -from dotenv import load_dotenv -import time -import pandas as pd -import re - -# Load environment variables -load_dotenv() - -# Initialize Firecrawl (reads FIRECRAWL_API_KEY from .env) -app = Firecrawl() - -def parse_listing_page(markdown: str, fund_type: str): - """Parse listing page markdown to extract funds.""" - funds = [] - - # Map fund type to URL pattern - url_patterns = { - 'fio': 'fundusze-inwestycyjne-otwarte', - 'fiz': 'fundusze-inwestycyjne-zamkniete', - 'fzg': 'fundusze-zagraniczne' - } - - url_segment = url_patterns[fund_type] - header_pattern = rf'\[Profil funduszu: ([^\]]+)\]\((https://www\.analizy\.pl/{url_segment}/([A-Z0-9_]+)/[^\)\"]+)' - - matches = re.finditer(header_pattern, markdown) - - for match in matches: - funds.append({ - 'code': match.group(3), - 'name': match.group(1).strip(), - 'url': match.group(2), - 'type': fund_type - }) - - return funds - -# Scrape FIO listing pages -all_fio_funds = [] -total_pages = 49 # FIO has 49 pages - -for page in range(1, total_pages + 1): - url = f"https://www.analizy.pl/fundusze-inwestycyjne-otwarte/notowania?page={page}" if page > 1 else "https://www.analizy.pl/fundusze-inwestycyjne-otwarte/notowania" - - print(f"Scraping page {page}/{total_pages}...") - - result = app.scrape( - url=url, - formats=['markdown'], - only_main_content=True - ) - - page_funds = parse_listing_page(result.markdown, 'fio') - all_fio_funds.extend(page_funds) - - print(f" Found {len(page_funds)} funds") - - # CRITICAL: 6-second delay for rate limiting (11 req/min free tier) - if page < total_pages: - time.sleep(6.0) - -# Save results -df = pd.DataFrame(all_fio_funds) -df.to_csv('fio_funds_directory.csv', index=False) - -print(f"\nTotal FIO funds scraped: {len(all_fio_funds)}") -print(f"Saved to: fio_funds_directory.csv") -``` - ---- - -## Example 4: Batch Download Multiple Funds - -Download data for multiple funds with rate limiting and error handling. - -```python -import time -import requests -import json -from pathlib import Path - -# Create output directory -output_dir = Path("data/quotations") -output_dir.mkdir(parents=True, exist_ok=True) - -# List of fund codes to download -fund_codes = ['SKR54', 'PCS55', 'ALL91', 'PZU81'] - -results = { - 'success': [], - 'failed': [] -} - -for code in fund_codes: - try: - # Fetch quotation data - url = f"https://www.analizy.pl/api/quotation/fio/{code}" - response = requests.get(url, timeout=60) - - if response.status_code == 200: - data = response.json() - prices = data['series'][0]['price'] - - # Save to file - output_file = output_dir / f"{code}_quotations.json" - with open(output_file, 'w') as f: - json.dump(prices, f, indent=2) - - results['success'].append({ - 'code': code, - 'count': len(prices), - 'file': str(output_file) - }) - - print(f"[OK] {code}: {len(prices)} quotations") - else: - results['failed'].append({ - 'code': code, - 'error': f"HTTP {response.status_code}" - }) - print(f"[FAIL] {code}: HTTP {response.status_code}") - - except Exception as e: - results['failed'].append({ - 'code': code, - 'error': str(e) - }) - print(f"[ERROR] {code}: {str(e)}") - - # Rate limiting: 2-second delay between requests - time.sleep(2) - -# Summary -print(f"\n=== Summary ===") -print(f"Success: {len(results['success'])}") -print(f"Failed: {len(results['failed'])}") - -if results['failed']: - print("\nFailed downloads:") - for item in results['failed']: - print(f" {item['code']}: {item['error']}") -``` - ---- - -## Example 5: Calculate Returns from Price Data - -Compute returns from raw quotation data using pandas. - -```python -import pandas as pd -import requests - -# Fetch data -fund_code = "SKR54" -url = f"https://www.analizy.pl/api/quotation/fio/{fund_code}" -response = requests.get(url, timeout=60) -data = response.json() - -# Convert to DataFrame -prices = pd.DataFrame(data['series'][0]['price']) -prices['date'] = pd.to_datetime(prices['date']) -prices = prices.sort_values('date').set_index('date') - -# Calculate returns -prices['return_1d'] = prices['value'].pct_change() -prices['return_1m'] = prices['value'].pct_change(periods=21) # ~21 trading days -prices['return_12m'] = prices['value'].pct_change(periods=252) # ~252 trading days - -# Calculate annualized volatility -daily_std = prices['return_1d'].std() -annual_vol = daily_std * (252 ** 0.5) - -# Calculate Sharpe ratio (assuming 4% risk-free rate) -risk_free_rate = 0.04 -avg_annual_return = prices['return_12m'].iloc[-1] # Last 12-month return -sharpe = (avg_annual_return - risk_free_rate) / annual_vol - -# Display results -latest = prices.iloc[-1] - -print(f"Fund: {fund_code}") -print(f"Latest NAV: {latest['value']:.2f} PLN") -print(f"Daily return: {latest['return_1d']:.2%}") -print(f"1-month return: {latest['return_1m']:.2%}") -print(f"12-month return: {latest['return_12m']:.2%}") -print(f"Annual volatility: {annual_vol:.2%}") -print(f"Sharpe ratio: {sharpe:.2f}") - -# Save processed data -prices.to_csv(f'{fund_code}_returns.csv') -``` - ---- - -## Example 6: Extract Metadata from Profile Page (HTML) - -Scrape detailed metadata from individual fund profile pages. - -```python -import re -import requests -from typing import Dict, Optional - -def extract_fund_metadata(fund_code: str, html_text: str) -> Dict[str, Optional[str]]: - """Extract metadata from fund profile page HTML.""" - - metadata = {'code': fund_code} - - # Peer group - peer_group_pattern = r'Nazwa\s+grupy

\s*]*class="[^"]*basicValue[^"]*"[^>]*>\s*]*>([^<]+)

' - match = re.search(peer_group_pattern, html_text, re.IGNORECASE) - if match: - metadata['peer_group'] = match.group(1).strip().replace(' ', ' ') - else: - metadata['peer_group'] = None - - # TFI company - tfi_pattern = r'Nazwa\s+towarzystwa[^>]*>[^>]*>([^<]+)<' - match = re.search(tfi_pattern, html_text) - metadata['tfi_company'] = match.group(1).strip() if match else None - - # Management fee - fee_pattern = r'Aktualna\s+opłata\s+stała[^>]*>[^>]*>([\d,]+)\s*%' - match = re.search(fee_pattern, html_text) - metadata['mgmt_fee'] = match.group(1).replace(',', '.') if match else None - - # First valuation date - date_pattern = r'Data\s+pierwszej\s+wyceny[^>]*>[^>]*>(\d{2}\.\d{2}\.\d{4})' - match = re.search(date_pattern, html_text) - metadata['inception_date'] = match.group(1) if match else None - - return metadata - -def fetch_fund_metadata(fund_code: str, fund_url: str) -> Dict: - """Fetch and extract metadata for a single fund.""" - headers = { - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' - } - - response = requests.get(fund_url, headers=headers, timeout=30) - response.raise_for_status() - - return extract_fund_metadata(fund_code, response.text) - -# Example usage -metadata = fetch_fund_metadata( - 'SKR54', - 'https://www.analizy.pl/fundusze-inwestycyjne-otwarte/SKR54/skarbiec-spolek-wzrostowych' -) - -print(f"Code: {metadata['code']}") -print(f"Peer group: {metadata['peer_group']}") -print(f"TFI: {metadata['tfi_company']}") -print(f"Management fee: {metadata['mgmt_fee']}%") -print(f"Inception: {metadata['inception_date']}") -``` - ---- - -## Example 7: Complete Workflow - Analyze Top Polish Equity Funds - -End-to-end workflow: download data, calculate metrics, rank funds. - -```python -import requests -import pandas as pd -import time - -# Step 1: Define funds to analyze -fund_codes = ['SKR54', 'PCS55', 'PCS33', 'PZU81', 'ALL91'] - -# Step 2: Download quotation data -all_data = {} - -for code in fund_codes: - try: - url = f"https://www.analizy.pl/api/quotation/fio/{code}" - response = requests.get(url, timeout=60) - data = response.json() - - # Extract and store prices - prices = pd.DataFrame(data['series'][0]['price']) - prices['date'] = pd.to_datetime(prices['date']) - prices = prices.sort_values('date').set_index('date') - - all_data[code] = prices - print(f"[OK] {code}: {len(prices)} days") - - time.sleep(2) # Rate limiting - - except Exception as e: - print(f"[ERROR] {code}: {e}") - -# Step 3: Calculate metrics -results = [] - -for code, prices in all_data.items(): - # Calculate returns - prices['return_1d'] = prices['value'].pct_change() - prices['return_1m'] = prices['value'].pct_change(periods=21) - prices['return_12m'] = prices['value'].pct_change(periods=252) - - # Calculate volatility - annual_vol = prices['return_1d'].std() * (252 ** 0.5) - - # Latest metrics - latest = prices.iloc[-1] - - results.append({ - 'code': code, - 'nav': latest['value'], - 'return_1m': latest['return_1m'], - 'return_12m': latest['return_12m'], - 'volatility': annual_vol - }) - -# Step 4: Rank by Sharpe ratio -results_df = pd.DataFrame(results) -results_df['sharpe'] = results_df['return_12m'] / results_df['volatility'] -results_df = results_df.sort_values('sharpe', ascending=False) - -# Step 5: Display results -print("\n=== Fund Analysis Results ===") -print(results_df.to_string(index=False)) - -# Save to file -results_df.to_csv('fund_analysis_results.csv', index=False) -print("\nResults saved to: fund_analysis_results.csv") -``` - -**Expected Output:** -``` -=== Fund Analysis Results === - code nav return_1m return_12m volatility sharpe - SKR54 315.43 0.033 0.296 0.185 1.600 - PCS33 130.23 0.028 0.242 0.168 1.440 - ... -``` - ---- - -## Example 8: Consolidate Multiple Scraping Outputs - -Merge FIO, FIZ, and FZG CSV files into a master dataset. - -```python -import pandas as pd -from pathlib import Path - -# Load individual CSV files -fio_df = pd.read_csv('data/scraped/fio_funds.csv') -fiz_df = pd.read_csv('data/scraped/fiz_funds.csv') -fzg_df = pd.read_csv('data/scraped/fzg_funds.csv') - -# Normalize column names (ensure consistency) -for df in [fio_df, fiz_df, fzg_df]: - if 'group' in df.columns and 'groupname' not in df.columns: - df.rename(columns={'group': 'groupname'}, inplace=True) - -# Concatenate -master_df = pd.concat([fio_df, fiz_df, fzg_df], ignore_index=True) - -# Deduplicate by code -master_df = master_df.drop_duplicates(subset=['code'], keep='first') - -# Validate completeness -print("=== Field Completeness ===") -for col in master_df.columns: - non_null = master_df[col].notna().sum() - total = len(master_df) - pct = (non_null / total) * 100 - print(f"{col:25s}: {non_null:4d}/{total:4d} ({pct:5.1f}%)") - -# Save master file -output_file = 'data/processed/fund_metadata_master.csv' -master_df.to_csv(output_file, index=False) - -print(f"\n[OK] Saved {len(master_df)} funds to: {output_file}") -``` - ---- - -## Environment Setup - -Before running these examples, ensure you have the required dependencies: - -```bash -# Install dependencies -uv add requests pandas python-dotenv firecrawl-py - -# Create .env file for Firecrawl API key -echo "FIRECRAWL_API_KEY=your-api-key-here" >> .env -``` - -**Required Packages:** -- `requests` - HTTP library for API calls -- `pandas` - Data manipulation and analysis -- `python-dotenv` - Environment variable management -- `firecrawl-py` - Firecrawl API client (v4.8.0+) diff --git a/claude/skills/quant/analizy-pl-data/references/extraction-patterns.md b/claude/skills/quant/analizy-pl-data/references/extraction-patterns.md deleted file mode 100644 index e78c0ea9..00000000 --- a/claude/skills/quant/analizy-pl-data/references/extraction-patterns.md +++ /dev/null @@ -1,502 +0,0 @@ -# Data Extraction Patterns - -This document contains patterns and best practices for extracting fund data from both markdown (listing pages) and HTML (profile pages). - -## Markdown Structure (Firecrawl Output) - -Firecrawl returns listing pages as **markdown**, not HTML. - -### Typical Structure - -```markdown -[Profil funduszu: FUND_NAME](https://www.analizy.pl/fundusze-inwestycyjne-{type}/{CODE}/{slug}) - -Akcyjne ← Category badge - -## FUND_NAME - -akcji polskich uniwersalne ← Peer group -PKO TFI S.A. ← TFI company - -PLN -315.43 PLN ← NAV value -Wartość certyfikatu - -31.10.2025 ← Valuation date - -+29.6% ← YTD return -YTD -``` - ---- - -## Listing Page Extraction Functions - -### Complete Listing Page Parser - -```python -import re -from typing import List, Dict, Optional - -def parse_listing_page_markdown(markdown: str, fund_type: str) -> List[Dict]: - """ - Parse listing page markdown to extract fund metadata. - - Args: - markdown: Markdown content from Firecrawl scrape - fund_type: 'fio', 'fiz', or 'fzg' - - Returns: - List of fund dictionaries with extracted fields - """ - funds = [] - - # Map fund type to URL pattern - url_patterns = { - 'fio': 'fundusze-inwestycyjne-otwarte', - 'fiz': 'fundusze-inwestycyjne-zamkniete', - 'fzg': 'fundusze-zagraniczne' - } - - url_segment = url_patterns[fund_type] - - # Extract fund headers (code, name, URL) - header_pattern = rf'\[Profil funduszu: ([^\]]+)\]\((https://www\.analizy\.pl/{url_segment}/([A-Z0-9_]+)/[^\)\"]+)' - - matches = re.finditer(header_pattern, markdown) - - for match in matches: - name = match.group(1).strip() - url = match.group(2) - code = match.group(3) - - # Extract content block for this fund (between this match and next) - start_pos = match.end() - # Find next fund or end of string - next_match = re.search(r'\[Profil funduszu:', markdown[start_pos:]) - end_pos = start_pos + next_match.start() if next_match else len(markdown) - - content_block = markdown[start_pos:end_pos] - - # Extract additional fields from content block - fund_data = { - 'code': code, - 'name': name, - 'type': fund_type, - 'url': url, - 'information_source': 'analizy.pl listing scraper', - 'groupname': extract_peer_group(content_block), - 'tfi_company': extract_tfi_company(content_block) if fund_type != 'fzg' else None, - 'currency': extract_currency(content_block), - 'nav_value': extract_nav_value(content_block), - 'valuation_date': extract_valuation_date(content_block), - 'ytd_return': extract_ytd_return(content_block) - } - - # FIZ-specific field - if fund_type == 'fiz': - fund_data['valuation_frequency'] = extract_valuation_frequency(content_block) - - funds.append(fund_data) - - return funds - - -def extract_peer_group(content: str) -> Optional[str]: - """Extract peer group from content block.""" - lines = content.split('\n') - - SKIP_BADGES = ['Akcyjne', 'Dłużne', 'Mieszane', 'Pozostałe', 'Absolute return'] - KEYWORDS = ['akcji', 'obligacji', 'papierów', 'mieszane', 'absolutnej', - 'dłużnych', 'polskich', 'zagranicznych', 'globalnych', 'stopy', - 'rynku', 'wzrostu', 'korporacyjnych', 'skarbowych'] - - found_heading = False - - for line in lines[:25]: - line = line.strip() - - if not line or len(line) < 8: - continue - if line.startswith('[') or line.startswith('http'): - continue - if line in SKIP_BADGES: - continue - - if line.startswith('##'): - found_heading = True - continue - - if found_heading: - if any(kw in line.lower() for kw in KEYWORDS): - return line - - return None - - -def extract_tfi_company(content: str) -> Optional[str]: - """Extract TFI company name.""" - lines = content.split('\n') - - for line in lines[:30]: - line = line.strip() - - if 'TFI' in line or 'Towarzystwo' in line: - if 10 < len(line) < 80: - if not any(skip in line for skip in ['Nazwa towarzystwa', 'firma', 'opłata']): - return line - - return None - - -def extract_currency(content: str) -> str: - """Extract currency code.""" - match = re.search(r'\b(PLN[DP]?|EUR|USD)\b', content) - - if match: - currency_raw = match.group(1) - return currency_raw[:3] if currency_raw.startswith('PLN') else currency_raw - - return 'PLN' - - -def extract_nav_value(content: str) -> Optional[str]: - """Extract NAV value.""" - nav_match = re.search(r'([\d\s]+,\d+)\s*PLN', content) - if nav_match: - return nav_match.group(1).replace(' ', '').strip() - return None - - -def extract_valuation_date(content: str) -> Optional[str]: - """Extract valuation date (DD.MM.YYYY).""" - date_match = re.search(r'\b(\d{2}\.\d{2}\.\d{4})\b', content) - if date_match: - return date_match.group(1) - return None - - -def extract_ytd_return(content: str) -> Optional[str]: - """Extract YTD return.""" - ytd_match = re.search(r'([+-]?\d+,\d+)%\s*YTD', content) - if ytd_match: - return ytd_match.group(1) - return None - - -def extract_valuation_frequency(content: str) -> Optional[str]: - """Extract valuation frequency (FIZ only).""" - if 'miesięczna' in content: - return 'miesięczna' - elif 'kwartalna' in content: - return 'kwartalna' - return None -``` - ---- - -## HTML Profile Page Extraction - -### HTML Structure - -Fund profile pages contain a `
` with metadata in label-value pairs: - -```html -
-
-
-

Nazwa grupy

-

- akcji globalnych rynków rozwiniętych -

-
-
-

Poziom ryzyka (SRI)

-

Wysokie

-
-
-

Benchmark

-

90% MSCI ACWI Index + 10% WIBOR O/N

-
-
-
-``` - -### Complete HTML Extraction Function - -```python -import re -import requests -from typing import Dict, Optional - -def extract_fund_metadata(fund_code: str, html_text: str) -> Dict[str, Optional[str]]: - """ - Extract core metadata from fund profile page HTML. - - Returns dict with: code, peer_group_detailed, tfi_company, - mgmt_fee_current, first_valuation_date - """ - - metadata = {'code': fund_code} - - # 1. Peer group - MOST RELIABLE PATTERN - peer_group_pattern = r'Nazwa\s+grupy

\s*]*class="[^"]*basicValue[^"]*"[^>]*>\s*]*>([^<]+)

' - match = re.search(peer_group_pattern, html_text, re.IGNORECASE) - if match: - peer_group = match.group(1).strip().replace(' ', ' ') - metadata['peer_group_detailed'] = peer_group - else: - metadata['peer_group_detailed'] = None - - # 2. TFI company - tfi_pattern = r'Nazwa\s+towarzystwa[^>]*>[^>]*>([^<]+)<' - match = re.search(tfi_pattern, html_text) - metadata['tfi_company'] = match.group(1).strip() if match else None - - # 3. Management fee - fee_pattern = r'Aktualna\s+opłata\s+stała[^>]*>[^>]*>([\d,]+)\s*%' - match = re.search(fee_pattern, html_text) - metadata['mgmt_fee_current'] = match.group(1).replace(',', '.') if match else None - - # 4. First valuation date - date_pattern = r'Data\s+pierwszej\s+wyceny[^>]*>[^>]*>(\d{2}\.\d{2}\.\d{4})' - match = re.search(date_pattern, html_text) - metadata['first_valuation_date'] = match.group(1) if match else None - - return metadata - - -def fetch_fund_metadata(fund_code: str, fund_url: str) -> Dict: - """Fetch and extract metadata for a single fund.""" - headers = { - 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' - } - - response = requests.get(fund_url, headers=headers, timeout=30) - response.raise_for_status() - - return extract_fund_metadata(fund_code, response.text) -``` - ---- - -## Batch Extraction Best Practices - -### Rate Limiting - -```python -import time - -# For listing pages (Firecrawl) -DELAY_BETWEEN_PAGES = 6.0 # 6 seconds (Firecrawl free tier: 11 req/min) - -for page in range(1, total_pages + 1): - result = app.scrape(url=url, formats=['markdown'], only_main_content=True) - funds = parse_listing_page_markdown(result.markdown, fund_type) - all_funds.extend(funds) - - time.sleep(DELAY_BETWEEN_PAGES) - -# For detail pages (direct HTTP) -DELAY_BETWEEN_REQUESTS = 2.0 # 2 seconds - -for fund in funds_list: - metadata = fetch_fund_metadata(fund['code'], fund['url']) - results.append(metadata) - - time.sleep(DELAY_BETWEEN_REQUESTS) -``` - -### Error Handling - -```python -errors = [] - -for fund in funds_list: - try: - metadata = fetch_fund_metadata(fund['code'], fund['url']) - results.append(metadata) - except requests.RequestException as e: - errors.append({'code': fund['code'], 'error': str(e)}) - print(f"[!] Error fetching {fund['code']}: {e}") - - time.sleep(2) - -# Save errors for later retry -if errors: - pd.DataFrame(errors).to_csv('scraping_errors.csv', index=False) -``` - -### Progress Tracking - -```python -total = len(funds_list) - -for idx, fund in enumerate(funds_list, 1): - print(f"[{idx}/{total}] {fund['code']}...", end=" ") - - metadata = fetch_fund_metadata(fund['code'], fund['url']) - - if metadata['peer_group_detailed']: - print(f"[OK] {metadata['peer_group_detailed'][:50]}") - else: - print("[FAIL] No peer group") - - time.sleep(2) -``` - -### Checkpoint Saving - -```python -import pandas as pd - -CHECKPOINT_INTERVAL = 50 # Save every 50 funds - -for idx, fund in enumerate(funds_list, 1): - metadata = fetch_fund_metadata(fund['code'], fund['url']) - results.append(metadata) - - # Save checkpoint - if idx % CHECKPOINT_INTERVAL == 0: - df = pd.DataFrame(results) - df.to_csv(f'checkpoint_{idx}.csv', index=False) - print(f"Checkpoint saved at {idx} funds") - - time.sleep(2) -``` - ---- - -## Validation and Quality Checks - -### Field Completeness Check - -```python -import pandas as pd - -def check_field_completeness(df: pd.DataFrame) -> pd.DataFrame: - """Check completeness of extracted fields.""" - completeness = {} - - for col in df.columns: - non_null = df[col].notna().sum() - total = len(df) - pct = (non_null / total) * 100 - completeness[col] = f"{non_null}/{total} ({pct:.1f}%)" - - return pd.DataFrame(completeness, index=['Completeness']).T - - -# Usage -df = pd.DataFrame(results) -print(check_field_completeness(df)) -``` - -### HTML Entity Check - -```python -def check_html_entities(df: pd.DataFrame, column: str) -> pd.DataFrame: - """Check for HTML entities in extracted text.""" - if column not in df.columns: - return pd.DataFrame() - - # Find rows with HTML entities - has_entities = df[column].str.contains('&#', na=False) - - if has_entities.any(): - print(f"Warning: {has_entities.sum()} rows contain HTML entities in {column}") - return df[has_entities][[column]] - else: - print(f"[OK] No HTML entities found in {column}") - return pd.DataFrame() - - -# Usage -check_html_entities(df, 'peer_group_detailed') -``` - -### Length Validation - -```python -def validate_field_lengths(df: pd.DataFrame, field_limits: dict) -> pd.DataFrame: - """Validate field lengths against expected limits.""" - issues = [] - - for field, max_length in field_limits.items(): - if field in df.columns: - too_long = df[df[field].str.len() > max_length] - if not too_long.empty: - issues.append({ - 'field': field, - 'count': len(too_long), - 'max_found': df[field].str.len().max() - }) - - return pd.DataFrame(issues) - - -# Usage -field_limits = { - 'peer_group_detailed': 80, - 'tfi_company': 80, - 'code': 20, - 'currency': 5 -} - -issues = validate_field_lengths(df, field_limits) -if not issues.empty: - print("Field length issues:") - print(issues) -``` - ---- - -## Listing vs Detail Page Strategy - -### When to Use Listing Pages - -Use listing pages when you need: -- Fast extraction (100 funds per page, ~6 seconds per page) -- Core metadata fields (8-12 fields) -- Current NAV, returns, and peer group classification -- Complete fund directory building - -### When to Use Detail Pages - -Use detail pages when you need: -- Comprehensive metadata (25+ fields) -- ISIN codes for cross-referencing -- Risk metrics (Sharpe, information ratio, volatility) -- Fund manager information -- Portfolio composition (top 10 holdings) - -### Recommended Two-Stage Workflow - -**Stage 1: Scrape Listing Pages** -```python -# Quick directory build: ~22 minutes for all 1,944 funds -all_funds = scrape_all_listing_pages() # Returns 8-12 fields per fund -``` - -**Stage 2: Filter and Detail Scrape** -```python -# Filter to funds of interest -df = pd.DataFrame(all_funds) -filtered = df[ - (df['groupname'].str.contains('akcji polskich', na=False)) & - (df['ytd_return'].str.replace(',', '.').astype(float) > 10) -] - -# Scrape detail pages for filtered subset only -for fund in filtered.itertuples(): - detail_metadata = fetch_fund_metadata(fund.code, fund.url) - # Merge with listing data -``` - -**Example:** To analyze Polish equity funds with Sharpe > 1.0: -1. Scrape FIO listing pages → 488 funds with peer_group (~5 min) -2. Filter for `peer_group.contains('akcji polskich')` → 58 funds -3. Scrape detail pages for those 58 funds → Get Sharpe ratios (~2 min) -4. Final filter: Sharpe > 1.0 → 12 funds for portfolio - -**Total time:** 7 minutes vs 16 minutes if scraping all detail pages first diff --git a/claude/skills/quant/analizy-pl-data/references/fund-type-specs.md b/claude/skills/quant/analizy-pl-data/references/fund-type-specs.md deleted file mode 100644 index ad6dbdbe..00000000 --- a/claude/skills/quant/analizy-pl-data/references/fund-type-specs.md +++ /dev/null @@ -1,362 +0,0 @@ -# Fund Type Specifications - -This document contains detailed specifications for the three fund types available on analizy.pl: FIO (open-end funds), FIZ (closed-end funds), and FZG (foreign funds). - -## Overview - -**Total Universe:** 2,133 funds (as of 2025-11-18) - -| Type | Count | Description | Domicile | -|------|-------|-------------|----------| -| **FIO** | 488 | Fundusze Inwestycyjne Otwarte | Poland | -| **FIZ** | 187 | Fundusze Inwestycyjne Zamknięte | Poland | -| **FZG** | 1,272* | Fundusze Zagraniczne | Luxembourg (UCITS) | - -*1,272 actively distributed / 1,457 total registered - ---- - -## FIO - Fundusze Inwestycyjne Otwarte (Open-End Funds) - -### Characteristics - -- **Count:** 488 funds -- **Domicile:** Poland -- **Regulatory Status:** Open-end investment funds -- **Liquidity:** Daily redemption -- **Valuation:** Daily NAV -- **Minimum Investment:** Typically low (100-1,000 PLN) -- **Primary Currency:** PLN - -### Profile Page URL Structure - -``` -https://www.analizy.pl/fundusze-inwestycyjne-otwarte/{CODE}/{SLUG} -``` - -**Example:** -``` -https://www.analizy.pl/fundusze-inwestycyjne-otwarte/SKR54/skarbiec-spolek-wzrostowych -``` - -### Listing Page - -**URL:** `https://www.analizy.pl/fundusze-inwestycyjne-otwarte/notowania` - -**Pagination:** 49 pages (488 funds at ~10 funds/page) - -**Tabs:** -1. **Notowania** - Current quotations, returns -2. **Oceny** - Ratings, rankings -3. **Metryka** - Metadata, fees, AUM -4. **Opłaty** - Fee details - -### Available Data Fields - -**From Listing Pages:** -- ✅ code, name, url (100%) -- ✅ peer_group, tfi_company, currency (Metryka tab, 90-95%) -- ✅ nav_value, valuation_date, ytd_return (Notowania tab, 95-100%) -- ✅ risk_level, aum_mln_pln, mgmt_fee_max (Metryka tab, 85-90%) - -**From Profile Pages (Additional):** -- ✅ ISIN code (100%) -- ✅ Inception date (100%) -- ✅ Sharpe ratio, information ratio, std deviation (100%) -- ✅ Fund manager names (90%) -- ✅ Portfolio holdings (top 10, 90%) -- ✅ Good Practices compliance score (FIO only) - -### Common Peer Groups - -**Equity Funds:** -- `akcji polskich uniwersalne` - Polish equities universal -- `akcji polskich małych i średnich spółek` - Polish small/mid cap -- `akcji amerykańskich` - US equities -- `akcji europejskich rynków rozwiniętych` - European developed markets -- `akcji globalnych rynków rozwiniętych` - Global developed markets - -**Debt Funds:** -- `papierów dłużnych polskich skarbowych` - Polish treasury bonds -- `papierów dłużnych polskich korporacyjnych` - Polish corporate bonds -- `papierów dłużnych polskich krótkoterminowych uniwersalne` - Polish short-term debt -- `papierów dłużnych globalnych uniwersalne` - Global debt universal - -**Mixed Funds:** -- `mieszane polskie zrównoważone` - Polish balanced mixed -- `mieszane polskie stabilnego wzrostu` - Polish stable growth mixed -- `mieszane zagraniczne pozostałe` - Foreign mixed other - -**Alternative:** -- `absolutnej stopy zwrotu uniwersalne` - Absolute return universal -- `rynku surowców pozostałe` - Commodities other - ---- - -## FIZ - Fundusze Inwestycyjne Zamknięte (Closed-End Funds) - -### Characteristics - -- **Count:** 187 funds (actual scraped: 187) -- **Domicile:** Poland -- **Regulatory Status:** Closed-end investment funds -- **Liquidity:** Limited (no daily redemption) -- **Valuation:** Monthly or quarterly (not daily) -- **Minimum Investment:** High (typically 40,000+ PLN) -- **Primary Currency:** PLN, PLND, PLNP - -### Profile Page URL Structure - -``` -https://www.analizy.pl/fundusze-inwestycyjne-zamkniete/{CODE}/{SLUG} -``` - -**Example:** -``` -https://www.analizy.pl/fundusze-inwestycyjne-zamkniete/QRS16/acer-multistrategy-fiz -``` - -### Listing Page - -**URL:** `https://www.analizy.pl/fundusze-inwestycyjne-zamkniete/notowania` - -**Pagination:** 19 pages (187 funds at ~10 funds/page) - -**Tabs:** -1. **Notowania** - Certificate value, valuation date, YTD return, valuation frequency -2. **Metryka** - Peer group, TFI company, AUM, fees, risk level - -### Available Data Fields - -**From Listing Pages:** -- ✅ code, name, url (100%) -- ✅ groupname (88%) -- ✅ tfi_company (100%) -- ✅ currency (100%) -- ✅ nav_value (98%) -- ✅ valuation_date (100%) -- ✅ ytd_return (85%) -- ✅ valuation_frequency (85%) - -**From Profile Pages (Additional):** -- ✅ Public vs non-public status -- ✅ Performance fee specifications -- ✅ Investment policy -- ✅ Exchange listing status (if applicable) -- ❌ No portfolio composition data (regulatory differences) -- ❌ No Good Practices scores - -### FIZ-Specific Fields - -**Valuation Frequency:** -- `miesięczna` - Monthly valuation -- `kwartalna` - Quarterly valuation - -**NAV Label:** -- "Wartość certyfikatu" (certificate value, not unit value) - -**Currency Variants:** -- PLN - Standard Polish złoty -- PLND - Distribution units -- PLNP - Accumulation units - -### Common Characteristics - -- Many funds in liquidation: "(w likwidacji)" in name -- Higher minimum investments than FIO -- Different investor protection rules -- No daily NAV available -- Performance fees more common - -### Common Peer Groups - -- `absolutnej stopy zwrotu uniwersalne` - Absolute return universal -- `wierzytelności` - Receivables/debt collection -- `nieruchomości` - Real estate -- `private equity` - Private equity investments - ---- - -## FZG - Fundusze Zagraniczne (Foreign Funds) - -### Characteristics - -- **Count:** 1,272 actively distributed (actual scraped) -- **Total Registered:** 1,457 (146 pages on website) -- **Domicile:** Luxembourg (UCITS) -- **Regulatory Status:** Foreign funds distributed in Poland -- **Liquidity:** Daily redemption -- **Valuation:** Daily NAV -- **Primary Currencies:** USD, EUR, PLN, PLNH (PLN-hedged) - -### Profile Page URL Structure - -``` -https://www.analizy.pl/fundusze-zagraniczne/{CODE}/{SLUG} -``` - -**Example:** -``` -https://www.analizy.pl/fundusze-zagraniczne/FTI068_A_USD/franklin-gold-and-precious-metals-fund-a-acc-usd -``` - -### Listing Page - -**URL:** `https://www.analizy.pl/fundusze-zagraniczne/notowania` - -**Pagination:** 146 pages (~1,272 funds at ~9 funds/page) - -**Important:** Website shows "1,453/2,199" indicating 1,453 actively distributed funds out of 2,199 registered. The remaining 746 are hidden and cannot be scraped from listing pages. - -**Tabs:** -1. **Notowania** - NAV, valuation date, returns (1D, 1M, YTD, 12M) -2. **Oceny** - AOL ratings, rankings (12M, 36M) -3. **Metryka** - Peer group, category, AUM, fees, risk level - -### Available Data Fields - -**From Listing Pages:** -- ✅ code, name, url (100%) -- ✅ groupname (100%) -- ❌ tfi_company (N/A - foreign funds don't have Polish TFIs) -- ✅ currency (100%) -- ✅ nav_value (13%) -- ✅ valuation_date (100%) -- ✅ ytd_return (95%) - -**From Profile Pages (Additional):** -- ✅ Fund management company (global managers) -- ✅ Fee structure (multiple unit classes) -- ✅ Currency and unit class information -- ✅ Hedged vs non-hedged variants -- ✅ UCITS compliance status -- ✅ Document links (factsheet, KIID, prospectus) - -### FZG Code Structure - -FZG codes follow this pattern: -``` -{PROVIDER}{NUM}_{CLASS}_{CURRENCY} -``` - -**Example:** `FTI068_A_USD` -- `FTI068` - Base code (Franklin Templeton fund #68) -- `A` - Unit class (A = retail, W = institutional, N = other) -- `USD` - Currency (USD, EUR, PLN, PLNH) - -**Parsing FZG Codes:** -```python -code_parts = code.split('_') - -if len(code_parts) == 3: - base_code = code_parts[0] # FTI068 - unit_class = code_parts[1] # A, W, N - currency = code_parts[2] # USD, EUR, PLN, PLNH - - # Check if hedged - is_hedged = currency.endswith('H') # PLNH, EURH - base_currency = currency.rstrip('H') -``` - -### Currency Variants - -Same fund available in multiple currencies: -- **USD** - US Dollar -- **EUR** - Euro -- **PLN** - Polish złoty -- **PLNH** - Polish złoty (currency-hedged) -- **EURH** - Euro (currency-hedged) - -### Unit Classes - -Different share classes for same fund: -- **A** - Retail class (higher fees) -- **W** - Institutional class (lower fees, higher minimums) -- **N** - Other/special classes - -### Global Fund Managers - -Common foreign fund providers: -- Franklin Templeton (Lux) - FTI codes -- Schroders (Lux) - SCH codes -- BlackRock - BLK codes -- JPMorgan - JPM codes -- Fidelity - FID codes - -### Key Differences from FIO - -- Multiple currency variants of same fund -- Multiple unit classes (retail vs institutional) -- Luxembourg domicile (not Polish) -- Self-reported tax treatment (vs automatic withholding for FIO) -- Global investment strategies -- No Good Practices scores -- No TFI company field (use global manager names instead) - ---- - -## Common Fund Codes (Examples) - -### Top FIO Funds by Popularity - -- **SKR54** - Skarbiec Spółek Wzrostowych (large-cap Polish equities) -- **PCS55** - PKO Akcji Rynku Złota (gold mining equities) -- **PCS33** - PKO Technologii i Innowacji Globalny (global tech) -- **PZU81** - inPZU Akcje Rynku Złota O (gold equities) -- **ALL91** - Allianz Akcji Rynku Złota (gold equities) -- **SUP59** - Superfund Akcji Blockchain (blockchain/crypto) -- **KAH32** - Esaliens Złota i Metali Szlachetnych (precious metals) - -### Finding More Codes - -1. Browse analizy.pl listings page -2. Search by TFI name on analizy.pl -3. Use fund search functionality on the site -4. Extract from existing datasets -5. Check `config/instrument_master.csv` for known codes - ---- - -## Field Availability Matrix: Listing vs Detail Pages - -| Field | Listing Pages | Detail Pages | Best Source | -|-------|---------------|--------------|-------------| -| **Core Identifiers** | -| code | ✅ 100% | ✅ 100% | Listing (faster) | -| name | ✅ 100% | ✅ 100% | Listing (faster) | -| url | ✅ 100% | ✅ 100% | Listing (faster) | -| isin | ❌ | ✅ 100% | **Detail only** | -| **Classification** | -| peer_group | ✅ 90-95% | ✅ 100% | Listing (sufficient) | -| category | ✅ 100% | ✅ 100% | Listing (faster) | -| tfi_company | ✅ 95-100% | ✅ 100% | Listing (sufficient) | -| **Valuations** | -| nav_value | ✅ 100% | ✅ 100% | Listing (always current) | -| valuation_date | ✅ 100% | ✅ 100% | Listing (always current) | -| currency | ✅ 100% | ✅ 100% | Listing (faster) | -| **Returns** | -| ytd_return | ✅ 85-95% | ✅ 100% | Listing (current) | -| 1m_return | ✅ FIO/FZG | ✅ 100% | Listing | -| 12m_return | ✅ FIO/FZG | ✅ 100% | Listing | -| **Risk Metrics** | -| risk_level (SRI) | ✅ 85-90% | ✅ 100% | Listing (sufficient) | -| sharpe_ratio | ❌ | ✅ 100% | **Detail only** | -| information_ratio | ❌ | ✅ 100% | **Detail only** | -| std_dev | ❌ | ✅ 100% | **Detail only** | -| max_drawdown | ❌ | ✅ 100% | **Detail only** | -| **Operational** | -| aum_mln_pln | ✅ 90% | ✅ 100% | Listing (sufficient) | -| mgmt_fee_max | ✅ 95% | ✅ 100% | Listing (sufficient) | -| inception_date | ❌ | ✅ 100% | **Detail only** | -| fund_manager_name | ❌ | ✅ 90% | **Detail only** | -| **Portfolio** | -| top_holdings | ❌ | ✅ 90% | **Detail only** | -| sector_allocation | ❌ | ✅ 80% | **Detail only** | -| geography_allocation | ❌ | ✅ 80% | **Detail only** | - -**Legend:** -- ✅ Available (% = typical completeness) -- ❌ Not available -- **Detail only** = Must scrape individual fund pages - -**Recommendation:** Use listing pages for 90% of use cases (fund screening, directory building, performance comparison). Reserve detail page scraping for deep analysis of shortlisted funds. diff --git a/claude/skills/quant/analizy-pl-data/references/provider-mapping.md b/claude/skills/quant/analizy-pl-data/references/provider-mapping.md deleted file mode 100644 index bba22356..00000000 --- a/claude/skills/quant/analizy-pl-data/references/provider-mapping.md +++ /dev/null @@ -1,155 +0,0 @@ -# Provider Mapping Reference - -Complete mapping of TFI companies to analizy.pl umbrella fund codes for portfolio PDF downloads. - -## Download URL Pattern - -``` -https://dokumenty.analizy.pl/pobierz/fi/{FUND_CODE}/SP/{DATE} -``` - -- `FUND_CODE`: Umbrella fund code (see table below) -- `SP`: "Skład Portfela" (Portfolio Composition) -- `DATE`: Quarter-end date (YYYY-MM-DD): 03-31, 06-30, 09-30, 12-31 - -## Complete Provider List (26 Providers) - -### Major TFIs (Large Fund Families) - -| Provider ID | TFI Company | Umbrella Code | Funds | Report Size | Notes | -|-------------|-------------|---------------|-------|-------------|-------| -| goldmansachs | Goldman Sachs TFI | ING02 | 35 | 5.2MB | All ING codes return same bulk report | -| pko | PKO TFI | PCS05 | 34 | 408KB | PKO Parasolowy FIO | -| pekao | Pekao TFI | PIO01 | 32 | 6.4MB | All PIO codes return same bulk report | -| santander | Santander TFI | ARK04 | 27 | 2.2MB | ARK13 (Credit Agricole) is separate | -| bnpparibas | BNP Paribas TFI | FOR08 | 19 | 9.6MB | All FOR codes return same bulk report | -| uniqa | UNIQA TFI | AXA05 | 18 | 954KB | Some global funds have smaller reports | - -### Medium TFIs - -| Provider ID | TFI Company | Umbrella Code | Funds | Report Size | Notes | -|-------------|-------------|---------------|-------|-------------|-------| -| quercus | QUERCUS TFI | QRS03 | 14 | 410KB | QRS33/34 return 404 | -| mtfi | mTFI | MBK02 | 13 | 1MB | SKR116-119 also work | -| skarbiec | Skarbiec TFI | SKR01 | 12 | - | SKARBIEC + BPS FIO subfunds | -| millennium | Millennium TFI | MIL04 | 12 | 726KB | All MIL codes return same report | -| superfund | SUPERFUND TFI | SUP12 | 12 | 470KB | All SUP codes return same report | -| amundi | Amundi Polska TFI | AMU05 | 11 | 83KB | All AMU codes return same report | -| velofunds | VeloFunds TFI | NOB08 | 10 | 295KB | All NOB codes return same report | - -### Smaller TFIs - -| Provider ID | TFI Company | Umbrella Code | Funds | Report Size | Notes | -|-------------|-------------|---------------|-------|-------------|-------| -| investor | Investors TFI | DWS02 | 9 | - | Formerly DWS | -| pzu | TFI PZU | PZU01 | 8 | - | PZU + inPZU subfunds | -| alior | Alior TFI | MON03 | 8 | 1MB | All MON codes return same report | -| agiofunds | AgioFunds TFI | AGF04 | 7 | 267KB | All AGF codes return same report | -| allianz | TFI Allianz Polska | ALL01 | 7 | - | Allianz FIO umbrella | -| ipopema | Ipopema TFI | IPO154 | 6 | - | IPO02 returns 404, using IPO154 | -| rockbridge | Rockbridge TFI | AIG02 | 5 | - | Rockbridge Neo umbrella | -| esaliens | Esaliens TFI | KAH02 | 5 | - | KAH01 returns 404, using KAH02 | -| generali | Generali Investments TFI | UNI02 | 15 | - | UNI01 returns 404 | -| vig | VIG / C-QUADRAT TFI | VIG01 | 4 | - | VIG SFIO | -| caspar | Caspar TFI | CAS15 | 4 | 765KB | All CAS codes return same report | -| templeton | Templeton Asset Management TFI | TEM01 | 3 | 494KB | Franklin Templeton FIO | -| eques | Eques Investment TFI | PLJ51 | 1 | 186KB | Only 1 fund | - -## Working vs Non-Working Codes - -### Codes Returning 404 - -Some codes that appear in instrument_master.csv don't work for bulk downloads: -- `IPO02` → Use `IPO154` instead -- `KAH01` → Use `KAH02` instead -- `UNI01` → Use `UNI02` instead -- `QRS33`, `QRS34` → Use `QRS03` -- `MBK03` → Use `MBK02` - -### Same Report, Multiple Codes - -Many TFIs return the same bulk report regardless of which subfund code is used: -- All `ING*` codes → Same Goldman Sachs report -- All `PIO*` codes → Same Pekao report -- All `FOR*` codes → Same BNP Paribas report -- All `MIL*` codes → Same Millennium report - -## Parser Status - -| Provider | Parser Status | Type | -|----------|--------------|------| -| rockbridge | ✅ Working | Custom | -| pzu | ✅ Working | Custom | -| skarbiec | ✅ Working | Custom | -| allianz | ✅ Working | Custom | -| generali | ✅ Working | Custom | -| vig | ✅ Working | Custom | -| ipopema | ✅ Working | Custom | -| investor | ✅ Working | Custom | -| esaliens | ✅ Working | Custom | -| quercus | ✅ Working | IZFiA | -| velofunds | ✅ Working | IZFiA | -| millennium | ✅ Working | IZFiA | -| alior | ✅ Working | IZFiA | -| santander | ✅ Working | IZFiA | -| bnpparibas | ✅ Working | IZFiA | -| pko | ✅ Working | IZFiA | -| amundi | ✅ Working | IZFiA | -| mtfi | ✅ Working | IZFiA | -| pekao | ⚠️ Needs parser | Has data | -| goldmansachs | ❌ Image PDF | Needs OCR | -| uniqa | ❌ Text PDF | No tables | -| superfund | ❌ Text PDF | No tables | -| agiofunds | ❌ Text PDF | No tables | -| caspar | ❌ Text PDF | No tables | -| templeton | ❌ Text PDF | No tables | -| eques | ❌ Text PDF | 1 fund only | - -## Usage Example - -```python -import requests -from pathlib import Path - -def download_portfolio_pdf(provider: str, code: str, date: str, output_dir: Path): - """Download portfolio PDF for a provider.""" - url = f"https://dokumenty.analizy.pl/pobierz/fi/{code}/SP/{date}" - response = requests.get(url, timeout=60) - - if response.status_code == 200: - filename = f"PAR_{code}__SP__{date}.pdf" - output_path = output_dir / provider / filename - output_path.parent.mkdir(parents=True, exist_ok=True) - output_path.write_bytes(response.content) - return output_path - else: - raise ValueError(f"Failed to download: {url} (status: {response.status_code})") - -# Example usage -download_portfolio_pdf("rockbridge", "AIG02", "2025-09-30", Path("data/raw/fund_holdings")) -``` - -## Configuration File - -Full mapping is stored in `config/provider_mapping.json` with schema: - -```json -{ - "download_url_pattern": "https://dokumenty.analizy.pl/pobierz/fi/{FUND_CODE}/SP/{DATE}", - "quarter_end_dates": ["03-31", "06-30", "09-30", "12-31"], - "providers": [ - { - "provider_id": "rockbridge", - "tfi_company": "Rockbridge TFI", - "umbrella_codes": ["AIG02"], - "umbrella_names": ["Rockbridge Neo FIO"], - "download_verified": true, - "notes": "..." - } - ] -} -``` - -## Last Verified - -All URLs tested: 2026-01-26 diff --git a/claude/skills/quant/analizy-pl-data/references/regex-patterns.md b/claude/skills/quant/analizy-pl-data/references/regex-patterns.md deleted file mode 100644 index d0db16dc..00000000 --- a/claude/skills/quant/analizy-pl-data/references/regex-patterns.md +++ /dev/null @@ -1,375 +0,0 @@ -# Regex Patterns for Data Extraction - -This document contains all regex patterns for extracting fund data from analizy.pl listing pages and profile pages. - -## Critical Formatting Note - -**Markdown links include title attributes that break simple patterns.** - -Example markdown structure: -```markdown -[Profil funduszu: Fund Name](https://www.analizy.pl/...url... "title attribute here") -``` - -**Key fix:** Use `[^\)\"]+` instead of `[^\)]+` to stop at either `)` or `"` (title attribute delimiter). - ---- - -## Listing Page Patterns (Markdown) - -### Fund Header Pattern - -Extracts fund code, name, URL, and type from listing page markdown. - -**FIO (Open-End Funds):** -```python -pattern = r'\[Profil funduszu: ([^\]]+)\]\((https://www\.analizy\.pl/fundusze-inwestycyjne-otwarte/([A-Z0-9]+)/[^\)\"]+)' -``` - -**FIZ (Closed-End Funds):** -```python -pattern = r'\[Profil funduszu: ([^\]]+)\]\((https://www\.analizy\.pl/fundusze-inwestycyjne-zamkniete/([A-Z0-9]+)/[^\)\"]+)' -``` - -**FZG (Foreign Funds):** -```python -pattern = r'\[Profil funduszu: ([^\]]+)\]\((https://www\.analizy\.pl/fundusze-zagraniczne/([A-Z0-9_]+)/[^\)\"]+)' -``` - -**Universal Pattern (All Types):** -```python -pattern = r'\[Profil funduszu: ([^\]]+)\]\((https://www\.analizy\.pl/fundusze-inwestycyjne-(otwarte|zamkniete|zagraniczne)/([A-Z0-9_]+)/[^\)\"]+)\)' - -# Groups: -# 1: fund name -# 2: full URL -# 3: fund type (otwarte/zamkniete/zagraniczne → fio/fiz/fzg) -# 4: fund code -``` - -**Type Mapping:** -```python -type_map = { - 'otwarte': 'fio', - 'zamkniete': 'fiz', - 'zagraniczne': 'fzg' -} -``` - ---- - -### Peer Group Pattern - -Extract peer group from markdown content after fund header. - -**Python Function:** -```python -def extract_peer_group(content_after_header: str) -> str: - """ - Extract peer group from listing page markdown. - - Peer group appears after category badge, before TFI company. - Contains Polish keywords: akcji, obligacji, mieszane, etc. - """ - lines = content_after_header.split('\n') - - # Skip these category badges - SKIP_BADGES = ['Akcyjne', 'Dłużne', 'Mieszane', 'Pozostałe', 'Absolute return'] - - # Polish keywords in peer groups - KEYWORDS = ['akcji', 'obligacji', 'papierów', 'mieszane', 'absolutnej', - 'dłużnych', 'polskich', 'zagranicznych', 'globalnych', 'stopy', - 'rynku', 'wzrostu', 'korporacyjnych', 'skarbowych'] - - found_heading = False - - for line in lines[:25]: - line = line.strip() - - # Skip empty, URLs, badges - if not line or len(line) < 8: - continue - if line.startswith('[') or line.startswith('http'): - continue - if line in SKIP_BADGES: - continue - - # Skip heading (## Fund Name) - if line.startswith('##'): - found_heading = True - continue - - # After heading, find line with Polish keywords - if found_heading: - if any(kw in line.lower() for kw in KEYWORDS): - return line - - return None -``` - -**Common Peer Groups:** - -FIO Examples: -- `akcji polskich uniwersalne` -- `papierów dłużnych polskich skarbowych` -- `mieszane polskie zrównoważone` - -FIZ Examples: -- `absolutnej stopy zwrotu uniwersalne` -- `wierzytelności` - -FZG Examples: -- `akcji globalnych rynków rozwiniętych` -- `obligacji globalnych` - ---- - -### TFI Company Pattern - -Extract management company name from markdown content. - -**Python Function:** -```python -def extract_tfi_company(content: str) -> str: - """Extract TFI company name from markdown content.""" - lines = content.split('\n') - - for line in lines[:30]: - line = line.strip() - - # TFI names contain "TFI" or "Towarzystwo" - if 'TFI' in line or 'Towarzystwo' in line: - # Length check (TFI names are 15-80 chars) - if 10 < len(line) < 80: - # Skip lines that are labels, not names - if not any(skip in line for skip in ['Nazwa towarzystwa', 'firma', 'opłata']): - return line - - return None -``` - -**TFI Name Patterns:** -- Polish: `PKO TFI S.A.`, `TFI Allianz Polska`, `Skarbiec TFI S.A.` -- Foreign (FZG): `Franklin Templeton (Lux)`, `Schroders (Lux)`, `BlackRock (Lux)` - ---- - -### Currency Pattern - -Extract currency code from markdown content. - -**Regex:** -```python -pattern = r'\b(PLN[DP]?|EUR|USD)\b' -``` - -**Python Function:** -```python -def extract_currency(content: str) -> str: - """Extract currency code from markdown content.""" - match = re.search(r'\b(PLN[DP]?|EUR|USD)\b', content) - - if match: - currency_raw = match.group(1) - # PLND = distribution units, PLNP = accumulation units - # For directory purposes, map to base currency - return currency_raw[:3] if currency_raw.startswith('PLN') else currency_raw - - return 'PLN' # Default for Polish funds -``` - ---- - -### NAV Value Pattern - -Extract current NAV value from markdown. - -**Regex:** -```python -pattern = r'([\d\s]+,\d+)\s*PLN\s*Wartość certyfikatu' -``` - -**Python Function:** -```python -def extract_nav_value(content: str) -> str: - """Extract NAV value from markdown content.""" - nav_match = re.search(r'([\d\s]+,\d+)\s*PLN\s*Wartość certyfikatu', content) - if nav_match: - return nav_match.group(1).replace(' ', '').strip() - return None -``` - ---- - -### Valuation Date Pattern - -Extract latest valuation date from markdown. - -**Regex:** -```python -pattern = r'\b(\d{2}\.\d{2}\.\d{4})\b' -``` - -**Format:** DD.MM.YYYY - ---- - -### YTD Return Pattern - -Extract year-to-date return from markdown. - -**Regex:** -```python -pattern = r'([+-]?\d+,\d+)%\s*YTD' -``` - -**Example:** `+29.6%` or `-2.1%` - ---- - -### Valuation Frequency Pattern (FIZ Only) - -Extract valuation frequency for closed-end funds. - -**Python Function:** -```python -def extract_valuation_frequency(content: str) -> str: - """Extract valuation frequency for FIZ funds.""" - if 'miesięczna' in content: - return 'miesięczna' # Monthly - elif 'kwartalna' in content: - return 'kwartalna' # Quarterly - return None -``` - ---- - -## Profile Page Patterns (HTML) - -### Peer Group Pattern (Most Reliable) - -Extract peer group from fund profile page HTML. - -**Regex:** -```python -peer_group_pattern = r'Nazwa\s+grupy

\s*]*class="[^"]*basicValue[^"]*"[^>]*>\s*]*>([^<]+)

' -``` - -**Usage:** -```python -match = re.search(peer_group_pattern, html_text, re.IGNORECASE) -if match: - peer_group = match.group(1).strip().replace(' ', ' ') -``` - -**HTML Structure:** -```html -

Nazwa grupy

-

- akcji globalnych rynków rozwiniętych -

-``` - ---- - -### TFI Company Pattern (HTML) - -**Regex:** -```python -tfi_pattern = r'Nazwa\s+towarzystwa[^>]*>[^>]*>([^<]+)<' -``` - ---- - -### Management Fee Pattern - -**Regex:** -```python -fee_pattern = r'Aktualna\s+opłata\s+stała[^>]*>[^>]*>([\d,]+)\s*%' -``` - -**Usage:** -```python -match = re.search(fee_pattern, html_text) -mgmt_fee = match.group(1).replace(',', '.') if match else None -``` - ---- - -### First Valuation Date Pattern - -**Regex:** -```python -date_pattern = r'Data\s+pierwszej\s+wyceny[^>]*>[^>]*>(\d{2}\.\d{2}\.\d{4})' -``` - -**Format:** DD.MM.YYYY - ---- - -## Complete Extraction Function (HTML) - -```python -import re -from typing import Dict, Optional - -def extract_fund_metadata(fund_code: str, html_text: str) -> Dict[str, Optional[str]]: - """ - Extract core metadata from fund profile page HTML. - - Returns dict with: code, peer_group_detailed, tfi_company, - mgmt_fee_current, first_valuation_date - """ - - metadata = {'code': fund_code} - - # 1. Peer group - MOST RELIABLE PATTERN - peer_group_pattern = r'Nazwa\s+grupy

\s*]*class="[^"]*basicValue[^"]*"[^>]*>\s*]*>([^<]+)

' - match = re.search(peer_group_pattern, html_text, re.IGNORECASE) - if match: - peer_group = match.group(1).strip().replace(' ', ' ') - metadata['peer_group_detailed'] = peer_group - else: - metadata['peer_group_detailed'] = None - - # 2. TFI company - tfi_pattern = r'Nazwa\s+towarzystwa[^>]*>[^>]*>([^<]+)<' - match = re.search(tfi_pattern, html_text) - metadata['tfi_company'] = match.group(1).strip() if match else None - - # 3. Management fee - fee_pattern = r'Aktualna\s+opłata\s+stała[^>]*>[^>]*>([\d,]+)\s*%' - match = re.search(fee_pattern, html_text) - metadata['mgmt_fee_current'] = match.group(1).replace(',', '.') if match else None - - # 4. First valuation date - date_pattern = r'Data\s+pierwszej\s+wyceny[^>]*>[^>]*>(\d{2}\.\d{2}\.\d{4})' - match = re.search(date_pattern, html_text) - metadata['first_valuation_date'] = match.group(1) if match else None - - return metadata -``` - ---- - -## Common Pitfalls - -### Problem 1: Benchmark field captures too much HTML -- **Cause:** Greedy regex patterns capture entire HTML sections -- **Solution:** Skip benchmark field or use very strict patterns -- **Impact:** Can corrupt CSV files with thousands of lines per record - -### Problem 2: HTML entities in extracted text -- **Cause:** Polish characters encoded as HTML entities (e.g., `ę`) -- **Solution:** Replace ` ` with space, let pandas handle other entities -- **Check:** Look for `&#` in extracted peer groups - indicates corruption - -### Problem 3: Different HTML for equity vs debt funds -- **Cause:** Analizy.pl uses different templates for different fund types -- **Solution:** Use the `basicValue` pattern which works for ALL fund types -- **Test:** Validate on both debt funds (e.g., ALL100) and equity funds (e.g., SKR54) - -### Problem 4: Title attributes in markdown links -- **Cause:** Markdown links include `"title"` attributes -- **Solution:** Use `[^\)\"]+` instead of `[^\)]+` in URL capture groups -- **Example:** `[Link](url "title")` requires stopping at `"` delimiter diff --git a/claude/skills/quant/analizy-pl-data/references/troubleshooting.md b/claude/skills/quant/analizy-pl-data/references/troubleshooting.md deleted file mode 100644 index bec271fc..00000000 --- a/claude/skills/quant/analizy-pl-data/references/troubleshooting.md +++ /dev/null @@ -1,580 +0,0 @@ -# Troubleshooting Guide - -This document contains solutions to common issues when working with analizy.pl data. - -## API Issues - -### Problem: API Returns 404 - -**Symptoms:** -- HTTP 404 response when calling quotation or performance API -- Fund code appears valid - -**Causes:** -- Fund code is invalid or incorrectly formatted -- Fund has been liquidated or delisted -- Wrong fund type (using FIO endpoint for FZG fund) - -**Solutions:** -1. Verify fund code spelling and format: - - FIO: Uppercase letters and numbers (e.g., `SKR54`) - - FZG: Underscores for unit class/currency (e.g., `FTI068_A_USD`) - -2. Check fund still exists on analizy.pl listings - -3. Verify fund type matches endpoint: - ```python - # Correct - https://www.analizy.pl/api/quotation/fio/SKR54 - https://www.analizy.pl/api/quotation/fzg/FTI068_A_USD - - # Wrong - https://www.analizy.pl/api/quotation/fzg/SKR54 # FIO code on FZG endpoint - ``` - ---- - -### Problem: Response Too Large (Timeout) - -**Symptoms:** -- Timeout errors when fetching quotation API -- Request takes >60 seconds -- Memory errors when processing response - -**Cause:** -- Quotation API returns years of daily data (3,000+ records) -- Default timeout too short -- Processing entire response in memory - -**Solutions:** -1. Increase timeout to 60-120 seconds: - ```python - response = requests.get(url, timeout=120) - ``` - -2. Stream response directly to file: - ```python - import requests - - response = requests.get(url, timeout=120, stream=True) - with open('output.json', 'wb') as f: - for chunk in response.iter_content(chunk_size=8192): - f.write(chunk) - ``` - -3. Process in chunks if loading to DataFrame: - ```python - import pandas as pd - from io import StringIO - - # Fetch and save - response = requests.get(url, timeout=120) - data = response.json() - - # Convert and save immediately - df = pd.DataFrame(data['series'][0]['price']) - df.to_parquet('quotations.parquet') # More efficient than CSV - ``` - ---- - -### Problem: Rate Limited (429 Error) - -**Symptoms:** -- HTTP 429 "Too Many Requests" response -- Requests succeed initially then start failing - -**Cause:** -- Too many requests too quickly -- Server rate limiting triggered - -**Solutions:** -1. Increase delays between requests: - ```python - import time - - for fund_code in fund_codes: - response = requests.get(url) - time.sleep(3) # Increase from 1-2s to 3-5s - ``` - -2. Implement exponential backoff: - ```python - import time - import requests - - def fetch_with_backoff(url, max_retries=3): - for attempt in range(max_retries): - try: - response = requests.get(url, timeout=60) - if response.status_code == 429: - wait_time = 2 ** attempt # 1s, 2s, 4s - print(f"Rate limited, waiting {wait_time}s...") - time.sleep(wait_time) - continue - return response - except requests.RequestException as e: - if attempt == max_retries - 1: - raise - time.sleep(2 ** attempt) - - raise Exception("Max retries exceeded") - ``` - ---- - -## Scraping Issues - -### Problem: Firecrawl Rate Limit Exceeded - -**Symptoms:** -- Firecrawl returns rate limit error -- "11 requests per minute" error message - -**Cause:** -- Delay between requests is too short -- Free tier limit: 11 requests/minute - -**Solutions:** -1. Increase `DELAY_BETWEEN_PAGES` to 6.0 seconds: - ```python - DELAY_BETWEEN_PAGES = 6.0 # 60s ÷ 11 req = 5.45s minimum - - for page in range(1, total_pages + 1): - result = app.scrape(url=url, formats=['markdown']) - time.sleep(DELAY_BETWEEN_PAGES) - ``` - -2. Check Firecrawl API usage: - ```python - # Add logging to track request timing - import time - - start_time = time.time() - request_times = [] - - for page in range(1, total_pages + 1): - page_start = time.time() - result = app.scrape(url=url, formats=['markdown']) - request_times.append(time.time() - page_start) - - print(f"Page {page}: {request_times[-1]:.2f}s") - time.sleep(6.0) - ``` - ---- - -### Problem: No Funds Extracted from Listing Page - -**Symptoms:** -- Scraping succeeds but returns 0 funds -- Markdown content exists but parsing fails - -**Cause:** -- Regex pattern doesn't handle title attributes in markdown links -- Pattern uses `[^\)]+` instead of `[^\)\"]+` - -**Solution:** -Use pattern that stops at either `)` or `"`: -```python -# Wrong - doesn't handle title attributes -pattern = r'\[Profil funduszu: ([^\]]+)\]\((https://www\.analizy\.pl/[^\)]+)\)' - -# Correct - stops at " or ) -pattern = r'\[Profil funduszu: ([^\]]+)\]\((https://www\.analizy\.pl/[^\)\"]+)' -``` - -**Test:** -```python -# Save markdown from first page -result = app.scrape(url=first_page_url, formats=['markdown']) -with open('test_page.md', 'w', encoding='utf-8') as f: - f.write(result.markdown) - -# Test pattern against saved file -import re -with open('test_page.md', 'r', encoding='utf-8') as f: - markdown = f.read() - -matches = re.finditer(pattern, markdown) -print(f"Found {len(list(matches))} funds") -``` - ---- - -### Problem: Unicode Encoding Fails on Windows - -**Symptoms:** -- `UnicodeEncodeError` when printing progress -- Characters like ✓, →, • fail to display - -**Cause:** -- Windows console doesn't support all Unicode characters -- Default encoding is cp1252, not UTF-8 - -**Solutions:** -1. Use ASCII equivalents: - ```python - # Replace Unicode characters - print("[OK]") # instead of "✓" - print("->") # instead of "→" - print("*") # instead of "•" - ``` - -2. Configure console for UTF-8 (Windows 10+): - ```python - import sys - import io - - # Force UTF-8 output - sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') - ``` - -3. Handle encoding in save operations: - ```python - # Save with explicit UTF-8 encoding - df.to_csv('output.csv', index=False, encoding='utf-8-sig') # BOM for Excel - ``` - ---- - -### Problem: ModuleNotFoundError for firecrawl - -**Symptoms:** -- `ModuleNotFoundError: No module named 'firecrawl'` -- Import fails despite installation - -**Cause:** -- Package not installed -- Wrong package name (old versions) - -**Solutions:** -1. Install correct package: - ```bash - uv add firecrawl-py python-dotenv - ``` - -2. Verify installation: - ```bash - uv pip list | grep firecrawl - ``` - -3. Check import syntax for v4.8.0: - ```python - # Correct for v4.8.0+ - from firecrawl import Firecrawl - - # Wrong - old v3 syntax - from firecrawl import FirecrawlApp - ``` - ---- - -### Problem: "No API key provided" - -**Symptoms:** -- Firecrawl initialization fails -- Error: "No API key provided" - -**Cause:** -- FIRECRAWL_API_KEY not in environment -- .env file not loaded or in wrong location - -**Solutions:** -1. Create .env file in project root: - ```bash - echo "FIRECRAWL_API_KEY=your-key-here" >> .env - ``` - -2. Load environment variables: - ```python - from dotenv import load_dotenv - - load_dotenv() # Must be called before Firecrawl() - app = Firecrawl() - ``` - -3. Verify .env location: - ```python - from pathlib import Path - - env_file = Path('.env') - if not env_file.exists(): - print(f".env not found at: {env_file.absolute()}") - ``` - -4. Alternative - explicit API key: - ```python - import os - - api_key = os.getenv('FIRECRAWL_API_KEY') - if not api_key: - raise ValueError("FIRECRAWL_API_KEY not found in environment") - - app = Firecrawl(api_key=api_key) - ``` - ---- - -## Data Quality Issues - -### Problem: Peer Group Extraction Fails (Returns None) - -**Symptoms:** -- Peer group field is None/empty for most funds -- Pattern works for some funds but not others - -**Cause:** -- Regex pattern doesn't match HTML structure -- Different HTML templates for different fund types - -**Solutions:** -1. Use reliable `basicValue` pattern: - ```python - pattern = r'Nazwa\s+grupy

\s*]*class="[^"]*basicValue[^"]*"[^>]*>\s*]*>([^<]+)

' - ``` - -2. Test on multiple fund types: - ```python - test_funds = [ - ('ALL100', 'debt'), # Debt fund - ('SKR54', 'equity'), # Equity fund - ('ARK04', 'mixed') # Mixed fund - ] - - for code, fund_type in test_funds: - metadata = fetch_fund_metadata(code, url) - print(f"{code} ({fund_type}): {metadata['peer_group']}") - ``` - -3. Debug by inspecting HTML: - ```python - # Save HTML snippet around "Nazwa grupy" - import re - - match = re.search(r'(Nazwa\s+grupy.{200})', html_text, re.DOTALL) - if match: - print(match.group(1)) - ``` - ---- - -### Problem: CSV Corruption with Multiline Fields - -**Symptoms:** -- CSV file has thousands of lines per record -- Data appears corrupted when loading -- Excel/pandas shows garbled content - -**Cause:** -- Extracted fields contain HTML fragments spanning many lines -- Benchmark field captures entire HTML sections - -**Solutions:** -1. Skip problematic fields: - ```python - # Don't extract benchmark - causes corruption - # metadata['benchmark'] = extract_benchmark(html) # SKIP THIS - ``` - -2. Validate field length before saving: - ```python - MAX_FIELD_LENGTH = 80 - - if 'peer_group' in metadata: - if len(metadata['peer_group']) > MAX_FIELD_LENGTH: - print(f"Warning: peer_group too long ({len(metadata['peer_group'])} chars)") - metadata['peer_group'] = None - ``` - -3. Check for HTML entities: - ```python - if '&#' in str(metadata.get('peer_group', '')): - print(f"Warning: HTML entities in peer_group for {code}") - metadata['peer_group'] = None - ``` - -4. Use strict regex patterns: - ```python - # Non-greedy, specific stop conditions - pattern = r'Nazwa\s+grupy

\s*]*>([^<]+)

' # Stops at first

- ``` - ---- - -### Problem: Different Success Rates for Fund Types - -**Symptoms:** -- 95% success for equity funds -- 60% success for debt funds -- Different extraction rates by category - -**Cause:** -- Different HTML templates for different fund categories -- Pattern optimized for one type - -**Solutions:** -1. Test pattern on all fund types before batch processing: - ```python - test_samples = { - 'equity': ['SKR54', 'PCS55'], - 'debt': ['ALL100', 'PZU91'], - 'mixed': ['ARK04', 'PKO21'] - } - - for category, codes in test_samples.items(): - success = 0 - for code in codes: - metadata = fetch_fund_metadata(code, get_url(code)) - if metadata['peer_group']: - success += 1 - print(f"{category}: {success}/{len(codes)} success") - ``` - -2. Use universal pattern (basicValue): - ```python - # Works for all fund types - pattern = r'Nazwa\s+grupy

\s*]*class="[^"]*basicValue[^"]*"[^>]*>\s*]*>([^<]+)

' - ``` - ---- - -## Performance Issues - -### Problem: HTML Structure Changed - -**Symptoms:** -- Scraping worked previously but now fails -- All funds return None for metadata fields -- Pattern matches but extracts wrong content - -**Cause:** -- Analizy.pl website redesign -- HTML class names or structure changed - -**Solutions:** -1. Fetch fresh HTML and inspect: - ```python - import requests - - response = requests.get(url, headers=headers) - with open('current_html.html', 'w', encoding='utf-8') as f: - f.write(response.text) - - # Open in browser and inspect structure - ``` - -2. Search for key labels: - ```python - # Find all instances of "Nazwa grupy" - import re - - matches = re.finditer(r'Nazwa\s+grupy(.{300})', html, re.DOTALL) - for i, match in enumerate(matches, 1): - print(f"\n=== Instance {i} ===") - print(match.group(0)) - ``` - -3. Update CSS selectors/patterns based on new structure - ---- - -### Problem: Performance Table Format Changed - -**Symptoms:** -- pandas.read_html() fails -- Table parsing returns wrong data -- Column names don't match expected - -**Cause:** -- Analizy.pl updated table structure -- New columns added or order changed - -**Solutions:** -1. Inspect actual HTML response: - ```python - url = "https://www.analizy.pl/api/rate-of-return/fio/SKR54" - response = requests.get(url) - - with open('performance_table.html', 'w', encoding='utf-8') as f: - f.write(response.text) - ``` - -2. Adjust pandas parsing parameters: - ```python - tables = pd.read_html(url, header=0) # Try with header - # or - tables = pd.read_html(url, skiprows=1) # Skip first row - ``` - -3. Parse manually if needed: - ```python - from bs4 import BeautifulSoup - - soup = BeautifulSoup(response.text, 'html.parser') - table = soup.find('table') - - # Extract data manually - rows = table.find_all('tr') - for row in rows: - cells = row.find_all(['td', 'th']) - print([cell.text.strip() for cell in cells]) - ``` - ---- - -## Best Practices to Avoid Issues - -1. **Always test on samples first:** - ```python - # Test scraper on 5 funds before running on 2,000 - test_codes = fund_codes[:5] - for code in test_codes: - result = scrape_fund(code) - verify_result(result) - ``` - -2. **Save checkpoints frequently:** - ```python - if idx % 50 == 0: - pd.DataFrame(results).to_csv(f'checkpoint_{idx}.csv') - ``` - -3. **Log errors with context:** - ```python - import logging - - logging.basicConfig( - filename='scraping.log', - level=logging.ERROR, - format='%(asctime)s - %(message)s' - ) - - try: - metadata = fetch_fund(code) - except Exception as e: - logging.error(f"Fund {code}: {e}") - ``` - -4. **Validate extracted data:** - ```python - def validate_metadata(metadata): - """Validate extracted metadata quality.""" - issues = [] - - if metadata.get('peer_group') and len(metadata['peer_group']) > 80: - issues.append('peer_group too long') - - if '&#' in str(metadata.get('peer_group', '')): - issues.append('HTML entities in peer_group') - - if not metadata.get('code'): - issues.append('missing code') - - return issues - - # Use in scraping loop - issues = validate_metadata(metadata) - if issues: - print(f"Validation issues for {code}: {issues}") - ``` diff --git a/claude/skills/quant/atlasetf-scraper/SKILL.md b/claude/skills/quant/atlasetf-scraper/SKILL.md deleted file mode 100644 index 1bf9f7fc..00000000 --- a/claude/skills/quant/atlasetf-scraper/SKILL.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -name: atlasetf-scraper -description: >- - Scrape ETF data from atlasetf.pl (aka "atlas etf", "atlasETF", "atlas-etf") - via its JSON API: the full ~13,000-fund screener, per-ISIN detail, - fundamentals and dividends, and price/quote (OHLC) data. Use whenever the user - wants to scrape, download, export, or query ETF data from atlasetf.pl — even - casual phrasings that just name the site. Not for other sources (justETF, - stooq, Yahoo, brokerage statements) or general ETF advice. ---- - -# atlasetf.pl Scraper - -atlasetf.pl is a Polish ETF research site. The front end is a React single-page -app, so fetching the raw HTML (`GET https://atlasetf.pl/`) returns only a -"JavaScript required" shell with **no data**. Don't scrape the DOM. Instead, hit -the site's own public JSON API at `https://atlasetf.pl/api/v2/`, which is what -the app itself calls. - -All endpoints are `POST` with a JSON body and need no API key for the public -data (only personal/premium account features are login-gated). This was verified -by inspecting the live site's network traffic. - -## When to use this skill - -Trigger whenever the user wants ETF data that lives on atlasetf.pl: a list/ -screener export, fundamentals for specific funds, returns/TER comparisons, or -price/quote data. The user may phrase it as "scrape", "download", "get me a -spreadsheet of...", "pull every ETF with...", or just name the site. - -## The three things people usually want - -1. **The ETF list / screener** — every fund with returns, TER, size, provider, etc. -2. **Per-ETF detail** — full fundamentals for one or more ISINs. -3. **Prices / quotes** — OHLC + intraday quote data. - -The bundled script handles all three. Read `references/api_reference.md` for the -exact endpoints, request bodies, and response fields before writing custom calls. - -## How to do it - -Use the bundled script `scripts/atlas_scraper.py` — it already encodes the -verified payloads, pagination, polite throttling, and retry/backoff. Don't -re-derive the API by hand unless the script fails; in that case consult -`references/api_reference.md`. - -Common invocations (run from the skill directory): - -```bash -# Full ETF list -> CSV (all ~13k funds, paginated automatically) -python scripts/atlas_scraper.py list --out etfs.csv - -# Filtered list (e.g., only Polish-domiciled accumulating equity) -> CSV -python scripts/atlas_scraper.py list --search "msci world" --out world.csv - -# Detail/fundamentals for one or more ISINs -> JSON -python scripts/atlas_scraper.py detail IE00B4L5YX21 IE00B5BMR087 --out detail.json - -# Homepage quote/price feeds -> JSON -python scripts/atlas_scraper.py prices --out prices.json -``` - -Run `python scripts/atlas_scraper.py --help` for all options (language, -currency, page size, delay, output format). - -If the user wants the result as a spreadsheet, the `list` command writes CSV by -default (`--out file.csv`); for `.xlsx`, pass `--format xlsx` or hand the CSV to -the spreadsheet workflow. - -## Throttling and terms of use — important - -atlasetf.pl is a **commercial data product**, and much of its data is licensed -from third parties (e.g. EOD Historical Data, Morningstar). Scrape considerately -so you don't hammer their servers or overstep their terms: - -- The script defaults to a **1 request/second** rate limit and exponential - backoff on errors. Keep it on. Don't crank concurrency. -- A full list pull is ~130 paginated requests; per-ETF detail is one request per - ISIN (~13k if you pull everything), so only fetch detail for funds the user - actually needs. -- Before any bulk pull, **remind the user to check `https://atlasetf.pl/robots.txt` - and the site's Terms of Service**, and not to redistribute the data. If the - user wants to scrape the entire universe repeatedly or commercially, flag that - this may exceed acceptable use and suggest they confirm they're allowed to. -- Set a real, identifying `User-Agent` (the script does). Don't try to evade any - rate limiting or blocks — if the site blocks you, stop and tell the user. - -## Auth-gated endpoints - -These return HTTP 403 without a logged-in session and are out of scope for -public scraping: `/api/v2/user/status`, `/api/v2/user/favourite-etfs`, -`/api/v2/user/etf/fundamentals` (premium fundamentals). Don't attempt to bypass -the login. diff --git a/claude/skills/quant/atlasetf-scraper/references/api_reference.md b/claude/skills/quant/atlasetf-scraper/references/api_reference.md deleted file mode 100644 index f052e179..00000000 --- a/claude/skills/quant/atlasetf-scraper/references/api_reference.md +++ /dev/null @@ -1,140 +0,0 @@ -# atlasetf.pl API Reference - -Reverse-engineered from the live site's network traffic (verified working). -Base URL: `https://atlasetf.pl/api/v2/`. All calls are `POST` with -`Content-Type: application/json`. No API key needed for the endpoints below; -only `/api/v2/user/*` requires a logged-in session (returns 403 otherwise). - -From a server, set headers `User-Agent`, and if you get blocked, `Origin: -https://atlasetf.pl` and `Referer: https://atlasetf.pl/`. No CAPTCHA observed. - -Most bodies accept `"lang"` (`"pl"` or `"en"`) and `"currency"` (`"PLN"`, -`"EUR"`, `"USD"`). - -## Table of contents -1. ETF list / screener — `etf/search` -2. Per-ETF detail — `etf/details` and friends -3. Prices / quotes -4. Auth-gated endpoints - ---- - -## 1. ETF list / screener - -`POST /api/v2/etf/search` - -The screener. Returns paginated ETF rows plus every filter facet. Empty filter -arrays = no filtering (returns the whole universe). - -Request body: -```json -{ - "filter": { - "class": null, "class_name": null, - "investment_area": [], "global_category": [], "morningstar_category": [], - "fund_yield_12m": [], "fi_average_yield_to_maturity": [], - "fi_effective_maturity": [], "fi_average_effective_duration": [], - "brokers": [], "broker_accounts": [], "groups": [], "providers": [], - "distribution_policy": null, "exchanges": [], "trade_currencies": [], - "domiciles": [], "replication": [], "age": null, "ter": [], - "fund_size": null, "currency_risk": null, "xlm": [], "strategy_risks": [], - "distribution_frequencies": [], "matching_index": null, - "search_filter": null, - "page": 1, "row_per_page": 100, - "sort_field": "fund_name", "sort_order": "asc", "ratings": [] - }, - "lang": "pl", "currency": "PLN" -} -``` - -- Free-text search: set `filter.search_filter` to a string (name, ticker, ISIN, - CUSIP). -- Pagination: `filter.page` (1-based) and `filter.row_per_page` (100 works well). -- Sorting: `filter.sort_field` (e.g. `fund_name`, `expense_ratio`, - `return_1y`, `fund_size`) and `filter.sort_order` (`asc`/`desc`). - -Response (top-level keys): -``` -etfs -> array of ETF rows (the data) -row_count -> total matching funds (string, e.g. "13113") -row_per_page, page -class, class_groups, class_summary, brokers, accounts, providers, -distribution_policy, exchanges, domiciles, replication, age, fund_sizes, -currency_risks, trade_currencies, matching_indices, xlm, strategy_risks, -distribution_frequencies, ter, ratings, return_end_date, return_year_y0, -return_year_y1..., category_info -> filter facet options + metadata -``` - -Each item in `etfs`: -``` -isin, ticker, fund_name, fund_currency, fund_size, fund_size_currency, -expense_ratio (TER %), fund_provider, replication_name_lang, -distribution_policy_lang, distribution_frequency_lang, domicile_lang, -inception_date, currency_hedged_lang, rating, -return_1m, return_3m, return_6m, return_1y, return_3y, return_5y, -return_y0, return_y1, return_y2, return_y3, return_y4, return_y5 -``` - -To pull everything: loop `page` from 1 while `(page-1)*row_per_page < row_count`. -At `row_per_page=100` that's ~`ceil(13113/100)=132` requests. - ---- - -## 2. Per-ETF detail - -All keyed by ISIN with body `{"isin": "", "lang": "pl", "currency": "PLN"}`. - -### `POST /api/v2/etf/details` (main fundamentals) -Returns: `isin, cusip, fund_name, expense_ratio, fund_currency, domicile_id, -domicile_name_lang, replication_name_lang, distribution_frequency_lang, -distribution_policy, fund_size, fund_size_currency, inception_date, -fund_provider, fund_provider_url, ucits_compliance, legal_structure, -description, currency_hedged, currency_hedged_to, turnover_ratio, -is_inverse_short_fund, is_actively_managed, benchmark, average_spread, -base_currency, exchange, global_broad_category_lang, morningstar_category, -category_lang, investment_area_lang, administrator, listings, ...` - -`listings` is an array of exchange listings, each: -`{ ticker, exchange, country_name, country_id, currency }`. - -### Other detail endpoints (same `{isin,lang,currency}` body, all public/200) -- `POST /api/v2/etf/extdata` — extended data -- `POST /api/v2/etf/allocations` — holdings / sector / country allocations -- `POST /api/v2/etf/dividend` — dividend history -- `POST /api/v2/etf/documents` — KIID / factsheet document links -- `POST /api/v2/etf/currency` — currency data - ---- - -## 3. Prices / quotes - -Quote data is sourced from EOD Historical Data; codes look like `IWDA.LSE`, -`ETFBW20TR.WAR`, `EURPLN.FOREX`. - -### `POST /api/v2/etf/main-page-quotes` — body `{"lang":"pl"}` -Array of instruments, each with a full `quote` -(`open/high/low/close/volume/previousClose/change/change_p/timestamp/code`) and -a `prices` array of intraday points (`timestamp`, `dateTime`, price). Good -source of live + intraday price data. - -### `POST /api/v2/etf/ticker-marquee-quotes` — body `{"lang":"pl"}` -FX and index quotes (the scrolling ticker). - -### Macro/aggregate feeds -- `POST /api/v2/etf/equity-markets-world` — `{"tab":"World","currency":"PLN","period":"1y"}` -- `POST /api/v2/etf/equity-sectors-world` — `{"lang":"pl","currency":"PLN","period":"1y"}` -- `POST /api/v2/etf/landing-page-map` — `{"lang":"pl","currency":"PLN"}` - -### Per-instrument real-time -`POST /api/v2/etf/real-time` is used on detail pages for a listing's live/ -intraday quote. It expects the listing's exchange-specific code (not just the -ISIN); the exact field wasn't pinned down. If you need per-ISIN intraday, -capture the request body from the detail page's network tab, or fall back to -matching the fund's listing code against `main-page-quotes`. - ---- - -## 4. Auth-gated endpoints (403 without login — out of scope) -- `POST /api/v2/user/status` -- `POST /api/v2/user/favourite-etfs` -- `POST /api/v2/user/etf/fundamentals` (premium fundamentals) diff --git a/claude/skills/quant/atlasetf-scraper/scripts/atlas_scraper.py b/claude/skills/quant/atlasetf-scraper/scripts/atlas_scraper.py deleted file mode 100644 index 527689e0..00000000 --- a/claude/skills/quant/atlasetf-scraper/scripts/atlas_scraper.py +++ /dev/null @@ -1,302 +0,0 @@ -#!/usr/bin/env python3 -""" -atlasetf.pl scraper. - -Pulls ETF data from atlasetf.pl's public JSON API (https://atlasetf.pl/api/v2/): - - list : the ETF screener (all ~13k funds, or filtered), -> CSV/XLSX/JSON - - detail : per-ETF fundamentals for one or more ISINs, -> JSON/CSV - - prices : homepage quote/price feeds, -> JSON - -The site is a JavaScript SPA, so its raw HTML has no data; this script calls the -same REST API the app uses. No API key needed for public data. - -Be considerate: atlasetf.pl is a commercial product with licensed data. This -script rate-limits to ~1 req/s by default and backs off on errors. Check the -site's robots.txt and Terms of Service before bulk-scraping, and don't -redistribute the data. - -Usage: - python atlas_scraper.py list [--search TEXT] [--sort FIELD] [--order asc|desc] - [--page-size N] [--max-pages N] - [--out FILE] [--format csv|xlsx|json] - python atlas_scraper.py detail ISIN [ISIN ...] [--out FILE] [--format json|csv] - [--endpoints details,allocations,dividend,...] - python atlas_scraper.py prices [--feeds main,marquee] [--out FILE] - -Common options: --lang pl|en --currency PLN|EUR|USD --delay SECONDS - -Requires: requests (pip install requests). XLSX output also needs: openpyxl. -""" -import argparse -import csv -import json -import sys -import time - -try: - import requests -except ImportError: - sys.exit("This script needs the 'requests' package: pip install requests") - -BASE = "https://atlasetf.pl/api/v2" -USER_AGENT = "atlasetf-scraper/1.0 (+personal data pull; respects robots.txt)" - -# Columns emitted for `list` CSV/XLSX, in a sensible order. -LIST_COLUMNS = [ - "isin", "ticker", "fund_name", "fund_provider", "fund_currency", - "fund_size", "fund_size_currency", "expense_ratio", - "replication_name_lang", "distribution_policy_lang", - "distribution_frequency_lang", "domicile_lang", "inception_date", - "currency_hedged_lang", "rating", - "return_1m", "return_3m", "return_6m", "return_1y", "return_3y", "return_5y", - "return_y0", "return_y1", "return_y2", "return_y3", "return_y4", "return_y5", -] - - -class AtlasClient: - """Thin, polite client over the atlasetf.pl API.""" - - def __init__(self, lang="pl", currency="PLN", delay=1.0, max_retries=4, - timeout=30): - self.lang = lang - self.currency = currency - self.delay = delay # min seconds between requests - self.max_retries = max_retries - self.timeout = timeout - self._last_call = 0.0 - self.session = requests.Session() - self.session.headers.update({ - "User-Agent": USER_AGENT, - "Content-Type": "application/json", - "Accept": "application/json", - "Origin": "https://atlasetf.pl", - "Referer": "https://atlasetf.pl/", - }) - - def _throttle(self): - wait = self.delay - (time.time() - self._last_call) - if wait > 0: - time.sleep(wait) - - def post(self, path, body): - """POST with throttling + exponential backoff. Returns parsed JSON.""" - url = f"{BASE}/{path.lstrip('/')}" - backoff = self.delay if self.delay > 0 else 1.0 - last_err = None - for attempt in range(self.max_retries): - self._throttle() - try: - r = self.session.post(url, data=json.dumps(body), - timeout=self.timeout) - self._last_call = time.time() - if r.status_code == 200: - return r.json() - if r.status_code == 403: - raise RuntimeError( - f"{path} returned 403 (login required / out of scope).") - if r.status_code in (429, 500, 502, 503, 504): - last_err = f"HTTP {r.status_code}" - eprint(f" {path}: {last_err}, retrying in {backoff:.0f}s " - f"(attempt {attempt+1}/{self.max_retries})") - time.sleep(backoff) - backoff *= 2 - continue - raise RuntimeError(f"{path} returned HTTP {r.status_code}: " - f"{r.text[:200]}") - except requests.RequestException as e: - last_err = str(e) - self._last_call = time.time() - eprint(f" {path}: {last_err}, retrying in {backoff:.0f}s " - f"(attempt {attempt+1}/{self.max_retries})") - time.sleep(backoff) - backoff *= 2 - raise RuntimeError(f"{path} failed after {self.max_retries} attempts: " - f"{last_err}") - - # -- screener --------------------------------------------------------- - def _empty_filter(self, page, page_size, search, sort, order): - return { - "class": None, "class_name": None, "investment_area": [], - "global_category": [], "morningstar_category": [], - "fund_yield_12m": [], "fi_average_yield_to_maturity": [], - "fi_effective_maturity": [], "fi_average_effective_duration": [], - "brokers": [], "broker_accounts": [], "groups": [], "providers": [], - "distribution_policy": None, "exchanges": [], "trade_currencies": [], - "domiciles": [], "replication": [], "age": None, "ter": [], - "fund_size": None, "currency_risk": None, "xlm": [], - "strategy_risks": [], "distribution_frequencies": [], - "matching_index": None, "search_filter": search, - "page": page, "row_per_page": page_size, - "sort_field": sort, "sort_order": order, "ratings": [], - } - - def search_page(self, page, page_size=100, search=None, - sort="fund_name", order="asc"): - body = { - "filter": self._empty_filter(page, page_size, search, sort, order), - "lang": self.lang, "currency": self.currency, - } - return self.post("etf/search", body) - - def search_all(self, page_size=100, search=None, sort="fund_name", - order="asc", max_pages=None): - """Yield ETF rows across all pages.""" - first = self.search_page(1, page_size, search, sort, order) - rows = first.get("etfs", []) - try: - total = int(first.get("row_count") or len(rows)) - except (TypeError, ValueError): - total = len(rows) - total_pages = max(1, -(-total // page_size)) # ceil - if max_pages: - total_pages = min(total_pages, max_pages) - eprint(f"Total matching funds: {total} -> {total_pages} page(s) " - f"of {page_size}") - for r in rows: - yield r - for page in range(2, total_pages + 1): - eprint(f" page {page}/{total_pages}") - data = self.search_page(page, page_size, search, sort, order) - for r in data.get("etfs", []): - yield r - - # -- detail ----------------------------------------------------------- - def detail(self, isin, endpoints=("details",)): - body = {"isin": isin, "lang": self.lang, "currency": self.currency} - out = {"isin": isin} - for ep in endpoints: - try: - out[ep] = self.post(f"etf/{ep}", body) - except RuntimeError as e: - out[ep] = {"_error": str(e)} - return out - - # -- prices ----------------------------------------------------------- - def prices(self, feeds=("main", "marquee")): - out = {} - if "main" in feeds: - out["main_page_quotes"] = self.post("etf/main-page-quotes", - {"lang": self.lang}) - if "marquee" in feeds: - out["ticker_marquee_quotes"] = self.post( - "etf/ticker-marquee-quotes", {"lang": self.lang}) - return out - - -def eprint(*a): - print(*a, file=sys.stderr, flush=True) - - -# -- output helpers ------------------------------------------------------- -def write_rows(rows, out, fmt, columns): - if fmt == "json": - _dump_json(rows, out) - elif fmt == "csv": - _write_csv(rows, out, columns) - elif fmt == "xlsx": - _write_xlsx(rows, out, columns) - else: - sys.exit(f"Unknown format: {fmt}") - - -def _dump_json(obj, out): - if out: - with open(out, "w", encoding="utf-8") as f: - json.dump(obj, f, ensure_ascii=False, indent=2) - eprint(f"Wrote {out}") - else: - print(json.dumps(obj, ensure_ascii=False, indent=2)) - - -def _write_csv(rows, out, columns): - cols = columns or (list(rows[0].keys()) if rows else []) - f = open(out, "w", newline="", encoding="utf-8-sig") if out else sys.stdout - try: - w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore") - w.writeheader() - for r in rows: - w.writerow(r) - finally: - if out: - f.close() - eprint(f"Wrote {len(rows)} rows -> {out}") - - -def _write_xlsx(rows, out, columns): - try: - from openpyxl import Workbook - except ImportError: - sys.exit("XLSX output needs openpyxl: pip install openpyxl") - if not out: - sys.exit("--out is required for xlsx format") - cols = columns or (list(rows[0].keys()) if rows else []) - wb = Workbook() - ws = wb.active - ws.title = "ETFs" - ws.append(cols) - for r in rows: - ws.append([r.get(c) for c in cols]) - wb.save(out) - eprint(f"Wrote {len(rows)} rows -> {out}") - - -# -- CLI ------------------------------------------------------------------ -def main(argv=None): - p = argparse.ArgumentParser(description="Scrape ETF data from atlasetf.pl") - p.add_argument("--lang", default="pl", choices=["pl", "en"]) - p.add_argument("--currency", default="PLN", choices=["PLN", "EUR", "USD"]) - p.add_argument("--delay", type=float, default=1.0, - help="Min seconds between requests (politeness; default 1.0)") - sub = p.add_subparsers(dest="cmd", required=True) - - pl = sub.add_parser("list", help="ETF screener -> CSV/XLSX/JSON") - pl.add_argument("--search", help="Free-text filter (name/ticker/ISIN)") - pl.add_argument("--sort", default="fund_name") - pl.add_argument("--order", default="asc", choices=["asc", "desc"]) - pl.add_argument("--page-size", type=int, default=100) - pl.add_argument("--max-pages", type=int, default=None, - help="Stop after N pages (for sampling)") - pl.add_argument("--out") - pl.add_argument("--format", default="csv", choices=["csv", "xlsx", "json"]) - - pd = sub.add_parser("detail", help="Per-ETF fundamentals -> JSON/CSV") - pd.add_argument("isins", nargs="+", help="One or more ISINs") - pd.add_argument("--endpoints", default="details", - help="Comma-separated: details,extdata,allocations," - "dividend,documents,currency") - pd.add_argument("--out") - pd.add_argument("--format", default="json", choices=["json", "csv"]) - - pp = sub.add_parser("prices", help="Homepage quote/price feeds -> JSON") - pp.add_argument("--feeds", default="main,marquee", - help="Comma-separated: main,marquee") - pp.add_argument("--out") - - args = p.parse_args(argv) - client = AtlasClient(lang=args.lang, currency=args.currency, - delay=args.delay) - - if args.cmd == "list": - rows = list(client.search_all( - page_size=args.page_size, search=args.search, - sort=args.sort, order=args.order, max_pages=args.max_pages)) - cols = LIST_COLUMNS if args.format in ("csv", "xlsx") else None - write_rows(rows, args.out, args.format, cols) - - elif args.cmd == "detail": - endpoints = tuple(e.strip() for e in args.endpoints.split(",") if e.strip()) - results = [client.detail(isin, endpoints) for isin in args.isins] - if args.format == "json": - _dump_json(results if len(results) > 1 else results[0], args.out) - else: # flat CSV of the 'details' payload - flat = [r.get("details", {}) for r in results - if isinstance(r.get("details"), dict)] - _write_csv(flat, args.out, None) - - elif args.cmd == "prices": - feeds = tuple(f.strip() for f in args.feeds.split(",") if f.strip()) - _dump_json(client.prices(feeds), args.out) - - -if __name__ == "__main__": - main() diff --git a/claude/skills/quant/gpw-benchmark-scraper/SKILL.md b/claude/skills/quant/gpw-benchmark-scraper/SKILL.md deleted file mode 100644 index a58e786e..00000000 --- a/claude/skills/quant/gpw-benchmark-scraper/SKILL.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -name: gpw-benchmark-scraper -description: >- - Scrape data from gpwbenchmark.pl (GPW Benchmark, Warsaw Stock Exchange): WIBID - and WIBOR delayed reference rates (the year-to-date /dane-opoznione table), the - full list of stock/bond/strategy indices with their ISINs, and per-index - historical OHLC time series (the karta-indeksu / chart data, keyed by ISIN). - Use whenever the user wants to download, export, scrape, or query GPW Benchmark - index values, index lists, or WIBOR/WIBID rates — even casual phrasings that - just name the site. Not for atlasetf.pl, stooq, justETF, or gpw.pl equities. ---- - -# GPW Benchmark scraper (gpwbenchmark.pl) - -gpwbenchmark.pl renders most of its data tables from its own backend endpoints -(`ajaxindex.php`, `chart-json.php`) and from server-side HTML. This skill hits -those directly. The site sits behind an F5 WAF, so use the exact request shapes -documented in `references/api_reference.md` — don't fuzz parameters. - -## When to use - -Trigger when the user wants any of: -1. **WIBID/WIBOR rates** — the delayed reference-rate table (year-to-date). -2. **Index list** — every GPW Benchmark index with its ISIN (and latest snapshot). -3. **Index history** — daily OHLC time series for one, several, or all indices. - -## How to do it - -Use the bundled script `scripts/gpw_benchmark.py`. It encodes the verified -endpoints, the CDATA/HTML parsing, request throttling (default 1 req/s), and -retry/backoff. Output is CSV. - -```bash -# install deps once -pip install requests beautifulsoup4 - -# 1. WIBID/WIBOR delayed rates (year-to-date) -> wibid_wibor.csv -python scripts/gpw_benchmark.py rates --out wibid_wibor.csv - -# 2. All indices + ISINs across every category -> indices.csv -python scripts/gpw_benchmark.py indices --out indices.csv - -# 3a. History for specific ISIN(s), 1-year daily OHLC -> series_1R.csv -python scripts/gpw_benchmark.py series PL9999999474 PL9999999987 --mode 1R - -# 3b. History for EVERY index (discovers ISINs first) -> series_1R.csv -python scripts/gpw_benchmark.py series --all --mode 1R --out all_series.csv - -# Everything at once (rates + indices + 1Y series for all indices) -python scripts/gpw_benchmark.py all --mode 1R -``` - -Options: `--lang PL|EN`, `--delay `, `--mode {14D,1M,3M,6M,1R}`, -`--batch N` (ISINs per chart request), `--tabs` (subset of index categories). -Run `python scripts/gpw_benchmark.py --help`. - -## Output CSVs - -- **rates** — `Date, WIBID_ON, WIBID_1M, WIBID_3M, WIBID_6M, WIBID_SW, - WIBOR_ON, WIBOR_1M, WIBOR_3M, WIBOR_6M, WIBOR_1Y, WIBOR_SW` (tenor columns are - derived from the live header, so they self-adjust if GPW changes them). -- **indices** — `category, section, shortcode, isin, cmng_id, num, last_time, - twi, open, min, max, last, change_pct, portfolio_pct, turnover_thousands_pln`. -- **series** — long format: `isin, date, timestamp, open, high, low, close` - (date is Europe/Warsaw trading date; `timestamp` is the raw epoch in seconds). - -If the user wants `.xlsx`, hand the CSV to the spreadsheet workflow. - -## Notes / gotchas - -- **`MAX` is not a real window.** The longest server-provided history is `1R` - (one year). For deeper history, GPW Benchmark publishes downloadable - historical files under "Dane historyczne" — out of scope for this scraper. -- The WIBID/WIBOR table is **year-to-date only** and one business-day delayed - (updated ~23:00). -- The same index can appear under multiple category tabs; the script - de-duplicates by ISIN. - -## Terms of use — important - -WIBID® and WIBOR® are **regulated reference rates** administered by GPW -Benchmark S.A. The delayed data is published for information only. -**Redistributing** WIBOR/WIBID, or using them in automated trading or -non-visualised data applications, requires a **Market Data License Agreement** -with GPW Benchmark. Index data is likewise a commercial product. - -Before any bulk or repeated pull: remind the user to check -`https://gpwbenchmark.pl/robots.txt` and the site's terms, keep the throttle on, -set a real identifying `User-Agent` in the script, and not to redistribute the -data. If the site blocks you (the WAF "Request Rejected" page), stop and tell -the user rather than trying to evade it. diff --git a/claude/skills/quant/gpw-benchmark-scraper/references/api_reference.md b/claude/skills/quant/gpw-benchmark-scraper/references/api_reference.md deleted file mode 100644 index 42f8681a..00000000 --- a/claude/skills/quant/gpw-benchmark-scraper/references/api_reference.md +++ /dev/null @@ -1,109 +0,0 @@ -# GPW Benchmark — endpoint reference - -All endpoints were verified by inspecting the live gpwbenchmark.pl front end's -own network traffic (June 2026). No API key is required for this public data. -Polish UI is the default; most endpoints accept `lang=EN` or have an `/en-` -page variant. - -The site is fronted by an F5/BIG-IP WAF. Blind parameter fuzzing gets you a -"Request Rejected" page. Stick to the exact request shapes below, send a normal -`User-Agent` and a `Referer`, and throttle. - ---- - -## 1. WIBID / WIBOR delayed reference rates - -**Page (server-rendered HTML — no AJAX):** - -``` -GET https://gpwbenchmark.pl/dane-opoznione (PL) -GET https://gpwbenchmark.pl/en-dane-opoznione (EN) -``` - -The table lives directly in the page HTML inside `
`. NOTE: a plain -"reader" extraction of the page can drop the table — fetch the raw HTML and -parse the `` that contains both "WIBID" and "WIBOR". - -Structure (two header rows): - -| row | cells | -|-----|-------| -| group row | `(empty)`, `WIBID®` colspan=5, `WIBOR®` colspan=6 | -| tenor row | `Data/Termin`, then `ON 1M 3M 6M SW` (WIBID), then `ON 1M 3M 6M 1Y SW` (WIBOR) | -| data rows | `YYYY-MM-DD`, then numeric values, comma decimal e.g. `3,53` | - -Coverage: **year-to-date**, one business-day delayed, updated daily ~23:00. -Tenor set can change over time (e.g. `SW` was added 22 Dec 2025), so derive -columns from the header rather than hard-coding them. - ---- - -## 2. Index list (all categories, with ISINs) - -``` -GET https://gpwbenchmark.pl/ajaxindex.php - ?action=GPWIndexes - &start=showTable - &tab= - &lang=PL -``` - -Response is XML: `…
…
]]> -`. Pull the HTML out of the CDATA and -parse the table(s). - -`` values (match the section anchors on `/notowania`): - -| tab | meaning | -|-----|---------| -| `indexes` | Indeksy główne (main) — incl. a real-time table + 15-min delayed table | -| `macroindices` | Makroindeksy | -| `indexes_other` | Indeksy pozostałe | -| `national` | Indeksy narodowe | -| `sectorbased` | Indeksy sektorowe | -| `indexes_strategy` | Indeksy strategii | -| `benchmarks` | Benchmarki | -| `tbsp` | Indeksy obligacji (bonds) | - -Each row gives: -- ISIN — from the `href="/karta-indeksu?isin=PLxxxxxxxxxx"` link. -- Shortcode/name — the link text (e.g. `WIG20`, `TBSP.Index`). -- `cmng_id` — the 3rd arg of `getChartModal('ISIN','CURR',)` (an internal id). -- Snapshot columns — vary by table; map them from each table's own `` - labels: `Skrót, Liczba spółek/instrumentów, Czas ost. pub., TWI, Kurs otw., - Kurs min., Kurs maks., Wart. ost., Zmiana do odn. (w %), % otw. portfela, - Wartość obrotu skum. (w tys. zł)`. - -The same ISIN can appear in more than one tab — de-duplicate by ISIN. - ---- - -## 3. Per-index historical OHLC time series - -``` -GET https://gpwbenchmark.pl/chart-json.php - ?req=[{"isin":"PL9999999474","mode":"1R"}] - &t= -``` - -- `req` is a JSON **array** — you may request several `{isin, mode}` objects in - one call (the script batches this). -- `t` is a cache-buster (current time in ms). -- `mode` ∈ `14D, 1M, 3M, 6M, 1R`. **`MAX` returns no data** — on the site MAX is - just a client-side "zoom to all" over whatever was already loaded, not a - server window. `1R` (one year) is the longest server-provided window. - -Response: - -```json -[{"mode":"1R","isin":"PL9999999474","from":"2025-06-28","to":"2026-06-28", - "data":[{"t":1751234400,"o":2133.7,"c":2132.65,"h":2133.7,"l":2132.65}, …]}] -``` - -- `t` — epoch **seconds**. Convert in **Europe/Warsaw** time to get the correct - trading date (UTC conversion can land on the previous calendar day). -- `o/h/l/c` — open / high / low / close index value. -- An unknown ISIN or `MAX` yields the request echoed back with no `data` key. - -For history longer than one year, GPW Benchmark publishes downloadable files -under "Dane historyczne" (`/dane_historyczne`, `/roczne`) — out of scope here. diff --git a/claude/skills/quant/gpw-benchmark-scraper/scripts/gpw_benchmark.py b/claude/skills/quant/gpw-benchmark-scraper/scripts/gpw_benchmark.py deleted file mode 100644 index d5c1fa80..00000000 --- a/claude/skills/quant/gpw-benchmark-scraper/scripts/gpw_benchmark.py +++ /dev/null @@ -1,491 +0,0 @@ -#!/usr/bin/env python3 -""" -GPW Benchmark scraper (gpwbenchmark.pl). - -Fetches three kinds of data that the gpwbenchmark.pl front end loads from its -own backend: - - 1. rates -> WIBID & WIBOR delayed reference rates (year-to-date table from - /dane-opoznione), one business-day delayed. - 2. indices -> the full list of stock / bond / strategy indices with their - ISINs and latest snapshot (from ajaxindex.php?action=GPWIndexes). - 3. series -> per-index historical OHLC time series (from chart-json.php), - for one/many ISINs or every index. - -Output is CSV. - ------------------------------------------------------------------------------- -IMPORTANT - terms of use ------------------------------------------------------------------------------- -WIBID(R) and WIBOR(R) are regulated reference rates administered by -GPW Benchmark S.A. The delayed data is published for informational purposes; -REDISTRIBUTION or use of WIBOR/WIBID in automated trading / non-visualised -applications requires a Market Data License Agreement with GPW Benchmark. -Index data is likewise a commercial product. Scrape considerately, do not -redistribute, and check https://gpwbenchmark.pl/robots.txt and the site's -terms before any bulk or repeated pull. This script defaults to ~1 request/sec. ------------------------------------------------------------------------------- - -Requires: requests, beautifulsoup4 - pip install requests beautifulsoup4 -""" - -from __future__ import annotations - -import argparse -import csv -import json -import re -import sys -import time -from datetime import UTC, datetime - -try: - from zoneinfo import ZoneInfo - - _WARSAW = ZoneInfo("Europe/Warsaw") -except Exception: # pragma: no cover - fallback if tzdata missing - _WARSAW = None - -try: - import requests -except ImportError: - sys.exit("Missing dependency: pip install requests beautifulsoup4") - -try: - from bs4 import BeautifulSoup -except ImportError: - sys.exit("Missing dependency: pip install beautifulsoup4") - - -BASE = "https://gpwbenchmark.pl" -USER_AGENT = ( - "gpw-benchmark-scraper/1.0 (personal data collection; " - "respects robots.txt; contact: set-your-email)" -) - -# Index category tabs used by ajaxindex.php?action=GPWIndexes&tab=... -# (these match the section anchors on /notowania) -INDEX_TABS = [ - "indexes", # Indeksy glowne (main indices) - "macroindices", # Makroindeksy - "indexes_other", # Indeksy pozostale - "national", # Indeksy narodowe - "sectorbased", # Indeksy sektorowe - "indexes_strategy", # Indeksy strategii - "benchmarks", # Benchmarki - "tbsp", # Indeksy obligacji (bonds) -] - -# Chart windows accepted by chart-json.php. "MAX" is a client-side zoom only and -# returns no data from the server, so it is intentionally excluded. -SERIES_MODES = ["14D", "1M", "3M", "6M", "1R"] - - -# --------------------------------------------------------------------------- # -# HTTP # -# --------------------------------------------------------------------------- # -class Client: - def __init__(self, lang: str = "PL", delay: float = 1.0, retries: int = 4, timeout: int = 30): - self.lang = lang.upper() - self.delay = delay - self.retries = retries - self.timeout = timeout - self.s = requests.Session() - self.s.headers.update( - { - "User-Agent": USER_AGENT, - "Accept": "text/html,application/json,*/*", - "Accept-Language": "pl,en;q=0.8", - "Referer": BASE + "/notowania", - } - ) - self._last = 0.0 - - def _throttle(self): - wait = self.delay - (time.time() - self._last) - if wait > 0: - time.sleep(wait) - - def get(self, url: str, params=None) -> requests.Response: - last_err = None - for attempt in range(self.retries): - self._throttle() - try: - r = self.s.get(url, params=params, timeout=self.timeout) - self._last = time.time() - if r.status_code == 200: - return r - if r.status_code in (429, 500, 502, 503, 504): - last_err = f"HTTP {r.status_code}" - time.sleep(self.delay * (2**attempt)) - continue - r.raise_for_status() - except requests.RequestException as e: - last_err = str(e) - self._last = time.time() - time.sleep(self.delay * (2**attempt)) - raise RuntimeError(f"GET failed after {self.retries} tries ({url}): {last_err}") - - -# --------------------------------------------------------------------------- # -# Parsing helpers # -# --------------------------------------------------------------------------- # -_NUM_CLEAN = str.maketrans({" ": "", " ": ""}) - - -def _num(text: str): - """'2 265,43' / '3,53' / ' - ' -> float or None.""" - if text is None: - return None - t = text.translate(_NUM_CLEAN).strip() - if t in ("", "-", "–", "N/A"): - return None - t = t.replace(",", ".") - try: - return float(t) - except ValueError: - return None - - -def extract_cdata_html(raw: str) -> str: - """ajaxindex.php wraps the fragment in .""" - m = re.search(r"", raw, re.S) - return m.group(1) if m else raw - - -# --------------------------------------------------------------------------- # -# 1. WIBID / WIBOR rates # -# --------------------------------------------------------------------------- # -def parse_rates(html: str): - """Return (columns, rows) from the /dane-opoznione WIBID/WIBOR table. - - Header is two rows: group row (WIBID colspan=N, WIBOR colspan=M) + tenor row - (Data/Termin, ON, 1M, ...). Columns come out as ['Date','WIBID_ON',...]. - """ - soup = BeautifulSoup(html, "html.parser") - table = None - for t in soup.find_all("table"): - txt = t.get_text(" ", strip=True) - if "WIBID" in txt and "WIBOR" in txt: - table = t - break - if table is None: - raise RuntimeError("WIBID/WIBOR table not found on page") - - rows = table.find_all("tr") - # group row -> ordered (label, span) - group_cells = rows[0].find_all(["th", "td"]) - groups = [] - for c in group_cells: - label = c.get_text(strip=True).replace("®", "") # drop (R) - span = int(c.get("colspan") or 1) - groups.append((label, span)) - # expand groups to a per-column prefix, skipping the leading empty cell - prefixes = [] - for label, span in groups: - for _ in range(span): - prefixes.append(label) - # tenor row - tenor_cells = rows[1].find_all(["th", "td"]) - tenors = [c.get_text(strip=True) for c in tenor_cells] - - columns = ["Date"] - # tenors[0] is "Data/Termin"; align remaining tenors with prefixes. - # prefixes has one entry per group-column. The first group cell is empty - # (covers the date column), so prefixes[0] == "" lines up with tenors[0]. - for i in range(1, len(tenors)): - prefix = prefixes[i] if i < len(prefixes) else "" - prefix = prefix.strip() - columns.append(f"{prefix}_{tenors[i]}" if prefix else tenors[i]) - - out = [] - for r in rows[2:]: - cells = [c.get_text(strip=True) for c in r.find_all(["td", "th"])] - if not cells or not re.match(r"^\d{4}-\d{2}-\d{2}$", cells[0]): - continue - rec = {"Date": cells[0]} - for i in range(1, len(columns)): - rec[columns[i]] = _num(cells[i]) if i < len(cells) else None - out.append(rec) - return columns, out - - -def cmd_rates(client: Client, args): - path = "/en-dane-opoznione" if client.lang == "EN" else "/dane-opoznione" - r = client.get(BASE + path) - columns, rows = parse_rates(r.text) - out = args.out or "wibid_wibor.csv" - write_csv(out, columns, rows) - print(f"rates: wrote {len(rows)} days x {len(columns) - 1} tenors -> {out}") - - -# --------------------------------------------------------------------------- # -# 2. Index list # -# --------------------------------------------------------------------------- # -# Polish column header -> canonical key + whether it is numeric -_HEADER_MAP = { - "skrót": ("shortcode", False), - "liczba spółek": ("num", True), - "liczba instrumentów": ("num", True), - "czas ost. pub.": ("last_time", False), - "twi": ("twi", True), - "kurs otw.": ("open", True), - "kurs min.": ("min", True), - "kurs maks.": ("max", True), - "wart. ost.": ("last", True), - "zmiana do odn. (w %)": ("change_pct", True), - "% otw. portfela": ("portfolio_pct", True), - "wartość obrotu skum. (w tys. zł)": ("turnover_thousands_pln", True), - # English column variants - "abbrev.": ("shortcode", False), - "no. of companies": ("num", True), - "last publ. time": ("last_time", False), - "open price": ("open", True), - "min. price": ("min", True), - "max. price": ("max", True), - "last value": ("last", True), - "change to ref. (in %)": ("change_pct", True), -} - -INDEX_COLUMNS = [ - "category", - "section", - "shortcode", - "isin", - "cmng_id", - "num", - "last_time", - "twi", - "open", - "min", - "max", - "last", - "change_pct", - "portfolio_pct", - "turnover_thousands_pln", -] - - -def _norm(s: str) -> str: - return re.sub(r"\s+", " ", s.replace("\xa0", " ")).strip().lower() - - -def parse_index_table(html: str, category: str): - """Parse an ajaxindex GPWIndexes fragment (may hold several tables) into - one record per index, mapping each table's own header labels to columns.""" - soup = BeautifulSoup(extract_cdata_html(html), "html.parser") - out = [] - for table in soup.find_all("table"): - # section caption sits in the .cardBox

right before the table - section = "" - prev = table.find_previous(class_="cardBox") - if prev: - section = prev.get_text(strip=True) - # header labels (skip the leading empty chart column at index 0) - head = table.find("thead") - header_cells = head.find_all(["th", "td"]) if head else [] - labels = [_norm(c.get_text()) for c in header_cells] - for tr in table.find_all("tr"): - link = tr.find("a", href=re.compile(r"karta-indeksu\?isin=")) - if not link: - continue - m = re.search(r"isin=([A-Z0-9]+)", link.get("href", "")) - if not m: - continue - rec = {k: None for k in INDEX_COLUMNS} - rec["category"] = category - rec["section"] = section - rec["isin"] = m.group(1) - rec["shortcode"] = link.get_text(strip=True) - chart = tr.find("a", onclick=True) - if chart: - cm = re.search(r"getChartModal\('[^']*','[^']*',(\d+)\)", chart.get("onclick", "")) - if cm: - rec["cmng_id"] = cm.group(1) - cells = tr.find_all("td") - for i, td in enumerate(cells): - if i >= len(labels): - break - key_info = _HEADER_MAP.get(labels[i]) - if not key_info: - continue - key, is_num = key_info - if key == "shortcode": - continue # already captured from the link - val = td.get_text(strip=True) - rec[key] = _num(val) if is_num else (val or None) - out.append(rec) - return out - - -def cmd_indices(client: Client, args): - tabs = args.tabs or INDEX_TABS - all_rows = [] - seen = set() - for tab in tabs: - url = f"{BASE}/ajaxindex.php" - params = {"action": "GPWIndexes", "start": "showTable", "tab": tab, "lang": client.lang} - try: - r = client.get(url, params=params) - rows = parse_index_table(r.text, tab) - except Exception as e: - print(f" ! tab '{tab}' failed: {e}", file=sys.stderr) - continue - for rec in rows: - key = rec["isin"] - if key in seen: - continue - seen.add(key) - all_rows.append(rec) - print(f" tab '{tab}': {len(rows)} indices") - columns = INDEX_COLUMNS - out = args.out or "indices.csv" - write_csv(out, columns, all_rows) - print(f"indices: wrote {len(all_rows)} unique indices -> {out}") - return all_rows - - -# --------------------------------------------------------------------------- # -# 3. Historical OHLC series # -# --------------------------------------------------------------------------- # -def _epoch_to_date(t: int) -> str: - dt = datetime.fromtimestamp(int(t), tz=UTC) - if _WARSAW is not None: - dt = dt.astimezone(_WARSAW) - return dt.strftime("%Y-%m-%d") - - -def fetch_series(client: Client, isins, mode: str): - """chart-json.php accepts an array of {isin, mode}; batch several at once.""" - req = [{"isin": i, "mode": mode} for i in isins] - params = {"req": json.dumps(req, separators=(",", ":")), "t": str(int(time.time() * 1000))} - r = client.get(BASE + "/chart-json.php", params=params) - try: - payload = r.json() - except json.JSONDecodeError: - payload = json.loads(r.text) - rows = [] - for block in payload: - isin = block.get("isin") - for pt in block.get("data", []) or []: - rows.append( - { - "isin": isin, - "date": _epoch_to_date(pt["t"]), - "timestamp": pt["t"], - "open": pt.get("o"), - "high": pt.get("h"), - "low": pt.get("l"), - "close": pt.get("c"), - } - ) - return rows - - -def cmd_series(client: Client, args): - mode = args.mode - if mode not in SERIES_MODES: - sys.exit(f"--mode must be one of {SERIES_MODES} (MAX is client-side only)") - - if args.all: - idx = cmd_indices(client, argparse.Namespace(tabs=None, out="indices.csv")) - isins = [r["isin"] for r in idx] - else: - isins = args.isins - if not isins: - sys.exit("Provide ISINs or use --all") - - batch = max(1, args.batch) - all_rows = [] - for i in range(0, len(isins), batch): - chunk = isins[i : i + batch] - try: - rows = fetch_series(client, chunk, mode) - except Exception as e: - print(f" ! batch {chunk} failed: {e}", file=sys.stderr) - continue - all_rows.extend(rows) - print(f" {min(i + batch, len(isins))}/{len(isins)} indices ({len(all_rows)} rows)") - columns = ["isin", "date", "timestamp", "open", "high", "low", "close"] - out = args.out or f"series_{mode}.csv" - write_csv(out, columns, all_rows) - print(f"series[{mode}]: wrote {len(all_rows)} rows -> {out}") - - -# --------------------------------------------------------------------------- # -# all # -# --------------------------------------------------------------------------- # -def cmd_all(client: Client, args): - cmd_rates(client, argparse.Namespace(out="wibid_wibor.csv")) - idx = cmd_indices(client, argparse.Namespace(tabs=None, out="indices.csv")) - cmd_series( - client, - argparse.Namespace( - all=False, - isins=[r["isin"] for r in idx], - mode=args.mode, - batch=args.batch, - out=f"series_{args.mode}.csv", - ), - ) - - -# --------------------------------------------------------------------------- # -# CSV # -# --------------------------------------------------------------------------- # -def write_csv(path: str, columns, rows): - with open(path, "w", newline="", encoding="utf-8-sig") as f: - w = csv.DictWriter(f, fieldnames=columns, extrasaction="ignore") - w.writeheader() - for r in rows: - w.writerow(r) - - -# --------------------------------------------------------------------------- # -# CLI # -# --------------------------------------------------------------------------- # -def build_parser(): - p = argparse.ArgumentParser(description="Scrape GPW Benchmark data to CSV.") - p.add_argument("--lang", default="PL", choices=["PL", "EN"]) - p.add_argument( - "--delay", type=float, default=1.0, help="seconds between requests (default 1.0)" - ) - sub = p.add_subparsers(dest="cmd", required=True) - - pr = sub.add_parser("rates", help="WIBID/WIBOR delayed rates -> CSV") - pr.add_argument("--out") - - pi = sub.add_parser("indices", help="all indices + ISINs -> CSV") - pi.add_argument("--tabs", nargs="*", help=f"subset of {INDEX_TABS}") - pi.add_argument("--out") - - ps = sub.add_parser("series", help="historical OHLC for ISIN(s) -> CSV") - ps.add_argument("isins", nargs="*") - ps.add_argument("--all", action="store_true", help="every index") - ps.add_argument("--mode", default="1R", choices=SERIES_MODES) - ps.add_argument("--batch", type=int, default=5, help="ISINs per chart-json request (default 5)") - ps.add_argument("--out") - - pa = sub.add_parser("all", help="rates + indices + series for everything") - pa.add_argument("--mode", default="1R", choices=SERIES_MODES) - pa.add_argument("--batch", type=int, default=5) - - return p - - -def main(argv=None): - args = build_parser().parse_args(argv) - client = Client(lang=args.lang, delay=args.delay) - if args.cmd == "rates": - cmd_rates(client, args) - elif args.cmd == "indices": - cmd_indices(client, args) - elif args.cmd == "series": - cmd_series(client, args) - elif args.cmd == "all": - cmd_all(client, args) - - -if __name__ == "__main__": - main() diff --git a/claude/skills/quant/gpw-benchmark-scraper/scripts/test_parsers.py b/claude/skills/quant/gpw-benchmark-scraper/scripts/test_parsers.py deleted file mode 100644 index 2a35493c..00000000 --- a/claude/skills/quant/gpw-benchmark-scraper/scripts/test_parsers.py +++ /dev/null @@ -1,129 +0,0 @@ -"""Offline tests for the parsing logic, using fixtures captured from the live -site (no network needed). Run: python test_parsers.py""" - -import json - -import gpw_benchmark as g - -# --- Fixture 1: WIBID/WIBOR table (exact structure from /dane-opoznione) --- -RATES_HTML = """ - - - - - - - - - - -
WIBID®WIBOR®
Data/TerminON1M3M6MSWON1M3M6M1YSW
2026-06-253,533,583,653,713,613,813,783,853,913,953,81
2026-06-243,493,583,643,713,613,773,783,843,913,963,81
-""" - -# --- Fixture 2: index list fragment (real CDATA from tab=tbsp) --- -INDEX_HTML = """

Dane opóźnione o 15 minut

-
- - - - - - - - - - - - -
SkrótLiczba instrumentówCzas ost. pub.Kurs otw.Kurs min.Kurs maks.Wart. ost.Zmiana do odn. (w %)% otw. portfela
TBSP.Index1917:20:002 265,432 265,432 267,422 267,420,200
GPWB-B1Y3Y517:20:001 329,121 329,121 329,341 329,340,090
-]]>
""" - -# --- Fixture 3: chart-json payload (real 14D response) --- -CHART_JSON = json.loads( - '[{"mode":"14D","isin":"PL9999999474","from":"2026-06-14","to":"2026-06-28",' - '"data":[{"t":1781474400,"o":2247.65,"c":2249.62,"h":2249.62,"l":2247.65},' - '{"t":1782424800,"o":2265.43,"c":2267.42,"h":2267.42,"l":2265.43}]}]' -) - - -def test_rates(): - cols, rows = g.parse_rates(RATES_HTML) - assert cols == [ - "Date", - "WIBID_ON", - "WIBID_1M", - "WIBID_3M", - "WIBID_6M", - "WIBID_SW", - "WIBOR_ON", - "WIBOR_1M", - "WIBOR_3M", - "WIBOR_6M", - "WIBOR_1Y", - "WIBOR_SW", - ], cols - assert len(rows) == 2 - assert rows[0]["Date"] == "2026-06-25" - assert rows[0]["WIBID_ON"] == 3.53 - assert rows[0]["WIBOR_SW"] == 3.81 - assert rows[1]["WIBID_ON"] == 3.49 - print("test_rates OK:", cols) - - -def test_indices(): - rows = g.parse_index_table(INDEX_HTML, "tbsp") - assert len(rows) == 2, len(rows) - r = rows[0] - assert r["isin"] == "PL9999999474" - assert r["shortcode"] == "TBSP.Index" - assert r["cmng_id"] == "495175" - assert r["num"] == 19 - assert r["last_time"] == "17:20:00" - assert r["open"] == 2265.43 - assert r["max"] == 2267.42 - assert r["change_pct"] == 0.20 - assert rows[1]["isin"] == "PL9999996652" - print("test_indices OK:", {k: r[k] for k in ("isin", "shortcode", "open", "change_pct")}) - - -def test_series(): - import types - - class FakeResp: - def __init__(self, payload): - self._p = payload - - def json(self): - return self._p - - @property - def text(self): - return json.dumps(self._p) - - client = types.SimpleNamespace(get=lambda url, params=None: FakeResp(CHART_JSON)) - rows = g.fetch_series(client, ["PL9999999474"], "14D") - assert len(rows) == 2 - assert rows[0]["isin"] == "PL9999999474" - assert rows[0]["open"] == 2247.65 and rows[0]["close"] == 2249.62 - assert rows[0]["high"] == 2249.62 and rows[0]["low"] == 2247.65 - # epoch -> Warsaw date - assert rows[0]["date"] == "2026-06-15", rows[0]["date"] - assert rows[1]["date"] == "2026-06-26", rows[1]["date"] - print("test_series OK:", [r["date"] for r in rows]) - - -def test_num(): - assert g._num("2 265,43") == 2265.43 - assert g._num("3,81") == 3.81 - assert g._num(" - ") is None - assert g._num("") is None - print("test_num OK") - - -if __name__ == "__main__": - test_num() - test_rates() - test_indices() - test_series() - print("\nALL TESTS PASSED") diff --git a/claude/skills/quant/market-datasets/.env.example b/claude/skills/quant/market-datasets/.env.example deleted file mode 100644 index 077df237..00000000 --- a/claude/skills/quant/market-datasets/.env.example +++ /dev/null @@ -1,44 +0,0 @@ -# Market Data Fetcher - API Keys Configuration -# Copy this file to .env and fill in your API keys -# -# The .env file will be automatically loaded by all fetcher scripts. -# Keys can also be set as environment variables. - -# ============================================================================= -# TIINGO (US stocks, ETFs, mutual funds) -# ============================================================================= -# Free tier: 50 req/hour, 1000 req/day, 500 symbols/month -# Get your free API key at: https://api.tiingo.com/ -TIINGO_API_KEY= - -# ============================================================================= -# FRED (Federal Reserve Economic Data) -# ============================================================================= -# Free tier: Unlimited requests -# Get your free API key at: https://fred.stlouisfed.org/docs/api/api_key.html -FRED_API_KEY= - -# ============================================================================= -# FINANCIALDATA.NET (Stocks, fundamentals, options, insider trading) -# ============================================================================= -# Free tier: Basic stock prices, symbol lists -# Standard: Company info, financial statements, ratios, derivatives -# Premium: Real-time quotes, international data, forex, press releases -# Get your API key at: https://financialdata.net -FINANCIAL_DATA_API_KEY= - -# ============================================================================= -# OPTIONAL: Future sources (not currently used) -# ============================================================================= -# Alpha Vantage (alternative US data) -# ALPHA_VANTAGE_API_KEY= - -# Polygon.io (real-time data) -# POLYGON_API_KEY= - -# IEX Cloud (US equities) -# IEX_API_KEY= - -# 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/.gitignore b/claude/skills/quant/market-datasets/.gitignore deleted file mode 100644 index 847b8ddd..00000000 --- a/claude/skills/quant/market-datasets/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -scripts/data/cache/ -.env diff --git a/claude/skills/quant/market-datasets/SKILL.md b/claude/skills/quant/market-datasets/SKILL.md deleted file mode 100644 index 1fd96e47..00000000 --- a/claude/skills/quant/market-datasets/SKILL.md +++ /dev/null @@ -1,241 +0,0 @@ ---- -name: market-datasets -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 ---- - -# Market Datasets - -Unified market data fetching with intelligent source selection, plus long-history asset construction for investment research. - -## When to Use - -- **Fetching**: Historical stock prices, indices, FX rates, economic indicators, crypto -- **Construction**: Building multi-decade return series for backtesting (ETF + academic backfill) -- **Comparison**: Cross-source data validation -- **Conversion**: ISIN/ticker lookups across sources - -## Supported Sources - -| Source | Best For | Auth | Coverage | -|--------|----------|------|----------| -| **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**); 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 | -| **FRED** | Macro indicators | API key | US economic data | -| **FinancialData.Net** | Fundamentals, options, insider | API key | US/intl stocks, options, statements, ratios | -| **Shiller** | Long-history equity/bonds | Free | Monthly S&P 500 + 10Y yield (1871+) | -| **Damodaran** | Long-history annual | Free | Annual S&P, T-Bond, T-Bill, Gold (1928+) | - -### Dividend Treatment - -| Source | Price Type | Use For | -|--------|------------|---------| -| 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 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 - -### Step 1: Determine Approach - -| Need | Approach | -|------|----------| -| Current/recent prices (ad-hoc) | Auto-routing via unified fetcher — **Yahoo primary** | -| 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 | - -### Step 2: Fetch Data - -**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_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 (EODHD) -uv run scripts/fetch_financialdata.py AAPL 2024-01-01 2024-12-31 -``` - -**Python**: -```python -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 → 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 -df = fetch_market_data('PLXTRDM00011', start_date='2024-01-01') # ISIN → auto-resolve -``` - -### Step 3: Handle Results - -All fetchers return pandas DataFrames with standardized columns: - -| Column | Description | -|--------|-------------| -| `Date` | datetime | -| `Open`, `High`, `Low`, `Close` | OHLC prices | -| `Volume` | Trading volume (if available) | -| `Adj_Close` | Adjusted close (Yahoo, EODHD) | - -Economic data (FRED, NBP): `Date`, `Value`, `Currency`/`Series_ID`. - -## Quick Examples - -```python -# 1. Simple fetch with auto-routing -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.WA', ['eodhd', 'yahoo'], start_date='2024-01-01') - -# 3. ISIN batch fetch -from fetch_yahoo_direct import fetch_by_isin -prices, dividends, splits, mapping = fetch_by_isin( - ['PLXTRDM00011', 'US0378331005'], start_date='2024-01-01' -) -``` - -For all usage patterns, see [references/usage_patterns.md](references/usage_patterns.md). - -## Long-History Asset Construction - -For investment research requiring multi-decade return series (backtesting, risk calibration), use the **ETF-primary, academic-backfill** pattern. - -### Strategy - -``` -ETF/fund data (real, 1976-2025) ← PRIMARY: highest quality - ↕ splice point -Academic data (synthetic, 1928+) ← BACKFILL: extends history -``` - -### Standard Asset Class Proxies - -| Asset Class | Primary Source | Backfill Source | Splice Point | -|-------------|---------------|-----------------|--------------| -| **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) | EODHD `XAUUSD.FOREX` | From 1990-01-02 (probed 2026-09-30); `GC=F` is not on EODHD | N/A | - -### Key Construction Patterns - -**Splice**: Use primary where available, backfill for earlier dates. No blending. -```python -splice_date = primary.index.min() -backfill_part = backfill[backfill.index < splice_date] -result = pd.concat([backfill_part, primary]).sort_index() -``` - -**Synthetic bond return** from yield: -```python -coupon = yield_series.shift(1) / 12 -price_change = -duration * (yield_series - yield_series.shift(1)) -monthly_return = coupon + price_change -``` - -**Total return from price + dividends**: -```python -total_return = (price + dividend / 12) / price.shift(1) - 1 -``` - -For complete source details, download patterns, and validation methodology, see [references/long_history_construction.md](references/long_history_construction.md). - -Reference implementation: `research/strategic-asset-allocation/build_asset_data_v2.py`. - -## Ticker Formats - -| Source | Example | Format | -|--------|---------|--------| -| 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 | - -Full reference: [references/ticker_formats.md](references/ticker_formats.md). - -## Caching - -File-based caching enabled by default: -- **Location**: `data/cache/market_data/{source}/` -- **Default TTL**: 24 hours - -```python -df = fetch_market_data('pko', use_cache=False) # Disable cache -fetcher = UnifiedMarketDataFetcher(cache_hours=48) # Custom TTL -``` - -## Configuration - -### API Keys - -| Source | Setup | Required? | -|--------|-------|-----------| -| 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). - -## Error Handling - -```python -try: - df = fetch_market_data(ticker) -except ValueError as e: - print(f"Invalid ticker or no data: {e}") # Bad ticker, empty result, date issues -except Exception as e: - print(f"Network or other error: {e}") -``` - -## Best Practices - -1. **Use auto-routing by default** — let the fetcher choose the best source -2. **Enable caching** — reduces API load, enables offline work -3. **Validate results** — check `not df.empty`, expected columns, no NaN gaps -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: - -| Reference | When to Load | -|-----------|-------------| -| [usage_patterns.md](references/usage_patterns.md) | All usage patterns with full code | -| [long_history_construction.md](references/long_history_construction.md) | Academic sources, splice methodology, validation | -| [sources_overview.md](references/sources_overview.md) | Detailed source comparison, coverage | -| [ticker_formats.md](references/ticker_formats.md) | Complete ticker format mappings | -| [eodhd.md](references/eodhd.md) | EODHD coverage, plan limits, ISIN→listing pinning, holdings/index gaps | -| [api_setup.md](references/api_setup.md) | API key setup, troubleshooting | -| [dividend_treatment.md](references/dividend_treatment.md) | Raw vs adjusted prices, validation | -| [security_master.md](references/security_master.md) | TickerRegistry API, UID conventions | -| [instrument_registry_schema.yaml](references/instrument_registry_schema.yaml) | Shared registry schema for dataset repos | -| [migration.md](references/migration.md) | Migrating fetchers to production projects | diff --git a/claude/skills/quant/market-datasets/data/security_master.csv b/claude/skills/quant/market-datasets/data/security_master.csv deleted file mode 100644 index b99895d0..00000000 --- a/claude/skills/quant/market-datasets/data/security_master.csv +++ /dev/null @@ -1,55 +0,0 @@ -uid,isin,name,instrument_type,country,exchange,ticker_bloomberg,ticker_yahoo,ticker_stooq,ticker_fred,sector,currency,mapping_source,last_updated -isin_PLCCC0000016,PLCCC0000016,CCC,equity,PL,WSE,,CCC.WA,ccc,,,PLN,yahoo_api,2026-01-09 -isin_PLBSK0000017,PLBSK0000017,ING Bank Slaski,equity,PL,WSE,,ING.WA,ing,,,PLN,yahoo_api,2026-01-09 -isin_LU2910446546,LU2910446546,Zabka,equity,LU,WSE,,ZAB.WA,,,,,yahoo_api,2026-01-09 -isin_PLBNFTS00018,PLBNFTS00018,Benefit Systems,equity,PL,WSE,,BFT.WA,bft,,,PLN,yahoo_api,2026-01-09 -isin_PLBIG0000016,PLBIG0000016,Bank Millennium,equity,PL,WSE,,MIL.WA,mil,,,PLN,yahoo_api,2026-01-09 -isin_PLXTRDM00011,PLXTRDM00011,XTB,equity,PL,WSE,,XTB.WA,xtb,,,PLN,yahoo_api,2026-01-09 -isin_PLSOFTB00016,PLSOFTB00016,Asseco Poland,equity,PL,WSE,,ACP.WA,acp,,,PLN,yahoo_api,2026-01-09 -isin_PLINTCS00010,PLINTCS00010,Inter Cars,equity,PL,WSE,,CAR.WA,car,,,PLN,yahoo_api,2026-01-09 -isin_PLTAURN00011,PLTAURN00011,Tauron,equity,PL,WSE,,TPE.WA,tpe,,,PLN,yahoo_api,2026-01-09 -isin_PLENEA000013,PLENEA000013,Enea,equity,PL,WSE,,ENA.WA,ena,,,PLN,yahoo_api,2026-01-09 -isin_PLBH00000012,PLBH00000012,Budimex,equity,PL,WSE,,BHW.WA,bhw,,,PLN,yahoo_api,2026-01-09 -isin_PLLCCRP00017,PLLCCRP00017,Develia,equity,PL,WSE,,DVL.WA,dvl,,,PLN,yahoo_api,2026-01-09 -isin_PLBGZ0000010,PLBGZ0000010,BNP Paribas Bank Polska,equity,PL,WSE,,BNP.WA,bnp,,,PLN,yahoo_api,2026-01-09 -isin_PLDMDVL00012,PLDMDVL00012,Dom Development,equity,PL,WSE,,DOM.WA,dom,,,PLN,yahoo_api,2026-01-09 -isin_PLATPRT00018,PLATPRT00018,Autopartner,equity,PL,WSE,,APR.WA,apr,,,PLN,yahoo_api,2026-01-09 -isin_PLWRTPL00027,PLWRTPL00027,Wirtualna Polska,equity,PL,WSE,,WPL.WA,wpl,,,PLN,yahoo_api,2026-01-09 -isin_PLTRFRM00018,PLTRFRM00018,Neuca,equity,PL,WSE,,NEU.WA,neu,,,PLN,yahoo_api,2026-01-09 -isin_ES0105375002,ES0105375002,AmRest,equity,ES,WSE,,EAT.WA,eat,,,PLN,yahoo_api,2026-01-09 -isin_PLGRPRC00015,PLGRPRC00015,Grupa Pracuj,equity,PL,WSE,,GPP.WA,gpp,,,PLN,yahoo_api,2026-01-09 -isin_PLRNBWT00031,PLRNBWT00031,Rainbow Tours,equity,PL,WSE,,RBW.WA,rbw,,,PLN,yahoo_api,2026-01-09 -isin_PLAB00000019,PLAB00000019,AB,equity,PL,WSE,,ABE.WA,abe,,,PLN,yahoo_api,2026-01-09 -isin_PLGPW0000017,PLGPW0000017,GPW,equity,PL,WSE,,GPW.WA,gpw,,,PLN,yahoo_api,2026-01-09 -isin_PLMOBRK00013,PLMOBRK00013,Mo-Bruk,equity,PL,WSE,,MBR.WA,mbr,,,PLN,yahoo_api,2026-01-09 -isin_PLZATRM00012,PLZATRM00012,Grupa Azoty,equity,PL,WSE,,ATT.WA,att,,,PLN,yahoo_api,2026-01-09 -isin_PLR220000018,PLR220000018,Cyfrowy Polsat,equity,PL,WSE,,CBF.WA,cbf,,,PLN,yahoo_api,2026-01-09 -isin_PLLVTSF00010,PLLVTSF00010,Text (LiveChat),equity,PL,WSE,,TXT.WA,txt,,,PLN,yahoo_api,2026-01-09 -isin_PLVOXEL00014,PLVOXEL00014,Voxel,equity,PL,WSE,,VOX.WA,vox,,,PLN,yahoo_api,2026-01-09 -isin_PLMRBUD00015,PLMRBUD00015,Mirbud,equity,PL,WSE,,MRB.WA,mrb,,,PLN,yahoo_api,2026-01-09 -isin_PLSLVCR00029,PLSLVCR00029,Silvair,equity,PL,WSE,,SLV.WA,slv,,,PLN,yahoo_api,2026-01-09 -isin_PLSNKTK00019,PLSNKTK00019,Synektik,equity,PL,WSE,,SNT.WA,snt,,,PLN,yahoo_api,2026-01-09 -isin_PLSELVT00013,PLSELVT00013,Selvita,equity,PL,WSE,,RVU.WA,rvu,,,PLN,yahoo_api,2026-01-09 -isin_PLCLNPH00015,PLCLNPH00015,Celon Pharma,equity,PL,WSE,,CLN.WA,cln,,,PLN,yahoo_api,2026-01-09 -isin_CY1000031710,CY1000031710,Assy,equity,CY,WSE,,ASB.WA,asb,,,PLN,yahoo_api,2026-01-09 -isin_PL11BTS00015,PL11BTS00015,11 bit studios,equity,PL,WSE,,11B.WA,11b,,,PLN,yahoo_api,2026-01-09 -isin_PLFAMUR00012,PLFAMUR00012,Famur,equity,PL,WSE,,GEA.WA,gea,,,PLN,yahoo_api,2026-01-09 -isin_PLEURCH00011,PLEURCH00011,Eurocash,equity,PL,WSE,,EUR.WA,eur,,,PLN,yahoo_api,2026-01-09 -isin_US44853H1086,US44853H1086,Huuuge,equity,US,WSE,,HUG.WA,hug,,,PLN,yahoo_api,2026-01-09 -isin_PLARTPR00012,PLARTPR00012,Arctic Paper,equity,PL,WSE,,ATC.WA,atc,,,PLN,yahoo_api,2026-01-09 -isin_PLTSQGM00016,PLTSQGM00016,Ten Square Games,equity,PL,WSE,,TEN.WA,ten,,,PLN,yahoo_api,2026-01-09 -isin_PLLWBGD00016,PLLWBGD00016,LW Bogdanka,equity,PL,WSE,,LWB.WA,lwb,,,PLN,yahoo_api,2026-01-09 -isin_PLCFRPT00013,PLCFRPT00013,Comp,equity,PL,WSE,,CPS.WA,cps,,,PLN,yahoo_api,2026-01-09 -isin_PLJSW0000015,PLJSW0000015,JSW,equity,PL,WSE,,JSW.WA,jsw,,,PLN,yahoo_api,2026-01-09 -isin_PLPLSEP00013,PLPLSEP00013,Polenergia,equity,PL,WSE,,PEP.WA,pep,,,PLN,yahoo_api,2026-01-09 -isin_PLNEWAG00012,PLNEWAG00012,Newag,equity,PL,WSE,,NWG.WA,nwg,,,PLN,yahoo_api,2026-01-09 -isin_PLVRCM000016,PLVRCM000016,Vercom,equity,PL,WSE,,VRC.WA,vrc,,,PLN,yahoo_api,2026-01-09 -isin_PLLUBAW00013,PLLUBAW00013,Lubawa,equity,PL,WSE,,LBW.WA,lbw,,,PLN,yahoo_api,2026-01-09 -isin_PLASSEE00014,PLASSEE00014,Asseco SEE,equity,PL,WSE,,ASE.WA,ase,,,PLN,yahoo_api,2026-01-09 -isin_PLDGNST00012,PLDGNST00012,Diagnostyka,equity,PL,WSE,,DIA.WA,dia,,,PLN,yahoo_api,2026-01-09 -idx_WIG20,,WIG20 Index,index,PL,WSE,,^WIG20,wig20,,,,manual,2026-01-09 -idx_MWIG40,,mWIG40 Index,index,PL,WSE,MWIG40 Index,^MWIG40,mwig40,,,,manual,2026-01-09 -idx_SWIG80,,sWIG80 Index,index,PL,WSE,,^SWIG80,swig80,,,,manual,2026-01-09 -fx_USDPLN,,USD/PLN,currency,,,,,usdpln,,,,manual,2026-01-09 -fx_EURPLN,,EUR/PLN,currency,,,,,eurpln,,,,manual,2026-01-09 -isin_US0378331005,US0378331005,Apple Inc,equity,US,NASDAQ,,AAPL,,,Technology,USD,manual,2026-01-09 diff --git a/claude/skills/quant/market-datasets/references/api_setup.md b/claude/skills/quant/market-datasets/references/api_setup.md deleted file mode 100644 index aca70e6a..00000000 --- a/claude/skills/quant/market-datasets/references/api_setup.md +++ /dev/null @@ -1,775 +0,0 @@ -# API Setup & Configuration Guide - -Configuration instructions for data sources requiring authentication or setup. - -## Overview - -Most data sources work out-of-the-box without configuration: -- **NBP API**: No setup required -- **Yahoo Finance**: No setup required (via yfinance) -- **CCXT/Crypto**: No setup required (via ccxt package) -- **Tiingo**: **API key required** (free) -- **FRED**: **API key required** (free) -- **FinancialData.Net**: **API key required** (free tier available) -- **pandas-datareader**: No setup (but some sub-sources may need keys) - ---- - -## FRED API Setup - -### Why FRED Requires API Key - -FRED (Federal Reserve Economic Data) requires a free API key to access their economic data. This helps them manage usage and provide better service. - -### Step 1: Register for API Key - -1. Visit: https://fred.stlouisfed.org/ -2. Click "My Account" (top right) → "API Keys" -3. Or go directly to: https://fredaccount.stlouisfed.org/apikeys -4. Click "Request API Key" -5. Fill out the form: - - Name your application (e.g., "Market Data Fetcher") - - Agree to terms - - Submit -6. You'll receive an API key immediately (32-character string) - -**Example API key format**: `a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6` - -### Step 2: Configure API Key - -You have three options for providing the API key: - -#### Option 1: Environment Variable (Recommended) - -Set the `FRED_API_KEY` environment variable: - -**Windows (PowerShell)**: -```powershell -$env:FRED_API_KEY = "your_api_key_here" - -# Make permanent (System Properties → Environment Variables) -[System.Environment]::SetEnvironmentVariable('FRED_API_KEY', 'your_api_key_here', 'User') -``` - -**Windows (Command Prompt)**: -```cmd -set FRED_API_KEY=your_api_key_here - -# Make permanent -setx FRED_API_KEY "your_api_key_here" -``` - -**Linux/Mac**: -```bash -export FRED_API_KEY="your_api_key_here" - -# Add to ~/.bashrc or ~/.zshrc for persistence -echo 'export FRED_API_KEY="your_api_key_here"' >> ~/.bashrc -source ~/.bashrc -``` - -#### Option 2: Config File - -Create a text file with your API key: - -1. Create directory (if doesn't exist): - ```bash - mkdir -p config - ``` - -2. Create file `config/fred_api_key.txt` with your key: - ``` - your_api_key_here - ``` - -3. The fetcher will automatically look for: - - `config/fred_api_key.txt` - - `U:/config_files/fred_api_key.txt` - - `~/.fred_api_key` - -#### Option 3: Direct Parameter - -Pass the API key directly in code: - -```python -from scripts.fetch_fred import fetch_fred - -df = fetch_fred('GDP', api_key='your_api_key_here') -``` - -Or with unified fetcher: - -```python -from scripts.fetch_unified import UnifiedMarketDataFetcher - -fetcher = UnifiedMarketDataFetcher(fred_api_key='your_api_key_here') -df = fetcher.fetch('GDP') -``` - -### Step 3: Verify Setup - -Test that FRED API key is working: - -```python -from scripts.fetch_fred import FREDFetcher - -try: - fetcher = FREDFetcher() # Will auto-detect key - df = fetcher.fetch('GDP', start_date='20200101') - print(f"Success! Retrieved {len(df)} data points") - print(df.head()) -except ValueError as e: - print(f"API key not configured: {e}") -``` - -### FRED Rate Limits - -- **No documented rate limits** for basic usage -- Be respectful: Don't hammer the API -- Caching is enabled by default (24 hours) -- For heavy usage, contact FRED about higher limits - ---- - -## Tiingo API Setup - -### Why Tiingo Requires API Key - -Tiingo provides high-quality US stock data with a generous free tier (1,000 requests/day). The API key helps them manage usage and provide better service. - -### Step 1: Register for API Key - -1. Visit: https://api.tiingo.com/ -2. Click "Sign Up" (top right) -3. Create account with email -4. Verify email -5. Go to "API" section in your account -6. Copy your API token (40-character string) - -**Example API key format**: `a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0` - -### Step 2: Configure API Key - -#### Option 1: Environment Variable (Recommended) - -**Windows (PowerShell)**: -```powershell -$env:TIINGO_API_KEY = "your_api_key_here" - -# Make permanent -[System.Environment]::SetEnvironmentVariable('TIINGO_API_KEY', 'your_api_key_here', 'User') -``` - -**Windows (Command Prompt)**: -```cmd -set TIINGO_API_KEY=your_api_key_here - -# Make permanent -setx TIINGO_API_KEY "your_api_key_here" -``` - -**Linux/Mac**: -```bash -export TIINGO_API_KEY="your_api_key_here" - -# Add to ~/.bashrc or ~/.zshrc for persistence -echo 'export TIINGO_API_KEY="your_api_key_here"' >> ~/.bashrc -source ~/.bashrc -``` - -#### Option 2: Direct Parameter - -Pass the API key directly in code: - -```python -from scripts.fetch_tiingo import fetch_tiingo - -df = fetch_tiingo('AAPL', api_key='your_api_key_here') -``` - -Or with unified fetcher: - -```python -from scripts.fetch_unified import UnifiedMarketDataFetcher - -fetcher = UnifiedMarketDataFetcher(tiingo_api_key='your_api_key_here') -df = fetcher.fetch('AAPL') -``` - -### Step 3: Verify Setup - -Test that Tiingo API key is working: - -```python -from scripts.fetch_tiingo import TiingoFetcher - -try: - fetcher = TiingoFetcher() # Will auto-detect key from env - df = fetcher.fetch('AAPL', start_date='20240101') - print(f"Success! Retrieved {len(df)} data points") - print(df.head()) -except ValueError as e: - print(f"API key not configured: {e}") -``` - -### Tiingo Rate Limits - -**Free tier limits**: -- 50 requests per hour -- 1,000 requests per day -- 500 unique symbols per month - -Caching is enabled by default (24 hours) to minimize requests. - ---- - -## CCXT (Cryptocurrency) Setup - -### No API Key Required - -CCXT provides free access to public historical data from 100+ cryptocurrency exchanges. No registration or API key needed for: -- Historical OHLCV data -- Market prices -- Trading pair information - -### Step 1: Install CCXT Package - -```bash -pip install ccxt -``` - -### Step 2: Verify Setup - -Test that CCXT is working: - -```python -from scripts.fetch_ccxt import fetch_crypto - -try: - df = fetch_crypto('BTC/USDT', start_date='20240101') - print(f"Success! Retrieved {len(df)} candles") - print(df.head()) -except ImportError: - print("CCXT not installed. Run: pip install ccxt") -``` - -### Supported Exchanges - -By default, the skill uses Binance. You can switch exchanges: - -```python -from scripts.fetch_unified import UnifiedMarketDataFetcher - -# Use Kraken instead of Binance -fetcher = UnifiedMarketDataFetcher(crypto_exchange='kraken') -df = fetcher.fetch('BTC/USD') -``` - -Supported exchanges include: -- `binance` (default) -- `kraken` -- `coinbasepro` -- `kucoin` -- `bybit` -- `okx` -- `bitfinex` -- And 100+ more - -### Rate Limits - -CCXT has built-in rate limiting that respects exchange-specific limits. Additional caching (24 hours default) reduces requests further. - ---- - -## FinancialData.Net API Setup - -### Why FinancialData.Net Requires API Key - -FinancialData.Net provides comprehensive financial data covering stocks, fundamentals, options, forex, crypto, financial statements, ratios, and insider/institutional trading. A free tier provides basic stock prices and symbol lists. - -### Step 1: Register for API Key - -1. Visit: https://financialdata.net -2. Click "Sign Up" or "Get API Key" -3. Create an account -4. Navigate to your API settings -5. Copy your API key - -### Step 2: Configure API Key - -#### Option 1: Environment Variable (Recommended) - -**Windows (PowerShell)**: -```powershell -$env:FINANCIAL_DATA_API_KEY = "your_api_key_here" - -# Make permanent -[System.Environment]::SetEnvironmentVariable('FINANCIAL_DATA_API_KEY', 'your_api_key_here', 'User') -``` - -**Windows (Command Prompt)**: -```cmd -set FINANCIAL_DATA_API_KEY=your_api_key_here - -# Make permanent -setx FINANCIAL_DATA_API_KEY "your_api_key_here" -``` - -**Linux/Mac**: -```bash -export FINANCIAL_DATA_API_KEY="your_api_key_here" - -# Add to ~/.bashrc or ~/.zshrc for persistence -echo 'export FINANCIAL_DATA_API_KEY="your_api_key_here"' >> ~/.bashrc -source ~/.bashrc -``` - -#### Option 2: Direct Parameter - -Pass the API key directly in code: - -```python -from scripts.fetch_financialdata import fetch_financialdata - -df = fetch_financialdata('AAPL', api_key='your_api_key_here') -``` - -Or with unified fetcher: - -```python -from scripts.fetch_unified import UnifiedMarketDataFetcher - -fetcher = UnifiedMarketDataFetcher(financialdata_api_key='your_api_key_here') -df = fetcher.fetch('AAPL', source='financialdata') -``` - -### Step 3: Verify Setup - -Test that FinancialData.Net API key is working: - -```python -from scripts.fetch_financialdata import FinancialDataFetcher - -try: - fetcher = FinancialDataFetcher() # Will auto-detect key from env - df = fetcher.get_stock_prices('AAPL', start_date='20240101', end_date='20240131') - print(f"Success! Retrieved {len(df)} data points") - print(df.head()) -except ValueError as e: - print(f"API key not configured: {e}") -``` - -### FinancialData.Net Subscription Tiers - -| Tier | Endpoints | Examples | -|------|-----------|---------| -| **Free** | Symbol lists, stock prices, commodity prices, OTC data | stock-symbols, stock-prices, commodity-prices | -| **Standard** | Company info, financials, ratios, derivatives, crypto | income-statements, option-chain, key-metrics | -| **Premium** | Real-time quotes, international data, forex, press releases | stock-quotes, forex-prices, press-releases | - ---- - -## Package Installation - -### Required Packages - -These are required for basic functionality: - -```bash -pip install pandas requests -``` - -### Optional Packages - -Install as needed for specific sources: - -#### Yahoo Finance Support - -```bash -pip install yfinance -``` - -Without yfinance: -- Yahoo Finance fetcher will not be available -- Can still use via pandas-datareader fallback - -#### pandas-datareader Support - -```bash -pip install pandas-datareader -``` - -Without pandas-datareader: -- pandas-datareader fetcher will not be available -- Individual source fetchers still work - -#### CCXT (Cryptocurrency) Support - -```bash -pip install ccxt -``` - -Without ccxt: -- Cryptocurrency fetcher will not be available -- Cannot fetch data from Binance/other exchanges - -#### Full Installation - -Install everything: - -```bash -pip install pandas requests yfinance pandas-datareader ccxt -``` - -Or using requirements file: - -```bash -# Create requirements.txt -echo "pandas>=1.5.0" > requirements.txt -echo "requests>=2.28.0" >> requirements.txt -echo "yfinance>=0.2.0" >> requirements.txt -echo "pandas-datareader>=0.10.0" >> requirements.txt -echo "ccxt>=4.0.0" >> requirements.txt - -# Install -pip install -r requirements.txt -``` - ---- - -## Project Integration - -### Adding to Existing Project - -If integrating into an existing project (like the performance attribution system): - -1. **Copy skill to project**: - ```bash - cp -r market-datasets /path/to/project/ - ``` - -2. **Install dependencies**: - ```bash - cd /path/to/project - pip install pandas requests yfinance pandas-datareader - ``` - -3. **Configure FRED** (if needed): - ```bash - # Option 1: Environment variable - export FRED_API_KEY="your_key" - - # Option 2: Config file - echo "your_key" > U:/config_files/fred_api_key.txt - ``` - -4. **Import in your code**: - ```python - import sys - sys.path.append('market-datasets/scripts') - - from fetch_unified import fetch_market_data - - # Use it - df = fetch_market_data('pko', start_date='20240101') - ``` - ---- - -## Cache Configuration - -### Cache Location - -By default, data is cached in: -``` -data/cache/market_data/ -├── eodhd/ -├── nbp/ -├── yahoo/ -├── fred/ -└── pandas_datareader/ -``` - -### Custom Cache Directory - -Change cache location: - -```python -from scripts.utils import CacheManager - -# Custom cache location -cache = CacheManager(cache_dir='custom/cache/path') -``` - -Or when creating fetchers: - -```python -from scripts.fetch_unified import UnifiedMarketDataFetcher - -# This will use custom cache for all sources -import os -os.environ['CACHE_DIR'] = 'custom/cache/path' - -fetcher = UnifiedMarketDataFetcher() -``` - -### Cache Validity - -Control how long cache is valid: - -```python -# Cache for 48 hours instead of default 24 -fetcher = UnifiedMarketDataFetcher(cache_hours=48) - -# Disable caching -fetcher = UnifiedMarketDataFetcher(use_cache=False) -``` - -### Clear Cache - -Manually clear cache: - -```bash -# Clear all cache -rm -rf data/cache/market_data/* - -# Clear specific source -rm -rf data/cache/market_data/yahoo/* -``` - ---- - -## Troubleshooting - -### FRED API Key Not Found - -**Error**: -``` -ValueError: FRED API key required. Set FRED_API_KEY environment variable... -``` - -**Solutions**: -1. Verify environment variable is set: - ```bash - echo $FRED_API_KEY # Linux/Mac - echo %FRED_API_KEY% # Windows CMD - $env:FRED_API_KEY # Windows PowerShell - ``` - -2. Check config file exists and has correct permissions: - ```bash - cat config/fred_api_key.txt - ``` - -3. Verify no extra spaces in API key - -4. Try passing key directly as parameter - -### Package Import Errors - -**Error**: -``` -ModuleNotFoundError: No module named 'yfinance' -``` - -**Solution**: -```bash -pip install yfinance -``` - -### Permission Denied (Config File) - -**Error**: -``` -PermissionError: [Errno 13] Permission denied: 'config/fred_api_key.txt' -``` - -**Solutions**: -1. Check file permissions: - ```bash - chmod 644 config/fred_api_key.txt - ``` - -2. Use environment variable instead - -3. Check directory permissions - -### Cache Write Errors - -**Error**: -``` -PermissionError: [Errno 13] Permission denied: 'data/cache/market_data/...' -``` - -**Solutions**: -1. Create cache directory: - ```bash - mkdir -p data/cache/market_data - ``` - -2. Check directory permissions: - ```bash - chmod 755 data/cache/market_data - ``` - -3. Use custom cache directory with proper permissions - -### Rate Limiting (429 Errors) - -**Error**: -``` -requests.exceptions.HTTPError: 429 Client Error: Too Many Requests -``` - -**Solutions**: -1. Enable caching (default) -2. Increase delay between requests: - ```python - from scripts.utils import get_rate_limiter - limiter = get_rate_limiter() - limiter.min_delay = 5.0 # 5 seconds - ``` -3. Batch requests instead of many individual calls -4. Wait and retry later - ---- - -## Security Best Practices - -### API Key Security - -**DO**: -- Use environment variables for production -- Keep API keys out of version control -- Use config files with restricted permissions -- Rotate keys periodically - -**DON'T**: -- Commit API keys to Git -- Share API keys publicly -- Hardcode API keys in scripts -- Use API keys in client-side code - -### .gitignore Configuration - -Add to your `.gitignore`: -``` -# API keys -config/fred_api_key.txt -*.key -*_api_key.txt - -# Cache -data/cache/ - -# Environment files -.env -.env.local -``` - ---- - -## Testing Configuration - -### Quick Test Script - -Save as `test_config.py`: - -```python -"""Test market data fetcher configuration.""" - -def test_all_sources(): - """Test all data sources.""" - from scripts.fetch_unified import UnifiedMarketDataFetcher - - fetcher = UnifiedMarketDataFetcher() - - print("Available sources:", fetcher.list_available_sources()) - print() - - # Test each source - tests = [ - ('EODHD (Polish stock)', 'PKO.WAR', 'eodhd'), - ('NBP (PLN rate)', 'USD', 'nbp'), - ('Yahoo (US stock)', 'AAPL', 'yahoo'), - ('Tiingo (US stock)', 'MSFT', 'tiingo'), - ('CCXT (Crypto)', 'BTC/USDT', 'ccxt'), - ('FRED (Economic data)', 'GDP', 'fred'), - ('FinancialData.Net (US stock)', 'AAPL', 'financialdata'), - ] - - for name, ticker, source in tests: - print(f"Testing {name}...") - try: - if source in fetcher.fetchers: - df = fetcher.fetch(ticker, source=source, start_date='20240101', end_date='20240131') - print(f" ✓ Success: {len(df)} rows") - else: - print(f" ✗ {source.upper()} not available") - except Exception as e: - print(f" ✗ Error: {e}") - print() - -if __name__ == '__main__': - test_all_sources() -``` - -Run test: -```bash -python test_config.py -``` - ---- - -## Additional Resources - -### Documentation Links - -- **FRED API**: https://fred.stlouisfed.org/docs/api/ -- **Tiingo API**: https://api.tiingo.com/documentation/general/overview -- **FinancialData.Net API**: https://financialdata.net/documentation -- **CCXT**: https://github.com/ccxt/ccxt/wiki -- **yfinance**: https://github.com/ranaroussi/yfinance -- **pandas-datareader**: https://pandas-datareader.readthedocs.io/ -- **NBP API**: http://api.nbp.pl/ - -### Support - -For issues with: -- **This skill**: Check GitHub issues or documentation -- **FRED API**: https://fred.stlouisfed.org/docs/api/fred/ -- **Tiingo API**: https://api.tiingo.com/documentation/ -- **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 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 deleted file mode 100644 index ed4b051d..00000000 --- a/claude/skills/quant/market-datasets/references/dividend_treatment.md +++ /dev/null @@ -1,134 +0,0 @@ -# Dividend Treatment in Market Data Sources - -How the price sources this skill fetches from handle dividends, and the one -trap that loses them silently. - -## Quick Reference - -| 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) | - -Both price sources give you **both** series. Pick by purpose: - -| 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 | - ---- - -## How an adjusted series is built - -For a dividend `D` with ex-date `t_ex`, every price **before** `t_ex` is -multiplied by - -``` -factor = (close[t_ex - 1] - D) / close[t_ex - 1] -``` - -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). - -### Example: XTB dividend (5.45 PLN, ex-div 2025-06-13), Yahoo - -``` -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) -``` - ---- - -## The trap: adjusted levels are rewritten backwards - -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. - -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**. - -Two correct ways to keep a history incrementally: - -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. - -Or re-fetch the full adjusted history every time and overwrite — never splice -an old adjusted fetch onto a new one. - ---- - -## Yahoo Finance - -`fetch_yahoo_direct.py` returns prices with both `close` and `adj_close`, plus -dividends (`events=div`), splits (`events=splits`) or both. - -```python -import yfinance as yf - -t = yf.Ticker('XTB.WA') -t.dividends # Date, amount -t.splits # Date, ratio -t.actions # Date, Dividends, Stock Splits -``` - -## EODHD - -`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). - ---- - -## Cross-source validation - -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): - -```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}" -``` - -A persistent gap usually means a different ex-date convention or a missed -corporate action on one side. - ---- - -## Key dates terminology - -- **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 | 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 deleted file mode 100644 index a32972b4..00000000 --- a/claude/skills/quant/market-datasets/references/eodhd.md +++ /dev/null @@ -1,125 +0,0 @@ -# EODHD — coverage, plan limits, ISIN→listing pinning - -Field notes for the EODHD source (`source='eodhd'`, `scripts/fetch_eodhd.py`, -repo client `src/shared/fetch/eodhd.py`). Verified 2026-06-29 on the paid EOD plan -against the dm-evo Bloomberg securities master (`config_market.xlsx`, 829 rows). - -## Plan limits — daily refresh fits easily - -- Paid EOD plan: **100,000 requests/day**; EOD = **1 request / ticker / day**. -- Full daily refresh of ~400 ETFs is <1% of the cap. Daily cadence is a non-issue. -- Cheaper bulk path: `eod-bulk-last-day/{EXCHANGE}` returns a whole exchange in one - call — use it when refreshing many tickers on the same exchange. -- Check usage/limit: `GET https://eodhd.com/api/user?api_token=KEY` → - `apiRequests`, `dailyRateLimit`. - -## What the EOD plan does NOT include - -- **ETF holdings** (`/api/fundamentals`) → `Forbidden` on the EOD-only plan; - needs the Fundamentals add-on. Even with it, EODHD ships only the **current** - holdings snapshot — **no historical constituents**. For historical ETF holdings - use Bloomberg or the issuer's own holdings files. -- **MSCI / proprietary NR-TR indices** — not licensed: MSCI World (`MXWO`), - EStoxx50 NR (`SX5T`), Stoxx600 NR (`SXXR`), S&P NTR variants all return empty. - Native **price** indices do exist: `GSPC.INDX` (S&P 500), `GDAXI.INDX`, - `STOXX50E.INDX`, `N100.INDX`, `BCOM.INDX`. Track MSCI World via an ETF proxy - (`IWDA.LSE`, `SWDA.LSE`, `URTH.US`, `EUNL.XETRA`). - -## Coverage on the securities master (829 rows) - -| Type | Total | EODHD | Note | -|---|---|---|---| -| ETP (ETF/ETC) | 406 | **388 (96%)** | ISIN-resolvable; the tradeable feed | -| Equity / FI / Commodity Index | 372 | native price only | NR/TR variants absent (see above) | -| FX (CROSS/SPOT/FWD) | 24 | via `/forex` | not ISIN-keyed | -| SWAP / futures / OEF | 17 | ~none | Bloomberg-proprietary | - -The 18 ETP misses are delisted / rebranded share classes (Lyxor→Amundi), -sanctioned Russia ETFs, and Swiss crypto ETPs — not a feed gap. - -## Pinning ISIN → exact listing (do this, don't fetch by ISIN alone) - -One ISIN has many EODHD listings (exchange × currency × Acc/Dist). Resolve to ONE -`CODE.EXCHANGE` by matching **exchange + currency** — both carried by a -Bloomberg-style master (`exch_code`, `currency`): - -```python -import requests -res = requests.get(f"https://eodhd.com/api/search/{isin}", - params={"api_token": KEY, "fmt": "json", "limit": 50}).json() -# each record: {Code, Exchange, Currency, ISIN, isPrimary, previousClose, ...} -BBG_TO_EODHD = {"LN":"LSE","GR":"XETRA","GY":"XETRA","FP":"PA","IM":"MI", - "SW":"SW","NA":"AS","SE":"ST","US":"US","PW":"WAR","WARSAW":"WAR"} -want = BBG_TO_EODHD[exch_code] -on_exch = [x for x in res if x["Exchange"] == want] -exact = [x for x in on_exch if x["Currency"] in (ccy, "GBX" if ccy == "GBP" else ccy)] -pick = exact[0] if exact else None -eodhd_symbol = f"{pick['Code']}.{pick['Exchange']}" -``` - -Matching exchange+currency uniquely pins **83%** of the ETP universe (335/406). -**Persist the resolved `eodhd_symbol` in config** (single source of truth) so the -daily feed is deterministic and never re-resolves the ISIN. - -### Gotchas - -- **GBX vs GBP** — LSE quotes in **pence**. Same listing, not a different ticker: - set `price_scale = 0.01` when EODHD `Currency == "GBX"` and config wants `GBP`. -- **SIX Swiss** encodes currency in the code (`HODL-USD.SW`) — currency match picks - the right line automatically. -- **Missing exchange** — some Milan (`IM`) / Stockholm (`SE`) lines aren't in EODHD; - the same fund exists on LSE/XETRA in a different currency. Flag `needs_review` - rather than silently feeding a different-currency proxy. - -### Resolution status buckets - -When building a `config_ticker → eodhd_symbol` map, classify each row and carry a -`needs_review` flag: - -| Status | Meaning | scale | review | -|---|---|---|---| -| `EXACT` | unique exchange+currency match | 1 | no | -| `GBX_SCALED` | LSE pence quote vs GBP config | 0.01 | no | -| `EXACT_MULTI` | several exact lines; pick `isPrimary` | 1 | no | -| `EXCH_ONLY_CCY_DIFF` | right exchange, currency differs (non-GBX) | 1 | **yes** | -| `EXCH_MULTI_CCY` | ambiguous currency on exchange | 1 | **yes** | -| `ALT_EXCHANGE` | ISIN not on configured exchange; fungible alt | 1 | **yes** | -| `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 deleted file mode 100644 index 151eb31b..00000000 --- a/claude/skills/quant/market-datasets/references/instrument_registry_schema.yaml +++ /dev/null @@ -1,336 +0,0 @@ -# Instrument Registry Schema -# -# Purpose: -# Shared machine-readable contract for instrument registries used by -# quantbox-datasets, client dataset repos, and Qute research tasks. -# -# Design: -# The registry is metadata around market data, not a replacement for simple -# prices DataFrames. Backtests may still use columns such as BTC, SPY, or -# US10Y, while manifests and promotion checks use stable uid values. - -schema_version: instrument-registry.v1 - -description: > - A tabular instrument registry. Files may be stored as CSV or Parquet. Each - row identifies one tradable instrument, index, rate, currency pair, crypto - market, macro series, or other research feature. Dataset-specific registries - may contain a subset of a larger master registry, but uid values should remain - stable across repos and versions. - -formats: - - csv - - parquet - -primary_key: uid - -required_columns: - - uid - - symbol - - instrument_type - - asset_class - - source - - source_ticker - -required_one_of: - - columns: - - currency - - quote_currency - reason: > - Most instruments need either a trading/reporting currency or a quote - currency. Some macro/rate series may only have currency when quote - currency is not meaningful. - -columns: - uid: - type: string - required: true - nullable: false - unique: true - description: Stable instrument identifier used across dataset versions. - examples: - - isin_US78462F1030 - - crypto_BTC_USDT_SPOT - - perp_BTC_USDT_BINANCE - - fx_EURUSD - - idx_SPX - - rate_US10Y - - cmd_GOLD - - symbol: - type: string - required: true - nullable: false - description: Human-friendly canonical column name used in research DataFrames. - examples: - - SPY - - BTC - - BTCUSDT_PERP - - EURUSD - - US10Y - - name: - type: string - required: false - nullable: true - description: Human-readable instrument name. - - instrument_type: - type: enum - required: true - nullable: false - values: - - equity - - etf - - index - - crypto_spot - - crypto_perp - - crypto_future - - currency_pair - - rate - - bond - - commodity - - commodity_future - - macro_series - - fundamental_series - - option - - other - - asset_class: - type: enum - required: true - nullable: false - values: - - equity - - fixed_income - - fx - - crypto - - commodity - - macro - - fundamental - - multi_asset - - alternative - - other - - source: - type: string - required: true - nullable: false - description: Primary source for this dataset row. - examples: - - yahoo_finance - - binance - - fred - - eodhd - - nbp - - tiingo - - financialdata_net - - client_vendor - - source_ticker: - type: string - required: true - nullable: false - description: Ticker or series identifier as used by the primary source. - examples: - - SPY - - BTC/USDT - - BTC/USDT:USDT - - ^GSPC - - DGS10 - - currency: - type: string - required: false - nullable: true - description: Trading, reporting, or local currency as ISO 4217 code. - examples: - - USD - - PLN - - EUR - - quote_currency: - type: string - required: false - nullable: true - description: Quote currency for pairs, crypto markets, and derivatives. - examples: - - USD - - USDT - - PLN - - base_currency: - type: string - required: false - nullable: true - description: Base currency for FX or crypto pairs. - examples: - - BTC - - ETH - - EUR - - isin: - type: string - required: false - nullable: true - pattern: "^[A-Z]{2}[A-Z0-9]{9}[0-9]$" - description: ISIN where applicable. - - exchange: - type: string - required: false - nullable: true - description: Primary venue or exchange code. - examples: - - NYSE - - NASDAQ - - WSE - - BINANCE - - CME - - country: - type: string - required: false - nullable: true - description: ISO 3166-1 alpha-2 country code where applicable. - examples: - - US - - PL - - GB - - sector: - type: string - required: false - nullable: true - description: Sector, industry, or broad category where useful. - - ticker_yahoo: - type: string - required: false - nullable: true - description: Yahoo Finance ticker. - - ticker_stooq: - type: string - required: false - nullable: true - 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 - required: false - nullable: true - description: Binance or CCXT market symbol. - - ticker_fred: - type: string - required: false - nullable: true - description: FRED series identifier. - - ticker_bloomberg: - type: string - required: false - nullable: true - description: Bloomberg ticker where available. - - vendor_ticker: - type: string - required: false - nullable: true - description: Client/vendor-specific ticker when no public source field fits. - - multiplier: - type: number - required: false - nullable: true - description: Contract multiplier for futures, options, or vendor feeds. - - point_value: - type: number - required: false - nullable: true - description: Monetary value of one point where applicable. - - price_unit: - type: string - required: false - nullable: true - description: Unit convention for price levels. - examples: - - USD - - percent - - index_points - - cents_per_bushel - - mapping_source: - type: enum - required: false - nullable: true - values: - - manual - - source_api - - yahoo_api - - vendor_file - - inferred - - migrated - - unknown - - last_verified: - type: date - required: false - nullable: true - description: Date when the mapping was last checked. - - active: - type: boolean - required: false - nullable: true - default: true - description: Whether the instrument is active in the registry. - - start_date: - type: date - required: false - nullable: true - description: Earliest expected data date for this instrument in the dataset. - - end_date: - type: date - required: false - nullable: true - description: Last expected data date when known, for delisted or retired instruments. - - notes: - type: string - required: false - nullable: true - description: Free-form notes for caveats or mapping assumptions. - -uid_conventions: - equity_with_isin: "isin_{ISIN}" - etf_with_isin: "isin_{ISIN}" - equity_without_isin: "eq_{COUNTRY}_{EXCHANGE}_{SYMBOL}" - etf_without_isin: "etf_{SYMBOL}" - equity_index: "idx_{SYMBOL}" - fx_pair: "fx_{BASE}{QUOTE}" - crypto_spot: "crypto_{BASE}_{QUOTE}_SPOT" - crypto_perp: "perp_{BASE}_{QUOTE}_{EXCHANGE}" - crypto_future: "future_{BASE}_{QUOTE}_{EXCHANGE}_{EXPIRY}" - rate: "rate_{SYMBOL}" - commodity: "cmd_{SYMBOL}" - commodity_future: "cmdf_{SYMBOL}_{EXCHANGE}" - macro_series: "macro_{SOURCE}_{SERIES}" - -validation_rules: - - uid must be unique and non-empty. - - symbol must be non-empty and should match a market data column when the registry is dataset-specific. - - source_ticker must be non-empty for the declared source. - - either currency or quote_currency should be present unless the row is a non-currency macro/fundamental series. - - ticker_* columns are optional, but if present they should not contradict source/source_ticker. - - dataset-specific registries may omit unused optional columns. - - master registries should preserve inactive instruments instead of deleting them when historical data still references them. - diff --git a/claude/skills/quant/market-datasets/references/long_history_construction.md b/claude/skills/quant/market-datasets/references/long_history_construction.md deleted file mode 100644 index 359772e8..00000000 --- a/claude/skills/quant/market-datasets/references/long_history_construction.md +++ /dev/null @@ -1,294 +0,0 @@ -# Long-History Asset Series Construction - -How to build multi-decade monthly total return series for investment research. Uses ETF/fund data as primary source with academic/government backfill for earlier periods. - -## When to Use - -- Portfolio backtesting requiring 30+ years of data -- Risk calibration across multiple crisis periods (GFC, dot-com, oil crisis, etc.) -- Strategic asset allocation studies -- Long-run return and risk estimation - -## Academic Data Sources - -### Damodaran (NYU Stern) - -**URL**: `pages.stern.nyu.edu/~adamodar/` → "Historical Returns on Stocks, Bonds and Bills" -**File**: `histretSP.xls` (download as `damodaran_histret.xls`) -**Coverage**: Annual returns 1928-2024 -**Series**: S&P 500 (with dividends), 3-month T-Bill, 10Y T-Bond, Gold -**Frequency**: Annual only - -```python -def load_damodaran(path: str) -> pd.DataFrame: - df = pd.read_excel(path, sheet_name="Returns by year", header=None) - # Find header row containing "Year" - header_row = None - for i, row in df.iterrows(): - if any(str(v).strip() == "Year" for v in row.values if pd.notna(v)): - header_row = i - break - data = df.iloc[header_row + 1:].copy() - data.columns = df.iloc[header_row].values - data["Year"] = pd.to_numeric(data["Year"], errors="coerce") - data = data[data["Year"].notna() & (data["Year"] >= 1928)].copy() - data = data.set_index(data["Year"].astype(int)) - - result = pd.DataFrame(index=data.index) - result["sp500"] = pd.to_numeric(data["S&P 500 (includes dividends)"], errors="coerce") - result["tbill"] = pd.to_numeric(data["3-month T.Bill"], errors="coerce") - result["tbond"] = pd.to_numeric(data["US T. Bond (10-year)"], errors="coerce") - result["gold"] = pd.to_numeric(data["Gold*"], errors="coerce") - return result.dropna() -``` - -**Gotchas**: -- Column names vary between Excel versions — search for "Year" row dynamically -- Returns are decimal fractions (0.12 = 12%), not percentages -- Annual only — need interpolation or Shiller for monthly - -### Shiller (ie_data.xls) - -**URL**: `shillerdata.com` → "Online Data Robert Shiller" -**File**: `ie_data.xls` -**Coverage**: Monthly from 1871+ -**Series**: S&P 500 price, dividends, earnings, CPI, 10Y GS10 yield -**Frequency**: Monthly - -```python -def load_shiller(path: str) -> pd.DataFrame: - df = pd.read_excel(path, sheet_name="Data", header=None, engine="xlrd") - data = df.iloc[8:].copy() # Skip header rows - data.columns = range(data.shape[1]) - data = data[pd.to_numeric(data[0], errors="coerce").notna()].copy() - - # Date is encoded as YYYY.MM (e.g., 2024.01) - data["year"] = data[0].astype(float).apply(lambda x: int(x)) - data["month"] = data[0].astype(float).apply(lambda x: round((x % 1) * 100)) - data["month"] = data["month"].clip(1, 12).astype(int) - data["date"] = pd.to_datetime( - data["year"].astype(str) + "-" + data["month"].astype(str).str.zfill(2) + "-01" - ) - data = data.set_index("date").sort_index() - - result = pd.DataFrame(index=data.index) - result["sp500_price"] = pd.to_numeric(data[1], errors="coerce") - result["sp500_dividend"] = pd.to_numeric(data[2], errors="coerce") # Annual rate - result["gs10"] = pd.to_numeric(data[6], errors="coerce") # 10Y yield % - return result.dropna(subset=["sp500_price"]) -``` - -**Gotchas**: -- Date column is float (2024.01 = Jan 2024) — parse carefully -- Dividends are annualized — divide by 12 for monthly -- Needs `engine="xlrd"` for .xls format -- Column positions may shift — verify against headers - -### FRED (Federal Reserve Economic Data) - -**URL**: `fred.stlouisfed.org` -**Key series**: TB3MS (3-month T-bill rate), DGS10 (10Y treasury yield) -**Coverage**: TB3MS from 1934+, monthly -**Access**: Free CSV download, no API key needed for direct download - -```python -def fetch_fred_tbill() -> pd.Series: - url = "https://fred.stlouisfed.org/graph/fredgraph.csv?id=TB3MS" - df = pd.read_csv(url) - date_col = [c for c in df.columns if "date" in c.lower()][0] - df[date_col] = pd.to_datetime(df[date_col]) - df = df.set_index(date_col).sort_index() - series = pd.to_numeric(df.iloc[:, 0], errors="coerce").dropna() - monthly_return = series / 100 / 12 # Annual % → monthly return - return monthly_return.resample("ME").last().dropna() -``` - -### EODHD (Gold) - -**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 -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() -``` - -If the series starts later than you need, backfill with Damodaran's annual -gold return (loses monthly granularity). - -## Construction Patterns - -### Pattern 1: ETF-Primary Splice - -Use real ETF/fund data where available, synthetic backfill for earlier dates. - -```python -def splice_series(primary: pd.Series, backfill: pd.Series, name: str) -> pd.Series: - """Use primary where available, backfill for earlier dates. No blending.""" - if len(primary) == 0: - result = backfill.copy() - result.name = name - return result - - splice_date = primary.index.min() - backfill_part = backfill[backfill.index < splice_date] - result = pd.concat([backfill_part, primary]).sort_index() - result = result[~result.index.duplicated(keep="last")] - result.name = name - return result -``` - -**Key decisions**: -- No overlap blending — clean switch at splice point -- Primary takes precedence (keep="last" for duplicates) -- Log the splice point for documentation - -### Pattern 2: Synthetic Bond Return from Yield - -Convert a yield time series to monthly bond total return using duration approximation. - -```python -def build_synthetic_bond_return(yields: pd.Series, duration: float = 7.0) -> pd.Series: - """Monthly total return from yield series. - - Args: - yields: Monthly yield in decimal (e.g., 0.05 for 5%) - duration: Modified duration (years). Use ~7 for 10Y benchmark, ~2 for short. - """ - coupon = yields.shift(1) / 12 # Monthly income - dy = yields - yields.shift(1) # Yield change - price_change = -duration * dy # Price return (duration approx) - monthly_return = (coupon + price_change).dropna() - monthly_return.index = monthly_return.index + pd.offsets.MonthEnd(0) - return monthly_return -``` - -**Duration choices**: -- `duration=7.0` → approximates Bloomberg Aggregate / VBMFX -- `duration=2.0` → approximates short treasury / VFISX -- Convexity ignored — acceptable for monthly frequency - -### Pattern 3: Equity Total Return from Price + Dividends - -```python -def build_equity_total_return(price: pd.Series, annual_dividend: pd.Series) -> pd.Series: - """Monthly total return from price and annualized dividend series.""" - monthly_dividend = annual_dividend / 12 - total_return = (price + monthly_dividend) / price.shift(1) - 1 - ret = total_return.dropna() - ret.index = ret.index + pd.offsets.MonthEnd(0) - return ret -``` - -### Pattern 4: T-Bill Yield to Monthly Return - -```python -# FRED TB3MS is annualized %, convert to monthly return -monthly_return = annual_pct / 100 / 12 -``` - -### Pattern 5: Blended Component Series - -For asset classes that are themselves blends (e.g., FI_SHORT = 50% T-bill + 50% short treasury): - -```python -def build_blended_series(components: dict[str, pd.Series], weights: dict[str, float]) -> pd.Series: - """Blend multiple component series with fixed weights.""" - df = pd.DataFrame(components).dropna() - result = sum(df[name] * w for name, w in weights.items()) - return result -``` - -### Pattern 6: ETF Monthly Return from yfinance - -```python -def fetch_etf_monthly(ticker: str, start: str = "1976-01-01") -> pd.Series: - """Fetch monthly total returns for ETF/fund via yfinance.""" - df = yf.download(ticker, start=start, auto_adjust=False, progress=False) - col = "Adj Close" if "Adj Close" in df.columns else "Close" - ts = df[col].squeeze().sort_index() - monthly = ts.resample("ME").last().dropna() - returns = monthly.pct_change().dropna() - returns.name = ticker - return returns -``` - -**Use `Adj Close`** for total return (includes dividends). `Close` is price return only. - -## Standard Asset Class Recipes - -### Equity (S&P 500 Total Return) - -``` -Primary: VFINX (Vanguard 500 Index Fund, 1976+) via yfinance -Backfill: Shiller S&P 500 price + dividends → total return (1871+) -Splice: ~1976 -Result: Monthly TR, 1871-2025 -``` - -### Core Bonds (Aggregate, ~5% vol) - -``` -Primary: VBMFX (Vanguard Total Bond Market, 1987+) via yfinance -Backfill: Shiller GS10 yield → synthetic bond return, duration=7 (1871+) -Splice: ~1987 -Result: Monthly TR, 1871-2025 -``` - -### Short Duration (~1.5% vol) - -``` -Primary: 50% SHV (T-bill ETF, 2007+) + 50% VFISX (short treasury, 1991+) -Backfill: 50% FRED TB3MS (1934+) + 50% synthetic bond dur=2 from Shiller -Splice: ~1991 (VFISX), ~2007 (SHV) -Result: Monthly TR, 1934-2025 -``` - -### Commodities (Gold) - -``` -Primary: EODHD XAUUSD.FOREX, resampled monthly (start date: probe) -Backfill: N/A (or Damodaran annual gold, but loses monthly granularity) -Result: Monthly price return from the EODHD start (Damodaran annual before it) -Note: Price return only — gold has no yield -``` - -## Validation - -### Overlap Comparison - -Always compare ETF vs synthetic in the overlap window: - -```python -overlap = primary.index.intersection(backfill.index) -if len(overlap) > 12: - r1 = backfill.loc[overlap] - r2 = primary.loc[overlap] - print(f"Correlation: {r1.corr(r2):.3f}") - print(f"Ann return diff: {((1+r2).prod()**(12/len(overlap)) - (1+r1).prod()**(12/len(overlap)))*100:.1f}pp") - print(f"Vol ratio: {r2.std() / r1.std():.2f}") -``` - -**Expected results**: -- Equity (Shiller vs VFINX): correlation >0.99 -- Bonds (synthetic vs VBMFX): correlation ~0.95 (duration approximation introduces noise) -- If correlation <0.90, investigate before trusting the splice - -### Full-Period Sanity Checks - -After construction, verify: -- Ann. return in expected range (equity 8-11%, bonds 4-7%, T-bill 3-5%) -- Vol in expected range (equity 14-17%, bonds 5-7%, T-bill 1-2%) -- Max DD plausible (equity -45 to -55%, bonds -15 to -25%) -- No gaps in time series -- Correct number of months for the date range - -## Reference Implementation - -See `research/risk-profile-calibration/build_asset_data_v2.py` for the complete working implementation covering all 4 asset classes. diff --git a/claude/skills/quant/market-datasets/references/migration.md b/claude/skills/quant/market-datasets/references/migration.md deleted file mode 100644 index 84d584fe..00000000 --- a/claude/skills/quant/market-datasets/references/migration.md +++ /dev/null @@ -1,42 +0,0 @@ -# Project Migration - -After prototyping with this skill, migrate fetchers to your production project. - -## Migrate a Data Source - -```bash -# List available sources -uv run scripts/migrate_to_project.py --list - -# 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 - -# Migrate all fetchers -uv run scripts/migrate_to_project.py all --target src/fetchers/ --include-utils --include-env -``` - -## What Migration Produces - -``` -src/data_sources/ # Your target directory -├── fetch_eodhd.py # Self-contained with PEP 723 dependencies -├── utils.py # Shared utilities (if --include-utils) -└── .env.example # API key template (if --include-env) -``` - -## After Migration - -The migrated scripts work standalone: -```bash -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_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 deleted file mode 100644 index 39c31b87..00000000 --- a/claude/skills/quant/market-datasets/references/security_master.md +++ /dev/null @@ -1,210 +0,0 @@ -# Security Master Schema - -Documentation for the `security_master.csv` file and `TickerRegistry` service. - -For QuantBox/Qute dataset repos, the canonical machine-readable contract is -[`instrument_registry_schema.yaml`](instrument_registry_schema.yaml). This page -documents the current CSV-backed skill registry and usage patterns. - -## Overview - -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, Bloomberg, FRED; EODHD symbols derive from Yahoo) -- Auto-discovery of Yahoo tickers from ISINs - -**Location**: `.claude/skills/market-datasets/data/security_master.csv` - -## Current CSV Schema - -| Column | Type | Required | Description | Example | -|--------|------|----------|-------------|---------| -| `uid` | string | **Yes** | Universal ID - primary key | `isin_PLXTRDM00011`, `idx_WIG20`, `fx_USDPLN` | -| `isin` | string | No | ISIN code (if applicable) | `PLXTRDM00011` | -| `name` | string | No | Instrument name | `XTB` | -| `instrument_type` | enum | No | Type: equity, index, currency, bond, commodity, etf | `equity` | -| `country` | string | No | ISO country code | `PL` | -| `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 | **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` | -| `mapping_source` | string | No | How mapping was obtained | `manual`, `yahoo_api` | -| `last_updated` | datetime | No | When mapping was verified | `2026-01-09` | - -## Dataset Registry Schema - -Dataset repos should use the shared instrument registry contract: - -```text -references/instrument_registry_schema.yaml -``` - -Minimum required columns: - -| Column | Description | -|--------|-------------| -| `uid` | Stable primary key across dataset versions | -| `symbol` | Canonical DataFrame column name | -| `instrument_type` | Instrument type such as `etf`, `crypto_spot`, `crypto_perp`, `rate` | -| `asset_class` | Broad asset class such as `equity`, `crypto`, `fx`, `macro` | -| `source` | Primary source used by this dataset row | -| `source_ticker` | Source-native ticker or series identifier | -| `currency` or `quote_currency` | Currency context where applicable | - -The older CSV registry uses `uid` plus source-specific `ticker_*` columns. A -dataset-specific registry should add `symbol`, `asset_class`, `source`, and -`source_ticker` so that simple price DataFrames remain easy to use while run -manifests can still record stable instrument identity. - -## UID Conventions - -The `uid` (Universal ID) is the primary key. Format conventions: - -| Instrument Type | UID Format | Example | -|-----------------|------------|---------| -| Equity (with ISIN) | `isin_{ISIN}` | `isin_PLXTRDM00011` | -| Index | `idx_{NAME}` | `idx_WIG20` | -| Currency pair | `fx_{PAIR}` | `fx_USDPLN` | -| Bond | `bond_{ISIN}` | `bond_US912828YM28` | -| Commodity | `cmd_{NAME}` | `cmd_GOLD` | -| Rate | `rate_{NAME}` | `rate_WIBOR3M` | - -For crypto and derivatives, prefer the newer dataset conventions: - -| Instrument Type | UID Format | Example | -|-----------------|------------|---------| -| Crypto spot | `crypto_{BASE}_{QUOTE}_SPOT` | `crypto_BTC_USDT_SPOT` | -| Crypto perpetual | `perp_{BASE}_{QUOTE}_{EXCHANGE}` | `perp_BTC_USDT_BINANCE` | -| Crypto future | `future_{BASE}_{QUOTE}_{EXCHANGE}_{EXPIRY}` | `future_BTC_USDT_BINANCE_20260626` | - -## TickerRegistry Usage - -### Basic Usage - -```python -from ticker_registry import TickerRegistry - -# Initialize (loads from default CSV path) -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('idx_WIG20') # By uid - -# Access properties -print(security.name) # 'XTB' -print(security.isin) # 'PLXTRDM00011' -print(security.get_ticker('yahoo')) # 'XTB.WA' -``` - -### Ticker Conversion - -```python -from ticker_registry import TickerRegistry, convert_ticker - -registry = TickerRegistry() - -# Convert between formats -yahoo_ticker = registry.convert_ticker('PLXTRDM00011', to_source='yahoo') # 'XTB.WA' - -# Convenience functions (use default registry) -from ticker_registry import isin_to_yahoo, ticker_to_isin - -yahoo = isin_to_yahoo('PLXTRDM00011') # 'XTB.WA' -isin = ticker_to_isin('XTB.WA') # 'PLXTRDM00011' -``` - -### Batch Operations - -```python -registry = TickerRegistry() - -# Convert multiple tickers -isins = ['PLXTRDM00011', 'PLCCC0000016', 'PLBSK0000017'] -yahoo_tickers = registry.convert_tickers_batch(isins, to_source='yahoo') -# {'PLXTRDM00011': 'XTB.WA', 'PLCCC0000016': 'CCC.WA', 'PLBSK0000017': 'ING.WA'} -``` - -### Auto-Discovery - -```python -registry = TickerRegistry() - -# Discover Yahoo tickers for ISINs not in registry -discovered = registry.discover_missing_yahoo_tickers(['US0378331005', 'GB0002634946']) -# {'US0378331005': 'AAPL', 'GB0002634946': 'BA.L'} - -# Discover for all ISINs missing Yahoo ticker in registry -discovered = registry.discover_missing_yahoo_tickers() -``` - -### Adding New Entries - -```python -from ticker_registry import TickerRegistry, Security -from datetime import datetime - -registry = TickerRegistry() - -# Add manually -security = Security( - uid='isin_GB0002634946', - isin='GB0002634946', - name='BAE Systems', - instrument_type='equity', - country='GB', - exchange='LSE', - tickers={'yahoo': 'BA.L'}, - mapping_source='manual', - last_updated=datetime.now() -) -registry.register_security(security) - -# Add ticker to existing security -registry.add_ticker_mapping('PLXTRDM00011', 'bloomberg', 'XTB PW Equity') - -# Export to DataFrame -df = registry.to_dataframe() -``` - -## Instrument Types - -| Type | Description | Examples | -|------|-------------|----------| -| `equity` | Listed stocks | XTB, CCC, PKO | -| `index` | Market indices | WIG20, S&P 500 | -| `currency` | FX pairs | USD/PLN, EUR/USD | -| `bond` | Fixed income | Government bonds, corporate bonds | -| `commodity` | Physical commodities | Gold, Oil | -| `etf` | Exchange-traded funds | SPY, QQQ | - -## Ticker Format Reference - -| Source | Format | Example | -|--------|--------|---------| -| Yahoo Finance | Uppercase + exchange suffix | `XTB.WA`, `AAPL`, `^GSPC` | -| 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` | - -## Data Sources for Mappings - -| Source | Method | Coverage | -|--------|--------|----------| -| `manual` | Hand-curated | Full control, any format | -| `yahoo_api` | Auto-discovered via Yahoo search | ISIN → Yahoo ticker | -| `csv` | Loaded from CSV | Existing entries | - -## File Location - -Default path: `.claude/skills/market-datasets/data/security_master.csv` - -Custom path: -```python -registry = TickerRegistry(csv_path=Path('/custom/path/master.csv')) -``` diff --git a/claude/skills/quant/market-datasets/references/sources_overview.md b/claude/skills/quant/market-datasets/references/sources_overview.md deleted file mode 100644 index 2f511ea7..00000000 --- a/claude/skills/quant/market-datasets/references/sources_overview.md +++ /dev/null @@ -1,639 +0,0 @@ -# Market Data Sources Overview - -Comprehensive comparison of all supported data sources for the market-datasets skill. - -## Quick Reference Table - -| Source | Best For | Coverage | Auth Required | Rate Limits | Cost | -|--------|----------|----------|---------------|-------------|------| -| **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 | -| **CCXT (Binance)** | Cryptocurrency | BTC, ETH, altcoins | No | Exchange limits | Free | -| **FRED** | Economic indicators | US economic data (GDP, CPI, rates) | Yes (API key) | None documented | Free | -| **FinancialData.Net** | Fundamentals, options, insider data | US/intl stocks, options, fundamentals, insider | Yes (API key) | Tier-dependent | Free/Paid | -| **pandas-datareader** | Meta-source fallback | Multiple sources via single interface | Varies | Varies | Free | - -## Dividend Treatment Quick Reference - -| Source | Price Type | Dividends Available | Use For | -|--------|------------|---------------------|---------| -| **EODHD** | Both (close + adjusted_close) | Yes (splits/div-adjusted) | P&L (close), returns (adjusted_close) | -| **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 | - -See `references/dividend_treatment.md` for detailed dividend handling documentation. - ---- - -## Detailed Source Descriptions - -### 1. NBP API (api.nbp.pl) - -**Purpose**: Official Polish National Bank exchange rates. - -**Coverage**: -- PLN exchange rates vs major currencies (USD, EUR, GBP, CHF, etc.) -- Table A: Most common currencies (daily rates) -- Table B: Less common currencies -- Table C: Buy/sell rates - -**Data Available**: -- Mid rates (Tables A & B) -- Bid/Ask rates (Table C) -- Daily data -- Historical data from ~2002 - -**Strengths**: -- Official NBP rates -- Free JSON API -- No authentication required -- Reliable and maintained - -**Limitations**: -- PLN pairs only (no USD/EUR etc.) -- Daily frequency only -- Market days only (no weekends) - -**Best For**: -- Official PLN FX rates for accounting -- Fund NAV calculations -- Regulatory reporting - -**Example Codes**: -- `USD` - US Dollar -- `EUR` - Euro -- `GBP` - British Pound - ---- - -### 2. Yahoo Finance (via yfinance or Direct API) - -**Purpose**: Comprehensive global market data. - -**Coverage**: -- US stocks (NASDAQ, NYSE, etc.) -- International stocks (with market suffix) -- ETFs -- Indices -- Cryptocurrencies -- Some commodities - -**Data Available**: -- OHLCV + Adjusted Close -- Intraday to monthly intervals -- Dividends and stock splits -- Company info/metadata - -**Two Access Methods**: - -1. **yfinance library** (`fetch_yahoo.py`) - - Standard Python library - - May experience rate limiting (HTTP 429 errors) - -2. **Direct API** (`fetch_yahoo_direct.py`) - **Recommended** - - Bypasses yfinance rate limiting issues - - Supports ISIN-to-ticker automatic conversion - - Returns prices, dividends, and splits separately - -**Corporate Actions Captured**: -| Action | Captured? | API Parameter | -|--------|-----------|---------------| -| Dividends | Yes | `events=div` | -| Stock splits | Yes | `events=splits` | -| Rights issues | No | - | -| Spin-offs | No | - | - -**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` 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 - -**Strengths**: -- Comprehensive US market coverage -- Global reach with market suffixes -- High data quality -- Adjusted prices for splits/dividends -- Free (no authentication required) -- ISIN lookup via search API - -**Limitations**: -- Unofficial API (could change) -- yfinance library prone to rate limiting (use Direct API instead) -- Polish stocks: Limited history -- Does NOT capture: rights issues, spin-offs, buybacks - -**Best For**: -- US stock analysis -- International equities -- Cross-market comparisons -- Portfolio tracking -- Fetching by ISIN (auto-conversion) -- Dividend and split data - -**Example Tickers**: -- `AAPL` - Apple Inc. -- `^GSPC` - S&P 500 Index -- `PKO.WA` - PKO on Warsaw Stock Exchange -- `XTB.WA` - XTB on Warsaw Stock Exchange - -**Example ISINs** (auto-converted via Direct API): -- `US0378331005` → `AAPL` -- `PLXTRDM00011` → `XTB.WA` -- `PLCCC0000016` → `CCC.WA` - ---- - -### 3. Tiingo (api.tiingo.com) - -**Purpose**: High-quality US stock data with generous free tier and 30+ years of history. - -**Coverage**: -- US stocks (NYSE, NASDAQ, AMEX) -- ETFs -- ADRs -- 86,000+ securities - -**Data Available**: -- OHLCV + Adjusted prices -- Dividend amounts -- Split factors -- 30+ years of history -- Daily frequency - -**Free Tier Limits**: -- 50 requests per hour -- 1,000 requests per day -- 500 unique symbols per month - -**Strengths**: -- Excellent data quality -- **Best free tier** of all stock APIs -- 30+ years of history -- Dividend and split data -- Reliable (backed by IEX data) - -**Limitations**: -- **Requires API key** (free registration) -- US securities focus -- Monthly symbol limit - -**Best For**: -- Yahoo Finance fallback -- Historical US stock analysis -- Dividend-adjusted returns -- Quality validation - -**Setup**: Get free API key at https://api.tiingo.com/ - -```python -# Set environment variable -os.environ['TIINGO_API_KEY'] = 'your_api_key' - -# Or pass directly -df = fetch_market_data('AAPL', source='tiingo', tiingo_api_key='your_key') -``` - ---- - -### 4. CCXT / Binance (Cryptocurrency) - -**Purpose**: Cryptocurrency historical OHLCV data from Binance and 100+ exchanges. - -**Coverage**: -- All Binance trading pairs (BTC, ETH, altcoins) -- 100+ exchanges via CCXT library -- Spot, futures, perpetuals - -**Data Available**: -- OHLCV (Open, High, Low, Close, Volume) -- Timeframes: 1m, 5m, 15m, 1h, 4h, 1d, 1w -- Years of history (exchange dependent) - -**Rate Limits**: -- Built-in CCXT rate limiting -- Exchange-specific limits respected - -**Strengths**: -- **Unlimited** historical data (no API key needed) -- Multiple exchanges with unified interface -- Minute-level granularity -- Real-time available - -**Limitations**: -- Requires ccxt package -- Exchange-specific quirks -- No fundamental data - -**Best For**: -- Bitcoin/Ethereum analysis -- Crypto portfolio tracking -- Algorithmic trading research -- DeFi token analysis - -**Supported Exchanges**: -- Binance (default) -- Kraken -- Coinbase Pro -- KuCoin -- Bybit -- OKX -- and 100+ more - -**Example Usage**: - -```python -# Auto-routed (detects crypto symbols) -df = fetch_market_data('BTC/USDT', start_date='20240101') - -# Symbol formats (all work) -df = fetch_market_data('ETHUSDT') # Without slash -df = fetch_market_data('ETH/USD') # With slash -df = fetch_market_data('SOL/USDT') # Altcoins - -# Different timeframes -df = fetch_market_data('BTC/USDT', timeframe='1h') # Hourly -df = fetch_market_data('BTC/USDT', timeframe='1w') # Weekly - -# Different exchange -fetcher = UnifiedMarketDataFetcher(crypto_exchange='kraken') -df = fetcher.fetch('BTC/USD') -``` - ---- - -### 5. FRED API (fred.stlouisfed.org) - -**Purpose**: US economic indicators from Federal Reserve. - -**Coverage**: -- US economic indicators -- GDP, inflation, unemployment -- Interest rates -- Consumer confidence -- Money supply -- 800,000+ time series - -**Data Available**: -- Economic indicator values -- Various frequencies (daily, monthly, quarterly, annual) -- Extensive historical data -- Metadata (units, seasonality, etc.) - -**Strengths**: -- Authoritative economic data -- Vast coverage -- Official Federal Reserve source -- Well-documented API -- Free with API key - -**Limitations**: -- **Requires API key** (free registration) -- US-focused data only -- Low-frequency data (mostly monthly/quarterly) - -**Best For**: -- Macroeconomic analysis -- Economic research -- Factor modeling -- Risk analysis - -**Example Series**: -- `GDP` - Gross Domestic Product -- `UNRATE` - Unemployment Rate -- `CPIAUCSL` - Consumer Price Index -- `DGS10` - 10-Year Treasury Rate - -**Setup**: See `references/api_setup.md` for API key configuration. - ---- - -### 6. FinancialData.Net (financialdata.net) - -**Purpose**: Comprehensive financial data API covering stocks, fundamentals, options, forex, crypto, and institutional data. - -**Coverage**: -- US stocks, international stocks, ETFs, commodities, OTC -- Options (chain, prices, Greeks), futures -- Cryptocurrency, forex -- Financial statements (income, balance sheet, cash flow) -- Financial ratios (liquidity, solvency, efficiency, profitability, valuation) -- Company info, key metrics, market cap -- Insider transactions, senate/house trading -- Institutional investors, holdings -- Earnings/IPO/splits/dividends calendars -- Press releases (company, SEC, Fed) - -**Data Available**: -- OHLCV prices (daily, minute) -- Real-time quotes (Premium) -- 50+ API endpoints -- JSON and CSV output formats - -**Subscription Tiers**: -| Tier | Access | -|------|--------| -| **Free** | Symbol lists, stock prices, commodity prices, OTC data | -| **Standard** | Company info, financials, ratios, derivatives, crypto | -| **Premium** | Real-time quotes, international data, forex, press releases | - -**Strengths**: -- Comprehensive coverage in a single API -- Options and derivatives data (chain, Greeks) -- Institutional and insider trading data -- Financial statements and ratios -- Senate/House trading disclosures -- Event calendars (earnings, IPO, splits, dividends) -- Python SDK available (`fdnpy`) - -**Limitations**: -- **Requires API key** (free tier available) -- Premium endpoints need paid subscription -- Record limits per call (300-500, paginated) -- No Polish market-specific data - -**Best For**: -- Fundamental analysis -- Options research -- Institutional ownership tracking -- Congressional trading monitoring -- Financial statement analysis -- Event-driven strategy research - -**API Details**: -- Base URL: `https://financialdata.net/api/v1/` -- Auth: Query parameter `?key=API_KEY` -- Pagination: `offset` parameter, limits vary by endpoint (300-500) -- Timezones: EST for stocks, UTC for crypto/forex - -**Example Usage**: - -```python -from fetch_financialdata import FinancialDataFetcher, fetch_financialdata - -# Stock prices -df = fetch_financialdata('AAPL', start_date='2024-01-01') - -# Financial statements -df = fetch_financialdata('AAPL', endpoint='income-statements', period='year') - -# Option chain -df = fetch_financialdata('AAPL', endpoint='option-chain') - -# Insider transactions -df = fetch_financialdata('AAPL', endpoint='insider-transactions') - -# Senate trading -fetcher = FinancialDataFetcher() -df = fetcher.get_senate_trading() -``` - -**Setup**: Get API key at https://financialdata.net, set `FINANCIAL_DATA_API_KEY` env var. - ---- - -### 7. pandas-datareader - -**Purpose**: Meta-source providing unified interface to multiple data providers. - -**Coverage**: -- Yahoo Finance (via pandas-datareader) -- FRED (via pandas-datareader) -- Alpha Vantage (requires API key) -- IEX Cloud (requires API key) -- Quandl (requires API key) - -**Data Available**: -- Depends on underlying source -- Generally: OHLCV for markets, values for economic data - -**Strengths**: -- Unified interface -- Useful fallback -- Access to multiple sources -- Well-maintained library - -**Limitations**: -- Requires pandas-datareader package -- Source-specific quirks -- Some sources deprecated over time -- Additional API keys may be needed - -**Best For**: -- Fallback when primary sources fail -- Quick prototyping -- Multi-source data pipelines - ---- - -## Source Selection Strategy - -### Automatic Routing (Recommended) - -The unified fetcher automatically selects sources based on ticker patterns: - -1. **Cryptocurrency** (BTC/USDT, ETHUSDT) → CCXT/Binance -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. **Other currency pairs** (EURUSD) → Yahoo (`EURUSD=X`) -8. **Fundamentals/options** → FinancialData.Net (via `fd_endpoint` parameter) -9. **Fallback** → pandas-datareader - -### Manual Source Selection - -Force specific source when needed: - -```python -# 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') - -# Force NBP for PLN rate -df = fetch_market_data('USD', source='nbp', table='A') -``` - -### Multi-Source Comparison - -Compare data across sources: - -```python -comparison = fetcher.compare_sources('PKO.WA', ['eodhd', 'yahoo']) -``` - ---- - -## Rate Limiting & Best Practices - -### Respect Rate Limits - -All fetchers include automatic rate limiting: -- Minimum 1-2 second delay between requests -- Configurable per source -- Automatic retry logic - -### Use Caching - -Enable caching to minimize requests: - -```python -fetcher = UnifiedMarketDataFetcher(use_cache=True, cache_hours=24) -``` - -Cache locations: -- `data/cache/market_data/eodhd/` -- `data/cache/market_data/nbp/` -- `data/cache/market_data/yahoo/` -- `data/cache/market_data/fred/` - -### Batch Requests - -Use batch methods when fetching multiple tickers: - -```python -# More efficient than individual calls -results = fetcher.fetch_multiple(['pko', 'cdr', 'pzu']) -``` - ---- - -## Dependencies - -### Required Packages - -```bash -pip install pandas requests -``` - -### Optional Packages - -```bash -# For Yahoo Finance -pip install yfinance - -# For pandas-datareader -pip install pandas-datareader - -# For Tiingo -pip install tiingo # Or use built-in REST (no extra package) - -# For Cryptocurrency (CCXT) -pip install ccxt -``` - -### API Keys (Optional) - -- **FRED**: Required for economic data - - Get at: https://fred.stlouisfed.org/docs/api/api_key.html - - See: `references/api_setup.md` - -- **Tiingo**: Required for Tiingo data - - Get at: https://api.tiingo.com/ - - Set: `TIINGO_API_KEY` environment variable - -- **FinancialData.Net**: Required for all endpoints - - Get at: https://financialdata.net - - Set: `FINANCIAL_DATA_API_KEY` environment variable - - Free tier: stock prices, symbol lists - - Standard/Premium: fundamentals, options, forex, insider data - -- **CCXT**: No API key needed for public historical data - ---- - -## Troubleshooting - -### Source Unavailable - -If a source is unavailable: -1. Check if required package is installed -2. Verify API key configuration (for FRED) -3. Check internet connectivity -4. Try fallback source - -### Data Quality Issues - -If data appears incorrect: -1. Compare across sources using `compare_sources()` -2. Check ticker format is correct for source -3. Verify date range is valid -4. Check for corporate actions (splits, dividends) - -### Rate Limiting - -If experiencing rate limiting: -1. Increase delay in rate limiter -2. Enable caching to reduce requests -3. Batch similar requests together -4. Use off-peak hours for large downloads - ---- - -## When to Use Which Source - -| Scenario | Recommended Source | Rationale | -|----------|-------------------|-----------| -| 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 | 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** | 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 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 | -| **US stocks when Yahoo fails** | Tiingo → FinancialData.Net | Best free tier backup | -| **Fundamental analysis** | FinancialData.Net | Income/balance/cash flow statements | -| **Financial ratios** | FinancialData.Net | Liquidity, solvency, profitability, valuation | -| **Options research** | FinancialData.Net | Option chain, prices, Greeks | -| **Insider trading** | FinancialData.Net | Insider transactions, congress trading | -| **Institutional ownership** | FinancialData.Net | Holders, holdings, portfolio stats | -| **Event calendars** | FinancialData.Net | Earnings, IPO, splits, dividends | - -### 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 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`. -- Exchange-suffixed symbols: `.US`, `.LSE` (London), `.WAR` (Warsaw/GPW), `.INDX` (indices), plus ISIN lookup. -- Splits/dividend-adjusted; tz-naive daily history. -- Validated 2026-06-29 on a 42-instrument ETF benchmark universe: **100% resolution**, fresher than yfinance (incl. GPW Beta ETFs `.WAR` and UCITS `.LSE`). - -**Tiers** -- Free: ~1 year history, 20 calls/day, limited symbols (validation only). -- Paid (EOD Historical Data, ~$20/mo): full multi-decade history, 100k calls/day. - -**Symbol mapping** (see `scripts/fetch_eodhd.py::eodhd_symbol`): bare ticker → `.US`; Yahoo `.WA` → `.WAR`; Yahoo `.L` → `.LSE`; `^IDX` → `IDX.INDX`; already-suffixed → passthrough. - -```bash -export EODHD_API_KEY="your_key" -uv run scripts/fetch_eodhd.py SPY 2024-01-01 # -> SPY.US -uv run scripts/fetch_eodhd.py IMEU.LSE 2024-01-01 # UCITS on London -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 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 deleted file mode 100644 index 6b75c6c0..00000000 --- a/claude/skills/quant/market-datasets/references/ticker_formats.md +++ /dev/null @@ -1,441 +0,0 @@ -# Ticker Format Reference - -Comprehensive guide to ticker symbol formats across all supported data sources. - -## Format Conventions by Source - -### EODHD - -**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.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) -``` - -**Indices**: `.INDX` -``` -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 -``` - -**FX, metals, crypto** -``` -USDPLN.FOREX # USD/PLN (PLN per 1 USD) -EURPLN.FOREX -XAUUSD.FOREX # gold spot (GC=F is not on EODHD) -BTC-USD.CC # crypto -``` - -**Other exchanges** -``` -SPY.US # US ETFs/stocks (bare ticker -> .US) -IMEU.LSE # UCITS on London (Yahoo .L -> .LSE) -``` - -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). - ---- - -### NBP API - -**Currency Codes**: 3-letter ISO codes (uppercase) -``` -USD # US Dollar -EUR # Euro -GBP # British Pound -CHF # Swiss Franc -JPY # Japanese Yen -CAD # Canadian Dollar -AUD # Australian Dollar -SEK # Swedish Krona -NOK # Norwegian Krone -DKK # Danish Krone -CZK # Czech Koruna -HUF # Hungarian Forint -``` - -**Important Notes**: -- Must be uppercase -- Only single currencies supported (not pairs like USD/EUR) -- All rates are quoted against PLN -- Limited to currencies traded at NBP - ---- - -### Yahoo Finance - -**US Stocks**: Uppercase, no suffix -``` -AAPL # Apple Inc. -MSFT # Microsoft Corporation -GOOGL # Alphabet Inc. (Class A) -AMZN # Amazon.com Inc. -TSLA # Tesla Inc. -META # Meta Platforms Inc. -NVDA # NVIDIA Corporation -``` - -**Polish Stocks**: Uppercase + `.WA` (Warsaw) suffix -``` -PKO.WA # PKO Bank Polski -CDR.WA # CD Projekt -PZU.WA # PZU -PKN.WA # PKN Orlen -KGH.WA # KGHM -PGE.WA # PGE -LPP.WA # LPP -``` - -**International Stocks**: Ticker + market suffix -``` -ASML.AS # ASML (Amsterdam) -VOW3.DE # Volkswagen (Frankfurt) -BP.L # BP (London) -7203.T # Toyota (Tokyo) -``` - -**Indices**: With caret prefix -``` -^GSPC # S&P 500 -^IXIC # NASDAQ Composite -^DJI # Dow Jones Industrial Average -^FTSE # FTSE 100 -^GDAXI # DAX -^N225 # Nikkei 225 -``` - -**ETFs**: Standard tickers -``` -SPY # SPDR S&P 500 ETF -QQQ # Invesco QQQ Trust -IWM # iShares Russell 2000 ETF -EEM # iShares MSCI Emerging Markets ETF -``` - -**Market Suffixes**: -- `.WA` - Warsaw Stock Exchange (Poland) -- `.L` - London Stock Exchange (UK) -- `.DE` - Frankfurt Stock Exchange (Germany) -- `.PA` - Euronext Paris (France) -- `.AS` - Euronext Amsterdam (Netherlands) -- `.T` - Tokyo Stock Exchange (Japan) -- `.HK` - Hong Kong Stock Exchange - ---- - -### FRED - -**Economic Indicators**: Short uppercase codes -``` -GDP # Gross Domestic Product -UNRATE # Unemployment Rate -CPIAUCSL # Consumer Price Index -PAYEMS # Total Nonfarm Payrolls -INDPRO # Industrial Production Index -``` - -**Interest Rates**: -``` -DGS10 # 10-Year Treasury Constant Maturity Rate -DGS2 # 2-Year Treasury Constant Maturity Rate -FEDFUNDS # Federal Funds Effective Rate -MORTGAGE30US # 30-Year Fixed Rate Mortgage Average -``` - -**Money Supply**: -``` -M1SL # M1 Money Stock -M2SL # M2 Money Stock -``` - -**Consumer Sentiment**: -``` -UMCSENT # University of Michigan Consumer Sentiment -CSCICP03USM665S # Consumer Confidence Index -``` - -**Search for Series**: https://fred.stlouisfed.org/ - ---- - -## Cross-Source Ticker Mapping - -### Same Company, Different Formats - -| Company | EODHD | Yahoo | Description | -|---------|-------|-------|-------------| -| 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 | EODHD | Yahoo | Description | -|-------|-------|-------|-------------| -| 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 | EODHD | NBP (component) | Yahoo | -|------|-------|-----------------|-------| -| 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` | - ---- - -## Common Ticker Patterns - -### Pattern Recognition for Routing - -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) - -2. **`.WA` / `.WAR` suffix** → EODHD, then Yahoo (same translation) - -3. **3 uppercase letters (USD, EUR, etc.)** → NBP, then Yahoo (`USDPLN=X`) - -4. **6 uppercase letters** → currency pair → `…PLN`: NBP, then Yahoo; otherwise Yahoo (`EURUSD=X`) - -5. **Short uppercase (2-10 chars)** → could be a FRED series → FRED (when keyed) - -6. **Starts with ^** → index → Yahoo - -7. **Uppercase 1-5 letters** → likely US stock → Yahoo, then Tiingo / FinancialData - -8. **Other `.XX` suffix** → international stock → Yahoo (`.INDX` → EODHD) - ---- - -## Ticker Lookup Resources - -### Polish Market - -- **GPW (Warsaw Stock Exchange)**: https://www.gpw.pl/spolki -- **EODHD exchange symbol list**: `GET https://eodhd.com/api/exchange-symbol-list/WAR?api_token=KEY&fmt=json` - -### US Market - -- **NASDAQ**: https://www.nasdaq.com/market-activity/stocks/screener -- **NYSE**: https://www.nyse.com/listings_directory/stock -- **Yahoo Finance**: https://finance.yahoo.com/lookup - -### FRED Series - -- **FRED Search**: https://fred.stlouisfed.org/ -- Search by keyword or browse categories -- Series ID shown in URL and metadata - ---- - -## Special Cases & Gotchas - -### Polish Stocks: EODHD vs Yahoo - -**Problem**: Same company, different suffixes - -**Solution**: -- For EODHD: uppercase + `.WAR` (`PKO.WAR`) -- For Yahoo: uppercase + `.WA` (`PKO.WA`) -- Unified fetcher translates automatically - -### Currency Pairs: Direction Matters - -**NBP API**: Always quotes **foreign currency per 1 PLN** -- `USD` from NBP = How many USD per PLN -- Returns mid rate, bid/ask for table C - -**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` (no WSE indices) - -**Without caret**: -- EODHD: `GSPC.INDX`, `WIG20.INDX` (`^X` → `X.INDX` via `eodhd_symbol`) - -### Class Shares - -**Google/Alphabet**: -- `GOOGL` - Class A shares (voting rights) -- `GOOG` - Class C shares (no voting rights) - -**Berkshire Hathaway**: -- `BRK.A` - Class A shares (~$500,000/share) -- `BRK.B` - Class B shares (~$333/share) - ---- - -## Ticker Validation - -### Valid Formats by Source - -**EODHD**: -```python -# Valid -'PKO.WAR' # GPW listing -'WIG20.INDX' # Index -'USDPLN.FOREX' # FX pair - -# Invalid -'PKO.WA' # Yahoo suffix — eodhd_symbol converts it to .WAR -'GC=F' # Yahoo futures code, not on EODHD (use XAUUSD.FOREX) -``` - -**Yahoo**: -```python -# Valid -'AAPL' # US stock -'PKO.WA' # Polish stock with market suffix -'^GSPC' # Index with caret - -# Invalid -'pko' # Ambiguous without .WA -``` - -**NBP**: -```python -# Valid -'USD' # 3-letter ISO code, uppercase -'EUR' -'GBP' - -# Invalid -'usd' # Must be uppercase -'USDPLN' # Pairs not supported (single currencies only) -``` - -**FRED**: -```python -# Valid -'GDP' # Exact series ID -'UNRATE' -'CPIAUCSL' - -# Invalid -'gdp' # Case sensitive -'Unemployment' # Use series ID, not name -``` - ---- - -## Ticker Normalization - -The unified fetcher automatically normalizes tickers: - -```python -# Automatic normalization examples - -# Polish stock name → per-source suffix -'pko' → 'PKO.WAR' (EODHD) / 'PKO.WA' (Yahoo) - -# US stock → Uppercase for Yahoo -'aapl' → 'AAPL' (when routed to Yahoo) - -# PLN pair → NBP currency / Yahoo pair -'USDPLN' → 'USD' (NBP) / 'USDPLN=X' (Yahoo) - -# Currency code → Uppercase for NBP -'usd' → 'USD' (when routed to NBP) -``` - ---- - -## ISIN Codes (Yahoo Direct API) - -The Yahoo Direct API (`fetch_yahoo_direct.py`) supports automatic ISIN-to-ticker conversion. - -**ISIN Format**: 12 characters - 2-letter country code + 9 alphanumeric + 1 check digit - -### Common Polish ISINs - -| ISIN | Yahoo Ticker | Company | -|------|--------------|---------| -| `PLPKO0000016` | `PKO.WA` | PKO Bank Polski | -| `PLXTRDM00011` | `XTB.WA` | XTB | -| `PLCCC0000016` | `CCC.WA` | CCC | -| `PLBSK0000017` | `ING.WA` | ING Bank Slaski | -| `PLKGHM000017` | `KGH.WA` | KGHM | -| `PLSOFTB00016` | `ACP.WA` | Asseco Poland | -| `PLINTCS00010` | `CAR.WA` | Inter Cars | -| `PLLVTSF00010` | `TXT.WA` | Text (LiveChat) | -| `PLJSW0000015` | `JSW.WA` | JSW | - -### Common US ISINs - -| ISIN | Yahoo Ticker | Company | -|------|--------------|---------| -| `US0378331005` | `AAPL` | Apple | -| `US5949181045` | `MSFT` | Microsoft | -| `US02079K3059` | `GOOGL` | Alphabet | -| `US0231351067` | `AMZN` | Amazon | -| `US88160R1014` | `TSLA` | Tesla | - -### Usage with Direct API - -```python -from fetch_yahoo_direct import YahooDirectFetcher, fetch_by_isin - -# Single ISIN lookup -fetcher = YahooDirectFetcher() -ticker = fetcher.isin_to_ticker('PLXTRDM00011') # Returns 'XTB.WA' - -# Batch ISIN fetching -isins = ['PLXTRDM00011', 'US0378331005'] -prices, dividends, splits, mapping = fetch_by_isin( - isins, - start_date='2024-01-01', - end_date='2025-01-01' -) -``` - -### Notes on ISIN Resolution - -- Yahoo search API matches ISINs to primary exchange listing -- Some ISINs may map to alternative exchanges (e.g., `.SG` for Stuttgart) -- Polish stocks typically resolve to `.WA` (Warsaw) suffix -- If `.SG` ticker returns no data, manually use `.WA` suffix - ---- - -## Quick Reference Cheat Sheet - -| You Want | Source | Format Example | Notes | -|----------|--------|----------------|-------| -| 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 | NBP or Yahoo | `USD` or `USDPLN=X` | NBP=currency, Yahoo=pair | -| US GDP | FRED | `GDP` | Exact series ID | -| 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` | diff --git a/claude/skills/quant/market-datasets/references/usage_patterns.md b/claude/skills/quant/market-datasets/references/usage_patterns.md deleted file mode 100644 index f8fdfbab..00000000 --- a/claude/skills/quant/market-datasets/references/usage_patterns.md +++ /dev/null @@ -1,186 +0,0 @@ -# Usage Patterns - -Complete code examples for all data fetching patterns. - -## Pattern 1: Simple Data Fetch (Auto-Routing) - -```python -from fetch_unified import fetch_market_data - -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') # 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 -``` - -## Pattern 2: Force Specific Source - -```python -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') -df = fetch_market_data('BTC/USDT', source='ccxt', timeframe='1h') -df = fetch_market_data('ETH/USD', source='ccxt', crypto_exchange='kraken') -``` - -## Pattern 3: Multi-Source Comparison - -```python -from fetch_unified import UnifiedMarketDataFetcher - -fetcher = UnifiedMarketDataFetcher() -comparison = fetcher.compare_sources( - ticker='PKO.WA', sources=['eodhd', 'yahoo'], - start_date='2024-01-01', end_date='2024-01-31' -) - -for source, df in comparison.items(): - if df is not None: - print(f"{source}: {len(df)} rows, avg close: {df['Close'].mean():.2f}") -``` - -## Pattern 4: Direct Source Usage - -```python -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') - -from fetch_yahoo import fetch_yahoo -df = fetch_yahoo('AAPL', start_date='2024-01-01', interval='1d') - -from fetch_fred import fetch_fred -df = fetch_fred('GDP', start_date='2020-01-01', api_key='your_key') -``` - -## Pattern 5: Fetch by ISIN (Yahoo Direct API) - -```python -from fetch_yahoo_direct import fetch_by_isin, YahooDirectFetcher - -# Multiple ISINs - returns prices, dividends, splits, and mapping -isins = ['PLXTRDM00011', 'US0378331005'] # XTB, Apple -prices, dividends, splits, mapping = fetch_by_isin( - isins, start_date='2024-01-01', end_date='2025-01-01' -) - -# Access by ISIN -xtb_prices = prices['PLXTRDM00011'] - -# Single ticker with direct API (bypasses yfinance rate limiting) -fetcher = YahooDirectFetcher() -prices_df, divs_df, splits_df = fetcher.fetch('XTB.WA', '2024-01-01', '2025-01-01') - -# ISIN to ticker lookup -ticker = fetcher.isin_to_ticker('PLXTRDM00011') # Returns 'XTB.WA' -``` - -## Pattern 6: Save ISIN Data to Files - -```python -from fetch_yahoo_direct import save_isin_data - -save_isin_data( - ['PLXTRDM00011', 'PLCCC0000016', 'PLBSK0000017'], - output_dir='data/prices/yfinance', - start_date='2024-11-01', end_date='2026-01-08' -) -# Creates: prices.xlsx, dividends.xlsx, splits.xlsx, isin_ticker_mapping.xlsx -``` - -## Pattern 7: TickerRegistry for ISIN/Ticker Conversion - -```python -from ticker_registry import TickerRegistry, isin_to_yahoo - -registry = TickerRegistry() - -# Lookup by any identifier -security = registry.get_security('PLXTRDM00011') # By ISIN -security = registry.get_security('XTB.WA') # By Yahoo ticker - -# Access properties -print(security.name) # 'XTB' -print(security.isin) # 'PLXTRDM00011' -print(security.get_ticker('yahoo')) # 'XTB.WA' - -# Convert between formats -yahoo = registry.convert_ticker('PLXTRDM00011', to_source='yahoo') # 'XTB.WA' - -# Convenience functions -yahoo = isin_to_yahoo('PLXTRDM00011') # 'XTB.WA' -``` - -## Pattern 8: Fetch by ISIN with Unified Fetcher - -```python -from fetch_unified import fetch_market_data - -df = fetch_market_data('PLXTRDM00011', start_date='2024-01-01') # Auto-resolve -df = fetch_market_data('idx_WIG20', start_date='2024-01-01') # By uid -df = fetch_market_data('PLXTRDM00011', source='yahoo', start_date='2024-01-01') # Force source -``` - -## Pattern 9: Auto-Discover Missing Yahoo Tickers - -```python -from ticker_registry import TickerRegistry - -registry = TickerRegistry() -discovered = registry.discover_missing_yahoo_tickers(['US0378331005', 'GB0002634946']) -# {'US0378331005': 'AAPL', 'GB0002634946': 'BA.L'} - -all_discovered = registry.discover_missing_yahoo_tickers() # All missing -``` - -## Pattern 10: Adding New Securities to Registry - -```python -from ticker_registry import TickerRegistry, Security -from datetime import datetime - -registry = TickerRegistry() - -security = Security( - uid='isin_GB0002634946', isin='GB0002634946', name='BAE Systems', - instrument_type='equity', country='GB', exchange='LSE', - tickers={'yahoo': 'BA.L'}, - mapping_source='manual', last_updated=datetime.now() -) -registry.register_security(security) -registry.add_ticker_mapping('PLXTRDM00011', 'bloomberg', 'XTB PW Equity') -registry.save() -``` - -## Date Format Handling - -All fetchers accept flexible date formats: -- `'2024-01-01'` (YYYY-MM-DD) -- `'20240101'` (YYYYMMDD) -- `datetime` / `date` / `pd.Timestamp` objects - -## Troubleshooting - -### "No module named 'yfinance'" -```bash -pip install yfinance -``` - -### "FRED API key required" -```bash -export FRED_API_KEY="your_key" -``` - -### "No data available for ticker" -1. Check ticker format (see ticker_formats.md) -2. Try different source -3. Verify date range is valid - -### Slow Performance -1. Enable caching (default) -2. Reduce date range -3. Batch requests with fetcher instance diff --git a/claude/skills/quant/market-datasets/scripts/fetch_ccxt.py b/claude/skills/quant/market-datasets/scripts/fetch_ccxt.py deleted file mode 100644 index 630ef8b8..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_ccxt.py +++ /dev/null @@ -1,400 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "ccxt>=4.0", -# ] -# /// -""" -CCXT crypto data fetcher. - -Downloads historical cryptocurrency OHLCV data from multiple exchanges -using the CCXT library (CryptoCurrency eXchange Trading Library). - -Supported exchanges: Binance, Kraken, Coinbase, and 100+ more. -Free tier: Unlimited historical data, no API key required for public data. - -Usage: - uv run fetch_ccxt.py BTC/USDT 2024-01-01 2024-12-31 - uv run fetch_ccxt.py ETH/USD 2024-01-01 --exchange kraken - uv run fetch_ccxt.py # Run self-tests -""" - -import pandas as pd -from typing import Optional, List, Literal -from datetime import datetime, timedelta - -try: - import ccxt - CCXT_AVAILABLE = True -except ImportError: - CCXT_AVAILABLE = False - print("[CCXT] Warning: ccxt not installed. Run: pip install ccxt") - -from utils import ( - get_cache_manager, - get_rate_limiter, - normalize_date, - normalize_date_display, - create_identifier, - handle_api_error -) - - -# Common exchange aliases -EXCHANGE_ALIASES = { - 'binance': 'binance', - 'kraken': 'kraken', - 'coinbase': 'coinbasepro', - 'coinbasepro': 'coinbasepro', - 'kucoin': 'kucoin', - 'bybit': 'bybit', - 'okx': 'okx', - 'okex': 'okx', - 'bitfinex': 'bitfinex', - 'huobi': 'huobi', - 'gate': 'gateio', - 'gateio': 'gateio', -} - -# Timeframe mapping -TIMEFRAME_MAP = { - '1m': '1m', - '5m': '5m', - '15m': '15m', - '30m': '30m', - '1h': '1h', - '4h': '4h', - '1d': '1d', - 'd': '1d', - 'daily': '1d', - '1w': '1w', - 'w': '1w', - 'weekly': '1w', -} - - -class CCXTFetcher: - """Fetcher for cryptocurrency data via CCXT.""" - - def __init__(self, exchange: str = 'binance', use_cache: bool = True, - cache_hours: int = 24): - """ - Initialize CCXT fetcher. - - Args: - exchange: Exchange name (binance, kraken, coinbase, etc.) - use_cache: Whether to use caching - cache_hours: Cache validity in hours - """ - if not CCXT_AVAILABLE: - raise ImportError("ccxt package not available. Install with: pip install ccxt") - - # Resolve exchange alias - exchange_id = EXCHANGE_ALIASES.get(exchange.lower(), exchange.lower()) - - if not hasattr(ccxt, exchange_id): - raise ValueError(f"Exchange not supported: {exchange}") - - self.exchange_id = exchange_id - self.exchange = getattr(ccxt, exchange_id)({ - 'enableRateLimit': True, # Built-in rate limiting - }) - - self.use_cache = use_cache - self.cache_hours = cache_hours - self.cache = get_cache_manager() - self.rate_limiter = get_rate_limiter() - - def fetch(self, symbol: str, start_date: Optional[str] = None, - end_date: Optional[str] = None, timeframe: str = '1d', - limit: int = 1000) -> pd.DataFrame: - """ - Fetch OHLCV data from exchange. - - Args: - symbol: Trading pair (e.g., 'BTC/USDT', 'ETH/USD', 'BTC/EUR') - start_date: Start date (YYYY-MM-DD or YYYYMMDD) - end_date: End date (YYYY-MM-DD or YYYYMMDD) - timeframe: Candle timeframe ('1m', '5m', '1h', '1d', '1w') - limit: Max candles per request (exchange dependent) - - Returns: - DataFrame with columns: Date, Open, High, Low, Close, Volume - - Raises: - ValueError: If symbol invalid or no data returned - """ - # Normalize symbol format - symbol = self._normalize_symbol(symbol) - timeframe = TIMEFRAME_MAP.get(timeframe, timeframe) - - # Verify symbol exists on exchange - if not self.exchange.has['fetchOHLCV']: - raise ValueError(f"Exchange {self.exchange_id} doesn't support OHLCV data") - - # 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( - f"{self.exchange_id}_{symbol.replace('/', '_')}", - start_norm, end_norm, timeframe - ) - - # Try cache first - if self.use_cache: - cached = self.cache.get('ccxt', cache_id, max_age_hours=self.cache_hours) - if cached is not None: - print(f"[CCXT] Using cached data for {symbol} from {self.exchange_id}") - return cached - - try: - # Convert dates to timestamps - since = None - if start_date: - start_dt = pd.Timestamp(normalize_date_display(start_date)) - since = int(start_dt.timestamp() * 1000) - - end_ts = None - if end_date: - end_dt = pd.Timestamp(normalize_date_display(end_date)) - end_ts = int(end_dt.timestamp() * 1000) - - # Fetch data in batches (some exchanges have limits) - all_ohlcv = [] - current_since = since - - print(f"[CCXT] Fetching {symbol} from {self.exchange_id} ({timeframe})") - - while True: - self.rate_limiter.wait('ccxt') - - ohlcv = self.exchange.fetch_ohlcv( - symbol, - timeframe=timeframe, - since=current_since, - limit=limit - ) - - if not ohlcv: - break - - all_ohlcv.extend(ohlcv) - - # Check if we've reached the end date - last_timestamp = ohlcv[-1][0] - if end_ts and last_timestamp >= end_ts: - break - - # Check if we got fewer than requested (end of data) - if len(ohlcv) < limit: - break - - # Move to next batch - current_since = last_timestamp + 1 - - # Safety limit to prevent infinite loops - if len(all_ohlcv) > 100000: - print(f"[CCXT] Warning: Reached 100k candles limit") - break - - if not all_ohlcv: - raise ValueError(f"No data returned for {symbol}") - - # Convert to DataFrame - df = pd.DataFrame(all_ohlcv, columns=['Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume']) - - # Convert timestamp to datetime - df['Date'] = pd.to_datetime(df['Timestamp'], unit='ms') - df.drop('Timestamp', axis=1, inplace=True) - - # Filter by end date if specified - if end_date: - end_dt = pd.Timestamp(normalize_date_display(end_date)) - df = df[df['Date'] <= end_dt] - - # Reorder columns - df = df[['Date', 'Open', 'High', 'Low', 'Close', 'Volume']] - - # Sort and deduplicate - df.sort_values('Date', inplace=True) - df.drop_duplicates(subset=['Date'], keep='last', inplace=True) - df.reset_index(drop=True, inplace=True) - - print(f"[CCXT] Retrieved {len(df)} candles") - - # Cache result - if self.use_cache: - self.cache.set('ccxt', cache_id, df) - - return df - - except Exception as e: - handle_api_error('CCXT', e, symbol) - raise - - def _normalize_symbol(self, symbol: str) -> str: - """ - Normalize symbol format for CCXT. - - Args: - symbol: Raw symbol - - Returns: - Normalized symbol (e.g., 'BTC/USDT') - """ - symbol = symbol.upper() - - # Already in correct format - if '/' in symbol: - return symbol - - # Common patterns without slash - # BTCUSDT -> BTC/USDT - # ETHBTC -> ETH/BTC - quote_currencies = ['USDT', 'USD', 'EUR', 'GBP', 'BTC', 'ETH', 'USDC', 'BUSD', 'PLN'] - - for quote in quote_currencies: - if symbol.endswith(quote): - base = symbol[:-len(quote)] - if base: - return f"{base}/{quote}" - - # If no pattern matched, return as-is - return symbol - - def list_symbols(self) -> List[str]: - """ - List available trading pairs on the exchange. - - Returns: - List of symbol strings - """ - self.exchange.load_markets() - return list(self.exchange.symbols) - - @staticmethod - def list_exchanges() -> List[str]: - """ - List supported exchanges. - - Returns: - List of exchange IDs - """ - if CCXT_AVAILABLE: - return ccxt.exchanges - return [] - - def get_ticker_info(self, symbol: str) -> dict: - """ - Get current ticker info (price, volume, etc.). - - Args: - symbol: Trading pair - - Returns: - Dictionary with ticker info - """ - symbol = self._normalize_symbol(symbol) - try: - self.rate_limiter.wait('ccxt') - return self.exchange.fetch_ticker(symbol) - except Exception as e: - handle_api_error('CCXT', e, symbol) - return {} - - -def fetch_crypto(symbol: str, start_date: Optional[str] = None, - end_date: Optional[str] = None, exchange: str = 'binance', - timeframe: str = '1d', use_cache: bool = True) -> pd.DataFrame: - """ - Convenience function to fetch crypto data. - - Args: - symbol: Trading pair (e.g., 'BTC/USDT', 'ETHUSDT', 'ETH/USD') - start_date: Start date - end_date: End date - exchange: Exchange name (binance, kraken, coinbase, etc.) - timeframe: Candle timeframe ('1m', '1h', '1d', '1w') - use_cache: Whether to use caching - - Returns: - DataFrame with OHLCV data - """ - fetcher = CCXTFetcher(exchange=exchange, use_cache=use_cache) - return fetcher.fetch(symbol, start_date, end_date, timeframe) - - -def is_crypto_symbol(symbol: str) -> bool: - """ - Check if a symbol looks like a crypto trading pair. - - Used by unified fetcher for routing. - - Args: - symbol: Symbol to check - - Returns: - True if likely a crypto symbol - """ - symbol_upper = symbol.upper() - - # Contains slash (BTC/USDT) - if '/' in symbol: - return True - - # Ends with common crypto quote currencies - crypto_quotes = ['USDT', 'USD', 'USDC', 'BUSD', 'BTC', 'ETH'] - for quote in crypto_quotes: - if symbol_upper.endswith(quote) and len(symbol_upper) > len(quote): - # Check if base is a known crypto - base = symbol_upper[:-len(quote)] - known_cryptos = ['BTC', 'ETH', 'SOL', 'XRP', 'ADA', 'DOGE', 'DOT', 'AVAX', - 'LINK', 'MATIC', 'UNI', 'LTC', 'ATOM', 'NEAR', 'FIL'] - if base in known_cryptos: - return True - - return False - - -if __name__ == '__main__': - # Test examples - if not CCXT_AVAILABLE: - print("ccxt not available. Install with: pip install ccxt") - else: - print("Testing CCXT fetcher...") - - # Test 1: Bitcoin from Binance - print("\n1. Fetching BTC/USDT from Binance (daily):") - try: - df = fetch_crypto('BTC/USDT', start_date='20240101', end_date='20240131') - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 2: Ethereum from Binance (hourly) - print("\n2. Fetching ETH/USDT from Binance (hourly, last 24h):") - try: - start = (datetime.now() - timedelta(days=1)).strftime('%Y%m%d') - df = fetch_crypto('ETH/USDT', start_date=start, timeframe='1h') - print(f" Retrieved {len(df)} rows") - print(df.tail()) - except Exception as e: - print(f" Error: {e}") - - # Test 3: Symbol detection - print("\n3. Testing crypto symbol detection:") - test_symbols = ['BTC/USDT', 'ETHUSDT', 'AAPL', 'pko', 'SOLUSD', 'EUR/USD'] - for sym in test_symbols: - is_crypto = is_crypto_symbol(sym) - print(f" {sym}: {'crypto' if is_crypto else 'not crypto'}") - - # Test 4: Symbol normalization - print("\n4. Testing symbol normalization:") - fetcher = CCXTFetcher('binance') - test_symbols = ['BTCUSDT', 'ETH/USD', 'btcusd', 'SOLETH'] - for sym in test_symbols: - normalized = fetcher._normalize_symbol(sym) - print(f" {sym} -> {normalized}") diff --git a/claude/skills/quant/market-datasets/scripts/fetch_coingecko.py b/claude/skills/quant/market-datasets/scripts/fetch_coingecko.py deleted file mode 100644 index 5030e5f2..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_coingecko.py +++ /dev/null @@ -1,154 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# "python-dotenv>=1.0", -# ] -# /// -""" -CoinGecko fetcher — daily crypto price / market-cap / volume. - -Rounds out the skill's crypto floor alongside CCXT (which gives exchange OHLCV): -CoinGecko is keyed by *coin id* (e.g. ``bitcoin``, ``ethereum``) and is the -right source for market-cap and cross-exchange daily price/volume. - -Free / Demo tier works with no key (rate-limited ~10-30 req/min); a demo key -(`COINGECKO_API_KEY`) raises the limit and is sent as the `x-cg-demo-api-key` -header. - -Usage: - uv run fetch_coingecko.py bitcoin 2024-01-01 2024-12-31 - uv run fetch_coingecko.py ethereum 2024-01-01 - uv run fetch_coingecko.py # self-test -""" - -import os -import sys -from datetime import datetime, timezone -from typing import Optional - -import pandas as pd -import requests - -from utils import ( - create_identifier, - get_cache_manager, - get_rate_limiter, - handle_api_error, - normalize_date, -) - - -class CoinGeckoFetcher: - """Fetcher for CoinGecko daily market data (price / mcap / volume).""" - - BASE_URL = "https://api.coingecko.com/api/v3" - - def __init__( - self, - api_key: Optional[str] = None, - use_cache: bool = True, - cache_hours: int = 24, - ): - self.api_key = api_key or os.environ.get("COINGECKO_API_KEY") - self.use_cache = use_cache - self.cache_hours = cache_hours - self.cache = get_cache_manager() - self.rate_limiter = get_rate_limiter() - - def fetch( - self, - coin_id: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - vs_currency: str = "usd", - ) -> pd.DataFrame: - """Fetch daily history for a CoinGecko coin id. - - Returns a standardized DataFrame: Date, Close, Market_Cap, Volume. - """ - coin_id = coin_id.lower() - cache_id = create_identifier( - f"{coin_id}_{vs_currency}", - normalize_date(start_date) if start_date else None, - normalize_date(end_date) if end_date else None, - "coingecko", - ) - if self.use_cache: - cached = self.cache.get("coingecko", cache_id, max_age_hours=self.cache_hours) - if cached is not None: - print(f"[CoinGecko] Using cached data for {coin_id}") - return cached - - # Range endpoint takes unix seconds; default to a wide window. - start_ts = int( - pd.Timestamp(start_date or "2013-01-01").replace(tzinfo=timezone.utc).timestamp() - ) - end_ts = int( - (pd.Timestamp(end_date) if end_date else pd.Timestamp(datetime.now(timezone.utc))) - .replace(tzinfo=timezone.utc) - .timestamp() - ) - url = f"{self.BASE_URL}/coins/{coin_id}/market_chart/range" - params = {"vs_currency": vs_currency, "from": start_ts, "to": end_ts} - headers = {"x-cg-demo-api-key": self.api_key} if self.api_key else {} - - try: - self.rate_limiter.wait("coingecko") - print(f"[CoinGecko] Fetching {coin_id} ({vs_currency})") - r = requests.get(url, params=params, headers=headers, timeout=30) - if r.status_code == 404: - raise ValueError(f"Unknown coin id: {coin_id}") - if r.status_code == 429: - raise ValueError("CoinGecko rate limit exceeded. Wait and retry.") - r.raise_for_status() - data = r.json() - prices = data.get("prices", []) - if not prices: - raise ValueError(f"No data returned for coin id: {coin_id}") - - df = pd.DataFrame(prices, columns=["ts", "Close"]) - df["Date"] = pd.to_datetime(df["ts"], unit="ms").dt.tz_localize(None).dt.normalize() - mcap = dict((int(t), v) for t, v in data.get("market_caps", [])) - vol = dict((int(t), v) for t, v in data.get("total_volumes", [])) - df["Market_Cap"] = df["ts"].map(mcap) - df["Volume"] = df["ts"].map(vol) - df = ( - df.drop(columns=["ts"]) - .drop_duplicates("Date", keep="last") - .sort_values("Date") - .reset_index(drop=True)[["Date", "Close", "Market_Cap", "Volume"]] - ) - - if self.use_cache: - self.cache.set("coingecko", cache_id, df) - return df - except Exception as e: # noqa: BLE001 - handle_api_error("CoinGecko", e, coin_id) - raise - - -def fetch_coingecko( - coin_id: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - api_key: Optional[str] = None, - use_cache: bool = True, -) -> pd.DataFrame: - """Convenience wrapper.""" - return CoinGeckoFetcher(api_key=api_key, use_cache=use_cache).fetch( - coin_id, start_date, end_date - ) - - -if __name__ == "__main__": - if len(sys.argv) > 1: - tk = sys.argv[1] - sd = sys.argv[2] if len(sys.argv) > 2 else None - ed = sys.argv[3] if len(sys.argv) > 3 else None - print(fetch_coingecko(tk, sd, ed).tail()) - else: - df = fetch_coingecko("bitcoin", "2026-06-01") - print(f" OK bitcoin rows={len(df)} last={df['Date'].max().date()}") diff --git a/claude/skills/quant/market-datasets/scripts/fetch_eodhd.py b/claude/skills/quant/market-datasets/scripts/fetch_eodhd.py deleted file mode 100644 index 62634171..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_eodhd.py +++ /dev/null @@ -1,232 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# "python-dotenv>=1.0", -# ] -# /// -""" -EODHD (EOD Historical Data) fetcher. - -Best for UCITS/ETF and global multi-exchange coverage keyed by exchange-suffixed -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 -indices (.INDX), fresher than yfinance. - -Tiers: -- free: ~1yr history, 20 calls/day (validation only) -- paid (EOD Historical Data ~$20/mo): full history, 100k calls/day - -Requires API key: https://eodhd.com/ -API key via: -1. .env file: EODHD_API_KEY=your_key -2. Environment variable: EODHD_API_KEY -3. Direct parameter - -Usage: - uv run fetch_eodhd.py SPY 2024-01-01 2024-12-31 # -> SPY.US - uv run fetch_eodhd.py IMEU.LSE 2024-01-01 # explicit exchange - uv run fetch_eodhd.py ETFBW20TR.WAR 2024-01-01 # GPW Beta ETF - uv run fetch_eodhd.py ^BCOM 2024-01-01 # index -> BCOM.INDX - uv run fetch_eodhd.py # self-tests (needs key) -""" - -import os -import sys -from datetime import date -from typing import Optional - -import pandas as pd -import requests - -from utils import ( - create_identifier, - get_cache_manager, - get_rate_limiter, - handle_api_error, - normalize_date, - normalize_date_display, - standardize_dataframe, -) - - -def eodhd_symbol(ticker: str) -> str: - """Map a bare/suffixed ticker to an EODHD symbol. - - - Already exchange-suffixed (contains '.') -> passthrough (e.g. IMEU.LSE) - - Leading '^' index -> NAME.INDX (e.g. ^BCOM -> BCOM.INDX) - - Yahoo Warsaw suffix '.WA' -> '.WAR' - - Yahoo London suffix '.L' -> '.LSE' - - bare ticker -> '.US' - """ - t = ticker.strip() - if t.startswith("^"): - return t[1:] + ".INDX" - if t.endswith(".WA"): - return t[:-3] + ".WAR" - if t.endswith(".L"): - return t[:-2] + ".LSE" - if "." in t: - return t # already exchange-suffixed (e.g. IMEU.LSE, ETFBW20TR.WAR) - return t + ".US" - - -class EODHDFetcher: - """Fetcher for EODHD (eodhd.com) end-of-day market data.""" - - BASE_URL = "https://eodhd.com/api" - - def __init__( - self, - api_key: Optional[str] = None, - use_cache: bool = True, - cache_hours: int = 24, - ): - self.api_key = api_key or os.environ.get("EODHD_API_KEY") - if not self.api_key: - raise ValueError( - "EODHD API key required. Set EODHD_API_KEY environment variable " - "or pass api_key parameter. Get a key at: https://eodhd.com/" - ) - 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, - ) -> pd.DataFrame: - """Fetch EOD data from EODHD. - - Args: - ticker: bare or exchange-suffixed symbol (see ``eodhd_symbol``) - start_date: YYYY-MM-DD or YYYYMMDD - end_date: YYYY-MM-DD or YYYYMMDD - - Returns: - Standardized DataFrame: Date, Open, High, Low, Close, Volume, Adj_Close - """ - symbol = eodhd_symbol(ticker) - - 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(symbol, start_norm, end_norm, "eodhd") - - if self.use_cache: - cached = self.cache.get("eodhd", cache_id, max_age_hours=self.cache_hours) - if cached is not None: - print(f"[EODHD] Using cached data for {symbol}") - return cached - - url = f"{self.BASE_URL}/eod/{symbol}" - params = {"api_token": self.api_key, "fmt": "json", "period": "d"} - if start_date: - params["from"] = normalize_date_display(start_date) - if end_date: - params["to"] = normalize_date_display(end_date) - - try: - self.rate_limiter.wait("eodhd") - print(f"[EODHD] Fetching {symbol}") - response = requests.get(url, params=params, timeout=30) - - if response.status_code == 401: - raise ValueError("Invalid EODHD API key") - if response.status_code == 403: - raise ValueError( - f"EODHD forbidden for {symbol} — symbol not in your plan " - "(free tier is limited; a few US symbols only)" - ) - if response.status_code == 429: - raise ValueError("EODHD daily rate limit exceeded. Wait and retry.") - response.raise_for_status() - - data = response.json() - if not isinstance(data, list) or not data: - raise ValueError(f"No data returned for symbol: {symbol}") - - df = pd.DataFrame(data) - df.rename( - columns={ - "date": "Date", - "open": "Open", - "high": "High", - "low": "Low", - "close": "Close", - "volume": "Volume", - "adjusted_close": "Adj_Close", - }, - inplace=True, - ) - df["Date"] = pd.to_datetime(df["Date"]).dt.tz_localize(None) - df.sort_values("Date", inplace=True) - df.reset_index(drop=True, inplace=True) - df = standardize_dataframe(df, "eodhd") - - if self.use_cache: - self.cache.set("eodhd", cache_id, df) - return df - - except Exception as e: - handle_api_error("EODHD", e, symbol) - raise - - def fetch_multiple( - self, - tickers: list, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - ) -> dict: - """Fetch multiple tickers -> {ticker: DataFrame}.""" - results = {} - for ticker in tickers: - try: - results[ticker] = self.fetch(ticker, start_date, end_date) - except Exception as e: - print(f"[EODHD] Skipping {ticker}: {e}") - return results - - -def fetch_eodhd( - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - api_key: Optional[str] = None, - use_cache: bool = True, -) -> pd.DataFrame: - """Convenience function to fetch EOD data from EODHD.""" - return EODHDFetcher(api_key=api_key, use_cache=use_cache).fetch(ticker, start_date, end_date) - - -if __name__ == "__main__": - if not os.environ.get("EODHD_API_KEY"): - print("Set EODHD_API_KEY to test. Get a key at: https://eodhd.com/") - sys.exit(1) - - if len(sys.argv) > 1: - tk = sys.argv[1] - sd = sys.argv[2] if len(sys.argv) > 2 else None - ed = sys.argv[3] if len(sys.argv) > 3 else None - out = fetch_eodhd(tk, sd, ed) - print(out.tail()) - else: - # self-tests: one symbol per exchange family - for tk in ["SPY", "IMEU.LSE", "ETFBW20TR.WAR", "^BCOM"]: - try: - df = fetch_eodhd(tk, "2026-06-01") - print( - f" OK {tk:<16} -> {eodhd_symbol(tk):<16} rows={len(df)} last={df['Date'].max().date()}" - ) - except Exception as e: # noqa: BLE001 - print(f" FAIL {tk}: {e}") diff --git a/claude/skills/quant/market-datasets/scripts/fetch_financialdata.py b/claude/skills/quant/market-datasets/scripts/fetch_financialdata.py deleted file mode 100644 index 2aa8051a..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_financialdata.py +++ /dev/null @@ -1,666 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# "python-dotenv>=1.0", -# ] -# /// -""" -FinancialData.Net data fetcher. - -Downloads market data from FinancialData.Net API (https://financialdata.net). -Covers US/international stocks, ETFs, commodities, crypto, forex, options, -futures, fundamentals, financial statements, ratios, and more. - -Requires API key: https://financialdata.net -Free tier available with basic endpoints; Standard/Premium for advanced data. - -API key can be provided via: -1. .env file: FINANCIAL_DATA_API_KEY=your_key -2. Environment variable: FINANCIAL_DATA_API_KEY -3. Direct parameter - -Usage: - uv run fetch_financialdata.py AAPL 2024-01-01 2024-12-31 - uv run fetch_financialdata.py MSFT 2024-01-01 - uv run fetch_financialdata.py # Run self-tests (requires API key) -""" - -import os -import pandas as pd -import requests -from typing import Optional, Any - -from utils import ( - get_cache_manager, - get_rate_limiter, - normalize_date, - normalize_date_display, - create_identifier, - handle_api_error, -) - - -class FinancialDataFetcher: - """Fetcher for FinancialData.Net market data.""" - - BASE_URL = "https://financialdata.net/api/v1" - - # Endpoint definitions: (path, default_limit, tier) - ENDPOINTS = { - # Symbol lists (Free) - "stock-symbols": ("stock-symbols", 500), - "international-stock-symbols": ("international-stock-symbols", 500), - "etf-symbols": ("etf-symbols", 500), - "commodity-symbols": ("commodity-symbols", None), - "otc-symbols": ("otc-symbols", 500), - "index-symbols": ("index-symbols", None), - "crypto-symbols": ("crypto-symbols", 500), - "forex-symbols": ("forex-symbols", None), - "futures-symbols": ("futures-symbols", 500), - # Market data - "stock-quotes": ("stock-quotes", 300), - "stock-prices": ("stock-prices", 300), - "international-stock-prices": ("international-stock-prices", 300), - "minute-prices": ("minute-prices", 300), - "latest-prices": ("latest-prices", 300), - "commodity-prices": ("commodity-prices", 300), - "otc-prices": ("otc-prices", 300), - "otc-volume": ("otc-volume", None), - # Indexes - "index-quotes": ("index-quotes", 300), - "index-prices": ("index-prices", 300), - "index-constituents": ("index-constituents", 300), - # Derivatives - "option-chain": ("option-chain", 300), - "option-prices": ("option-prices", 300), - "option-greeks": ("option-greeks", 300), - "futures-prices": ("futures-prices", 300), - # Crypto - "crypto-information": ("crypto-information", None), - "crypto-quotes": ("crypto-quotes", 300), - "crypto-prices": ("crypto-prices", 300), - "crypto-minute-prices": ("crypto-minute-prices", 300), - # Forex - "forex-quotes": ("forex-quotes", 300), - "forex-prices": ("forex-prices", 300), - "forex-minute-prices": ("forex-minute-prices", 300), - # Company info - "company-information": ("company-information", None), - "international-company-information": ( - "international-company-information", - None, - ), - "key-metrics": ("key-metrics", None), - "market-cap": ("market-cap", None), - "employee-count": ("employee-count", None), - "executive-compensation": ("executive-compensation", 100), - "securities-information": ("securities-information", None), - # Financial statements - "income-statements": ("income-statements", 50), - "balance-sheet-statements": ("balance-sheet-statements", 50), - "cash-flow-statements": ("cash-flow-statements", 50), - "international-income-statements": ("international-income-statements", 50), - "international-balance-sheet-statements": ( - "international-balance-sheet-statements", - 50, - ), - "international-cash-flow-statements": ( - "international-cash-flow-statements", - 50, - ), - # Financial ratios - "liquidity-ratios": ("liquidity-ratios", 50), - "solvency-ratios": ("solvency-ratios", 50), - "efficiency-ratios": ("efficiency-ratios", 50), - "profitability-ratios": ("profitability-ratios", 50), - "valuation-ratios": ("valuation-ratios", 50), - # News & events - "press-releases": ("press-releases", 1), - "sec-press-releases": ("sec-press-releases", None), - "fed-press-releases": ("fed-press-releases", None), - "earnings-calendar": ("earnings-calendar", None), - "ipo-calendar": ("ipo-calendar", None), - "splits-calendar": ("splits-calendar", None), - "dividends-calendar": ("dividends-calendar", None), - "economic-calendar": ("economic-calendar", None), - # Insider & institutional - "insider-transactions": ("insider-transactions", None), - "proposed-sales": ("proposed-sales", None), - "senate-trading": ("senate-trading", None), - "house-trading": ("house-trading", None), - "institutional-investors": ("institutional-investors", None), - "institutional-holdings": ("institutional-holdings", None), - "institutional-portfolio-statistics": ( - "institutional-portfolio-statistics", - None, - ), - } - - def __init__( - self, - api_key: Optional[str] = None, - use_cache: bool = True, - cache_hours: int = 24, - ): - """ - Initialize FinancialData.Net fetcher. - - Args: - api_key: API key (or set FINANCIAL_DATA_API_KEY env var) - use_cache: Whether to use caching - cache_hours: Cache validity in hours - """ - self.api_key = api_key or os.environ.get("FINANCIAL_DATA_API_KEY") - if not self.api_key: - raise ValueError( - "FinancialData.Net API key required. Set FINANCIAL_DATA_API_KEY " - "environment variable or pass api_key parameter. " - "Get key at: https://financialdata.net" - ) - - self.use_cache = use_cache - self.cache_hours = cache_hours - self.cache = get_cache_manager() - self.rate_limiter = get_rate_limiter() - - def _request( - self, - endpoint: str, - params: Optional[dict] = None, - paginate: bool = False, - ) -> list[dict]: - """ - Make API request with optional auto-pagination. - - Args: - endpoint: API endpoint path (e.g. 'stock-prices') - params: Query parameters (excluding key) - paginate: Whether to auto-paginate through all results - - Returns: - List of result dictionaries - - Raises: - ValueError: If endpoint unknown or API returns error - requests.RequestException: On network failure - """ - if endpoint not in self.ENDPOINTS: - raise ValueError( - f"Unknown endpoint: {endpoint}. " - f"Valid endpoints: {', '.join(sorted(self.ENDPOINTS.keys()))}" - ) - - path, page_limit = self.ENDPOINTS[endpoint] - url = f"{self.BASE_URL}/{path}" - - params = dict(params or {}) - params["key"] = self.api_key - - all_data: list[dict] = [] - offset = 0 - - while True: - if paginate and page_limit and offset > 0: - params["offset"] = offset - - self.rate_limiter.wait("financialdata") - - response = requests.get(url, params=params, timeout=30) - - if response.status_code == 401: - raise ValueError("Invalid FinancialData.Net API key") - if response.status_code == 403: - raise ValueError( - f"Access denied for endpoint '{endpoint}'. " - "Check your subscription tier." - ) - if response.status_code == 429: - raise ValueError( - "FinancialData.Net rate limit exceeded. Wait and retry." - ) - - response.raise_for_status() - - data = response.json() - - if isinstance(data, list): - all_data.extend(data) - elif isinstance(data, dict): - # Some endpoints return a dict wrapper - all_data.append(data) - - # Stop pagination if not requested, no limit, or fewer results than limit - if ( - not paginate - or page_limit is None - or (isinstance(data, list) and len(data) < page_limit) - ): - break - - offset += page_limit - - return all_data - - def fetch( - self, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - endpoint: str = "stock-prices", - paginate: bool = True, - **kwargs, - ) -> pd.DataFrame: - """ - Fetch price data from FinancialData.Net. - - Args: - ticker: Stock/asset identifier (e.g. 'AAPL', 'MSFT') - start_date: Start date (YYYY-MM-DD or YYYYMMDD) - end_date: End date (YYYY-MM-DD or YYYYMMDD) - endpoint: API endpoint to use (default: 'stock-prices') - paginate: Auto-paginate through all results - **kwargs: Additional query parameters - - Returns: - DataFrame with market data - - Raises: - ValueError: If ticker invalid or no data returned - """ - ticker_upper = ticker.upper() - - # Build 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( - f"{ticker_upper}_{endpoint}", start_norm, end_norm, "financialdata" - ) - - # Try cache first - if self.use_cache: - cached = self.cache.get( - "financialdata", cache_id, max_age_hours=self.cache_hours - ) - if cached is not None: - print(f"[FinancialData] Using cached data for {ticker_upper}") - return cached - - # Build params - params: dict[str, Any] = {} - - # Endpoints using 'identifiers' (plural, comma-separated) vs 'identifier' (single) - plural_endpoints = { - "stock-quotes", - "index-quotes", - "crypto-quotes", - "forex-quotes", - } - if endpoint in plural_endpoints: - params["identifiers"] = ticker_upper - else: - params["identifier"] = ticker_upper - - # Date handling for minute-prices and crypto-minute-prices - if endpoint in ("minute-prices", "crypto-minute-prices", "forex-minute-prices"): - if start_date: - params["date"] = normalize_date_display(start_date) - # Period for financial statements and ratios - elif endpoint in ( - "income-statements", - "balance-sheet-statements", - "cash-flow-statements", - "international-income-statements", - "international-balance-sheet-statements", - "international-cash-flow-statements", - "liquidity-ratios", - "solvency-ratios", - "efficiency-ratios", - "profitability-ratios", - "valuation-ratios", - ): - if "period" not in kwargs: - params["period"] = "year" - - # Add extra kwargs as params - params.update(kwargs) - - try: - start_display = ( - normalize_date_display(start_date) if start_date else "earliest" - ) - end_display = normalize_date_display(end_date) if end_date else "latest" - print( - f"[FinancialData] Fetching {ticker_upper} ({endpoint}) " - f"from {start_display} to {end_display}" - ) - - data = self._request(endpoint, params, paginate=paginate) - - if not data: - raise ValueError( - f"No data returned for {ticker_upper} from endpoint '{endpoint}'" - ) - - df = pd.DataFrame(data) - - # Normalize date columns - for col in ("date", "Date"): - if col in df.columns: - df[col] = pd.to_datetime(df[col], errors="coerce") - if df[col].dt.tz is not None: - df[col] = df[col].dt.tz_localize(None) - df.rename(columns={col: "Date"}, inplace=True) - - # Standardize OHLCV column names for price endpoints - price_endpoints = { - "stock-prices", - "international-stock-prices", - "commodity-prices", - "otc-prices", - "index-prices", - "crypto-prices", - "forex-prices", - "futures-prices", - "latest-prices", - "minute-prices", - "crypto-minute-prices", - "forex-minute-prices", - } - if endpoint in price_endpoints: - col_map = { - "open": "Open", - "high": "High", - "low": "Low", - "close": "Close", - "volume": "Volume", - "adjClose": "Adj_Close", - "adj_close": "Adj_Close", - } - df.rename(columns=col_map, inplace=True) - - # Sort by Date if available - if "Date" in df.columns: - df.sort_values("Date", inplace=True) - df.reset_index(drop=True, inplace=True) - - # Cache result - if self.use_cache: - self.cache.set("financialdata", cache_id, df) - - return df - - except Exception as e: - handle_api_error("FinancialData", e, ticker_upper) - raise - - def get_stock_prices( - self, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - ) -> pd.DataFrame: - """Fetch historical stock prices.""" - return self.fetch(ticker, start_date, end_date, endpoint="stock-prices") - - def get_stock_quotes(self, tickers: str) -> pd.DataFrame: - """Fetch real-time stock quotes. Tickers comma-separated (e.g. 'AAPL,MSFT').""" - return self.fetch(tickers, endpoint="stock-quotes", paginate=False) - - def get_international_stock_prices( - self, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - ) -> pd.DataFrame: - """Fetch international stock prices.""" - return self.fetch( - ticker, start_date, end_date, endpoint="international-stock-prices" - ) - - def get_minute_prices(self, ticker: str, trade_date: str) -> pd.DataFrame: - """Fetch intraday minute prices for a specific date.""" - return self.fetch(ticker, start_date=trade_date, endpoint="minute-prices") - - def get_commodity_prices( - self, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - ) -> pd.DataFrame: - """Fetch commodity prices.""" - return self.fetch(ticker, start_date, end_date, endpoint="commodity-prices") - - def get_index_prices( - self, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - ) -> pd.DataFrame: - """Fetch index prices.""" - return self.fetch(ticker, start_date, end_date, endpoint="index-prices") - - def get_crypto_prices( - self, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - ) -> pd.DataFrame: - """Fetch cryptocurrency prices.""" - return self.fetch(ticker, start_date, end_date, endpoint="crypto-prices") - - def get_forex_prices( - self, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - ) -> pd.DataFrame: - """Fetch forex prices.""" - return self.fetch(ticker, start_date, end_date, endpoint="forex-prices") - - def get_option_chain(self, ticker: str) -> pd.DataFrame: - """Fetch option chain for a ticker.""" - return self.fetch(ticker, endpoint="option-chain") - - def get_option_greeks(self, ticker: str) -> pd.DataFrame: - """Fetch option Greeks for a ticker.""" - return self.fetch(ticker, endpoint="option-greeks") - - def get_futures_prices( - self, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - ) -> pd.DataFrame: - """Fetch futures prices.""" - return self.fetch(ticker, start_date, end_date, endpoint="futures-prices") - - def get_company_info(self, ticker: str) -> pd.DataFrame: - """Fetch company information.""" - return self.fetch(ticker, endpoint="company-information", paginate=False) - - def get_key_metrics(self, ticker: str) -> pd.DataFrame: - """Fetch key financial metrics.""" - return self.fetch(ticker, endpoint="key-metrics", paginate=False) - - def get_income_statements(self, ticker: str, period: str = "year") -> pd.DataFrame: - """Fetch income statements (period: 'year' or 'quarter').""" - return self.fetch(ticker, endpoint="income-statements", period=period) - - def get_balance_sheet(self, ticker: str, period: str = "year") -> pd.DataFrame: - """Fetch balance sheet statements (period: 'year' or 'quarter').""" - return self.fetch(ticker, endpoint="balance-sheet-statements", period=period) - - def get_cash_flow(self, ticker: str, period: str = "year") -> pd.DataFrame: - """Fetch cash flow statements (period: 'year' or 'quarter').""" - return self.fetch(ticker, endpoint="cash-flow-statements", period=period) - - def get_financial_ratios( - self, ticker: str, ratio_type: str = "profitability", period: str = "year" - ) -> pd.DataFrame: - """ - Fetch financial ratios. - - Args: - ticker: Stock ticker - ratio_type: One of 'liquidity', 'solvency', 'efficiency', - 'profitability', 'valuation' - period: 'year' or 'quarter' - """ - endpoint = f"{ratio_type}-ratios" - return self.fetch(ticker, endpoint=endpoint, period=period) - - def get_symbols(self, symbol_type: str = "stock") -> pd.DataFrame: - """ - Fetch symbol lists. - - Args: - symbol_type: One of 'stock', 'international-stock', 'etf', - 'commodity', 'otc', 'index', 'crypto', 'forex', 'futures' - """ - endpoint = f"{symbol_type}-symbols" - return self.fetch("", endpoint=endpoint, paginate=True) - - def get_earnings_calendar(self) -> pd.DataFrame: - """Fetch upcoming earnings calendar.""" - return self.fetch("", endpoint="earnings-calendar", paginate=False) - - def get_insider_transactions(self, ticker: str) -> pd.DataFrame: - """Fetch insider transactions for a ticker.""" - return self.fetch(ticker, endpoint="insider-transactions") - - def get_senate_trading(self) -> pd.DataFrame: - """Fetch recent senate trading disclosures.""" - return self.fetch("", endpoint="senate-trading") - - def get_house_trading(self) -> pd.DataFrame: - """Fetch recent house trading disclosures.""" - return self.fetch("", endpoint="house-trading") - - def get_institutional_holders(self, ticker: str) -> pd.DataFrame: - """Fetch institutional holders for a ticker.""" - return self.fetch(ticker, endpoint="institutional-holdings") - - def fetch_multiple( - self, - tickers: list[str], - start_date: Optional[str] = None, - end_date: Optional[str] = None, - endpoint: str = "stock-prices", - ) -> dict[str, pd.DataFrame]: - """ - Fetch data for multiple tickers. - - Args: - tickers: List of ticker symbols - start_date: Start date - end_date: End date - endpoint: API endpoint to use - - Returns: - Dictionary mapping ticker -> DataFrame - """ - results = {} - - for ticker in tickers: - try: - df = self.fetch(ticker, start_date, end_date, endpoint=endpoint) - results[ticker] = df - except Exception as e: - print(f"[FinancialData] Skipping {ticker}: {e}") - continue - - return results - - -def fetch_financialdata( - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - api_key: Optional[str] = None, - use_cache: bool = True, - endpoint: str = "stock-prices", - **kwargs, -) -> pd.DataFrame: - """ - Convenience function to fetch data from FinancialData.Net. - - Args: - ticker: Stock/asset identifier - start_date: Start date - end_date: End date - api_key: API key (or set FINANCIAL_DATA_API_KEY env var) - use_cache: Whether to use caching - endpoint: API endpoint (default: 'stock-prices') - **kwargs: Additional query parameters - - Returns: - DataFrame with market data - """ - fetcher = FinancialDataFetcher(api_key=api_key, use_cache=use_cache) - return fetcher.fetch(ticker, start_date, end_date, endpoint=endpoint, **kwargs) - - -if __name__ == "__main__": - import sys - - api_key = os.environ.get("FINANCIAL_DATA_API_KEY") - if not api_key: - print("Set FINANCIAL_DATA_API_KEY environment variable to test") - print("Get API key at: https://financialdata.net") - sys.exit(1) - - print("Testing FinancialData.Net fetcher...\n") - - # Test 1: Stock prices (Free tier) - print("1. Fetching AAPL stock prices:") - try: - df = fetch_financialdata("AAPL", start_date="20240101", end_date="20240131") - print(f" Retrieved {len(df)} rows") - print(f" Columns: {list(df.columns)}") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 2: Commodity prices (Free tier) - print("\n2. Fetching gold commodity prices:") - try: - df = fetch_financialdata( - "GC", - start_date="20240101", - end_date="20240131", - endpoint="commodity-prices", - ) - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 3: Company information (Standard tier) - print("\n3. Fetching MSFT company info:") - try: - df = fetch_financialdata("MSFT", endpoint="company-information") - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 4: Income statements (Standard tier) - print("\n4. Fetching AAPL income statements:") - try: - df = fetch_financialdata("AAPL", endpoint="income-statements", period="year") - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 5: Stock symbols list (Free tier) - print("\n5. Fetching stock symbol list (first page):") - try: - df = fetch_financialdata("", endpoint="stock-symbols") - print(f" Retrieved {len(df)} symbols") - print(df.head()) - except Exception as e: - print(f" Error: {e}") diff --git a/claude/skills/quant/market-datasets/scripts/fetch_fred.py b/claude/skills/quant/market-datasets/scripts/fetch_fred.py deleted file mode 100644 index 0d1ad08b..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_fred.py +++ /dev/null @@ -1,340 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# "python-dotenv>=1.0", -# ] -# /// -""" -FRED (Federal Reserve Economic Data) API fetcher. - -Downloads economic indicators from FRED database. -Requires API key from https://fred.stlouisfed.org/docs/api/api_key.html - -API key can be provided via: -1. .env file: FRED_API_KEY=your_key -2. Environment variable: FRED_API_KEY -3. Config file: config/fred_api_key.txt -4. Direct parameter - -Usage: - uv run fetch_fred.py GDP 2020-01-01 2024-12-31 - uv run fetch_fred.py UNRATE 2020-01-01 - uv run fetch_fred.py # Run self-tests (requires API key) -""" - -import pandas as pd -import requests -from typing import Optional -from datetime import datetime, date -import os - -from utils import ( - get_cache_manager, - get_rate_limiter, - normalize_date, - normalize_date_display, - create_identifier, - handle_api_error -) - - -class FREDFetcher: - """Fetcher for FRED economic data.""" - - BASE_URL = "https://api.stlouisfed.org/fred/series/observations" - - def __init__(self, api_key: Optional[str] = None, use_cache: bool = True, - cache_hours: int = 24): - """ - Initialize FRED fetcher. - - Args: - api_key: FRED API key (optional if set in env or config) - use_cache: Whether to use caching - cache_hours: Cache validity in hours - """ - self.api_key = self._get_api_key(api_key) - if not self.api_key: - raise ValueError( - "FRED API key required. Set FRED_API_KEY environment variable, " - "create config/fred_api_key.txt, or pass api_key parameter. " - "Get key at: https://fred.stlouisfed.org/docs/api/api_key.html" - ) - - self.use_cache = use_cache - self.cache_hours = cache_hours - self.cache = get_cache_manager() - self.rate_limiter = get_rate_limiter() - - def _get_api_key(self, api_key: Optional[str] = None) -> Optional[str]: - """ - Get FRED API key from various sources. - - Priority: - 1. Direct parameter - 2. Environment variable - 3. Config file - - Args: - api_key: Direct API key - - Returns: - API key or None - """ - # 1. Direct parameter - if api_key: - return api_key - - # 2. Environment variable - env_key = os.environ.get('FRED_API_KEY') - if env_key: - return env_key - - # 3. Config file - config_paths = [ - 'config/fred_api_key.txt', - 'U:/config_files/fred_api_key.txt', - os.path.expanduser('~/.fred_api_key') - ] - - for path in config_paths: - if os.path.exists(path): - try: - with open(path, 'r') as f: - key = f.read().strip() - if key: - return key - except Exception: - continue - - return None - - def fetch(self, series_id: str, start_date: Optional[str] = None, - end_date: Optional[str] = None) -> pd.DataFrame: - """ - Fetch economic data series from FRED. - - Args: - series_id: FRED series ID (e.g., 'GDP', 'UNRATE', 'CPIAUCSL') - start_date: Start date (YYYY-MM-DD or YYYYMMDD) - end_date: End date (YYYY-MM-DD or YYYYMMDD) - - Returns: - DataFrame with columns: Date, Value - - Raises: - ValueError: If series_id invalid or no data returned - requests.RequestException: If request fails - """ - # 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(series_id, start_norm, end_norm) - - # Try cache first - if self.use_cache: - cached = self.cache.get('fred', cache_id, max_age_hours=self.cache_hours) - if cached is not None: - print(f"[FRED] Using cached data for {series_id}") - return cached - - # Convert dates to display format - start_display = normalize_date_display(start_date) if start_date else None - end_display = normalize_date_display(end_date) if end_date else None - - # Build request parameters - params = { - 'series_id': series_id, - 'api_key': self.api_key, - 'file_type': 'json' - } - - if start_display: - params['observation_start'] = start_display - if end_display: - params['observation_end'] = end_display - - try: - # Rate limiting - self.rate_limiter.wait('fred') - - # Fetch data - print(f"[FRED] Fetching {series_id} from {start_display or 'earliest'} to {end_display or 'latest'}") - response = requests.get(self.BASE_URL, params=params, timeout=30) - response.raise_for_status() - - # Parse JSON - data = response.json() - - if 'error_code' in data: - raise ValueError(f"FRED API error: {data.get('error_message', 'Unknown error')}") - - # Extract observations - df = self._parse_response(data, series_id) - - if df.empty: - raise ValueError(f"No data returned for series: {series_id}") - - # Cache result - if self.use_cache: - self.cache.set('fred', cache_id, df) - - return df - - except requests.exceptions.HTTPError as e: - if e.response.status_code == 400: - raise ValueError(f"Invalid series ID or parameters: {series_id}") - handle_api_error('FRED', e, series_id) - raise - except Exception as e: - handle_api_error('FRED', e, series_id) - raise - - def _parse_response(self, data: dict, series_id: str) -> pd.DataFrame: - """ - Parse FRED API JSON response. - - Args: - data: JSON response - series_id: Series ID - - Returns: - Parsed DataFrame - """ - if 'observations' not in data: - return pd.DataFrame() - - observations = [] - for obs in data['observations']: - # Skip missing values - if obs['value'] == '.': - continue - - observations.append({ - 'Date': pd.to_datetime(obs['date']), - 'Value': float(obs['value']), - 'Series_ID': series_id - }) - - df = pd.DataFrame(observations) - - # Sort by date - if not df.empty: - df.sort_values('Date', inplace=True) - df.reset_index(drop=True, inplace=True) - - return df - - def get_series_info(self, series_id: str) -> dict: - """ - Get metadata about a FRED series. - - Args: - series_id: FRED series ID - - Returns: - Dictionary with series information - """ - url = "https://api.stlouisfed.org/fred/series" - params = { - 'series_id': series_id, - 'api_key': self.api_key, - 'file_type': 'json' - } - - try: - response = requests.get(url, params=params, timeout=30) - response.raise_for_status() - data = response.json() - - if 'seriess' in data and len(data['seriess']) > 0: - return data['seriess'][0] - return {} - - except Exception as e: - handle_api_error('FRED', e, series_id) - return {} - - def fetch_multiple(self, series_ids: list, start_date: Optional[str] = None, - end_date: Optional[str] = None) -> dict: - """ - Fetch multiple series. - - Args: - series_ids: List of FRED series IDs - start_date: Start date - end_date: End date - - Returns: - Dictionary mapping series_id -> DataFrame - """ - results = {} - - for series_id in series_ids: - try: - df = self.fetch(series_id, start_date, end_date) - results[series_id] = df - except Exception as e: - print(f"[FRED] Skipping {series_id}: {e}") - continue - - return results - - -def fetch_fred(series_id: str, start_date: Optional[str] = None, - end_date: Optional[str] = None, api_key: Optional[str] = None, - use_cache: bool = True) -> pd.DataFrame: - """ - Convenience function to fetch FRED economic data. - - Args: - series_id: FRED series ID - start_date: Start date - end_date: End date - api_key: FRED API key (optional if in env/config) - use_cache: Whether to use caching - - Returns: - DataFrame with economic data - """ - fetcher = FREDFetcher(api_key=api_key, use_cache=use_cache) - return fetcher.fetch(series_id, start_date, end_date) - - -if __name__ == '__main__': - # Test examples - print("Testing FRED fetcher...") - - try: - # Test 1: GDP - print("\n1. Fetching GDP:") - df = fetch_fred('GDP', start_date='20200101', end_date='20241231') - print(f" Retrieved {len(df)} rows") - print(df.head()) - print(df.tail()) - - # Test 2: Unemployment rate - print("\n2. Fetching UNRATE (Unemployment Rate):") - df = fetch_fred('UNRATE', start_date='20240101') - print(f" Retrieved {len(df)} rows") - print(df.head()) - - # Test 3: Get series info - print("\n3. Getting GDP series info:") - fetcher = FREDFetcher() - info = fetcher.get_series_info('GDP') - print(f" Title: {info.get('title')}") - print(f" Units: {info.get('units')}") - print(f" Frequency: {info.get('frequency')}") - - except ValueError as e: - print(f"\nAPI key not configured: {e}") - print("\nTo use FRED:") - print("1. Get API key from https://fred.stlouisfed.org/docs/api/api_key.html") - print("2. Set environment variable: FRED_API_KEY=your_key") - print("3. Or create config/fred_api_key.txt with your key") - except Exception as e: - print(f" Error: {e}") diff --git a/claude/skills/quant/market-datasets/scripts/fetch_nbp.py b/claude/skills/quant/market-datasets/scripts/fetch_nbp.py deleted file mode 100644 index aaa340d9..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_nbp.py +++ /dev/null @@ -1,288 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# ] -# /// -""" -NBP (Narodowy Bank Polski) API fetcher. - -Downloads official PLN exchange rates from NBP API. -API Documentation: http://api.nbp.pl/ - -Rate tables: -- Table A: Foreign exchange rates (most common currencies) -- Table B: Foreign exchange rates (less common currencies) -- Table C: Buy/sell rates - -Usage: - uv run fetch_nbp.py USD 2024-01-01 2024-12-31 - uv run fetch_nbp.py EUR 2024-01-01 - uv run fetch_nbp.py # Run self-tests -""" - -import pandas as pd -import requests -from typing import Optional, Literal -from datetime import datetime, date - -from utils import ( - get_cache_manager, - get_rate_limiter, - normalize_date, - normalize_date_display, - create_identifier, - handle_api_error -) - - -class NBPFetcher: - """Fetcher for NBP API exchange rates.""" - - BASE_URL = "http://api.nbp.pl/api/exchangerates" - - def __init__(self, use_cache: bool = True, cache_hours: int = 24): - """ - Initialize NBP 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, currency_code: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - table: Literal['A', 'B', 'C'] = 'A') -> pd.DataFrame: - """ - Fetch exchange rates from NBP API. - - Args: - currency_code: Three-letter currency code (e.g., 'USD', 'EUR', 'GBP') - start_date: Start date (YYYY-MM-DD or YYYYMMDD) - end_date: End date (YYYY-MM-DD or YYYYMMDD) - table: Rate table - 'A' (most common), 'B' (others), 'C' (buy/sell) - - Returns: - DataFrame with columns: Date, Currency, Mid (or Bid/Ask for table C) - - Raises: - ValueError: If currency code or dates invalid - requests.RequestException: If request fails - """ - # Normalize currency code - currency_code = currency_code.upper() - - # 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 = f"{currency_code}_{table}_{start_norm}_{end_norm}" - - # Try cache first - if self.use_cache: - cached = self.cache.get('nbp', cache_id, format='json', - max_age_hours=self.cache_hours) - if cached is not None: - print(f"[NBP] Using cached data for {currency_code}") - return pd.DataFrame(cached) - - # Build URL - url = self._build_url(currency_code, start_norm, end_norm, table) - - try: - # Rate limiting - self.rate_limiter.wait('nbp') - - # Fetch data - print(f"[NBP] Fetching {currency_code} (Table {table}) from {start_norm or 'earliest'} to {end_norm or 'latest'}") - response = requests.get(url, timeout=30, headers={'Accept': 'application/json'}) - response.raise_for_status() - - # Parse JSON - data = response.json() - - # Extract rates - df = self._parse_response(data, currency_code, table) - - if df.empty: - raise ValueError(f"No data returned for {currency_code}") - - # Cache result (as dict for JSON) - if self.use_cache: - self.cache.set('nbp', cache_id, df.to_dict(orient='records'), format='json') - - return df - - except requests.exceptions.HTTPError as e: - if e.response.status_code == 404: - raise ValueError(f"Currency code '{currency_code}' not found in table {table}") - handle_api_error('NBP', e, currency_code) - raise - except Exception as e: - handle_api_error('NBP', e, currency_code) - raise - - def _parse_response(self, data: dict, currency_code: str, table: str) -> pd.DataFrame: - """ - Parse NBP API JSON response into DataFrame. - - Args: - data: JSON response from API - currency_code: Currency code - table: Table type - - Returns: - Parsed DataFrame - """ - rates_data = [] - - if 'rates' in data: - for rate in data['rates']: - row = { - 'Date': pd.to_datetime(rate['effectiveDate']), - 'Currency': currency_code - } - - if table in ['A', 'B']: - row['Mid'] = rate['mid'] - elif table == 'C': - row['Bid'] = rate['bid'] - row['Ask'] = rate['ask'] - - rates_data.append(row) - - df = pd.DataFrame(rates_data) - - # Sort by date - if not df.empty: - df.sort_values('Date', inplace=True) - df.reset_index(drop=True, inplace=True) - - return df - - def _build_url(self, currency_code: str, start_date: Optional[str] = None, - end_date: Optional[str] = None, table: str = 'A') -> str: - """ - Build NBP API URL. - - Args: - currency_code: Currency code - start_date: Start date (YYYYMMDD) - end_date: End date (YYYYMMDD) - table: Table type - - Returns: - Complete URL - """ - # Convert dates to display format (YYYY-MM-DD) for NBP API - start_display = normalize_date_display(start_date) if start_date else None - end_display = normalize_date_display(end_date) if end_date else None - - if start_display and end_display: - # Date range query - url = f"{self.BASE_URL}/rates/{table}/{currency_code}/{start_display}/{end_display}/" - elif start_display: - # From start date to today - today = datetime.now().strftime('%Y-%m-%d') - url = f"{self.BASE_URL}/rates/{table}/{currency_code}/{start_display}/{today}/" - else: - # Latest rate only - url = f"{self.BASE_URL}/rates/{table}/{currency_code}/last/255/" - - return url - - def fetch_multiple(self, currency_codes: list, start_date: Optional[str] = None, - end_date: Optional[str] = None, table: str = 'A') -> pd.DataFrame: - """ - Fetch multiple currencies and combine into single DataFrame. - - Args: - currency_codes: List of currency codes - start_date: Start date - end_date: End date - table: Rate table - - Returns: - Combined DataFrame with all currencies - """ - all_data = [] - - for code in currency_codes: - try: - df = self.fetch(code, start_date, end_date, table) - all_data.append(df) - except Exception as e: - print(f"[NBP] Skipping {code}: {e}") - continue - - if not all_data: - raise ValueError("No data retrieved for any currency") - - # Combine all DataFrames - combined = pd.concat(all_data, ignore_index=True) - combined.sort_values(['Date', 'Currency'], inplace=True) - combined.reset_index(drop=True, inplace=True) - - return combined - - -def fetch_nbp(currency_code: str, start_date: Optional[str] = None, - end_date: Optional[str] = None, table: str = 'A', - use_cache: bool = True) -> pd.DataFrame: - """ - Convenience function to fetch NBP exchange rates. - - Args: - currency_code: Currency code (e.g., 'USD', 'EUR') - start_date: Start date - end_date: End date - table: Rate table ('A', 'B', or 'C') - use_cache: Whether to use caching - - Returns: - DataFrame with exchange rates - """ - fetcher = NBPFetcher(use_cache=use_cache) - return fetcher.fetch(currency_code, start_date, end_date, table) - - -if __name__ == '__main__': - # Test examples - print("Testing NBP fetcher...") - - # Test 1: USD rates - print("\n1. Fetching USD rates (Table A):") - try: - df = fetch_nbp('USD', start_date='20240101', end_date='20241231') - print(f" Retrieved {len(df)} rows") - print(df.head()) - print(df.tail()) - except Exception as e: - print(f" Error: {e}") - - # Test 2: EUR rates - print("\n2. Fetching EUR rates (Table A):") - try: - df = fetch_nbp('EUR', start_date='20240101') - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 3: Multiple currencies - print("\n3. Fetching multiple currencies:") - try: - fetcher = NBPFetcher() - df = fetcher.fetch_multiple(['USD', 'EUR', 'GBP'], - start_date='20240101', - end_date='20240131') - print(f" Retrieved {len(df)} rows") - print(df.head(10)) - except Exception as e: - print(f" Error: {e}") diff --git a/claude/skills/quant/market-datasets/scripts/fetch_pandas_datareader.py b/claude/skills/quant/market-datasets/scripts/fetch_pandas_datareader.py deleted file mode 100644 index 4ab6cc19..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_pandas_datareader.py +++ /dev/null @@ -1,250 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "pandas-datareader>=0.10.0", -# ] -# /// -""" -pandas-datareader wrapper. - -Meta-fetcher that provides access to multiple data sources through pandas-datareader. - -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 yahoo - uv run fetch_pandas_datareader.py GDP 2020-01-01 --source fred - uv run fetch_pandas_datareader.py # Run self-tests -""" - -import pandas as pd -from typing import Optional, Literal -from datetime import datetime, date - -try: - import pandas_datareader as pdr - from pandas_datareader.data import DataReader - PANDAS_DATAREADER_AVAILABLE = True -except ImportError: - PANDAS_DATAREADER_AVAILABLE = False - print("[pandas-datareader] Warning: pandas-datareader not installed. Run: pip install pandas-datareader") - -from utils import ( - get_cache_manager, - get_rate_limiter, - normalize_date, - normalize_date_display, - standardize_dataframe, - create_identifier, - handle_api_error -) - - -class PandasDataReaderFetcher: - """Wrapper for pandas-datareader multi-source data access.""" - - SUPPORTED_SOURCES = [ - 'yahoo', # Yahoo Finance - 'fred', # FRED economic data - 'av-daily', # Alpha Vantage (requires API key) - 'iex', # IEX Cloud (requires API key) - 'quandl', # Quandl (requires API key) - ] - - def __init__(self, use_cache: bool = True, cache_hours: int = 24): - """ - Initialize pandas-datareader fetcher. - - Args: - use_cache: Whether to use caching - cache_hours: Cache validity in hours - """ - if not PANDAS_DATAREADER_AVAILABLE: - raise ImportError( - "pandas-datareader not available. Install with: pip install pandas-datareader" - ) - - 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, source: str = 'yahoo', - start_date: Optional[str] = None, - end_date: Optional[str] = None, - **kwargs) -> pd.DataFrame: - """ - Fetch data using pandas-datareader. - - Args: - ticker: Ticker symbol (format depends on source) - 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 - - Returns: - DataFrame with market data - - Raises: - ValueError: If source invalid or no data returned - """ - if source not in self.SUPPORTED_SOURCES: - raise ValueError( - f"Source '{source}' not supported. " - f"Supported sources: {', '.join(self.SUPPORTED_SOURCES)}" - ) - - # 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 = f"{source}_{create_identifier(ticker, start_norm, end_norm)}" - - # Try cache first - if self.use_cache: - cached = self.cache.get('pandas_datareader', cache_id, - max_age_hours=self.cache_hours) - if cached is not None: - print(f"[pandas-datareader] Using cached data for {ticker} from {source}") - return cached - - # Convert dates to display format - start_display = normalize_date_display(start_date) if start_date else None - end_display = normalize_date_display(end_date) if end_date else None - - try: - # Rate limiting - self.rate_limiter.wait(f'pdr_{source}') - - # Fetch data - print(f"[pandas-datareader] Fetching {ticker} from {source} " - f"({start_display or 'earliest'} to {end_display or 'latest'})") - - df = DataReader( - ticker, - source, - start=start_display, - end=end_display, - **kwargs - ) - - if df.empty: - raise ValueError(f"No data returned for {ticker} from {source}") - - # Reset index if needed (make Date a column) - if isinstance(df.index, pd.DatetimeIndex): - df.reset_index(inplace=True) - - # Standardize (best effort, some sources may not have all columns) - try: - df = standardize_dataframe(df, f'pdr_{source}') - except Exception as e: - print(f"[pandas-datareader] Warning: Could not standardize DataFrame: {e}") - - # Cache result - if self.use_cache: - self.cache.set('pandas_datareader', cache_id, df) - - return df - - except Exception as e: - handle_api_error(f'pandas-datareader ({source})', e, ticker) - raise - - def fetch_multiple(self, tickers: list, source: str = 'yahoo', - start_date: Optional[str] = None, - end_date: Optional[str] = None, - **kwargs) -> dict: - """ - Fetch multiple tickers from pandas-datareader. - - Args: - tickers: List of ticker symbols - source: Data source - start_date: Start date - end_date: End date - **kwargs: Additional arguments - - Returns: - Dictionary mapping ticker -> DataFrame - """ - results = {} - - for ticker in tickers: - try: - df = self.fetch(ticker, source, start_date, end_date, **kwargs) - results[ticker] = df - except Exception as e: - print(f"[pandas-datareader] Skipping {ticker}: {e}") - continue - - return results - - @staticmethod - def list_sources() -> list: - """ - List supported sources. - - Returns: - List of supported source names - """ - return PandasDataReaderFetcher.SUPPORTED_SOURCES - - -def fetch_pandas_datareader(ticker: str, source: str = 'yahoo', - start_date: Optional[str] = None, - end_date: Optional[str] = None, - use_cache: bool = True, - **kwargs) -> pd.DataFrame: - """ - Convenience function to fetch data via pandas-datareader. - - Args: - ticker: Ticker symbol - source: Data source - start_date: Start date - end_date: End date - use_cache: Whether to use caching - **kwargs: Additional arguments - - Returns: - DataFrame with market data - """ - fetcher = PandasDataReaderFetcher(use_cache=use_cache) - return fetcher.fetch(ticker, source, start_date, end_date, **kwargs) - - -if __name__ == '__main__': - # Test examples - if not PANDAS_DATAREADER_AVAILABLE: - print("pandas-datareader not available. Install with: pip install pandas-datareader") - else: - print("Testing pandas-datareader fetcher...") - - # Test 1: Yahoo via pandas-datareader - print("\n1. Fetching AAPL from Yahoo:") - try: - df = fetch_pandas_datareader('AAPL', source='yahoo', - start_date='20240101', - end_date='20240131') - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 2: FRED via pandas-datareader - print("\n3. Fetching GDP from FRED:") - try: - df = fetch_pandas_datareader('GDP', source='fred', - start_date='20200101', - end_date='20241231') - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 3: List sources - print("\n3. Supported sources:") - print(" " + ", ".join(PandasDataReaderFetcher.list_sources())) diff --git a/claude/skills/quant/market-datasets/scripts/fetch_tiingo.py b/claude/skills/quant/market-datasets/scripts/fetch_tiingo.py deleted file mode 100644 index 41aff84e..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_tiingo.py +++ /dev/null @@ -1,292 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# "python-dotenv>=1.0", -# ] -# /// -""" -Tiingo data fetcher. - -Downloads historical market data from Tiingo API. -Best for US stocks with 30+ years of history and generous free tier. - -Free tier: 50 req/hour, 1000 req/day, 500 symbols/month -Requires API key: https://api.tiingo.com/ - -API key can be provided via: -1. .env file: TIINGO_API_KEY=your_key -2. Environment variable: TIINGO_API_KEY -3. Direct parameter - -Usage: - uv run fetch_tiingo.py AAPL 2024-01-01 2024-12-31 - uv run fetch_tiingo.py MSFT 2024-01-01 - uv run fetch_tiingo.py # Run self-tests (requires API key) -""" - -import os -import pandas as pd -import requests -from typing import Optional -from datetime import datetime, date - -from utils import ( - get_cache_manager, - get_rate_limiter, - normalize_date, - normalize_date_display, - standardize_dataframe, - create_identifier, - handle_api_error -) - - -class TiingoFetcher: - """Fetcher for Tiingo market data.""" - - BASE_URL = "https://api.tiingo.com" - - def __init__(self, api_key: Optional[str] = None, use_cache: bool = True, - cache_hours: int = 24): - """ - Initialize Tiingo fetcher. - - Args: - api_key: Tiingo API key (or set TIINGO_API_KEY env var) - use_cache: Whether to use caching - cache_hours: Cache validity in hours - """ - self.api_key = api_key or os.environ.get('TIINGO_API_KEY') - if not self.api_key: - raise ValueError( - "Tiingo API key required. Set TIINGO_API_KEY environment variable " - "or pass api_key parameter. Get free key at: https://api.tiingo.com/" - ) - - self.use_cache = use_cache - self.cache_hours = cache_hours - self.cache = get_cache_manager() - self.rate_limiter = get_rate_limiter() - - self.headers = { - 'Content-Type': 'application/json', - 'Authorization': f'Token {self.api_key}' - } - - def fetch(self, ticker: str, start_date: Optional[str] = None, - end_date: Optional[str] = None) -> pd.DataFrame: - """ - Fetch EOD data from Tiingo. - - Args: - ticker: Stock ticker (e.g., 'AAPL', 'MSFT') - start_date: Start date (YYYY-MM-DD or YYYYMMDD) - end_date: End date (YYYY-MM-DD or YYYYMMDD) - - Returns: - DataFrame with columns: Date, Open, High, Low, Close, Volume, Adj_Close - - Raises: - ValueError: If ticker invalid or no data returned - requests.RequestException: If request fails - """ - # Normalize ticker (Tiingo uses uppercase) - ticker = ticker.upper() - - # 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, 'tiingo') - - # Try cache first - if self.use_cache: - cached = self.cache.get('tiingo', cache_id, max_age_hours=self.cache_hours) - if cached is not None: - print(f"[Tiingo] Using cached data for {ticker}") - return cached - - # Build URL - url = f"{self.BASE_URL}/tiingo/daily/{ticker}/prices" - params = {} - - if start_date: - params['startDate'] = normalize_date_display(start_date) - if end_date: - params['endDate'] = normalize_date_display(end_date) - - try: - # Rate limiting - self.rate_limiter.wait('tiingo') - - # Fetch data - start_display = normalize_date_display(start_date) if start_date else 'earliest' - end_display = normalize_date_display(end_date) if end_date else 'latest' - print(f"[Tiingo] Fetching {ticker} from {start_display} to {end_display}") - - response = requests.get(url, headers=self.headers, params=params, timeout=30) - - # Handle errors - if response.status_code == 404: - raise ValueError(f"Ticker not found: {ticker}") - elif response.status_code == 401: - raise ValueError("Invalid Tiingo API key") - elif response.status_code == 429: - raise ValueError("Tiingo rate limit exceeded. Wait and retry.") - - response.raise_for_status() - - data = response.json() - - if not data: - raise ValueError(f"No data returned for ticker: {ticker}") - - # Convert to DataFrame - df = pd.DataFrame(data) - - # Rename columns to standard format - column_mapping = { - 'date': 'Date', - 'open': 'Open', - 'high': 'High', - 'low': 'Low', - 'close': 'Close', - 'volume': 'Volume', - 'adjOpen': 'Adj_Open', - 'adjHigh': 'Adj_High', - 'adjLow': 'Adj_Low', - 'adjClose': 'Adj_Close', - 'adjVolume': 'Adj_Volume', - 'divCash': 'Dividend', - 'splitFactor': 'Split' - } - df.rename(columns=column_mapping, inplace=True) - - # Parse date and remove timezone - df['Date'] = pd.to_datetime(df['Date']).dt.tz_localize(None) - - # Sort by date - df.sort_values('Date', inplace=True) - df.reset_index(drop=True, inplace=True) - - # Cache result - if self.use_cache: - self.cache.set('tiingo', cache_id, df) - - return df - - except Exception as e: - handle_api_error('Tiingo', e, ticker) - raise - - def get_metadata(self, ticker: str) -> dict: - """ - Get ticker metadata from Tiingo. - - Args: - ticker: Stock ticker - - Returns: - Dictionary with ticker metadata - """ - ticker = ticker.upper() - url = f"{self.BASE_URL}/tiingo/daily/{ticker}" - - try: - self.rate_limiter.wait('tiingo') - response = requests.get(url, headers=self.headers, timeout=30) - response.raise_for_status() - return response.json() - except Exception as e: - handle_api_error('Tiingo', e, ticker) - return {} - - def fetch_multiple(self, tickers: list, start_date: Optional[str] = None, - end_date: Optional[str] = None) -> dict: - """ - Fetch multiple tickers. - - Args: - tickers: List of ticker symbols - start_date: Start date - end_date: End date - - Returns: - Dictionary mapping ticker -> DataFrame - """ - results = {} - - for ticker in tickers: - try: - df = self.fetch(ticker, start_date, end_date) - results[ticker] = df - except Exception as e: - print(f"[Tiingo] Skipping {ticker}: {e}") - continue - - return results - - -def fetch_tiingo(ticker: str, start_date: Optional[str] = None, - end_date: Optional[str] = None, api_key: Optional[str] = None, - use_cache: bool = True) -> pd.DataFrame: - """ - Convenience function to fetch data from Tiingo. - - Args: - ticker: Stock ticker - start_date: Start date - end_date: End date - api_key: Tiingo API key (or set TIINGO_API_KEY env var) - use_cache: Whether to use caching - - Returns: - DataFrame with market data - """ - fetcher = TiingoFetcher(api_key=api_key, use_cache=use_cache) - return fetcher.fetch(ticker, start_date, end_date) - - -if __name__ == '__main__': - # Test examples - import sys - - api_key = os.environ.get('TIINGO_API_KEY') - if not api_key: - print("Set TIINGO_API_KEY environment variable to test") - print("Get free API key at: https://api.tiingo.com/") - sys.exit(1) - - print("Testing Tiingo fetcher...") - - # Test 1: US stock - print("\n1. Fetching AAPL (US stock):") - try: - df = fetch_tiingo('AAPL', start_date='20240101', end_date='20240131') - print(f" Retrieved {len(df)} rows") - print(f" Columns: {list(df.columns)}") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 2: ETF - print("\n2. Fetching SPY (S&P 500 ETF):") - try: - df = fetch_tiingo('SPY', 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: Get metadata - print("\n3. Getting MSFT metadata:") - try: - fetcher = TiingoFetcher() - meta = fetcher.get_metadata('MSFT') - print(f" Name: {meta.get('name')}") - print(f" Exchange: {meta.get('exchangeCode')}") - print(f" Start date: {meta.get('startDate')}") - except Exception as e: - print(f" Error: {e}") diff --git a/claude/skills/quant/market-datasets/scripts/fetch_unified.py b/claude/skills/quant/market-datasets/scripts/fetch_unified.py deleted file mode 100644 index b0099924..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_unified.py +++ /dev/null @@ -1,876 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# "python-dotenv>=1.0", -# ] -# /// -""" -Unified market data fetcher with intelligent routing. - -Automatically selects the best data source based on: -- Ticker pattern/format -- Data type (stock, index, currency, economic indicator) -- Geographic market -- 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 - uv run fetch_unified.py USDPLN 2024-01-01 # FX pair - uv run fetch_unified.py BTC/USDT 2024-01-01 # Crypto - uv run fetch_unified.py # Run self-tests -""" - -import pandas as pd -from typing import Optional, List, Tuple -import re - -# Import TickerRegistry for security lookups -try: - from ticker_registry import TickerRegistry - - REGISTRY_AVAILABLE = True -except ImportError: - REGISTRY_AVAILABLE = False - -# 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." - ), -} - - -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 - - NBP_AVAILABLE = True -except ImportError: - NBP_AVAILABLE = False - -try: - from fetch_yahoo import YahooFetcher - - YAHOO_AVAILABLE = True -except ImportError: - YAHOO_AVAILABLE = False - -try: - from fetch_fred import FREDFetcher - - FRED_AVAILABLE = True -except ImportError: - FRED_AVAILABLE = False - -try: - from fetch_pandas_datareader import PandasDataReaderFetcher - - PDR_AVAILABLE = True -except ImportError: - PDR_AVAILABLE = False - -try: - from fetch_tiingo import TiingoFetcher - - TIINGO_AVAILABLE = True -except ImportError: - TIINGO_AVAILABLE = False - -try: - from fetch_ccxt import CCXTFetcher, is_crypto_symbol - - CCXT_AVAILABLE = True -except ImportError: - CCXT_AVAILABLE = False - - def is_crypto_symbol(s): - """Fallback if ccxt not available.""" - return "/" in s or s.upper().endswith(("USDT", "USDC", "BTC")) - - -try: - from fetch_financialdata import FinancialDataFetcher - - FINANCIALDATA_AVAILABLE = True -except ImportError: - FINANCIALDATA_AVAILABLE = False - -try: - 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 - - COINGECKO_AVAILABLE = True -except ImportError: - COINGECKO_AVAILABLE = False - - -class UnifiedMarketDataFetcher: - """ - Unified market data fetcher with intelligent source selection. - """ - - # Polish stock symbols (common ones) - POLISH_STOCKS = [ - "pko", - "cdr", - "pzu", - "peo", - "pkn", - "kgh", - "pge", - "lpp", - "ale", - "dnp", - "cps", - "jsw", - "tpe", - "mil", - "opl", - ] - - # Polish indices - POLISH_INDICES = ["wig", "wig20", "mwig40", "swig80", "wig30", "wig-ukraine"] - - # FRED series patterns (economic indicators) - FRED_PATTERNS = [ - r"^[A-Z]{2,10}$", # Short uppercase codes like GDP, UNRATE, CPIAUCSL - r".*RATE.*", # Contains RATE - r".*CPI.*", # Contains CPI - r".*GDP.*", # Contains GDP - ] - - # NBP currency codes - NBP_CURRENCIES = [ - "USD", - "EUR", - "GBP", - "CHF", - "JPY", - "CAD", - "AUD", - "SEK", - "NOK", - "DKK", - "CZK", - "HUF", - "RON", - "BGN", - "HRK", - ] - - def __init__( - self, - use_cache: bool = True, - cache_hours: int = 24, - fred_api_key: Optional[str] = None, - tiingo_api_key: Optional[str] = None, - financialdata_api_key: Optional[str] = None, - eodhd_api_key: Optional[str] = None, - crypto_exchange: str = "binance", - use_registry: bool = True, - ): - """ - Initialize unified fetcher. - - Args: - use_cache: Whether to use caching - cache_hours: Cache validity in hours - fred_api_key: FRED API key (optional) - tiingo_api_key: Tiingo API key (optional, or set TIINGO_API_KEY env var) - financialdata_api_key: FinancialData.Net API key (optional, or set FINANCIAL_DATA_API_KEY env var) - crypto_exchange: Default crypto exchange for CCXT (default: binance) - use_registry: Whether to use TickerRegistry for lookups - """ - self.use_cache = use_cache - self.cache_hours = cache_hours - self.fred_api_key = fred_api_key - self.tiingo_api_key = tiingo_api_key - self.financialdata_api_key = financialdata_api_key - self.eodhd_api_key = eodhd_api_key - self.crypto_exchange = crypto_exchange - - # Initialize TickerRegistry for ISIN/ticker lookups - self.registry = None - if use_registry and REGISTRY_AVAILABLE: - try: - self.registry = TickerRegistry() - except Exception as e: - print(f"[Unified] TickerRegistry unavailable: {e}") - - # Initialize available fetchers - self.fetchers = {} - - if NBP_AVAILABLE: - self.fetchers["nbp"] = NBPFetcher(use_cache, cache_hours) - - if YAHOO_AVAILABLE: - self.fetchers["yahoo"] = YahooFetcher(use_cache, cache_hours) - - if FRED_AVAILABLE and fred_api_key: - try: - self.fetchers["fred"] = FREDFetcher(fred_api_key, use_cache, cache_hours) - except ValueError: - print("[Unified] FRED API key not configured, FRED unavailable") - - if PDR_AVAILABLE: - self.fetchers["pdr"] = PandasDataReaderFetcher(use_cache, cache_hours) - - # Initialize Tiingo (requires API key) - if TIINGO_AVAILABLE: - try: - self.fetchers["tiingo"] = TiingoFetcher(tiingo_api_key, use_cache, cache_hours) - except ValueError: - print("[Unified] Tiingo API key not configured, Tiingo unavailable") - - # Initialize CCXT for crypto (no API key needed for public data) - if CCXT_AVAILABLE: - try: - self.fetchers["ccxt"] = CCXTFetcher(crypto_exchange, use_cache, cache_hours) - except Exception as e: - print(f"[Unified] CCXT unavailable: {e}") - - # Initialize FinancialData.Net (requires API key) - if FINANCIALDATA_AVAILABLE: - try: - self.fetchers["financialdata"] = FinancialDataFetcher( - financialdata_api_key, use_cache, cache_hours - ) - except ValueError: - print( - "[Unified] FinancialData.Net API key not configured, FinancialData unavailable" - ) - - # 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) - except ValueError: - print("[Unified] EODHD API key not configured, EODHD unavailable") - - # Initialize CoinGecko (no key needed for the free tier) — crypto - # price/market-cap/volume by coin id, complementing CCXT's exchange - # OHLCV. Opt-in via source='coingecko'. - if COINGECKO_AVAILABLE: - try: - self.fetchers["coingecko"] = CoinGeckoFetcher( - use_cache=use_cache, cache_hours=cache_hours - ) - except Exception as e: # noqa: BLE001 - print(f"[Unified] CoinGecko unavailable: {e}") - - def fetch( - self, - identifier: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - source: Optional[str] = None, - **kwargs, - ) -> pd.DataFrame: - """ - Fetch market data with automatic source selection. - - Supports ISINs, UIDs, and ticker symbols. Uses TickerRegistry for - smart routing when identifier is found in security master. - - Args: - identifier: ISIN, UID, or ticker symbol - start_date: Start date (YYYY-MM-DD or YYYYMMDD) - end_date: End date (YYYY-MM-DD or YYYYMMDD) - source: Force specific source (None for auto-routing) - **kwargs: Additional arguments passed to fetcher - - Returns: - DataFrame with market data - - 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: - security = self.registry.get_security(identifier) - if security: - print( - f"[Unified] Found '{identifier}' in registry: {security.name} ({security.uid})" - ) - - # If source specified, use it directly (with ticker conversion if security found) - if source: - ticker = identifier - if security: - source_ticker = security.get_ticker(source) - if source_ticker: - ticker = source_ticker - return self._fetch_from_source(source, ticker, start_date, end_date, **kwargs) - - # Auto-detect best source using registry or pattern matching - if security: - sources, ticker_map = self._route_security(security) - else: - sources = self._route_ticker(identifier) - ticker_map = {s: self._ticker_for_source(identifier, s) for s in sources} - - print(f"[Unified] Routing '{identifier}' -> {', '.join(sources)}") - - # Try sources in order with fallback - last_error = None - for source_name in sources: - try: - ticker = ticker_map.get(source_name, identifier) - return self._fetch_from_source(source_name, ticker, start_date, end_date, **kwargs) - except Exception as e: - print(f"[Unified] {source_name} failed: {e}") - last_error = e - continue - - # All sources failed - raise ValueError(f"All sources failed for '{identifier}'. Last error: {last_error}") - - def _route_security(self, security) -> Tuple[List[str], dict]: - """ - Determine best sources for a known security. - - Uses instrument type and available tickers to route. - - Args: - security: Security object from registry - - Returns: - Tuple of (source priority list, ticker mapping dict) - """ - sources = [] - ticker_map = {} - - instrument_type = security.instrument_type - - # 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, then Yahoo - if security.uid and "PLN" in security.uid: - priority = ["nbp", "yahoo"] - else: - priority = ["yahoo", "pdr"] - - else: - # 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: - if src not in self.fetchers: - 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 - elif src == "nbp" and security.instrument_type == "currency": - # NBP uses currency codes, not tickers - # Extract currency from uid like fx_USDPLN -> USD - if security.uid and security.uid.startswith("fx_"): - currency = security.uid[3:6] # First currency in pair - 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()) - fallback = security.isin or security.uid - ticker_map = {s: fallback for s in sources} - - return sources, ticker_map - - def _route_ticker(self, ticker: str) -> List[str]: - """ - Determine best sources for a ticker. - - Args: - ticker: Ticker symbol - - Returns: - List of source names in priority order - """ - ticker_lower = ticker.lower() - ticker_upper = ticker.upper() - - # Check for crypto symbols first (BTC/USDT, ETHUSDT, etc.) - if is_crypto_symbol(ticker) and "ccxt" in self.fetchers: - return ["ccxt"] - - # 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: - sources = self._polish_sources() - if "tiingo" in self.fetchers: - sources.append("tiingo") - sources.append("pdr") - return sources - - # Check for NBP currency request (direct 3-letter code) - if ticker_upper in self.NBP_CURRENCIES and NBP_AVAILABLE: - return ["nbp", "yahoo"] - - # Check for currency pairs (e.g., USDPLN, EURUSD) - if re.match(r"^[A-Z]{6}$", ticker_upper): # 6-letter currency pair - 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: - if re.match(pattern, ticker_upper): - if "fred" in self.fetchers: - return ["fred", "pdr"] - - # Check for international indices (^SPX, ^IXIC, ^BCOM, etc.) - if ticker.startswith("^"): - return ["yahoo", "pdr"] - - # Check for US stocks / ETFs (all caps, short). - if ticker.isupper() and 1 <= len(ticker) <= 5: - sources = ["yahoo"] - if "tiingo" in self.fetchers: - sources.append("tiingo") - if "financialdata" in self.fetchers: - sources.append("financialdata") - sources.append("pdr") - return sources - - # Check for explicit market suffix (.WA, .WAR, .US, .L, .LSE, etc.) - if "." in ticker: - suffix = ticker.split(".")[-1].upper() - 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"] - if "tiingo" in self.fetchers: - sources.append("tiingo") - if "financialdata" in self.fetchers: - sources.append("financialdata") - 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, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - **kwargs, - ) -> pd.DataFrame: - """ - Fetch data from specific source. - - Args: - source: Source name - ticker: Ticker symbol - start_date: Start date - end_date: End date - **kwargs: Additional arguments - - Returns: - DataFrame with market data - """ - _reject_removed_source(source) - if source not in self.fetchers: - raise ValueError(f"Source '{source}' not available") - - fetcher = self.fetchers[source] - - # Handle source-specific quirks - if source == "nbp": - # NBP needs table parameter - table = kwargs.pop("table", "A") - return fetcher.fetch(ticker, start_date, end_date, table=table) - - elif source == "pdr": - # pandas-datareader needs explicit source parameter - pdr_source = kwargs.pop("pdr_source", "yahoo") - return fetcher.fetch(ticker, pdr_source, start_date, end_date, **kwargs) - - elif source == "ccxt": - # CCXT needs timeframe parameter - timeframe = kwargs.pop("timeframe", "1d") - return fetcher.fetch(ticker, start_date, end_date, timeframe=timeframe, **kwargs) - - elif source == "financialdata": - # FinancialData.Net - supports endpoint parameter for different data types - endpoint = kwargs.pop("fd_endpoint", "stock-prices") - return fetcher.fetch(ticker, start_date, end_date, endpoint=endpoint, **kwargs) - - else: - # Standard fetchers (yahoo, eodhd, fred, tiingo) - return fetcher.fetch(ticker, start_date, end_date, **kwargs) - - def compare_sources( - self, - ticker: str, - sources: List[str], - start_date: Optional[str] = None, - end_date: Optional[str] = None, - ) -> dict: - """ - Fetch data from multiple sources for comparison. - - Args: - ticker: Ticker symbol - sources: List of source names to compare - start_date: Start date - end_date: End date - - Returns: - Dictionary mapping source -> DataFrame - """ - results = {} - - for source in sources: - try: - df = self._fetch_from_source(source, ticker, start_date, end_date) - results[source] = df - except Exception as e: - print(f"[Unified] {source} failed: {e}") - results[source] = None - - return results - - def list_available_sources(self) -> List[str]: - """ - List currently available sources. - - Returns: - List of source names - """ - return list(self.fetchers.keys()) - - -def fetch_market_data( - identifier: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - source: Optional[str] = None, - use_cache: bool = True, - use_registry: bool = True, - fred_api_key: Optional[str] = None, - tiingo_api_key: Optional[str] = None, - financialdata_api_key: Optional[str] = None, - crypto_exchange: str = "binance", - **kwargs, -) -> pd.DataFrame: - """ - Main convenience function for fetching market data. - - Auto-routes to best source unless source specified. - Supports ISINs, UIDs, ticker symbols, and crypto pairs. - - Args: - identifier: ISIN, UID, ticker symbol, or crypto pair (e.g., 'BTC/USDT') - start_date: Start date - end_date: End date - source: Force specific source (None for auto) - use_cache: Whether to use caching - use_registry: Whether to use TickerRegistry for lookups - fred_api_key: FRED API key (optional) - tiingo_api_key: Tiingo API key (optional, or set TIINGO_API_KEY env var) - financialdata_api_key: FinancialData.Net API key (optional, or set FINANCIAL_DATA_API_KEY env var) - crypto_exchange: Default crypto exchange for CCXT (default: binance) - **kwargs: Additional arguments (e.g., timeframe='1h' for crypto, fd_endpoint for FinancialData) - - Returns: - DataFrame with market data - """ - fetcher = UnifiedMarketDataFetcher( - use_cache=use_cache, - use_registry=use_registry, - fred_api_key=fred_api_key, - tiingo_api_key=tiingo_api_key, - financialdata_api_key=financialdata_api_key, - crypto_exchange=crypto_exchange, - ) - return fetcher.fetch(identifier, start_date, end_date, source, **kwargs) - - -if __name__ == "__main__": - # Test examples - print("Testing Unified Market Data Fetcher...\n") - - fetcher = UnifiedMarketDataFetcher() - - print(f"Available sources: {', '.join(fetcher.list_available_sources())}") - if fetcher.registry: - print(f"Registry loaded: {len(fetcher.registry._securities)} securities") - print() - - # 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") - print(f" Retrieved {len(df)} rows from auto-selected source") - print(df.head(3)) - except Exception as e: - print(f" Error: {e}") - - # Test 2: Fetch by ISIN (should lookup in registry) - print("\n2. Fetching XTB by ISIN (PLXTRDM00011):") - try: - df = fetcher.fetch("PLXTRDM00011", start_date="20240101", end_date="20240131") - print(f" Retrieved {len(df)} rows from auto-selected source") - print(df.head(3)) - except Exception as e: - print(f" Error: {e}") - - # Test 3: Fetch by UID - print("\n3. Fetching WIG20 by UID (idx_WIG20):") - try: - df = fetcher.fetch("idx_WIG20", start_date="20240101", end_date="20240131") - print(f" Retrieved {len(df)} rows from auto-selected source") - print(df.head(3)) - except Exception as e: - print(f" Error: {e}") - - # Test 4: US stock (should route to Yahoo) - print("\n4. Fetching AAPL (US stock):") - try: - df = fetcher.fetch("AAPL", start_date="20240101", end_date="20240131") - print(f" Retrieved {len(df)} rows from auto-selected source") - print(df.head(3)) - except Exception as e: - print(f" Error: {e}") - - # 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") - print(f" Retrieved {len(df)} rows from auto-selected source") - print(df.head(3)) - except Exception as e: - print(f" Error: {e}") - - # Test 6: Force specific source with ISIN - print("\n6. Fetching PLXTRDM00011 from Yahoo (forced):") - try: - df = fetcher.fetch( - "PLXTRDM00011", start_date="20240101", end_date="20240131", source="yahoo" - ) - print(f" Retrieved {len(df)} rows") - print(df.head(3)) - except Exception as e: - print(f" Error: {e}") - - # Test 7: Compare sources - print("\n7. Comparing PKO from different sources:") - try: - comparison = fetcher.compare_sources( - "PKO.WA", ["eodhd", "yahoo"], start_date="20240115", end_date="20240119" - ) - for source, df in comparison.items(): - if df is not None: - print(f" {source}: {len(df)} rows") - else: - print(f" {source}: Failed") - except Exception as e: - print(f" Error: {e}") - - # Test 8: Crypto (should route to CCXT) - print("\n8. Fetching BTC/USDT (crypto):") - try: - df = fetcher.fetch("BTC/USDT", start_date="20240101", end_date="20240131") - print(f" Retrieved {len(df)} rows from auto-selected source") - print(df.head(3)) - except Exception as e: - print(f" Error: {e}") - - # Test 9: Crypto with different format - print("\n9. Fetching ETHUSDT (crypto, no slash):") - try: - df = fetcher.fetch("ETHUSDT", start_date="20240101", end_date="20240115") - print(f" Retrieved {len(df)} rows from auto-selected source") - print(df.head(3)) - except Exception as e: - print(f" Error: {e}") - - # Test 10: Tiingo (if available) - if "tiingo" in fetcher.fetchers: - print("\n10. Fetching MSFT via Tiingo:") - try: - df = fetcher.fetch("MSFT", start_date="20240101", end_date="20240131", source="tiingo") - print(f" Retrieved {len(df)} rows") - print(df.head(3)) - except Exception as e: - print(f" Error: {e}") - else: - print("\n10. Tiingo not available (set TIINGO_API_KEY)") - - # Test 11: FinancialData.Net (if available) - if "financialdata" in fetcher.fetchers: - print("\n11. Fetching AAPL via FinancialData.Net:") - try: - df = fetcher.fetch( - "AAPL", - start_date="20240101", - end_date="20240131", - source="financialdata", - ) - print(f" Retrieved {len(df)} rows") - print(df.head(3)) - except Exception as e: - print(f" Error: {e}") - else: - print("\n11. FinancialData.Net not available (set FINANCIAL_DATA_API_KEY)") diff --git a/claude/skills/quant/market-datasets/scripts/fetch_yahoo.py b/claude/skills/quant/market-datasets/scripts/fetch_yahoo.py deleted file mode 100644 index 2960a1bb..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_yahoo.py +++ /dev/null @@ -1,226 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "yfinance>=0.2.0", -# ] -# /// -""" -Yahoo Finance fetcher. - -Downloads market data using yfinance library. -Best for US stocks, ETFs, and international equities. - -Usage: - uv run fetch_yahoo.py AAPL 2024-01-01 2024-12-31 - uv run fetch_yahoo.py PKO.WA 2024-01-01 - uv run fetch_yahoo.py # Run self-tests -""" - -import pandas as pd -from typing import Optional -from datetime import datetime, date - -try: - import yfinance as yf - YFINANCE_AVAILABLE = True -except ImportError: - YFINANCE_AVAILABLE = False - print("[Yahoo] Warning: yfinance not installed. Run: pip install yfinance") - -from utils import ( - get_cache_manager, - get_rate_limiter, - normalize_date, - normalize_date_display, - standardize_dataframe, - create_identifier, - handle_api_error -) - - -class YahooFetcher: - """Fetcher for Yahoo Finance data via yfinance.""" - - def __init__(self, use_cache: bool = True, cache_hours: int = 24): - """ - Initialize Yahoo Finance fetcher. - - Args: - use_cache: Whether to use caching - cache_hours: Cache validity in hours - """ - if not YFINANCE_AVAILABLE: - raise ImportError("yfinance package not available. Install with: pip install yfinance") - - 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 = '1d') -> pd.DataFrame: - """ - Fetch data from Yahoo Finance. - - Args: - ticker: Stock ticker (e.g., 'AAPL', 'MSFT', '^GSPC', 'PKO.WA') - start_date: Start date (YYYY-MM-DD or YYYYMMDD), None for max history - end_date: End date (YYYY-MM-DD or YYYYMMDD), None for today - interval: Data interval - '1d', '1wk', '1mo', '1h', etc. - - Returns: - DataFrame with columns: Date, Open, High, Low, Close, Volume, Adj_Close - - Raises: - ValueError: If ticker invalid or no data returned - """ - # 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('yahoo', cache_id, max_age_hours=self.cache_hours) - if cached is not None: - print(f"[Yahoo] Using cached data for {ticker}") - return cached - - # Convert dates to display format for yfinance - start_display = normalize_date_display(start_date) if start_date else None - end_display = normalize_date_display(end_date) if end_date else None - - try: - # Rate limiting - self.rate_limiter.wait('yahoo') - - # Fetch data - print(f"[Yahoo] Fetching {ticker} from {start_display or 'max'} to {end_display or 'today'}") - - ticker_obj = yf.Ticker(ticker) - df = ticker_obj.history( - start=start_display, - end=end_display, - interval=interval, - auto_adjust=False, # Keep Adj Close separate - actions=False # Don't include dividends/splits in main DataFrame - ) - - if df.empty: - raise ValueError(f"No data returned for ticker: {ticker}") - - # Reset index to make Date a column - df.reset_index(inplace=True) - - # Standardize column names - df = standardize_dataframe(df, 'yahoo') - - # Cache result - if self.use_cache: - self.cache.set('yahoo', cache_id, df) - - return df - - except Exception as e: - handle_api_error('Yahoo', e, ticker) - raise - - def get_info(self, ticker: str) -> dict: - """ - Get ticker information/metadata. - - Args: - ticker: Stock ticker - - Returns: - Dictionary with ticker information - """ - try: - ticker_obj = yf.Ticker(ticker) - return ticker_obj.info - except Exception as e: - handle_api_error('Yahoo', e, ticker) - return {} - - def fetch_multiple(self, tickers: list, start_date: Optional[str] = None, - end_date: Optional[str] = None, interval: str = '1d') -> dict: - """ - Fetch multiple tickers. - - Args: - tickers: List of ticker symbols - start_date: Start date - end_date: End date - interval: Data interval - - Returns: - Dictionary mapping ticker -> DataFrame - """ - results = {} - - for ticker in tickers: - try: - df = self.fetch(ticker, start_date, end_date, interval) - results[ticker] = df - except Exception as e: - print(f"[Yahoo] Skipping {ticker}: {e}") - continue - - return results - - -def fetch_yahoo(ticker: str, start_date: Optional[str] = None, - end_date: Optional[str] = None, interval: str = '1d', - use_cache: bool = True) -> pd.DataFrame: - """ - Convenience function to fetch data from Yahoo Finance. - - Args: - ticker: Stock ticker - start_date: Start date - end_date: End date - interval: Data interval ('1d', '1wk', '1mo') - use_cache: Whether to use caching - - Returns: - DataFrame with market data - """ - fetcher = YahooFetcher(use_cache=use_cache) - return fetcher.fetch(ticker, start_date, end_date, interval) - - -if __name__ == '__main__': - # Test examples - if not YFINANCE_AVAILABLE: - print("yfinance not available. Install with: pip install yfinance") - else: - print("Testing Yahoo Finance fetcher...") - - # Test 1: US stock - print("\n1. Fetching AAPL (US stock):") - try: - df = fetch_yahoo('AAPL', start_date='20240101', end_date='20241231') - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 2: Index - print("\n2. Fetching ^GSPC (S&P 500):") - try: - df = fetch_yahoo('^GSPC', start_date='20240101') - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") - - # Test 3: Polish stock on WSE - print("\n3. Fetching PKO.WA (PKO on Warsaw Stock Exchange):") - try: - df = fetch_yahoo('PKO.WA', start_date='20240101') - print(f" Retrieved {len(df)} rows") - print(df.head()) - except Exception as e: - print(f" Error: {e}") diff --git a/claude/skills/quant/market-datasets/scripts/fetch_yahoo_direct.py b/claude/skills/quant/market-datasets/scripts/fetch_yahoo_direct.py deleted file mode 100644 index d050e444..00000000 --- a/claude/skills/quant/market-datasets/scripts/fetch_yahoo_direct.py +++ /dev/null @@ -1,368 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# ] -# /// -""" -Yahoo Finance Direct API fetcher. - -Bypasses yfinance library and uses direct API calls to avoid rate limiting issues. -Supports ISIN-to-ticker conversion via Yahoo search API. -Fetches prices, dividends, and splits. - -Usage: - uv run fetch_yahoo_direct.py XTB.WA 2024-01-01 2024-12-31 - uv run fetch_yahoo_direct.py PLXTRDM00011 2024-01-01 # ISIN - uv run fetch_yahoo_direct.py # Run self-tests - -Module usage: - from fetch_yahoo_direct import YahooDirectFetcher, fetch_by_isin - - # By ticker - fetcher = YahooDirectFetcher() - prices, dividends, splits = fetcher.fetch('XTB.WA', '2024-01-01', '2025-01-01') - - # By ISIN (auto-converts to ticker) - prices, dividends, splits, mapping = fetch_by_isin( - ['PLXTRDM00011', 'US0378331005'], - start_date='2024-01-01', - end_date='2025-01-01' - ) -""" - -import requests -import pandas as pd -from typing import Optional, Tuple -from datetime import datetime -import time - - -class YahooDirectFetcher: - """Fetcher using Yahoo Finance direct API (bypasses yfinance library).""" - - BASE_URL = 'https://query1.finance.yahoo.com/v8/finance/chart' - SEARCH_URL = 'https://query2.finance.yahoo.com/v1/finance/search' - HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'} - - def __init__(self, delay: float = 0.5): - """ - Initialize fetcher. - - Args: - delay: Delay between requests in seconds (rate limiting) - """ - self.delay = delay - self._last_request = 0 - - def _rate_limit(self): - """Apply rate limiting between requests.""" - elapsed = time.time() - self._last_request - if elapsed < self.delay: - time.sleep(self.delay - elapsed) - self._last_request = time.time() - - def isin_to_ticker(self, isin: str) -> Optional[str]: - """ - Convert ISIN to Yahoo Finance ticker using search API. - - Args: - isin: ISIN code (e.g., 'PLXTRDM00011') - - Returns: - Yahoo Finance ticker (e.g., 'XTB.WA') or None if not found - """ - self._rate_limit() - - try: - resp = requests.get( - self.SEARCH_URL, - params={'q': isin, 'quotesCount': 5}, - headers=self.HEADERS, - timeout=10 - ) - data = resp.json() - - if data.get('quotes'): - # Return first result's symbol - return data['quotes'][0]['symbol'] - except Exception as e: - print(f"[Yahoo Direct] Error searching for {isin}: {e}") - - return None - - def fetch( - self, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - include_events: bool = True - ) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]: - """ - Fetch price data, dividends, and splits from Yahoo Finance. - - Args: - ticker: Yahoo Finance ticker symbol (e.g., 'XTB.WA', 'AAPL') - start_date: Start date (YYYY-MM-DD), None for 1 year ago - end_date: End date (YYYY-MM-DD), None for today - include_events: Whether to fetch dividends and splits - - Returns: - Tuple of (prices_df, dividends_df, splits_df) - """ - self._rate_limit() - - # Convert dates to timestamps - if start_date: - start_ts = int(datetime.strptime(start_date, '%Y-%m-%d').timestamp()) - else: - start_ts = int((datetime.now().timestamp()) - 365 * 24 * 60 * 60) - - if end_date: - end_ts = int(datetime.strptime(end_date, '%Y-%m-%d').timestamp()) + 86400 - else: - end_ts = int(datetime.now().timestamp()) + 86400 - - params = { - 'period1': start_ts, - 'period2': end_ts, - 'interval': '1d', - } - if include_events: - params['events'] = 'div,splits' - - try: - resp = requests.get( - f'{self.BASE_URL}/{ticker}', - params=params, - headers=self.HEADERS, - timeout=15 - ) - data = resp.json() - - if 'chart' not in data or not data['chart']['result']: - return pd.DataFrame(), pd.DataFrame(), pd.DataFrame() - - result = data['chart']['result'][0] - - # Parse prices - timestamps = result.get('timestamp', []) - if not timestamps: - return pd.DataFrame(), pd.DataFrame(), pd.DataFrame() - - quotes = result['indicators']['quote'][0] - - prices_df = pd.DataFrame({ - 'date': pd.to_datetime(timestamps, unit='s'), - 'open': quotes.get('open'), - 'high': quotes.get('high'), - 'low': quotes.get('low'), - 'close': quotes.get('close'), - 'volume': quotes.get('volume') - }) - - # Adjusted close - if 'adjclose' in result['indicators']: - prices_df['adj_close'] = result['indicators']['adjclose'][0]['adjclose'] - - # Parse events - events = result.get('events', {}) - - # Dividends - dividends = [] - if 'dividends' in events: - for ts, div_data in events['dividends'].items(): - dividends.append({ - 'date': pd.to_datetime(int(ts), unit='s'), - 'dividend': div_data['amount'] - }) - dividends_df = pd.DataFrame(dividends) if dividends else pd.DataFrame() - - # Splits - splits = [] - if 'splits' in events: - for ts, split_data in events['splits'].items(): - splits.append({ - 'date': pd.to_datetime(int(ts), unit='s'), - 'numerator': split_data['numerator'], - 'denominator': split_data['denominator'], - 'ratio': split_data['numerator'] / split_data['denominator'] - }) - splits_df = pd.DataFrame(splits) if splits else pd.DataFrame() - - return prices_df, dividends_df, splits_df - - except Exception as e: - print(f"[Yahoo Direct] Error fetching {ticker}: {e}") - return pd.DataFrame(), pd.DataFrame(), pd.DataFrame() - - def fetch_prices_only( - self, - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None - ) -> pd.DataFrame: - """ - Fetch only price data (no dividends/splits). - - Args: - ticker: Yahoo Finance ticker symbol - start_date: Start date (YYYY-MM-DD) - end_date: End date (YYYY-MM-DD) - - Returns: - DataFrame with OHLCV data - """ - prices, _, _ = self.fetch(ticker, start_date, end_date, include_events=False) - return prices - - -def fetch_by_isin( - isins: list, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - delay: float = 0.5 -) -> Tuple[dict, dict, dict, dict]: - """ - Fetch prices and dividends for multiple ISINs. - - Automatically converts ISINs to Yahoo Finance tickers using search API. - - Args: - isins: List of ISIN codes - start_date: Start date (YYYY-MM-DD) - end_date: End date (YYYY-MM-DD) - delay: Delay between requests in seconds - - Returns: - Tuple of (prices_dict, dividends_dict, splits_dict, isin_to_ticker_mapping) - Each dict is keyed by ISIN. - """ - fetcher = YahooDirectFetcher(delay=delay) - - prices = {} - dividends = {} - splits = {} - isin_to_ticker = {} - - for i, isin in enumerate(isins): - print(f"[{i+1}/{len(isins)}] Processing {isin}...", end=' ') - - # Convert ISIN to ticker - ticker = fetcher.isin_to_ticker(isin) - if not ticker: - print("NOT FOUND") - continue - - isin_to_ticker[isin] = ticker - print(f"-> {ticker}", end=' ') - - # Fetch data - p, d, s = fetcher.fetch(ticker, start_date, end_date) - - if not p.empty: - p['isin'] = isin - p['ticker'] = ticker - prices[isin] = p - print(f"({len(p)} prices", end='') - else: - print("(NO DATA", end='') - - if not d.empty: - d['isin'] = isin - d['ticker'] = ticker - dividends[isin] = d - print(f", {len(d)} divs", end='') - - if not s.empty: - s['isin'] = isin - s['ticker'] = ticker - splits[isin] = s - print(f", {len(s)} splits", end='') - - print(")") - - return prices, dividends, splits, isin_to_ticker - - -def save_isin_data( - isins: list, - output_dir: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None -) -> None: - """ - Fetch data for ISINs and save to Excel files. - - Args: - isins: List of ISIN codes - output_dir: Directory to save output files - start_date: Start date (YYYY-MM-DD) - end_date: End date (YYYY-MM-DD) - - Creates: - - {output_dir}/prices.xlsx - - {output_dir}/dividends.xlsx - - {output_dir}/splits.xlsx (if any) - - {output_dir}/isin_ticker_mapping.xlsx - """ - import os - os.makedirs(output_dir, exist_ok=True) - - prices, dividends, splits, mapping = fetch_by_isin(isins, start_date, end_date) - - # Combine and save prices - if prices: - prices_df = pd.concat(prices.values(), ignore_index=True) - prices_df.to_excel(f'{output_dir}/prices.xlsx', index=False) - print(f"Saved prices: {len(prices_df)} rows, {len(prices)} ISINs") - - # Combine and save dividends - if dividends: - divs_df = pd.concat(dividends.values(), ignore_index=True) - divs_df.to_excel(f'{output_dir}/dividends.xlsx', index=False) - print(f"Saved dividends: {len(divs_df)} rows") - - # Combine and save splits - if splits: - splits_df = pd.concat(splits.values(), ignore_index=True) - splits_df.to_excel(f'{output_dir}/splits.xlsx', index=False) - print(f"Saved splits: {len(splits_df)} rows") - - # Save mapping - mapping_df = pd.DataFrame(list(mapping.items()), columns=['isin', 'ticker']) - mapping_df.to_excel(f'{output_dir}/isin_ticker_mapping.xlsx', index=False) - print(f"Saved mapping: {len(mapping_df)} ISINs") - - -if __name__ == '__main__': - print("Testing Yahoo Finance Direct API fetcher...") - - # Test 1: Single ticker - print("\n1. Fetching XTB.WA (Polish stock):") - fetcher = YahooDirectFetcher() - prices, divs, splits = fetcher.fetch('XTB.WA', '2024-01-01', '2025-01-01') - print(f" Prices: {len(prices)} rows") - print(f" Dividends: {len(divs)} rows") - print(f" Splits: {len(splits)} rows") - if not prices.empty: - print(prices.tail()) - - # Test 2: ISIN lookup - print("\n2. ISIN to ticker conversion:") - ticker = fetcher.isin_to_ticker('PLXTRDM00011') - print(f" PLXTRDM00011 -> {ticker}") - - # Test 3: Multiple ISINs - print("\n3. Fetching multiple ISINs:") - test_isins = ['PLXTRDM00011', 'US0378331005'] - prices, divs, splits, mapping = fetch_by_isin( - test_isins, - start_date='2024-01-01', - end_date='2024-12-31' - ) - print(f"\nMapping: {mapping}") - print(f"Prices fetched for: {list(prices.keys())}") - print(f"Dividends fetched for: {list(divs.keys())}") diff --git a/claude/skills/quant/market-datasets/scripts/migrate_to_project.py b/claude/skills/quant/market-datasets/scripts/migrate_to_project.py deleted file mode 100644 index 660950fe..00000000 --- a/claude/skills/quant/market-datasets/scripts/migrate_to_project.py +++ /dev/null @@ -1,187 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "click>=8.0", -# ] -# /// -""" -Migrate a data source fetcher from skill to production project. - -This script copies fetcher scripts to your project directory, -making them available for production use. - -Usage: - 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 -""" - -import shutil -import sys -from pathlib import Path -from typing import List, Dict - -# Script directory -SKILL_DIR = Path(__file__).parent - -# Source to file mapping -SOURCE_MAP: Dict[str, List[str]] = { - 'eodhd': ['fetch_eodhd.py'], - 'yahoo': ['fetch_yahoo.py'], - 'yahoo-direct': ['fetch_yahoo_direct.py'], - 'nbp': ['fetch_nbp.py'], - 'fred': ['fetch_fred.py'], - 'tiingo': ['fetch_tiingo.py'], - 'ccxt': ['fetch_ccxt.py'], - 'pandas-datareader': ['fetch_pandas_datareader.py'], - 'registry': ['ticker_registry.py'], - 'unified': ['fetch_unified.py'], - 'all': [ - 'fetch_unified.py', - 'fetch_eodhd.py', - 'fetch_yahoo.py', - 'fetch_yahoo_direct.py', - 'fetch_nbp.py', - 'fetch_fred.py', - 'fetch_tiingo.py', - 'fetch_ccxt.py', - 'fetch_pandas_datareader.py', - 'ticker_registry.py', - 'utils.py', - ], -} - -# API keys required by each source -ENV_KEYS: Dict[str, List[str]] = { - 'tiingo': ['TIINGO_API_KEY'], - 'fred': ['FRED_API_KEY'], - 'eodhd': ['EODHD_API_KEY'], - 'all': ['TIINGO_API_KEY', 'FRED_API_KEY', 'EODHD_API_KEY'], -} - - -def list_sources(): - """Print available sources.""" - print("Available sources:\n") - for source, files in SOURCE_MAP.items(): - print(f" {source:20} -> {', '.join(files)}") - print("\nUsage: uv run migrate_to_project.py --target ") - - -def migrate(source: str, target: str, include_utils: bool, include_env: bool): - """Migrate data source fetcher to project directory.""" - if source not in SOURCE_MAP: - print(f"Error: Unknown source '{source}'") - print("Use --list to see available sources.") - sys.exit(1) - - target_dir = Path(target) - target_dir.mkdir(parents=True, exist_ok=True) - - files = SOURCE_MAP[source].copy() - - # Add utils.py if requested and not already included - if include_utils and 'utils.py' not in files: - files.append('utils.py') - - print(f"Migrating '{source}' to {target_dir}/\n") - - copied_files = [] - for filename in files: - src = SKILL_DIR / filename - dst = target_dir / filename - - if not src.exists(): - print(f" Warning: {src} not found, skipping") - continue - - print(f" Copying {filename}") - shutil.copy2(src, dst) - copied_files.append(filename) - - # Create .env.example if requested - if include_env: - env_keys = ENV_KEYS.get(source, []) - if env_keys: - env_template = target_dir / '.env.example' - env_content = "# API Keys for market data fetchers\n" - env_content += "# Copy to .env and fill in your keys\n\n" - for key in env_keys: - env_content += f"{key}=\n" - env_template.write_text(env_content) - print(f" Created .env.example") - copied_files.append('.env.example') - - # Also copy data files for registry - if source in ['registry', 'all', 'unified']: - data_dir = SKILL_DIR.parent / 'data' - if data_dir.exists(): - target_data_dir = target_dir / 'data' - target_data_dir.mkdir(exist_ok=True) - for data_file in data_dir.glob('*.csv'): - dst = target_data_dir / data_file.name - shutil.copy2(data_file, dst) - print(f" Copying data/{data_file.name}") - - print(f"\n{len(copied_files)} file(s) migrated to {target_dir}/") - print(f"\nTo use, run:") - print(f" uv run {target_dir}/{copied_files[0]} --help") - - if include_utils: - print(f"\nNote: utils.py included. Scripts can import shared utilities.") - - -def main(): - """Main entry point.""" - # Simple argument parsing without click (for minimal dependencies) - args = sys.argv[1:] - - if not args or '--help' in args or '-h' in args: - print(__doc__) - sys.exit(0) - - if '--list' in args: - list_sources() - sys.exit(0) - - # Parse arguments - source = None - target = None - include_utils = '--include-utils' in args - include_env = '--include-env' in args - - i = 0 - while i < len(args): - arg = args[i] - if arg in ['--include-utils', '--include-env']: - i += 1 - continue - elif arg in ['--target', '-t']: - if i + 1 < len(args): - target = args[i + 1] - i += 2 - else: - print("Error: --target requires a value") - sys.exit(1) - elif not source and not arg.startswith('-'): - source = arg - i += 1 - else: - i += 1 - - if not source: - print("Error: Source name required") - print("Use --list to see available sources.") - sys.exit(1) - - if not target: - print("Error: --target required") - sys.exit(1) - - migrate(source, target, include_utils, include_env) - - -if __name__ == "__main__": - main() diff --git a/claude/skills/quant/market-datasets/scripts/ticker_registry.py b/claude/skills/quant/market-datasets/scripts/ticker_registry.py deleted file mode 100644 index 7fbfc9ec..00000000 --- a/claude/skills/quant/market-datasets/scripts/ticker_registry.py +++ /dev/null @@ -1,575 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "requests>=2.28", -# ] -# /// -""" -Ticker Registry - Security master and cross-source ticker mapping service. - -Provides unified lookup for converting between different ticker formats -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 bloomberg - uv run ticker_registry.py discover PLXTRDM00011 US0378331005 - uv run ticker_registry.py # Run self-tests - -Module usage: - from ticker_registry import TickerRegistry, convert_ticker, isin_to_yahoo - - # Initialize registry - registry = TickerRegistry() - - # Convert ISIN to Yahoo ticker - yahoo_ticker = registry.isin_to_ticker('PLXTRDM00011', source='yahoo') # 'XTB.WA' - - # Convert any ticker to another format - bbg_ticker = registry.convert_ticker('^MWIG40', to_source='bloomberg') # 'MWIG40 Index' - - # Auto-discover missing Yahoo tickers - discovered = registry.discover_missing_yahoo_tickers(['PLXTRDM00011']) -""" - -from typing import Optional, Dict, List, Literal -from pathlib import Path -from dataclasses import dataclass, field -from datetime import datetime -import pandas as pd -import csv - -# Type definitions -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'] - - -@dataclass -class Security: - """Represents a security/instrument with all its identifiers and metadata.""" - uid: str = "" # Universal ID - primary key (e.g., isin_PLXTRDM00011, idx_WIG20, fx_USDPLN) - isin: Optional[str] = None - name: str = "" - instrument_type: InstrumentType = "equity" - country: str = "" - exchange: str = "" - tickers: Dict[str, Optional[str]] = field(default_factory=dict) - 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: - """Return uid as primary key.""" - return self.uid - - def get_ticker(self, source: SourceType) -> Optional[str]: - """Get ticker for specific source.""" - return self.tickers.get(source) - - def to_dict(self) -> dict: - """Convert to dictionary for CSV export.""" - return { - 'uid': self.uid, - 'isin': self.isin or '', - 'name': self.name, - 'instrument_type': self.instrument_type, - 'country': self.country, - 'exchange': self.exchange, - 'ticker_bloomberg': self.tickers.get('bloomberg', ''), - 'ticker_yahoo': self.tickers.get('yahoo', ''), - **{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', ''), - 'mapping_source': self.mapping_source, - 'last_updated': self.last_updated.isoformat() if self.last_updated else '' - } - - @classmethod - def from_dict(cls, d: dict) -> 'Security': - """Create Security from dictionary (CSV row).""" - tickers = {} - for source in ['bloomberg', 'yahoo', 'fred']: - key = f'ticker_{source}' - if d.get(key): - tickers[source] = d[key] - - metadata = {} - if d.get('sector'): - metadata['sector'] = d['sector'] - if d.get('currency'): - metadata['currency'] = d['currency'] - - last_updated = None - if d.get('last_updated'): - try: - last_updated = datetime.fromisoformat(d['last_updated']) - except ValueError: - pass - - return cls( - uid=d.get('uid', ''), - isin=d.get('isin') or None, - name=d.get('name', ''), - instrument_type=d.get('instrument_type', 'equity'), - country=d.get('country', ''), - exchange=d.get('exchange', ''), - tickers=tickers, - metadata=metadata, - last_updated=last_updated, - mapping_source=d.get('mapping_source', 'csv'), - legacy={col: d[col] for col in LEGACY_COLUMNS if d.get(col)}, - ) - - -class TickerRegistry: - """ - Central registry for security master data and ticker mappings. - - Features: - - Load from CSV security_master file - - Auto-discover Yahoo tickers via ISIN lookup - - Bidirectional lookup: ISIN -> ticker or ticker -> ISIN - - Single CSV file as both master and cache - """ - - # 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', - 'sector', 'currency', 'mapping_source', 'last_updated' - ] - - def __init__( - self, - csv_path: Optional[Path] = None, - auto_discover: bool = True - ): - """ - Initialize registry. - - Args: - csv_path: Path to security_master.csv (default: skill data directory) - auto_discover: Whether to auto-lookup missing Yahoo tickers - """ - if csv_path is None: - # Default to skill's data directory - csv_path = Path(__file__).parent.parent / 'data' / 'security_master.csv' - self.csv_path = Path(csv_path) - self.auto_discover = auto_discover - - # In-memory stores - self._securities: Dict[str, Security] = {} # primary_key -> Security - self._ticker_index: Dict[str, str] = {} # any_ticker -> primary_key - - # Load data - self._load() - - # === Core Lookup Methods === - - def get_security(self, identifier: str) -> Optional[Security]: - """ - Get security by any identifier (uid, ISIN, ticker from any source). - - Args: - identifier: uid, ISIN, or any ticker format - - Returns: - Security object or None if not found - """ - # Try direct uid lookup - if identifier in self._securities: - return self._securities[identifier] - - # Try ISIN format (convert to uid) - if self._looks_like_isin(identifier): - uid = f"isin_{identifier}" - if uid in self._securities: - return self._securities[uid] - - # Try ticker index (uppercase) - primary_key = self._ticker_index.get(identifier.upper()) - if primary_key: - return self._securities.get(primary_key) - - return None - - def convert_ticker( - self, - ticker: str, - from_source: Optional[SourceType] = None, - to_source: SourceType = 'yahoo' - ) -> Optional[str]: - """ - Convert ticker from one source format to another. - - Args: - ticker: Input ticker - from_source: Source format (auto-detected if None) - to_source: Target format - - Returns: - Converted ticker or None if conversion not possible - """ - security = self.get_security(ticker) - if not security: - # Try auto-discovery if looks like ISIN - if self.auto_discover and self._looks_like_isin(ticker): - security = self._discover_from_isin(ticker) - - if security: - return security.get_ticker(to_source) - return None - - def isin_to_ticker(self, isin: str, source: SourceType = 'yahoo') -> Optional[str]: - """ - Convert ISIN to ticker for specified source. - - Args: - isin: ISIN code - source: Target source - - Returns: - Ticker or None - """ - return self.convert_ticker(isin, from_source=None, to_source=source) - - def ticker_to_isin(self, ticker: str) -> Optional[str]: - """ - Get ISIN for a ticker. - - Args: - ticker: Any ticker format - - Returns: - ISIN or None - """ - security = self.get_security(ticker) - return security.isin if security else None - - def get_all_tickers(self, source: SourceType) -> Dict[str, str]: - """ - Get all ticker mappings for a source. - - Args: - source: Source name - - Returns: - Dict mapping primary_key -> ticker - """ - return { - pk: sec.get_ticker(source) - for pk, sec in self._securities.items() - if sec.get_ticker(source) - } - - # === Batch Operations === - - def convert_tickers_batch( - self, - tickers: List[str], - to_source: SourceType = 'yahoo' - ) -> Dict[str, Optional[str]]: - """ - Convert multiple tickers to target source format. - - Args: - tickers: List of input tickers - to_source: Target source - - Returns: - Dict mapping input_ticker -> converted_ticker - """ - return {t: self.convert_ticker(t, to_source=to_source) for t in tickers} - - def discover_missing_yahoo_tickers( - self, - isins: Optional[List[str]] = None - ) -> Dict[str, str]: - """ - Auto-discover Yahoo tickers for ISINs without mappings. - - Args: - isins: Specific ISINs to lookup (None = all missing in registry) - - Returns: - Dict of newly discovered ISIN -> Yahoo ticker mappings - """ - if isins is None: - # Find securities with ISIN but no Yahoo ticker - isins = [ - sec.isin for sec in self._securities.values() - if sec.isin and not sec.get_ticker('yahoo') - ] - - discovered = {} - for isin in isins: - yahoo_ticker = self._lookup_yahoo_ticker(isin) - if yahoo_ticker: - discovered[isin] = yahoo_ticker - uid = f"isin_{isin}" - # Update in-memory if exists - if uid in self._securities: - self._securities[uid].tickers['yahoo'] = yahoo_ticker - self._securities[uid].last_updated = datetime.now() - self._securities[uid].mapping_source = 'yahoo_api' - self._ticker_index[yahoo_ticker.upper()] = uid - else: - # Create new security - security = self._create_security_from_discovery(isin, yahoo_ticker) - self.register_security(security) - - # Persist to CSV - if discovered: - self._save() - - return discovered - - # === Registration Methods === - - def register_security(self, security: Security) -> None: - """ - Add or update a security in the registry. - - Args: - security: Security object to register - """ - uid = security.uid - if not uid: - raise ValueError("Security must have uid") - - self._securities[uid] = security - - # Build ticker index - also index by ISIN if present - if security.isin: - self._ticker_index[security.isin] = uid - - # Index all tickers - for source, ticker in security.tickers.items(): - if ticker: - self._ticker_index[ticker.upper()] = uid - - def add_ticker_mapping( - self, - identifier: str, - source: SourceType, - ticker: str, - persist: bool = True - ) -> bool: - """ - Add a ticker mapping for an existing security. - - Args: - identifier: ISIN or primary key - source: Source name - ticker: New ticker value - persist: Whether to save to CSV - - Returns: - True if mapping added successfully - """ - security = self.get_security(identifier) - if not security: - return False - - security.tickers[source] = ticker - security.last_updated = datetime.now() - self._ticker_index[ticker.upper()] = security.primary_key - - if persist: - self._save() - - return True - - # === Data Loading/Saving === - - def _load(self) -> None: - """Load data from CSV file.""" - if not self.csv_path.exists(): - print(f"[TickerRegistry] No CSV found at {self.csv_path}, starting empty") - return - - try: - with open(self.csv_path, 'r', encoding='utf-8', newline='') as f: - reader = csv.DictReader(f) - for row in reader: - security = Security.from_dict(row) - if security.primary_key: - self.register_security(security) - - print(f"[TickerRegistry] Loaded {len(self._securities)} securities from {self.csv_path}") - - except Exception as e: - print(f"[TickerRegistry] Error loading CSV: {e}") - - def _save(self) -> None: - """Save current state to CSV file.""" - # Ensure directory exists - self.csv_path.parent.mkdir(parents=True, exist_ok=True) - - try: - with open(self.csv_path, 'w', encoding='utf-8', newline='') as f: - writer = csv.DictWriter(f, fieldnames=self.CSV_COLUMNS) - writer.writeheader() - - for security in self._securities.values(): - writer.writerow(security.to_dict()) - - print(f"[TickerRegistry] Saved {len(self._securities)} securities to {self.csv_path}") - - except Exception as e: - print(f"[TickerRegistry] Error saving CSV: {e}") - - # === Yahoo API Integration === - - def _lookup_yahoo_ticker(self, isin: str) -> Optional[str]: - """ - Lookup Yahoo ticker via Yahoo search API. - - Uses YahooDirectFetcher.isin_to_ticker() internally. - """ - try: - from fetch_yahoo_direct import YahooDirectFetcher - fetcher = YahooDirectFetcher(delay=0.5) - ticker = fetcher.isin_to_ticker(isin) - if ticker: - print(f"[TickerRegistry] Discovered {isin} -> {ticker}") - return ticker - except Exception as e: - print(f"[TickerRegistry] Yahoo lookup failed for {isin}: {e}") - return None - - def _discover_from_isin(self, isin: str) -> Optional[Security]: - """ - Create new security entry from ISIN via Yahoo lookup. - """ - yahoo_ticker = self._lookup_yahoo_ticker(isin) - if not yahoo_ticker: - return None - - security = self._create_security_from_discovery(isin, yahoo_ticker) - self.register_security(security) - self._save() - - return security - - def _create_security_from_discovery(self, isin: str, yahoo_ticker: str) -> Security: - """Create Security object from ISIN and discovered Yahoo ticker.""" - return Security( - uid=f"isin_{isin}", - isin=isin, - name=f"[Auto] {yahoo_ticker}", - instrument_type=self._infer_type_from_ticker(yahoo_ticker), - country=isin[:2] if len(isin) >= 2 else '', - exchange=self._infer_exchange_from_ticker(yahoo_ticker), - tickers={'yahoo': yahoo_ticker}, - mapping_source='yahoo_api', - last_updated=datetime.now() - ) - - # === Helper Methods === - - def _looks_like_isin(self, s: str) -> bool: - """Check if string looks like an ISIN (2 letters + 10 alphanumeric).""" - return len(s) == 12 and s[:2].isalpha() and s[2:].isalnum() - - def _infer_type_from_ticker(self, yahoo_ticker: str) -> InstrumentType: - """Infer instrument type from Yahoo ticker format.""" - if yahoo_ticker.startswith('^'): - return 'index' - if '=X' in yahoo_ticker: - return 'currency' - return 'equity' - - def _infer_exchange_from_ticker(self, yahoo_ticker: str) -> str: - """Infer exchange from Yahoo ticker suffix.""" - if '.WA' in yahoo_ticker: - return 'WSE' - if '.L' in yahoo_ticker: - return 'LSE' - if '.DE' in yahoo_ticker: - return 'XETRA' - if '.' not in yahoo_ticker: - return 'NYSE/NASDAQ' - return '' - - # === Export Methods === - - def to_dataframe(self) -> pd.DataFrame: - """Export registry to DataFrame.""" - records = [sec.to_dict() for sec in self._securities.values()] - return pd.DataFrame(records, columns=self.CSV_COLUMNS) - - def export_to_csv(self, path: Path) -> None: - """Export registry to a different CSV file.""" - df = self.to_dataframe() - df.to_csv(path, index=False) - - def __len__(self) -> int: - return len(self._securities) - - def __repr__(self) -> str: - return f"TickerRegistry({len(self._securities)} securities)" - - -# === Module-level convenience functions === - -_default_registry: Optional[TickerRegistry] = None - - -def get_default_registry() -> TickerRegistry: - """Get or create default registry instance.""" - global _default_registry - if _default_registry is None: - _default_registry = TickerRegistry() - return _default_registry - - -def convert_ticker(ticker: str, to_source: SourceType = 'yahoo') -> Optional[str]: - """Quick ticker conversion using default registry.""" - return get_default_registry().convert_ticker(ticker, to_source=to_source) - - -def isin_to_yahoo(isin: str) -> Optional[str]: - """Convert ISIN to Yahoo ticker.""" - return get_default_registry().isin_to_ticker(isin, source='yahoo') - - -def ticker_to_isin(ticker: str) -> Optional[str]: - """Get ISIN for any ticker.""" - return get_default_registry().ticker_to_isin(ticker) - - -if __name__ == '__main__': - print("Testing TickerRegistry...") - - # Create registry - registry = TickerRegistry() - print(f"Loaded: {registry}") - - # Test ISIN discovery - print("\nTesting ISIN discovery...") - discovered = registry.discover_missing_yahoo_tickers(['PLXTRDM00011', 'PLCCC0000016']) - print(f"Discovered: {discovered}") - - # Test lookups - print("\nTesting lookups...") - for isin in ['PLXTRDM00011', 'PLCCC0000016']: - yahoo = registry.isin_to_ticker(isin, 'yahoo') - print(f" {isin} -> Yahoo: {yahoo}") - - # Export - print("\nExporting to DataFrame...") - df = registry.to_dataframe() - print(df) diff --git a/claude/skills/quant/market-datasets/scripts/utils.py b/claude/skills/quant/market-datasets/scripts/utils.py deleted file mode 100644 index 3997d687..00000000 --- a/claude/skills/quant/market-datasets/scripts/utils.py +++ /dev/null @@ -1,363 +0,0 @@ -#!/usr/bin/env python3 -# /// script -# requires-python = ">=3.11" -# dependencies = [ -# "pandas>=2.0", -# "python-dotenv>=1.0", -# ] -# /// -""" -Shared utilities for market data fetchers. - -Provides caching, date handling, rate limiting, error handling, -and environment variable loading for all data source implementations. - -Usage: - uv run utils.py # Run self-tests -""" - -import json -import os -import time -from datetime import datetime, date -from pathlib import Path -from typing import Optional, Union, Dict -import pandas as pd - -# Load .env file for API keys -try: - from dotenv import load_dotenv - - # Search for .env in multiple locations - for env_path in [ - Path(__file__).parent.parent - / ".env", # Skill root (.claude/skills/market-datasets/.env) - Path.cwd() / ".env", # Current working directory - Path.home() / ".env", # Home directory (fallback) - ]: - if env_path.exists(): - load_dotenv(env_path) - break -except ImportError: - pass # python-dotenv not installed, rely on system env vars - - -def get_api_key(key_name: str, default: Optional[str] = None) -> Optional[str]: - """ - Get API key from environment variables (loaded from .env or system). - - Args: - key_name: Name of environment variable (e.g., 'TIINGO_API_KEY') - default: Default value if not found - - Returns: - API key value or default - """ - return os.getenv(key_name, default) - - -class CacheManager: - """Manages file-based caching for market data.""" - - def __init__(self, cache_dir: str = "data/cache/market_data"): - """ - Initialize cache manager. - - Args: - cache_dir: Base directory for cache storage - """ - self.cache_dir = Path(cache_dir) - self.cache_dir.mkdir(parents=True, exist_ok=True) - - def get_cache_path(self, source: str, identifier: str, format: str = "csv") -> Path: - """ - Get cache file path for a data request. - - Args: - source: Data source name (nbp, yahoo, eodhd, fred, ...) - identifier: Unique identifier (e.g., ticker_start_end) - format: File format (csv, json) - - Returns: - Path to cache file - """ - source_dir = self.cache_dir / source - source_dir.mkdir(exist_ok=True) - return source_dir / f"{identifier}.{format}" - - def get( - self, - source: str, - identifier: str, - format: str = "csv", - max_age_hours: Optional[int] = None, - ) -> Optional[Union[pd.DataFrame, Dict]]: - """ - Retrieve cached data if available and not expired. - - Args: - source: Data source name - identifier: Unique identifier - format: File format - max_age_hours: Maximum cache age in hours (None = no expiry) - - Returns: - Cached data or None if not found/expired - """ - cache_path = self.get_cache_path(source, identifier, format) - - if not cache_path.exists(): - return None - - # Check age - if max_age_hours is not None: - file_age = time.time() - cache_path.stat().st_mtime - if file_age > max_age_hours * 3600: - return None - - try: - if format == "csv": - return pd.read_csv( - cache_path, - parse_dates=["Date"] - if "Date" in pd.read_csv(cache_path, nrows=0).columns - else None, - ) - elif format == "json": - with open(cache_path, "r", encoding="utf-8") as f: - return json.load(f) - except Exception as e: - print(f"Error reading cache: {e}") - return None - - def set( - self, - source: str, - identifier: str, - data: Union[pd.DataFrame, Dict], - format: str = "csv", - ) -> None: - """ - Store data in cache. - - Args: - source: Data source name - identifier: Unique identifier - data: Data to cache - format: File format - """ - cache_path = self.get_cache_path(source, identifier, format) - - try: - if format == "csv" and isinstance(data, pd.DataFrame): - data.to_csv(cache_path, index=False) - elif format == "json" and isinstance(data, dict): - with open(cache_path, "w", encoding="utf-8") as f: - json.dump(data, f, indent=2, ensure_ascii=False) - except Exception as e: - print(f"Error writing cache: {e}") - - -class RateLimiter: - """Simple rate limiter with delay between requests.""" - - def __init__(self, min_delay_seconds: float = 1.0): - """ - Initialize rate limiter. - - Args: - min_delay_seconds: Minimum delay between requests - """ - self.min_delay = min_delay_seconds - self.last_request_time = {} - - def wait(self, source: str) -> None: - """ - Wait if necessary to respect rate limit for a source. - - Args: - source: Data source name - """ - if source in self.last_request_time: - elapsed = time.time() - self.last_request_time[source] - if elapsed < self.min_delay: - time.sleep(self.min_delay - elapsed) - - self.last_request_time[source] = time.time() - - -def normalize_date(dt: Union[str, date, datetime, pd.Timestamp]) -> str: - """ - Normalize date to YYYYMMDD format. - - Args: - dt: Date in various formats - - Returns: - Date string in YYYYMMDD format - """ - if isinstance(dt, str): - # Try parsing common formats - for fmt in ["%Y-%m-%d", "%Y%m%d", "%d-%m-%Y", "%m/%d/%Y"]: - try: - parsed = datetime.strptime(dt, fmt) - return parsed.strftime("%Y%m%d") - except ValueError: - continue - raise ValueError(f"Unable to parse date: {dt}") - elif isinstance(dt, (date, datetime, pd.Timestamp)): - return dt.strftime("%Y%m%d") - else: - raise TypeError(f"Unsupported date type: {type(dt)}") - - -def normalize_date_display(dt: Union[str, date, datetime, pd.Timestamp]) -> str: - """ - Normalize date to YYYY-MM-DD format for display. - - Args: - dt: Date in various formats - - Returns: - Date string in YYYY-MM-DD format - """ - yyyymmdd = normalize_date(dt) - return f"{yyyymmdd[:4]}-{yyyymmdd[4:6]}-{yyyymmdd[6:]}" - - -def standardize_dataframe(df: pd.DataFrame, source: str) -> pd.DataFrame: - """ - Standardize DataFrame format across sources. - - Ensures consistent column names and date handling. - - Args: - df: Input DataFrame - source: Source name for logging - - Returns: - Standardized DataFrame with columns: Date, Open, High, Low, Close, Volume - """ - # Make a copy to avoid modifying original - df = df.copy() - - # Column mapping from various sources - column_mapping = { - # Common English - "date": "Date", - "open": "Open", - "high": "High", - "low": "Low", - "close": "Close", - "volume": "Volume", - # Yahoo Finance / pandas-datareader - "Open": "Open", - "High": "High", - "Low": "Low", - "Close": "Close", - "Volume": "Volume", - "Adj Close": "Adj_Close", - } - - # Rename columns - df.rename(columns=column_mapping, inplace=True) - - # Ensure Date column is datetime - if "Date" in df.columns: - df["Date"] = pd.to_datetime(df["Date"]) - - # Sort by date - if "Date" in df.columns: - df.sort_values("Date", inplace=True) - df.reset_index(drop=True, inplace=True) - - return df - - -def create_identifier( - ticker: str, - start_date: Optional[str] = None, - end_date: Optional[str] = None, - interval: str = "d", -) -> str: - """ - Create unique identifier for caching. - - Args: - ticker: Ticker symbol - start_date: Start date - end_date: End date - interval: Data interval (d, w, m) - - Returns: - Unique identifier string - """ - parts = [ticker.lower(), interval] - if start_date: - parts.append(start_date) - if end_date: - parts.append(end_date) - return "_".join(parts) - - -def handle_api_error(source: str, error: Exception, ticker: str) -> None: - """ - Handle and log API errors consistently. - - Args: - source: Data source name - error: Exception that occurred - ticker: Ticker that caused error - """ - print(f"[{source}] Error fetching data for {ticker}: {str(error)}") - - -# Global instances for reuse -_cache_manager = CacheManager() -_rate_limiter = RateLimiter() - - -def get_cache_manager() -> CacheManager: - """Get global cache manager instance.""" - return _cache_manager - - -def get_rate_limiter() -> RateLimiter: - """Get global rate limiter instance.""" - return _rate_limiter - - -if __name__ == "__main__": - # Self-tests - print("Running utils.py self-tests...") - - # Test date normalization - assert normalize_date("2024-01-15") == "20240115", "Date normalization failed" - assert normalize_date("20240115") == "20240115", "Date passthrough failed" - assert normalize_date_display("20240115") == "2024-01-15", "Date display failed" - print(" Date normalization tests passed") - - # Test cache identifier creation - assert ( - create_identifier("PKO", "20240101", "20241231") == "pko_d_20240101_20241231" - ), "Identifier creation failed" - print(" Identifier creation tests passed") - - # Test API key retrieval (should return None or value if set) - key = get_api_key("TEST_API_KEY_THAT_DOES_NOT_EXIST") - assert key is None, "Expected None for missing key" - key_with_default = get_api_key("TEST_API_KEY_THAT_DOES_NOT_EXIST", "default_value") - assert key_with_default == "default_value", "Default value not returned" - print(" API key retrieval tests passed") - - # Test cache manager - cache = get_cache_manager() - assert cache is not None, "Cache manager should not be None" - print(" Cache manager tests passed") - - # Test rate limiter - limiter = get_rate_limiter() - assert limiter is not None, "Rate limiter should not be None" - print(" Rate limiter tests passed") - - print("\nAll utils.py tests passed!") diff --git a/claude/skills/quant/pipeline-docs/SKILL.md b/claude/skills/quant/pipeline-docs/SKILL.md deleted file mode 100644 index 91e47976..00000000 --- a/claude/skills/quant/pipeline-docs/SKILL.md +++ /dev/null @@ -1,338 +0,0 @@ ---- -name: pipeline-docs -description: Create or audit documentation for a data pipeline using the 4-doc pattern (instruction, dataset, methodology, reference). Use when adding a new pipeline, when documentation is missing or incomplete for an existing pipeline, or when the user says "document this pipeline", "create pipeline docs", "4-doc pattern", or "/pipeline-docs". ---- - -# Pipeline Documentation — 4-Doc Pattern - -Create complete documentation for a data pipeline. Every pipeline gets exactly 4 docs, each answering one question. - -## The 4 Docs - -| Doc | Location | Answers | Audience | -|-----|----------|---------|----------| -| **Instruction** | `docs/instructions/{name}_pipeline.md` | What to run | Operator (human or AI) | -| **Dataset** | `docs/datasets/{dataset_name}.md` | What the data looks like | Consumer of the data | -| **Methodology** | `docs/methodology/{name}_extraction.md` | Why it works this way | Future maintainer | -| **Reference** | `docs/reference/{name}_convention.md` | What the conventions are | Anyone mapping IDs or configs | - -## Process - -### Step 1: Gather Context - -Before writing, collect: - -1. **Pipeline name** and dataset name (may differ — e.g., pipeline "fund_holdings", dataset "fund_holdings") -2. **Scripts**: entry points, CLI flags, pipeline orchestrator -3. **Config files**: what they contain, when to edit -4. **Data paths**: raw → intermediate → processed -5. **Schema**: columns, types, examples -6. **Design decisions**: why this approach, what alternatives were rejected - -Search the codebase: -- `scripts/` for pipeline scripts and CLIs -- `config/` for config files used by this pipeline -- `data/` for directory structure and file formats -- `extraction/` or `src/` for processing logic - -### Step 2: Check Existing Docs - -Look for existing docs that cover this pipeline: -- `docs/instructions/` — any operational guide? -- `docs/datasets/` — any schema doc? -- `docs/methodology/` — any design doc? -- `docs/reference/` — any convention doc? - -If some exist, audit them against the templates below. Fill gaps, don't duplicate. - -### Step 3: Write Missing Docs - -Create each missing doc using the templates below. Rules: - -- **One concern per doc** — instructions don't explain "why", methodology doesn't list commands -- **Cross-reference all 4** — every doc's "Related" section links to the other 3 -- **No duplication** — file paths, CLI options, and schema appear in exactly one doc -- **Concrete over abstract** — use real values, real paths, real examples from this project - -### Step 4: Update Routing Pages - -After creating docs, update: - -1. **`docs/README.md`** — add entries under Quick Links for each new doc -2. **`docs/data_operations.md`** (if it exists) — add routing table for this pipeline - ---- - -## Template: Instruction Doc - -`docs/instructions/{name}_pipeline.md` - -````markdown -# {Pipeline Name} Pipeline - -> Quick reference for running the {pipeline_name} pipeline. For schema details see [dataset doc]. For design decisions see [methodology doc]. - -## Quick Reference - -| Task | Command | -|------|---------| -| **Full pipeline** | `uv run python scripts/pipelines/{script}.py --latest` | -| ... | ... | - -## Steps - -### 1. {First Step Name} - -{Exact command with flags. Expected output location. What to check.} - -### 2. {Second Step Name} - -{Same pattern.} - -## Maintenance - -| Task | Command | When | -|------|---------|------| -| ... | ... | ... | - -## Related - -- [Dataset doc](../datasets/{dataset_name}.md) — schema, loading, data quality -- [Methodology doc](../methodology/{name}_extraction.md) — design decisions, trade-offs -- [Reference doc](../reference/{name}_convention.md) — IDs, config files, naming -```` - -**Style**: imperative voice ("Run X", "Check Y"). Copy-pasteable commands. No explanatory prose. - ---- - -## Template: Dataset Doc - -`docs/datasets/{dataset_name}.md` - -Use the **dataset template** from the `datasets.md` rule if available in this project. Otherwise use this structure: - -````markdown -# {Dataset Name} - -## Overview - -**Purpose**: {One sentence — why this dataset exists} - -**Data Source**: {Where it comes from} - -**Last Updated**: {YYYY-MM-DD} - -**Maintainer**: {Name/team} - -## Scope - -- **Time Period**: {Date range} -- **Record Count**: {Approximate} -- **Update Frequency**: {Quarterly, monthly, etc.} -- **Coverage**: {What's included} - -## File Location - -**Processed Data**: `data/processed/{dataset_name}/{partitioning}/` - -**Raw Data**: `data/raw/{dataset_name}/` - -**Format**: {Parquet, CSV, etc.} - -**Partitioning**: {By provider, by date, etc.} - -## Schema - -| Column | Type | Description | Example | Notes | -|--------|------|-------------|---------|-------| -| ... | ... | ... | ... | ... | - -## Data Quality - -### Validation Status - -| Check | Status | Details | -|-------|--------|---------| -| ... | ... | ... | - -### Known Issues - -- **{Issue}**: {Description}. Workaround: {if applicable}. - -## Usage - -### Loading - -```python -import pandas as pd -df = pd.read_parquet('data/processed/{dataset_name}/...') -``` - -### Common Operations - -```python -# {Useful operation} -``` - -## Processing - -**Script**: `scripts/datasets/{dataset_name}/{script}.py` - -**Pipeline**: -1. **Extract**: {source} -> `data/raw/...` -2. **Transform**: {processing} -> `data/intermediate/...` (if applicable) -3. **Process**: {final step} -> `data/processed/...` - -**Reproducibility**: {Can processed data be regenerated from raw?} - -## Related - -- [Pipeline doc](../instructions/{name}_pipeline.md) — commands, steps -- [Methodology doc](../methodology/{name}_extraction.md) — design decisions -- [Reference doc](../reference/{name}_convention.md) — IDs, config files - ---- - -**Last Updated**: {YYYY-MM-DD} -```` - -**Style**: factual, schema-focused. Loading examples must work. Include real column names and real example values. - ---- - -## Template: Methodology Doc - -`docs/methodology/{name}_extraction.md` - -````markdown -# {Pipeline Name} — Methodology - -Why the {pipeline_name} pipeline works the way it does: design decisions, algorithms, trade-offs. - -## Why {Data Source} - -{Why this source? Why not an API, database, or other format?} - -## Architecture - -### {Component Type} - -{How components are organized. Why per-X instead of generic.} - -| Type | When used | Engine/Tool | -|------|-----------|-------------| -| ... | ... | ... | - -### Why {Key Decision} - -{Explain the reasoning behind the most important architectural choice.} - -## Processing Pipeline - -{Numbered sub-steps, applied in order. Each is independent and idempotent.} - -### 1. {Step Name} - -{What it does. Data sources used. Key guards or heuristics.} - -### 2. {Step Name} - -{Same pattern.} - -## Trade-offs - -| Decision | Alternative Considered | Why This Way | -|----------|----------------------|--------------| -| ... | ... | ... | - -## Related - -- [Pipeline doc](../instructions/{name}_pipeline.md) — commands, steps -- [Dataset doc](../datasets/{dataset_name}.md) — schema, loading -- [Reference doc](../reference/{name}_convention.md) — IDs, config files -```` - -**Style**: explain the "why". Future maintainers should understand what was tried and rejected. No commands — those go in the instruction doc. - ---- - -## Template: Reference Doc - -`docs/reference/{name}_convention.md` - -````markdown -# {Pipeline Name} — Conventions - -IDs, config files, naming rules, and mapping logic for the {pipeline_name} pipeline. - -## ID Schemes - -| ID | Format | Example | Source | -|----|--------|---------|--------| -| ... | ... | ... | ... | - -## Config Files - -| File | Purpose | Key Columns | When to Edit | -|------|---------|-------------|--------------| -| `config/{file}.csv` | {What it maps} | {Key columns} | {When} | - -## Naming Conventions - -### File Naming - -{Pattern for raw files, processed files, output directories.} - -### Folder Structure - -``` -data/{dataset_name}/ -├── {provider}/ -│ └── {date}/ -│ └── {filename} -``` - -## Mapping Rules - -### {Mapping Name} - -{How X maps to Y. Explicit vs fuzzy. Priority order. What happens when no match.} - -## Related - -- [Pipeline doc](../instructions/{name}_pipeline.md) — commands, steps -- [Dataset doc](../datasets/{dataset_name}.md) — schema, loading -- [Methodology doc](../methodology/{name}_extraction.md) — design decisions -```` - -**Style**: lookup-oriented. Tables over prose. A developer should find the answer to "what's the naming convention for X?" in seconds. - ---- - -## Duplication Rules - -Each piece of information lives in exactly one doc: - -| Information | Lives In | NOT In | -|-------------|----------|--------| -| CLI commands and flags | Instruction | Methodology, Dataset | -| File paths and partitioning | Dataset | Instruction, Reference | -| Schema (columns, types) | Dataset | Methodology | -| Config file roles and columns | Reference | Instruction, Dataset | -| Design decisions and trade-offs | Methodology | Instruction, Reference | -| ID formats and naming rules | Reference | Dataset, Methodology | - -Other docs may **link** to these sections but must not repeat them. - -## Checklist - -Before finishing, verify: - -- [ ] All 4 docs exist for this pipeline -- [ ] Each doc's "Related" section links to the other 3 -- [ ] No information is duplicated across docs -- [ ] `docs/README.md` updated with links to all 4 -- [ ] Routing page (e.g., `data_operations.md`) updated if it exists -- [ ] All file paths in docs are real and correct -- [ ] Code examples in dataset doc actually work diff --git a/claude/skills/visual/architecture-diagram/SKILL.md b/claude/skills/visual/architecture-diagram/SKILL.md deleted file mode 100644 index b6e5aacf..00000000 --- a/claude/skills/visual/architecture-diagram/SKILL.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -name: architecture-diagram -description: Create professional, dark-themed architecture diagrams as standalone HTML files with SVG graphics. Use when the user asks for system architecture diagrams, infrastructure diagrams, cloud architecture visualizations, security diagrams, network topology diagrams, or any technical diagram showing system components and their relationships. -license: MIT -metadata: - version: "1.0" - author: Cocoon AI (hello@cocoon-ai.com) ---- - -# Architecture Diagram Skill - -Create professional technical architecture diagrams as self-contained HTML files with inline SVG graphics and CSS styling. - -## Design System - -### Color Palette - -Use these semantic colors for component types: - -| Component Type | Fill (rgba) | Stroke | -|---------------|-------------|--------| -| Frontend | `rgba(8, 51, 68, 0.4)` | `#22d3ee` (cyan-400) | -| Backend | `rgba(6, 78, 59, 0.4)` | `#34d399` (emerald-400) | -| Database | `rgba(76, 29, 149, 0.4)` | `#a78bfa` (violet-400) | -| AWS/Cloud | `rgba(120, 53, 15, 0.3)` | `#fbbf24` (amber-400) | -| Security | `rgba(136, 19, 55, 0.4)` | `#fb7185` (rose-400) | -| Message Bus | `rgba(251, 146, 60, 0.3)` | `#fb923c` (orange-400) | -| External/Generic | `rgba(30, 41, 59, 0.5)` | `#94a3b8` (slate-400) | - -### Typography - -Use JetBrains Mono for all text (monospace, technical aesthetic): -```html - -``` - -Font sizes: 12px for component names, 9px for sublabels, 8px for annotations, 7px for tiny labels. - -### Visual Elements - -**Background:** `#020617` (slate-950) with subtle grid pattern: -```svg - - - -``` - -**Component boxes:** Rounded rectangles (`rx="6"`) with 1.5px stroke, semi-transparent fills. - -**Security groups:** Dashed stroke (`stroke-dasharray="4,4"`), transparent fill, rose color. - -**Region boundaries:** Larger dashed stroke (`stroke-dasharray="8,4"`), amber color, `rx="12"`. - -**Arrows:** Use SVG marker for arrowheads: -```svg - - - -``` - -**Arrow z-order:** Draw connection arrows early in the SVG (after the background grid) so they render behind component boxes. SVG elements are painted in document order, so arrows drawn first will appear behind shapes drawn later. - -**Masking arrows behind transparent fills:** Since component boxes use semi-transparent fills (`rgba(..., 0.4)`), arrows behind them will show through. To fully mask arrows, draw an opaque background rect (e.g., `fill="#0f172a"`) at the same position before drawing the semi-transparent styled rect on top: -```svg - - - - -``` - -**Auth/security flows:** Dashed lines in rose color (`#fb7185`). - -**Message buses / Event buses:** Small connector elements between services. Use orange color (`#fb923c` stroke, `rgba(251, 146, 60, 0.3)` fill): -```svg - -Kafka / RabbitMQ -``` - -### Spacing Rules - -**CRITICAL:** When stacking components vertically, ensure proper spacing to avoid overlaps: - -- **Standard component height:** 60px for services, 80-120px for larger components -- **Minimum vertical gap between components:** 40px -- **Inline connectors (message buses):** Place IN the gap between components, not overlapping - -**Example vertical layout:** -``` -Component A: y=70, height=60 → ends at y=130 -Gap: y=130 to y=170 → 40px gap, place bus at y=140 (20px tall) -Component B: y=170, height=60 → ends at y=230 -``` - -**Wrong:** Placing a message bus at y=160 when Component B starts at y=170 (causes overlap) -**Right:** Placing a message bus at y=140, centered in the 40px gap (y=130 to y=170) - -### Legend Placement - -**CRITICAL:** Place legends OUTSIDE all boundary boxes (region boundaries, cluster boundaries, security groups). - -- Calculate where all boundaries end (y position + height) -- Place legend at least 20px below the lowest boundary -- Expand SVG viewBox height if needed to accommodate - -**Example:** -``` -Kubernetes Cluster: y=30, height=460 → ends at y=490 -Legend should start at: y=510 or below -SVG viewBox height: at least 560 to fit legend -``` - -**Wrong:** Legend at y=470 inside a cluster boundary that ends at y=490 -**Right:** Legend at y=510, below the cluster boundary, with viewBox height extended - -### Layout Structure - -1. **Header** - Title with pulsing dot indicator, subtitle -2. **Main SVG diagram** - Contained in rounded border card -3. **Summary cards** - Grid of 3 cards below diagram with key details -4. **Footer** - Minimal metadata line - -### Component Box Pattern - -```svg - -LABEL -sublabel -``` - -### Info Card Pattern - -```html -
-
-
-

Title

-
-
    -
  • • Item one
  • -
  • • Item two
  • -
-
-``` - -## Template - -Copy and customize the template at `assets/template.html`. Key customization points: - -1. Update the `` and header text -2. Modify SVG viewBox dimensions if needed (default: `1000 x 680`) -3. Add/remove/reposition component boxes -4. Draw connection arrows between components -5. Update the three summary cards -6. Update footer metadata - -## Output - -Always produce a single self-contained `.html` file with: -- Embedded CSS (no external stylesheets except Google Fonts) -- Inline SVG (no external images) -- No JavaScript required (pure CSS animations) - -The file should render correctly when opened directly in any modern browser. diff --git a/claude/skills/visual/architecture-diagram/assets/template.html b/claude/skills/visual/architecture-diagram/assets/template.html deleted file mode 100644 index f5b32fbe..00000000 --- a/claude/skills/visual/architecture-diagram/assets/template.html +++ /dev/null @@ -1,319 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head> - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <title>[PROJECT NAME] Architecture Diagram - - - - -
- -
-
-
-

[PROJECT NAME] Architecture

-
-

[Subtitle description]

-
- - -
- - - - - - - - - - - - - - - - - - - Users - Browser/Mobile - - - - Auth Provider - OAuth 2.0 - - - - AWS Region: us-west-2 - - - - CloudFront - CDN - - - - S3 Buckets - • bucket-one - • bucket-two - • bucket-three - OAI Protected - - - - sg-name :port - - - - Load Balancer - HTTPS :443 - - - - API Server - FastAPI :8000 - - - - Database - PostgreSQL - - - - Frontend - React + TypeScript - Additional detail - More info - domain.example.com - - - - - - HTTPS - - - - - - - OAI - - - - - TLS - - - - JWT + PKCE - - - Legend - - - Frontend - - - Backend - - - Cloud Service - - - Database - - - Security - - - Auth Flow - - - Security Group - -
- - -
-
-
-
-

Card Title 1

-
-
    -
  • • Item one
  • -
  • • Item two
  • -
  • • Item three
  • -
  • • Item four
  • -
-
- -
-
-
-

Card Title 2

-
-
    -
  • • Item one
  • -
  • • Item two
  • -
  • • Item three
  • -
  • • Item four
  • -
-
- -
-
-
-

Card Title 3

-
-
    -
  • • Item one
  • -
  • • Item two
  • -
  • • Item three
  • -
  • • Item four
  • -
-
-
- - - -
- - diff --git a/claude/skills/visual/image-generator/SKILL.md b/claude/skills/visual/image-generator/SKILL.md deleted file mode 100644 index b188dde3..00000000 --- a/claude/skills/visual/image-generator/SKILL.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -name: image-generator -description: Generate and edit images using Google Gemini API. Use when the user asks to create images, infographics, logos, mockups, diagrams, or edit existing images. ---- - -# Image Generator (Gemini) - -Generate and edit images using Google's Gemini API. Requires `GEMINI_API_KEY` or `GOOGLE_API_KEY` environment variable. - -## When to Use - -Use this skill when the user needs to: -- Generate images from text descriptions -- Create infographics, diagrams, or data visualizations -- Design logos, icons, or brand assets -- Create product mockups or social media graphics -- Edit or modify existing images -- Remove backgrounds or composite multiple images -- Iteratively refine an image through conversation - -## Default Settings - -| Setting | Default | Options | -|---------|---------|----------| -| Model | `gemini-3-pro-image-preview` | Always use Pro | -| Resolution | 1K | 1K, 2K, 4K | -| Aspect Ratio | 1:1 | 1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9 | -| Output Format | JPEG (.jpg) | Convert to PNG via PIL | - -## Core API Pattern - -```python -import os -from google import genai -from google.genai import types - -api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") -client = genai.Client(api_key=api_key) - -response = client.models.generate_content( - model="gemini-3-pro-image-preview", - contents=["Your prompt here"], - config=types.GenerateContentConfig( - response_modalities=['TEXT', 'IMAGE'], - ), -) - -for part in response.parts: - if part.text: - print(part.text) - elif part.inline_data: - image = part.as_image() - image.save("output.jpg") # Always .jpg — Gemini returns JPEG -``` - -## Custom Resolution & Aspect Ratio - -```python -config=types.GenerateContentConfig( - response_modalities=['TEXT', 'IMAGE'], - image_config=types.ImageConfig( - aspect_ratio="16:9", # Wide format - image_size="2K" # Higher resolution - ), -) -``` - -## PNG Conversion (IMPORTANT) - -Gemini's `part.as_image()` returns a Gemini Image object, NOT a PIL Image. -Its `.save()` method does NOT support `format=` kwargs. To get PNG: - -```python -# WRONG — will crash with TypeError -image = part.as_image() -image.save("output.png", format="PNG") # TypeError! - -# CORRECT — save as JPEG first, then convert with PIL -image = part.as_image() -image.save("output.jpg") - -from PIL import Image as PILImage -pil_img = PILImage.open("output.jpg") -pil_img.save("output.png", format="PNG") -``` - -Or in one step without intermediate file: - -```python -import io -from PIL import Image as PILImage - -for part in response.parts: - if part.inline_data: - pil_img = PILImage.open(io.BytesIO(part.inline_data.data)) - pil_img.save("output.jpg") # JPEG - pil_img.save("output.png") # PNG (PIL auto-detects from extension) -``` - -## Editing Existing Images - -```python -from PIL import Image - -img = Image.open("input.png") -response = client.models.generate_content( - model="gemini-3-pro-image-preview", - contents=["Add a sunset to this scene", img], - config=types.GenerateContentConfig( - response_modalities=['TEXT', 'IMAGE'], - ), -) -``` - -## Multi-Turn Refinement - -```python -chat = client.chats.create( - model="gemini-3-pro-image-preview", - config=types.GenerateContentConfig( - response_modalities=['TEXT', 'IMAGE'] - ) -) - -response = chat.send_message("Create a logo for 'Acme Corp'") -# Save first image... - -response = chat.send_message("Make the text bolder and add a blue gradient") -# Save refined image... -``` - -## Multiple Reference Images (Up to 14) - -```python -response = client.models.generate_content( - model="gemini-3-pro-image-preview", - contents=[ - "Create a group photo of these people in an office", - Image.open("person1.png"), - Image.open("person2.png"), - ], - config=types.GenerateContentConfig( - response_modalities=['TEXT', 'IMAGE'], - ), -) -``` - -## Google Search Grounding - -```python -response = client.models.generate_content( - model="gemini-3-pro-image-preview", - contents=["Visualize today's weather in Tokyo as an infographic"], - config=types.GenerateContentConfig( - response_modalities=['TEXT', 'IMAGE'], - tools=[{"google_search": {}}] - ) -) -``` - -## Style Presets - -Prepend these style directives to your prompt for consistent results: - -### NotebookLM / Google Material (light, clean) -``` -Create a clean, modern infographic in Google NotebookLM style — light #f8f9fa -background, soft rounded cards with subtle drop shadows, Google Material Design -aesthetic, clean sans-serif typography, muted pastel colors (soft blue, purple, -green, coral), generous whitespace, thin gray connecting lines with small labels. -NO dark backgrounds, NO heavy borders, NO neon colors. -``` - -### Dark Tech Infographic -``` -Create a professional infographic with dark navy/charcoal background, modern -design aesthetic, clean typography, cohesive color palette (teal, coral, gold -accents on dark background). Sharp contrast, readable text, no clutter. -Think McKinsey report meets modern tech blog. -``` - -### Technical Architecture Diagram -``` -Create a clean technical architecture diagram with a light background, clearly -labeled boxes connected by directional arrows, color-coded by component type, -legend in the corner. Professional engineering documentation style. -``` - -### Sticker / Icon -``` -A kawaii-style sticker with bold outlines, cel-shading, white/transparent -background. Simple, bold, and instantly recognizable. -``` - -## Prompting Best Practices - -### Photorealistic -Include camera details: lens type, lighting, angle, mood. -> "A photorealistic close-up portrait, 85mm lens, soft golden hour light, shallow depth of field" - -### Text in Images -Be explicit about font style and placement: -> "Create a logo with text 'Daily Grind' in clean sans-serif, black and white, coffee bean motif" - -### Infographics -Describe layout structure explicitly — sections, color scheme, columns, flow direction: -> "9:16 portrait infographic, 3-column layout (left/center/right), top-to-bottom flow, connecting arrows between cards" - -### Product Mockups -Describe lighting setup and surface: -> "Studio-lit product photo on polished concrete, three-point softbox setup, 45-degree angle" - -## Critical Notes - -- **File format**: Gemini returns JPEG by default. Always save as `.jpg` first. -- **PNG conversion**: Use PIL (`from PIL import Image`), NOT Gemini's `.save(format=)` which doesn't exist. -- **SynthID**: All generated images include invisible SynthID watermarks. -- **Dependencies**: `pip install google-genai pillow` -- **Model**: Always use `gemini-3-pro-image-preview` unless user specifies otherwise. -- **Aspect ratios for infographics**: Use `9:16` for portrait posters, `16:9` for presentations. -- **Resolution**: Use `2K` for final output. `1K` for drafts/iteration. `4K` only when explicitly needed. - -## Workflow: Generate → Review → Refine - -1. Write a Python script using the core API pattern above -2. Apply a style preset if the user mentions a visual style -3. Run it to generate the initial image (save as .jpg) -4. Convert to .png with PIL if the user needs PNG -5. View the output with the Read tool -6. If refinement needed, adjust the prompt and regenerate -7. Save final output to user's desired location diff --git a/claude/skills/visual/image-generator/scripts/generate.py b/claude/skills/visual/image-generator/scripts/generate.py deleted file mode 100644 index 3fffa8d3..00000000 --- a/claude/skills/visual/image-generator/scripts/generate.py +++ /dev/null @@ -1,144 +0,0 @@ -#!/usr/bin/env python3 -"""Generate an image using Google Gemini API. - -Usage: - python generate.py "prompt" [--aspect RATIO] [--size SIZE] [--output PATH] - -Examples: - python generate.py "A sunset over mountains" --aspect 16:9 --size 2K - python generate.py "Logo for TechCo" --output logo.jpg - python generate.py "Edit: add clouds" --input photo.jpg --output photo_edited.jpg - python generate.py "Dark infographic about AI" --aspect 9:16 --size 2K --png -""" - -import argparse -import io -import os -import sys - - -def main(): - parser = argparse.ArgumentParser(description="Generate images with Gemini") - parser.add_argument("prompt", help="Image generation prompt") - parser.add_argument("--aspect", default="1:1", - choices=["1:1", "2:3", "3:2", "3:4", "4:3", - "4:5", "5:4", "9:16", "16:9", "21:9"], - help="Aspect ratio (default: 1:1)") - parser.add_argument("--size", default="1K", choices=["1K", "2K", "4K"], - help="Image resolution (default: 1K)") - parser.add_argument("--output", "-o", default="output.jpg", - help="Output file path (default: output.jpg)") - parser.add_argument("--input", "-i", default=None, - help="Input image for editing (optional)") - parser.add_argument("--png", action="store_true", - help="Also save a PNG version alongside the JPEG") - parser.add_argument("--style", default=None, - choices=["notebooklm", "dark", "technical", "sticker"], - help="Prepend a style preset to the prompt") - parser.add_argument("--model", default="gemini-3-pro-image-preview", - help="Model name (default: gemini-3-pro-image-preview)") - args = parser.parse_args() - - # Resolve API key - api_key = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY") - if not api_key: - print("Error: Set GEMINI_API_KEY or GOOGLE_API_KEY environment variable", - file=sys.stderr) - sys.exit(1) - - # Import SDK - try: - from google import genai - from google.genai import types - except ImportError: - print("Error: Install google-genai: pip install google-genai pillow", - file=sys.stderr) - sys.exit(1) - - # Style presets - STYLE_PRESETS = { - "notebooklm": ( - "Create this in Google NotebookLM style — light #f8f9fa background, " - "soft rounded cards with subtle drop shadows, Material Design aesthetic, " - "clean sans-serif typography, muted pastel colors, generous whitespace, " - "thin gray connecting lines. NO dark backgrounds, NO heavy borders. " - ), - "dark": ( - "Create this with a dark navy/charcoal background, modern design, " - "clean typography, teal/coral/gold accents on dark background. " - "Sharp contrast, readable text, no clutter. " - ), - "technical": ( - "Create a clean technical architecture diagram, light background, " - "labeled boxes with directional arrows, color-coded components, " - "professional engineering documentation style. " - ), - "sticker": ( - "Create a kawaii-style sticker with bold outlines, cel-shading, " - "white background. Simple, bold, instantly recognizable. " - ), - } - - # Build prompt - prompt = args.prompt - if args.style and args.style in STYLE_PRESETS: - prompt = STYLE_PRESETS[args.style] + prompt - - # Build contents - contents = [prompt] - if args.input: - from PIL import Image as PILImage - if not os.path.exists(args.input): - print(f"Error: Input file not found: {args.input}", file=sys.stderr) - sys.exit(1) - img = PILImage.open(args.input) - contents = [prompt, img] - - # Generate - client = genai.Client(api_key=api_key) - print(f"Generating ({args.size}, {args.aspect})...", file=sys.stderr) - - response = client.models.generate_content( - model=args.model, - contents=contents, - config=types.GenerateContentConfig( - response_modalities=["TEXT", "IMAGE"], - image_config=types.ImageConfig( - aspect_ratio=args.aspect, - image_size=args.size, - ), - ), - ) - - # Process response - saved = False - for part in response.parts: - if part.text: - print(part.text) - elif part.inline_data: - # Ensure output has .jpg extension (Gemini returns JPEG) - out_path = args.output - if not out_path.lower().endswith((".jpg", ".jpeg")): - out_path = os.path.splitext(out_path)[0] + ".jpg" - - # Save via PIL for format-safe handling - from PIL import Image as PILImage - pil_img = PILImage.open(io.BytesIO(part.inline_data.data)) - pil_img.save(out_path, format="JPEG", quality=95) - print(f"Saved: {out_path}") - - # Optional PNG - if args.png: - png_path = os.path.splitext(out_path)[0] + ".png" - pil_img.save(png_path, format="PNG") - print(f"Saved: {png_path}") - - saved = True - - if not saved: - print("Warning: No image was generated in the response", file=sys.stderr) - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/claude/skills/visual/motion-reel/SKILL.md b/claude/skills/visual/motion-reel/SKILL.md deleted file mode 100644 index 624b9585..00000000 --- a/claude/skills/visual/motion-reel/SKILL.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -name: motion-reel -description: Render motion-graphics films as code — showreels, brand and product films, animated data stories, explainer reels, kinetic typography. One JavaScript function of time draws every frame on a canvas, headless Chrome renders it at 1080p60 with real motion blur, a numpy synth scores it to the same cue sheet, ffmpeg encodes it. Use when the user asks for a motion graphics video, a showreel, a reel, a brand film, an animated explainer, a data animation, or "make a 15/30/60-second video". Scaffolds a project, reviews contact sheets before the full render, verifies the encoded file. -argument-hint: "[project dir]" ---- - -# Motion reel - -A film here is a project directory with two sources of truth: `reel.js`, whose -`render(ctx, t)` paints any frame from nothing but the time, and `score.py`, which -places every sound at a time `reel.js` exports. Everything else is generated. - -``` -reel.js ──render.py (headless Chrome, 8 sub-frames of motion blur)──> frames/*.png ──┐ - └─ cueSheet() ─> cues.json ─> synth.py runs score.py ──────────────> audio.wav ───┴─> encode.py ─> NAME.mp4 -``` - -`SKILL` below means this skill's directory. The scripts carry their dependencies -inline (PEP 723), so `uv run` is the whole setup; Chrome is found on the system or -Playwright's Chromium is installed on first use. - -## Workflow - -1. **Scaffold.** `uv run SKILL/scripts/new_reel.py DIR` copies `reel.js` and - `score.py` from `assets/`, downloads the fonts (Inter + DM Mono by default, - `--family` to change, latin-ext kept for diacritics) and writes `DIR/make.sh`, - the one command for every later step. The template is a complete 8-scene, - 56-second demo with placeholder copy: it renders before you change anything. - -2. **Pin the story and the facts before any pixels.** Read every number from its - source (config, data, a document the user points to) into `CONTENT`, with the - as-of date. The template's numbers are invented placeholders: none may survive - into a real film, and a number with no source does not go on screen. What else may - appear (illustrations, performance claims, a real brand) is in - `references/craft.md` under "Honesty on screen". Copy follows the brand's voice and - language; `CONTENT.locale` formats every number. - -3. **Pace it: each scene's `bars` in `SCENES`.** A scene is choreographed for `nom` - bars at 128 BPM and stretches or squeezes to the bars it gets. A scene that - carries numbers needs about 4 bars (7.5 s); all 1s is a 15-second teaser for mood, - not for reading. Reading time and re-timing: `references/craft.md`, "The grid". - -4. **Look: `THEME`, `FAM`, `GRAIN`, and each scene's `bloom` and `vig`.** Take colours - and type from the brand, and pick one register per film, calm or punchy - (`references/craft.md`, "Restraint"). `LIGHT` lists the grounds that take dark type. - -5. **Review loop, about a minute.** `./make.sh sheets` runs `render.py check` (about - 50 s; what it proves is in `references/pipeline.md`, "Checks that fail loudly") and - then writes 8 frames per scene into `review/sheet-*.png`. **Read every sheet** - before rendering in full: clipped or colliding text, a transition that does not - cover the frame, a scene that reads too small. Sheets are quarter size; for small - type, `./make.sh still 39.9` renders that second at full size. Fix `reel.js`, - re-run, repeat. - -6. **Render, score, encode.** `./make.sh all`: every frame with motion blur (a few - minutes), the soundtrack, the video (a CRF-14 master plus `NAME.mp4`, the lowest - CRF under `--max-mb`, default 29 MiB for chat uploads), and a contact sheet pulled - from the encoded file. Every step exits non-zero when it cannot vouch for its - output. - -7. **Verify what ships, then report.** Look at `review/NAME-sheet.png` (frames of - the ENCODED file) and at 1:1 crops of the densest text, in the template the result - legend: `./make.sh review --at 39.9 --crop 1100:560:760:300`. Quote what `encode.py` - printed (frames, duration, size) and the levels `synth.py` printed at its checks. - You cannot listen: say that the mix is measured, not judged by ear. - -## Editing reel.js - -- **Contract.** A scene is `draw(ctx, t, lt, tf)`. `lt` is choreography time inside - the scene: entrances count from 0, exits back from `choreoLen(i)`, the choreographed - end. `t` is film time (the kick pulse, flashes). `tf` is the frame's own time, for - anything discrete, such as which card shows or a count (why: `references/pipeline.md`, - "Motion blur"). -- **One timing record per scene.** Every time a sound hangs on lives in one record - that both the scene and `cueSheet()` read: `T_SCALE`, `T_MIX`, `T_SIG`, `T_RANK`, - `T_CHECK`, `T_RES`, `COUNT`, `T_END`, and `KICK` for the groove. A sound on an eased - motion sits where the easing gets there (`reach(ease, y)`), a sound on a spring where - it lands (`springLands(f)`). Re-timing a scene then moves its sound with it. Never - type a cue time twice. -- **Pure function of time.** No state between calls; randomness only from - `mulberry32(seed)`, never `Math.random`. Anything that must persist is recomputed. -- **Adding a scene:** one record in `SCENES` (`id`, HUD `name` and `spec`, process - `step`, `nom` and `bars`, `ground`, `bloom`, `vig`, `draw`), its copy in `CONTENT`, - its timing record, its cues in `cueSheet()`, their sounds in `score.py`. Refer to - scenes by id (`ST[at.check]`), never by position. Transitions live in `TRANS`, - windowed in film time via `absTime(i, u)`, which maps choreography time `u` of - scene `i` to the film. -- **Layout** assumes 1920×1080 at 60 fps. Another aspect ratio means revisiting - every scene's coordinates; review sheets will show where. - -## Sound - -`score.py` is a function `score(s)` over a `Session` from `synth.py`. Place every -sound from `s.cues`, never from a typed time. The buses, the instruments, gated -silence and the level checks are in `references/sound.md`. - -## References - -- `references/craft.md`: timing grid, easing and spring settings, reading time, - holds that stay alive, the transition catalogue, restraint, honesty on screen. -- `references/pipeline.md`: motion blur, `t` versus `tf`, headless canvas and font - pitfalls, the checks, encoding and file sizes, render costs. -- `references/sound.md`: scoring to the cue sheet, the instrument set, the mix, - checking a soundtrack you cannot hear. diff --git a/claude/skills/visual/motion-reel/assets/reel-template.js b/claude/skills/visual/motion-reel/assets/reel-template.js deleted file mode 100644 index de0197e0..00000000 --- a/claude/skills/visual/motion-reel/assets/reel-template.js +++ /dev/null @@ -1,961 +0,0 @@ -/* reel.js — a motion-reel project, scaffolded from the motion-reel skill. - * - * The whole film is one pure function of time: render(ctx, t, tf) paints the frame at - * time t, and tf is the frame's own time, used for anything that must switch on a frame - * boundary (cuts, on-screen counters). Nothing carries over between frames, so any - * frame renders in any order, sub-frames average into real motion blur, and the film - * can be scrubbed. - * - * Edit CONTENT (the story), THEME (the look) and SCENES (the order and the pacing). - * Every number below is an invented placeholder: replace each with one read from your - * source, and label anything illustrative on screen (see CONTENT.signal.tag). - */ -(function (root) { -'use strict'; - -// ================================================================== STORY -const CONTENT = { - brand: 'ACME SIGNALS', - asOf: 'DATA: 2026-09-01', - locale: 'en-US', - process: ['DISCOVER', 'ANALYSE', 'BUILD', 'REVIEW'], - scale: { - title: 'Pick a level.', sub: 'FROM CAUTIOUS TO BOLD', low: 'LOWER RISK', high: 'HIGHER RISK', - levels: [ - { key: 'L1', name: 'Cautious', note: '1 month' }, - { key: 'L2', name: 'Careful', note: '3 months' }, - { key: 'L3', name: 'Balanced', note: '6 months' }, - { key: 'L4', name: 'Dynamic', note: '1 year' }, - { key: 'L5', name: 'Bold', note: '2+ years' }, - ], - }, - mix: { - title: 'The mix', sub: 'NEUTRAL WEIGHTS · A RANGE FOR GROWTH', parts: ['Core', 'Growth', 'Extras'], - rows: [[90, 10, 0], [70, 25, 5], [50, 40, 10], [30, 55, 15], [15, 70, 15]], // one row per level; parts sum to 100 - ranges: [[0, 20], [15, 35], [30, 50], [45, 65], [60, 80]], // allowed range of the dive part, per level - focus: 2, // the column the camera dives into - divePart: 1, // the part it dives through; its colour becomes the next scene's ground - }, - signal: { - title: 'The signal', sub: 'DAILY · QUALITY, TREND AND MOMENTUM', - inputs: [{ name: 'Quality', value: 0.5 }, { name: 'Trend', value: 0.35 }, { name: 'Momentum', value: -0.15 }], - composite: 0.23, label: 'Composite', - gauge: { title: 'Growth at level 3', range: [30, 50], neutral: 40, overshoot: 46.5, target: 45, rangeLabel: 'range', neutralLabel: 'neutral', targetLabel: 'target' }, - tag: 'ILLUSTRATION', - }, - rank: { - title: 'The ranking', sub: 'ONE SCORE · 1,000 ITEMS', axis: 'SCORE', top: 'TOP RATED', - pillars: [{ name: 'QUALITY', weight: 40 }, { name: 'STABILITY', weight: 35 }, { name: 'VALUE', weight: 25 }], - hist: [9, 15, 24, 33, 45, 57, 68, 76, 83, 86, 86, 83, 76, 68, 58, 47, 36, 26, 15, 9], // items per score bin, low to high: 1,000 - }, - check: { - title: 'The check', sub: 'ONE PASS OVER EVERY ITEM', legend: 'Status', - groups: [ // counts sum to the ranking's items - { name: 'pass', count: 612, color: 'good' }, { name: 'watch', count: 214, color: 'warm' }, - { name: 'fail', count: 121, color: 'bad' }, { name: 'no data', count: 53, color: 'muted' }, - ], - flag: 2, // the group that steps out of the sphere - }, - result: { - title: 'The result', sub: 'ONE MODEL MIX · LEVEL 3', - center: { big: 'L3', name: 'Balanced', note: 'HORIZON 6 MONTHS' }, - classes: [{ name: 'Core', weight: 50, color: 'dark' }, { name: 'Growth', weight: 40, color: 'accent' }, { name: 'Extras', weight: 10, color: 'warm' }], - items: [ // cls: index into classes - { name: 'Core, short term', weight: 15, color: 'dark', cls: 0 }, - { name: 'Core, long term', weight: 25, color: 'slate', cls: 0 }, - { name: 'Core, global', weight: 10, color: 'steel', cls: 0 }, - { name: 'Growth, developed markets', weight: 30, color: 'accent', cls: 1 }, - { name: 'Growth, emerging markets', weight: 10, color: 'accent2', cls: 1 }, - { name: 'Extras, gold', weight: 10, color: 'warm', cls: 2 }, - ], - }, - cards: [ // one per slot of the rhythm scene; a `quiet` card is held in silence - { big: '5', label: 'levels', bg: 'accent' }, { big: '3', label: 'parts', bg: 'paper' }, { count: 1000, label: 'items', bg: 'dark' }, - { word: 'daily', label: 'SIGNALS', bg: 'soft' }, { word: 'weekly', label: 'RANKING', bg: 'accent' }, - { word: 'monthly', label: 'REPORT', bg: 'paper' }, { word: 'quarterly', label: 'REVIEW', bg: 'mid' }, { quiet: 'breathe.', bg: 'dark' }, - ], - end: { name: 'Acme Signals', line: 'Built to last', recap: 'SCALE · MIX · SIGNAL · RANKING · CHECK · RESULT' }, -}; - -// ================================================================== LOOK -const THEME = { - dark: '#0F1B2D', deep: '#050B16', mid: '#1C2E4A', paper: '#FFFFFF', soft: '#E3ECFF', - accent: '#1F6BFF', accent2: '#6B9BFF', sky: '#A9C4FF', slate: '#2C4466', steel: '#4E6C96', - text: '#0E1726', muted: '#6B7280', warm: '#F29D0B', good: '#16A34A', bad: '#DC2626', white: '#FFFFFF', -}; -const LIGHT = new Set(['paper', 'soft']); // grounds that take dark type -const FAM = { sans: 'Inter', mono: 'DM Mono' }; // must match fonts.css (scripts/fonts.py) -const HUD_ON = true; -const GRAIN = 0.035; - -// ================================================================== SEQUENCE: one record per scene -// nom: bars the scene is choreographed for; bars: bars it gets (it stretches or squeezes -// to fit; all 1s makes a 15-second teaser); ground: the THEME key under it (null: the -// scene decides); step: its place in CONTENT.process (past the end: every step done); -// bloom and vig: finishing-pass strengths, glow for dark grounds only. -const SCENES = [ - { id: 'scale', name: 'SCALE', spec: '5 levels · from cautious to bold', step: 0, nom: 3, bars: 3, ground: 'dark', bloom: 0.22, vig: 0.3, draw: sScale }, - { id: 'mix', name: 'MIX', spec: 'three parts · a range for the middle one', step: 0, nom: 4, bars: 4, ground: 'paper', bloom: 0, vig: 0.05, draw: sMix }, - { id: 'signal', name: 'SIGNAL', spec: 'three inputs · one composite', step: 1, nom: 4, bars: 4, ground: null, bloom: 0.08, vig: 0.12, draw: sSignal }, - { id: 'rank', name: 'RANKING', spec: '1,000 items · one score', step: 1, nom: 4, bars: 4, ground: 'dark', bloom: 0.3, vig: 0.3, draw: sRank }, - { id: 'check', name: 'CHECK', spec: 'every item · one pass', step: 1, nom: 4, bars: 4, ground: 'deep', bloom: 0.42, vig: 0.35, draw: sCheck }, - { id: 'result', name: 'RESULT', spec: 'level 3 · 50 / 40 / 10', step: 2, nom: 4, bars: 4, ground: 'paper', bloom: 0, vig: 0.05, draw: sResult }, - { id: 'rhythm', name: 'RHYTHM', spec: 'daily · weekly · monthly · quarterly', step: 3, nom: 4, bars: 4, ground: null, bloom: 0, vig: 0.08, draw: sRhythm }, - { id: 'end', name: 'END', spec: 'Built to last.', step: 4, nom: 3, bars: 3, ground: 'dark', bloom: 0.25, vig: 0.35, draw: sEnd }, -]; -const at = Object.fromEntries(SCENES.map((s, i) => [s.id, i])); // scene index by id - -// ================================================================== PACING -const W = 1920, H = 1080, FPS = 60; -const BPM = 128, BEAT = 60 / BPM, BAR = 4 * BEAT; -const ST = SCENES.reduce((acc, s, i) => (acc.push(acc[i] + s.bars * BAR), acc), [0]); // scene start times -const DUR = ST[SCENES.length]; -const choreoLen = i => SCENES[i].nom * BAR; // the length scene i is choreographed for -const sceneLen = i => ST[i + 1] - ST[i]; // the length it actually gets -const pace = i => choreoLen(i) / sceneLen(i); // choreography seconds per real second -const absTime = (i, u) => ST[i] + u / pace(i); // choreography time u of scene i -> film time -const CARD = sceneLen(at.rhythm) / CONTENT.cards.length; -const QUIET = CONTENT.cards.findIndex(c => c.quiet); -const SIL = QUIET < 0 ? [ST[at.end], ST[at.end]] : [ST[at.rhythm] + QUIET * CARD, ST[at.rhythm] + (QUIET + 1) * CARD]; -const GROOVE = [ST[at.mix], SIL[0]]; // the drums play from the second scene until the silence -const KICK = [0, 1.5]; // the groove's kicks, in beats after each bar line (half time); [0, 1, 2, 3] is four on the floor -const TAU = Math.PI * 2; - -// ------------------------------------------------------------------ colour and number helpers -const hex = h => [1, 3, 5].map(i => parseInt(h.slice(i, i + 2), 16)); -const RGB = Object.fromEntries(Object.entries(THEME).map(([k, v]) => [k, hex(v)])); -const mixc = (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; -const css = (c, a = 1) => `rgba(${c[0] | 0},${c[1] | 0},${c[2] | 0},${a})`; -const inkOn = key => (LIGHT.has(key) ? THEME.text : THEME.white); -const NUM = new Intl.NumberFormat(CONTENT.locale); -const SIGNED = new Intl.NumberFormat(CONTENT.locale, { minimumFractionDigits: 2, maximumFractionDigits: 2, signDisplay: 'always' }); -const fmt = n => NUM.format(n); -const signed = v => SIGNED.format(v).replace('-', '−'); -const pct = v => `${fmt(v)}%`; - -// ------------------------------------------------------------------ math -const clamp = (x, a = 0, b = 1) => (x < a ? a : x > b ? b : x); -const lerp = (a, b, t) => a + (b - a) * t; -const seg = (t, a, b) => clamp((t - a) / (b - a)); -const E = { - inCubic: x => x * x * x, - outCubic: x => 1 - (1 - x) ** 3, - inOutCubic: x => (x < 0.5 ? 4 * x * x * x : 1 - (-2 * x + 2) ** 3 / 2), - outExpo: x => (x >= 1 ? 1 : 1 - 2 ** (-10 * x)), - inExpo: x => (x <= 0 ? 0 : 2 ** (10 * x - 10)), - inOutExpo: x => (x <= 0 ? 0 : x >= 1 ? 1 : x < 0.5 ? 2 ** (20 * x - 10) / 2 : (2 - 2 ** (-20 * x + 10)) / 2), -}; -// where a rising easing reaches y (bisection), so a sound hung on an eased motion follows the easing -function reach(ease, y) { - let a = 0, b = 1; - for (let i = 0; i < 40; i++) { const m = (a + b) / 2; if (ease(m) < y) a = m; else b = m; } - return b; -} -// damped spring: seconds since release -> 0..1, overshooting on the way (f in Hz, d = decay) -const spring = (s, f = 3, d = 7) => (s <= 0 ? 0 : 1 - Math.exp(-d * s) * Math.cos(TAU * f * s)); -const springLands = f => 1 / (4 * f); // when spring(s, f) first reaches its target -const bump = (t, a, b, edge) => seg(t, a, a + edge) * (1 - seg(t, b - edge, b)); -const hash = n => { const x = Math.sin(n * 127.1 + 311.7) * 43758.5453; return x - Math.floor(x); }; -function mulberry32(a) { - return () => { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; -} - -// ------------------------------------------------------------------ drawing helpers -const G = {}; -const mkCanvas = (w, h) => Object.assign(document.createElement('canvas'), { width: w, height: h }); -function setFont(ctx, fam, size, weight = 400, spacing = 0) { - ctx.font = `${Math.round(weight)} ${size}px "${fam}"`; - ctx.letterSpacing = spacing + 'px'; -} -function letters(ctx, text, fam, size, weight, tracking = 0) { - const ch = [...text], ws = []; - setFont(ctx, fam, size, weight); - for (const c of ch) ws.push(ctx.measureText(c).width); - const total = ws.reduce((a, b) => a + b, 0) + tracking * (ch.length - 1), xs = []; - let x = -total / 2; - for (let i = 0; i < ch.length; i++) { xs.push(x + ws[i] / 2); x += ws[i] + tracking; } - return { ch, ws, xs, total }; -} -function camera(ctx, z = 1, dx = 0, dy = 0, cx = W / 2, cy = H / 2) { - ctx.translate(cx + dx, cy + dy); - ctx.scale(z, z); - ctx.translate(-cx, -cy); -} -// the kick as the picture feels it: a pulse on every kick of KICK, within the groove -function kick(t) { - if (t < GROOVE[0] || t >= GROOVE[1]) return 0; - const u = (t - GROOVE[0]) % BAR, last = Math.max(...KICK.map(k => k * BEAT).filter(o => o <= u + 1e-9)); - return Math.exp(-(u - last) * 8); -} -function kickTimes() { // every kick in the groove, for the soundtrack - const out = []; - for (let b = GROOVE[0]; b < GROOVE[1] - 1e-6; b += BAR) for (const k of KICK) if (b + k * BEAT < GROOVE[1] - 1e-6) out.push(b + k * BEAT); - return out; -} -const pump = t => 1 + 0.005 * kick(t); -// text rising out of a mask under its own baseline -function reveal(ctx, text, x, y, size, weight, col, s, opts = {}) { - if (s <= 0) return; - const e = E.outExpo(clamp(s / (opts.dur || 0.9))); - setFont(ctx, opts.fam || FAM.sans, size, weight, opts.spacing || 0); - ctx.save(); - ctx.beginPath(); ctx.rect(-W, y - size * 1.35, 3 * W, size * 1.35 + size * 0.3); ctx.clip(); - ctx.fillStyle = col; ctx.textAlign = opts.align || 'left'; ctx.globalAlpha *= clamp(s / 0.2); - ctx.fillText(text, x, y + (1 - e) * size * 1.15); - ctx.restore(); -} -function typed(ctx, text, x, y, col, s, dur, opts = {}) { - const n = Math.ceil(text.length * clamp(s / dur)); - if (n <= 0) return; - setFont(ctx, FAM.mono, opts.size || 16, opts.weight || 400, opts.spacing ?? 3); - ctx.textAlign = opts.align || 'left'; ctx.fillStyle = col; - const a = ctx.globalAlpha; ctx.globalAlpha = a * (opts.alpha ?? 0.72); - ctx.fillText(text.slice(0, n), x, y); - ctx.globalAlpha = a; -} -function headline(ctx, title, sub, col, lt, at0) { - reveal(ctx, title, 150, 250, 104, 700, col, lt - at0, { dur: 0.9 }); - if (sub) typed(ctx, sub, 153, 302, col, lt - at0 - 0.35, 0.6); -} -function flash(ctx, t, t0, amp, k, col = THEME.white) { - if (t < t0) return; - const a = amp * Math.exp(-(t - t0) * k); - if (a < 0.004) return; - ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = a; ctx.fillStyle = col; ctx.fillRect(0, 0, W, H); ctx.restore(); -} -// squash on contact, stretch along the fall -function drawBall(ctx, x, st, r, v0, col) { - const stretch = 0.3 * Math.min(1, Math.abs(st.v) / v0), sq = st.sq; - const rx = (r * (1 + 0.55 * sq)) / Math.sqrt(1 + stretch), ry = r * (1 - 0.45 * sq) * (1 + stretch); - ctx.fillStyle = col; ctx.beginPath(); ctx.ellipse(x, sq > 0 ? st.y + r - ry : st.y, rx, ry, 0, 0, TAU); ctx.fill(); -} -// a ball that falls, lands on c0, bounces to land again on c1, and settles with the same restitution -function makeBounce({ y0, rest, tDrop, c0, c1, sq }) { - if (!(tDrop < c0 && c0 + sq < c1)) throw new Error(`makeBounce: need drop < first contact < second contact, got ${tDrop} / ${c0} / ${c1}`); - const h0 = rest - y0, g = (2 * h0) / (c0 - tDrop) ** 2, air0 = c1 - c0 - sq, h1 = (g * (air0 / 2) ** 2) / 2, e2 = h1 / h0; - // a second contact too late for the drop means each bounce is higher than the last: it would never settle - if (!(e2 < 1)) throw new Error(`makeBounce: contacts ${c0} and ${c1} after a drop at ${tDrop} bounce higher than the drop; bring the second contact closer`); - const contacts = [c0], vin = [Math.sqrt(2 * g * h0)], air = []; - let h = h1, tc = c0; - while (h > 1.2) { const a = 2 * Math.sqrt((2 * h) / g); air.push(a); tc += sq + a; contacts.push(tc); vin.push(Math.sqrt(2 * g * h)); h *= e2; } - const v0 = vin[0]; - function state(t) { - if (t < c0) { const s = Math.max(0, t - tDrop); return { y: y0 + 0.5 * g * s * s, v: g * s, sq: 0 }; } - for (let k = 0; k < contacts.length; k++) { - const tk = contacts[k]; - if (t < tk + sq) return { y: rest, v: 0, sq: (Math.sin(Math.PI * clamp((t - tk) / sq)) * vin[k]) / v0 }; - if (k < air.length && t < tk + sq + air[k]) { const s = t - tk - sq, up = (g * air[k]) / 2; return { y: rest - (up * s - 0.5 * g * s * s), v: -(up - g * s), sq: 0 }; } - } - return { y: rest, v: 0, sq: 0 }; - } - return { state, contacts, v0, settle: tc + sq }; -} -function wrap(ctx, text, maxW) { - const out = []; - let line = ''; - for (const w of text.split(' ')) { const tryL = line ? line + ' ' + w : w; if (ctx.measureText(tryL).width > maxW && line) { out.push(line); line = w; } else line = tryL; } - if (line) out.push(line); - return out; -} - -// ================================================================== SCALE -// A ball hops along the levels, one hop per beat, each higher than the last: the arc -// is the risk. Then it rises, takes the accent colour and opens into the next scene. -const SC = { x0: 380, x1: 1540, FY: 690, R: 18 }; -const SQ = 0.035; // how long a ball stays squashed on a contact -// drop: the ball starts falling; c0, step: the first contact and one hop per beat; settle: the -// last little hop; rise, iris: seconds before the scene's end, the ball rises to the centre and -// the ring opens into the next scene -const T_SCALE = { drop: 0.95, c0: 3 * BEAT, step: BEAT, settle: 0.22, rise: [1.025, 0.525], iris: 0.45 }; -// the hop contacts and the settle, in choreography time: the ball and the sound both read these -function scaleContacts() { - const n = CONTENT.scale.levels.length, hops = Array.from({ length: n }, (_, k) => T_SCALE.c0 + k * T_SCALE.step); - return { hops, settle: hops[n - 1] + SQ + T_SCALE.settle }; -} -const levelX = (k, n) => (n > 1 ? SC.x0 + (k * (SC.x1 - SC.x0)) / (n - 1) : (SC.x0 + SC.x1) / 2); -const hopH = (k, n) => lerp(70, 290, n > 2 ? k / (n - 2) : 1); -function scaleBall(u) { - const n = CONTENT.scale.levels.length, { hops, settle } = scaleContacts(), t0 = T_SCALE.drop, y0 = -60, rest = SC.FY - SC.R; - const g = (2 * (rest - y0)) / (hops[0] - t0) ** 2, v0 = g * (hops[0] - t0); - if (u < hops[0]) { const s = Math.max(0, u - t0); return { x: levelX(0, n), y: y0 + 0.5 * g * s * s, v: g * s, sq: 0, v0 }; } - for (let k = 0; k < n; k++) { - const ck = hops[k], strength = Math.min(1, Math.sqrt((k === 0 ? rest - y0 : hopH(k - 1, n)) / 290)); - if (u < ck + SQ) return { x: levelX(k, n), y: rest, v: 0, sq: Math.sin(Math.PI * clamp((u - ck) / SQ)) * strength, v0 }; - if (k < n - 1 && u < hops[k + 1]) { - const s0 = ck + SQ, T = hops[k + 1] - s0, f = (u - s0) / T, h = hopH(k, n); - return { x: lerp(levelX(k, n), levelX(k + 1, n), f), y: rest - 4 * h * f * (1 - f), v: (-4 * h * (1 - 2 * f)) / T, sq: 0, v0 }; - } - } - const s1 = settle, s0 = s1 - T_SCALE.settle, h = 28, xl = levelX(n - 1, n); - if (u < s1) { const f = (u - s0) / (s1 - s0); return { x: xl, y: rest - 4 * h * f * (1 - f), v: (-4 * h * (1 - 2 * f)) / T_SCALE.settle, sq: 0, v0 }; } - if (u < s1 + SQ) return { x: xl, y: rest, v: 0, sq: Math.sin(Math.PI * clamp((u - s1) / SQ)) * 0.3, v0 }; - return { x: xl, y: rest, v: 0, sq: 0, v0 }; -} -function irisGeom(t) { - if (t < ST[at.mix]) return { hole: 24 * E.outCubic(seg(t, absTime(at.scale, choreoLen(at.scale) - T_SCALE.iris), ST[at.mix])), outer: 44 }; - const e = E.outExpo(seg(t, ST[at.mix], absTime(at.mix, 0.65))), hole = lerp(24, 1260, e); - return { hole, outer: hole + lerp(20, 3, e) }; -} -function sScale(ctx, t, lt) { - const S = CONTENT.scale, n = S.levels.length, D = choreoLen(at.scale), FY = SC.FY, X = k => levelX(k, n); - ctx.fillStyle = THEME.dark; ctx.fillRect(0, 0, W, H); - const fade = 1 - 0.85 * seg(lt, D - 1.225, D - 0.725); - ctx.globalAlpha = fade; - headline(ctx, S.title, S.sub, THEME.white, lt, 0.25); - const cx = (X(0) + X(n - 1)) / 2, half = (X(n - 1) - X(0)) / 2 + 70, e = E.outExpo(seg(lt, 0.1, 1.2)); - ctx.globalAlpha = 0.3 * fade; ctx.fillStyle = THEME.white; - ctx.fillRect(cx - half * e, FY, 2 * half * e, 2); - const gy = FY + 160, gr = ctx.createLinearGradient(X(0), 0, X(n - 1), 0); - gr.addColorStop(0, css(RGB.sky, 0.35)); gr.addColorStop(1, THEME.accent); - ctx.globalAlpha = fade * seg(lt, 0.9, 1.4); ctx.fillStyle = gr; - ctx.fillRect(X(0) - 40, gy, (X(n - 1) - X(0) + 80) * E.outExpo(seg(lt, 0.9, 1.9)), 4); - setFont(ctx, FAM.mono, 13, 400, 2); ctx.fillStyle = THEME.white; ctx.globalAlpha = 0.55 * fade * seg(lt, 1.3, 1.8); - ctx.textAlign = 'left'; ctx.fillText(S.low, X(0) - 40, gy + 30); - ctx.textAlign = 'right'; ctx.fillText(S.high, X(n - 1) + 40, gy + 30); - // the spacing chart: where the ball was, every third frame - ctx.fillStyle = THEME.sky; ctx.globalAlpha = 0.8 * fade; - const { hops } = scaleContacts(), lastHop = hops[n - 1] + 0.3; - for (let f = 3; f / FPS <= Math.min(lt, lastHop); f += 3) { - const st = scaleBall(f / FPS); - if (st.y < -10) continue; - ctx.beginPath(); ctx.arc(st.x, st.y, 2.8, 0, TAU); ctx.fill(); - } - ctx.textAlign = 'center'; - S.levels.forEach((lv, k) => { - const x = X(k), ck = hops[k], hit = lt >= ck, ap = seg(lt, 0.5 + 0.12 * k, 0.9 + 0.12 * k) * fade; - if (hit && lt < ck + 0.7) { - const s = (lt - ck) / 0.7; - ctx.globalAlpha = (1 - s) * 0.7 * fade; ctx.strokeStyle = THEME.sky; ctx.lineWidth = 2; - ctx.beginPath(); ctx.arc(x, FY + 1, 10 + 64 * E.outCubic(s), 0, TAU); ctx.stroke(); - } - ctx.globalAlpha = ap; ctx.lineWidth = 2; ctx.strokeStyle = THEME.white; ctx.fillStyle = THEME.accent; - ctx.beginPath(); ctx.arc(x, FY + 1, 8 * (hit ? 0.8 + 0.2 * spring(lt - ck, 2, 6) : 1), 0, TAU); - if (hit) ctx.fill(); - ctx.stroke(); - const lift = hit ? -6 * spring(lt - ck, 1.8, 7) : 0; - ctx.fillStyle = THEME.white; ctx.globalAlpha = ap * (hit ? 1 : 0.55); - setFont(ctx, FAM.mono, 17, 500, 2); ctx.fillText(lv.key, x, FY + 50 + lift); - setFont(ctx, FAM.sans, 25, 600); ctx.fillText(lv.name, x, FY + 86 + lift); - setFont(ctx, FAM.mono, 14, 400, 1); ctx.globalAlpha *= 0.7; ctx.fillText(lv.note, x, FY + 114 + lift); - }); - ctx.globalAlpha = 1; - if (t >= ST[at.mix]) { ctx.fillStyle = THEME.accent; ctx.beginPath(); ctx.arc(W / 2, H / 2, irisGeom(t).outer, 0, TAU); ctx.fill(); return; } - const st = scaleBall(lt), rise = E.inOutCubic(seg(lt, D - T_SCALE.rise[0], D - T_SCALE.rise[1])); - drawBall(ctx, lerp(st.x, W / 2, rise), { y: lerp(st.y, H / 2, rise), v: st.v * (1 - rise), sq: st.sq * (1 - rise) }, lerp(SC.R, 44, rise), st.v0, css(mixc(RGB.white, RGB.accent, rise))); -} - -// ================================================================== MIX -// One stacked column per level rises on a spring, each with the allowed range of one -// part beside it. The eye is led to the focus column, then the camera dives into it. -const PARTC = ['dark', 'accent', 'warm']; // THEME keys of the parts, in order -const T_MIX = { rise: 0.5, stagger: 0.22, dive: [1.5, 0.3] }; // dive: seconds before the scene's end -function mixGeom(n) { - const pitch = Math.min(250, 1250 / n), w = pitch * 0.6; - return { pitch, w, x0: (W - (n * w + (n - 1) * (pitch - w))) / 2, HC: 480, base: 820 }; -} -function sMix(ctx, t, lt) { - const M = CONTENT.mix, n = M.rows.length, D = choreoLen(at.mix), geo = mixGeom(n), colX = k => geo.x0 + k * geo.pitch; - ctx.fillStyle = THEME.paper; ctx.fillRect(0, 0, W, H); - const F = M.focus, P = M.divePart, row = M.rows[F]; - const fx = colX(F) + geo.w / 2, fy = geo.base - (geo.HC * (row.slice(0, P).reduce((a, b) => a + b, 0) + row[P] / 2)) / 100; - const zE = E.inExpo(seg(lt, D - T_MIX.dive[0], D - T_MIX.dive[1])), mv = E.inOutCubic(seg(lt, D - T_MIX.dive[0], D - 0.6)); - camera(ctx, (1 + 0.02 * seg(lt, T_MIX.rise, D - T_MIX.dive[0])) * (1 + 24 * zE) * pump(t), (W / 2 - fx) * mv, (H / 2 - fy) * mv, fx, fy); - const out = 1 - seg(lt, D - 1.55, D - 1.1), focus = E.inOutCubic(seg(lt, D - 3.1, D - 2.5)); - ctx.globalAlpha = out; - headline(ctx, M.title, M.sub, THEME.text, lt, 0.35); - setFont(ctx, FAM.sans, 20, 500); - let lx = W - 150; - for (let j = M.parts.length - 1; j >= 0; j--) { - const name = M.parts[j], w = ctx.measureText(name).width, r = M.parts.length - 1 - j; - ctx.globalAlpha = out * seg(lt, 0.8 + 0.12 * r, 1.2 + 0.12 * r); - ctx.fillStyle = THEME.text; ctx.textAlign = 'left'; ctx.fillText(name, lx - w, 244); - ctx.fillStyle = THEME[PARTC[j]]; ctx.fillRect(lx - w - 24, 228, 14, 14); - lx -= w + 60; - } - M.rows.forEach((r, k) => { - const x = colX(k), g = spring(lt - T_MIX.rise - T_MIX.stagger * k, 1.2, 6), a = k === F ? 1 : out * (1 - 0.6 * focus); - if (g <= 0) return; - const hTot = geo.HC * g; - ctx.globalAlpha = a; - ctx.save(); ctx.beginPath(); ctx.roundRect(x, geo.base - hTot, geo.w, hTot, [8, 8, 0, 0]); ctx.clip(); - let y = geo.base; - r.forEach((v, j) => { const h = ((geo.HC * v) / 100) * g; if (h > 0) { ctx.fillStyle = THEME[PARTC[j]]; ctx.fillRect(x, y - h, geo.w, h); y -= h; } }); - ctx.fillStyle = THEME.paper; y = geo.base; - r.forEach(v => { y -= ((geo.HC * v) / 100) * g; if (v > 0 && y > geo.base - hTot + 1) ctx.fillRect(x, y - 1.5, geo.w, 3); }); - ctx.restore(); - const la = seg(lt, 1.5 + 0.15 * k, 1.9 + 0.15 * k) * (lt > D - 1.6 ? 0 : a); - if (la > 0) { - let yy = geo.base; - setFont(ctx, FAM.mono, 18, 500); ctx.textAlign = 'center'; ctx.globalAlpha = la; - r.forEach((v, j) => { const h = (geo.HC * v) / 100; if (h >= 34) { ctx.fillStyle = PARTC[j] === 'warm' ? THEME.text : THEME.white; ctx.fillText(pct(v), x + geo.w / 2, yy - h / 2 + 6); } yy -= h; }); - } - const lv = CONTENT.scale.levels[k] || { key: `#${k + 1}`, name: '' }; - ctx.globalAlpha = a * seg(lt, 0.6 + 0.2 * k, 1.1 + 0.2 * k); ctx.textAlign = 'center'; - setFont(ctx, FAM.mono, 16, 500, 2); ctx.fillStyle = THEME.muted; ctx.fillText(lv.key, x + geo.w / 2, geo.base + 40); - setFont(ctx, FAM.sans, 22, k === F ? 700 : 600); ctx.fillStyle = k === F ? css(mixc(RGB.text, RGB.accent, focus)) : THEME.text; - ctx.fillText(lv.name, x + geo.w / 2, geo.base + 70); - const ca = a * seg(lt, 2.4 + 0.15 * k, 2.9 + 0.15 * k), rg = M.ranges[k]; - if (ca > 0 && rg) { - const gx = x + geo.w + 22, yv = v => geo.base - (geo.HC * v) / 100; - ctx.globalAlpha = ca * 0.18; ctx.fillStyle = THEME.text; ctx.fillRect(gx - 1, yv(100), 2, geo.HC); - ctx.globalAlpha = ca * 0.3; ctx.fillStyle = THEME[PARTC[P]]; ctx.fillRect(gx - 4, yv(rg[1]), 8, Math.max(2, yv(rg[0]) - yv(rg[1]))); - ctx.globalAlpha = ca; ctx.fillStyle = THEME.text; ctx.fillRect(gx - 8, yv(r[P]) - 1.5, 16, 3); - setFont(ctx, FAM.mono, 12, 400); ctx.fillStyle = THEME.muted; ctx.textAlign = 'center'; - ctx.fillText(rg[1] ? `${fmt(rg[0])}–${fmt(rg[1])}` : '0', gx, yv(rg[1]) - 10); - } - }); - ctx.globalAlpha = 1; -} - -// ================================================================== SIGNAL -// Three inputs fold into one composite, which moves a weight inside its range and -// snaps to the grid. Illustrative numbers are labelled as such on screen. -const T_SIG = { inputs: 0.7, stagger: 0.25, fold: [2.9, 3.7], connector: [4.0, 4.6], slide: [4.5, 5.3], snap: 5.4 }; -function sSignal(ctx, t, lt) { - const S = CONTENT.signal, gz = S.gauge, ground = PARTC[CONTENT.mix.divePart], ink = inkOn(ground); - ctx.fillStyle = THEME[ground]; ctx.fillRect(0, 0, W, H); - camera(ctx, pump(t)); - headline(ctx, S.title, S.sub, ink, lt, 0.2); - const AX0 = 500, AX1 = 1020, AC = (AX0 + AX1) / 2, AH = (AX1 - AX0) / 2, yC = 790, comp = S.composite; - const fold = E.inOutCubic(seg(lt, ...T_SIG.fold)); - ctx.fillStyle = ink; - S.inputs.forEach(({ name, value }, i) => { - const at0 = T_SIG.inputs + T_SIG.stagger * i; // this input's bar starts growing - const y = lerp(470 + 92 * i, yC, fold), g = E.outExpo(seg(lt, at0, at0 + 0.9)), val = lerp(value, comp, fold) * g; - ctx.globalAlpha = seg(lt, at0 - 0.2, at0 + 0.2) * (1 - fold); - setFont(ctx, FAM.sans, 30, 600); ctx.textAlign = 'left'; ctx.fillText(name, 150, y + 10); - ctx.globalAlpha = 0.28 * seg(lt, 0.3, 0.8) * (i === 0 ? 1 : 1 - fold); - ctx.fillRect(AX0, y - 1, AX1 - AX0, 2); ctx.fillRect(AC - 1, y - 14, 2, 28); - if (g > 0) { - ctx.globalAlpha = 1; - const x0 = Math.min(AC, AC + val * AH), w = Math.abs(val * AH); - ctx.beginPath(); ctx.roundRect(x0, y - 11, Math.max(2, w), 22, 11); ctx.fill(); - ctx.globalAlpha = seg(lt, at0 + 0.5, at0 + 0.9) * (1 - fold); - setFont(ctx, FAM.mono, 19, 500); ctx.textAlign = value >= 0 ? 'left' : 'right'; - ctx.fillText(signed(value), AC + val * AH + (value >= 0 ? 18 : -18), y + 7); - } - }); - const ca = seg(lt, T_SIG.fold[1] - 0.2, T_SIG.fold[1] + 0.3); - if (ca > 0) { - ctx.globalAlpha = ca; setFont(ctx, FAM.sans, 30, 600); ctx.textAlign = 'left'; ctx.fillText(S.label, 150, yC + 10); - setFont(ctx, FAM.mono, 20, 500); ctx.fillText(signed(comp), AC + comp * AH + 18, yC + 8); - setFont(ctx, FAM.mono, 13, 400); ctx.globalAlpha = ca * 0.65; ctx.textAlign = 'center'; - [[-1, '−1'], [0, '0'], [1, '+1']].forEach(([v, s]) => ctx.fillText(s, AC + v * AH, yC + 40)); - } - const GX0 = 1200, GX1 = 1770, GY = 640, gx = v => GX0 + ((GX1 - GX0) * v) / 100, ga = seg(lt, 1.2, 1.8); - ctx.globalAlpha = ga; setFont(ctx, FAM.sans, 30, 600); ctx.textAlign = 'left'; ctx.fillText(gz.title, GX0, 500); - if (S.tag) { - setFont(ctx, FAM.mono, 12, 500, 3); ctx.textAlign = 'right'; - const tw = ctx.measureText(S.tag).width; - ctx.globalAlpha = ga * 0.85; ctx.strokeStyle = ink; ctx.lineWidth = 1.5; - ctx.beginPath(); ctx.roundRect(GX1 - tw - 14, 436, tw + 24, 28, 14); ctx.stroke(); ctx.fillText(S.tag, GX1 - 4, 455); - } - ctx.globalAlpha = ga * 0.3; ctx.fillRect(GX0, GY - 2, GX1 - GX0, 4); - for (let v = 0; v <= 100; v += 5) { const major = v % 25 === 0; ctx.globalAlpha = ga * (major ? 0.55 : 0.3); ctx.fillRect(gx(v) - 1, GY + 10, 2, major ? 14 : 8); } - setFont(ctx, FAM.mono, 13, 400); ctx.textAlign = 'center'; ctx.globalAlpha = ga * 0.65; - [0, 25, 50, 75, 100].forEach(v => ctx.fillText(fmt(v), gx(v), GY + 46)); - const cb = seg(lt, 1.6, 2.2), [lo, hi] = gz.range; - ctx.globalAlpha = cb * 0.2; ctx.fillRect(gx(lo), GY - 18, gx(hi) - gx(lo), 36); - ctx.globalAlpha = cb * 0.7; ctx.fillRect(gx(lo) - 1, GY - 18, 2, 36); ctx.fillRect(gx(hi) - 1, GY - 18, 2, 36); - ctx.globalAlpha = cb; setFont(ctx, FAM.mono, 14, 400); ctx.textAlign = 'left'; ctx.fillText(`${gz.rangeLabel} ${fmt(lo)}–${fmt(hi)}%`, gx(lo), GY - 32); - ctx.globalAlpha = cb * 0.9; ctx.fillRect(gx(gz.neutral) - 1.5, GY - 24, 3, 48); - setFont(ctx, FAM.mono, 14, 400); ctx.textAlign = 'center'; ctx.globalAlpha = cb * 0.8; ctx.fillText(`${gz.neutralLabel} ${pct(gz.neutral)}`, gx(gz.neutral), GY + 78); - const cp = seg(lt, ...T_SIG.connector); - if (cp > 0) { - ctx.globalAlpha = 0.6; ctx.strokeStyle = ink; ctx.lineWidth = 2; ctx.setLineDash([1400 * cp, 1400]); - ctx.beginPath(); ctx.moveTo(AC + comp * AH + 110, yC); ctx.bezierCurveTo(1110, yC, 1110, GY, gx(gz.neutral) - 34, GY); ctx.stroke(); ctx.setLineDash([]); - } - let v = gz.neutral + (gz.overshoot - gz.neutral) * E.outExpo(seg(lt, ...T_SIG.slide)); - if (lt > T_SIG.snap) v = lerp(gz.overshoot, gz.target, spring(lt - T_SIG.snap, 2.2, 7)); - const snap = seg(lt, T_SIG.snap, T_SIG.snap + 0.05) * (1 - seg(lt, T_SIG.snap + 0.5, T_SIG.snap + 0.9)); - if (snap > 0) { ctx.globalAlpha = snap; ctx.fillRect(gx(gz.target) - 1.5, GY + 6, 3, 26); } - ctx.globalAlpha = cb; ctx.fillStyle = ink; - ctx.beginPath(); ctx.arc(gx(v), GY, 14, 0, TAU); ctx.fill(); - ctx.fillStyle = THEME[ground]; ctx.beginPath(); ctx.arc(gx(v), GY, 5, 0, TAU); ctx.fill(); - const tl = seg(lt, T_SIG.snap + 0.05, T_SIG.snap + 0.4); - if (tl > 0) { ctx.globalAlpha = tl; ctx.fillStyle = ink; setFont(ctx, FAM.mono, 16, 500); ctx.textAlign = 'center'; ctx.fillText(`${gz.targetLabel} ${pct(gz.target)}`, gx(gz.target), GY - 64); } - ctx.globalAlpha = 1; -} - -// ================================================================== RANKING -// One particle per item leaves a cloud and settles into the score distribution, left -// to right. The top fifth gets its stars, then every item lifts into the sphere. -const HIST = { base: 850, span: 1272 }; -const SPH = { cx: 880, cy: 620, R: 370 }; -const DNC = { cx: 760, cy: 590 }; // the result donut's centre, where the check ring lands -function sphereXY(k, r) { // r: film seconds since the check scene began (negative while items fly in) - const p = G.sph[k], ry = 0.6 + 0.3 * r, rx = 0.32, cr = Math.cos(ry), sr = Math.sin(ry), cx = Math.cos(rx), sx = Math.sin(rx); - const x1 = p[0] * cr + p[2] * sr, z1 = -p[0] * sr + p[2] * cr, y1 = p[1] * cx - z1 * sx, z2 = p[1] * sx + z1 * cx; - const Z = z2 * SPH.R, s = 1300 / (1500 + Z); - return [SPH.cx + x1 * SPH.R * s, SPH.cy + y1 * SPH.R * s, Z, s]; -} -// move: each item's flight into the chart (it lands when the move ends); stars: the first star, -// then one every starStep; fly: seconds before the end, the items lift into the sphere -const T_RANK = { move: 0.9, stars: 3.6, starStep: 0.12, starCount: 5, fly: [1.2, 0.3] }; -const QCOL = ['#34507A', '#2B4FA8', THEME.accent, THEME.accent2, THEME.white]; // score fifths, low to high -function star(ctx, x, y, r) { - ctx.beginPath(); - for (let k = 0; k < 10; k++) { const a = -Math.PI / 2 + (k * Math.PI) / 5, rr = k % 2 ? r * 0.45 : r; ctx.lineTo(x + rr * Math.cos(a), y + rr * Math.sin(a)); } - ctx.closePath(); ctx.fill(); -} -function sRank(ctx, t, lt) { - const R = CONTENT.rank, D = choreoLen(at.rank), I = G.items; - ctx.fillStyle = THEME.dark; ctx.fillRect(0, 0, W, H); - const flyAt = D - T_RANK.fly[0], deep = seg(lt, flyAt, D - 0.5); - if (deep > 0) { ctx.globalAlpha = deep; ctx.fillStyle = THEME.deep; ctx.fillRect(0, 0, W, H); ctx.globalAlpha = 1; } - camera(ctx, pump(t) * (1 + 0.02 * seg(lt, 1.0, flyAt) * (1 - E.inOutCubic(seg(lt, flyAt, D - 0.2)))), 0, 0, W / 2, 700); - const out = 1 - seg(lt, flyAt - 0.1, flyAt + 0.3), x0 = I.x0, span = I.span; - ctx.globalAlpha = out; - headline(ctx, R.title, R.sub, THEME.white, lt, 0.2); - const ax = seg(lt, 0.6, 1.2) * out; - ctx.globalAlpha = ax * 0.3; ctx.fillStyle = THEME.white; ctx.fillRect(x0 - 12, HIST.base + 8, (span + 24) * E.outExpo(seg(lt, 0.6, 1.6)), 2); - setFont(ctx, FAM.mono, 14, 400); ctx.textAlign = 'center'; ctx.globalAlpha = ax * 0.6; - [0, 25, 50, 75, 100].forEach(s => { const x = x0 + (s / 100) * span; ctx.fillRect(x - 1, HIST.base + 10, 2, 8); ctx.fillText(fmt(s), x, HIST.base + 40); }); - setFont(ctx, FAM.mono, 13, 500, 3); ctx.textAlign = 'left'; ctx.globalAlpha = ax * 0.75; ctx.fillText(R.axis, x0 - 12, HIST.base + 72); - if (seg(lt, 0.9, 1.5) > 0) { - let bx = 1170; - R.pillars.forEach(({ name, weight }, j) => { - const segW = (600 * weight) / 100, e = E.outExpo(seg(lt, 0.9 + 0.2 * j, 1.7 + 0.2 * j)); - ctx.globalAlpha = out * [1, 0.75, 0.5][j % 3]; ctx.fillStyle = [THEME.white, THEME.sky, THEME.soft][j % 3]; - ctx.fillRect(bx, 222, (segW - 4) * e, 12); - ctx.globalAlpha = out * e * 0.8; setFont(ctx, FAM.mono, 12, 500, 1); ctx.fillStyle = THEME.white; ctx.textAlign = 'center'; - ctx.fillText(`${name} ${fmt(weight)}%`, bx + segW / 2, 262); - bx += segW; - }); - } - const stars = seg(lt, T_RANK.stars, T_RANK.stars + 0.3) * out, focus = seg(lt, T_RANK.stars - 0.1, T_RANK.stars + 0.2) * (1 - seg(lt, flyAt - 0.1, flyAt + 0.1)); - const fly = seg(lt, flyAt, D - T_RANK.fly[1]); - for (let q = 0; q < 5; q++) { - const idx = I.groups[q]; - ctx.fillStyle = css(mixc(hex(QCOL[q]), RGB.sky, fly), q < 4 ? 1 - 0.45 * focus : 1); - ctx.globalAlpha = 1; ctx.beginPath(); - for (let j = 0; j < idx.length; j++) { - const i = idx[j]; - const cxp = I.cx[i] + 14 * Math.sin(lt * 0.8 + I.ph[i]), cyp = I.cy[i] + 9 * Math.cos(lt * 0.7 + I.ph[i]); - const m = E.inOutCubic(seg(lt, I.del[i], I.del[i] + T_RANK.move)); - let x = lerp(cxp, I.sx[i], m), y = lerp(cyp, I.sy[i], m); - if (m > 0 && m < 1) { const dx = I.sx[i] - cxp, dy = I.sy[i] - cyp, L = Math.hypot(dx, dy) + 1e-6, sw = Math.sin(Math.PI * m) * 70 * I.sgn[i]; x += (-dy / L) * sw; y += (dx / L) * sw; } - let z = lerp(5, I.dot, m); - const f = E.inOutCubic(seg(lt, flyAt + I.sd[i], D - T_RANK.fly[1] + I.sd[i])); - if (f > 0) { const [px, py, , s] = sphereXY(I.perm[i], t - ST[at.check]); x = lerp(x, px, f); y = lerp(y, py, f); z = lerp(z, 1.5 + 2.6 * s, f); } - ctx.rect(x - z / 2, y - z / 2, z, z); - } - ctx.fill(); - } - if (stars > 0) { - const b0 = I.topFrom, sx0 = x0 + b0 * I.binW, sw = (I.bins - b0) * I.binW - 8, sy = HIST.base - I.topH - 60; - ctx.fillStyle = THEME.white; - for (let k = 0; k < T_RANK.starCount; k++) { - const sp = spring(lt - T_RANK.stars - T_RANK.starStep * k, 2, 7); - if (sp <= 0) continue; - ctx.globalAlpha = stars; star(ctx, sx0 + 26 + ((sw - 52) * k) / Math.max(1, T_RANK.starCount - 1), sy, 13 * sp); - } - setFont(ctx, FAM.mono, 13, 500, 2); ctx.textAlign = 'center'; ctx.globalAlpha = stars * 0.8; - ctx.fillText(R.top, sx0 + sw / 2, sy - 32); - } - ctx.globalAlpha = 1; -} - -// ================================================================== CHECK -// The same items as a slowly turning sphere. A scan passes over it and every item -// takes its group's colour; the flagged group steps out. Then it all folds into a ring. -const T_CHECK = { scan: [1.0, 3.6], flag: 3.8, collapse: [1.15, 0.35], collapseStagger: 0.3 }; // collapse: before the end -function sCheck(ctx, t, lt) { - const C = CONTENT.check, D = choreoLen(at.check), N = G.sph.length; - ctx.fillStyle = THEME.deep; ctx.fillRect(0, 0, W, H); - camera(ctx, pump(t)); - const out = 1 - seg(lt, D - T_CHECK.collapse[0] - 0.15, D - T_CHECK.collapse[0] + 0.25), scanEnd = T_CHECK.scan[1]; - ctx.globalAlpha = out; - headline(ctx, C.title, C.sub, THEME.white, lt, 0.3); - const silR = SPH.R * 0.9; // the sphere's projected silhouette: the scan stays inside it - const scanY = lerp(SPH.cy - silR, SPH.cy + silR, E.inOutCubic(seg(lt, ...T_CHECK.scan))); - const flag = spring(lt - T_CHECK.flag, 1.2, 5); - const cls = G.cls, fills = [...C.groups.map(gr => THEME[gr.color] || THEME.muted), css(RGB.sky, 0.85), THEME.accent]; - const unscanned = C.groups.length, ringed = C.groups.length + 1; - const pts = []; - for (let k = 0; k < N; k++) { - let [x, y, Z, s] = sphereXY(k, lt / pace(at.check)); - if (cls[k] === C.flag && lt > T_CHECK.flag) { const push = 1 + 0.09 * flag; x = SPH.cx + (x - SPH.cx) * push; y = SPH.cy + (y - SPH.cy) * push; } - const lag = T_CHECK.collapseStagger * (k / N), m = E.inOutCubic(seg(lt, D - T_CHECK.collapse[0] + lag, D - T_CHECK.collapse[1] + lag)); - if (m > 0) { const a = (TAU * k) / N - Math.PI / 2; x = lerp(x, DNC.cx + 272 * Math.cos(a), m); y = lerp(y, DNC.cy + 272 * Math.sin(a), m); s = lerp(s, 0.95, m); Z = lerp(Z, 0, m); } - pts.push([x, y, Z, s, m > 0.5 ? ringed : y < scanY || lt > scanEnd + 0.1 ? cls[k] : unscanned]); - } - for (const back of [true, false]) { - for (let g = 0; g < fills.length; g++) { - ctx.fillStyle = fills[g]; ctx.globalAlpha = back ? 0.45 : 1; ctx.beginPath(); - for (const [x, y, Z, s, gg] of pts) { - if (gg !== g || (Z > 0) !== back) continue; - const r = (2.6 + 4.2 * (s - 0.7)) * (gg === C.flag && lt > T_CHECK.flag ? 1 + 0.6 * Math.exp(-(lt - T_CHECK.flag) * 3) : 1); - ctx.moveTo(x + r, y); ctx.arc(x, y, Math.max(0.8, r), 0, TAU); - } - ctx.fill(); - } - } - const sa = seg(lt, T_CHECK.scan[0] - 0.1, T_CHECK.scan[0] + 0.2) * (1 - seg(lt, scanEnd - 0.1, scanEnd + 0.2)); - if (sa > 0) { - const dy = scanY - SPH.cy, rx = 1.08 * Math.sqrt(Math.max(0, silR * silR - dy * dy)); - ctx.globalAlpha = sa; ctx.strokeStyle = THEME.accent2; ctx.lineWidth = 2.5; ctx.shadowColor = THEME.accent; ctx.shadowBlur = 24; - ctx.beginPath(); ctx.ellipse(SPH.cx, scanY, Math.max(1, rx), Math.max(1, rx * 0.16), 0, 0, TAU); ctx.stroke(); - ctx.shadowBlur = 0; - } - const lx = 1370; - ctx.globalAlpha = out * seg(lt, scanEnd - 0.4, scanEnd); setFont(ctx, FAM.sans, 30, 700); ctx.fillStyle = THEME.white; ctx.textAlign = 'left'; - ctx.fillText(C.legend, lx, 450); - C.groups.forEach(({ name, count, color }, k) => { - const a = out * seg(lt, scanEnd - 0.2 + 0.18 * k, scanEnd + 0.2 + 0.18 * k), y = 510 + 50 * k; - if (a <= 0) return; - ctx.globalAlpha = a; ctx.fillStyle = THEME[color] || THEME.muted; ctx.beginPath(); ctx.arc(lx + 8, y - 8, 8, 0, TAU); ctx.fill(); - ctx.fillStyle = THEME.white; setFont(ctx, FAM.sans, 24, 500); ctx.textAlign = 'left'; ctx.fillText(name, lx + 32, y); - setFont(ctx, FAM.mono, 20, 500); ctx.textAlign = 'right'; ctx.fillText(fmt(count), 1770, y); - }); - ctx.globalAlpha = out * seg(lt, scanEnd + 0.6, scanEnd + 1.0) * 0.6; setFont(ctx, FAM.mono, 13, 400, 2); ctx.textAlign = 'left'; ctx.fillStyle = THEME.white; - ctx.fillText(CONTENT.asOf, lx, 510 + 50 * C.groups.length + 30); - ctx.globalAlpha = 1; -} - -// ================================================================== RESULT -// The ring becomes the result: classes inside, items flying into place outside, the -// names on the right. During the hold each class steps forward in turn. -const DN = { r0: 150, r1: 212, r2: 224, r3: 318 }; -// sweep: the classes draw on; items: the first item flies in, then one every itemStep, each on a -// spring of itemSpring Hz (it locks when springLands); focus: each class steps forward for -// focusLen; flood: seconds before the end, the next card's colour fills the frame -const T_RES = { sweep: [0.2, 1.6], items: 0.9, itemStep: 0.2, itemSpring: 1.0, focus: 3.2, focusLen: 1.0, flood: [1.1, 0.1] }; -function ring(ctx, rin, rout, a0, a1, push = 0) { - const am = (a0 + a1) / 2, ox = Math.cos(am) * push, oy = Math.sin(am) * push; - ctx.beginPath(); ctx.arc(DNC.cx + ox, DNC.cy + oy, rout, a0, a1); ctx.arc(DNC.cx + ox, DNC.cy + oy, rin, a1, a0, true); ctx.closePath(); ctx.fill(); -} -function sResult(ctx, t, lt) { - const Rz = CONTENT.result, D = choreoLen(at.result); - ctx.fillStyle = THEME.paper; ctx.fillRect(0, 0, W, H); - camera(ctx, pump(t) * (1 + 0.015 * seg(lt, 1.0, D - T_RES.flood[0])), 0, 0, DNC.cx, DNC.cy); - headline(ctx, Rz.title, Rz.sub, THEME.text, lt, 0.3); - const focusOf = c => bump(lt, T_RES.focus + c * T_RES.focusLen, T_RES.focus + (c + 1) * T_RES.focusLen, 0.3); - const anyFocus = Math.max(0, ...Rz.classes.map((_, c) => focusOf(c))); - const rot = -Math.PI / 2 + 0.035 * lt, gap = 0.012, A = TAU * E.outExpo(seg(lt, ...T_RES.sweep)); - let a = 0; - Rz.classes.forEach(({ weight, color }, c) => { - const a0 = a, a1 = a + (TAU * weight) / 100, f = focusOf(c); - a = a1; - if (a0 >= A) return; - ctx.globalAlpha = 1 - 0.55 * (anyFocus - f); ctx.fillStyle = THEME[color]; - ring(ctx, DN.r0, DN.r1, rot + a0 + gap, rot + Math.min(a1, A) - gap, 10 * E.inOutCubic(f)); - }); - a = 0; - Rz.items.forEach(({ weight, color, cls }, k) => { - const a0 = a, a1 = a + (TAU * weight) / 100, s = lt - T_RES.items - T_RES.itemStep * k, sp = spring(s, T_RES.itemSpring, 6), f = focusOf(cls); - a = a1; - if (sp <= 0) return; - const off = 1 - sp; - ctx.globalAlpha = seg(s, 0, 0.25) * (1 - 0.55 * (anyFocus - f)); ctx.fillStyle = THEME[color]; - ring(ctx, DN.r2 + 140 * off, DN.r3 + 140 * off, rot + a0 + gap - 0.6 * off, rot + a1 - gap - 0.6 * off, 10 * E.inOutCubic(f)); - }); - ctx.globalAlpha = seg(lt, 0.6, 1.1); ctx.textAlign = 'center'; ctx.fillStyle = THEME.text; - setFont(ctx, FAM.sans, 72, 800); ctx.fillText(Rz.center.big, DNC.cx, DNC.cy + 8); - setFont(ctx, FAM.sans, 26, 500); ctx.fillText(Rz.center.name, DNC.cx, DNC.cy + 48); - setFont(ctx, FAM.mono, 13, 400, 2); ctx.fillStyle = THEME.muted; ctx.fillText(Rz.center.note, DNC.cx, DNC.cy + 78); - const LX = 1180, RX = 1770; - let y = 340, row = 0; - Rz.classes.forEach((cl, c) => { - const dim = 1 - 0.55 * (anyFocus - focusOf(c)); - const ra = seg(lt, 1.6 + 0.14 * row, 2.0 + 0.14 * row), dx = 40 * (1 - E.outExpo(ra)); - ctx.globalAlpha = ra * dim; ctx.fillStyle = THEME.text; setFont(ctx, FAM.sans, 22, 700); ctx.textAlign = 'left'; ctx.fillText(cl.name, LX + dx, y); - setFont(ctx, FAM.mono, 18, 500); ctx.textAlign = 'right'; ctx.fillText(pct(cl.weight), RX + dx, y); - y += 38; row++; - for (const it of Rz.items.filter(item => item.cls === c)) { - const rb = seg(lt, 1.6 + 0.14 * row, 2.0 + 0.14 * row), dx2 = 40 * (1 - E.outExpo(rb)); - ctx.globalAlpha = rb * dim; ctx.fillStyle = THEME[it.color]; ctx.fillRect(LX + dx2, y - 13, 12, 12); - setFont(ctx, FAM.sans, 19, 400); ctx.fillStyle = THEME.text; ctx.textAlign = 'left'; - const lines = wrap(ctx, it.name, RX - LX - 90); - lines.forEach((ln, j) => ctx.fillText(ln, LX + 24 + dx2, y + j * 26)); - setFont(ctx, FAM.mono, 16, 400); ctx.fillStyle = THEME.muted; ctx.textAlign = 'right'; ctx.fillText(pct(it.weight), RX + dx2, y); - y += 26 * lines.length + 12; row++; - } - y += 14; - }); - ctx.globalAlpha = 1; - const fr = 2200 * E.inOutCubic(seg(lt, D - T_RES.flood[0], D - T_RES.flood[1])), next = CONTENT.cards[0]; - if (fr > 1) { ctx.fillStyle = THEME[next ? next.bg : 'accent']; ctx.beginPath(); ctx.arc(DNC.cx, DNC.cy, fr, 0, TAU); ctx.fill(); } -} - -// ================================================================== RHYTHM -// Cards on the beat grid: the numbers, then the cadence. A `quiet` card is the -// punchline: one small word, held in total silence. -// the count-up: it takes `span` of its card on `ease`; the soundtrack plays `ticks` odometer -// ticks, placed where the number on screen passes each step -const COUNT = { span: 0.55, ease: E.outExpo, ticks: 40 }; -const cardIndex = tf => clamp(Math.floor((tf - ST[at.rhythm]) / CARD + 1e-6), 0, CONTENT.cards.length - 1); -function sRhythm(ctx, t, lt, tf) { - const k = cardIndex(tf), c = t - (ST[at.rhythm] + k * CARD), cd = CONTENT.cards[k], fg = inkOn(cd.bg); - ctx.fillStyle = THEME[cd.bg]; ctx.fillRect(0, 0, W, H); - if (cd.quiet) { - setFont(ctx, FAM.sans, 40, 400); ctx.fillStyle = fg; ctx.textAlign = 'center'; - ctx.globalAlpha = seg(c, 0, 0.16 * CARD); ctx.fillText(cd.quiet, W / 2, H / 2 + 14); ctx.globalAlpha = 1; - return; - } - const rv = 0.3 * CARD; - camera(ctx, 1.03 - 0.03 * E.outExpo(clamp(c / (0.48 * CARD))) + 0.02 * clamp(c / CARD)); - const e = E.outExpo(clamp(c / rv)); - ctx.textAlign = 'center'; - let lineY; - if (cd.word) { - let size = 180; - setFont(ctx, FAM.sans, size, 800, -4); - const w = ctx.measureText(cd.word).width; - if (w > 1500) size *= 1500 / w; - const yb = H / 2 + 40; - reveal(ctx, cd.word, W / 2, yb, size, 800, fg, c, { dur: rv, align: 'center', spacing: -4 }); - ctx.globalAlpha = e * 0.85; setFont(ctx, FAM.mono, 24, 500, 5); ctx.fillStyle = fg; ctx.fillText(cd.label, W / 2, yb + 92); - lineY = yb + 130; - } else { - const yb = H / 2 + 70, size = 320; - if (cd.count) { - // the number is discrete, so it reads the frame's time: one number per frame, never a - // blend of the numbers its motion-blur sub-frames would show - const cf = tf - (ST[at.rhythm] + k * CARD), n = Math.round(cd.count * COUNT.ease(clamp(cf / (CARD * COUNT.span)))); - setFont(ctx, FAM.sans, size, 800, -6); - const wFinal = ctx.measureText(fmt(cd.count)).width; - reveal(ctx, fmt(n), W / 2 + wFinal / 2, yb, size, 800, fg, c, { dur: rv, align: 'right', spacing: -6 }); - } else reveal(ctx, cd.big, W / 2, yb, size, 800, fg, c, { dur: rv, align: 'center', spacing: -6 }); - ctx.globalAlpha = e; setFont(ctx, FAM.sans, 60, 600); ctx.fillStyle = fg; ctx.textAlign = 'center'; ctx.fillText(cd.label, W / 2, yb + 110); - lineY = yb + 160; - } - ctx.globalAlpha = 0.25; ctx.fillStyle = fg; ctx.fillRect(W / 2 - 180, lineY, 360, 3); - ctx.globalAlpha = 1; ctx.fillRect(W / 2 - 180, lineY, 360 * clamp(c / CARD), 3); -} - -// ================================================================== END -// The name on the downbeat after the silence; the ball from the first scene returns to -// land as the full stop of the closing line. -// drop: the ball starts falling; contacts: its first two landings, on beats 5 and 6 (the rest -// follow from the bounce); recap: seconds after the ball settles, then the typing time; fade: -// seconds before the end -const T_END = { drop: 1.35, contacts: [4 * BEAT, 5 * BEAT], recap: [0.15, 0.8], fade: 0.725 }; -function sEnd(ctx, t, lt) { - const En = G.end, D = choreoLen(at.end); - ctx.fillStyle = THEME.dark; ctx.fillRect(0, 0, W, H); - camera(ctx, lerp(1.04, 1, E.outExpo(seg(lt, 0, 1.6))) * (1 + 0.015 * seg(lt, 1.0, D - 0.6)), 0, 0, W / 2, En.yb); - setFont(ctx, FAM.sans, En.fs, 700, -2); ctx.fillStyle = THEME.white; ctx.textAlign = 'center'; - ctx.save(); ctx.beginPath(); ctx.rect(0, En.yb - En.fs * 1.3, W, En.fs * 1.3 + En.fs * 0.3); ctx.clip(); - En.L.ch.forEach((ch, i) => { - const s = lt - 0.03 * i; - if (s <= 0) return; - ctx.globalAlpha = clamp(s / 0.2); ctx.fillText(ch, W / 2 + En.L.xs[i], En.yb + (1 - E.outExpo(clamp(s / 0.9))) * En.fs * 0.95); - }); - ctx.restore(); - ctx.globalAlpha = 1; - const ul = (E.outExpo(seg(lt, 0.6, 1.5)) * En.L.total) / 2; - if (ul > 0.5) { ctx.fillStyle = THEME.accent; ctx.fillRect(W / 2 - ul, En.yb + 40, ul * 2, 5); } - setFont(ctx, FAM.sans, 64, 300); ctx.fillStyle = THEME.white; ctx.textAlign = 'left'; - ctx.save(); ctx.beginPath(); ctx.rect(0, En.yb2 - 90, W, 115); ctx.clip(); - En.words.forEach((wd, k) => { - const s = lt - (0.9 + 0.12 * k); - if (s > 0) ctx.fillText(wd.text, wd.x, En.yb2 + (1 - E.outExpo(seg(s, 0, 0.8))) * 90); - }); - ctx.restore(); - const b = En.ball, st = b.state(lt); - if (lt > T_END.drop) drawBall(ctx, lerp(En.px + 220, En.px, E.outCubic(clamp((lt - T_END.drop) / (b.settle - T_END.drop)))), st, En.rP, b.v0, THEME.accent); - ctx.globalAlpha = 1; - typed(ctx, En.recap, W / 2 - En.recapW / 2, En.yb + 270, THEME.white, lt - b.settle - T_END.recap[0], T_END.recap[1], { spacing: 4, alpha: 0.6 }); - flash(ctx, t, ST[at.end], 0.1, 6); - const fo = E.inCubic(seg(lt, D - T_END.fade, D)); - if (fo > 0) { ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = fo; ctx.fillStyle = THEME.dark; ctx.fillRect(0, 0, W, H); ctx.globalAlpha = 1; } -} - -// ================================================================== transitions -function sceneIdx(tf) { for (let i = SCENES.length - 1; i > 0; i--) if (tf >= ST[i] - 1e-9) return i; return 0; } -function drawScene(ctx, i, t, tf) { ctx.save(); SCENES[i].draw(ctx, t, (t - ST[i]) * pace(i), tf); ctx.restore(); } -function clipCircle(ctx, x, y, r) { ctx.beginPath(); ctx.arc(x, y, r, 0, TAU); ctx.clip(); } -const PUSH = Math.min(0.9, 0.12 * sceneLen(at.signal)); -const TRANS = [ - { a: absTime(at.scale, choreoLen(at.scale) - T_SCALE.iris), b: absTime(at.mix, 0.7), draw(ctx, t, tf) { // the ball becomes a ring, the ring an iris - drawScene(ctx, at.scale, t, tf); - const g = irisGeom(t); - if (g.hole > 0.3) { ctx.save(); clipCircle(ctx, W / 2, H / 2, g.hole); drawScene(ctx, at.mix, t, tf); ctx.restore(); } - } }, - { a: ST[at.rank] - PUSH, b: ST[at.rank] + 0.02, draw(ctx, t, tf) { // push up - const e = E.inOutExpo(seg(t, ST[at.rank] - PUSH, ST[at.rank])); - ctx.save(); ctx.translate(0, -H * e); drawScene(ctx, at.signal, t, tf); ctx.restore(); - ctx.save(); ctx.translate(0, H * (1 - e)); drawScene(ctx, at.rank, t, tf); ctx.restore(); - } }, - { a: ST[at.result], b: absTime(at.result, 1.05), draw(ctx, t, tf) { // the ring of items opens into the result - drawScene(ctx, at.check, t, tf); - const r = 1500 * E.inOutCubic(seg(t, ST[at.result], absTime(at.result, 1.0))); - if (r > 0.3) { ctx.save(); clipCircle(ctx, DNC.cx, DNC.cy, r); drawScene(ctx, at.result, t, tf); ctx.restore(); } - } }, -]; - -// ================================================================== HUD -const pad2 = n => String(n).padStart(2, '0'); -function hudInk(i, tf) { - if (i === at.rhythm) { const cd = CONTENT.cards[cardIndex(tf)]; return cd.quiet ? null : inkOn(cd.bg); } - return inkOn(SCENES[i].ground || PARTC[CONTENT.mix.divePart]); -} -function drawHud(ctx, t, tf) { - if (!HUD_ON) return; - const i = sceneIdx(tf), col = hudInk(i, tf); - const a = 0.9 * seg(t, 0.06, 0.5) * (1 - seg(t, DUR - 0.8, DUR - 0.2)); - if (!col || a <= 0) return; - const sc = SCENES[i]; - ctx.save(); ctx.setTransform(1, 0, 0, 1, 0, 0); - ctx.globalAlpha = a; ctx.fillStyle = col; ctx.textBaseline = 'alphabetic'; - setFont(ctx, FAM.mono, 15, 500, 3); ctx.textAlign = 'left'; ctx.fillText(CONTENT.brand, 84, 76); - const steps = CONTENT.process, sep = ' — '; - setFont(ctx, FAM.mono, 14, 500, 3); - const parts = []; - steps.forEach((s, k) => { parts.push([s, k]); if (k < steps.length - 1) parts.push([sep, -1]); }); - let x = W - 84; - for (let p = parts.length - 1; p >= 0; p--) { - const [txt, k] = parts[p], w = ctx.measureText(txt).width; - x -= w; - ctx.globalAlpha = a * (k < 0 ? 0.3 : sc.step >= steps.length || k === sc.step ? 1 : k < sc.step ? 0.6 : 0.3); - ctx.fillText(txt, x, 76); - if (k === sc.step) { ctx.globalAlpha = a; ctx.fillRect(x, 86, w - 3, 2); } - } - const since = tf - ST[i], idx = `${pad2(i + 1)} / ${pad2(SCENES.length)}`; - ctx.globalAlpha = a; setFont(ctx, FAM.mono, 15, 500, 3); ctx.textAlign = 'left'; - ctx.fillText(idx, 84, H - 92); - ctx.fillText(sc.name.slice(0, Math.ceil(sc.name.length * seg(since, 0, 0.3))), 84 + ctx.measureText(idx).width + 20, H - 92); - setFont(ctx, FAM.mono, 14, 400, 1.5); ctx.globalAlpha = a * 0.62; - ctx.fillText(sc.spec.slice(0, Math.ceil(sc.spec.length * seg(since, 0.1, 0.7))), 84, H - 64); - ctx.textAlign = 'right'; setFont(ctx, FAM.mono, 14, 400, 2); ctx.fillText(CONTENT.asOf, W - 84, H - 64); - const x0 = W / 2 - 240, x1 = W / 2 + 240, y = H - 78, ph = x0 + ((x1 - x0) * tf) / DUR; - ctx.globalAlpha = a * 0.3; ctx.fillRect(x0, y - 0.75, x1 - x0, 1.5); - for (let k = 0; k <= SCENES.length; k++) ctx.fillRect(x0 + ((x1 - x0) * ST[k]) / DUR - 0.75, y - 4, 1.5, 8); - ctx.globalAlpha = a; ctx.fillRect(x0, y - 1, ph - x0, 2); ctx.fillRect(ph - 3, y - 6, 6, 12); - ctx.restore(); -} - -// ================================================================== render -function render(ctx, t, tf = t) { - t = clamp(t, 0, DUR - 1e-6); tf = clamp(tf, 0, DUR - 1e-6); - ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'; ctx.filter = 'none'; - const tr = TRANS.find(x => tf >= x.a && tf < x.b); - if (tr) tr.draw(ctx, t, tf); else drawScene(ctx, sceneIdx(tf), t, tf); - ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.globalAlpha = 1; ctx.globalCompositeOperation = 'source-over'; - drawHud(ctx, t, tf); -} - -// ------------------------------------------------------------------ finishing pass (after the motion blur) -function post(src, dst, tf) { - const o = dst.getContext('2d'), sc = SCENES[sceneIdx(tf)]; - o.setTransform(1, 0, 0, 1, 0, 0); o.globalAlpha = 1; o.filter = 'none'; - o.globalCompositeOperation = 'copy'; o.drawImage(src, 0, 0); - if (sc.bloom > 0) { - const b = G.bloom.getContext('2d'); - b.globalCompositeOperation = 'copy'; b.filter = 'blur(6px)'; b.drawImage(dst, 0, 0, W / 4, H / 4); b.filter = 'none'; - o.globalCompositeOperation = 'screen'; o.globalAlpha = sc.bloom; o.drawImage(G.bloom, 0, 0, W, H); o.globalAlpha = 1; - } - if (GRAIN > 0) { - const f = Math.round(tf * FPS), pat = o.createPattern(G.grain[f % G.grain.length], 'repeat'); - pat.setTransform(new DOMMatrix([2, 0, 0, 2, (hash(f) * 512) | 0, (hash(f + 99) * 512) | 0])); - o.globalCompositeOperation = 'overlay'; o.globalAlpha = GRAIN; o.fillStyle = pat; o.fillRect(0, 0, W, H); - } - const vg = o.createRadialGradient(W / 2, H / 2, H * 0.42, W / 2, H / 2, H * 1.08), d = RGB.deep; - vg.addColorStop(0, css(d, 0)); vg.addColorStop(1, css(d, 1)); - o.globalCompositeOperation = 'source-over'; o.globalAlpha = sc.vig; o.fillStyle = vg; o.fillRect(0, 0, W, H); - o.globalAlpha = 1; -} - -// ------------------------------------------------------------------ init -function initItems() { - const hist = CONTENT.rank.hist, bins = hist.length, N = hist.reduce((a, b) => a + b, 0), rnd = mulberry32(11), F32 = () => new Float32Array(N); - const I = { cx: F32(), cy: F32(), sx: F32(), sy: F32(), ph: F32(), del: F32(), sgn: F32(), sd: F32(), bin: new Uint16Array(N), perm: new Uint32Array(N) }; - I.bins = bins; I.span = HIST.span; I.binW = HIST.span / bins; I.x0 = (W - HIST.span) / 2; - const perRow = Math.max(1, Math.floor((I.binW - 6) / 14)), rowsMax = Math.ceil(Math.max(...hist) / perRow); - const pitch = Math.max(4, Math.min(14, Math.floor(330 / rowsMax), (I.binW - 6) / perRow)); - I.dot = pitch - 4; I.topFrom = Math.floor(bins * 0.8); - I.topH = Math.ceil(Math.max(...hist.slice(I.topFrom)) / perRow) * pitch; - let i = 0; - hist.forEach((n, b) => { - for (let j = 0; j < n; j++, i++) { - I.bin[i] = b; - I.sx[i] = I.x0 + b * I.binW + (j % perRow) * pitch + pitch / 2; I.sy[i] = HIST.base - pitch / 2 - Math.floor(j / perRow) * pitch; - const a = rnd() * TAU, r = Math.sqrt(rnd()); - I.cx[i] = W / 2 + Math.cos(a) * r * 560; I.cy[i] = 560 + Math.sin(a) * r * 240; - I.ph[i] = rnd() * TAU; I.del[i] = 1.0 + (b / Math.max(1, bins - 1)) + 0.25 * rnd(); I.sgn[i] = rnd() < 0.5 ? -1 : 1; I.sd[i] = rnd() * 0.3; - } - }); - const order = [...Array(N).keys()]; - for (let k = N - 1; k > 0; k--) { const j = Math.floor(rnd() * (k + 1)); [order[k], order[j]] = [order[j], order[k]]; } - order.forEach((p, k) => { I.perm[k] = p; }); - I.groups = [0, 1, 2, 3, 4].map(q => Int32Array.from([...Array(N).keys()].filter(k => Math.min(4, Math.floor((5 * I.bin[k]) / bins)) === q))); - return I; -} -function initSphere(N) { - const sph = []; - for (let k = 0; k < N; k++) { - const y = 1 - (2 * (k + 0.5)) / N, r = Math.sqrt(1 - y * y), th = k * Math.PI * (3 - Math.sqrt(5)); - sph.push([Math.cos(th) * r, y, Math.sin(th) * r]); - } - const groups = CONTENT.check.groups, rnd = mulberry32(5), cls = []; - groups.forEach(({ count }, g) => { for (let j = 0; j < count && cls.length < N; j++) cls.push(g); }); - while (cls.length < N) cls.push(groups.length - 1); - for (let k = cls.length - 1; k > 0; k--) { const j = Math.floor(rnd() * (k + 1)); [cls[k], cls[j]] = [cls[j], cls[k]]; } - return { sph, cls }; -} -function initEnd(x) { - const e = CONTENT.end, fs = 128, L = letters(x, e.name, FAM.sans, fs, 700, -2), yb = 480, yb2 = yb + 160, rP = 7; - setFont(x, FAM.sans, 64, 300); - const words = e.line.split(' '), sp = x.measureText(' ').width, ws = words.map(w => x.measureText(w).width); - const tot = ws.reduce((a, b) => a + b, 0) + sp * (words.length - 1); - let cx = W / 2 - tot / 2 - 8; - const pos = words.map((w, i) => { const o = { text: w, x: cx }; cx += ws[i] + sp; return o; }); - const ball = makeBounce({ y0: -30, rest: yb2 - rP, tDrop: T_END.drop, c0: T_END.contacts[0], c1: T_END.contacts[1], sq: SQ }); - setFont(x, FAM.mono, 16, 400, 4); - return { fs, L, yb, yb2, rP, px: W / 2 - tot / 2 - 8 + tot + 5 + rP, ball, words: pos, recap: e.recap, recapW: x.measureText(e.recap).width }; -} -// the cue sheet: score.py places every sound from these film times. Every entry reads the same -// timing record its scene animates with, so re-timing a scene moves its sound with it. -function cueSheet() { - const r = v => +v.toFixed(4), countAt = CONTENT.cards.findIndex(c => c.count), end = i => choreoLen(i); - const win = (i, a, b) => [r(absTime(i, a)), r(absTime(i, b))]; - const { hops, settle } = scaleContacts(); - const countStart = ST[at.rhythm] + countAt * CARD, countLen = COUNT.span * CARD; - return { - bpm: BPM, scenes: SCENES.map(s => s.id), starts: ST.map(r), silence: SIL.map(r), groove: GROOVE.map(r), kicks: kickTimes().map(r), - scale: hops.map(u => r(absTime(at.scale, u))), scaleSettle: r(absTime(at.scale, settle)), - rise: win(at.scale, end(at.scale) - T_SCALE.rise[0], end(at.scale) - T_SCALE.rise[1]), arrive: r(ST[at.mix]), - columns: CONTENT.mix.rows.map((_, k) => r(absTime(at.mix, T_MIX.rise + T_MIX.stagger * k))), - dive: win(at.mix, end(at.mix) - T_MIX.dive[0], end(at.mix) - T_MIX.dive[1]), cut: r(ST[at.signal]), - inputs: CONTENT.signal.inputs.map((_, i) => r(absTime(at.signal, T_SIG.inputs + T_SIG.stagger * i))), - fold: win(at.signal, ...T_SIG.fold), connector: win(at.signal, ...T_SIG.connector), - slide: win(at.signal, ...T_SIG.slide), snap: r(absTime(at.signal, T_SIG.snap)), push: [r(ST[at.rank] - PUSH), r(ST[at.rank])], - landings: Array.from(G.items.del, d => r(absTime(at.rank, d + T_RANK.move))), - stars: Array.from({ length: T_RANK.starCount }, (_, k) => r(absTime(at.rank, T_RANK.stars + T_RANK.starStep * k))), - fly: [r(absTime(at.rank, end(at.rank) - T_RANK.fly[0])), r(ST[at.check])], - scan: win(at.check, ...T_CHECK.scan), flag: r(absTime(at.check, T_CHECK.flag)), - collapse: win(at.check, end(at.check) - T_CHECK.collapse[0], end(at.check) - T_CHECK.collapse[1] + T_CHECK.collapseStagger), - iris: r(ST[at.result]), sweep: win(at.result, ...T_RES.sweep), - items: CONTENT.result.items.map((_, k) => r(absTime(at.result, T_RES.items + T_RES.itemStep * k + springLands(T_RES.itemSpring)))), - focus: CONTENT.result.classes.map((_, c) => r(absTime(at.result, T_RES.focus + c * T_RES.focusLen))), - flood: win(at.result, end(at.result) - T_RES.flood[0], end(at.result) - T_RES.flood[1]), - cards: CONTENT.cards.map((_, k) => r(ST[at.rhythm] + k * CARD)), card: r(CARD), quiet: QUIET, - countTicks: countAt < 0 ? [] : Array.from({ length: COUNT.ticks }, (_, k) => r(countStart + countLen * reach(COUNT.ease, (k + 1) / COUNT.ticks))), - end: r(ST[at.end]), endBall: G.end.ball.contacts.map(c => r(absTime(at.end, c))), fade: [r(absTime(at.end, end(at.end) - T_END.fade)), r(DUR)], - }; -} -async function init() { - if (document.fonts) { - const sample = 'Aa1 ąćęłńóśźżĄĆĘŁŃÓŚŹŻäöüßéèàç'; // pulls in the latin-ext faces too - await Promise.all(['800 100px "' + FAM.sans + '"', '300 100px "' + FAM.sans + '"', '400 20px "' + FAM.mono + '"', '500 20px "' + FAM.mono + '"'].map(f => document.fonts.load(f, sample))); - } - const x = mkCanvas(64, 64).getContext('2d'); - G.items = initItems(); - const s = initSphere(G.items.cx.length); G.sph = s.sph; G.cls = s.cls; - G.end = initEnd(x); - G.bloom = mkCanvas(W / 4, H / 4); - G.grain = [0, 1, 2, 3].map(k => { - const cv = mkCanvas(256, 256), cx = cv.getContext('2d'), im = cx.createImageData(256, 256), r = mulberry32(100 + k); - for (let i = 0; i < 256 * 256; i++) { const v = clamp((r() + r() + r() - 1.5) * 95 + 128, 0, 255) | 0; im.data[i * 4] = im.data[i * 4 + 1] = im.data[i * 4 + 2] = v; im.data[i * 4 + 3] = 255; } - cx.putImageData(im, 0, 0); - return cv; - }); - return cueSheet(); -} - -root.Reel = { - W, H, FPS, DUR, init, render, post, - scenes: () => SCENES.map((s, i) => ({ id: s.id, name: s.name, start: ST[i], dur: sceneLen(i) })), -}; -})(typeof window !== 'undefined' ? window : globalThis); diff --git a/claude/skills/visual/motion-reel/assets/render.html b/claude/skills/visual/motion-reel/assets/render.html deleted file mode 100644 index 14f9bd08..00000000 --- a/claude/skills/visual/motion-reel/assets/render.html +++ /dev/null @@ -1,58 +0,0 @@ - - - - - diff --git a/claude/skills/visual/motion-reel/assets/score-template.py b/claude/skills/visual/motion-reel/assets/score-template.py deleted file mode 100644 index c4d6533a..00000000 --- a/claude/skills/visual/motion-reel/assets/score-template.py +++ /dev/null @@ -1,210 +0,0 @@ -"""The soundtrack for this reel. It runs inside motion-reel's synth.py: - - ./make.sh audio (or: uv run /scripts/synth.py .) - -Every sound is placed from cues.json, which reel.js exports, so when the picture moves -the sound moves with it. Change the harmony, the instruments and the gains here; add a -cue to reel.js's cueSheet() when a new picture event should be heard. -""" - -import numpy as np -from synth import bass as bass_note -from synth import ( - glide, - grain, - midi, - pad, - plink, - pluck, - reverse, - rim, - soft_impact, - sonar, - sweep, - tick, - whoosh, - woodblock, -) - -# F major in half-time. One (pad voicing, bass root) per groove bar, cycling. -CHORDS = [ - ([53, 57, 60, 64, 67], 41), # Fmaj9 - ([53, 57, 60, 64, 67], 41), - ([50, 53, 57, 60, 64], 38), # Dm9 - ([50, 53, 57, 60, 64], 38), - ([46, 50, 53, 57, 60], 34), # Bbmaj9 - ([46, 50, 53, 57, 60], 34), - ([46, 50, 53, 55, 57], 43), # Gm9 over Bb - ([48, 53, 55, 60], 36), # Csus4 -] -INTRO = [53, 57, 60, 64, 67] -FINAL = [41, 48, 53, 57, 60, 67, 72, 79] # F add9, wide -PENTA = [77, 79, 81, 84, 86, 89, 91, 93, 96] # F major pentatonic, high -ARP = [0, 2, 1, 3, 2, 4, 3, 1] - - -def score(s): - c, beat, bar, rng = s.cues, s.beat, s.bar, s.rng - g0, g1 = c["groove"] - start = dict(zip(c["scenes"], c["starts"])) # scene start time by id - - def span(key): # the length of a [t0, t1] cue window - return c[key][1] - c[key][0] - - def hit( - sound, t, gain, pan=0.0, wet=0.0 - ): # one sound, dry on fx and, when wet, into the reverb - s.fx.add(sound, t, gain, pan) - if wet: - s.send.add(sound, t, wet) - - # ---- intro: a slow swell, soft quarter ticks, a marimba note per level - s.pad.add( - np.stack( - [ - sweep(ch, lambda t: 220 * (1600 / 220) ** min(1, t / g0)) - for ch in pad(INTRO, g0 - 0.02, attack=min(2.5, g0 / 2), release=0.02) - ] - ), - 0, - 0.9, - ) - t = bar - while t < g0 - 1e-6: - s.drums.add(tick(), t, 0.03, 0.35) - t += beat - for k, t in enumerate(c["scale"]): - hit( - plink(midi(PENTA[min(k, len(PENTA) - 1)])), - t, - 0.24 + 0.03 * k, - -0.6 + 1.2 * k / max(1, len(c["scale"]) - 1), - wet=0.1, - ) - hit(plink(midi(89)), c["scaleSettle"], 0.09, 0.6) - # the ball rises into the ring: a swell that peaks on the arrival - rise = c["rise"][0] - hit(whoosh(c["arrive"] - rise + 0.1, 200, 2500, 0.92, (0, 0)), rise, 0.12) - hit(soft_impact(2.6), c["arrive"], 0.55, wet=0.2) - - # ---- the groove: the kicks reel.js pulses on (KICK), rim on 3, eighth ticks, bass, pads - bars = [] - b = g0 - while b < g1 - 1e-6: - bars.append(b) - b += bar - for t in c["kicks"]: # a kick on a bar line hits harder - s.kick(t, 0.72 if min(abs(t - x) for x in bars) < 1e-3 else 0.5) - for j, b in enumerate(bars): - notes, root = CHORDS[j % len(CHORDS)] - if b + 2 * beat < g1: - r = rim() - s.drums.add(r, b + 2 * beat, 0.2, 0.1) - s.send.add(r, b + 2 * beat, 0.1) - for e in range(8): - if b + e * beat / 2 < g1: - s.drums.add(tick(), b + e * beat / 2, 0.06 if e % 2 else 0.035, 0.35) - for off, d in ( - (0, 0.9 * beat), - (1.5 * beat, 0.4 * beat), - (2 * beat, 1.5 * beat), - ): - if b + off < g1: - s.bass.add( - bass_note(midi(root), min(d, g1 - b - off - 0.02)), b + off, 0.34 - ) - end = min(b + bar, g1) - s.pad.add( - pad(notes, end - b, attack=0.08, release=0.1 if end == b + bar else 0.01), - b, - 1.0, - ) - if ( - start["signal"] <= b < start["rhythm"] - ): # felt-piano eighths through the analytic middle - for i in range(8): - if b + i * beat / 2 < g1: - note = midi(notes[ARP[i] % len(notes)] + 12) - s.keys.add( - pluck(note, dur=0.7, bright=0.45), - b + i * beat / 2, - 0.1 if i % 2 == 0 else 0.07, - 0.4 if i % 2 else -0.4, - ) - - # ---- one sound per picture event - for k, t in enumerate(c["columns"]): - hit(woodblock(midi(PENTA[k % len(PENTA)] - 5) * 2), t, 0.16, -0.5 + k * 0.25) - hit(whoosh(span("dive") + 0.1, 250, 6500, 0.9, (0, 0)), c["dive"][0], 0.16) - hit(soft_impact(1.6), c["cut"], 0.25) - for k, t in enumerate(c["inputs"]): - hit(woodblock(midi(84 + 2 * k) * 1.5, 0.08), t, 0.1) - hit(whoosh(span("fold"), 400, 2500, 0.6, (-0.3, 0.3)), c["fold"][0], 0.08) - hit(whoosh(span("connector"), 600, 3000, 0.5, (-0.2, 0.4)), c["connector"][0], 0.05) - hit(glide(660, 780, span("slide")) * 0.5, c["slide"][0], 0.1, 0.4) - hit(woodblock(2600, 0.06), c["snap"], 0.22, 0.4) - hit(whoosh(span("push") + 0.1, 250, 4000, 0.8, (0, 0)), c["push"][0], 0.14) - for t in c["landings"]: # one grain per item landing in the ranking - hit( - grain(midi(PENTA[int(rng.integers(0, len(PENTA)))])), - t, - 0.016, - float(rng.uniform(-0.8, 0.8)), - ) - for k, t in enumerate(c["stars"]): - hit(plink(midi(PENTA[2 + k]), 0.8), t, 0.12, -0.2 + 0.1 * k, wet=0.07) - hit(whoosh(span("fly"), 500, 7000, 0.9, (-0.3, 0.3)), c["fly"][0], 0.14) - hit(sonar(span("scan")), c["scan"][0], 0.12, wet=0.1) - for k in range(2): - hit(woodblock(220, 0.1), c["flag"] + 0.1 * k, 0.12, 0.3) - hit( - reverse(whoosh(span("collapse"), 300, 3000, 0.95, (0, 0))), - c["collapse"][0], - 0.14, - ) - hit(soft_impact(1.6), c["iris"], 0.22) - hit(whoosh(span("sweep"), 300, 2000, 0.5, (-0.4, 0.4)), c["sweep"][0], 0.1) - for k, t in enumerate(c["items"]): - hit( - woodblock(midi(PENTA[k % len(PENTA)] - 5) * 2, 0.09), - t, - 0.14, - -0.4 + 0.16 * k, - ) - for k, t in enumerate(c["focus"]): - hit(plink(midi(PENTA[2 * k % len(PENTA)]), 0.9), t, 0.1, -0.3 + 0.3 * k) - hit(whoosh(span("flood"), 250, 3500, 0.85, (0, 0)), c["flood"][0], 0.16) - for k, t in enumerate(c["cards"]): - if k != c["quiet"]: - hit(plink(midi(PENTA[k % len(PENTA)]), 0.6), t, 0.14, -0.3 + 0.1 * k) - # an odometer, ticking as fast as the number on screen climbs - for t in c["countTicks"]: - hit(tick(0.02), t, 0.05, 0.2) - for i in range(int((c["cards"][-1] + c["card"] - c["cards"][0]) / (beat / 2))): - t = c["cards"][0] + i * beat / 2 + beat / 4 - if t < g1: - s.drums.add(tick(0.03), t, 0.03, -0.35) - - # ---- the end: after the silence, a warm arrival and the last chord; the ball lands as the full stop - if c["silence"][1] > c["silence"][0]: - s.silence(*c["silence"]) - s.fade_out = span("fade") # the sound fades with the picture - hit(soft_impact(3.2), c["end"], 0.7, wet=0.25) - s.pad.add( - pad(FINAL, s.dur - c["end"] - 0.3, attack=0.01, release=0.3), c["end"], 1.25 - ) - for k, n in enumerate([65, 69, 72, 76]): - s.keys.add( - pluck(midi(n + 12), dur=1.6, bright=0.35), - c["end"] + 0.03 + 0.09 * k, - 0.08, - -0.3 + 0.2 * k, - ) - for k, t in enumerate(c["endBall"]): - hit(plink(midi(PENTA[5 + min(k, 3)])), t, 0.16 * 0.55**k, 0.3) - - # ---- what to measure after the mix (nobody here can listen) - s.check("first level lands", c["scale"][0]) - s.check("arrival", c["arrive"]) - s.check("snap to grid", c["snap"]) - s.check("the end", c["end"]) diff --git a/claude/skills/visual/motion-reel/references/craft.md b/claude/skills/visual/motion-reel/references/craft.md deleted file mode 100644 index e1ec0918..00000000 --- a/claude/skills/visual/motion-reel/references/craft.md +++ /dev/null @@ -1,99 +0,0 @@ -# Craft notes - -What makes a code-rendered reel read as designed rather than generated. Every rule -here came out of a film that was made, reviewed and changed. - -## The grid - -Everything sits on a musical grid. At 128 BPM a beat is 0.469 s and a bar 1.875 s. -Scenes last whole bars, cuts land on bar lines, events land on beats or eighths, and -the soundtrack is written to the same grid, so picture and sound agree by -construction rather than by nudging. - -| a scene that carries | bars at 128 BPM | seconds | -|---|---|---| -| a title and one idea | 2–3 | 3.8–5.6 | -| numbers to read: a chart, a legend | 4 | 7.5 | -| one montage card | ½ | 0.94 | -| a one-word punchline | ¼–½ | 0.5–0.9 | - -**Reading time is the constraint, not the music.** Give a headline at least 1 s after -its reveal settles, every number on screen 1.5 s, a legend of n rows about -0.4 s × n + 1 s, and 2 s more wherever the viewer is meant to compare. A 15-second cut -of eight data scenes (1.9 s each) came back as "nice, but too fast"; re-timed to 56 s -it landed. Keep fast cuts for mood teasers. - -**Re-time, don't slow down.** Stretching a finished film 3–4× turns 128 BPM into -35 BPM and every spring into slow motion. Give scenes more bars instead -(each scene's `bars` in `SCENES`), let entrances run about 2× calmer, and add holds -after each idea. - -## Easing vocabulary - -| motion | curve | typical length | -|---|---|---| -| an entrance (text rising, a bar growing) | outExpo | 0.6–0.9 s; 0.25–0.3 s on a card | -| a move between two states | inOutCubic | 0.5–1 s | -| a dive or zoom that accelerates into a cut | inExpo | 1–1.2 s | -| ambient drift and rotation | linear / sine | the whole hold | - -`spring(s, f, d)`: lively is f = 2–3 Hz, d = 7–8 (about 15–25 % overshoot); calm is -f = 1–1.2 Hz, d = 6 (about 8 %). An object that lands on a floor must bounce, not sink: -reflect the overshoot, `y = -abs(1 - spring(s)) * height`. Squash on contact for -0.03–0.05 s, stretch along the speed in flight. - -## Physics that reads as craft - -- `makeBounce` pins the first two contacts to beats and derives the rest from the - restitution, so the ball is both musical and physical. -- The spacing chart (a dot every 2–3 frames of the path) shows the easing to anyone who - animates; frame numbers at the contacts say the timing was chosen. -- Let a motion encode a quantity: hop heights that grow with the level, a ring that is - exactly the next chart's radius. - -## Holds that stay alive - -A hold is where the viewer reads, but a frozen frame looks broken. Keep something -moving at a fraction of its entrance speed: a 1–2 % camera drift over the hold, a -sphere that keeps turning, a focus cycle (dim the others to about 45 %, push the -focused item out 10 px, light its legend rows), a slow light sweep. Slow things down; -never stop them. - -## Transitions in the template - -- **Iris from an object:** the ball rises, becomes a ring, and the ring opens the next - scene. -- **Dive:** the camera accelerates into one block of a chart until its colour fills the - frame, and the next scene is that colour. -- **Push:** the next scene rises from below (inOutExpo, 0.9 s). -- **Match cut by geometry:** items fly from a histogram to exactly where the next - scene's sphere will have them; the sphere folds into a ring at the radius of the next - scene's donut; the donut floods the screen with the next card's colour. -- **Hard cut on a downbeat after silence**, for the name. - -## Restraint - -- One punchline card: a small word, a lot of space, digital silence under it, then the - name on the downbeat. It is the most remembered beat of the film. -- A calm brand gets shallow springs, flashes no brighter than 10 %, no chromatic - glitches, a half-time groove. -- A showreel may spike chromatic aberration and flash on the drop, and shake the - camera on the name slam. Choose one register per film. - -## Honesty on screen - -- Every number is read from a source and the as-of date is on screen (HUD, bottom - right). -- An illustrative value carries a visible tag (the template's `ILLUSTRATION` pill). -- The template's own numbers are invented and internally consistent; no real client's - data belongs in a template. -- No return or performance claims unless the user supplies them with their source. -- A film that carries a real organisation's name and branding is a file for its owner, - not something to publish on their behalf. - -## The HUD - -Brand top left, the process tracker top right with the current step underlined, the -scene name and a one-line spec typed on at each cut bottom left, the as-of bottom -right, a progress line with a tick per scene bottom centre. It frames the film as a -designed object and carries the facts that do not fit the frame. `HUD_ON` turns it off. diff --git a/claude/skills/visual/motion-reel/references/pipeline.md b/claude/skills/visual/motion-reel/references/pipeline.md deleted file mode 100644 index 9d78cba0..00000000 --- a/claude/skills/visual/motion-reel/references/pipeline.md +++ /dev/null @@ -1,101 +0,0 @@ -# Pipeline notes - -## One function of time - -`reel.js` exposes `Reel.init()` (fonts, precomputed geometry; returns the cue sheet), -`Reel.render(ctx, t, tf)` and `Reel.post(src, dst, tf)`. The harness -(`assets/render.html`, served by `render.py` next to the project) owns the canvases. -Because a frame depends on nothing but time, frames render in any order, in parallel -workers, and a single frame can be re-rendered to check it (`./make.sh still 39.9`). - -## Motion blur - -The harness renders `sub` sub-frames at -`t = tf + ((s + 0.5) / sub − 0.5) × shutter / FPS` and keeps a running average -(`globalAlpha = 1 / (s + 1)`). `shutter = 0.5` is a film camera's 180° shutter: fast -moves smear, held type stays sharp. Grain, bloom and the vignette run once in `post`, -after the average. If they ran per sub-frame, the averaging would erase the grain. - -**`t` versus `tf`.** Sub-frames straddle the frame's time. Anything discrete (which -card shows, a count, the scene index, HUD text) must switch on `tf`, or one frame -blends two cards, or a count-up shows a dozen numbers on top of each other. -Continuous motion uses `t`. Sheets render one sub-frame and cannot show such a blend; -`./make.sh still` renders all eight. - -`sheets` renders with `sub = 1` (fast, sharp, good for layout); `frames` with 8. - -## Costs, measured on an 8-core box at 1920×1080 - -| job | time | -|---|---| -| `render.py check`, 1,065 frames of 56 s at one sample | about 50 s | -| review sheets, 64 frames | 5–6 s | -| 900 frames × 8 sub-frames | 42–69 s | -| 3,375 frames (56 s) × 8 sub-frames | 134–146 s | -| encode 56 s, master and share copy | about 3 min | - -PNG frames take 1.3–2.3 MB each, so a 56-second film needs about 5 GB while it -renders. Delete `frames/` after encoding when space is tight. - -## Headless canvas specifics - -- **Fonts.** `document.fonts.load(font, sample)` loads only the faces whose - `unicode-range` covers `sample`. The default sample `" "` loads the latin face alone, - and ł, ą or ß then fall back to another font without an error. The template passes a - sample with diacritics; `fonts.py` keeps latin-ext for the same reason. -- `ctx.letterSpacing` is part of the canvas state and sticks; set it with every font - (`setFont` does). -- `ctx.filter = 'blur()'` works in software rendering. `shadowBlur` is expensive: one - glowing ring is fine, a thousand shadowed dots is not. -- Batch primitives of one colour into a single path and fill once; that is how several - thousand particles stay cheap. -- Per-pixel effects (metaballs, fields) belong in an ImageData at ½ or ¼ resolution, - drawn scaled up with smoothing. -- Transitions draw two scenes in one frame, so a scene must have no side effects. - Wrap each in save/restore and reset the transform before the HUD. -- A scene drawn outside its own time (a transition runs it early or late) must still - draw something sensible: clamp its timelines rather than assume `lt ≥ 0`. - -## Checks that fail loudly - -- `render.py check` draws every quarter second and two seconds around every cut at one - sample, and exits non-zero when any of those frames throws, with a count and the - first five; `make.sh` runs it before the sheets and before the full render. Sheets - alone sample eight frames a scene, and an error between two samples passes them. -- `render.py` exits non-zero on any page error or console error (a missing - `fonts.css` is a 404, not a warning) and on any missing frame. -- `render.py frames` renders one sample frame, then refuses before it deletes or writes - any frame when the filesystem cannot hold every frame (the larger of 1.25 bytes a - pixel and twice the sample) with 1 GiB to spare; the message names the size it needs. -- `encode.py` writes each video to `NAME-master.part.mp4` and `NAME.part.mp4`, and - renames both over the final names only after ffmpeg exits 0 and the frame counts - pass; a failed encode removes the partial files and keeps the previous videos. -- `encode.py` decodes both outputs and compares their frame counts with `cues.json`, - and fails when even the last CRF cannot bring the share copy under `--max-mb`. -- `synth.py` exits non-zero when a registered silence window is louder than −100 dB. -- No script writes through a symbolic link or out of the project. A generated file is - written beside its destination and renamed over it (`scripts/project_files.py`), the - videos included, and the frames go into a `frames/` made fresh for the run. A - destination that is a link is refused, and so is an output directory outside the - project unless it is named with `review --out`. `synth.py` loads - `score.py` without writing its bytecode. - -## Encoding - -H.264 High, yuv420p, bt709 primaries, transfer and matrix tagged, `+faststart`. The -master is CRF 14. The share copy climbs a CRF ladder (14, 16, 18…) until it fits -`--max-mb`. ffmpeg is always imageio-ffmpeg's build: a system ffmpeg older than 5.1 -rejects options `encode.py` uses. - -| film | size | -|---|---| -| 15 s, flat-colour brand film, CRF 14 | 13.5 MB | -| 56 s, same film re-timed, CRF 14 / CRF 16 | 39 MiB / 26 MiB | -| 15 s, grain-heavy showreel, CRF 14 | 48.7 MB | - -Grain is the expensive part. Keep `GRAIN ≤ 0.04` when the copy must be small. - -## Delivering - -Send `NAME.mp4`, the copy under `--max-mb`; the master is for re-encoding. Whether a -film may be published at all is decided in `craft.md`, under "Honesty on screen". diff --git a/claude/skills/visual/motion-reel/references/sound.md b/claude/skills/visual/motion-reel/references/sound.md deleted file mode 100644 index 9f8b766b..00000000 --- a/claude/skills/visual/motion-reel/references/sound.md +++ /dev/null @@ -1,67 +0,0 @@ -# Sound notes - -## Scoring to the cue sheet - -`render.py info` writes `cues.json`: the timing (`dur`, `bpm`, scene `starts`), the -groove window, the silence window, and one named time or list of times for every -picture event that should be heard. It comes from `cueSheet()` in `reel.js`, which -reads the same per-scene timing records the scenes animate with; a sound on an eased -motion is placed where the easing reaches it (`reach`), so the count-up's ticks thin -out as the number slows. `score.py` places sounds only from it, so re-timing the -picture re-times the sound on the next `./make.sh audio`. - -One family of sound per kind of picture event: - -| picture | sound | -|---|---| -| a contact (a ball landing, a level reached) | `plink` (marimba), rising in pitch with the quantity | -| something locking into place | `woodblock`, one per item, stepping up the scale | -| a move, a dive, a push | `whoosh` panned with the motion | -| an arrival, a scene opening | `soft_impact` (calm) or `impact` (punchy) | -| items landing in a chart | `grain`, one per item: a soft rain | -| a scan | `sonar` | -| a number counting up | `tick` bursts, thinning as the count slows | -| a snap to a grid | a high `woodblock` | -| the swell into a hit | `reverse(...)` of the sound that follows | -| a build into a drop (punchy register) | `riser` | -| an explosion, particles bursting (punchy register) | `burst` | -| a cut in a fast montage (punchy register) | `blip`, climbing the scale | - -## Harmony and groove - -`score.py` cycles `CHORDS`, one (pad voicing, bass root) per groove bar, after a -filtered pad swell under the intro and before a wide final chord from the `end` cue. -The template is in F major with a half-time groove: the kicks of `KICK` in `reel.js` -(1 and the and-of-2, exported as the `kicks` cue, so the picture pulses on the same -hits), rim on 3, eighth ticks, felt-piano eighths through the analytic middle. For an -energetic film, set `KICK` to `[0, 1, 2, 3]` (four on the floor), add a `clap` on 2 -and 4 and off-beat `hat`s, and switch the arrivals to `impact`. - -`s.kick(t)` places a kick and registers it for the sidechain, which ducks the pads and -bass (`s.duck_depth`) so the groove breathes. - -## Silence as a device - -A quiet card gets digital silence: `s.silence(t0, t1)` gates the whole mix after the -reverb and delay, so no tail leaks into it. The next downbeat then hits harder than -any drum could. - -## The mix - -Six buses: `drums`, `bass`, `pad` (low-passed at `s.pad_cut`), `keys` (with a -dotted-eighth ping-pong delay), `fx`, and `send` (convolution reverb, plus a little -pad and keys). Master chain: 30 Hz high-pass, gates, normalise, `tanh` soft clip -(`s.drive`), fade-out, −1 dBFS peak. Measured RMS: about −16.8 dBFS for the calm -template, about −13.7 dBFS for a four-on-the-floor showreel. - -## Checking a soundtrack nobody can hear - -A model cannot listen to what it made, so measure and say so: - -- `s.check(label, t)` prints the post-mix peak at each named event: the cue should be - well above its surroundings (in the template, the first level about −15 dB, the - arrival about −1 dB). A reading can move by a decibel after an unrelated edit, - because every noise-based sound draws from one random stream; a cue that went - missing drops by far more. -- Every silence window must read about −180 dB; `synth.py` fails above −100 dB. -- Report the levels, and report that the mix is measured, not judged by ear. diff --git a/claude/skills/visual/motion-reel/scripts/encode.py b/claude/skills/visual/motion-reel/scripts/encode.py deleted file mode 100644 index a06cbfdc..00000000 --- a/claude/skills/visual/motion-reel/scripts/encode.py +++ /dev/null @@ -1,242 +0,0 @@ -# /// script -# requires-python = ">=3.10" -# dependencies = ["imageio-ffmpeg>=0.5"] -# /// -"""Encode a motion-reel project, and check what came out. - - uv run encode.py PROJECT [--name reel] [--max-mb 29] - frames/ + audio.wav -> NAME-master.mp4 (H.264 CRF 14) and NAME.mp4, the lowest - CRF that fits under --max-mb (for chat uploads with a size cap) - uv run encode.py review VIDEO [--out DIR] [--at 12.5 [--crop W:H:X:Y]] - a 4x4 contact sheet pulled from the ENCODED file, to review what ships; - with --at, one full-size frame of it instead, to read small type 1:1 - -Both outputs are decoded again and their frame count is compared with cues.json; -a mismatch exits non-zero. Each output is encoded to NAME*.part.mp4 and renamed -over its final name only after ffmpeg and the frame counts pass for both. A failed -encode or a mismatch keeps the previous videos and leaves no partial file under a -final name. When the share copy stays over --max-mb, both videos are complete: -they replace the previous ones, and the run then exits non-zero. ffmpeg is imageio-ffmpeg's own build, never -one from PATH: an older system ffmpeg lacks options this script uses. -""" - -import argparse -import json -import os -import re -import shutil -import subprocess -import sys -from pathlib import Path - -from project_files import output_dir - -COLOR = [ - "-vf", "scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+full_chroma_int,format=yuv420p", - "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv", -] # fmt: skip -CRF_LADDER = [14, 16, 18, 20, 22, 24] - - -def ffmpeg(): - import imageio_ffmpeg - - return imageio_ffmpeg.get_ffmpeg_exe() - - -def run(args): - subprocess.run( - [ffmpeg(), "-hide_banner", "-loglevel", "error", "-y", *args], check=True - ) - - -def part_of(out): - """The partial file beside `out`: x.mp4 -> x.part.mp4. The suffix stays last, so - ffmpeg still picks the format from the name.""" - return out.with_name(out.stem + ".part" + out.suffix) - - -def fresh(out, args, hint=""): - """ffmpeg into a new file, which then replaces `out`. ffmpeg can exit 0 having - written nothing (a seek past the end), and an old image must never pass for one of - the video just encoded. `-update 1` makes the image muxer take the path as a name, - not a pattern, so a % in the project's path cannot send the image elsewhere.""" - if out.is_symlink(): - raise SystemExit( - f"{out} is a symbolic link: remove it, outputs are written as files" - ) - part = part_of(out) - part.unlink(missing_ok=True) - try: - run([*args, "-update", "1", str(part)]) - except subprocess.CalledProcessError: - part.unlink(missing_ok=True) - raise - if not part.exists() or part.stat().st_size == 0: - part.unlink(missing_ok=True) - raise SystemExit(f"ffmpeg wrote no {out.name}{hint}") - os.replace(part, out) - - -def decoded_frames(video): - r = subprocess.run( - [ffmpeg(), "-hide_banner", "-i", str(video), "-map", "0:v", "-f", "null", "-"], - capture_output=True, - text=True, - ) - counts = re.findall(r"frame=\s*(\d+)", r.stderr) - return int(counts[-1]) if counts else 0 - - -def probe(video): - r = subprocess.run( - [ffmpeg(), "-hide_banner", "-i", str(video)], capture_output=True, text=True - ) - return " | ".join( - ln.strip() - for ln in r.stderr.splitlines() - if re.search(r"Duration|Video:|Audio:", ln) - ) - - -def encode(project, name, max_mb): - if Path(name).name != name or name in ("", ".", ".."): - raise SystemExit(f"--name {name!r} must be a file name, not a path") - master, share = project / f"{name}-master.mp4", project / f"{name}.mp4" - for out in (master, share): # never through a link, never out of the project - if out.is_symlink(): - raise SystemExit( - f"{out} is a symbolic link: remove it, outputs are written as files" - ) - if out.resolve().parent != project: - raise SystemExit(f"{out} resolves to {out.resolve()}, outside {project}") - info = json.loads((project / "cues.json").read_text()) - fps, expected = info["fps"], info["frames"] - frames = sorted((project / "frames").glob("f_*.png")) - if len(frames) != expected: - raise SystemExit( - f"expected {expected} frames in {project / 'frames'}, found {len(frames)} — run render.py frames" - ) - audio = project / "audio.wav" - # the frame pattern is ffmpeg syntax: a % in the project's path must stay literal - pattern = str(project / "frames").replace("%", "%%") + "/f_%05d.png" - src = ["-framerate", str(fps), "-i", pattern] - if audio.exists(): - src += ["-i", str(audio)] - else: - print("no audio.wav — encoding a silent video", file=sys.stderr) - - def one(out, crf, abr): - a = ["-c:a", "aac", "-b:a", abr, "-shortest"] if audio.exists() else ["-an"] - run( - [ - *src, - "-c:v", - "libx264", - "-preset", - "slow", - "-crf", - str(crf), - *COLOR, - *a, - "-movflags", - "+faststart", - str(out), - ] - ) - - # Both videos are encoded to NAME-master.part.mp4 and NAME.part.mp4, new files - # beside the final names, never written in place through a hard link. They are - # decoded and checked there, and renamed over the final names only when both pass. - # A failed encode (a broken audio.wav, a full disk) removes the partial files and - # leaves the previous videos as they were. - parts = {out: part_of(out) for out in (master, share)} - try: - for part in parts.values(): - part.unlink(missing_ok=True) - one(parts[master], 14, "320k") - for crf in CRF_LADDER: - if crf == 14: - shutil.copyfile(parts[master], parts[share]) - else: - one(parts[share], crf, "256k") - size = parts[share].stat().st_size / 2**20 - print(f" crf {crf}: {size:.1f} MiB") - if size <= max_mb: - break - for out, part in parts.items(): - n = decoded_frames(part) - print( - f"{out.name}: {part.stat().st_size / 2**20:.1f} MiB, {n} frames decoded | {probe(part)}" - ) - if n != expected: - raise SystemExit( - f"{out.name} decodes to {n} frames, expected {expected}: previous videos kept" - ) - for out, part in parts.items(): - os.replace(part, out) - except subprocess.CalledProcessError as e: - raise SystemExit( - f"ffmpeg exited {e.returncode}: no video written, previous videos kept" - ) from e - finally: - for part in parts.values(): - part.unlink(missing_ok=True) - if ( - size > max_mb - ): # the capped copy is the promise of this step: missing it is a failure - raise SystemExit( - f"{share.name} is {size:.1f} MiB even at CRF {CRF_LADDER[-1]}, over --max-mb {max_mb}: shorten the reel, lower GRAIN, or raise the cap" - ) - - -def review(video, out_dir, at=None, crop=None, n=16): - out_dir.mkdir(parents=True, exist_ok=True) - # --at: one frame of the encoded file at full size, to read small type 1:1 - if at is not None: - out = out_dir / f"{video.stem}-{at:.3f}.png" - vf = ["-vf", f"crop={crop}"] if crop else [] - args = ["-ss", str(at), "-i", str(video), "-frames:v", "1", *vf] - fresh(out, args, hint=": is --at past the end?") - print(f"wrote {out}") - return - total = decoded_frames(video) - picks = [round((k + 0.5) * total / n) for k in range(n)] - sel = "+".join(f"eq(n\\,{p})" for p in picks) - out = out_dir / f"{video.stem}-sheet.png" - tile = f"select='{sel}',scale=480:270,tile=4x{(n + 3) // 4}" - fresh(out, ["-i", str(video), "-vf", tile, "-frames:v", "1", "-fps_mode", "vfr"]) - print(f"wrote {out}: frames {picks}") - - -def main(): - if len(sys.argv) > 1 and sys.argv[1] == "review": - ap = argparse.ArgumentParser(prog="encode.py review") - ap.add_argument("video", type=Path) - ap.add_argument("--out", type=Path, default=None) - ap.add_argument("--at", type=float, help="one full-size frame at this second") - ap.add_argument("--crop", help="with --at: W:H:X:Y, e.g. 1100:560:760:300") - a = ap.parse_args(sys.argv[2:]) - if a.crop and a.at is None: - ap.error("--crop needs --at") - # absolute, not resolved: a linked video still reviews into its own project - video = a.video.absolute() - review( - video, - a.out or output_dir(video.parent / "review", video.parent), - a.at, - a.crop, - ) - return - ap = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - ap.add_argument("project", type=Path) - ap.add_argument("--name", default="reel") - ap.add_argument("--max-mb", type=float, default=29.0) - a = ap.parse_args() - encode(a.project.resolve(), a.name, a.max_mb) - - -if __name__ == "__main__": - main() diff --git a/claude/skills/visual/motion-reel/scripts/fonts.py b/claude/skills/visual/motion-reel/scripts/fonts.py deleted file mode 100644 index c8489824..00000000 --- a/claude/skills/visual/motion-reel/scripts/fonts.py +++ /dev/null @@ -1,83 +0,0 @@ -# /// script -# requires-python = ">=3.10" -# /// -"""Download Google Fonts into a project, so headless Chrome renders them offline. - - uv run fonts.py PROJECT --family "Inter:wght@100..900" --family "DM Mono:wght@400;500" - -Writes PROJECT/fonts/*.woff2 and PROJECT/fonts.css. The latin and latin-ext -subsets are kept by default, so Polish and most European diacritics render; pass ---subsets to change that. Family specs use the Google Fonts css2 syntax. -""" - -import argparse -import re -import urllib.request -from pathlib import Path -from urllib.parse import quote - -from project_files import output_dir, write_file - -UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36" -DEFAULT_FAMILIES = ["Inter:wght@100..900", "DM Mono:wght@400;500"] - - -def fetch(url): - req = urllib.request.Request(url, headers={"User-Agent": UA}) - with urllib.request.urlopen(req, timeout=30) as r: - return r.read() - - -def main(): - ap = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - ap.add_argument("project", type=Path) - ap.add_argument( - "--family", - action="append", - help="css2 family spec; repeatable (default: Inter + DM Mono)", - ) - ap.add_argument("--subsets", default="latin,latin-ext") - a = ap.parse_args() - families = a.family or DEFAULT_FAMILIES - keep = set(a.subsets.split(",")) - query = "&".join( - "family=" + quote(f, safe=":@.;,").replace("%20", "+") for f in families - ) - out_dir = output_dir(a.project / "fonts", a.project) # before any download - if (a.project / "fonts.css").is_symlink(): - raise SystemExit( - f"{a.project / 'fonts.css'} is a symbolic link: remove it, outputs are written as files" - ) - css = fetch(f"https://fonts.googleapis.com/css2?{query}&display=block").decode() - faces = [] - for subset, body in re.findall(r"/\*\s*(\S+)\s*\*/\s*@font-face\s*{([^}]*)}", css): - if subset not in keep: - continue - fam = re.search(r"font-family: '([^']+)'", body).group(1) - style = re.search(r"font-style: (\w+)", body).group(1) - weight = re.search(r"font-weight: ([\d ]+);", body).group(1) - url = re.search(r"url\((\S+?)\)", body).group(1) - rng = re.search(r"unicode-range: ([^;]+);", body) - name = ( - f"{fam.replace(' ', '')}-{style}-{weight.replace(' ', '_')}-{subset}.woff2" - ) - write_file(out_dir / name, fetch(url), a.project) - faces.append( - f"@font-face{{font-family:'{fam}';font-style:{style};font-weight:{weight};" - f"src:url(fonts/{name}) format('woff2');" - + (f"unicode-range:{rng.group(1)};" if rng else "") - + "font-display:block}" - ) - print(" ", name) - if not faces: - raise SystemExit( - f"no faces matched subsets {sorted(keep)} — check the family specs" - ) - write_file(a.project / "fonts.css", "\n".join(faces) + "\n", a.project) - print(f"wrote {a.project / 'fonts.css'}: {len(faces)} faces") - - -if __name__ == "__main__": - main() diff --git a/claude/skills/visual/motion-reel/scripts/new_reel.py b/claude/skills/visual/motion-reel/scripts/new_reel.py deleted file mode 100644 index 348253ab..00000000 --- a/claude/skills/visual/motion-reel/scripts/new_reel.py +++ /dev/null @@ -1,124 +0,0 @@ -# /// script -# requires-python = ">=3.10" -# /// -"""Scaffold a motion-reel project. - - uv run new_reel.py DIR [--family "Inter:wght@100..900" --family "DM Mono:wght@400;500"] - -Copies reel.js and score.py from the skill's templates, downloads the fonts, and -writes make.sh, which runs every later step. Run again on an existing project, it -keeps every file already there: --force writes them all again, --family changes -only the fonts. - - ./make.sh sheets check the whole timeline, then review contact sheets - ./make.sh all check, frames with motion blur, soundtrack, video, review sheet - ./make.sh info | check | frames | audio | encode | review one step at a time - ./make.sh still 12.5 one frame at full size, before the render - ./make.sh review --at 12.5 [--crop W:H:X:Y] one frame of the encoded video -""" - -import argparse -import shlex -import stat -import subprocess -import sys -from pathlib import Path - -from project_files import present, write_file - -SKILL = Path(__file__).resolve().parent.parent -MAKE = """#!/usr/bin/env bash -# motion-reel project. Every step reads reel.js (picture) and score.py (sound). -USAGE="usage: ./make.sh [sheets|all|info|check|frames|audio|encode|review|still SECONDS]" -set -euo pipefail -cd "$(dirname "$0")" -SCRIPTS={scripts} -NAME={name} -run() {{ uv run --quiet "$SCRIPTS/$1" "${{@:2}}"; }} -case "${{1:-all}}" in - info) run render.py info . ;; - check) run render.py info . && run render.py check . ;; - sheets) run render.py info . && run render.py check . && run render.py sheets . ;; - frames) run render.py info . && run render.py check . && run render.py frames . ;; - audio) run render.py info . && run synth.py . ;; - encode) run encode.py . --name="$NAME" ;; - review) run encode.py review "./$NAME.mp4" "${{@:2}}" ;; - still) run render.py still . --t "${{2:?$USAGE}}" ;; - all) run render.py info . && run render.py check . && run render.py frames . && run synth.py . \\ - && run encode.py . --name="$NAME" && run encode.py review "./$NAME.mp4" ;; - *) echo "$USAGE" >&2; exit 2 ;; -esac -""" - - -def main(): - ap = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - ap.add_argument("dir", type=Path) - ap.add_argument( - "--family", - action="append", - help="css2 font family spec, repeatable (default: Inter + DM Mono)", - ) - ap.add_argument( - "--force", - action="store_true", - help="write reel.js, score.py, make.sh and the fonts even if present", - ) - a = ap.parse_args() - d = a.dir.resolve() - d.mkdir(parents=True, exist_ok=True) - fetch_fonts = a.family or a.force or not present(d / "fonts.css") - planned = [ - d / f - for f in ("reel.js", "score.py", "make.sh") - if a.force or not present(d / f) - ] - planned += [d / "fonts.css", d / "fonts"] if fetch_fonts else [] - for target in ( - planned - ): # every refusal before any write: --force never half-rewrites a project - if target.is_symlink(): - raise SystemExit( - f"{target} is a symbolic link: remove it, outputs are written as files" - ) - for src, dst in ( - ("reel-template.js", "reel.js"), - ("score-template.py", "score.py"), - ): - target = d / dst - if present(target) and not a.force: # a dangling link counts: never followed - print(f"kept existing {target}") - continue - write_file(target, (SKILL / "assets" / src).read_bytes(), d) - print(f"wrote {target}") - make = d / "make.sh" - if present(make) and not a.force: - # never suggest --force here: it also writes reel.js and score.py over the film - print(f"kept existing {make} (delete it and re-run to write a fresh one)") - else: - # shell-quoted: a directory name is data, never code - paths = { - "scripts": shlex.quote(str(SKILL / "scripts")), - "name": shlex.quote(d.name), - } - write_file(make, MAKE.format(**paths), d) - make.chmod(make.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) - print(f"wrote {make}") - if fetch_fonts: - fam = [x for f in (a.family or []) for x in ("--family", f)] - sys.stdout.flush() # our lines first, then fonts.py's - subprocess.run( - [sys.executable, str(SKILL / "scripts" / "fonts.py"), str(d), *fam], - check=True, - ) - else: # reel.js's FAM names these fonts; a silent default would break that link - print(f"kept existing {d / 'fonts.css'} (pass --family to change the fonts)") - print( - f"\nnext:\n cd {shlex.quote(str(d))}\n ./make.sh sheets # then look at review/*.png\n ./make.sh all" - ) - - -if __name__ == "__main__": - main() diff --git a/claude/skills/visual/motion-reel/scripts/project_files.py b/claude/skills/visual/motion-reel/scripts/project_files.py deleted file mode 100644 index 93bdf2c6..00000000 --- a/claude/skills/visual/motion-reel/scripts/project_files.py +++ /dev/null @@ -1,58 +0,0 @@ -"""How every motion-reel script writes into a project: never through a link, never out of it. - -A generated file is written beside its destination and renamed over it, so nothing is -ever written through a symbolic link. A destination that is itself a link, even a -dangling one, is refused: a link there means someone arranged for the output to land -somewhere else. A directory an output goes into must lie inside the project. -""" - -import os -import tempfile -from pathlib import Path - - -def present(path): - """Whether anything is at `path`, a dangling link included.""" - return path.exists() or path.is_symlink() - - -def _inside(path, project): - root, p = Path(project).resolve(), Path(path).resolve() - return p == root or root in p.parents - - -def output_dir(path, project): - """`path`, created if missing, as a directory inside `project`.""" - if path.is_symlink(): - raise SystemExit( - f"{path} is a symbolic link: outputs go into the project itself" - ) - if not _inside( - path, project - ): # checked before mkdir, which would already act there - raise SystemExit(f"{path} lies outside the project {Path(project).resolve()}") - path.mkdir(parents=True, exist_ok=True) - return path - - -def write_file(path, data, project): - """Write `data` (bytes or str) to `path` inside `project`: atomically, never through a link.""" - if path.is_symlink(): - raise SystemExit( - f"{path} is a symbolic link: remove it, outputs are written as files" - ) - if not _inside(path.parent, project): - raise SystemExit(f"{path} lies outside the project {Path(project).resolve()}") - fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".tmp") - try: - with os.fdopen(fd, "wb") as f: - f.write(data.encode() if isinstance(data, str) else data) - umask = os.umask(0) - os.umask(umask) - os.chmod( - tmp, 0o666 & ~umask - ) # a plain file's mode, not mkstemp's owner-only 0600 - os.replace(tmp, path) - except BaseException: - Path(tmp).unlink(missing_ok=True) - raise diff --git a/claude/skills/visual/motion-reel/scripts/render.py b/claude/skills/visual/motion-reel/scripts/render.py deleted file mode 100644 index 70469764..00000000 --- a/claude/skills/visual/motion-reel/scripts/render.py +++ /dev/null @@ -1,312 +0,0 @@ -# /// script -# requires-python = ">=3.10" -# dependencies = ["playwright>=1.40"] -# /// -"""Render a motion-reel project through headless Chrome. - - uv run render.py info PROJECT cue sheet + timing -> PROJECT/cues.json - uv run render.py check PROJECT every quarter second + every cut, one sample, - nothing saved: fails on any script error - uv run render.py sheets PROJECT review contact sheets -> PROJECT/review/ - uv run render.py frames PROJECT [--sub 8] every frame -> PROJECT/frames/f_00000.png - uv run render.py still PROJECT --t 12.5 one full-resolution frame -> PROJECT/review/ - -PROJECT holds reel.js and fonts.css (see new_reel.py). The harness page is served -from this skill, so a project never carries a copy of it. Chrome comes from -$MOTION_REEL_CHROME, a system install, or Playwright's own Chromium (installed on -first use). Exits non-zero when the page reports an error or a frame is missing. -`frames` renders one sample frame first and refuses, before it writes any frame, -when the filesystem cannot hold every frame with 1 GiB to spare. -""" - -import argparse -import base64 -import functools -import json -import multiprocessing as mp -import os -import shutil -import subprocess -import sys -import threading -import time -from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer -from pathlib import Path -from urllib.parse import urlparse - -from project_files import output_dir, write_file - -HARNESS = Path(__file__).resolve().parent.parent / "assets" / "render.html" -CHROMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"] -MAC_CHROMES = [ - "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", - "/Applications/Chromium.app/Contents/MacOS/Chromium", -] -SHEET_FRACTIONS = [0.06, 0.18, 0.31, 0.44, 0.57, 0.7, 0.83, 0.96] -# Disk budget for `frames`. Measured PNG frames run 1.3-2.3 MB at 1920x1080, at most -# 1.1 bytes a pixel, so the floor is 1.25 bytes a pixel. A sample frame often -# compresses better than a busy one, so its size counts twice. -BYTES_PER_PIXEL_FLOOR = 1.25 -SAMPLE_FACTOR = 2 -FREE_MARGIN = 2**30 # leave 1 GiB free after the frames are written - - -class Handler(SimpleHTTPRequestHandler): - def log_message(self, *a): - pass - - def translate_path(self, path): - if urlparse(path).path == "/__harness.html": - return str(HARNESS) - return super().translate_path(path) - - -def serve(project): - srv = ThreadingHTTPServer( - ("127.0.0.1", 0), functools.partial(Handler, directory=str(project)) - ) - threading.Thread(target=srv.serve_forever, daemon=True).start() - return srv.server_address[1] - - -def chrome_path(): - if os.environ.get("MOTION_REEL_CHROME"): - return os.environ["MOTION_REEL_CHROME"] - for name in CHROMES: - if shutil.which(name): - return shutil.which(name) - return next((p for p in MAC_CHROMES if Path(p).exists()), None) - - -def launch(p): - args = ["--disable-gpu", "--force-color-profile=srgb"] - exe = chrome_path() - if exe: - return p.chromium.launch(executable_path=exe, args=args) - try: - return p.chromium.launch(args=args) - except Exception as e: # Playwright's Chromium is not installed yet - if "Executable doesn't exist" not in str(e): - raise - subprocess.run( - [sys.executable, "-m", "playwright", "install", "chromium"], check=True - ) - return p.chromium.launch(args=args) - - -def open_page(p, port, errors): - browser = launch(p) - page = browser.new_page() - page.on("pageerror", lambda e: errors.append(str(e))) - # every console error fails the run: a missing fonts.css is a 404, not a warning - page.on("console", lambda m: errors.append(m.text) if m.type == "error" else None) - page.goto(f"http://127.0.0.1:{port}/__harness.html") - page.wait_for_function( - "window.READY === true || !!window.READY_ERR", timeout=120000 - ) - err = page.evaluate("window.READY_ERR || null") - if err: - raise SystemExit(f"reel.js failed to start:\n{err}") - return browser, page - - -def png(data_url): - return base64.b64decode(data_url.split(",", 1)[1]) - - -def worker(job): - port, frames, out, sub = job - from playwright.sync_api import sync_playwright - - errors, done = [], 0 - with sync_playwright() as p: - browser, page = open_page(p, port, errors) - for f in frames: - # a frame goes into the frames/ this run just made, so a plain write is safe - (out / f"f_{f:05d}.png").write_bytes( - png(page.evaluate("([f, s]) => renderFrame(f, s)", [f, sub])) - ) - done += 1 - browser.close() - return done, errors - - -def with_page(project, fn): - from playwright.sync_api import sync_playwright - - port, errors = serve(project), [] - with sync_playwright() as p: - browser, page = open_page(p, port, errors) - result = fn(page) - browser.close() - if errors: - raise SystemExit("page errors:\n " + "\n ".join(errors)) - return result - - -def cmd_info(project, a): - info = with_page(project, lambda page: page.evaluate("window.INFO")) - out = project / "cues.json" - write_file(out, json.dumps(info, indent=1), project) - print( - f"wrote {out}: {info['dur']:.2f} s, {info['frames']} frames at {info['fps']} fps, {len(info['scenes'])} scenes" - ) - - -def cmd_sheets(project, a): - review = output_dir(project / "review", project) - - def run(page): - info = page.evaluate("window.INFO") - fps, written = info["fps"], [] - scenes = info["scenes"] - for k in range(0, len(scenes), 2): - frames = [ - round((sc["start"] + fr * sc["dur"]) * fps) - for sc in scenes[k : k + 2] - for fr in SHEET_FRACTIONS - ] - frames = [min(f, info["frames"] - 1) for f in frames] - path = review / f"sheet-{k + 1}-{min(k + 2, len(scenes))}.png" - sheet = page.evaluate("([fr, c, s]) => sheet(fr, c, s)", [frames, 4, a.sub]) - write_file(path, png(sheet), project) - written.append(path) - return written - - for path in with_page(project, run): - print("wrote", path) - - -def cmd_check(project, a): - """Render the whole timeline sparsely: a quarter-second grid plus two seconds around - every scene boundary, where transitions draw two scenes at once. Review sheets sample - eight frames a scene; a script error between two samples passes them and still - breaks the full render.""" - - def run(page): - info = page.evaluate("window.INFO") - fps, total = info["fps"], info["frames"] - frames = set(range(0, total, max(1, fps // 4))) - for sc in info["scenes"]: - b = round(sc["start"] * fps) - frames.update(range(max(0, b - fps), min(total, b + fps))) - frames = sorted(frames) - return len(frames), page.evaluate("fr => probe(fr)", frames) - - n, failures = with_page(project, run) - if failures: - first = "\n ".join(f"frame {x['f']}: {x['error']}" for x in failures[:5]) - raise SystemExit(f"check: {len(failures)} of {n} frames throw\n {first}") - print(f"check: {n} frames rendered, no script errors") - - -def cmd_still(project, a): - review = output_dir(project / "review", project) - path = review / f"still-{a.t:.3f}.png" - - def run(page): - fps = page.evaluate("window.INFO.fps") - still = page.evaluate( - "([f, s]) => renderFrame(f, s)", [round(a.t * fps), a.sub] - ) - write_file(path, png(still), project) - - with_page(project, run) - print("wrote", path) - - -def gib(n): - return f"{n / 2**30:.1f} GiB" - - -def frames_bytes(info, sample_bytes): - """The bytes all frames need: the larger of the pixel floor and the sample frame - times SAMPLE_FACTOR, for every frame.""" - per_frame = max( - BYTES_PER_PIXEL_FLOOR * info["w"] * info["h"], SAMPLE_FACTOR * sample_bytes - ) - return int(per_frame * info["frames"]) - - -def check_space(out, project, need): - """Refuse a render the filesystem under `out` cannot hold with FREE_MARGIN left. - It runs before the old frames are deleted, so a refused run keeps them. Their - bytes count as free, because the render deletes them first.""" - old = out.is_dir() - free = shutil.disk_usage(out if old else project).free - if old: - free += sum(p.stat().st_size for p in out.iterdir() if p.is_file()) - if need + FREE_MARGIN > free: - raise SystemExit( - f"frames need about {gib(need)} plus a {gib(FREE_MARGIN)} margin, " - f"but {out} has {gib(free)} free: free space or render elsewhere" - ) - - -def cmd_frames(project, a): - def sample(page): - info = page.evaluate("window.INFO") - mid = info["frames"] // 2 # frame 0 is often black and compresses to nothing - data = page.evaluate("([f, s]) => renderFrame(f, s)", [mid, a.sub]) - return info, len(png(data)) - - info, sample_bytes = with_page(project, sample) - frames = list(range(info["frames"])) - out = project / "frames" - if out.is_symlink(): - raise SystemExit( - f"{out} is a symbolic link: frames render into the project itself" - ) - check_space(out, project, frames_bytes(info, sample_bytes)) - if out.exists(): # every frame from this reel.js, never a mix of two versions - shutil.rmtree(out) - out.mkdir() - port, workers = serve(project), max(1, min(a.workers, len(frames))) - t0 = time.time() - print(f"rendering {len(frames)} frames, {a.sub} sub-frames each, {workers} workers") - with mp.get_context("spawn").Pool(workers) as pool: - results = pool.map( - worker, [(port, frames[w::workers], out, a.sub) for w in range(workers)] - ) - done = sum(r[0] for r in results) - errors = [e for r in results for e in r[1]] - print(f"rendered {done} frames in {time.time() - t0:.0f} s -> {out}") - if errors: - raise SystemExit("page errors:\n " + "\n ".join(sorted(set(errors)))) - missing = [f for f in frames if not (out / f"f_{f:05d}.png").exists()] - if missing: - raise SystemExit(f"{len(missing)} frames missing, first {missing[:5]}") - - -def main(): - ap = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - ap.add_argument("mode", choices=["info", "check", "sheets", "frames", "still"]) - ap.add_argument("project", type=Path) - ap.add_argument( - "--sub", - type=int, - default=None, - help="motion-blur sub-frames (default 8 for frames/still, 1 for sheets)", - ) - ap.add_argument("--workers", type=int, default=min(8, os.cpu_count() or 1)) - ap.add_argument("--t", type=float, default=0.0, help="still only: time in seconds") - a = ap.parse_args() - project = a.project.resolve() - if not (project / "reel.js").exists(): - raise SystemExit(f"{project} has no reel.js — scaffold one with new_reel.py") - if a.sub is None: - a.sub = 1 if a.mode == "sheets" else 8 - modes = { - "info": cmd_info, - "check": cmd_check, - "sheets": cmd_sheets, - "frames": cmd_frames, - "still": cmd_still, - } - modes[a.mode](project, a) - - -if __name__ == "__main__": - main() diff --git a/claude/skills/visual/motion-reel/scripts/synth.py b/claude/skills/visual/motion-reel/scripts/synth.py deleted file mode 100644 index 3bc2290c..00000000 --- a/claude/skills/visual/motion-reel/scripts/synth.py +++ /dev/null @@ -1,476 +0,0 @@ -# /// script -# requires-python = ">=3.10" -# dependencies = ["numpy>=1.24", "scipy>=1.10"] -# /// -"""motion-reel soundtrack engine: instruments, buses, a mastering chain, and a -runner that plays a project's score.py against the reel's cue sheet. - - uv run synth.py PROJECT # PROJECT/score.py + PROJECT/cues.json -> PROJECT/audio.wav - -score.py defines `score(s)`, where `s` is a Session: it places sounds on buses at -times read from `s.cues`, registers kicks for the sidechain, silences to gate, and -checks to measure. The runner mixes, masters, writes the WAV, and prints the level -at every check. It exits non-zero when a registered silence is not silent, because -nobody on the pipeline can listen: the measurement is the only ear there is. -""" - -import argparse -import importlib.util -import io -import json -import sys -from pathlib import Path - -import numpy as np -from project_files import write_file -from scipy import signal -from scipy.io import wavfile - -SR = 48000 -_rng = np.random.default_rng(2026) - - -# ------------------------------------------------------------------ basics -def midi(n): - return 440.0 * 2 ** ((n - 69) / 12) - - -def tvec(dur): - return np.arange(max(0, int(round(dur * SR)))) / SR - - -def lp(x, fc, order=2): - return signal.sosfilt(signal.butter(order, fc, "lowpass", fs=SR, output="sos"), x) - - -def hp(x, fc, order=2): - return signal.sosfilt(signal.butter(order, fc, "highpass", fs=SR, output="sos"), x) - - -def bp(x, lo, hi, order=2): - return signal.sosfilt( - signal.butter(order, [lo, hi], "bandpass", fs=SR, output="sos"), x - ) - - -def sweep(x, fc_of_t, kind="lowpass", block=256, width=1.4): - """Time-varying filter, block by block, carrying the filter state across blocks.""" - y = np.empty_like(x) - zi = None - for s in range(0, len(x), block): - fc = fc_of_t((s + block / 2) / SR) - if kind == "bandpass": - sos = signal.butter( - 2, - [fc / width, min(fc * width, SR * 0.45)], - "bandpass", - fs=SR, - output="sos", - ) - else: - sos = signal.butter(2, min(fc, SR * 0.45), kind, fs=SR, output="sos") - if zi is None: - zi = np.zeros((sos.shape[0], 2)) - y[s : s + block], zi = signal.sosfilt(sos, x[s : s + block], zi=zi) - return y - - -def norm(x): - return x / (np.max(np.abs(x)) + 1e-12) - - -def saw(freq, t, phase=0.0): - """Band-limited sawtooth (polyBLEP).""" - dt = freq / SR - p = (freq * t + phase) % 1.0 - y = 2 * p - 1 - m = p < dt - q = p[m] / dt - y[m] -= q + q - q * q - 1 - m = p > 1 - dt - q = (p[m] - 1) / dt - y[m] -= q * q + q + q + 1 - return y - - -def _env_on(t, a=0.001): - return np.clip(t / a, 0, 1) - - -def pan_stereo(x, pan): - """Mono to stereo, equal-power; `pan` is -1..1, a number or an array per sample.""" - a = (np.asarray(pan) + 1) * np.pi / 4 - return np.stack([x * np.cos(a), x * np.sin(a)]) * np.sqrt(2) - - -def _with(t, x): - """`x` laid over zeros the length of `t`: a layer that may be shorter or longer.""" - out = np.zeros_like(t) - out[: min(len(x), len(t))] = x[: len(t)] - return out - - -# ------------------------------------------------------------------ drums -def kick(f0=130.0, f1=46.0, pdec=32.0, adec=6.0, dur=0.6, click=0.1): - t = tvec(dur) - f = f1 + (f0 - f1) * np.exp(-t * pdec) - x = np.sin(2 * np.pi * np.cumsum(f) / SR) * np.exp(-t * adec) * _env_on(t) - x += hp(_rng.standard_normal(len(t)), 3000) * np.exp(-t * 700) * click - return np.tanh(1.5 * x) / np.tanh(1.5) - - -def clap(): - t = tvec(0.4) - nz = bp(_rng.standard_normal(len(t)), 800, 3200) - env = sum(np.where(t >= d, np.exp(-(t - d) * 170), 0) for d in (0, 0.010, 0.021)) - env = env + 0.9 * np.where(t >= 0.031, np.exp(-(t - 0.031) * 16), 0) - return norm(nz * env) - - -def rim(dur=0.18): - t = tvec(dur) - body = np.sin(2 * np.pi * 1700 * t) * np.exp(-t * 70) * 0.5 - nz = bp(_rng.standard_normal(len(t)), 1800, 6000) * np.exp(-t * 60) - return norm(body + nz) - - -def hat(decay=48.0, dur=0.12): - t = tvec(dur) - return norm(hp(_rng.standard_normal(len(t)), 7500, 4) * np.exp(-t * decay)) - - -def tick(dur=0.05): - t = tvec(dur) - return norm(hp(_rng.standard_normal(len(t)), 8000, 4) * np.exp(-t * 90)) - - -# ------------------------------------------------------------------ pitched -def bass(freq, dur=0.21): - t = tvec(max(dur, 0.01) + 0.03) - x = 0.55 * saw(freq, t) + 0.9 * np.sin(2 * np.pi * freq * t) - env = ( - np.clip(t / 0.003, 0, 1) * np.exp(-t * 4.0) * np.clip((t[-1] - t) / 0.03, 0, 1) - ) - return lp(x * env, 520) - - -def pad(notes, dur, attack=0.08, release=0.12): - """Detuned saw pad, stereo; filter it on the bus (Session.pad_cut).""" - t = tvec(dur + release) - L = np.zeros_like(t) - R = np.zeros_like(t) - for n in notes: - f = midi(n) - for cents, side in ((-11, "L"), (5, "L"), (0, "C"), (-5, "R"), (11, "R")): - v = saw(f * 2 ** (cents / 1200), t, _rng.uniform()) - if side in "LC": - L += v - if side in "RC": - R += v - env = np.clip(t / attack, 0, 1) * np.where( - t < dur, 1.0, np.clip(1 - (t - dur) / release, 0, 1) - ) - return np.stack([L, R]) * env / (len(notes) * 3) - - -def pluck(freq, dur=0.6, bright=0.5): - """Felt-piano-ish pluck: additive partials, the high ones dying first.""" - t = tvec(dur) - out = np.zeros_like(t) - for h in range(1, 14): - if h * freq > 12000: - break - out += ( - np.sin(2 * np.pi * h * freq * t) - / h**1.1 - * np.exp(-t * (5 + h * h * 0.9 * bright)) - ) - return norm(out * np.clip(t / 0.002, 0, 1)) - - -def plink(freq, dur=0.6): - """Marimba-ish: partials at 1, 3.93 and 9.2, a tiny pitch drop on the strike.""" - t = tvec(dur) - ph = 2 * np.pi * np.cumsum(freq * (1 + 0.06 * np.exp(-t * 60))) / SR - x = ( - np.sin(ph) * np.exp(-t * 8) - + 0.35 * np.sin(3.93 * ph) * np.exp(-t * 30) - + 0.15 * np.sin(9.2 * ph) * np.exp(-t * 60) - ) - return norm(x * _env_on(t)) - - -def woodblock(freq, dur=0.12): - t = tvec(dur) - tone = np.sin(2 * np.pi * freq * t) * np.exp(-t * 55) + 0.4 * np.sin( - 2 * np.pi * freq * 2.4 * t - ) * np.exp(-t * 90) - click = hp(_rng.standard_normal(len(t)), 2500) * np.exp(-t * 400) * 0.3 - return norm((tone + click) * np.clip(t / 0.0008, 0, 1)) - - -def grain(freq, dur=0.05): - t = tvec(dur) - return np.sin(2 * np.pi * freq * t) * np.exp(-t * 70) * np.clip(t / 0.002, 0, 1) - - -def blip(freq, dur=0.1): - t = tvec(dur) - return ( - (np.sin(2 * np.pi * freq * t) + 0.3 * np.sin(4 * np.pi * freq * t)) - * np.exp(-t * 38) - * _env_on(t) - ) - - -def glide(f0, f1, dur): - t = tvec(dur) - f = f0 + (f1 - f0) * (1 - np.exp(-t * 8)) / (1 - np.exp(-8)) - return ( - np.sin(2 * np.pi * np.cumsum(f) / SR) * np.sin(np.pi * t / max(dur, 1e-6)) ** 2 - ) - - -def sonar(dur, f0=520.0, f1=880.0): - t = tvec(dur) - u = t / max(dur, 1e-6) - f = f0 * (f1 / f0) ** u * (1 + 0.004 * np.sin(2 * np.pi * 5.5 * t)) - ph = 2 * np.pi * np.cumsum(f) / SR - return (np.sin(ph) + 0.25 * np.sin(2 * ph)) * np.sin(np.pi * u) ** 1.5 - - -# ------------------------------------------------------------------ effects -def whoosh(dur=0.5, lo=250.0, hi=5000.0, peak=0.65, pan=(-0.7, 0.7)): - """Band-passed noise sweeping up to `peak` of its length, panned across; stereo.""" - t = tvec(dur) - u = t / max(dur, 1e-6) - - def fc(tt): - v = tt / dur - return ( - lo * (hi / lo) ** (v / peak) - if v < peak - else hi * 0.5 ** ((v - peak) / (1 - peak)) - ) - - y = norm(sweep(_rng.standard_normal(len(t)), fc, "bandpass", width=1.6)) - y = y * np.where( - u < peak, (u / peak) ** 2, np.clip(1 - (u - peak) / (1 - peak), 0, 1) ** 1.6 - ) - return pan_stereo(y, np.linspace(pan[0], pan[1], len(t))) - - -def reverse(stereo_or_mono): - """A sound played backwards with a rising fade: the swell into a hit.""" - x = np.asarray(stereo_or_mono) - x = x.sum(axis=0) if x.ndim == 2 else x - x = norm(x[::-1]) - return x * np.linspace(0, 1, len(x)) ** 2 - - -def riser(dur): - t = tvec(dur) - u = t / max(dur, 1e-6) - y = ( - norm( - sweep( - _rng.standard_normal(len(t)), - lambda tt: 250 * (7000 / 250) ** (tt / dur), - "bandpass", - width=1.35, - ) - ) - * u**2.4 - ) - tone = np.sin(2 * np.pi * np.cumsum(160 * (1400 / 160) ** u) / SR) * u**3 * 0.25 - return y + tone - - -def impact(dur=2.6, crash=1.0): - """A big hit: pitched boom, crash, kick. For punchy reels.""" - t = tvec(dur) - boom = np.sin(2 * np.pi * np.cumsum(34 + 70 * np.exp(-t * 16)) / SR) * np.exp( - -t * 1.9 - ) - cr = hp(_rng.standard_normal(len(t)), 3200) * ( - np.exp(-t * 3.2) * 0.3 + np.exp(-t * 25) * 0.5 - ) - k = _with(t, kick(f0=190, f1=42, adec=4, dur=0.8, click=0.5)) - return np.tanh(1.2 * (boom * 0.9 + cr * crash + k * 0.8)) - - -def soft_impact(dur=3.0): - """A warm arrival: sub boom and a little air, no crash. For calm brands.""" - t = tvec(dur) - boom = np.sin(2 * np.pi * np.cumsum(38 + 40 * np.exp(-t * 14)) / SR) * np.exp( - -t * 1.6 - ) - air = lp(hp(_rng.standard_normal(len(t)), 4000), 9000) * np.exp(-t * 3.5) * 0.12 - k = _with(t, kick(f0=120, f1=44, adec=3.5, dur=0.9, click=0.08)) - return np.tanh(1.1 * (boom + air + 0.6 * k)) - - -def burst(dur=0.9): - t = tvec(dur) - y = sweep( - _rng.standard_normal(len(t)), lambda tt: 9000 * (300 / 9000) ** min(1, tt / 0.7) - ) - y = norm(y * np.exp(-t * 4.5) * np.clip(t / 0.002, 0, 1)) - th = np.sin(2 * np.pi * np.cumsum(50 + 80 * np.exp(-t * 20)) / SR) * np.exp(-t * 6) - return y * 0.8 + th * 0.7 - - -def make_ir(dur=2.6, decay=2.6): - t = tvec(dur) - ir = _rng.standard_normal((2, len(t))) * np.exp(-t * decay) - ir = np.stack([lp(ch, 6500) for ch in ir]) - ir[:, : int(0.012 * SR)] = 0 - return ir / np.sqrt(np.sum(ir**2, axis=1, keepdims=True)) - - -# ------------------------------------------------------------------ buses and the session -class Bus: - def __init__(self, n): - self.n = n - self.x = np.zeros((2, n)) - - def add(self, sig, t0, gain=1.0, pan=0.0): - """Mix `sig` (mono or stereo) in at t0 seconds; mono is panned equal-power.""" - sig = np.asarray(sig, dtype=float) - if sig.ndim == 1: - sig = pan_stereo(sig, pan) - i0 = int(round(t0 * SR)) - if i0 < 0: - sig, i0 = sig[:, -i0:], 0 - n = min(sig.shape[1], self.n - i0) - if n > 0: - self.x[:, i0 : i0 + n] += gain * sig[:, :n] - - -class Session: - """What score.py gets: the cue sheet, six buses, and the mix settings.""" - - def __init__(self, info, seed=2026): - global _rng - _rng = np.random.default_rng(seed) - self.rng = np.random.default_rng(seed + 1) - self.cues = info["cues"] - self.dur = float(info["dur"]) - self.bpm = float(self.cues["bpm"]) - self.beat = 60 / self.bpm - self.bar = 4 * self.beat - self.n = int(round(self.dur * SR)) - self.drums, self.bass, self.pad, self.keys, self.fx, self.send = ( - Bus(self.n) for _ in range(6) - ) - self.kicks, self.silences, self.checks = [], [], [] - # mix settings a score may change - self.duck_depth = 0.45 # sidechain: how far pads and bass dip under a kick - self.pad_cut = 1500 # pad bus low-pass, Hz - self.reverb = 0.3 - self.delay = 0.45 # dotted-eighth ping-pong on the keys bus - self.drive = 1.1 # soft-clip drive before the final normalise - self.fade_out = 0.6 - - def kick(self, t, gain=0.72): - """A kick that also ducks the pads and bass.""" - self.drums.add(kick(), t, gain) - self.kicks.append(t) - - def silence(self, t0, t1): - """Gate [t0, t1) to digital silence. Checked after the mix.""" - self.silences.append((t0, t1)) - - def check(self, label, t): - """Report the peak level of the 30 ms from t, after the mix.""" - self.checks.append((label, t, t + 0.03)) - - def render(self, out): - n, tt = self.n, np.arange(self.n) / SR - kicks = np.array(sorted(self.kicks)) if self.kicks else np.array([-10.0]) - idx = np.searchsorted(kicks, tt, side="right") - 1 - since = np.where(idx >= 0, tt - kicks[np.clip(idx, 0, None)], 10.0) - duck = 1 - self.duck_depth * np.exp(-since * 8) - padf = np.stack([lp(ch, self.pad_cut) for ch in self.pad.x]) - ir = make_ir() - wet = np.stack( - [ - signal.fftconvolve( - self.send.x[c] + 0.2 * padf[c] + 0.25 * self.keys.x[c], ir[c] - )[:n] - for c in range(2) - ] - ) - dly = np.zeros_like(self.keys.x) - d = int(round(3 * self.beat / 4 * SR)) - for k in range(1, 5): - src = self.keys.x.sum(axis=0) * 0.5 * 0.4**k - if k * d < n: - dly[k % 2, k * d :] += src[: n - k * d] - mix = ( - self.drums.x - + (self.bass.x + 0.22 * padf) * duck - + self.keys.x - + self.delay * dly - + self.fx.x - + self.reverb * wet - ) - mix = np.stack([hp(ch, 30) for ch in mix]) - gate = np.ones(n) - ramp = int(0.008 * SR) - for t0, t1 in self.silences: - a, b = int(t0 * SR), int(t1 * SR) - gate[a:b] = 0 - gate[max(0, a - ramp) : a] *= np.linspace(1, 0, a - max(0, a - ramp)) - mix *= gate - mix = norm(mix) - mix = np.tanh(self.drive * mix) / np.tanh(self.drive) - mix *= np.clip((self.dur - tt) / self.fade_out, 0, 1) - mix = 0.89 * norm(mix) # -1 dBFS peak - wav = io.BytesIO() - wavfile.write(wav, SR, (mix.T * 32767).astype(np.int16)) - write_file(out, wav.getvalue(), out.parent) # never through a link at audio.wav - return mix - - -def level_db(mix, t0, t1): - x = mix.mean(axis=0) - a, b = int(t0 * SR), max(int(t0 * SR) + 1, int(t1 * SR)) - return 20 * np.log10(np.max(np.abs(x[a:b])) + 1e-9) - - -def main(): - ap = argparse.ArgumentParser( - description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter - ) - ap.add_argument("project", type=Path) - a = ap.parse_args() - project = a.project.resolve() - info = json.loads((project / "cues.json").read_text()) - # `from synth import ...` in score.py sees this module - sys.modules.setdefault("synth", sys.modules[__name__]) - # loading score.py must not write its bytecode into the project (a linked __pycache__ - # would carry it elsewhere): nothing but audio.wav is written there - sys.dont_write_bytecode = True - spec = importlib.util.spec_from_file_location("reel_score", project / "score.py") - mod = importlib.util.module_from_spec(spec) - spec.loader.exec_module(mod) - s = Session(info) - mod.score(s) - out = project / "audio.wav" - mix = s.render(out) - rms = 20 * np.log10(np.sqrt(np.mean(mix**2))) - print(f"wrote {out}: {s.dur:.2f} s, peak -1.0 dBFS, rms {rms:.1f} dBFS") - for label, t0, t1 in s.checks: - print(f" {label:32s} {t0:8.3f} s {level_db(mix, t0, t1):7.1f} dB") - loud = [(t0, t1, level_db(mix, t0 + 0.01, t1 - 0.005)) for t0, t1 in s.silences] - for t0, t1, db in loud: - print(f" {'silence':32s} {t0:8.3f} s {db:7.1f} dB") - bad = [x for x in loud if x[2] > -100] - if bad: - print(f"FAIL: {len(bad)} silence window(s) are not silent", file=sys.stderr) - sys.exit(1) - - -if __name__ == "__main__": - main() diff --git a/claude/skills/visual/motion-reel/scripts/test_motion_reel.py b/claude/skills/visual/motion-reel/scripts/test_motion_reel.py deleted file mode 100644 index dffc275a..00000000 --- a/claude/skills/visual/motion-reel/scripts/test_motion_reel.py +++ /dev/null @@ -1,137 +0,0 @@ -"""Offline tests for the disk guards in render.py and encode.py (TOM-1222). -No Chrome and no real ffmpeg: the page and ffmpeg are stubbed. -Run: python -m pytest test_motion_reel.py""" - -import argparse -import json -import sys -from collections import namedtuple -from pathlib import Path - -import pytest - -sys.path.insert(0, str(Path(__file__).resolve().parent)) - -import encode -import render - -Usage = namedtuple("Usage", "total used free") - -INFO = {"w": 1920, "h": 1080, "fps": 60, "dur": 56.25, "frames": 3375, "scenes": []} - - -class Reached(Exception): - """The render went past the disk check.""" - - -def frames_args(project): - return argparse.Namespace(sub=8, workers=2, project=project) - - -def stub_render(monkeypatch, free): - monkeypatch.setattr(render, "with_page", lambda project, fn: (INFO, 2_000_000)) - monkeypatch.setattr(render.shutil, "disk_usage", lambda p: Usage(0, 0, free)) - - def serve(project): - raise Reached - - monkeypatch.setattr(render, "serve", serve) - - -def test_frames_refuses_when_disk_too_small(tmp_path, monkeypatch): - stub_render(monkeypatch, free=2**30) - old = tmp_path / "frames" / "f_00000.png" - old.parent.mkdir() - old.write_bytes(b"old frame") - with pytest.raises(SystemExit) as e: - render.cmd_frames(tmp_path, frames_args(tmp_path)) - msg = str(e.value) - # 2 x 2.0 MB sample > 1.25 B/px floor: 4,000,000 x 3,375 frames = 12.6 GiB - assert "12.6 GiB" in msg, msg - assert "1.0 GiB free" in msg, msg - # refused before the render started, and before the old frames were deleted - assert [p.name for p in old.parent.iterdir()] == ["f_00000.png"] - - -def test_frames_proceeds_when_disk_holds_them(tmp_path, monkeypatch): - stub_render(monkeypatch, free=20 * 2**30) - with pytest.raises(Reached): - render.cmd_frames(tmp_path, frames_args(tmp_path)) - - -def test_frames_bytes_uses_pixel_floor_for_a_blank_sample(): - assert render.frames_bytes(INFO, 1000) == int(1.25 * 1920 * 1080 * 3375) - - -STUB = """#!/usr/bin/env python3 -import os, sys -args = sys.argv[1:] -if "null" in args: - sys.stderr.write("frame= %s fps=0\\n" % os.environ.get("STUB_FRAMES", "3")) - sys.exit(0) -if args[-2] == "-i": # probe: input only, no output - sys.stderr.write("Duration: 00:00:00.05\\n") - sys.exit(1) -with open(args[-1], "wb") as f: - f.write(b"NEW" * 100) -sys.exit(1 if os.environ.get("STUB_FAIL") else 0) -""" - - -@pytest.fixture -def project(tmp_path, monkeypatch): - stub = tmp_path / "ffmpeg" - stub.write_text(STUB) - stub.chmod(0o755) - monkeypatch.setattr(encode, "ffmpeg", lambda: str(stub)) - proj = tmp_path / "reel-project" - (proj / "frames").mkdir(parents=True) - for f in range(3): - (proj / "frames" / f"f_{f:05d}.png").write_bytes(b"png") - (proj / "cues.json").write_text(json.dumps({"fps": 60, "frames": 3})) - return proj.resolve() - - -def test_failed_encode_keeps_previous_videos(project, monkeypatch): - (project / "reel-master.mp4").write_bytes(b"OLD-MASTER") - (project / "reel.mp4").write_bytes(b"OLD-SHARE") - monkeypatch.setenv("STUB_FAIL", "1") - with pytest.raises(SystemExit) as e: - encode.encode(project, "reel", 29.0) - assert "ffmpeg exited 1" in str(e.value) - assert (project / "reel-master.mp4").read_bytes() == b"OLD-MASTER" - assert (project / "reel.mp4").read_bytes() == b"OLD-SHARE" - assert list(project.glob("*.part.*")) == [] - - -def test_frame_count_mismatch_keeps_previous_videos(project, monkeypatch): - (project / "reel-master.mp4").write_bytes(b"OLD-MASTER") - (project / "reel.mp4").write_bytes(b"OLD-SHARE") - monkeypatch.delenv("STUB_FAIL", raising=False) - monkeypatch.setenv("STUB_FRAMES", "2") - with pytest.raises(SystemExit) as e: - encode.encode(project, "reel", 29.0) - assert "decodes to 2 frames, expected 3" in str(e.value) - assert (project / "reel-master.mp4").read_bytes() == b"OLD-MASTER" - assert (project / "reel.mp4").read_bytes() == b"OLD-SHARE" - assert list(project.glob("*.part.*")) == [] - - -def test_failed_first_encode_leaves_no_final_file(project, monkeypatch): - monkeypatch.setenv("STUB_FAIL", "1") - with pytest.raises(SystemExit): - encode.encode(project, "reel", 29.0) - assert sorted(p.name for p in project.iterdir()) == ["cues.json", "frames"] - - -def test_normal_encode_writes_the_same_final_names(project, monkeypatch): - monkeypatch.delenv("STUB_FAIL", raising=False) - (project / "reel-master.mp4").write_bytes(b"OLD-MASTER") - encode.encode(project, "reel", 29.0) - assert (project / "reel-master.mp4").read_bytes() == b"NEW" * 100 - assert (project / "reel.mp4").read_bytes() == b"NEW" * 100 - assert list(project.glob("*.part.*")) == [] - - -if __name__ == "__main__": - sys.exit(pytest.main([__file__, "-v"])) diff --git a/claude/skills/visual/ui-ux-pro-max/SKILL.md b/claude/skills/visual/ui-ux-pro-max/SKILL.md deleted file mode 100644 index e27f60d4..00000000 --- a/claude/skills/visual/ui-ux-pro-max/SKILL.md +++ /dev/null @@ -1,354 +0,0 @@ ---- -name: ui-ux-pro-max -description: | - UI/UX design intelligence for web and mobile. Use when tasks involve visual design decisions, - component creation, style/color/font selection, layout, accessibility, or UX quality control. - Covers 50+ styles, 161 color palettes, 57 font pairings, 99 UX guidelines, and 25 chart types - across 10 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind, - shadcn/ui, HTML/CSS). Actions: plan, build, design, review, fix, improve UI/UX code. -user-invocable: true -argument-hint: "[design request or review target]" ---- - -# UI/UX Pro Max — Design Intelligence - -Comprehensive design guide for web and mobile applications. Based on [nextlevelbuilder/ui-ux-pro-max-skill](https://github.com/nextlevelbuilder/ui-ux-pro-max-skill). - -## When to Apply - -Use when the task involves **UI structure, visual design decisions, interaction patterns, or user experience quality control**. - -### Must Use - -- Designing new pages (Landing Page, Dashboard, Admin, SaaS, Mobile App) -- Creating or refactoring UI components (buttons, modals, forms, tables, charts) -- Choosing color schemes, typography systems, spacing standards, or layout systems -- Reviewing UI code for user experience, accessibility, or visual consistency -- Implementing navigation structures, animations, or responsive behavior -- Making product-level design decisions (style, information hierarchy, brand expression) - -### Skip - -- Pure backend logic, API/database design, DevOps, non-visual scripts - -**Decision criteria**: If the task changes how a feature **looks, feels, moves, or is interacted with**, use this skill. - -## Rule Categories by Priority - -| Priority | Category | Impact | Key Checks (Must Have) | Anti-Patterns (Avoid) | -|----------|----------|--------|------------------------|------------------------| -| 1 | Accessibility | CRITICAL | Contrast 4.5:1, Alt text, Keyboard nav, Aria-labels | Removing focus rings, Icon-only buttons without labels | -| 2 | Touch & Interaction | CRITICAL | Min size 44×44px, 8px+ spacing, Loading feedback | Reliance on hover only, Instant state changes (0ms) | -| 3 | Performance | HIGH | WebP/AVIF, Lazy loading, Reserve space (CLS < 0.1) | Layout thrashing, Cumulative Layout Shift | -| 4 | Style Selection | HIGH | Match product type, Consistency, SVG icons (no emoji) | Mixing flat & skeuomorphic randomly, Emoji as icons | -| 5 | Layout & Responsive | HIGH | Mobile-first breakpoints, Viewport meta, No horizontal scroll | Horizontal scroll, Fixed px container widths, Disable zoom | -| 6 | Typography & Color | MEDIUM | Base 16px, Line-height 1.5, Semantic color tokens | Text < 12px body, Gray-on-gray, Raw hex in components | -| 7 | Animation | MEDIUM | Duration 150–300ms, Motion conveys meaning, Spatial continuity | Decorative-only animation, Animating width/height, No reduced-motion | -| 8 | Forms & Feedback | MEDIUM | Visible labels, Error near field, Helper text, Progressive disclosure | Placeholder-only label, Errors only at top, Overwhelm upfront | -| 9 | Navigation Patterns | HIGH | Predictable back, Bottom nav ≤5, Deep linking | Overloaded nav, Broken back behavior, No deep links | -| 10 | Charts & Data | LOW | Legends, Tooltips, Accessible colors | Relying on color alone to convey meaning | - -## Quick Reference - -### 1. Accessibility (CRITICAL) - -- `color-contrast` — Minimum 4.5:1 ratio for normal text (large text 3:1) -- `focus-states` — Visible focus rings on interactive elements (2–4px) -- `alt-text` — Descriptive alt text for meaningful images -- `aria-labels` — aria-label for icon-only buttons; accessibilityLabel in native -- `keyboard-nav` — Tab order matches visual order; full keyboard support -- `form-labels` — Use label with for attribute -- `skip-links` — Skip to main content for keyboard users -- `heading-hierarchy` — Sequential h1→h6, no level skip -- `color-not-only` — Don't convey info by color alone (add icon/text) -- `dynamic-type` — Support system text scaling; avoid truncation as text grows -- `reduced-motion` — Respect prefers-reduced-motion; reduce/disable animations when requested -- `voiceover-sr` — Meaningful accessibilityLabel/accessibilityHint; logical reading order -- `escape-routes` — Provide cancel/back in modals and multi-step flows -- `keyboard-shortcuts` — Preserve system and a11y shortcuts; offer keyboard alternatives for drag-and-drop - -### 2. Touch & Interaction (CRITICAL) - -- `touch-target-size` — Min 44×44pt (Apple) / 48×48dp (Material); extend hit area if needed -- `touch-spacing` — Minimum 8px/8dp gap between touch targets -- `hover-vs-tap` — Use click/tap for primary interactions; don't rely on hover alone -- `loading-buttons` — Disable button during async operations; show spinner or progress -- `error-feedback` — Clear error messages near problem -- `cursor-pointer` — Add cursor-pointer to clickable elements (Web) -- `gesture-conflicts` — Avoid horizontal swipe on main content; prefer vertical scroll -- `tap-delay` — Use touch-action: manipulation to reduce 300ms delay (Web) -- `standard-gestures` — Use platform standard gestures consistently -- `system-gestures` — Don't block system gestures (Control Center, back swipe, etc.) -- `press-feedback` — Visual feedback on press (ripple/highlight) -- `haptic-feedback` — Use haptic for confirmations and important actions; avoid overuse -- `gesture-alternative` — Always provide visible controls for critical actions -- `safe-area-awareness` — Keep primary touch targets away from notch, Dynamic Island, gesture bar -- `no-precision-required` — Avoid requiring pixel-perfect taps on small icons or thin edges -- `swipe-clarity` — Swipe actions must show clear affordance or hint -- `drag-threshold` — Use a movement threshold before starting drag to avoid accidental drags - -### 3. Performance (HIGH) - -- `image-optimization` — Use WebP/AVIF, responsive images (srcset/sizes), lazy load non-critical assets -- `image-dimension` — Declare width/height or use aspect-ratio to prevent layout shift (CLS) -- `font-loading` — Use font-display: swap/optional to avoid invisible text (FOIT) -- `font-preload` — Preload only critical fonts -- `critical-css` — Prioritize above-the-fold CSS -- `lazy-loading` — Lazy load non-hero components via dynamic import / route-level splitting -- `bundle-splitting` — Split code by route/feature to reduce initial load and TTI -- `third-party-scripts` — Load third-party scripts async/defer -- `reduce-reflows` — Avoid frequent layout reads/writes; batch DOM reads then writes -- `content-jumping` — Reserve space for async content to avoid layout jumps (CLS) -- `virtualize-lists` — Virtualize lists with 50+ items -- `main-thread-budget` — Keep per-frame work under ~16ms for 60fps -- `progressive-loading` — Use skeleton screens / shimmer instead of long blocking spinners -- `input-latency` — Keep input latency under ~100ms for taps/scrolls -- `debounce-throttle` — Use debounce/throttle for high-frequency events (scroll, resize, input) -- `offline-support` — Provide offline state messaging and basic fallback (PWA / mobile) - -### 4. Style Selection (HIGH) - -- `style-match` — Match style to product type -- `consistency` — Use same style across all pages -- `no-emoji-icons` — Use SVG icons (Heroicons, Lucide), not emojis -- `color-palette-from-product` — Choose palette from product/industry -- `effects-match-style` — Shadows, blur, radius aligned with chosen style -- `platform-adaptive` — Respect platform idioms (iOS HIG vs Material) -- `state-clarity` — Make hover/pressed/disabled states visually distinct while staying on-style -- `elevation-consistent` — Use a consistent elevation/shadow scale -- `dark-mode-pairing` — Design light/dark variants together -- `icon-style-consistent` — Use one icon set/visual language across the product -- `system-controls` — Prefer native/system controls over fully custom ones -- `blur-purpose` — Use blur to indicate background dismissal, not as decoration -- `primary-action` — Each screen should have only one primary CTA - -### 5. Layout & Responsive (HIGH) - -- `viewport-meta` — width=device-width initial-scale=1 (never disable zoom) -- `mobile-first` — Design mobile-first, then scale up -- `breakpoint-consistency` — Use systematic breakpoints (e.g. 375 / 768 / 1024 / 1440) -- `readable-font-size` — Minimum 16px body text on mobile (avoids iOS auto-zoom) -- `line-length-control` — Mobile 35–60 chars per line; desktop 60–75 chars -- `horizontal-scroll` — No horizontal scroll on mobile -- `spacing-scale` — Use 4pt/8dp incremental spacing system -- `container-width` — Consistent max-width on desktop -- `z-index-management` — Define layered z-index scale -- `fixed-element-offset` — Fixed navbar/bottom bar must reserve safe padding -- `scroll-behavior` — Avoid nested scroll regions that interfere with main scroll -- `viewport-units` — Prefer min-h-dvh over 100vh on mobile -- `orientation-support` — Keep layout readable in landscape mode -- `content-priority` — Show core content first on mobile -- `visual-hierarchy` — Establish hierarchy via size, spacing, contrast — not color alone - -### 6. Typography & Color (MEDIUM) - -- `line-height` — Use 1.5–1.75 for body text -- `line-length` — Limit to 65–75 characters per line -- `font-pairing` — Match heading/body font personalities -- `font-scale` — Consistent type scale (e.g. 12 14 16 18 24 32) -- `contrast-readability` — Darker text on light backgrounds -- `text-styles-system` — Use platform type system (iOS Dynamic Type / Material type roles) -- `weight-hierarchy` — Bold headings (600–700), Regular body (400), Medium labels (500) -- `color-semantic` — Define semantic color tokens (primary, secondary, error, surface) not raw hex -- `color-dark-mode` — Dark mode uses desaturated / lighter tonal variants, not inverted colors -- `color-accessible-pairs` — Foreground/background pairs must meet 4.5:1 (AA) or 7:1 (AAA) -- `color-not-decorative-only` — Functional color must include icon/text -- `truncation-strategy` — Prefer wrapping over truncation; when truncating use ellipsis with tooltip -- `number-tabular` — Use tabular/monospaced figures for data columns, prices, timers -- `whitespace-balance` — Use whitespace intentionally to group related items and separate sections - -### 7. Animation (MEDIUM) - -- `duration-timing` — 150–300ms for micro-interactions; complex transitions ≤400ms; avoid >500ms -- `transform-performance` — Use transform/opacity only; avoid animating width/height/top/left -- `loading-states` — Show skeleton or progress indicator when loading exceeds 300ms -- `excessive-motion` — Animate 1–2 key elements per view max -- `easing` — Use ease-out for entering, ease-in for exiting; avoid linear for UI transitions -- `motion-meaning` — Every animation must express cause-effect, not just be decorative -- `state-transition` — State changes should animate smoothly, not snap -- `continuity` — Page/screen transitions should maintain spatial continuity -- `spring-physics` — Prefer spring/physics-based curves for natural feel -- `exit-faster-than-enter` — Exit animations shorter than enter (~60–70% of enter duration) -- `stagger-sequence` — Stagger list/grid item entrance by 30–50ms per item -- `shared-element-transition` — Use shared element / hero transitions between screens -- `interruptible` — Animations must be interruptible; user tap cancels in-progress animation -- `no-blocking-animation` — Never block user input during an animation -- `scale-feedback` — Subtle scale (0.95–1.05) on press for tappable cards/buttons -- `gesture-feedback` — Drag, swipe, and pinch must provide real-time visual response -- `modal-motion` — Modals/sheets should animate from their trigger source -- `navigation-direction` — Forward navigation animates left/up; backward right/down - -### 8. Forms & Feedback (MEDIUM) - -- `input-labels` — Visible label per input (not placeholder-only) -- `error-placement` — Show error below the related field -- `submit-feedback` — Loading then success/error state on submit -- `required-indicators` — Mark required fields (e.g. asterisk) -- `empty-states` — Helpful message and action when no content -- `toast-dismiss` — Auto-dismiss toasts in 3–5s -- `confirmation-dialogs` — Confirm before destructive actions -- `input-helper-text` — Provide persistent helper text below complex inputs -- `disabled-states` — Reduced opacity (0.38–0.5) + cursor change + semantic attribute -- `progressive-disclosure` — Reveal complex options progressively -- `inline-validation` — Validate on blur (not keystroke) -- `input-type-keyboard` — Use semantic input types (email, tel, number) for correct mobile keyboard -- `password-toggle` — Provide show/hide toggle for password fields -- `undo-support` — Allow undo for destructive or bulk actions -- `success-feedback` — Confirm completed actions with brief visual feedback -- `error-recovery` — Error messages must include a clear recovery path -- `multi-step-progress` — Multi-step flows show step indicator; allow back navigation -- `form-autosave` — Long forms should auto-save drafts -- `error-clarity` — Error messages must state cause + how to fix -- `field-grouping` — Group related fields logically -- `focus-management` — After submit error, auto-focus the first invalid field -- `destructive-emphasis` — Destructive actions use semantic danger color and are visually separated -- `toast-accessibility` — Toasts must not steal focus; use aria-live="polite" - -### 9. Navigation Patterns (HIGH) - -- `bottom-nav-limit` — Bottom navigation max 5 items; use labels with icons -- `drawer-usage` — Use drawer/sidebar for secondary navigation, not primary actions -- `back-behavior` — Back navigation must be predictable and consistent; preserve scroll/state -- `deep-linking` — All key screens must be reachable via deep link / URL -- `tab-bar-ios` — iOS: use bottom Tab Bar for top-level navigation -- `top-app-bar-android` — Android: use Top App Bar with navigation icon -- `nav-label-icon` — Navigation items must have both icon and text label -- `nav-state-active` — Current location must be visually highlighted in navigation -- `nav-hierarchy` — Primary nav vs secondary nav must be clearly separated -- `modal-escape` — Modals and sheets must offer a clear close/dismiss affordance -- `search-accessible` — Search must be easily reachable; provide recent/suggested queries -- `breadcrumb-web` — Web: use breadcrumbs for 3+ level deep hierarchies -- `state-preservation` — Navigating back must restore previous scroll position and filter state -- `gesture-nav-support` — Support system gesture navigation without conflict -- `overflow-menu` — When actions exceed available space, use overflow/more menu -- `adaptive-navigation` — Large screens prefer sidebar; small screens use bottom/top nav -- `back-stack-integrity` — Never silently reset the navigation stack -- `navigation-consistency` — Navigation placement must stay the same across all pages -- `modal-vs-navigation` — Modals must not be used for primary navigation flows -- `focus-on-route-change` — After page transition, move focus to main content region for screen readers -- `persistent-nav` — Core navigation must remain reachable from deep pages -- `destructive-nav-separation` — Dangerous actions must be visually and spatially separated from normal nav items - -### 10. Charts & Data (LOW) - -- `chart-type` — Match chart type to data type (trend→line, comparison→bar, proportion→pie/donut) -- `color-guidance` — Use accessible color palettes; avoid red/green only pairs -- `data-table` — Provide table alternative for accessibility -- `pattern-texture` — Supplement color with patterns/textures/shapes -- `legend-visible` — Always show legend; position near the chart -- `tooltip-on-interact` — Provide tooltips on hover (Web) or tap (mobile) showing exact values -- `axis-labels` — Label axes with units and readable scale -- `responsive-chart` — Charts must reflow or simplify on small screens -- `empty-data-state` — Show meaningful empty state when no data exists -- `loading-chart` — Use skeleton/shimmer placeholder while chart data loads -- `large-dataset` — For 1000+ data points, aggregate or sample; provide drill-down -- `number-formatting` — Use locale-aware formatting for numbers, dates, currencies -- `touch-target-chart` — Interactive chart elements must have ≥44pt tap area -- `no-pie-overuse` — Avoid pie/donut for >5 categories; switch to bar chart -- `contrast-data` — Data lines/bars vs background ≥3:1; data text labels ≥4.5:1 -- `legend-interactive` — Legends should be clickable to toggle series visibility -- `tooltip-keyboard` — Tooltip content must be keyboard-reachable -- `sortable-table` — Data tables must support sorting with aria-sort -- `focusable-elements` — Interactive chart elements must be keyboard-navigable -- `screen-reader-summary` — Provide a text summary or aria-label describing the chart's key insight - -## Design System Workflow - -When designing a new project or page, follow this workflow: - -### Step 1: Analyze Requirements - -Extract from user request: -- **Product type**: Entertainment, Tool, Productivity, E-commerce, SaaS, Portfolio, etc. -- **Target audience**: Age group, usage context (commute, leisure, work) -- **Style keywords**: playful, vibrant, minimal, dark mode, content-first, immersive, etc. -- **Stack**: React, Next.js, Vue, Svelte, React Native, Flutter, Tailwind, etc. - -### Step 2: Generate Design System - -Recommend a complete design system covering: -1. **Pattern** — Page structure and layout approach matching product type -2. **Style** — Visual style (glassmorphism, minimalism, brutalism, neumorphism, etc.) -3. **Colors** — Palette aligned with product type and industry -4. **Typography** — Font pairings (heading + body) from Google Fonts -5. **Effects** — Shadows, blur, radius, animations matching the chosen style -6. **Anti-patterns** — What to avoid for this specific product type - -### Step 3: Apply Rules by Priority - -Work through the priority table (§1–§10), focusing on: -1. CRITICAL rules first (Accessibility, Touch & Interaction) -2. HIGH impact rules next (Performance, Style, Layout, Navigation) -3. MEDIUM rules for polish (Typography, Animation, Forms) -4. LOW rules as applicable (Charts & Data) - -## Common Rules for Professional UI - -### Icons & Visual Elements - -| Rule | Standard | Avoid | -|------|----------|-------| -| No Emoji as Icons | Use vector icons (Heroicons, Lucide, react-native-vector-icons) | Emojis (🎨 🚀 ⚙️) for navigation or system controls | -| Vector-Only Assets | SVG or platform vector icons that scale cleanly | Raster PNG icons that blur or pixelate | -| Stable Interaction States | Color, opacity, or elevation transitions for press states | Layout-shifting transforms that move surrounding content | -| Correct Brand Logos | Official brand assets following usage guidelines | Guessing logo paths or recoloring unofficially | -| Consistent Icon Sizing | Define icon sizes as design tokens (icon-sm, icon-md=24pt, icon-lg) | Mixing arbitrary values randomly | -| Stroke Consistency | Consistent stroke width within the same visual layer | Mixing thick and thin stroke styles | -| Filled vs Outline | One icon style per hierarchy level | Mixing filled and outline at the same level | - -### Light/Dark Mode Contrast - -| Rule | Do | Don't | -|------|----|----- | -| Surface readability | Cards/surfaces clearly separated from background | Overly transparent surfaces that blur hierarchy | -| Text contrast (light) | Body text contrast ≥4.5:1 against light surfaces | Low-contrast gray body text | -| Text contrast (dark) | Primary text ≥4.5:1, secondary ≥3:1 on dark surfaces | Dark mode text blending into background | -| Border visibility | Separators visible in both themes | Theme-specific borders disappearing in one mode | -| State contrast parity | Pressed/focused/disabled equally distinguishable in both modes | Defining interaction states for one theme only | -| Token-driven theming | Semantic color tokens mapped per theme | Hardcoded per-screen hex values | - -### Layout & Spacing - -| Rule | Do | Don't | -|------|----|----- | -| Safe-area compliance | Respect top/bottom safe areas for fixed headers, tab bars, CTAs | Placing UI under notch, status bar, gesture area | -| System bar clearance | Add spacing for status/navigation bars and gesture indicator | Tappable content colliding with OS chrome | -| 8dp spacing rhythm | Consistent 4/8dp spacing system | Random spacing increments | -| Readable text measure | Keep long-form text readable on large devices | Full-width paragraphs on tablets | -| Scroll + fixed coexistence | Add content insets so lists aren't hidden behind fixed bars | Scroll content obscured by sticky headers/footers | - -## Pre-Delivery Checklist - -### Visual Quality -- [ ] No emojis used as icons (use SVG instead) -- [ ] All icons from a consistent icon family and style -- [ ] Official brand assets with correct proportions -- [ ] Pressed-state visuals do not shift layout bounds -- [ ] Semantic theme tokens used consistently - -### Interaction -- [ ] All tappable elements provide clear pressed feedback -- [ ] Touch targets meet minimum size (≥44×44pt iOS, ≥48×48dp Android) -- [ ] Micro-interaction timing 150–300ms with native-feeling easing -- [ ] Disabled states visually clear and non-interactive -- [ ] Screen reader focus order matches visual order - -### Light/Dark Mode -- [ ] Primary text contrast ≥4.5:1 in both modes -- [ ] Secondary text contrast ≥3:1 in both modes -- [ ] Dividers/borders distinguishable in both modes -- [ ] Both themes tested before delivery - -### Layout -- [ ] Safe areas respected for headers, tab bars, bottom CTAs -- [ ] Scroll content not hidden behind fixed/sticky bars -- [ ] Verified on small phone, large phone, and tablet (portrait + landscape) -- [ ] 4/8dp spacing rhythm maintained -- [ ] Long-form text measure readable on larger devices - -### Accessibility -- [ ] All meaningful images/icons have accessibility labels -- [ ] Form fields have labels, hints, and clear error messages -- [ ] Color is not the only indicator -- [ ] Reduced motion and dynamic text size supported -- [ ] Accessibility traits/roles/states announced correctly diff --git a/templates/WORKFLOW.md b/templates/WORKFLOW.md deleted file mode 100644 index 383b570b..00000000 --- a/templates/WORKFLOW.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -# WORKFLOW.md — Symphony/Elixir-style repo workflow contract (template). -# Copy to the repo root of an orchestrated repo. Frontmatter configures the -# orchestrator (Jimek running Symphony-style, or Symphony itself); the markdown -# body becomes the agent's session prompt. -# -# Compatible with the standard regime (qute-code-kit ADR-0001..0004): -# Linear is the task source; the body routes agents through docs/agents/, -# Matt-style skills for the engineering flow, and qute runtime skills. -tracker: - kind: linear - provider: - project_slug: "CHANGEME" # scopes candidate issues - api_key: $LINEAR_API_KEY # held HOST-SIDE; stripped from agent env - # assignee: "me" # optional routing match - # required_labels: [agent] # optional label gate -workspace: - root: ~/code/workspaces -hooks: - after_create: | - git clone git@github.com:CHANGEME/CHANGEME.git . -agent: - max_concurrent_agents: 4 - max_turns: 20 ---- - -You are working on issue {{ issue.identifier }}: {{ issue.title }}. - -Before any material work, read the repo's operating contract: - -- `docs/agents/issue-tracker.md` — tracker binding. Linear is the task source; your - Linear state changes and comments go through the orchestrator's `linear` tool - (the API key is not in your environment — do not look for it). GitHub Issues are an - issue record, not a queue. -- `docs/agents/research-workflow.md` — if present, this is a research repo: results are - written only via `/finding` (verdict-forced); no analysis outside a registered line. -- `CONTEXT.md` — domain glossary. `docs/adr/` — decisions; never contradict an accepted - ADR silently, supersede it via `/decision`. - -Engineering flow — use the installed Matt-style skills when the work is non-trivial: -`/grill-with-docs` if the issue is underspecified (post questions to the issue and block), -`/to-spec` for material changes, `/implement` + `/tdd` for the build, `/code-review` -before finishing. - -Runtime — qute-essentials is active underneath: guards stay on; run `/test` and `/audit` -before declaring done; record durable decisions with `/decision`; `/qute-review` before -any merge-facing handoff. Open PRs per the repo's PR policy; reference -`{{ issue.identifier }}` in the PR body. - -Definition of done: acceptance criteria on the issue are met, tests pass, review verdict -posted, the issue is moved to its terminal state with a closing comment linking the PR. -If blocked, say exactly what you need on the issue and stop — do not improvise around -missing approvals. diff --git a/templates/docs/prd-template.md b/templates/docs/prd-template.md deleted file mode 100644 index 97c81bdb..00000000 --- a/templates/docs/prd-template.md +++ /dev/null @@ -1,59 +0,0 @@ -# {Project Name} — Product Requirements Document - -## Problem - -What problem does this solve? Who has this problem? How do they solve it today? - -## Solution - -What are we building? One-paragraph overview + flow diagram. - -``` -Input → Process → Output -``` - -## Users - -### {Primary user} -Who are they? What's their daily workflow? What do they care about? - -### {Secondary user} (Phase N) -Who are they? Why are they secondary? - -## Key Decisions - -### {Decision 1: e.g., "Data model approach"} -What we decided and why. What alternatives we rejected. - -### {Decision 2} -... - -## Integrations - -What external systems does this connect to? What are the constraints? - -| Integration | Priority | Auth method | Notes | -|-------------|----------|-------------|-------| - -## Phase Plan - -### Phase 1: MVP -- Scope -- Users included -- Success criteria - -### Phase 2: {name} -- What it adds -- Why it's Phase 2 - -## Market Position (optional) - -Where does this fit? What's the differentiator? What do we intentionally not do? - -## Risks - -1. **{Risk}** — {mitigation} - -## Open Questions - -- {Question that still needs answering} diff --git a/templates/docs/tech-spec-template.md b/templates/docs/tech-spec-template.md deleted file mode 100644 index de63ccfb..00000000 --- a/templates/docs/tech-spec-template.md +++ /dev/null @@ -1,44 +0,0 @@ -# {Project Name} — Technical Spec - -## Stack - -| Layer | Choice | Why | -|-------|--------|-----| -| Backend | | | -| Database | | | -| Frontend | | | -| Auth | | | -| Deployment | | | - -## Project Structure - -``` -project/ -├── ... -``` - -## Data Model - -(ERD diagram, key entities, relationships) - -## API Design - -| Method | Path | Purpose | -|--------|------|---------| -| | | | - -## Services / Business Logic - -| Service | Purpose | Key methods | -|---------|---------|-------------| -| | | | - -## Implementation Order - -1. **{First thing to build}** — why first -2. **{Second}** — depends on #1 -3. ... - -## Open Questions - -- {Technical question that needs answering} diff --git a/templates/docs/user-flows-template.md b/templates/docs/user-flows-template.md deleted file mode 100644 index 7bd129fe..00000000 --- a/templates/docs/user-flows-template.md +++ /dev/null @@ -1,33 +0,0 @@ -# User Flows - -## Flow 1: {Name} - -**Actor:** {who} -**Precondition:** {what must be true before} - -1. {Step} -2. {Step} -3. **Path A ({condition}):** {steps} -4. **Path B ({condition}):** {steps} -5. {Step} - -**Result:** {what's true after} - ---- - -## Flow 2: {Name} - -**Actor:** {who} -**Time:** {how long this takes, if relevant} - -1. {Step} -2. {Step} - ---- - -## Flow N: {Name} (Phase {X}) - -**Actor:** {who} -**Note:** This flow is planned for Phase {X}. - -1. {Step}