File size: 8,057 Bytes
cb928fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env node
// 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)
})