yahoo-finance2
Version:
JS API for Yahoo Finance
303 lines • 9.58 kB
TypeScript
/**
* Chart module for retrieving historical price data with extensive customization options.
*
* This module provides detailed historical price, volume, and event data for financial
* instruments, with flexible date ranges, intervals, and data formats. It's the primary
* source for building charts and conducting technical analysis.
*
* @example Basic Usage
* ```typescript
* import YahooFinance from "yahoo-finance2";
* const yahooFinance = new YahooFinance();
*
* // Get last year of daily data
* const result = await yahooFinance.chart('AAPL', {
* period1: '2023-01-01',
* period2: '2024-01-01'
* });
*
* console.log(result.quotes[0]); // First day's OHLCV data
* console.log(result.meta.currency); // "USD"
* ```
*
* @example Different Time Intervals
* ```typescript
* // Intraday 5-minute data for last 5 days
* const intraday = await yahooFinance.chart('TSLA', {
* period1: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000),
* interval: '5m'
* });
*
* // Weekly data for 2 years
* const weekly = await yahooFinance.chart('NVDA', {
* period1: '2022-01-01',
* period2: '2024-01-01',
* interval: '1wk'
* });
*
* // Monthly data for maximum available period
* const monthly = await yahooFinance.chart('MSFT', {
* period1: new Date('1985-01-01'),
* interval: '1mo'
* });
* ```
*
* @example Object Format for Charting Libraries
* ```typescript
* // Get data in object format (better for some charting libraries)
* const chartData = await yahooFinance.chart('GOOGL', {
* period1: '2023-06-01',
* period2: '2023-12-01',
* return: 'object'
* });
*
* // Access data by timestamp keys
* const timestamps = chartData.timestamp;
* const prices = chartData.indicators.quote[0];
*
* timestamps.forEach((timestamp, index) => {
* console.log(`${new Date(timestamp * 1000)}: $${prices.close[index]}`);
* });
* ```
*
* @example Working with Events and Dividends
* ```typescript
* const data = await yahooFinance.chart('AAPL', {
* period1: '2020-01-01',
* period2: '2024-01-01',
* events: 'div|split|earn'
* });
*
* // Process dividends
* if (data.events?.dividends) {
* data.events.dividends.forEach(dividend => {
* console.log(`Dividend: $${dividend.amount} on ${dividend.date}`);
* });
* }
*
* // Process stock splits
* if (data.events?.splits) {
* data.events.splits.forEach(split => {
* console.log(`Split: ${split.splitRatio} on ${split.date}`);
* });
* }
* ```
*
* @example Cryptocurrency and International Markets
* ```typescript
* // Bitcoin data
* const btc = await yahooFinance.chart('BTC-USD', {
* period1: '2024-01-01',
* interval: '1h'
* });
*
* // European stocks
* const asml = await yahooFinance.chart('ASML.AS', {
* period1: '2023-01-01'
* });
*
* // Japanese stocks
* const toyota = await yahooFinance.chart('7203.T', {
* period1: '2023-01-01'
* });
* ```
*
* @example Error Handling and Edge Cases
* ```typescript
* try {
* const result = await yahooFinance.chart('INVALID', {
* period1: '2023-01-01'
* });
* } catch (error) {
* if (error.message.includes('No data found')) {
* console.log('Symbol may be delisted or invalid');
* }
* }
*
* // Handle potential empty results
* const result = await yahooFinance.chart('AAPL', {
* period1: '2025-01-01' // Future date
* });
*
* if (result.quotes.length === 0) {
* console.log('No data available for the specified period');
* }
* ```
*
* @remarks
* **Data Formats**: The module provides two return formats:
* - `array` (default): Easier to iterate over with Date objects
* - `object`: Optimized for charting libraries, with timestamp keys
*
* **Intervals**: Intraday intervals (1m, 5m, etc.) have limited historical availability
* (~60 days for 1-minute data). Daily and longer intervals have extensive history.
*
* **Market Hours**: Pre/post market data is included by default but may not be
* available for all symbols or time periods.
*
* **Delisted Stocks**: When a stock is delisted, ALL historical data becomes
* unavailable through Yahoo Finance, including periods when it was actively traded.
*
* @see {@link historical} for a simpler interface focused on OHLCV data
*
* @module chart
*/
import type { ModuleOptionsWithValidateFalse, ModuleOptionsWithValidateTrue, ModuleThis } from "../lib/moduleCommon.js";
export interface ChartResultObject {
[key: string]: unknown;
meta: ChartMeta;
timestamp?: Array<number>;
events?: ChartEventsObject;
indicators: ChartIndicatorsObject;
}
export interface ChartResultArray {
meta: ChartMeta;
events?: ChartEventsArray;
quotes: Array<ChartResultArrayQuote>;
}
export interface ChartResultArrayQuote {
[key: string]: unknown;
date: Date;
high: number | null;
low: number | null;
open: number | null;
close: number | null;
volume: number | null;
adjclose?: number | null;
}
export interface ChartMeta {
[key: string]: unknown;
currency: string;
symbol: string;
exchangeName: string;
instrumentType: string;
fiftyTwoWeekHigh?: number;
fiftyTwoWeekLow?: number;
firstTradeDate: Date | null;
fullExchangeName?: string;
regularMarketTime: Date;
gmtoffset: number;
hasPrePostMarketData?: boolean;
timezone: string;
exchangeTimezoneName: string;
regularMarketPrice: number;
chartPreviousClose?: number;
previousClose?: number;
regularMarketDayHigh?: number;
regularMarketDayLow?: number;
regularMarketVolume?: number;
longName?: string;
shortName?: string;
scale?: number;
priceHint: number;
currentTradingPeriod: {
[key: string]: unknown;
pre: ChartMetaTradingPeriod;
regular: ChartMetaTradingPeriod;
post: ChartMetaTradingPeriod;
};
tradingPeriods?: ChartMetaTradingPeriods | ChartMetaTradingPeriod[][];
dataGranularity: string;
range: string;
validRanges: Array<string>;
}
export interface ChartMetaTradingPeriod {
[key: string]: unknown;
timezone: string;
start: Date;
end: Date;
gmtoffset: number;
}
export interface ChartMetaTradingPeriods {
[key: string]: unknown;
pre?: Array<Array<ChartMetaTradingPeriod>>;
post?: Array<Array<ChartMetaTradingPeriod>>;
regular?: Array<Array<ChartMetaTradingPeriod>>;
}
export interface ChartEventsObject {
[key: string]: unknown;
dividends?: ChartEventDividends;
splits?: ChartEventSplits;
}
export interface ChartEventsArray {
[key: string]: unknown;
dividends?: Array<ChartEventDividend>;
splits?: Array<ChartEventSplit>;
}
export interface ChartEventDividends {
[key: string]: ChartEventDividend;
}
export interface ChartEventDividend {
[key: string]: unknown;
amount: number;
date: Date;
}
export interface ChartEventSplits {
[key: string]: ChartEventSplit;
}
export interface ChartEventSplit {
[key: string]: unknown;
date: Date;
numerator: number;
denominator: number;
splitRatio: string;
}
export interface ChartIndicatorsObject {
[key: string]: unknown;
quote: Array<ChartIndicatorQuote>;
adjclose?: Array<ChartIndicatorAdjclose>;
}
export interface ChartIndicatorQuote {
[key: string]: unknown;
high: Array<number | null>;
low: Array<number | null>;
open: Array<number | null>;
close: Array<number | null>;
volume: Array<number | null>;
}
export interface ChartIndicatorAdjclose {
[key: string]: unknown;
adjclose?: Array<number | null>;
}
export interface ChartOptions {
period1: Date | string | number;
period2?: Date | string | number;
useYfid?: boolean;
interval?: "1m" | "2m" | "5m" | "15m" | "30m" | "60m" | "90m" | "1h" | "1d" | "5d" | "1wk" | "1mo" | "3mo";
includePrePost?: boolean;
events?: string;
lang?: string;
return?: "array" | "object";
}
export interface ChartOptionsWithReturnArray extends ChartOptions {
return?: "array";
}
export interface ChartOptionsWithReturnObject extends ChartOptions {
return: "object";
}
export declare const _chart: typeof chart;
/**
* Fetch historical price, dividend, split and other data useful for charts.
*
* **See the {@link [modules/chart] chart module} docs for examples and more.**
* @see {@link [modules/chart] chart module} docs for examples and more.
*/
export default function chart(this: ModuleThis, symbol: string, queryOptionsOverrides: ChartOptionsWithReturnObject, moduleOptions?: ModuleOptionsWithValidateTrue): Promise<ChartResultObject>;
/**
* Fetch historical price, dividend, split and other data useful for charts.
*
* **See the {@link [modules/chart] chart module} docs for examples and more.**
* @see {@link [modules/chart] chart module} docs for examples and more.
*/
export default function chart(this: ModuleThis, symbol: string, queryOptionsOverrides: ChartOptionsWithReturnArray, moduleOptions?: ModuleOptionsWithValidateTrue): Promise<ChartResultArray>;
/**
* Fetch historical price, dividend, split and other data useful for charts.
*
* **See the {@link [modules/chart] chart module} docs for examples and more.**
* @see {@link [modules/chart] chart module} docs for examples and more.
*
* @returns An unvalidated and untyped result, but that have a similar form to {@linkcode ChartResultArray}.
* @throws {ModuleError}
*/
export default function chart(this: ModuleThis, symbol: string, queryOptionsOverrides: ChartOptions, moduleOptions?: ModuleOptionsWithValidateFalse): Promise<unknown>;
//# sourceMappingURL=chart.d.ts.map