fixed up types and working on utils lib
This commit is contained in:
parent
25d9f2dd85
commit
da75979574
17 changed files with 1093 additions and 901 deletions
34
libs/types/src/backtesting.ts
Normal file
34
libs/types/src/backtesting.ts
Normal file
|
|
@ -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;
|
||||||
|
}
|
||||||
197
libs/types/src/financial-statements.ts
Normal file
197
libs/types/src/financial-statements.ts
Normal file
|
|
@ -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;
|
||||||
|
}
|
||||||
36
libs/types/src/helpers.ts
Normal file
36
libs/types/src/helpers.ts
Normal file
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
@ -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
|
* Stock Bot Types Library
|
||||||
* Used for candlestick/bar chart data across all market data providers
|
* 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
// Export all market data types
|
||||||
* OHLCV data with additional metadata
|
export type {
|
||||||
*/
|
LiquidityMetrics,
|
||||||
export interface OHLCVWithMetadata extends OHLCV {
|
MarketData,
|
||||||
/** Source of the data (e.g., 'yahoo', 'ib', 'quotemedia') */
|
MarketRegime,
|
||||||
source: string;
|
OHLCV,
|
||||||
/** Whether this is adjusted data */
|
OHLCVWithMetadata,
|
||||||
adjusted?: boolean;
|
} from './market-data';
|
||||||
/** Number of trades during the period */
|
|
||||||
trades?: number;
|
|
||||||
/** Volume weighted average price */
|
|
||||||
vwap?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ============================================================================
|
// Export all portfolio & position types
|
||||||
// PORTFOLIO & POSITION TYPES
|
export type {
|
||||||
// ============================================================================
|
AssetAllocation,
|
||||||
|
KellyParams,
|
||||||
|
PortfolioAnalysis,
|
||||||
|
PortfolioPosition,
|
||||||
|
PositionSizeParams,
|
||||||
|
} from './portfolio';
|
||||||
|
|
||||||
/**
|
// Export all trading & execution types
|
||||||
* Individual portfolio position
|
export type { TradeExecution, TradePerformance } from './trading';
|
||||||
*/
|
|
||||||
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 risk & performance metrics
|
||||||
* Portfolio analysis metrics
|
export type { DrawdownAnalysis, ReturnAnalysis, RiskMetrics } from './risk-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 options pricing types
|
||||||
* Asset allocation breakdown
|
export type { GreeksCalculation, OptionParameters, OptionPricing } from './options';
|
||||||
*/
|
|
||||||
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 financial statement types
|
||||||
// TRADE & EXECUTION TYPES
|
export type { BalanceSheet, CashFlowStatement, IncomeStatement } from './financial-statements';
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/**
|
// Export all technical analysis types
|
||||||
* Trade execution record
|
export type {
|
||||||
*/
|
CorrelationMatrix,
|
||||||
export interface TradeExecution {
|
CorrelationResult,
|
||||||
/** Trade ID */
|
GARCHParameters,
|
||||||
id?: string;
|
TechnicalIndicators,
|
||||||
/** Security symbol */
|
VolatilityEstimates,
|
||||||
symbol: string;
|
} from './technical-analysis';
|
||||||
/** 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 backtesting types
|
||||||
* Trade performance analysis
|
export type { BacktestResults } from './backtesting';
|
||||||
*/
|
|
||||||
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 helper types
|
||||||
// RISK & PERFORMANCE METRICS
|
export type { HasClose, HasOHLC, HasTimestamp, HasVolume } from './helpers';
|
||||||
// ============================================================================
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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;
|
|
||||||
}
|
|
||||||
|
|
|
||||||
107
libs/types/src/market-data.ts
Normal file
107
libs/types/src/market-data.ts
Normal file
|
|
@ -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';
|
||||||
|
}
|
||||||
58
libs/types/src/options.ts
Normal file
58
libs/types/src/options.ts
Normal file
|
|
@ -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;
|
||||||
|
}
|
||||||
108
libs/types/src/portfolio.ts
Normal file
108
libs/types/src/portfolio.ts
Normal file
|
|
@ -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;
|
||||||
|
}
|
||||||
86
libs/types/src/risk-metrics.ts
Normal file
86
libs/types/src/risk-metrics.ts
Normal file
|
|
@ -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;
|
||||||
|
}
|
||||||
109
libs/types/src/technical-analysis.ts
Normal file
109
libs/types/src/technical-analysis.ts
Normal file
|
|
@ -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;
|
||||||
|
}
|
||||||
62
libs/types/src/trading.ts
Normal file
62
libs/types/src/trading.ts
Normal file
|
|
@ -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;
|
||||||
|
}
|
||||||
|
|
@ -95,8 +95,11 @@ export function internalRateOfReturn(
|
||||||
let dnpv = 0;
|
let dnpv = 0;
|
||||||
|
|
||||||
for (let j = 0; j < cashFlows.length; j++) {
|
for (let j = 0; j < cashFlows.length; j++) {
|
||||||
npv += cashFlows[j] / Math.pow(1 + rate, j);
|
const cashFlow = cashFlows[j];
|
||||||
dnpv += (-j * cashFlows[j]) / Math.pow(1 + rate, j + 1);
|
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) {
|
if (Math.abs(npv) < 1e-10) {
|
||||||
|
|
@ -119,9 +122,12 @@ export function paybackPeriod(initialInvestment: number, cashFlows: number[]): n
|
||||||
let cumulativeCashFlow = 0;
|
let cumulativeCashFlow = 0;
|
||||||
|
|
||||||
for (let i = 0; i < cashFlows.length; i++) {
|
for (let i = 0; i < cashFlows.length; i++) {
|
||||||
cumulativeCashFlow += cashFlows[i];
|
const cashFlow = cashFlows[i];
|
||||||
if (cumulativeCashFlow >= initialInvestment) {
|
if (cashFlow !== undefined) {
|
||||||
return i + 1 - (cumulativeCashFlow - initialInvestment) / cashFlows[i];
|
cumulativeCashFlow += cashFlow;
|
||||||
|
if (cumulativeCashFlow >= initialInvestment) {
|
||||||
|
return i + 1 - (cumulativeCashFlow - initialInvestment) / cashFlow;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -65,7 +65,10 @@ export function pearsonCorrelation(x: number[], y: number[]): CorrelationResult
|
||||||
const n = x.length;
|
const n = x.length;
|
||||||
const sumX = x.reduce((a, b) => a + b, 0);
|
const sumX = x.reduce((a, b) => a + b, 0);
|
||||||
const sumY = y.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 sumX2 = x.reduce((sum, xi) => sum + xi * xi, 0);
|
||||||
const sumY2 = y.reduce((sum, yi) => sum + yi * yi, 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 i = 0; i < n - 1; i++) {
|
||||||
for (let j = i + 1; j < n; j++) {
|
for (let j = i + 1; j < n; j++) {
|
||||||
const xDiff = x[i] - x[j];
|
const xi = x[i];
|
||||||
const yDiff = y[i] - y[j];
|
const xj = x[j];
|
||||||
|
const yi = y[i];
|
||||||
|
const yj = y[j];
|
||||||
|
|
||||||
if (xDiff * yDiff > 0) {
|
if (xi !== undefined && xj !== undefined && yi !== undefined && yj !== undefined) {
|
||||||
concordant++;
|
const xDiff = xi - xj;
|
||||||
} else if (xDiff * yDiff < 0) {
|
const yDiff = yi - yj;
|
||||||
discordant++;
|
|
||||||
|
if (xDiff * yDiff > 0) {
|
||||||
|
concordant++;
|
||||||
|
} else if (xDiff * yDiff < 0) {
|
||||||
|
discordant++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -25,98 +25,40 @@ import {
|
||||||
* Organized into logical categories for easy use and maintenance.
|
* Organized into logical categories for easy use and maintenance.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Re-export standardized types
|
// Re-export all standardized types from @stock-bot/types
|
||||||
export type { OHLCV, OHLCVWithMetadata } from '@stock-bot/types';
|
export type {
|
||||||
|
OHLCV,
|
||||||
// Legacy interface for backward compatibility - prefer OHLCV from @stock-bot/types
|
OHLCVWithMetadata,
|
||||||
/** @deprecated Use OHLCV from @stock-bot/types instead */
|
PortfolioPosition,
|
||||||
export interface OHLCVData {
|
PortfolioAnalysis,
|
||||||
open: number;
|
AssetAllocation,
|
||||||
high: number;
|
TradeExecution,
|
||||||
low: number;
|
TradePerformance,
|
||||||
close: number;
|
RiskMetrics,
|
||||||
volume: number;
|
DrawdownAnalysis,
|
||||||
timestamp: Date;
|
ReturnAnalysis,
|
||||||
}
|
OptionParameters,
|
||||||
|
OptionPricing,
|
||||||
export interface PriceData {
|
GreeksCalculation,
|
||||||
price: number;
|
MarketData,
|
||||||
timestamp: Date;
|
LiquidityMetrics,
|
||||||
}
|
MarketRegime,
|
||||||
|
PositionSizeParams,
|
||||||
// Financial calculation result interfaces
|
KellyParams,
|
||||||
export interface PortfolioMetrics {
|
BalanceSheet,
|
||||||
totalValue: number;
|
IncomeStatement,
|
||||||
totalReturn: number;
|
CashFlowStatement,
|
||||||
totalReturnPercent: number;
|
TechnicalIndicators,
|
||||||
dailyReturn: number;
|
CorrelationResult,
|
||||||
dailyReturnPercent: number;
|
CorrelationMatrix,
|
||||||
maxDrawdown: number;
|
VolatilityEstimates,
|
||||||
sharpeRatio: number;
|
GARCHParameters,
|
||||||
beta: number;
|
BacktestResults,
|
||||||
alpha: number;
|
HasClose,
|
||||||
volatility: number;
|
HasOHLC,
|
||||||
}
|
HasVolume,
|
||||||
|
HasTimestamp
|
||||||
export interface RiskMetrics {
|
} from '@stock-bot/types';
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
// Export all calculation functions
|
// Export all calculation functions
|
||||||
export * from './basic-calculations';
|
export * from './basic-calculations';
|
||||||
|
|
@ -132,7 +74,7 @@ export * from './correlation-analysis';
|
||||||
|
|
||||||
// Convenience function to calculate all technical indicators at once
|
// Convenience function to calculate all technical indicators at once
|
||||||
export function calculateAllTechnicalIndicators(
|
export function calculateAllTechnicalIndicators(
|
||||||
ohlcv: OHLCVData[],
|
ohlcv: OHLCV[],
|
||||||
periods: { sma?: number; ema?: number; rsi?: number; atr?: number } = {}
|
periods: { sma?: number; ema?: number; rsi?: number; atr?: number } = {}
|
||||||
): TechnicalIndicators {
|
): TechnicalIndicators {
|
||||||
const {
|
const {
|
||||||
|
|
@ -166,7 +108,7 @@ export function analyzePortfolio(
|
||||||
benchmarkReturns?: number[],
|
benchmarkReturns?: number[],
|
||||||
riskFreeRate: number = 0.02
|
riskFreeRate: number = 0.02
|
||||||
): {
|
): {
|
||||||
performance: PortfolioMetrics;
|
performance: PortfolioAnalysis;
|
||||||
risk: RiskMetrics;
|
risk: RiskMetrics;
|
||||||
trades?: any;
|
trades?: any;
|
||||||
drawdown?: any;
|
drawdown?: any;
|
||||||
|
|
|
||||||
|
|
@ -43,7 +43,8 @@ export const dateUtils = {
|
||||||
* Format a date as YYYY-MM-DD
|
* Format a date as YYYY-MM-DD
|
||||||
*/
|
*/
|
||||||
formatDate(date: Date): string {
|
formatDate(date: Date): string {
|
||||||
return date.toISOString().split('T')[0];
|
const parts = date.toISOString().split('T');
|
||||||
|
return parts[0] ?? '';
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
191
libs/utils/src/generic-functions.ts
Normal file
191
libs/utils/src/generic-functions.ts
Normal file
|
|
@ -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<T extends HasClose>(data: T[]): number[] {
|
||||||
|
return data.map(item => 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[];
|
||||||
|
} {
|
||||||
|
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 data.map(item => 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[] {
|
||||||
|
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<T extends HasOHLC>(data: T[]): number[] {
|
||||||
|
return data.map(item => (item.high + item.low + item.close) / 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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++) {
|
||||||
|
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<T extends HasClose>(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<T extends HasClose>(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<T extends HasOHLC & HasVolume>(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<string, OHLCV[]> {
|
||||||
|
const grouped: Record<string, OHLCV[]> = {};
|
||||||
|
|
||||||
|
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<OHLCV & { date: Date }> {
|
||||||
|
return data.map(item => ({
|
||||||
|
...item,
|
||||||
|
date: new Date(item.timestamp)
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
export * from './calculations/index';
|
export * from './calculations/index';
|
||||||
export * from './common';
|
export * from './common';
|
||||||
export * from './dateUtils';
|
export * from './dateUtils';
|
||||||
|
export * from './generic-functions';
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue