yahoo-finance2
Version:
JS API for Yahoo Finance
189 lines (188 loc) • 7.05 kB
JavaScript
/**
* Quote module for retrieving real-time or near real-time quote data.
*
* This module provides essential symbol information including current prices,
* market state, volume, and other key metrics for stocks, ETFs, options,
* cryptocurrencies, and other financial instruments.
*
* @example Basic Usage
* ```typescript
* import YahooFinance from "yahoo-finance2";
* const yahooFinance = new YahooFinance();
*
* // Single symbol
* const result = await yahooFinance.quote('AAPL');
* console.log(result.regularMarketPrice, result.currency);
*
* // Multiple symbols
* const results = await yahooFinance.quote(['AAPL', 'GOOGL', 'TSLA']);
*
* // With options - return as object for easier access
* const quotes = await yahooFinance.quote(['AAPL', 'GOOGL'], {
* return: "object"
* });
* console.log(quotes.AAPL.regularMarketPrice);
*
* // Only return specific fields
* const minimal = await yahooFinance.quote('TSLA', {
* fields: ['symbol', 'regularMarketPrice', 'currency']
* });
* ```
*
* @example Options Trading
* ```typescript
* // Get option quote
* const optionResult = await yahooFinance.quote("AAPL220121C00025000");
* console.log(optionResult.strike, optionResult.expireDate);
* ```
*
* @remarks
* **Important Notes:**
* - Some fields like `earningsTimestamp` can be inaccurate (±2 days)
* - Delisted symbols with `quoteType: "NONE"` are filtered out
* - Some fields may only appear during certain market hours
* - Essential fields like `language`, `quoteType` are always returned
*
* @module quote
*/
import { getTypedDefinitions } from "../lib/validate/index.js";
// @yf-schema: see the docs on how this file is automatically updated.
import schema from "./quote.schema.js";
const definitions = getTypedDefinitions(schema);
const queryOptionsDefaults = {};
/**
* Get real-time or near real-time quote data for financial instruments.
*
* This function retrieves essential symbol information including current prices,
* market state, volume, and other key metrics. It supports stocks, ETFs, options,
* cryptocurrencies, mutual funds, and other financial instruments.
*
* @example Single Symbol
* ```typescript
* import YahooFinance from "yahoo-finance2";
* const yahooFinance = new YahooFinance();
*
* const quote = await yahooFinance.quote('AAPL');
* console.log(`${quote.symbol}: $${quote.regularMarketPrice} ${quote.currency}`);
* ```
*
* @example Multiple Symbols
* ```typescript
* // Returns array by default
* const quotes = await yahooFinance.quote(['AAPL', 'GOOGL', 'TSLA']);
* quotes.forEach(q => console.log(`${q.symbol}: $${q.regularMarketPrice}`));
*
* // Or return as object for easier access
* const quoteObj = await yahooFinance.quote(['AAPL', 'GOOGL'], {
* return: "object"
* });
* console.log(quoteObj.AAPL.regularMarketPrice);
* ```
*
* @example Specific Fields Only
* ```typescript
* const minimal = await yahooFinance.quote('TSLA', {
* fields: ['symbol', 'regularMarketPrice', 'currency', 'marketState']
* });
* ```
*
* @example Options Contract
* ```typescript
* const option = await yahooFinance.quote("AAPL220121C00025000");
* console.log(`Strike: $${option.strike}, Expires: ${option.expireIsoDate}`);
* ```
*
* @param query - Symbol or array of symbols to get quotes for.
* Use search() to find symbols if needed.
* @param queryOptionsOverrides - Optional configuration:
* - `fields`: Only return specific fields
* - `return`: Format as "array", "object", or "map"
* @param moduleOptions - Optional module configuration (validateResult, etc.)
*
* @returns Promise that resolves to:
* - Single Quote object (for string input)
* - Quote array (for array input with default options)
* - Quote object/Map (for array input with return option)
*
* @throws Will throw an error if:
* - Network request fails
* - Invalid symbol format
* - Validation fails (if enabled)
*
* @remarks
* **Important Notes:**
* - Missing symbols are skipped in results (no undefined entries)
* - Delisted symbols (`quoteType: "NONE"`) are filtered out
* - Some fields like earnings dates may be inaccurate (±2 days)
* - Essential fields (`language`, `quoteType`, etc.) are always returned
* - Some fields only appear during certain market hours
*
* @see {@link QuoteOptions} for all available options
* @see {@link Quote} for all possible return fields
*/
export default async function quote(query, queryOptionsOverrides, moduleOptions) {
const symbols = typeof query === "string" ? query : query.join(",");
const returnAs = queryOptionsOverrides && queryOptionsOverrides.return;
const results = await this._moduleExec({
moduleName: "quote",
query: {
url: "https://${YF_QUERY_HOST}/v7/finance/quote",
needsCrumb: true,
definitions,
schemaKey: "#/definitions/QuoteOptions",
defaults: queryOptionsDefaults,
runtime: { symbols },
overrides: queryOptionsOverrides,
transformWith(queryOptions) {
// Options validation ensures this is a string[]
if (queryOptions.fields)
queryOptions.fields.join(",");
// Don't pass this on to Yahoo
delete queryOptions.return;
return queryOptions;
},
},
result: {
definitions,
schemaKey: "#/definitions/QuoteResponseArray",
// deno-lint-ignore no-explicit-any
transformWith(rawResult) {
let results = rawResult?.quoteResponse?.result;
if (!results || !Array.isArray(results)) {
throw new Error("Unexpected result: " + JSON.stringify(rawResult));
}
// Filter out quoteType==='NONE'
// So that delisted stocks will be undefined just like symbol-not-found
// deno-lint-ignore no-explicit-any
results = results.filter((quote) => quote?.quoteType !== "NONE");
return results;
},
},
moduleOptions,
});
if (returnAs) {
switch (returnAs) {
case "array":
return results;
case "object": {
// deno-lint-ignore no-explicit-any
const object = {};
for (const result of results)
object[result.symbol] = result;
return object; // TODO: type
}
case "map": {
const map = new Map();
for (const result of results)
map.set(result.symbol, result);
return map; // TODO: type
}
}
}
else {
// By default, match the query input shape (string or string[]).
return typeof query === "string"
? results[0]
: results;
}
}