UNPKG

yahoo-finance2

Version:
566 lines 21.6 kB
/** * 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 type { ModuleOptionsWithValidateFalse, ModuleOptionsWithValidateTrue, ModuleThis } from "../lib/moduleCommon.js"; import type { DateInMs, TwoNumberRange } from "../lib/commonTypes.js"; /** * Base interface for all quote data containing common fields across all asset types. * * This interface includes essential information that appears for all financial instruments, * including stocks, ETFs, options, cryptocurrencies, etc. */ export interface QuoteBase { [key: string]: any; /** Language code for the quote data, e.g., "en-US" */ language: string; /** Region code, e.g., "US" */ region: string; /** Type of financial instrument: "EQUITY", "ETF", "MUTUALFUND", "CRYPTOCURRENCY", etc. */ quoteType: string; /** Display name for the quote type, e.g., "Equity" (not always present) */ typeDisp?: string; /** Source of the quote data, e.g., "Delayed Quote", "Nasdaq Real Time Price" */ quoteSourceName?: string; /** Whether price alerts can be triggered for this symbol */ triggerable: boolean; /** Currency code, e.g., "USD" */ currency?: string; /** * Price alert confidence level (appears/disappears based on network load) * @see {@link https://github.com/gadicc/yahoo-finance2/issues/445} */ customPriceAlertConfidence?: string; /** Current market state for this symbol */ marketState: "REGULAR" | "CLOSED" | "PRE" | "PREPRE" | "POST" | "POSTPOST"; /** Whether the symbol is currently tradeable */ tradeable: boolean; /** Whether cryptocurrency trading is available for this symbol */ cryptoTradeable?: boolean; /** Corporate actions data (structure TBD) */ corporateActions?: unknown[]; /** Exchange code where the symbol is traded, e.g., "NMS" */ exchange: string; /** Short name/ticker display name, e.g., "NVIDIA Corporation" */ shortName?: string; /** Full company/instrument name, e.g., "NVIDIA Corporation" */ longName?: string; /** Yahoo Finance message board identifier */ messageBoardId?: string; /** Exchange timezone name, e.g., "America/New_York" */ exchangeTimezoneName: string; /** Exchange timezone abbreviation, e.g., "EST", "EDT" */ exchangeTimezoneShortName: string; /** GMT offset in milliseconds */ gmtOffSetMilliseconds: number; /** Market identifier, e.g., "us_market" */ market: string; /** Whether ESG (Environmental, Social, Governance) data is available */ esgPopulated: boolean; /** Change from 52-week low */ fiftyTwoWeekLowChange?: number; /** Percentage change from 52-week low */ fiftyTwoWeekLowChangePercent?: number; /** 52-week trading range with low and high values */ fiftyTwoWeekRange?: TwoNumberRange; /** Change from 52-week high */ fiftyTwoWeekHighChange?: number; /** Percentage change from 52-week high */ fiftyTwoWeekHighChangePercent?: number; /** 52-week low price */ fiftyTwoWeekLow?: number; /** 52-week high price */ fiftyTwoWeekHigh?: number; /** 52-week percentage change */ fiftyTwoWeekChangePercent?: number; /** Date of last dividend payment */ dividendDate?: Date; /** * Earnings announcement timestamp (may be inaccurate ±2 days) * @see {@link https://github.com/gadicc/yahoo-finance2/issues/386} */ earningsTimestamp?: Date; /** * Earnings period start timestamp (may be inaccurate ±2 days) * @see {@link https://github.com/gadicc/yahoo-finance2/issues/386} */ earningsTimestampStart?: Date; /** * Earnings period end timestamp (may be inaccurate ±2 days) * @see {@link https://github.com/gadicc/yahoo-finance2/issues/386} */ earningsTimestampEnd?: Date; /** Earnings call start timestamp */ earningsCallTimestampStart?: Date; /** Earnings call end timestamp */ earningsCallTimestampEnd?: Date; /** Whether earnings date is estimated */ isEarningsDateEstimate?: boolean; /** Trailing 12-month annual dividend rate */ trailingAnnualDividendRate?: number; /** Trailing price-to-earnings ratio */ trailingPE?: number; /** Trailing 12-month dividend yield percentage */ trailingAnnualDividendYield?: number; /** Earnings per share over trailing 12 months */ epsTrailingTwelveMonths?: number; /** Forward-looking earnings per share estimate */ epsForward?: number; /** Current year earnings per share estimate */ epsCurrentYear?: number; /** Price to current year EPS ratio */ priceEpsCurrentYear?: number; /** Number of shares outstanding */ sharesOutstanding?: number; /** Book value per share */ bookValue?: number; /** 50-day moving average price */ fiftyDayAverage?: number; /** Change from 50-day average */ fiftyDayAverageChange?: number; /** Percentage change from 50-day average */ fiftyDayAverageChangePercent?: number; /** 200-day moving average price */ twoHundredDayAverage?: number; /** Change from 200-day average */ twoHundredDayAverageChange?: number; /** Percentage change from 200-day average */ twoHundredDayAverageChangePercent?: number; /** Market capitalization */ marketCap?: number; /** Forward price-to-earnings ratio */ forwardPE?: number; /** Price-to-book ratio */ priceToBook?: number; /** Data source update interval in minutes */ sourceInterval: number; /** Exchange data delay in minutes */ exchangeDataDelayedBy: number; /** First trade date in milliseconds since epoch (converted to Date) */ firstTradeDateMilliseconds?: DateInMs; /** * Price precision hint for display purposes * @remarks Was always present except occasionally missing from BTC-USD */ priceHint?: number; /** After-hours price change percentage */ postMarketChangePercent?: number; /** After-hours market timestamp */ postMarketTime?: Date; /** After-hours market price */ postMarketPrice?: number; /** After-hours price change */ postMarketChange?: number; /** Whether pre/post market data is available */ hasPrePostMarketData?: boolean; /** * Extended hours price change (pre-market or after-hours depending on market state). * This is a unified field that represents the current extended session. */ extendedMarketChange?: number; /** * Extended hours price change percentage (pre-market or after-hours depending on market state). * This is a unified field that represents the current extended session. */ extendedMarketChangePercent?: number; /** * Extended hours price (pre-market or after-hours depending on market state). * This is a unified field that represents the current extended session. */ extendedMarketPrice?: number; /** * Extended hours timestamp (pre-market or after-hours depending on market state). * This is a unified field that represents the current extended session. */ extendedMarketTime?: Date; /** Regular market session price change */ regularMarketChange?: number; /** Regular market session price change percentage */ regularMarketChangePercent?: number; /** Regular market session timestamp */ regularMarketTime?: Date; /** Regular market session current/last price */ regularMarketPrice?: number; /** Regular market session day high */ regularMarketDayHigh?: number; /** Regular market session day range with low and high */ regularMarketDayRange?: TwoNumberRange; /** Regular market session day low */ regularMarketDayLow?: number; /** Regular market session volume */ regularMarketVolume?: number; /** * Day high price, may include extended hours trading. * Separate from regularMarketDayHigh which only covers regular session. */ dayHigh?: number; /** * Day low price, may include extended hours trading. * Separate from regularMarketDayLow which only covers regular session. */ dayLow?: number; /** * Trading volume, may include extended hours trading. * Separate from regularMarketVolume which only covers regular session. */ volume?: number; /** Previous day's closing price */ regularMarketPreviousClose?: number; /** Pre-market price change */ preMarketChange?: number; /** Pre-market price change percentage */ preMarketChangePercent?: number; /** Pre-market timestamp */ preMarketTime?: Date; /** Pre-market price */ preMarketPrice?: number; /** Current bid price */ bid?: number; /** Current ask price */ ask?: number; /** Size of current bid */ bidSize?: number; /** Size of current ask */ askSize?: number; /** Full exchange name, e.g., "NasdaqGS" */ fullExchangeName: string; /** Currency used for financial reporting */ financialCurrency?: string; /** Regular market session opening price */ regularMarketOpen?: number; /** Average daily volume over 3 months */ averageDailyVolume3Month?: number; /** Average daily volume over 10 days */ averageDailyVolume10Day?: number; /** Display name for the symbol, e.g., "NVIDIA" */ displayName?: string; /** Symbol ticker */ symbol: string; /** Underlying symbol (for derivatives like options) */ underlyingSymbol?: string; /** Year-to-date return (primarily for ETFs) */ ytdReturn?: number; /** Trailing 3-month returns */ trailingThreeMonthReturns?: number; /** Trailing 3-month NAV returns */ trailingThreeMonthNavReturns?: number; /** Expected IPO date for upcoming listings */ ipoExpectedDate?: Date; /** New listing date */ newListingDate?: Date; /** Date of name change */ nameChangeDate?: Date; /** Previous name before name change */ prevName?: string; /** Average analyst rating */ averageAnalystRating?: string; /** Page view growth weekly (since 2021-11-11) */ pageViewGrowthWeekly?: number; /** Open interest (for options) */ openInterest?: number; /** Beta coefficient relative to market */ beta?: number; /** * Link to the company logo, hosted on Yahoo's image CDN s.yimg.com. * Identical to `logoUrl`. Must be explicitly requested in `fields`. */ companyLogoUrl?: string; /** * Link to the company logo, hosted on Yahoo's image CDN s.yimg.com. * Identical to `companyLogoUrl`. Must be explicitly requested in `fields`. */ logoUrl?: string; } /** * Cryptocurrency quote data with specific fields for digital assets. */ export interface QuoteCryptoCurrency extends QuoteBase { quoteType: "CRYPTOCURRENCY"; /** Current circulating supply of the cryptocurrency */ circulatingSupply?: number; /** Base currency symbol, e.g., 'BTC' */ fromCurrency?: string; /** Quote currency symbol, e.g., 'USD=X' */ toCurrency?: string; /** Last market data source, e.g., 'CoinMarketCap' */ lastMarket?: string; /** URL to coin image/logo */ coinImageUrl?: string; /** 24-hour trading volume */ volume24Hr?: number; /** Volume across all currencies */ volumeAllCurrencies?: number; /** Start date for this cryptocurrency */ startDate?: Date; /** Link to CoinMarketCap page */ coinMarketCapLink?: string; /** URL to logo image */ logoUrl?: string; } /** * Currency quote data for forex pairs. */ export interface QuoteCurrency extends QuoteBase { quoteType: "CURRENCY"; } /** * ETF (Exchange-Traded Fund) quote data with fund-specific metrics. */ export interface QuoteEtf extends QuoteBase { quoteType: "ETF"; /** Annual dividend yield percentage */ dividendYield?: number; /** Total net assets under management */ netAssets?: number; /** Net expense ratio percentage */ netExpenseRatio?: number; } /** * Stock/equity quote data with company-specific metrics. */ export interface QuoteEquity extends QuoteBase { quoteType: "EQUITY"; /** Annual dividend rate per share */ dividendRate?: number; /** Annual dividend yield percentage */ dividendYield?: number; } /** * Electronic Communication Network quote, i.e. a a price coming from an * ECN/ATS rather than the primary exchange book. ECNs are electronic * venues that match orders directly (and are heavily used for pre- and * post-market trading). */ export interface QuoteECNQuote extends Omit<QuoteEquity, "quoteType"> { quoteType: "ECNQUOTE"; } /** * Futures contract quote data. */ export interface QuoteFuture extends QuoteBase { quoteType: "FUTURE"; /** Head symbol as string identifier */ headSymbolAsString?: string; /** Whether this is a contract symbol */ contractSymbol: boolean; /** Underlying exchange symbol */ underlyingExchangeSymbol: string; /** Contract expiration date */ expireDate: Date; /** ISO formatted expiration date */ expireIsoDate: Date; } /** * Market index quote data. */ export interface QuoteIndex extends QuoteBase { quoteType: "INDEX"; } /** * Options contract quote data with options-specific fields. */ export interface QuoteOption extends QuoteBase { quoteType: "OPTION"; /** Strike price of the option */ strike: number; /** Open interest (number of open contracts) */ openInterest: number; /** Expiration date as timestamp */ expireDate: number; /** ISO formatted expiration date */ expireIsoDate: Date; /** Symbol of the underlying asset */ underlyingSymbol: string; } /** * Mutual fund quote data. */ export interface QuoteMutualfund extends QuoteBase { quoteType: "MUTUALFUND"; /** Whether pre/post market data is available (typically false for mutual funds) */ hasPrePostMarketData?: boolean; /** Annual dividend rate per share */ dividendRate?: number; /** Annual dividend yield percentage */ dividendYield?: number; } /** * Money market fund quote data. */ export interface QuoteMoneyMarket extends QuoteBase { quoteType: "MONEYMARKET"; typeDisp: "MoneyMarket"; /** Total net assets under management */ netAssets?: number; } export interface QuoteAltSymbol extends QuoteBase { quoteType: "ALTSYMBOL"; typeDisp: "ALTSYMBOL"; underlyingExchangeSymbol: string; expireDate: Date; expireIsoDate: string; } /** * Union type for all possible quote data structures. * * The actual interface returned depends on the `quoteType` field: * - `"ALTSYMBOL"` → QuoteAltSymbol * - `"ECNQUOTE"` → QuoteECNQuote * - `"EQUITY"` → QuoteEquity * - `"ETF"` → QuoteEtf * - `"CRYPTOCURRENCY"` → QuoteCryptoCurrency * - `"OPTION"` → QuoteOption * - `"MUTUALFUND"` → QuoteMutualfund * - `"CURRENCY"` → QuoteCurrency * - `"FUTURE"` → QuoteFuture * - `"INDEX"` → QuoteIndex * - `"MONEYMARKET"` → QuoteMoneyMarket * * @discriminator quoteType */ export type Quote = QuoteAltSymbol | QuoteCryptoCurrency | QuoteCurrency | QuoteECNQuote | QuoteEtf | QuoteEquity | QuoteFuture | QuoteIndex | QuoteMutualfund | QuoteOption | QuoteMoneyMarket; /** All possible field names available in quote data */ export type QuoteField = keyof Quote; /** Return format options for quote results */ export type ResultType = "array" | "object" | "map"; /** Quote result as an array (default return type) */ export type QuoteResponseArray = Quote[]; /** Quote result as a Map with symbol as key */ export type QuoteResponseMap = Map<string, Quote>; /** Quote result as an object with symbol as property name */ export type QuoteResponseObject = { [key: string]: Quote; }; /** * Configuration options for quote requests. */ export interface QuoteOptions { /** * Specific fields to return. If not specified, all available fields are returned. * Some essential fields like `language`, `quoteType`, `symbol` are always included. */ fields?: QuoteField[]; lang?: string; region?: string; /** * Format for the returned data: * - `"array"` (default): Returns array of quotes in same order as input symbols * - `"object"`: Returns object with symbol names as keys * - `"map"`: Returns Map with symbol names as keys */ return?: ResultType; } /** Quote options with array return type (default) */ export interface QuoteOptionsWithReturnArray extends QuoteOptions { return?: "array"; } /** Quote options with Map return type */ export interface QuoteOptionsWithReturnMap extends QuoteOptions { return: "map"; } /** Quote options with object return type */ export interface QuoteOptionsWithReturnObject extends QuoteOptions { return: "object"; } /** * Get quote data for multiple symbols returning an array. * * **See the {@link [modules/quote] quote module} docs for examples and more.** * @see {@link [modules/quote] quote module} docs for examples and more. * * @param query - Array of symbol strings to get quotes for * @param queryOptionsOverrides - Optional query configuration * @param moduleOptions - Optional module configuration * @returns Promise resolving to array of Quote objects */ export default function quote(this: ModuleThis, query: string[], queryOptionsOverrides?: QuoteOptionsWithReturnArray, moduleOptions?: ModuleOptionsWithValidateTrue): Promise<QuoteResponseArray>; /** * Get quote data for multiple symbols returning a Map. * * **See the {@link [modules/quote] quote module} docs for examples and more.** * @see {@link [modules/quote] quote module} docs for examples and more. * * @param query - Array of symbol strings to get quotes for * @param queryOptionsOverrides - Query configuration with return: "map" * @param moduleOptions - Optional module configuration * @returns Promise resolving to Map with symbols as keys and Quote objects as values */ export default function quote(this: ModuleThis, query: string[], queryOptionsOverrides?: QuoteOptionsWithReturnMap, moduleOptions?: ModuleOptionsWithValidateTrue): Promise<QuoteResponseMap>; /** * Get quote data for multiple symbols returning an object. * * **See the {@link [modules/quote] quote module} docs for examples and more.** * @see {@link [modules/quote] quote module} docs for examples and more. * * @param query - Array of symbol strings to get quotes for * @param queryOptionsOverrides - Query configuration with return: "object" * @param moduleOptions - Optional module configuration * @returns Promise resolving to object with symbols as properties and Quote objects as values */ export default function quote(this: ModuleThis, query: string[], queryOptionsOverrides?: QuoteOptionsWithReturnObject, moduleOptions?: ModuleOptionsWithValidateTrue): Promise<QuoteResponseObject>; /** * Get quote data for a single symbol. * * **See the {@link [modules/quote] quote module} docs for examples and more.** * @see {@link [modules/quote] quote module} docs for examples and more. * * @param query - Symbol string to get quote for * @param queryOptionsOverrides - Optional query configuration * @param moduleOptions - Optional module configuration * @returns Promise resolving to a Quote object */ export default function quote(this: ModuleThis, query: string, queryOptionsOverrides?: QuoteOptions, moduleOptions?: ModuleOptionsWithValidateTrue): Promise<Quote>; /** * Get quote data with validation disabled. * * **See the {@link [modules/quote] quote module} docs for examples and more.** * @see {@link [modules/quote] quote module} docs for examples and more. * * @param query - Symbol string or array of symbols * @param queryOptionsOverrides - Optional query configuration * @param moduleOptions - Module configuration with validateResult: false * @returns Promise resolving to unvalidated data, but resembling {@linkcode Quote}. */ export default function quote(this: ModuleThis, query: string | string[], queryOptionsOverrides?: QuoteOptions, moduleOptions?: ModuleOptionsWithValidateFalse): Promise<any>; //# sourceMappingURL=quote.d.ts.map