安裝與驗證
請使用 Node 22 或更新版本。將 API 金鑰設定在 NARWHAL_API_KEY 環境變數中。SDK 只在伺服器端使用,切勿把金鑰放進瀏覽器程式碼。設定方式請依照快速入門。
// npm install narwhalapi
import { Narwhal } from "narwhalapi";
// Reads NARWHAL_API_KEY from the server environment.
const nw = new Narwhal();取得最新殖利率曲線
請求美國 2 年期與 10 年期的殖利率。回應包含 date、curve_type 與 yields,每筆資料都有 maturity 與 yield_percent。十進位數值會以精確的字串傳回,例如 "4.25"。請參閱殖利率曲線參考文件。
const curve = await nw.economics.yieldCurve("USA", { maturity: ["2y", "10y"] }); console.log(curve.date, curve.curve_type); for (const point of curve.yields) { console.log(point.maturity, point.yield_percent); }讀取每日歷史資料
將 start 與 end 設為你要求的日期範圍。迭代器會以惰性方式逐頁讀取每日歷史資料,每頁最多 1,000 個日期。此範例請求的是德國 10 年期殖利率。
for await (const day of nw.economics.yieldCurveHistoryIter("DEU", { maturity: ["10y"], start: "2026-01-01", end: "2026-03-31", })) { console.log(day.date, day.yields[0]?.yield_percent); }檢查殖利率曲線是否倒掛
以同一條曲線上的 10 年期殖利率減去 2 年期殖利率。差值為負代表倒掛。只有兩個到期期限都存在時才計算。此範例會先把十進位字串轉成數字再計算。
const yieldOf = (maturity: string) => curve.yields.find((point) => point.maturity === maturity)?.yield_percent; const two = yieldOf("2y"); const ten = yieldOf("10y"); if (two && ten) { const spread = Number(ten) - Number(two); console.log(spread.toFixed(2), spread < 0 ? "inverted" : "not inverted"); }常見問題
可以使用哪些國家代碼?
請使用 USA、GBR、DEU、JPN 或 CAN。各國保留自己的來源曲線類型,所以可用的到期期限與衡量方式不同。
十進位數值是字串還是數字?
十進位數值會以精確的字串傳回,例如 "4.25"。十進位輸入值也必須是字串,不接受數字。
可以比較各國相同到期期限的殖利率嗎?
請先確認各國資料來源的殖利率曲線類型與衡量方式。到期期限的標示相同,並不代表曲線可以互換。
發布日期: 。最近審閱日期: 。