yahoo-finance
| Kind | kit |
|---|---|
| Capabilities | net |
| Categories | finance web data |
| Keywords | finance stocks yahoo market-data trading api |
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
| File | Description |
|---|---|
.editorconfig | Editor formatting configuration |
.gitignore | Git ignore rules for build artifacts and dependencies |
.tool-versions | asdf tool versions (Zig, Kit) |
examples/basic-quote.kit | Example: basic quote |
examples/dataframe-integration.kit | Example: dataframe integration |
examples/dividends-splits.kit | Example: dividends splits |
examples/fundamentals.kit | Example: fundamentals |
examples/historical-chart.kit | Example: historical chart |
examples/options-chain.kit | Example: options chain |
examples/plot-integration.kit | Example: plot integration |
examples/search-symbols.kit | Example: search symbols |
examples/ta-lib-integration.kit | Example: TA-Lib integration |
kit.toml | Package manifest with metadata and dependencies |
README.md | This file |
src/errors.kit | Yahoo Finance Error Types |
src/tickers.kit | Well-Known Ticker Symbols |
src/types.kit | Yahoo Finance Types |
src/yahoo-finance.kit | Yahoo Finance API Client for Kit |
tests/errors.test.kit | Tests for errors |
tests/tickers.test.kit | Tests for tickers |
tests/types.test.kit | Tests for types |
Installation
kit add yahoo-financeQuick 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] YahooFinanceErrorHistorical 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] YahooFinanceErrorRange values: Day1, Day5, Month1, Month3, Month6, Year1, Year2, Year5, Year10, YTD, Max
Interval values: Minute1, Minute5, Minute15, Minute30, Hour1, Day1, Week1, Month1
Search
# 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] YahooFinanceErrorFundamentals
# 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] YahooFinanceErrorAnalyst 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] YahooFinanceErrorDividends & 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] YahooFinanceErrorOptions
# Full option chain (calls and puts)
get-options: String -> Result OptionChain YahooFinanceErrorIndex Ticker Constants
sp500-ticker # "^GSPC" - S&P 500
dow30-ticker # "^DJI" - Dow Jones Industrial Average
nasdaq-ticker # "^IXIC" - Nasdaq Composite
russell2000-ticker # "^RUT" - Russell 2000Types
| Type | Fields |
|---|---|
Quote | symbol, name, price, change, change-percent, volume, market-cap (Option), timestamp |
Bar | timestamp, open, high, low, close, volume, adj-close (Option) |
Range | Day1, Day5, Month1, Month3, Month6, Year1, Year2, Year5, Year10, YTD, Max |
Interval | Minute1, Minute5, Minute15, Minute30, Hour1, Day1, Week1, Month1 |
SearchResult | symbol, name, exchange, asset-type |
StatementPeriod | Annual, Quarterly |
IncomeStatement | end-date, total-revenue, cost-of-revenue, gross-profit, operating-income, net-income, ebitda |
BalanceSheet | end-date, total-assets, total-liabilities, total-equity, cash, total-debt |
CashFlowStatement | end-date, operating-cash-flow, investing-cash-flow, financing-cash-flow, free-cash-flow, capital-expenditures |
Recommendation | period, strong-buy, buy, hold, sell, strong-sell |
RatingChange | date, firm, to-grade, from-grade, action |
Dividend | date, amount |
Split | date, numerator, denominator |
OptionContract | contract-symbol, strike, expiration, last-price, bid, ask, volume, open-interest, implied-volatility, in-the-money |
OptionChain | symbol, 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:
| Variant | Description |
|---|---|
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 quoteshistorical-chart.kit- OHLCV data with basic statisticsfundamentals.kit- Income statements, balance sheets, cash flowoptions-chain.kit- Options data with ITM/OTM analysissearch-symbols.kit- Symbol search and trending tickersdividends-splits.kit- Dividend and split history
Integration Examples
ta-lib-integration.kit- Fetch history, compute SMA/EMA/RSI/Bollinger Bands (requireskit-ta-lib)dataframe-integration.kit- Load quotes into DataFrame for sorting/filtering (requireskit-dataframe)plot-integration.kit- Candlestick chart from historical data (requireskit-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-etfs
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
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
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
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
QuoteBar
OHLCV bar data from historical chart endpoint.
Variants
BarRange
Time range for historical data queries.
Variants
RangeInterval
Interval for historical data granularity.
Variants
IntervalSearchResult
Search result from symbol search endpoint.
Variants
SearchResultStatementPeriod
Financial statement period (Annual or Quarterly).
Variants
StatementPeriodIncomeStatement
Income statement data from quoteSummary.
Variants
IncomeStatementBalanceSheet
Balance sheet data from quoteSummary.
Variants
BalanceSheetCashFlowStatement
Cash flow statement data from quoteSummary.
Variants
CashFlowStatementRecommendation
Analyst recommendation summary for a period.
Variants
RecommendationRatingChange
Analyst rating change (upgrade/downgrade).
Variants
RatingChangeDividend
Dividend event from the chart API.
Variants
DividendSplit
Stock split event from the chart API.
Variants
SplitOptionContract
Option contract data.
Variants
OptionContractOptionChain
Option chain for a symbol (calls and puts).
Variants
OptionChainYahooFinanceError
Yahoo Finance error types.
Variants
YahooFinanceErrorsp500-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 Day1Variants
Day1Day5Month1Month3Month6Year1Year2Year5Year10YTDMaxInterval
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
Minute1Minute5Minute15Minute30Hour1Day1Week1Month1SearchResult
Search result from the /v1/finance/search endpoint.
Variants
SearchResult {symbol, name, exchange, asset-type}StatementPeriod
Financial statement period
Variants
AnnualQuarterlyIncomeStatement
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