Download scripts/refresh.mjs from iizy/calcfi-open-data: direct link, hf CLI and curl.
- Browser
- Download file 8.06 kB
-
https://huggingface.co/datasets/iizy/calcfi-open-data/resolve/main/scripts/refresh.mjs
- Command line
-
hf download hf://datasets/iizy/calcfi-open-data/scripts/refresh.mjs
-
curl -L -o refresh.mjs https://huggingface.co/datasets/iizy/calcfi-open-data/resolve/main/scripts/refresh.mjs
8.06 kB
| // CalcFi Open Data — refresh script | |
| // Pulls every series from calcfi.app/api/llms/rates manifest, fetches | |
| // per-series history, writes CSV + datapackage.json + README per subdir. | |
| // Idempotent. Safe to run on cron. | |
| import { writeFile, mkdir, readFile } from 'node:fs/promises' | |
| import { existsSync } from 'node:fs' | |
| import { dirname, join } from 'node:path' | |
| import { fileURLToPath } from 'node:url' | |
| const __dirname = dirname(fileURLToPath(import.meta.url)) | |
| const ROOT = join(__dirname, '..') | |
| const DATASETS = join(ROOT, 'datasets') | |
| const MANIFEST_URL = 'https://calcfi.app/api/llms/rates' | |
| const HISTORY_CSV = (slug) => `https://calcfi.app/api/data/${slug}/history.csv` | |
| const SCHEMA_FOR_UNIT = { | |
| percent: { type: 'number', description: 'Value as a percent (e.g. 6.36 means 6.36%).' }, | |
| index: { type: 'number', description: 'Index value (base period varies; see source).' }, | |
| usd: { type: 'number', description: 'Value in US dollars.' }, | |
| usd_per_barrel: { type: 'number', description: 'US dollars per barrel.' }, | |
| usd_per_gallon: { type: 'number', description: 'US dollars per gallon.' }, | |
| ratio: { type: 'number', description: 'Exchange rate (units of currency A per 1 unit of currency B).' }, | |
| } | |
| const PROVIDER_NAME = { | |
| fred: 'Federal Reserve Economic Data (FRED)', | |
| fdic: 'Federal Deposit Insurance Corporation (FDIC)', | |
| coingecko: 'CoinGecko', | |
| worldbank: 'World Bank', | |
| bls: 'Bureau of Labor Statistics (BLS)', | |
| bea: 'Bureau of Economic Analysis (BEA)', | |
| eia: 'Energy Information Administration (EIA)', | |
| treasury: 'US Treasury', | |
| } | |
| async function fetchJson(url) { | |
| const res = await fetch(url, { headers: { 'User-Agent': 'calcfi-open-data/1.0 (+https://calcfi.app/developers)' } }) | |
| if (!res.ok) throw new Error(`${res.status} ${url}`) | |
| return res.json() | |
| } | |
| async function fetchText(url) { | |
| const res = await fetch(url, { headers: { 'User-Agent': 'calcfi-open-data/1.0 (+https://calcfi.app/developers)' } }) | |
| if (!res.ok) throw new Error(`${res.status} ${url}`) | |
| return res.text() | |
| } | |
| function csvEscape(v) { | |
| if (v == null) return '' | |
| const s = String(v) | |
| return /[",\n]/.test(s) ? `"${s.replaceAll('"', '""')}"` : s | |
| } | |
| function buildCsv(rows, columns) { | |
| const lines = [columns.join(',')] | |
| for (const r of rows) lines.push(columns.map((c) => csvEscape(r[c])).join(',')) | |
| return lines.join('\n') + '\n' | |
| } | |
| function buildDatapackage(rate, columns, schemaCols, today) { | |
| const provider = PROVIDER_NAME[rate.source.provider] || rate.source.provider | |
| return { | |
| name: rate.slug, | |
| title: rate.name, | |
| description: `${rate.name}. Source: ${rate.source.name}. Live current value at https://calcfi.app/rates/history/${rate.slug}. Cadence: ${rate.cadence}. Unit: ${rate.unit}.`, | |
| homepage: `https://calcfi.app/rates/history/${rate.slug}`, | |
| licenses: [ | |
| { | |
| name: 'CC-BY-4.0', | |
| path: 'https://creativecommons.org/licenses/by/4.0/', | |
| title: 'Creative Commons Attribution 4.0 International', | |
| }, | |
| ], | |
| keywords: ['finance', 'calcfi', rate.category, rate.source.provider, rate.unit].filter(Boolean), | |
| sources: [ | |
| { title: provider, path: rate.source.url || `https://fred.stlouisfed.org/series/${rate.source.series_id}` }, | |
| { title: 'CalcFi live page', path: `https://calcfi.app/rates/history/${rate.slug}` }, | |
| ], | |
| resources: [ | |
| { | |
| name: 'data', | |
| path: 'data.csv', | |
| format: 'csv', | |
| mediatype: 'text/csv', | |
| encoding: 'utf-8', | |
| schema: { fields: schemaCols }, | |
| }, | |
| ], | |
| version: today, | |
| } | |
| } | |
| function buildReadme(rate) { | |
| const provider = PROVIDER_NAME[rate.source.provider] || rate.source.provider | |
| return `# ${rate.name} | |
| ${rate.cadence === 'daily' ? 'Daily' : rate.cadence === 'weekly' ? 'Weekly' : rate.cadence === 'monthly' ? 'Monthly' : rate.cadence === 'quarterly' ? 'Quarterly' : 'Periodic'} observations of **${rate.name}** (${rate.short_name}). | |
| ## At a glance | |
| | Field | Value | | |
| |---|---| | |
| | Slug | \`${rate.slug}\` | | |
| | Category | ${rate.category} | | |
| | Unit | ${rate.unit} | | |
| | Cadence | ${rate.cadence} | | |
| | Source | [${rate.source.name}](${rate.source.url}) | | |
| | Source series ID | \`${rate.source.series_id}\` | | |
| | License | [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) | | |
| ## Live data on CalcFi | |
| - **Latest value + chart:** https://calcfi.app/rates/history/${rate.slug} | |
| - **JSON API (no auth):** https://calcfi.app/api/rates/${rate.slug} | |
| - **CSV (this file, daily-refreshed via cron):** [data.csv](data.csv) | |
| ## Quick start | |
| \`\`\`bash | |
| # Latest single value from the API | |
| curl https://calcfi.app/api/rates/${rate.slug} | |
| # Full history from this repo | |
| curl https://raw.githubusercontent.com/jerehere/calcfi-open-data/main/datasets/${rate.slug}/data.csv | |
| \`\`\` | |
| \`\`\`python | |
| import pandas as pd | |
| url = "https://raw.githubusercontent.com/jerehere/calcfi-open-data/main/datasets/${rate.slug}/data.csv" | |
| df = pd.read_csv(url, parse_dates=["date"]) | |
| print(df.tail()) | |
| \`\`\` | |
| ## Source + provenance | |
| This dataset mirrors **${rate.source.name}** (\`${rate.source.series_id}\`). | |
| Primary source: ${provider}. | |
| Values are pulled daily by a GitHub Actions workflow (\`.github/workflows/refresh.yml\`) from CalcFi's read-only data API, which itself pulls from primary sources. No transformations or imputations are applied; values are passed through verbatim. | |
| ## Citation | |
| If you use this dataset, please cite: | |
| > CalcFi (${new Date().getFullYear()}). ${rate.name} dataset. https://calcfi.app/rates/history/${rate.slug} | |
| ## License | |
| CC BY 4.0 — attribution requested. The data itself is sourced from ${provider}; consult their terms for any additional restrictions. | |
| ` | |
| } | |
| async function processRate(rate) { | |
| const slug = rate.slug | |
| const dir = join(DATASETS, slug) | |
| await mkdir(dir, { recursive: true }) | |
| const schemaCols = [ | |
| { name: 'date', type: 'date', format: '%Y-%m-%d', description: 'Observation date (YYYY-MM-DD).' }, | |
| { name: 'value', ...(SCHEMA_FOR_UNIT[rate.unit] || { type: 'number', description: 'Observed value.' }) }, | |
| { name: 'unit', type: 'string', description: 'Unit of observation (matches manifest).' }, | |
| ] | |
| let rowCount = 0 | |
| try { | |
| const csv = await fetchText(HISTORY_CSV(slug)) | |
| await writeFile(join(dir, 'data.csv'), csv) | |
| rowCount = csv.split('\n').filter((l) => l && !l.startsWith('#') && !l.startsWith('date,')).length | |
| } catch (e) { | |
| console.warn(` [WARN] ${slug}: history.csv unavailable (${e.message}); writing manifest-only snapshot`) | |
| if (rate.value != null && rate.observation_date) { | |
| const csv = `# ${rate.name}\n# Source: ${rate.source.name}\n# Snapshot from manifest only — history endpoint unavailable\ndate,value,unit\n${rate.observation_date},${rate.value},${rate.unit}\n` | |
| await writeFile(join(dir, 'data.csv'), csv) | |
| rowCount = 1 | |
| } else { | |
| await writeFile(join(dir, 'data.csv'), `date,value,unit\n`) | |
| } | |
| } | |
| const today = new Date().toISOString().slice(0, 10) | |
| await writeFile(join(dir, 'datapackage.json'), JSON.stringify(buildDatapackage(rate, ['date', 'value', 'unit'], schemaCols, today), null, 2) + '\n') | |
| await writeFile(join(dir, 'README.md'), buildReadme(rate)) | |
| console.log(` [OK] ${slug.padEnd(32)} ${rowCount} rows`) | |
| return { slug, rows: rowCount } | |
| } | |
| async function main() { | |
| console.log(`Fetching manifest: ${MANIFEST_URL}`) | |
| const manifest = await fetchJson(MANIFEST_URL) | |
| console.log(` ${manifest.count} series in manifest\n`) | |
| const summary = [] | |
| for (const rate of manifest.rates) { | |
| try { | |
| const res = await processRate(rate) | |
| summary.push(res) | |
| } catch (e) { | |
| console.error(` [FAIL] ${rate.slug}: ${e.message}`) | |
| summary.push({ slug: rate.slug, rows: 0, error: e.message }) | |
| } | |
| } | |
| const indexPath = join(ROOT, 'datasets', 'INDEX.json') | |
| await writeFile(indexPath, JSON.stringify({ generated_at: new Date().toISOString(), datasets: summary }, null, 2) + '\n') | |
| console.log(`\nWrote ${summary.length} datasets. Index: datasets/INDEX.json`) | |
| } | |
| main().catch((e) => { | |
| console.error(e) | |
| process.exit(1) | |
| }) | |