yahoo-finance

Yahoo Finance API client for Kit - stock quotes, historical data, and fundamentals

Uses Kit's built-in HTTP and JSON capabilities with no external dependencies. Includes browser-like headers and retry logic to handle Yahoo Finance's rate limiting.

Files

FileDescription
.editorconfigEditor formatting configuration
.gitignoreGit ignore rules for build artifacts and dependencies
.tool-versionsasdf tool versions (Zig, Kit)
examples/basic-quote.kitExample: basic quote
examples/dataframe-integration.kitExample: dataframe integration
examples/dividends-splits.kitExample: dividends splits
examples/fundamentals.kitExample: fundamentals
examples/historical-chart.kitExample: historical chart
examples/options-chain.kitExample: options chain
examples/plot-integration.kitExample: plot integration
examples/search-symbols.kitExample: search symbols
examples/ta-lib-integration.kitExample: TA-Lib integration
kit.tomlPackage manifest with metadata and dependencies
README.mdThis file
src/errors.kitYahoo Finance Error Types
src/tickers.kitWell-Known Ticker Symbols
src/types.kitYahoo Finance Types
src/yahoo-finance.kitYahoo Finance API Client for Kit
tests/errors.test.kitTests for errors
tests/tickers.test.kitTests for tickers
tests/types.test.kitTests for types

Installation

kit add yahoo-finance

Quick Start

import Kit.YahooFinance as YahooFinance

main = fn =>
  match YahooFinance.get-quote "AAPL"
    | Ok quote ->
        println "${quote.symbol}: $${Float.to-string quote.price}"
        println "Change: ${Float.to-string quote.change-percent}%"
    | Err e -> println "Error: ${show e}"

API Reference

Quotes

# Single quote
get-quote: String -> Result Quote YahooFinanceError

# Multiple quotes in one request
get-quotes: [String] -> Result [Quote] YahooFinanceError

Historical Data

# OHLCV bars with range and interval
get-history: String -> Range -> Interval -> Result [Bar] YahooFinanceError

# OHLCV bars with explicit Unix timestamp range
get-history-range: String -> Int -> Int -> Interval -> Result [Bar] YahooFinanceError

Range values: Day1, Day5, Month1, Month3, Month6, Year1, Year2, Year5, Year10, YTD, Max

Interval values: Minute1, Minute5, Minute15, Minute30, Hour1, Day1, Week1, Month1

# Search symbols by name or ticker
search: String -> Result [SearchResult] YahooFinanceError

# Get trending tickers for a region (e.g., "US", "GB")
get-trending: String -> Result [String] YahooFinanceError

Fundamentals

# Income statements (Annual or Quarterly)
get-income-statements: String -> StatementPeriod -> Result [IncomeStatement] YahooFinanceError

# Balance sheets
get-balance-sheets: String -> StatementPeriod -> Result [BalanceSheet] YahooFinanceError

# Cash flow statements
get-cash-flow: String -> StatementPeriod -> Result [CashFlowStatement] YahooFinanceError

Analyst Data

# Analyst recommendation summaries (buy/hold/sell counts by period)
get-recommendations: String -> Result [Recommendation] YahooFinanceError

# Analyst rating changes (upgrades/downgrades)
get-rating-changes: String -> Result [RatingChange] YahooFinanceError

Dividends & Splits

# Dividend history for a given range
get-dividends: String -> Range -> Result [Dividend] YahooFinanceError

# Stock split history for a given range
get-splits: String -> Range -> Result [Split] YahooFinanceError

Options

# Full option chain (calls and puts)
get-options: String -> Result OptionChain YahooFinanceError

Index Ticker Constants

sp500-ticker     # "^GSPC" - S&P 500
dow30-ticker     # "^DJI"  - Dow Jones Industrial Average
nasdaq-ticker    # "^IXIC" - Nasdaq Composite
russell2000-ticker  # "^RUT"  - Russell 2000

Types

