stock-bot/libs/calculations/src/market-data.ts

189 lines
5.1 KiB
TypeScript

import { defined } from '@stock-bot/invariants';
/**
* Generic utility functions that work with standardized types
* These functions demonstrate how to use generic types with OHLCV data
*/
import type { HasClose, HasOHLC, HasVolume, OHLCV } from '@stock-bot/types';
import { finite } from './analytics/equity';
import { sma } from './indicators/sma';
import { logReturns, simpleReturns } from './returns';
function priceRange(item: HasOHLC): number {
const range = finite(finite(item.high) - finite(item.low));
if (range < 0) {
throw new RangeError('High must be at least low');
}
if (finite(item.close) < item.low || item.close > item.high) {
throw new RangeError('Close must be within high and low');
}
return range;
}
function typicalPrice(item: HasOHLC): number {
priceRange(item);
return finite((item.high + item.low + item.close) / 3);
}
/**
* Extract close prices from any data structure that has a close field
* Works with OHLCV, MarketData, or any custom type with close price
*/
export function extractCloses<T extends HasClose>(data: T[]): number[] {
return Array.from(data, item => finite(item.close));
}
/**
* Extract OHLC prices from any data structure that has OHLC fields
*/
export function extractOHLC<T extends HasOHLC>(
data: T[]
): {
opens: number[];
highs: number[];
lows: number[];
closes: number[];
} {
for (const item of data) {
priceRange(item);
finite(item.open);
}
return {
opens: data.map(item => item.open),
highs: data.map(item => item.high),
lows: data.map(item => item.low),
closes: data.map(item => item.close),
};
}
/**
* Extract volumes from any data structure that has a volume field
*/
export function extractVolumes<T extends HasVolume>(data: T[]): number[] {
return Array.from(data, item => finite(item.volume));
}
/**
* Calculate simple moving average using close prices from any compatible data type
*/
export function calculateSMA<T extends HasClose>(data: T[], period: number): number[] {
return sma(extractCloses(data), period);
}
/**
* Calculate typical price (HLC/3) from any OHLC compatible data
*/
export function calculateTypicalPrice<T extends HasOHLC>(data: T[]): number[] {
return Array.from(data, typicalPrice);
}
/**
* Calculate true range from OHLC data
*/
export function calculateTrueRange<T extends HasOHLC>(data: T[]): number[] {
const result: number[] = [];
for (let i = 0; i < data.length; i++) {
priceRange(defined(data[i]));
if (i === 0) {
result.push(defined(data[i]).high - defined(data[i]).low);
} else {
const current = defined(data[i]);
const previous = defined(data[i - 1]);
const tr = Math.max(
current.high - current.low,
Math.abs(current.high - previous.close),
Math.abs(current.low - previous.close)
);
result.push(finite(tr));
}
}
return result;
}
/**
* Calculate returns from close prices
*/
export function calculateReturns<T extends HasClose>(data: T[]): number[] {
return simpleReturns(extractCloses(data));
}
/**
* Calculate log returns from close prices
*/
export function calculateLogReturns<T extends HasClose>(data: T[]): number[] {
return logReturns(extractCloses(data));
}
/**
* Calculate volume-weighted average price (VWAP) from OHLC + Volume data
*/
export function calculateVWAP<T extends HasOHLC & HasVolume>(data: T[]): Array<number | null> {
const result: Array<number | null> = [];
let cumulativeVolumePrice = 0;
let cumulativeVolume = 0;
for (const item of data) {
const price = typicalPrice(item);
if (finite(item.volume) < 0) {
throw new RangeError('Volume must be nonnegative');
}
cumulativeVolumePrice = finite(cumulativeVolumePrice + price * item.volume);
cumulativeVolume = finite(cumulativeVolume + item.volume);
if (cumulativeVolume > 0) {
result.push(finite(cumulativeVolumePrice / cumulativeVolume));
} else {
result.push(null);
}
}
return result;
}
/**
* Filter OHLCV data by symbol
*/
export function filterBySymbol(data: OHLCV[], symbol: string): OHLCV[] {
return data.filter(item => item.symbol === symbol);
}
/**
* Filter OHLCV data by time range
*/
export function filterByTimeRange(data: OHLCV[], startTime: number, endTime: number): OHLCV[] {
if (finite(startTime) > finite(endTime)) {
throw new RangeError('Invalid time range');
}
return data.filter(item => finite(item.timestamp) >= startTime && item.timestamp <= endTime);
}
/**
* Group OHLCV data by symbol
*/
export function groupBySymbol(data: OHLCV[]): Record<string, OHLCV[]> {
const grouped: Record<string, OHLCV[]> = Object.create(null);
for (const item of data) {
if (!grouped[item.symbol]) {
grouped[item.symbol] = [];
}
defined(grouped[item.symbol]).push(item);
}
return grouped;
}
/**
* Convert timestamp to Date for OHLCV data
*/
export function convertTimestamps(data: OHLCV[]): Array<OHLCV & { date: Date }> {
return data.map(item => {
const date = new Date(finite(item.timestamp));
if (!Number.isFinite(date.getTime())) {
throw new RangeError('Invalid timestamp');
}
return { ...item, date };
});
}