From 25d9f2dd85c518d6efdb225a6735412b0dead26c Mon Sep 17 00:00:00 2001 From: Boki Date: Thu, 19 Jun 2025 09:35:03 -0400 Subject: [PATCH] updated config files and starting work on utils lib --- libs/browser/tsconfig.json | 5 + libs/cache/tsconfig.json | 5 + libs/config/src/utils/secrets.ts | 9 +- libs/config/src/utils/validation.ts | 7 +- libs/config/tsconfig.json | 5 + libs/event-bus/tsconfig.json | 5 + libs/http/tsconfig.json | 5 + libs/logger/tsconfig.json | 5 + libs/mongodb-client/tsconfig.json | 5 + libs/postgres-client/tsconfig.json | 5 + libs/proxy/tsconfig.json | 5 + libs/questdb-client/tsconfig.json | 5 + libs/queue/tsconfig.json | 5 + libs/shutdown/tsconfig.json | 5 + libs/strategy-engine/tsconfig.json | 5 + libs/types/src/index.ts | 804 +++++++++++++++++++++++++++ libs/types/tsconfig.json | 5 + libs/utils/src/calculations/index.ts | 9 +- libs/utils/tsconfig.json | 5 + libs/vector-engine/tsconfig.json | 5 + 20 files changed, 900 insertions(+), 9 deletions(-) diff --git a/libs/browser/tsconfig.json b/libs/browser/tsconfig.json index 82dd634..2ecd08d 100644 --- a/libs/browser/tsconfig.json +++ b/libs/browser/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ { "path": "../logger" }, { "path": "../http" } diff --git a/libs/cache/tsconfig.json b/libs/cache/tsconfig.json index 281c836..eae3dc0 100644 --- a/libs/cache/tsconfig.json +++ b/libs/cache/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ { "path": "../logger" } ] diff --git a/libs/config/src/utils/secrets.ts b/libs/config/src/utils/secrets.ts index 35e8456..b4c57a2 100644 --- a/libs/config/src/utils/secrets.ts +++ b/libs/config/src/utils/secrets.ts @@ -55,7 +55,7 @@ export class SecretValue { /** * Zod schema for secret values */ -export const secretSchema = (schema: T) => { +export const secretSchema = (_schema: T) => { return z.custom>>( (val) => val instanceof SecretValue, { @@ -100,15 +100,16 @@ export function redactSecrets>( let current: any = result; for (let i = 0; i < keys.length - 1; i++) { - if (current[keys[i]] && typeof current[keys[i]] === 'object') { - current = current[keys[i]]; + const key = keys[i]; + if (key && current[key] && typeof current[key] === 'object') { + current = current[key]; } else { break; } } const lastKey = keys[keys.length - 1]; - if (current && lastKey in current) { + if (current && lastKey && lastKey in current) { current[lastKey] = '***REDACTED***'; } } diff --git a/libs/config/src/utils/validation.ts b/libs/config/src/utils/validation.ts index 338a1b0..7eb54ed 100644 --- a/libs/config/src/utils/validation.ts +++ b/libs/config/src/utils/validation.ts @@ -1,5 +1,4 @@ import { z } from 'zod'; -import { ConfigValidationError } from '../errors'; export interface ValidationResult { valid: boolean; @@ -58,7 +57,7 @@ export function checkDeprecations( if (pathStr in deprecations) { warnings?.push({ path: pathStr, - message: deprecations[pathStr], + message: deprecations[pathStr]!, }); } @@ -183,10 +182,10 @@ export function mergeSchemas( throw new Error('At least two schemas required for merge'); } - let result = schemas[0].and(schemas[1]); + let result = schemas[0]!.and(schemas[1]!); for (let i = 2; i < schemas.length; i++) { - result = result.and(schemas[i]) as any; + result = result.and(schemas[i]!) as any; } return result as any; diff --git a/libs/config/tsconfig.json b/libs/config/tsconfig.json index 19b7195..e02b16b 100644 --- a/libs/config/tsconfig.json +++ b/libs/config/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ ] } \ No newline at end of file diff --git a/libs/event-bus/tsconfig.json b/libs/event-bus/tsconfig.json index 281c836..eae3dc0 100644 --- a/libs/event-bus/tsconfig.json +++ b/libs/event-bus/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ { "path": "../logger" } ] diff --git a/libs/http/tsconfig.json b/libs/http/tsconfig.json index ea0f8bb..bdc180d 100644 --- a/libs/http/tsconfig.json +++ b/libs/http/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ { "path": "../logger" }, { "path": "../types" } diff --git a/libs/logger/tsconfig.json b/libs/logger/tsconfig.json index 37bbf89..969ce3b 100644 --- a/libs/logger/tsconfig.json +++ b/libs/logger/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ ] } diff --git a/libs/mongodb-client/tsconfig.json b/libs/mongodb-client/tsconfig.json index ea0f8bb..bdc180d 100644 --- a/libs/mongodb-client/tsconfig.json +++ b/libs/mongodb-client/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ { "path": "../logger" }, { "path": "../types" } diff --git a/libs/postgres-client/tsconfig.json b/libs/postgres-client/tsconfig.json index ea0f8bb..bdc180d 100644 --- a/libs/postgres-client/tsconfig.json +++ b/libs/postgres-client/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ { "path": "../logger" }, { "path": "../types" } diff --git a/libs/proxy/tsconfig.json b/libs/proxy/tsconfig.json index 37bbf89..969ce3b 100644 --- a/libs/proxy/tsconfig.json +++ b/libs/proxy/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ ] } diff --git a/libs/questdb-client/tsconfig.json b/libs/questdb-client/tsconfig.json index ea0f8bb..bdc180d 100644 --- a/libs/questdb-client/tsconfig.json +++ b/libs/questdb-client/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ { "path": "../logger" }, { "path": "../types" } diff --git a/libs/queue/tsconfig.json b/libs/queue/tsconfig.json index 9c84c72..f6dd3d7 100644 --- a/libs/queue/tsconfig.json +++ b/libs/queue/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ { "path": "../cache" }, { "path": "../logger" }, diff --git a/libs/shutdown/tsconfig.json b/libs/shutdown/tsconfig.json index 37bbf89..969ce3b 100644 --- a/libs/shutdown/tsconfig.json +++ b/libs/shutdown/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ ] } diff --git a/libs/strategy-engine/tsconfig.json b/libs/strategy-engine/tsconfig.json index 91d6db6..09b47c0 100644 --- a/libs/strategy-engine/tsconfig.json +++ b/libs/strategy-engine/tsconfig.json @@ -1,4 +1,9 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [{ "path": "../event-bus" }, { "path": "../logger" }, { "path": "../utils" }] } diff --git a/libs/types/src/index.ts b/libs/types/src/index.ts index 1da603f..b72d7ea 100644 --- a/libs/types/src/index.ts +++ b/libs/types/src/index.ts @@ -1 +1,805 @@ // 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 + */ +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; +} + +// ============================================================================ +// PORTFOLIO & POSITION TYPES +// ============================================================================ + +/** + * 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; +} + +// ============================================================================ +// TRADE & EXECUTION TYPES +// ============================================================================ + +/** + * 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; +} + +// ============================================================================ +// 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; +} diff --git a/libs/types/tsconfig.json b/libs/types/tsconfig.json index 37bbf89..969ce3b 100644 --- a/libs/types/tsconfig.json +++ b/libs/types/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ ] } diff --git a/libs/utils/src/calculations/index.ts b/libs/utils/src/calculations/index.ts index e33aa25..52c877e 100644 --- a/libs/utils/src/calculations/index.ts +++ b/libs/utils/src/calculations/index.ts @@ -1,3 +1,6 @@ +// Import standardized types +import type { OHLCV, OHLCVWithMetadata } from '@stock-bot/types'; + // Import specific functions for convenience functions import { calculateStrategyMetrics } from './performance-metrics'; import { calculateRiskMetrics } from './risk-metrics'; @@ -22,7 +25,11 @@ import { * Organized into logical categories for easy use and maintenance. */ -// Core interfaces for financial data +// 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; diff --git a/libs/utils/tsconfig.json b/libs/utils/tsconfig.json index 73fbab9..e67ccaf 100644 --- a/libs/utils/tsconfig.json +++ b/libs/utils/tsconfig.json @@ -1,5 +1,10 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [ { "path": "../types" } ] diff --git a/libs/vector-engine/tsconfig.json b/libs/vector-engine/tsconfig.json index 5bcc934..adf6deb 100644 --- a/libs/vector-engine/tsconfig.json +++ b/libs/vector-engine/tsconfig.json @@ -1,4 +1,9 @@ { "extends": "../../tsconfig.lib.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src" + }, + "include": ["src/**/*"], "references": [{ "path": "../logger" }, { "path": "../utils" }] }