TypeFields
Quotesymbol, name, price, change, change-percent, volume, market-cap (Option), timestamp
Bartimestamp, open, high, low, close, volume, adj-close (Option)
RangeDay1, Day5, Month1, Month3, Month6, Year1, Year2, Year5, Year10, YTD, Max
IntervalMinute1, Minute5, Minute15, Minute30, Hour1, Day1, Week1, Month1
SearchResultsymbol, name, exchange, asset-type
StatementPeriodAnnual, Quarterly
IncomeStatementend-date, total-revenue, cost-of-revenue, gross-profit, operating-income, net-income, ebitda
BalanceSheetend-date, total-assets, total-liabilities, total-equity, cash, total-debt
CashFlowStatementend-date, operating-cash-flow, investing-cash-flow, financing-cash-flow, free-cash-flow, capital-expenditures
Recommendationperiod, strong-buy, buy, hold, sell, strong-sell
RatingChangedate, firm, to-grade, from-grade, action
Dividenddate, amount
Splitdate, numerator, denominator
OptionContractcontract-symbol, strike, expiration, last-price, bid, ask, volume, open-interest, implied-volatility, in-the-money
OptionChainsymbol, expiration-dates, calls, puts

Fundamentals fields (revenue, assets, etc.) are Option Float since Yahoo may not return all fields.

Error Handling

All functions return Result T YahooFinanceError. Error variants:

VariantDescription
NetworkError {message}HTTP request failed
ParseError {message}JSON parsing failed
RateLimitError {message}Too many requests (HTTP 429)
NotFoundError {symbol}Symbol not found
InvalidSymbolError {symbol}Invalid ticker format
ApiError {code, description}Error returned by Yahoo Finance API
NoDataError {symbol}No data available for symbol/range

Pattern match on specific error types for fine-grained handling:

import Kit.YahooFinance as YahooFinance

match YahooFinance.get-quote "INVALID"
  | Ok quote -> use-quote quote
  | Err (NotFoundError {symbol}) -> println "Unknown symbol: ${symbol}"
  | Err (NetworkError {message}) -> println "Network issue: ${message}"
  | Err e -> println "Error: ${show e}"

Examples

See the examples/ directory:

  • basic-quote.kit - Single and batch quote lookups, index quotes
  • historical-chart.kit - OHLCV data with basic statistics
  • fundamentals.kit - Income statements, balance sheets, cash flow
  • options-chain.kit - Options data with ITM/OTM analysis
  • search-symbols.kit - Symbol search and trending tickers
  • dividends-splits.kit - Dividend and split history

Integration Examples

  • ta-lib-integration.kit - Fetch history, compute SMA/EMA/RSI/Bollinger Bands (requires kit-ta-lib)
  • dataframe-integration.kit - Load quotes into DataFrame for sorting/filtering (requires kit-dataframe)
  • plot-integration.kit - Candlestick chart from historical data (requires kit-plot)

Notes

  • Yahoo Finance does not offer an official public API. These endpoints are unofficial and may change.
  • Real-time data may be delayed 15-20 minutes.
  • The package includes browser-like User-Agent headers (required by Yahoo to avoid blocking).
  • Retry logic (3 retries with exponential backoff) is built in.
  • Intraday intervals (Minute1-Hour1) are only available for recent data (7-60 days).
  • Data is for personal and educational use. Commercial use may require licensing from Yahoo.
  • Respect rate limits to avoid IP blocks.

Exported Functions & Types

apple

Apple Inc.

microsoft

Microsoft Corporation

google

Alphabet Inc. (Google)

amazon

Amazon.com Inc.

meta

Meta Platforms Inc. (Facebook)

nvidia

NVIDIA Corporation

tesla

Tesla Inc.

broadcom

Broadcom Inc.

amd

Advanced Micro Devices Inc.

intel

Intel Corporation

ibm

International Business Machines

oracle

Oracle Corporation

salesforce

Salesforce Inc.

adobe

Adobe Inc.

netflix

Netflix Inc.

cisco

Cisco Systems Inc.

qualcomm

Qualcomm Inc.

uber

Uber Technologies Inc.

palantir

Palantir Technologies Inc.

shopify

Shopify Inc.

snowflake

Snowflake Inc.

jpmorgan

JPMorgan Chase & Co.

goldman-sachs

Goldman Sachs Group Inc.

bank-of-america

Bank of America Corporation

berkshire

Berkshire Hathaway Inc. (Class B)

visa

Visa Inc.

mastercard

Mastercard Inc.

morgan-stanley

Morgan Stanley

amex

American Express Company

unitedhealth

UnitedHealth Group Inc.

johnson-and-johnson

Johnson & Johnson

eli-lilly

Eli Lilly and Company

pfizer

Pfizer Inc.

merck

