From da75979574d948d98b7f804a18ee3b88d0168f5b Mon Sep 17 00:00:00 2001 From: Boki Date: Thu, 19 Jun 2025 09:47:57 -0400 Subject: [PATCH] fixed up types and working on utils lib --- libs/types/src/backtesting.ts | 34 + libs/types/src/events/events.ts | 0 libs/types/src/financial-statements.ts | 197 +++++ libs/types/src/helpers.ts | 36 + libs/types/src/index.ts | 832 +----------------- libs/types/src/market-data.ts | 107 +++ libs/types/src/options.ts | 58 ++ libs/types/src/portfolio.ts | 108 +++ libs/types/src/risk-metrics.ts | 86 ++ libs/types/src/technical-analysis.ts | 109 +++ libs/types/src/trading.ts | 62 ++ .../src/calculations/basic-calculations.ts | 16 +- .../src/calculations/correlation-analysis.ts | 24 +- libs/utils/src/calculations/index.ts | 130 +-- libs/utils/src/dateUtils.ts | 3 +- libs/utils/src/generic-functions.ts | 191 ++++ libs/utils/src/index.ts | 1 + 17 files changed, 1093 insertions(+), 901 deletions(-) create mode 100644 libs/types/src/backtesting.ts delete mode 100644 libs/types/src/events/events.ts create mode 100644 libs/types/src/financial-statements.ts create mode 100644 libs/types/src/helpers.ts create mode 100644 libs/types/src/market-data.ts create mode 100644 libs/types/src/options.ts create mode 100644 libs/types/src/portfolio.ts create mode 100644 libs/types/src/risk-metrics.ts create mode 100644 libs/types/src/technical-analysis.ts create mode 100644 libs/types/src/trading.ts create mode 100644 libs/utils/src/generic-functions.ts diff --git a/libs/types/src/backtesting.ts b/libs/types/src/backtesting.ts new file mode 100644 index 0000000..b7700c6 --- /dev/null +++ b/libs/types/src/backtesting.ts @@ -0,0 +1,34 @@ +/** + * Backtesting & Strategy Types + * Types for strategy backtesting and analysis + */ + +import type { TradeExecution, TradePerformance } from './trading'; +import type { PortfolioAnalysis } from './portfolio'; +import type { RiskMetrics, DrawdownAnalysis } from './risk-metrics'; + +/** + * Backtesting results + */ +export interface BacktestResults { + /** All trades executed */ + trades: TradeExecution[]; + /** Equity curve over time */ + equityCurve: Array<{ value: number; date: Date }>; + /** Performance metrics */ + performance: PortfolioAnalysis; + /** Risk metrics */ + riskMetrics: RiskMetrics; + /** Drawdown analysis */ + drawdownAnalysis: DrawdownAnalysis; + /** Trade performance */ + tradePerformance: TradePerformance; + /** Start date */ + startDate: Date; + /** End date */ + endDate: Date; + /** Initial capital */ + initialCapital: number; + /** Final value */ + finalValue: number; +} \ No newline at end of file diff --git a/libs/types/src/events/events.ts b/libs/types/src/events/events.ts deleted file mode 100644 index e69de29..0000000 diff --git a/libs/types/src/financial-statements.ts b/libs/types/src/financial-statements.ts new file mode 100644 index 0000000..20f5fdb --- /dev/null +++ b/libs/types/src/financial-statements.ts @@ -0,0 +1,197 @@ +/** + * Financial Statements Types + * Types for fundamental financial statement data + */ + +/** + * Balance Sheet data structure + */ +export interface BalanceSheet { + /** Reporting period date */ + date: string; + /** Fiscal period (Q1, Q2, Q3, Q4, FY) */ + period: string; + /** Currency */ + currency: string; + + // Assets + /** Total current assets */ + totalCurrentAssets: number; + /** Cash and cash equivalents */ + cashAndEquivalents: number; + /** Short-term investments */ + shortTermInvestments?: number; + /** Accounts receivable */ + accountsReceivable: number; + /** Inventory */ + inventory: number; + /** Prepaid expenses */ + prepaidExpenses?: number; + /** Other current assets */ + otherCurrentAssets?: number; + + /** Total non-current assets */ + totalNonCurrentAssets: number; + /** Property, plant & equipment (net) */ + propertyPlantEquipmentNet: number; + /** Intangible assets */ + intangibleAssets?: number; + /** Goodwill */ + goodwill?: number; + /** Long-term investments */ + longTermInvestments?: number; + /** Other non-current assets */ + otherNonCurrentAssets?: number; + + /** Total assets */ + totalAssets: number; + + // Liabilities + /** Total current liabilities */ + totalCurrentLiabilities: number; + /** Accounts payable */ + accountsPayable: number; + /** Short-term debt */ + shortTermDebt: number; + /** Accrued liabilities */ + accruedLiabilities?: number; + /** Other current liabilities */ + otherCurrentLiabilities?: number; + + /** Total non-current liabilities */ + totalNonCurrentLiabilities: number; + /** Long-term debt */ + longTermDebt: number; + /** Deferred tax liabilities */ + deferredTaxLiabilities?: number; + /** Other non-current liabilities */ + otherNonCurrentLiabilities?: number; + + /** Total liabilities */ + totalLiabilities: number; + + // Equity + /** Total stockholders' equity */ + totalStockholdersEquity: number; + /** Common stock */ + commonStock: number; + /** Retained earnings */ + retainedEarnings: number; + /** Additional paid-in capital */ + additionalPaidInCapital?: number; + /** Treasury stock */ + treasuryStock?: number; + /** Accumulated other comprehensive income */ + accumulatedOtherComprehensiveIncome?: number; +} + +/** + * Income Statement data structure + */ +export interface IncomeStatement { + /** Reporting period date */ + date: string; + /** Fiscal period (Q1, Q2, Q3, Q4, FY) */ + period: string; + /** Currency */ + currency: string; + + /** Total revenue/net sales */ + totalRevenue: number; + /** Cost of goods sold */ + costOfGoodsSold: number; + /** Gross profit */ + grossProfit: number; + + /** Operating expenses */ + operatingExpenses: number; + /** Research and development */ + researchAndDevelopment?: number; + /** Selling, general & administrative */ + sellingGeneralAdministrative?: number; + /** Depreciation and amortization */ + depreciationAmortization?: number; + /** Other operating expenses */ + otherOperatingExpenses?: number; + + /** Operating income */ + operatingIncome: number; + + /** Interest income */ + interestIncome?: number; + /** Interest expense */ + interestExpense?: number; + /** Other income/expense */ + otherIncomeExpense?: number; + + /** Income before taxes */ + incomeBeforeTaxes: number; + /** Income tax expense */ + incomeTaxExpense: number; + /** Net income */ + netIncome: number; + + /** Earnings per share (basic) */ + earningsPerShareBasic: number; + /** Earnings per share (diluted) */ + earningsPerShareDiluted: number; + /** Weighted average shares outstanding (basic) */ + sharesOutstandingBasic: number; + /** Weighted average shares outstanding (diluted) */ + sharesOutstandingDiluted: number; +} + +/** + * Cash Flow Statement data structure + */ +export interface CashFlowStatement { + /** Reporting period date */ + date: string; + /** Fiscal period (Q1, Q2, Q3, Q4, FY) */ + period: string; + /** Currency */ + currency: string; + + // Operating Activities + /** Net income */ + netIncome: number; + /** Depreciation and amortization */ + depreciationAmortization: number; + /** Changes in working capital */ + changesInWorkingCapital: number; + /** Other operating activities */ + otherOperatingActivities?: number; + /** Net cash from operating activities */ + netCashFromOperatingActivities: number; + + // Investing Activities + /** Capital expenditures */ + capitalExpenditures: number; + /** Acquisitions */ + acquisitions?: number; + /** Investments */ + investments?: number; + /** Other investing activities */ + otherInvestingActivities?: number; + /** Net cash from investing activities */ + netCashFromInvestingActivities: number; + + // Financing Activities + /** Debt issuance/repayment */ + debtIssuanceRepayment?: number; + /** Equity issuance/repurchase */ + equityIssuanceRepurchase?: number; + /** Dividends paid */ + dividendsPaid?: number; + /** Other financing activities */ + otherFinancingActivities?: number; + /** Net cash from financing activities */ + netCashFromFinancingActivities: number; + + /** Net change in cash */ + netChangeInCash: number; + /** Cash at beginning of period */ + cashAtBeginningOfPeriod: number; + /** Cash at end of period */ + cashAtEndOfPeriod: number; +} \ No newline at end of file diff --git a/libs/types/src/helpers.ts b/libs/types/src/helpers.ts new file mode 100644 index 0000000..f4cc2ed --- /dev/null +++ b/libs/types/src/helpers.ts @@ -0,0 +1,36 @@ +/** + * Helper Types + * Generic utility types for making functions work across different data types + */ + +/** + * Interface for data that has a close price + * Used to make functions generic across different data types + */ +export interface HasClose { + close: number; +} + +/** + * Interface for data that has OHLC prices + */ +export interface HasOHLC { + open: number; + high: number; + low: number; + close: number; +} + +/** + * Interface for data that has volume + */ +export interface HasVolume { + volume: number; +} + +/** + * Interface for data that has timestamp + */ +export interface HasTimestamp { + timestamp: number; +} \ No newline at end of file diff --git a/libs/types/src/index.ts b/libs/types/src/index.ts index b72d7ea..e66c07e 100644 --- a/libs/types/src/index.ts +++ b/libs/types/src/index.ts @@ -1,805 +1,49 @@ -// Export all types from the events module -export interface testEvent { - stringValue: string; -} - /** - * Standard OHLCV (Open, High, Low, Close, Volume) data structure - * Used for candlestick/bar chart data across all market data providers + * Stock Bot Types Library + * Standardized type definitions for the entire trading platform */ -export interface OHLCV { - /** Opening price for the time period */ - open: number; - /** Highest price during the time period */ - high: number; - /** Lowest price during the time period */ - low: number; - /** Closing price for the time period */ - close: number; - /** Trading volume during the time period */ - volume: number; - /** Timestamp of the data point (Unix timestamp in milliseconds) */ - timestamp: number; - /** Symbol/ticker for the security */ - symbol: string; - /** Time interval (e.g., '1m', '5m', '1h', '1d') */ - interval?: string; -} -/** - * OHLCV data with additional metadata - */ -export interface OHLCVWithMetadata extends OHLCV { - /** Source of the data (e.g., 'yahoo', 'ib', 'quotemedia') */ - source: string; - /** Whether this is adjusted data */ - adjusted?: boolean; - /** Number of trades during the period */ - trades?: number; - /** Volume weighted average price */ - vwap?: number; -} +// Export all market data types +export type { + LiquidityMetrics, + MarketData, + MarketRegime, + OHLCV, + OHLCVWithMetadata, +} from './market-data'; -// ============================================================================ -// PORTFOLIO & POSITION TYPES -// ============================================================================ +// Export all portfolio & position types +export type { + AssetAllocation, + KellyParams, + PortfolioAnalysis, + PortfolioPosition, + PositionSizeParams, +} from './portfolio'; -/** - * Individual portfolio position - */ -export interface PortfolioPosition { - /** Security symbol/ticker */ - symbol: string; - /** Number of shares/units */ - shares: number; - /** Average entry price */ - averagePrice: number; - /** Current market price */ - currentPrice: number; - /** Current market value */ - marketValue: number; - /** Unrealized P&L */ - unrealizedPnL: number; - /** Unrealized P&L percentage */ - unrealizedPnLPercent: number; - /** Weight in portfolio */ - weight: number; - /** Security type (stock, bond, option, etc.) */ - securityType?: string; - /** Currency */ - currency?: string; -} +// Export all trading & execution types +export type { TradeExecution, TradePerformance } from './trading'; -/** - * Portfolio analysis metrics - */ -export interface PortfolioAnalysis { - /** Total portfolio value */ - totalValue: number; - /** Total cash balance */ - cash: number; - /** Total invested amount */ - invested: number; - /** Total unrealized P&L */ - unrealizedPnL: number; - /** Total unrealized P&L percentage */ - unrealizedPnLPercent: number; - /** Total return */ - totalReturn: number; - /** Total return percentage */ - totalReturnPercent: number; - /** Annualized return */ - annualizedReturn: number; - /** Portfolio volatility (annualized) */ - volatility: number; - /** Sharpe ratio */ - sharpeRatio: number; - /** Maximum drawdown */ - maxDrawdown: number; - /** Number of positions */ - positionCount: number; - /** Portfolio concentration (largest position weight) */ - concentration: number; -} +// Export all risk & performance metrics +export type { DrawdownAnalysis, ReturnAnalysis, RiskMetrics } from './risk-metrics'; -/** - * Asset allocation breakdown - */ -export interface AssetAllocation { - /** Asset class or category */ - category: string; - /** Allocation value */ - value: number; - /** Allocation percentage */ - percentage: number; - /** Target allocation percentage */ - target?: number; - /** Deviation from target */ - deviation?: number; -} +// Export all options pricing types +export type { GreeksCalculation, OptionParameters, OptionPricing } from './options'; -// ============================================================================ -// TRADE & EXECUTION TYPES -// ============================================================================ +// Export all financial statement types +export type { BalanceSheet, CashFlowStatement, IncomeStatement } from './financial-statements'; -/** - * Trade execution record - */ -export interface TradeExecution { - /** Trade ID */ - id?: string; - /** Security symbol */ - symbol: string; - /** Trade type */ - type: 'buy' | 'sell' | 'short' | 'cover'; - /** Number of shares/units */ - quantity: number; - /** Execution price */ - price: number; - /** Total trade value */ - value: number; - /** Commission/fees */ - commission?: number; - /** Execution timestamp */ - timestamp: number; - /** Order ID reference */ - orderId?: string; - /** Execution venue */ - venue?: string; -} +// Export all technical analysis types +export type { + CorrelationMatrix, + CorrelationResult, + GARCHParameters, + TechnicalIndicators, + VolatilityEstimates, +} from './technical-analysis'; -/** - * Trade performance analysis - */ -export interface TradePerformance { - /** Total number of trades */ - totalTrades: number; - /** Number of winning trades */ - winningTrades: number; - /** Number of losing trades */ - losingTrades: number; - /** Win rate percentage */ - winRate: number; - /** Average winning trade */ - averageWin: number; - /** Average losing trade */ - averageLoss: number; - /** Largest winning trade */ - largestWin: number; - /** Largest losing trade */ - largestLoss: number; - /** Profit factor (gross profit / gross loss) */ - profitFactor: number; - /** Mathematical expectancy */ - expectancy: number; - /** Total gross profit */ - grossProfit: number; - /** Total gross loss */ - grossLoss: number; - /** Net profit */ - netProfit: number; -} +// Export backtesting types +export type { BacktestResults } from './backtesting'; -// ============================================================================ -// RISK & PERFORMANCE METRICS -// ============================================================================ - -/** - * Comprehensive risk metrics - */ -export interface RiskMetrics { - /** Value at Risk 95% */ - var95: number; - /** Value at Risk 99% */ - var99: number; - /** Conditional VaR 95% */ - cvar95: number; - /** Maximum drawdown */ - maxDrawdown: number; - /** Volatility (annualized) */ - volatility: number; - /** Downside deviation */ - downside_deviation: number; - /** Calmar ratio */ - calmar_ratio: number; - /** Sortino ratio */ - sortino_ratio: number; - /** Beta (vs benchmark) */ - beta: number; - /** Alpha (vs benchmark) */ - alpha: number; - /** Sharpe ratio */ - sharpeRatio: number; - /** Treynor ratio */ - treynorRatio: number; - /** Tracking error */ - trackingError: number; - /** Information ratio */ - informationRatio: number; -} - -/** - * Drawdown analysis - */ -export interface DrawdownAnalysis { - /** Maximum drawdown percentage */ - maxDrawdown: number; - /** Maximum drawdown duration (days) */ - maxDrawdownDuration: number; - /** Current drawdown percentage */ - currentDrawdown: number; - /** Current drawdown duration (days) */ - currentDrawdownDuration: number; - /** Average drawdown percentage */ - averageDrawdown: number; - /** Average drawdown duration (days) */ - averageDrawdownDuration: number; - /** Number of drawdown periods */ - drawdownPeriods: number; - /** Recovery factor */ - recoveryFactor: number; -} - -/** - * Return analysis statistics - */ -export interface ReturnAnalysis { - /** Total return */ - totalReturn: number; - /** Annualized return */ - annualizedReturn: number; - /** Volatility (annualized) */ - volatility: number; - /** Skewness */ - skewness: number; - /** Kurtosis */ - kurtosis: number; - /** Best period return */ - bestPeriod: number; - /** Worst period return */ - worstPeriod: number; - /** Positive periods percentage */ - positivePeriods: number; - /** Average positive return */ - averagePositiveReturn: number; - /** Average negative return */ - averageNegativeReturn: number; -} - -// ============================================================================ -// OPTIONS PRICING TYPES -// ============================================================================ - -/** - * Options pricing parameters - */ -export interface OptionParameters { - /** Underlying asset price */ - spotPrice: number; - /** Strike price */ - strikePrice: number; - /** Time to expiration (in years) */ - timeToExpiry: number; - /** Risk-free interest rate */ - riskFreeRate: number; - /** Volatility */ - volatility: number; - /** Dividend yield */ - dividendYield?: number; - /** Option type */ - optionType: 'call' | 'put'; -} - -/** - * Option pricing results - */ -export interface OptionPricing { - /** Call option price */ - callPrice: number; - /** Put option price */ - putPrice: number; - /** Call intrinsic value */ - callIntrinsic: number; - /** Put intrinsic value */ - putIntrinsic: number; - /** Call time value */ - callTimeValue: number; - /** Put time value */ - putTimeValue: number; -} - -/** - * Option Greeks calculation - */ -export interface GreeksCalculation { - /** Delta - price sensitivity */ - delta: number; - /** Gamma - delta sensitivity */ - gamma: number; - /** Theta - time decay */ - theta: number; - /** Vega - volatility sensitivity */ - vega: number; - /** Rho - interest rate sensitivity */ - rho: number; -} - -// ============================================================================ -// MARKET DATA & STATISTICS TYPES -// ============================================================================ - -/** - * Market data structure - */ -export interface MarketData { - /** Security symbol */ - symbol: string; - /** Current price */ - price: number; - /** Trading volume */ - volume: number; - /** Timestamp */ - timestamp: number; - /** Bid price */ - bid?: number; - /** Ask price */ - ask?: number; - /** Bid size */ - bidSize?: number; - /** Ask size */ - askSize?: number; - /** Previous close */ - previousClose?: number; - /** Day's high */ - high?: number; - /** Day's low */ - low?: number; - /** Day's open */ - open?: number; -} - -/** - * Market liquidity metrics - */ -export interface LiquidityMetrics { - /** Bid-ask spread */ - bidAskSpread: number; - /** Bid-ask spread percentage */ - bidAskSpreadPercent: number; - /** Market depth */ - marketDepth: number; - /** Average daily volume */ - averageDailyVolume: number; - /** Volume rate */ - volumeRate: number; - /** Price impact */ - priceImpact: number; - /** Liquidity score */ - liquidityScore: number; -} - -/** - * Market regime classification - */ -export interface MarketRegime { - /** Current regime */ - regime: 'trending' | 'ranging' | 'volatile' | 'quiet'; - /** Regime strength (0-1) */ - strength: number; - /** Regime duration (periods) */ - duration: number; - /** Trend direction (if trending) */ - trendDirection?: 'up' | 'down'; - /** Volatility level */ - volatilityLevel: 'low' | 'medium' | 'high'; -} - -// ============================================================================ -// POSITION SIZING TYPES -// ============================================================================ - -/** - * Position sizing parameters - */ -export interface PositionSizeParams { - /** Account size */ - accountSize: number; - /** Risk percentage per trade */ - riskPercent: number; - /** Entry price */ - entryPrice: number; - /** Stop loss price */ - stopPrice: number; - /** Commission per share */ - commission?: number; -} - -/** - * Kelly Criterion parameters - */ -export interface KellyParams { - /** Win rate (0-1) */ - winRate: number; - /** Average winning trade */ - averageWin: number; - /** Average losing trade */ - averageLoss: number; - /** Risk-free rate */ - riskFreeRate?: number; -} - -// ============================================================================ -// FINANCIAL STATEMENTS TYPES -// ============================================================================ - -/** - * Balance Sheet data structure - */ -export interface BalanceSheet { - /** Reporting period date */ - date: string; - /** Fiscal period (Q1, Q2, Q3, Q4, FY) */ - period: string; - /** Currency */ - currency: string; - - // Assets - /** Total current assets */ - totalCurrentAssets: number; - /** Cash and cash equivalents */ - cashAndEquivalents: number; - /** Short-term investments */ - shortTermInvestments?: number; - /** Accounts receivable */ - accountsReceivable: number; - /** Inventory */ - inventory: number; - /** Prepaid expenses */ - prepaidExpenses?: number; - /** Other current assets */ - otherCurrentAssets?: number; - - /** Total non-current assets */ - totalNonCurrentAssets: number; - /** Property, plant & equipment (net) */ - propertyPlantEquipmentNet: number; - /** Intangible assets */ - intangibleAssets?: number; - /** Goodwill */ - goodwill?: number; - /** Long-term investments */ - longTermInvestments?: number; - /** Other non-current assets */ - otherNonCurrentAssets?: number; - - /** Total assets */ - totalAssets: number; - - // Liabilities - /** Total current liabilities */ - totalCurrentLiabilities: number; - /** Accounts payable */ - accountsPayable: number; - /** Short-term debt */ - shortTermDebt: number; - /** Accrued liabilities */ - accruedLiabilities?: number; - /** Other current liabilities */ - otherCurrentLiabilities?: number; - - /** Total non-current liabilities */ - totalNonCurrentLiabilities: number; - /** Long-term debt */ - longTermDebt: number; - /** Deferred tax liabilities */ - deferredTaxLiabilities?: number; - /** Other non-current liabilities */ - otherNonCurrentLiabilities?: number; - - /** Total liabilities */ - totalLiabilities: number; - - // Equity - /** Total stockholders' equity */ - totalStockholdersEquity: number; - /** Common stock */ - commonStock: number; - /** Retained earnings */ - retainedEarnings: number; - /** Additional paid-in capital */ - additionalPaidInCapital?: number; - /** Treasury stock */ - treasuryStock?: number; - /** Accumulated other comprehensive income */ - accumulatedOtherComprehensiveIncome?: number; -} - -/** - * Income Statement data structure - */ -export interface IncomeStatement { - /** Reporting period date */ - date: string; - /** Fiscal period (Q1, Q2, Q3, Q4, FY) */ - period: string; - /** Currency */ - currency: string; - - /** Total revenue/net sales */ - totalRevenue: number; - /** Cost of goods sold */ - costOfGoodsSold: number; - /** Gross profit */ - grossProfit: number; - - /** Operating expenses */ - operatingExpenses: number; - /** Research and development */ - researchAndDevelopment?: number; - /** Selling, general & administrative */ - sellingGeneralAdministrative?: number; - /** Depreciation and amortization */ - depreciationAmortization?: number; - /** Other operating expenses */ - otherOperatingExpenses?: number; - - /** Operating income */ - operatingIncome: number; - - /** Interest income */ - interestIncome?: number; - /** Interest expense */ - interestExpense?: number; - /** Other income/expense */ - otherIncomeExpense?: number; - - /** Income before taxes */ - incomeBeforeTaxes: number; - /** Income tax expense */ - incomeTaxExpense: number; - /** Net income */ - netIncome: number; - - /** Earnings per share (basic) */ - earningsPerShareBasic: number; - /** Earnings per share (diluted) */ - earningsPerShareDiluted: number; - /** Weighted average shares outstanding (basic) */ - sharesOutstandingBasic: number; - /** Weighted average shares outstanding (diluted) */ - sharesOutstandingDiluted: number; -} - -/** - * Cash Flow Statement data structure - */ -export interface CashFlowStatement { - /** Reporting period date */ - date: string; - /** Fiscal period (Q1, Q2, Q3, Q4, FY) */ - period: string; - /** Currency */ - currency: string; - - // Operating Activities - /** Net income */ - netIncome: number; - /** Depreciation and amortization */ - depreciationAmortization: number; - /** Changes in working capital */ - changesInWorkingCapital: number; - /** Other operating activities */ - otherOperatingActivities?: number; - /** Net cash from operating activities */ - netCashFromOperatingActivities: number; - - // Investing Activities - /** Capital expenditures */ - capitalExpenditures: number; - /** Acquisitions */ - acquisitions?: number; - /** Investments */ - investments?: number; - /** Other investing activities */ - otherInvestingActivities?: number; - /** Net cash from investing activities */ - netCashFromInvestingActivities: number; - - // Financing Activities - /** Debt issuance/repayment */ - debtIssuanceRepayment?: number; - /** Equity issuance/repurchase */ - equityIssuanceRepurchase?: number; - /** Dividends paid */ - dividendsPaid?: number; - /** Other financing activities */ - otherFinancingActivities?: number; - /** Net cash from financing activities */ - netCashFromFinancingActivities: number; - - /** Net change in cash */ - netChangeInCash: number; - /** Cash at beginning of period */ - cashAtBeginningOfPeriod: number; - /** Cash at end of period */ - cashAtEndOfPeriod: number; -} - -// ============================================================================ -// TECHNICAL ANALYSIS TYPES -// ============================================================================ - -/** - * Technical indicators collection - */ -export interface TechnicalIndicators { - /** Simple Moving Average */ - sma: number[]; - /** Exponential Moving Average */ - ema: number[]; - /** Relative Strength Index */ - rsi: number[]; - /** MACD indicator */ - macd: { - macd: number[]; - signal: number[]; - histogram: number[]; - }; - /** Bollinger Bands */ - bollinger: { - upper: number[]; - middle: number[]; - lower: number[]; - }; - /** Average True Range */ - atr: number[]; - /** Stochastic Oscillator */ - stochastic: { - k: number[]; - d: number[]; - }; - /** Williams %R */ - williams_r: number[]; - /** Commodity Channel Index */ - cci: number[]; - /** Momentum */ - momentum: number[]; - /** Rate of Change */ - roc: number[]; -} - -// ============================================================================ -// CORRELATION & VOLATILITY TYPES -// ============================================================================ - -/** - * Correlation analysis result - */ -export interface CorrelationResult { - /** Correlation coefficient */ - correlation: number; - /** P-value for statistical significance */ - pValue: number; - /** Is statistically significant */ - isSignificant: boolean; - /** Confidence interval */ - confidenceInterval: [number, number]; - /** Sample size */ - sampleSize: number; -} - -/** - * Correlation matrix - */ -export interface CorrelationMatrix { - /** Asset symbols */ - symbols: string[]; - /** Correlation matrix values */ - matrix: number[][]; - /** Eigenvalues */ - eigenvalues: number[]; - /** Condition number */ - conditionNumber: number; - /** Is positive definite */ - isPositiveDefinite: boolean; -} - -/** - * Volatility estimates using different models - */ -export interface VolatilityEstimates { - /** Close-to-close volatility */ - closeToClose: number; - /** Parkinson volatility */ - parkinson: number; - /** Garman-Klass volatility */ - garmanKlass: number; - /** Rogers-Satchell volatility */ - rogersSatchell: number; - /** Yang-Zhang volatility */ - yangZhang: number; -} - -/** - * GARCH model parameters - */ -export interface GARCHParameters { - /** Alpha parameter */ - alpha: number; - /** Beta parameter */ - beta: number; - /** Omega parameter */ - omega: number; - /** Log likelihood */ - logLikelihood: number; - /** AIC (Akaike Information Criterion) */ - aic: number; - /** BIC (Bayesian Information Criterion) */ - bic: number; -} - -// ============================================================================ -// BACKTESTING & STRATEGY TYPES -// ============================================================================ - -/** - * Backtesting results - */ -export interface BacktestResults { - /** All trades executed */ - trades: TradeExecution[]; - /** Equity curve over time */ - equityCurve: Array<{ value: number; date: Date }>; - /** Performance metrics */ - performance: PortfolioAnalysis; - /** Risk metrics */ - riskMetrics: RiskMetrics; - /** Drawdown analysis */ - drawdownAnalysis: DrawdownAnalysis; - /** Trade performance */ - tradePerformance: TradePerformance; - /** Start date */ - startDate: Date; - /** End date */ - endDate: Date; - /** Initial capital */ - initialCapital: number; - /** Final value */ - finalValue: number; -} - -// ============================================================================ -// HELPER TYPES FOR GENERIC FUNCTIONS -// ============================================================================ - -/** - * Interface for data that has a close price - * Used to make functions generic across different data types - */ -export interface HasClose { - close: number; -} - -/** - * Interface for data that has OHLC prices - */ -export interface HasOHLC { - open: number; - high: number; - low: number; - close: number; -} - -/** - * Interface for data that has volume - */ -export interface HasVolume { - volume: number; -} - -/** - * Interface for data that has timestamp - */ -export interface HasTimestamp { - timestamp: number; -} +// Export helper types +export type { HasClose, HasOHLC, HasTimestamp, HasVolume } from './helpers'; diff --git a/libs/types/src/market-data.ts b/libs/types/src/market-data.ts new file mode 100644 index 0000000..ec82774 --- /dev/null +++ b/libs/types/src/market-data.ts @@ -0,0 +1,107 @@ +/** + * Market Data Types + * Standard types for market data and pricing information + */ + +/** + * Standard OHLCV (Open, High, Low, Close, Volume) data structure + * Used for candlestick/bar chart data across all market data providers + */ +export interface OHLCV { + /** Opening price for the time period */ + open: number; + /** Highest price during the time period */ + high: number; + /** Lowest price during the time period */ + low: number; + /** Closing price for the time period */ + close: number; + /** Trading volume during the time period */ + volume: number; + /** Timestamp of the data point (Unix timestamp in milliseconds) */ + timestamp: number; + /** Symbol/ticker for the security */ + symbol: string; + /** Time interval (e.g., '1m', '5m', '1h', '1d') */ + interval?: string; +} + +/** + * OHLCV data with additional metadata + */ +export interface OHLCVWithMetadata extends OHLCV { + /** Source of the data (e.g., 'yahoo', 'ib', 'quotemedia') */ + source: string; + /** Whether this is adjusted data */ + adjusted?: boolean; + /** Number of trades during the period */ + trades?: number; + /** Volume weighted average price */ + vwap?: number; +} + +/** + * Market data structure + */ +export interface MarketData { + /** Security symbol */ + symbol: string; + /** Current price */ + price: number; + /** Trading volume */ + volume: number; + /** Timestamp */ + timestamp: number; + /** Bid price */ + bid?: number; + /** Ask price */ + ask?: number; + /** Bid size */ + bidSize?: number; + /** Ask size */ + askSize?: number; + /** Previous close */ + previousClose?: number; + /** Day's high */ + high?: number; + /** Day's low */ + low?: number; + /** Day's open */ + open?: number; +} + +/** + * Market liquidity metrics + */ +export interface LiquidityMetrics { + /** Bid-ask spread */ + bidAskSpread: number; + /** Bid-ask spread percentage */ + bidAskSpreadPercent: number; + /** Market depth */ + marketDepth: number; + /** Average daily volume */ + averageDailyVolume: number; + /** Volume rate */ + volumeRate: number; + /** Price impact */ + priceImpact: number; + /** Liquidity score */ + liquidityScore: number; +} + +/** + * Market regime classification + */ +export interface MarketRegime { + /** Current regime */ + regime: 'trending' | 'ranging' | 'volatile' | 'quiet'; + /** Regime strength (0-1) */ + strength: number; + /** Regime duration (periods) */ + duration: number; + /** Trend direction (if trending) */ + trendDirection?: 'up' | 'down'; + /** Volatility level */ + volatilityLevel: 'low' | 'medium' | 'high'; +} \ No newline at end of file diff --git a/libs/types/src/options.ts b/libs/types/src/options.ts new file mode 100644 index 0000000..ea7cd9b --- /dev/null +++ b/libs/types/src/options.ts @@ -0,0 +1,58 @@ +/** + * Options Pricing Types + * Types for options pricing and derivatives + */ + +/** + * Options pricing parameters + */ +export interface OptionParameters { + /** Underlying asset price */ + spotPrice: number; + /** Strike price */ + strikePrice: number; + /** Time to expiration (in years) */ + timeToExpiry: number; + /** Risk-free interest rate */ + riskFreeRate: number; + /** Volatility */ + volatility: number; + /** Dividend yield */ + dividendYield?: number; + /** Option type */ + optionType: 'call' | 'put'; +} + +/** + * Option pricing results + */ +export interface OptionPricing { + /** Call option price */ + callPrice: number; + /** Put option price */ + putPrice: number; + /** Call intrinsic value */ + callIntrinsic: number; + /** Put intrinsic value */ + putIntrinsic: number; + /** Call time value */ + callTimeValue: number; + /** Put time value */ + putTimeValue: number; +} + +/** + * Option Greeks calculation + */ +export interface GreeksCalculation { + /** Delta - price sensitivity */ + delta: number; + /** Gamma - delta sensitivity */ + gamma: number; + /** Theta - time decay */ + theta: number; + /** Vega - volatility sensitivity */ + vega: number; + /** Rho - interest rate sensitivity */ + rho: number; +} \ No newline at end of file diff --git a/libs/types/src/portfolio.ts b/libs/types/src/portfolio.ts new file mode 100644 index 0000000..d034e48 --- /dev/null +++ b/libs/types/src/portfolio.ts @@ -0,0 +1,108 @@ +/** + * Portfolio & Position Types + * Types for portfolio management and position tracking + */ + +/** + * Individual portfolio position + */ +export interface PortfolioPosition { + /** Security symbol/ticker */ + symbol: string; + /** Number of shares/units */ + shares: number; + /** Average entry price */ + averagePrice: number; + /** Current market price */ + currentPrice: number; + /** Current market value */ + marketValue: number; + /** Unrealized P&L */ + unrealizedPnL: number; + /** Unrealized P&L percentage */ + unrealizedPnLPercent: number; + /** Weight in portfolio */ + weight: number; + /** Security type (stock, bond, option, etc.) */ + securityType?: string; + /** Currency */ + currency?: string; +} + +/** + * Portfolio analysis metrics + */ +export interface PortfolioAnalysis { + /** Total portfolio value */ + totalValue: number; + /** Total cash balance */ + cash: number; + /** Total invested amount */ + invested: number; + /** Total unrealized P&L */ + unrealizedPnL: number; + /** Total unrealized P&L percentage */ + unrealizedPnLPercent: number; + /** Total return */ + totalReturn: number; + /** Total return percentage */ + totalReturnPercent: number; + /** Annualized return */ + annualizedReturn: number; + /** Portfolio volatility (annualized) */ + volatility: number; + /** Sharpe ratio */ + sharpeRatio: number; + /** Maximum drawdown */ + maxDrawdown: number; + /** Number of positions */ + positionCount: number; + /** Portfolio concentration (largest position weight) */ + concentration: number; +} + +/** + * Asset allocation breakdown + */ +export interface AssetAllocation { + /** Asset class or category */ + category: string; + /** Allocation value */ + value: number; + /** Allocation percentage */ + percentage: number; + /** Target allocation percentage */ + target?: number; + /** Deviation from target */ + deviation?: number; +} + +/** + * Position sizing parameters + */ +export interface PositionSizeParams { + /** Account size */ + accountSize: number; + /** Risk percentage per trade */ + riskPercent: number; + /** Entry price */ + entryPrice: number; + /** Stop loss price */ + stopPrice: number; + /** Commission per share */ + commission?: number; +} + +/** + * Kelly Criterion parameters + */ +export interface KellyParams { + /** Win rate (0-1) */ + winRate: number; + /** Average winning trade */ + averageWin: number; + /** Average losing trade */ + averageLoss: number; + /** Risk-free rate */ + riskFreeRate?: number; +} \ No newline at end of file diff --git a/libs/types/src/risk-metrics.ts b/libs/types/src/risk-metrics.ts new file mode 100644 index 0000000..b3d7ca8 --- /dev/null +++ b/libs/types/src/risk-metrics.ts @@ -0,0 +1,86 @@ +/** + * Risk & Performance Metrics Types + * Types for risk measurement and performance analysis + */ + +/** + * Comprehensive risk metrics + */ +export interface RiskMetrics { + /** Value at Risk 95% */ + var95: number; + /** Value at Risk 99% */ + var99: number; + /** Conditional VaR 95% */ + cvar95: number; + /** Maximum drawdown */ + maxDrawdown: number; + /** Volatility (annualized) */ + volatility: number; + /** Downside deviation */ + downside_deviation: number; + /** Calmar ratio */ + calmar_ratio: number; + /** Sortino ratio */ + sortino_ratio: number; + /** Beta (vs benchmark) */ + beta: number; + /** Alpha (vs benchmark) */ + alpha: number; + /** Sharpe ratio */ + sharpeRatio: number; + /** Treynor ratio */ + treynorRatio: number; + /** Tracking error */ + trackingError: number; + /** Information ratio */ + informationRatio: number; +} + +/** + * Drawdown analysis + */ +export interface DrawdownAnalysis { + /** Maximum drawdown percentage */ + maxDrawdown: number; + /** Maximum drawdown duration (days) */ + maxDrawdownDuration: number; + /** Current drawdown percentage */ + currentDrawdown: number; + /** Current drawdown duration (days) */ + currentDrawdownDuration: number; + /** Average drawdown percentage */ + averageDrawdown: number; + /** Average drawdown duration (days) */ + averageDrawdownDuration: number; + /** Number of drawdown periods */ + drawdownPeriods: number; + /** Recovery factor */ + recoveryFactor: number; +} + +/** + * Return analysis statistics + */ +export interface ReturnAnalysis { + /** Total return */ + totalReturn: number; + /** Annualized return */ + annualizedReturn: number; + /** Volatility (annualized) */ + volatility: number; + /** Skewness */ + skewness: number; + /** Kurtosis */ + kurtosis: number; + /** Best period return */ + bestPeriod: number; + /** Worst period return */ + worstPeriod: number; + /** Positive periods percentage */ + positivePeriods: number; + /** Average positive return */ + averagePositiveReturn: number; + /** Average negative return */ + averageNegativeReturn: number; +} \ No newline at end of file diff --git a/libs/types/src/technical-analysis.ts b/libs/types/src/technical-analysis.ts new file mode 100644 index 0000000..cd3d2d7 --- /dev/null +++ b/libs/types/src/technical-analysis.ts @@ -0,0 +1,109 @@ +/** + * Technical Analysis Types + * Types for technical indicators and market analysis + */ + +/** + * Technical indicators collection + */ +export interface TechnicalIndicators { + /** Simple Moving Average */ + sma: number[]; + /** Exponential Moving Average */ + ema: number[]; + /** Relative Strength Index */ + rsi: number[]; + /** MACD indicator */ + macd: { + macd: number[]; + signal: number[]; + histogram: number[]; + }; + /** Bollinger Bands */ + bollinger: { + upper: number[]; + middle: number[]; + lower: number[]; + }; + /** Average True Range */ + atr: number[]; + /** Stochastic Oscillator */ + stochastic: { + k: number[]; + d: number[]; + }; + /** Williams %R */ + williams_r: number[]; + /** Commodity Channel Index */ + cci: number[]; + /** Momentum */ + momentum: number[]; + /** Rate of Change */ + roc: number[]; +} + +/** + * Correlation analysis result + */ +export interface CorrelationResult { + /** Correlation coefficient */ + correlation: number; + /** P-value for statistical significance */ + pValue: number; + /** Is statistically significant */ + isSignificant: boolean; + /** Confidence interval */ + confidenceInterval: [number, number]; + /** Sample size */ + sampleSize: number; +} + +/** + * Correlation matrix + */ +export interface CorrelationMatrix { + /** Asset symbols */ + symbols: string[]; + /** Correlation matrix values */ + matrix: number[][]; + /** Eigenvalues */ + eigenvalues: number[]; + /** Condition number */ + conditionNumber: number; + /** Is positive definite */ + isPositiveDefinite: boolean; +} + +/** + * Volatility estimates using different models + */ +export interface VolatilityEstimates { + /** Close-to-close volatility */ + closeToClose: number; + /** Parkinson volatility */ + parkinson: number; + /** Garman-Klass volatility */ + garmanKlass: number; + /** Rogers-Satchell volatility */ + rogersSatchell: number; + /** Yang-Zhang volatility */ + yangZhang: number; +} + +/** + * GARCH model parameters + */ +export interface GARCHParameters { + /** Alpha parameter */ + alpha: number; + /** Beta parameter */ + beta: number; + /** Omega parameter */ + omega: number; + /** Log likelihood */ + logLikelihood: number; + /** AIC (Akaike Information Criterion) */ + aic: number; + /** BIC (Bayesian Information Criterion) */ + bic: number; +} \ No newline at end of file diff --git a/libs/types/src/trading.ts b/libs/types/src/trading.ts new file mode 100644 index 0000000..e7a3eac --- /dev/null +++ b/libs/types/src/trading.ts @@ -0,0 +1,62 @@ +/** + * Trading & Execution Types + * Types for trade execution and performance analysis + */ + +/** + * Trade execution record + */ +export interface TradeExecution { + /** Trade ID */ + id?: string; + /** Security symbol */ + symbol: string; + /** Trade type */ + type: 'buy' | 'sell' | 'short' | 'cover'; + /** Number of shares/units */ + quantity: number; + /** Execution price */ + price: number; + /** Total trade value */ + value: number; + /** Commission/fees */ + commission?: number; + /** Execution timestamp */ + timestamp: number; + /** Order ID reference */ + orderId?: string; + /** Execution venue */ + venue?: string; +} + +/** + * Trade performance analysis + */ +export interface TradePerformance { + /** Total number of trades */ + totalTrades: number; + /** Number of winning trades */ + winningTrades: number; + /** Number of losing trades */ + losingTrades: number; + /** Win rate percentage */ + winRate: number; + /** Average winning trade */ + averageWin: number; + /** Average losing trade */ + averageLoss: number; + /** Largest winning trade */ + largestWin: number; + /** Largest losing trade */ + largestLoss: number; + /** Profit factor (gross profit / gross loss) */ + profitFactor: number; + /** Mathematical expectancy */ + expectancy: number; + /** Total gross profit */ + grossProfit: number; + /** Total gross loss */ + grossLoss: number; + /** Net profit */ + netProfit: number; +} \ No newline at end of file diff --git a/libs/utils/src/calculations/basic-calculations.ts b/libs/utils/src/calculations/basic-calculations.ts index eec0f31..f555ca5 100644 --- a/libs/utils/src/calculations/basic-calculations.ts +++ b/libs/utils/src/calculations/basic-calculations.ts @@ -95,8 +95,11 @@ export function internalRateOfReturn( let dnpv = 0; for (let j = 0; j < cashFlows.length; j++) { - npv += cashFlows[j] / Math.pow(1 + rate, j); - dnpv += (-j * cashFlows[j]) / Math.pow(1 + rate, j + 1); + const cashFlow = cashFlows[j]; + if (cashFlow !== undefined) { + npv += cashFlow / Math.pow(1 + rate, j); + dnpv += (-j * cashFlow) / Math.pow(1 + rate, j + 1); + } } if (Math.abs(npv) < 1e-10) { @@ -119,9 +122,12 @@ export function paybackPeriod(initialInvestment: number, cashFlows: number[]): n let cumulativeCashFlow = 0; for (let i = 0; i < cashFlows.length; i++) { - cumulativeCashFlow += cashFlows[i]; - if (cumulativeCashFlow >= initialInvestment) { - return i + 1 - (cumulativeCashFlow - initialInvestment) / cashFlows[i]; + const cashFlow = cashFlows[i]; + if (cashFlow !== undefined) { + cumulativeCashFlow += cashFlow; + if (cumulativeCashFlow >= initialInvestment) { + return i + 1 - (cumulativeCashFlow - initialInvestment) / cashFlow; + } } } diff --git a/libs/utils/src/calculations/correlation-analysis.ts b/libs/utils/src/calculations/correlation-analysis.ts index 6a80981..8c2f457 100644 --- a/libs/utils/src/calculations/correlation-analysis.ts +++ b/libs/utils/src/calculations/correlation-analysis.ts @@ -65,7 +65,10 @@ export function pearsonCorrelation(x: number[], y: number[]): CorrelationResult const n = x.length; const sumX = x.reduce((a, b) => a + b, 0); const sumY = y.reduce((a, b) => a + b, 0); - const sumXY = x.reduce((sum, xi, i) => sum + xi * y[i], 0); + const sumXY = x.reduce((sum, xi, i) => { + const yi = y[i]; + return yi !== undefined ? sum + xi * yi : sum; + }, 0); const sumX2 = x.reduce((sum, xi) => sum + xi * xi, 0); const sumY2 = y.reduce((sum, yi) => sum + yi * yi, 0); @@ -127,13 +130,20 @@ export function kendallTau(x: number[], y: number[]): CorrelationResult { for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { - const xDiff = x[i] - x[j]; - const yDiff = y[i] - y[j]; + const xi = x[i]; + const xj = x[j]; + const yi = y[i]; + const yj = y[j]; + + if (xi !== undefined && xj !== undefined && yi !== undefined && yj !== undefined) { + const xDiff = xi - xj; + const yDiff = yi - yj; - if (xDiff * yDiff > 0) { - concordant++; - } else if (xDiff * yDiff < 0) { - discordant++; + if (xDiff * yDiff > 0) { + concordant++; + } else if (xDiff * yDiff < 0) { + discordant++; + } } } } diff --git a/libs/utils/src/calculations/index.ts b/libs/utils/src/calculations/index.ts index 52c877e..c88cb5a 100644 --- a/libs/utils/src/calculations/index.ts +++ b/libs/utils/src/calculations/index.ts @@ -25,98 +25,40 @@ import { * Organized into logical categories for easy use and maintenance. */ -// Re-export standardized types -export type { OHLCV, OHLCVWithMetadata } from '@stock-bot/types'; - -// Legacy interface for backward compatibility - prefer OHLCV from @stock-bot/types -/** @deprecated Use OHLCV from @stock-bot/types instead */ -export interface OHLCVData { - open: number; - high: number; - low: number; - close: number; - volume: number; - timestamp: Date; -} - -export interface PriceData { - price: number; - timestamp: Date; -} - -// Financial calculation result interfaces -export interface PortfolioMetrics { - totalValue: number; - totalReturn: number; - totalReturnPercent: number; - dailyReturn: number; - dailyReturnPercent: number; - maxDrawdown: number; - sharpeRatio: number; - beta: number; - alpha: number; - volatility: number; -} - -export interface RiskMetrics { - var95: number; // Value at Risk 95% - var99: number; // Value at Risk 99% - cvar95: number; // Conditional VaR 95% - maxDrawdown: number; - volatility: number; - downside_deviation: number; - calmar_ratio: number; - sortino_ratio: number; - beta: number; - alpha: number; - sharpeRatio: number; - treynorRatio: number; - trackingError: number; - informationRatio: number; -} - -export interface TechnicalIndicators { - sma: number[]; - ema: number[]; - rsi: number[]; - macd: { macd: number[]; signal: number[]; histogram: number[] }; - bollinger: { upper: number[]; middle: number[]; lower: number[] }; - atr: number[]; - stochastic: { k: number[]; d: number[] }; - williams_r: number[]; - cci: number[]; - momentum: number[]; - roc: number[]; -} - -// Additional interfaces for new functionality -export interface TradeExecution { - entry: number; - exit: number; - peak?: number; - trough?: number; - volume: number; - timestamp: Date; -} - -export interface MarketData { - price: number; - volume: number; - timestamp: Date; - bid?: number; - ask?: number; - bidSize?: number; - askSize?: number; -} - -export interface BacktestResults { - trades: TradeExecution[]; - equityCurve: Array<{ value: number; date: Date }>; - - performance: PortfolioMetrics; - riskMetrics: RiskMetrics; - drawdownAnalysis: any; // Import from performance-metrics -} +// Re-export all standardized types from @stock-bot/types +export type { + OHLCV, + OHLCVWithMetadata, + PortfolioPosition, + PortfolioAnalysis, + AssetAllocation, + TradeExecution, + TradePerformance, + RiskMetrics, + DrawdownAnalysis, + ReturnAnalysis, + OptionParameters, + OptionPricing, + GreeksCalculation, + MarketData, + LiquidityMetrics, + MarketRegime, + PositionSizeParams, + KellyParams, + BalanceSheet, + IncomeStatement, + CashFlowStatement, + TechnicalIndicators, + CorrelationResult, + CorrelationMatrix, + VolatilityEstimates, + GARCHParameters, + BacktestResults, + HasClose, + HasOHLC, + HasVolume, + HasTimestamp +} from '@stock-bot/types'; // Export all calculation functions export * from './basic-calculations'; @@ -132,7 +74,7 @@ export * from './correlation-analysis'; // Convenience function to calculate all technical indicators at once export function calculateAllTechnicalIndicators( - ohlcv: OHLCVData[], + ohlcv: OHLCV[], periods: { sma?: number; ema?: number; rsi?: number; atr?: number } = {} ): TechnicalIndicators { const { @@ -166,7 +108,7 @@ export function analyzePortfolio( benchmarkReturns?: number[], riskFreeRate: number = 0.02 ): { - performance: PortfolioMetrics; + performance: PortfolioAnalysis; risk: RiskMetrics; trades?: any; drawdown?: any; diff --git a/libs/utils/src/dateUtils.ts b/libs/utils/src/dateUtils.ts index 6e96a4e..7495d32 100644 --- a/libs/utils/src/dateUtils.ts +++ b/libs/utils/src/dateUtils.ts @@ -43,7 +43,8 @@ export const dateUtils = { * Format a date as YYYY-MM-DD */ formatDate(date: Date): string { - return date.toISOString().split('T')[0]; + const parts = date.toISOString().split('T'); + return parts[0] ?? ''; }, /** diff --git a/libs/utils/src/generic-functions.ts b/libs/utils/src/generic-functions.ts new file mode 100644 index 0000000..0fdd76b --- /dev/null +++ b/libs/utils/src/generic-functions.ts @@ -0,0 +1,191 @@ +/** + * Generic utility functions that work with standardized types + * These functions demonstrate how to use generic types with OHLCV data + */ + +import type { OHLCV, HasClose, HasOHLC, HasVolume } from '@stock-bot/types'; + +/** + * 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(data: T[]): number[] { + return data.map(item => item.close); +} + +/** + * Extract OHLC prices from any data structure that has OHLC fields + */ +export function extractOHLC(data: T[]): { + opens: number[]; + highs: number[]; + lows: number[]; + closes: number[]; +} { + 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(data: T[]): number[] { + return data.map(item => item.volume); +} + +/** + * Calculate simple moving average using close prices from any compatible data type + */ +export function calculateSMA(data: T[], period: number): number[] { + const closes = extractCloses(data); + const result: number[] = []; + + for (let i = period - 1; i < closes.length; i++) { + const sum = closes.slice(i - period + 1, i + 1).reduce((a, b) => a + b, 0); + result.push(sum / period); + } + + return result; +} + +/** + * Calculate typical price (HLC/3) from any OHLC compatible data + */ +export function calculateTypicalPrice(data: T[]): number[] { + return data.map(item => (item.high + item.low + item.close) / 3); +} + +/** + * Calculate true range from OHLC data + */ +export function calculateTrueRange(data: T[]): number[] { + const result: number[] = []; + + for (let i = 0; i < data.length; i++) { + if (i === 0) { + result.push(data[i]!.high - data[i]!.low); + } else { + const current = data[i]!; + const previous = 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(tr); + } + } + + return result; +} + +/** + * Calculate returns from close prices + */ +export function calculateReturns(data: T[]): number[] { + const closes = extractCloses(data); + const returns: number[] = []; + + for (let i = 1; i < closes.length; i++) { + const current = closes[i]!; + const previous = closes[i - 1]!; + if (previous > 0) { + returns.push((current - previous) / previous); + } else { + returns.push(0); + } + } + + return returns; +} + +/** + * Calculate log returns from close prices + */ +export function calculateLogReturns(data: T[]): number[] { + const closes = extractCloses(data); + const logReturns: number[] = []; + + for (let i = 1; i < closes.length; i++) { + const current = closes[i]!; + const previous = closes[i - 1]!; + if (previous > 0 && current > 0) { + logReturns.push(Math.log(current / previous)); + } else { + logReturns.push(0); + } + } + + return logReturns; +} + +/** + * Calculate volume-weighted average price (VWAP) from OHLC + Volume data + */ +export function calculateVWAP(data: T[]): number[] { + const result: number[] = []; + let cumulativeVolumePrice = 0; + let cumulativeVolume = 0; + + for (const item of data) { + const typicalPrice = (item.high + item.low + item.close) / 3; + cumulativeVolumePrice += typicalPrice * item.volume; + cumulativeVolume += item.volume; + + if (cumulativeVolume > 0) { + result.push(cumulativeVolumePrice / cumulativeVolume); + } else { + result.push(typicalPrice); + } + } + + 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[] { + return data.filter(item => item.timestamp >= startTime && item.timestamp <= endTime); +} + +/** + * Group OHLCV data by symbol + */ +export function groupBySymbol(data: OHLCV[]): Record { + const grouped: Record = {}; + + for (const item of data) { + if (!grouped[item.symbol]) { + grouped[item.symbol] = []; + } + grouped[item.symbol]!.push(item); + } + + return grouped; +} + +/** + * Convert timestamp to Date for OHLCV data + */ +export function convertTimestamps(data: OHLCV[]): Array { + return data.map(item => ({ + ...item, + date: new Date(item.timestamp) + })); +} \ No newline at end of file diff --git a/libs/utils/src/index.ts b/libs/utils/src/index.ts index 213f278..d6b297e 100644 --- a/libs/utils/src/index.ts +++ b/libs/utils/src/index.ts @@ -1,3 +1,4 @@ export * from './calculations/index'; export * from './common'; export * from './dateUtils'; +export * from './generic-functions';