Merck & Co. Inc.

abbvie

AbbVie Inc.

walmart

Walmart Inc.

coca-cola

The Coca-Cola Company

pepsi

PepsiCo Inc.

mcdonalds

McDonald's Corporation

nike

Nike Inc.

disney

The Walt Disney Company

starbucks

Starbucks Corporation

costco

Costco Wholesale Corporation

home-depot

The Home Depot Inc.

procter-and-gamble

Procter & Gamble Company

exxon

Exxon Mobil Corporation

chevron

Chevron Corporation

att

AT&T Inc.

verizon

Verizon Communications Inc.

comcast

Comcast Corporation

boeing

Boeing Company

lockheed-martin

Lockheed Martin Corporation

caterpillar

Caterpillar Inc.

three-m

3M Company

spy

SPDR S&P 500 ETF Trust

qqq

Invesco QQQ Trust (Nasdaq 100)

dia

SPDR Dow Jones Industrial Average ETF

iwm

iShares Russell 2000 ETF

vti

Vanguard Total Stock Market ETF

voo

Vanguard S&P 500 ETF

arkk

ARK Innovation ETF

eem

iShares MSCI Emerging Markets ETF

bitcoin

Bitcoin (USD)

ethereum

Ethereum (USD)

solana

Solana (USD)

sp500

S&P 500 index

dow

Dow Jones Industrial Average

nasdaq

Nasdaq Composite

russell2000

Russell 2000

vix

CBOE Volatility Index (VIX)

mag7

Magnificent Seven tickers

tech-stocks

Popular technology stock tickers

finance-stocks

Popular finance stock tickers

healthcare-stocks

Popular healthcare stock tickers

consumer-stocks

Popular consumer stock tickers

Popular ETF tickers

lookup

Look up a ticker symbol by company name. Case-insensitive exact match against known company names and aliases.

Parameters:

Returns:

String -> Option String

Tickers.lookup "Apple"      # => Some "AAPL"
Tickers.lookup "facebook"   # => Some "META"
Tickers.lookup "unknown"    # => None

Search for ticker symbols where the company name contains the query. Case-insensitive partial match. Returns all matching (name, symbol) pairs.

Parameters:

Returns:

String -> [(String, String)]

Tickers.search "bank"
# => [("bank of america", "BAC")]

Tickers.search "gold"
# => [("goldman sachs", "GS"), ("goldman", "GS")]

YahooFinanceError

Yahoo Finance error types.

Variants: - NetworkError: HTTP request failed - ParseError: JSON parsing failed - RateLimitError: Too many requests (HTTP 429) - NotFoundError: Symbol not found - InvalidSymbolError: Invalid ticker symbol format - ApiError: Error returned by Yahoo Finance API - NoDataError: No data available for the requested symbol/range

Variants

NetworkError {message}
ParseError {message}
RateLimitError {message}
NotFoundError {symbol}
InvalidSymbolError {symbol}
ApiError {code, description}
NoDataError {symbol}

get-quote

Get a real-time quote for a symbol.

Parameters:

Returns:

String -> Result Quote YahooFinanceError

match YahooFinance.get-quote "AAPL"
  | Ok quote -> println "Price: ${Float.to-string quote.price}"
  | Err e -> println "Error: ${show e}"

get-quotes

Get quotes for multiple symbols.

Parameters:

Returns:

[String] -> Result [Quote] YahooFinanceError

match YahooFinance.get-quotes ["AAPL", "MSFT", "GOOGL"]
  | Ok quotes -> List.each quotes (fn(q) => println q.symbol)
  | Err e -> println "Error: ${show e}"

get-history

Get historical OHLCV data for a symbol.

Parameters:

Returns:

String -> Range -> Interval -> Result [Bar] YahooFinanceError

match YahooFinance.get-history "AAPL" Year1 Day1
  | Ok bars -> println "Got ${Int.to-string (List.length bars)} bars"
  | Err e -> println "Error: ${show e}"

get-history-range

Get historical data with explicit Unix timestamp range.

Parameters:

Returns:

String -> Int -> Int -> Interval -> Result [Bar] YahooFinanceError

start = 1704067200  # 2024-01-01
end = 1735689600    # 2025-01-01
match YahooFinance.get-history-range "AAPL" start end Day1
  | Ok bars -> println "Got ${Int.to-string (List.length bars)} bars"
  | Err e -> println "Error: ${show e}"

Search for symbols by name or ticker.

Parameters:

Returns:

String -> Result [SearchResult] YahooFinanceError

match YahooFinance.search "Apple"
  | Ok results -> List.each results (fn(r) => println "${r.symbol}: ${r.name}")
  | Err e -> println "Error: ${show e}"

Get trending tickers for a region.

Parameters:

Returns:

String -> Result [String] YahooFinanceError

match YahooFinance.get-trending "US"
  | Ok tickers -> List.each tickers println
  | Err e -> println "Error: ${show e}"

get-income-statements

Get income statements for a symbol.

Parameters:

Returns:

String -> StatementPeriod -> Result [IncomeStatement] YahooFinanceError

match YahooFinance.get-income-statements "AAPL" Annual
  | Ok statements -> List.each statements (fn(s) => println "Revenue: ${show s.total-revenue}")
  | Err e -> println "Error: ${show e}"

get-balance-sheets

Get balance sheets for a symbol.

Parameters:

Returns:

String -> StatementPeriod -> Result [BalanceSheet] YahooFinanceError

match YahooFinance.get-balance-sheets "AAPL" Annual
  | Ok sheets -> List.each sheets (fn(s) => println "Assets: ${show s.total-assets}")
  | Err e -> println "Error: ${show e}"

get-cash-flow

Get cash flow statements for a symbol.

Parameters:

Returns:

String -> StatementPeriod -> Result [CashFlowStatement] YahooFinanceError

match YahooFinance.get-cash-flow "AAPL" Annual
  | Ok statements -> List.each statements (fn(s) => println "FCF: ${show s.free-cash-flow}")
  | Err e -> println "Error: ${show e}"

get-recommendations

Get analyst recommendations for a symbol.

Parameters:

Returns:

String -> Result [Recommendation] YahooFinanceError

match YahooFinance.get-recommendations "AAPL"
  | Ok recs -> List.each recs (fn(r) => println "${r.period}: ${Int.to-string r.buy} buy")
  | Err e -> println "Error: ${show e}"

get-rating-changes

Get analyst rating changes (upgrades/downgrades) for a symbol.

Parameters:

Returns:

String -> Result [RatingChange] YahooFinanceError

match YahooFinance.get-rating-changes "AAPL"
  | Ok changes -> List.each changes (fn(c) => println "${c.firm}: ${c.action}")
  | Err e -> println "Error: ${show e}"

get-dividends

Get dividend history for a symbol.

Parameters:

Returns:

String -> Range -> Result [Dividend] YahooFinanceError

match YahooFinance.get-dividends "AAPL" Year5
  | Ok divs -> List.each divs (fn(d) => println "$${Float.to-string d.amount}")
  | Err e -> println "Error: ${show e}"

get-splits

Get stock split history for a symbol.

Parameters:

Returns:

String -> Range -> Result [Split] YahooFinanceError

match YahooFinance.get-splits "AAPL" Max
  | Ok splits -> List.each splits (fn(s) => println "${Int.to-string s.numerator}:${Int.to-string s.denominator}")
  | Err e -> println "Error: ${show e}"

get-options

Get option chain for a symbol.

Parameters:

Returns:

String -> Result OptionChain YahooFinanceError

match YahooFinance.get-options "AAPL"
  | Ok chain -> println "Calls: ${Int.to-string (List.length chain.calls)}"
  | Err e -> println "Error: ${show e}"

Quote

Stock quote data with price, volume, and market cap.

Variants

Quote

Bar

OHLCV bar data from historical chart endpoint.

Variants

Bar

Range

Time range for historical data queries.

Variants

Range

Interval

Interval for historical data granularity.

Variants

Interval

SearchResult

Search result from symbol search endpoint.

Variants

SearchResult

StatementPeriod

Financial statement period (Annual or Quarterly).

Variants

StatementPeriod

IncomeStatement

Income statement data from quoteSummary.

Variants

IncomeStatement

BalanceSheet

Balance sheet data from quoteSummary.

Variants

BalanceSheet

CashFlowStatement

Cash flow statement data from quoteSummary.

Variants

CashFlowStatement

Recommendation

Analyst recommendation summary for a period.

Variants

Recommendation

RatingChange

Analyst rating change (upgrade/downgrade).

Variants

RatingChange

Dividend

Dividend event from the chart API.

Variants

Dividend

Split

Stock split event from the chart API.

Variants

Split

OptionContract

Option contract data.

Variants

OptionContract

OptionChain

Option chain for a symbol (calls and puts).

Variants

OptionChain

YahooFinanceError

Yahoo Finance error types.

Variants

YahooFinanceError

sp500-ticker

S&P 500 index ticker.

dow30-ticker

Dow Jones Industrial Average ticker.

nasdaq-ticker

Nasdaq Composite ticker.

russell2000-ticker

Russell 2000 ticker.

Tickers

Well-known ticker symbols and company name lookup. Access individual tickers (e.g., Tickers.apple, Tickers.nvidia) or use Tickers.lookup for name-to-symbol resolution.

Quote

Stock quote data from the /v7/finance/quote endpoint.

match YahooFinance.get-quote "AAPL"
  | Ok quote -> println "Price: ${Float.to-string quote.price}"
  | Err e -> println "Error: ${show e}"

Variants

Quote {symbol, name, price, change, change-percent, volume, market-cap, timestamp}

Bar

OHLCV bar data from the /v8/finance/chart endpoint.

Fields: - timestamp: Unix timestamp in seconds - open, high, low, close: Price data (may be 0.0 if unavailable) - volume: Trading volume - adj-close: Split/dividend adjusted close price

Variants

Bar {timestamp, open, high, low, close, volume, adj-close}

Range

Time range for historical data queries.

YahooFinance.get-history "AAPL" Year1 Day1

Variants

Day1
Day5
Month1
Month3
Month6
Year1
Year2
Year5
Year10
YTD
Max

Interval

Interval for historical data granularity.

Note: Intraday intervals (Minute1-Hour1) are only available for recent data (typically last 7-60 days depending on interval).

Variants

Minute1
Minute5
Minute15
Minute30
Hour1
Day1
Week1
Month1

SearchResult

Search result from the /v1/finance/search endpoint.

Variants

SearchResult {symbol, name, exchange, asset-type}

StatementPeriod

Financial statement period

Variants

Annual
Quarterly

IncomeStatement

Income statement data from quoteSummary.

Fields: - end-date: End date as Unix timestamp - total-revenue, cost-of-revenue, gross-profit: Revenue metrics - operating-income, net-income, ebitda: Profitability metrics

Variants

IncomeStatement {end-date, total-revenue, cost-of-revenue, gross-profit, operating-income, net-income, ebitda}

BalanceSheet

Balance sheet data from quoteSummary.

Fields: - end-date: End date as Unix timestamp - total-assets, total-liabilities, total-equity: Balance sheet totals - cash: Cash and cash equivalents - total-debt: Total debt outstanding

Variants

BalanceSheet {end-date, total-assets, total-liabilities, total-equity, cash, total-debt}

CashFlowStatement

Cash flow statement data from quoteSummary.

Fields: - end-date: End date as Unix timestamp - operating-cash-flow, investing-cash-flow, financing-cash-flow: Cash flow categories - free-cash-flow: Operating cash flow minus capital expenditures - capital-expenditures: Capital spending

Variants

CashFlowStatement {end-date, operating-cash-flow, investing-cash-flow, financing-cash-flow, free-cash-flow, capital-expenditures}

Recommendation

Analyst recommendation summary for a period.

Variants

Recommendation {period, strong-buy, buy, hold, sell, strong-sell}

RatingChange

Analyst rating change (upgrade/downgrade).

Variants

RatingChange {date, firm, to-grade, from-grade, action}

Dividend

Dividend event from the chart API.

Variants

Dividend {date, amount}

Split

Stock split event from the chart API.

Variants

Split {date, numerator, denominator}

OptionContract

Option contract data.

Variants

OptionContract {contract-symbol, strike, expiration, last-price, bid, ask, volume, open-interest, implied-volatility, in-the-money}

OptionChain

Option chain for a symbol (calls and puts).

Variants

OptionChain {symbol, expiration-dates, calls, puts}

range-to-string

Convert Range to Yahoo Finance query string.

Range -> String

interval-to-string

Convert Interval to Yahoo Finance query string.

Interval -> String

sp500-ticker

S&P 500 index ticker

dow30-ticker

Dow Jones Industrial Average ticker

nasdaq-ticker

Nasdaq Composite ticker

russell2000-ticker

Russell 2000 ticker