Extract shared calculations and preserve legacy research capabilities

This commit is contained in:
Boki 2026-10-21 20:27:07 -04:00
parent ccce401f72
commit 7827220b9b
82 changed files with 3099 additions and 1994 deletions

View file

@ -1,97 +0,0 @@
# Position Sizing Calculations - Fixed Issues Summary
## Issues Identified and Fixed:
### 1. **Duplicate Kelly Function** ✅ FIXED
- **Problem**: Two different `kellyPositionSize` functions with conflicting signatures
- **Solution**: Removed the duplicate and kept the version with proper `KellyParams` interface
### 2. **Incorrect Kelly Criterion Formula** ✅ FIXED
- **Problem**: Formula was implemented as `winRate - ((1 - winRate) / winLossRatio)`
- **Solution**: Corrected to `(winRate * winLossRatio - lossRate) / winLossRatio`
- **Mathematical Validation**: Kelly formula is `f = (bp - q) / b` where b = win/loss ratio, p = win rate, q = loss rate
### 3. **Missing Input Validation** ✅ FIXED
- **Problem**: Functions didn't validate inputs (zero/negative values)
- **Solution**: Added comprehensive input validation to all functions
- **Examples**:
- Check for `accountSize <= 0`, `riskPercentage <= 0`
- Validate `winRate` is between 0 and 1
- Ensure prices and volatilities are positive
### 4. **ATR Position Sizing Units Error** ✅ FIXED
- **Problem**: Function returned risk amount instead of shares
- **Solution**: Changed to return `Math.floor(riskAmount / stopDistance)` (shares)
### 5. **Flawed Monte Carlo Simulation** ✅ FIXED
- **Problem**: Simulation applied returns to entire portfolio instead of position-sized returns
- **Solution**: Rewritten to test different position fractions and optimize based on Sharpe ratio
### 6. **Redundant Liquidity Calculations** ✅ FIXED
- **Problem**: Unnecessary conversions between shares and dollar values
- **Solution**: Simplified to directly compare `desiredPositionSize` with `maxShares`
### 7. **Risk Parity Not Using Target Risk** ✅ FIXED
- **Problem**: `targetRisk` parameter was ignored in calculations
- **Solution**: Incorporated target risk into weight calculations: `weight * (targetRisk / asset.volatility)`
### 8. **Missing Safety Constraints** ✅ FIXED
- **Problem**: No caps on leverage or volatility ratios
- **Solution**: Added reasonable caps:
- Volatility targeting: max 2x leverage
- Volatility adjustment: max 3x leverage
- Kelly fraction: max 25% with safety factor
### 9. **Correlation Risk Calculation Error** ✅ FIXED
- **Problem**: Correlation risk calculation didn't consider relative position sizes
- **Solution**: Weight correlations by relative position sizes for more accurate risk assessment
### 10. **Integer Share Handling** ✅ FIXED
- **Problem**: Functions returned fractional shares
- **Solution**: Added `Math.floor()` to return whole shares where appropriate
## Mathematical Validation Examples:
### Fixed Risk Position Sizing:
```
Account: $100,000, Risk: 2%, Entry: $100, Stop: $95
Risk Amount: $100,000 × 0.02 = $2,000
Risk Per Share: |$100 - $95| = $5
Position Size: $2,000 ÷ $5 = 400 shares ✅
```
### Kelly Criterion (Corrected):
```
Win Rate: 60%, Avg Win: $150, Avg Loss: $100
Win/Loss Ratio: $150 ÷ $100 = 1.5
Kelly Fraction: (1.5 × 0.6 - 0.4) ÷ 1.5 = 0.333
With Safety Factor (25%): 0.333 × 0.25 = 0.083
Position: $100,000 × 0.083 = $8,333 ✅
```
### Volatility Targeting:
```
Price: $100, Asset Vol: 20%, Target Vol: 10%
Volatility Ratio: 10% ÷ 20% = 0.5
Position Value: $100,000 × 0.5 = $50,000
Position Size: $50,000 ÷ $100 = 500 shares ✅
```
## Edge Cases Now Handled:
- ✅ Zero or negative account sizes
- ✅ Equal entry and stop loss prices
- ✅ Zero volatility assets
- ✅ Negative expectancy strategies
- ✅ Extreme correlation values
- ✅ Division by zero scenarios
- ✅ Invalid win rates (≤0 or ≥1)
## Additional Improvements:
- ✅ Consistent return types (whole shares vs. dollar amounts)
- ✅ Proper TypeScript interfaces for all parameters
- ✅ Comprehensive JSDoc documentation
- ✅ Mathematical formulas verified against financial literature
- ✅ Safety factors to prevent over-leveraging
- ✅ Portfolio-level risk management functions
All position sizing calculations are now mathematically correct, properly validated, and production-ready!

View file

@ -1,34 +1,79 @@
# Utils Library
Common utility functions shared across services in the stock-bot project.
## Included Utilities
### Date Utilities
Helper functions for working with market dates:
```typescript
import { dateUtils } from '@stock-bot/utils';
// Check if a date is a trading day
const isTradingDay = dateUtils.isTradingDay(new Date());
// Get the next trading day
const nextTradingDay = dateUtils.getNextTradingDay(new Date());
```
### Financial Utilities
Mathematical functions for financial calculations:
```typescript
import { calculateCAGR, calculateSharpeRatio } from '@stock-bot/utils';
// Calculate compound annual growth rate
const returns = [0.05, 0.03, -0.01, 0.04, 0.02];
const cagr = calculateCAGR(startValue, endValue, years);
// Calculate Sharpe ratio
const sharpeRatio = calculateSharpeRatio(returns, 0.02);
```
# General utilities
`@stock-bot/utils` is a private workspace package for infrastructure-neutral general
helpers. Financial/feature calculations belong to `@stock-bot/calculations`, not here.
## Supported capabilities
- `@stock-bot/utils/fetch`: `fetch` and the type-only `FetchOptions`.
- `@stock-bot/utils/user-agent`: `getRandomUserAgent` selects from a fixed local list.
- `@stock-bot/utils/common`: `createProxyUrl` encodes proxy credentials; `sleep`
returns a timer-backed promise.
- `@stock-bot/utils/dates`: `utcDates` supplies `isWeekday`, `nextWeekday`,
`previousWeekday`, strict `parseDate` (`YYYY-MM-DD`) and `formatDate`.
The root explicitly exports these six runtime values (`fetch`, `getRandomUserAgent`,
`createProxyUrl`, `sleep`, `utcDates`, `dateUtils`) plus the `FetchOptions` type.
Capability subpaths avoid loading unrelated helpers. There are no wildcard/deep exports.
```ts
import { utcDates } from '@stock-bot/utils/dates';
import { fetch, type FetchOptions } from '@stock-bot/utils/fetch';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
const options: FetchOptions = {
headers: { 'User-Agent': getRandomUserAgent() },
timeout: 5_000,
};
const response = await fetch('https://example.com/data', options);
const next = utcDates.nextWeekday(utcDates.parseDate('2024-03-08'));
```
Fetch keeps its existing logging, Bun proxy, timeout and original-`Response` behavior.
Non-OK statuses are returned, not thrown. Timeout cancellation and caller cancellation
are not composed: a configured timeout currently replaces the supplied signal. The
user-agent list is not fingerprinting or a guarantee of provider access.
Date arithmetic is explicitly UTC, validates inputs and does not mutate the supplied
date. Weekdays are **not** exchange sessions: holidays, exchange time zones and trading
hours are not modeled. The deprecated `dateUtils` names (`isTradingDay`,
`getNextTradingDay`, `getPreviousTradingDay`, `formatDate`, `parseDate`) remain
as aliases for migration, not as verified trading-calendar APIs. This replaces the old
environment-dependent local weekday arithmetic; use `utcDates` in new code.
`@stock-bot/invariants` is the only runtime workspace dependency. `LoggerLike`
from `@stock-bot/logger` is type-only. No databases, configuration initialization,
application service containers or mandatory native bindings may be added here.
## Calculation migration and removals
The financial modules and OHLCV helpers were **relocated/preserved**, not discarded:
- Reviewed returns/analytics/window math and OHLCV processing:
`@stock-bot/calculations` and its explicit capability subpaths.
- All 105 formerly active calculation functions with their original bodies:
`@stock-bot/calculations/legacy`, an opt-in historical API, not reviewed core.
- All seven disabled numerical/indicator prototypes:
non-executable source-verified snapshots in `libs/calculations/research/`.
See [the calculation contract](../calculations/README.md) and
[the complete cleanup audit](../../docs/cleanup-audit.md) for readiness, preserved test
scenarios and deliberate removals. The empty `analyzePortfolio` placeholder remains
removed because it calculated nothing.
Import assertions directly from `@stock-bot/invariants`; the redundant utility assertion
facade was removed, not its functionality. Import domain types from `@stock-bot/types`.
No finance compatibility re-export is added to the general utility package.
## Verify
From the repository root:
```sh
bun run test:utils
bun run test:calculations
bun run check
```
The root gate includes general-utility and handler HTTP-consumer tests, calculation
regressions and architecture checks for the explicit APIs and dependency boundaries.

View file

@ -1,7 +1,8 @@
{
"name": "@stock-bot/utils",
"version": "1.0.0",
"description": "Common utility functions for stock-bot services",
"private": true,
"description": "General HTTP, date and asynchronous helpers for stock-bot services",
"main": "./src/index.ts",
"types": "./src/index.ts",
"scripts": {
@ -10,10 +11,7 @@
"test": "bun test"
},
"dependencies": {
"@stock-bot/config": "workspace:*",
"@stock-bot/logger": "workspace:*",
"@stock-bot/cache": "workspace:*",
"@stock-bot/types": "workspace:*",
"@stock-bot/invariants": "workspace:*"
},
"devDependencies": {
@ -23,6 +21,9 @@
},
"exports": {
".": "./src/index.ts",
"./assertions": "./src/assertions.ts"
"./fetch": "./src/fetch.ts",
"./user-agent": "./src/user-agent.ts",
"./common": "./src/common.ts",
"./dates": "./src/dateUtils.ts"
}
}

View file

@ -1 +0,0 @@
export { at, defined } from '@stock-bot/invariants';

View file

@ -1,453 +0,0 @@
/**
* Basic Financial Calculations
* Core mathematical functions for financial analysis
*/
/**
* Calculate percentage change between two values
*/
export function percentageChange(oldValue: number, newValue: number): number {
if (oldValue === 0) {
return 0;
}
return ((newValue - oldValue) / oldValue) * 100;
}
/**
* Calculate simple return
*/
export function simpleReturn(initialPrice: number, finalPrice: number): number {
if (initialPrice === 0) {
return 0;
}
return (finalPrice - initialPrice) / initialPrice;
}
/**
* Calculate logarithmic return
*/
export function logReturn(initialPrice: number, finalPrice: number): number {
if (initialPrice <= 0 || finalPrice <= 0) {
return 0;
}
return Math.log(finalPrice / initialPrice);
}
/**
* Calculate compound annual growth rate (CAGR)
*/
export function cagr(startValue: number, endValue: number, years: number): number {
if (years <= 0 || startValue <= 0 || endValue <= 0) {
return 0;
}
return Math.pow(endValue / startValue, 1 / years) - 1;
}
/**
* Calculate annualized return from periodic returns
*/
export function annualizeReturn(periodicReturn: number, periodsPerYear: number): number {
return Math.pow(1 + periodicReturn, periodsPerYear) - 1;
}
/**
* Calculate annualized volatility from periodic returns
*/
export function annualizeVolatility(periodicVolatility: number, periodsPerYear: number): number {
return periodicVolatility * Math.sqrt(periodsPerYear);
}
/**
* Calculate present value
*/
export function presentValue(futureValue: number, rate: number, periods: number): number {
return futureValue / Math.pow(1 + rate, periods);
}
/**
* Calculate future value
*/
export function futureValue(presentValue: number, rate: number, periods: number): number {
return presentValue * Math.pow(1 + rate, periods);
}
/**
* Calculate net present value of cash flows
*/
export function netPresentValue(cashFlows: number[], discountRate: number): number {
return cashFlows.reduce((npv, cashFlow, index) => {
return npv + cashFlow / Math.pow(1 + discountRate, index);
}, 0);
}
/**
* Calculate internal rate of return (IRR) using Newton-Raphson method
*/
export function internalRateOfReturn(
cashFlows: number[],
guess: number = 0.1,
maxIterations: number = 100
): number {
let rate = guess;
for (let i = 0; i < maxIterations; i++) {
let npv = 0;
let dnpv = 0;
for (let j = 0; j < cashFlows.length; j++) {
const cashFlow = cashFlows[j];
if (cashFlow !== undefined) {
npv += cashFlow / Math.pow(1 + rate, j);
dnpv += (-j * cashFlow) / Math.pow(1 + rate, j + 1);
}
}
if (Math.abs(npv) < 1e-10) {
break;
}
if (Math.abs(dnpv) < 1e-10) {
break;
}
rate = rate - npv / dnpv;
}
return rate;
}
/**
* Calculate payback period
*/
export function paybackPeriod(initialInvestment: number, cashFlows: number[]): number {
let cumulativeCashFlow = 0;
for (let i = 0; i < cashFlows.length; i++) {
const cashFlow = cashFlows[i];
if (cashFlow !== undefined) {
cumulativeCashFlow += cashFlow;
if (cumulativeCashFlow >= initialInvestment) {
return i + 1 - (cumulativeCashFlow - initialInvestment) / cashFlow;
}
}
}
return -1; // Never pays back
}
/**
* Calculate compound interest
*/
export function compoundInterest(
principal: number,
rate: number,
periods: number,
compoundingFrequency: number = 1
): number {
return principal * Math.pow(1 + rate / compoundingFrequency, compoundingFrequency * periods);
}
/**
* Calculate effective annual rate
*/
export function effectiveAnnualRate(nominalRate: number, compoundingFrequency: number): number {
return Math.pow(1 + nominalRate / compoundingFrequency, compoundingFrequency) - 1;
}
/**
* Calculate bond price given yield
*/
export function bondPrice(
faceValue: number,
couponRate: number,
yieldToMaturity: number,
periodsToMaturity: number,
paymentsPerYear: number = 2
): number {
const couponPayment = (faceValue * couponRate) / paymentsPerYear;
const discountRate = yieldToMaturity / paymentsPerYear;
let price = 0;
// Present value of coupon payments
for (let i = 1; i <= periodsToMaturity; i++) {
price += couponPayment / Math.pow(1 + discountRate, i);
}
// Present value of face value
price += faceValue / Math.pow(1 + discountRate, periodsToMaturity);
return price;
}
/**
* Calculate bond yield given price (Newton-Raphson approximation)
*/
export function bondYield(
price: number,
faceValue: number,
couponRate: number,
periodsToMaturity: number,
paymentsPerYear: number = 2,
guess: number = 0.05
): number {
let yield_ = guess;
const maxIterations = 100;
const tolerance = 1e-8;
for (let i = 0; i < maxIterations; i++) {
const calculatedPrice = bondPrice(
faceValue,
couponRate,
yield_,
periodsToMaturity,
paymentsPerYear
);
const diff = calculatedPrice - price;
if (Math.abs(diff) < tolerance) {
break;
}
// Numerical derivative
const delta = 0.0001;
const priceUp = bondPrice(
faceValue,
couponRate,
yield_ + delta,
periodsToMaturity,
paymentsPerYear
);
const derivative = (priceUp - calculatedPrice) / delta;
if (Math.abs(derivative) < tolerance) {
break;
}
yield_ = yield_ - diff / derivative;
}
return yield_;
}
/**
* Calculate duration (Macaulay duration)
*/
export function macaulayDuration(
faceValue: number,
couponRate: number,
yieldToMaturity: number,
periodsToMaturity: number,
paymentsPerYear: number = 2
): number {
const couponPayment = (faceValue * couponRate) / paymentsPerYear;
const discountRate = yieldToMaturity / paymentsPerYear;
const bondPriceValue = bondPrice(
faceValue,
couponRate,
yieldToMaturity,
periodsToMaturity,
paymentsPerYear
);
let weightedTime = 0;
// Weighted time of coupon payments
for (let i = 1; i <= periodsToMaturity; i++) {
const presentValue = couponPayment / Math.pow(1 + discountRate, i);
weightedTime += (i * presentValue) / bondPriceValue;
}
// Weighted time of face value
const faceValuePV = faceValue / Math.pow(1 + discountRate, periodsToMaturity);
weightedTime += (periodsToMaturity * faceValuePV) / bondPriceValue;
return weightedTime / paymentsPerYear; // Convert to years
}
/**
* Calculate modified duration
*/
export function modifiedDuration(
faceValue: number,
couponRate: number,
yieldToMaturity: number,
periodsToMaturity: number,
paymentsPerYear: number = 2
): number {
const macDuration = macaulayDuration(
faceValue,
couponRate,
yieldToMaturity,
periodsToMaturity,
paymentsPerYear
);
return macDuration / (1 + yieldToMaturity / paymentsPerYear);
}
/**
* Calculate bond convexity
*/
export function bondConvexity(
faceValue: number,
couponRate: number,
yieldToMaturity: number,
periodsToMaturity: number,
paymentsPerYear: number = 2
): number {
const couponPayment = (faceValue * couponRate) / paymentsPerYear;
const discountRate = yieldToMaturity / paymentsPerYear;
let convexity = 0;
const bondPriceValue = bondPrice(
faceValue,
couponRate,
yieldToMaturity,
periodsToMaturity,
paymentsPerYear
);
for (let i = 1; i <= periodsToMaturity; i++) {
const presentValue = couponPayment / Math.pow(1 + discountRate, i);
convexity += (i * (i + 1) * presentValue) / Math.pow(1 + discountRate, 2);
}
const faceValuePV = faceValue / Math.pow(1 + discountRate, periodsToMaturity);
convexity +=
(periodsToMaturity * (periodsToMaturity + 1) * faceValuePV) / Math.pow(1 + discountRate, 2);
return convexity / (bondPriceValue * paymentsPerYear * paymentsPerYear);
}
/**
* Calculate dollar duration
*/
export function dollarDuration(
faceValue: number,
couponRate: number,
yieldToMaturity: number,
periodsToMaturity: number,
paymentsPerYear: number = 2,
basisPointChange: number = 0.01 // 1 basis point = 0.01%
): number {
const modifiedDur = modifiedDuration(
faceValue,
couponRate,
yieldToMaturity,
periodsToMaturity,
paymentsPerYear
);
const bondPriceValue = bondPrice(
faceValue,
couponRate,
yieldToMaturity,
periodsToMaturity,
paymentsPerYear
);
return modifiedDur * bondPriceValue * basisPointChange;
}
/**
* Calculate accrued interest
*/
export function accruedInterest(
faceValue: number,
couponRate: number,
daysSinceLastCoupon: number,
daysInCouponPeriod: number
): number {
return faceValue * couponRate * (daysSinceLastCoupon / daysInCouponPeriod);
}
/**
* Calculate clean price
*/
export function cleanPrice(dirtyPrice: number, accruedInterestValue: number): number {
return dirtyPrice - accruedInterestValue;
}
/**
* Calculate dirty price
*/
export function dirtyPrice(cleanPriceValue: number, accruedInterestValue: number): number {
return cleanPriceValue + accruedInterestValue;
}
/**
* Calculate dividend discount model (DDM)
*/
export function dividendDiscountModel(
currentDividend: number,
growthRate: number,
discountRate: number
): number {
if (discountRate <= growthRate) {
return NaN;
} // Indeterminate
return (currentDividend * (1 + growthRate)) / (discountRate - growthRate);
}
/**
* Calculate weighted average cost of capital (WACC)
*/
export function weightedAverageCostOfCapital(
costOfEquity: number,
costOfDebt: number,
equityWeight: number,
debtWeight: number,
taxRate: number
): number {
return equityWeight * costOfEquity + debtWeight * costOfDebt * (1 - taxRate);
}
/**
* Calculate capital asset pricing model (CAPM)
*/
export function capitalAssetPricingModel(
riskFreeRate: number,
beta: number,
marketRiskPremium: number
): number {
return riskFreeRate + beta * marketRiskPremium;
}
/**
* Calculate hurdle rate
*/
export function hurdleRate(costOfCapital: number, riskPremium: number): number {
return costOfCapital + riskPremium;
}
/**
* Calculate degree of operating leverage (DOL)
*/
export function degreeOfOperatingLeverage(
contributionMargin: number,
operatingIncome: number
): number {
return contributionMargin / operatingIncome;
}
/**
* Calculate degree of financial leverage (DFL)
*/
export function degreeOfFinancialLeverage(ebit: number, earningsBeforeTax: number): number {
return ebit / earningsBeforeTax;
}
/**
* Calculate degree of total leverage (DTL)
*/
export function degreeOfTotalLeverage(dol: number, dfl: number): number {
return dol * dfl;
}
/**
* Calculate economic value added (EVA)
*/
export function economicValueAdded(
netOperatingProfitAfterTax: number,
capitalInvested: number,
wacc: number
): number {
return netOperatingProfitAfterTax - capitalInvested * wacc;
}

File diff suppressed because it is too large Load diff

View file

@ -1,104 +0,0 @@
/**
* Financial Calculations Library
*
* This module provides a core set of financial calculations for trading and investment analysis.
* Focuses on basic calculations and standardized type exports.
*/
// Re-export all standardized types from @stock-bot/types
export type {
OHLCV,
OHLCVWithMetadata,
PortfolioPosition,
PortfolioAnalysis,
AssetAllocation,
TradeExecution,
TradePerformance,
RiskMetrics,
DrawdownAnalysis,
ReturnAnalysis,
OptionParameters,
OptionPricing,
GreeksCalculation,
MarketData,
LiquidityMetrics,
MarketRegime,
PositionSizeParams,
KellyParams,
BalanceSheet,
IncomeStatement,
CashFlowStatement,
TechnicalIndicators,
CorrelationResult,
CorrelationMatrix,
VolatilityEstimates,
GARCHParameters,
BacktestResults,
HasClose,
HasOHLC,
HasVolume,
HasTimestamp,
} from '@stock-bot/types';
// Export working calculation functions
export * from './basic-calculations';
// Export working technical indicators (building one by one)
export {
sma,
ema,
rsi,
macd,
bollingerBands,
atr,
obv,
stochastic,
williamsR,
cci,
mfi,
vwma,
momentum,
roc,
accumulationDistribution,
aroon,
adx,
parabolicSAR,
chaikinMoneyFlow,
pivotPoints,
ichimoku,
ultimateOscillator,
easeOfMovement,
tema,
wma,
keltnerChannels,
donchianChannels,
klingerVolumeOscillator,
priceOscillator,
chandeMomentumOscillator,
stochasticRSI,
vortexIndicator,
balanceOfPower,
trix,
massIndex,
coppockCurve,
} from './technical-indicators';
export * from './risk-metrics';
export * from './performance-metrics';
// Convenience function for comprehensive portfolio analysis
export function analyzePortfolio(
_returns: number[],
_equityCurve: Array<{ value: number; date: Date }>,
_benchmarkReturns?: number[],
_riskFreeRate: number = 0.02
): {
performance: Record<string, unknown>;
risk: Record<string, unknown>;
} {
// Note: Implementation depends on performance-metrics and risk-metrics
// This is a placeholder for the full implementation
return {
performance: {},
risk: {},
};
}

File diff suppressed because it is too large Load diff

View file

@ -1,810 +0,0 @@
/**
* Options Pricing Models
* Implementation of various options pricing models and Greeks calculations
*/
export interface OptionParameters {
spotPrice: number;
strikePrice: number;
timeToExpiry: number; // in years
riskFreeRate: number;
volatility: number;
dividendYield?: number;
}
export interface OptionPricing {
callPrice: number;
putPrice: number;
intrinsicValueCall: number;
intrinsicValuePut: number;
timeValueCall: number;
timeValuePut: number;
}
export interface GreeksCalculation {
delta: number;
gamma: number;
theta: number;
vega: number;
rho: number;
}
export interface ImpliedVolatilityResult {
impliedVolatility: number;
iterations: number;
converged: boolean;
}
/**
* Black-Scholes option pricing model
*/
export function blackScholes(params: OptionParameters): OptionPricing {
const {
spotPrice,
strikePrice,
timeToExpiry,
riskFreeRate,
volatility,
dividendYield = 0,
} = params;
if (timeToExpiry <= 0) {
const intrinsicValueCall = Math.max(spotPrice - strikePrice, 0);
const intrinsicValuePut = Math.max(strikePrice - spotPrice, 0);
return {
callPrice: intrinsicValueCall,
putPrice: intrinsicValuePut,
intrinsicValueCall,
intrinsicValuePut,
timeValueCall: 0,
timeValuePut: 0,
};
}
const d1 =
(Math.log(spotPrice / strikePrice) +
(riskFreeRate - dividendYield + 0.5 * volatility * volatility) * timeToExpiry) /
(volatility * Math.sqrt(timeToExpiry));
const d2 = d1 - volatility * Math.sqrt(timeToExpiry);
const nd1 = normalCDF(d1);
const nd2 = normalCDF(d2);
const nMinusd1 = normalCDF(-d1);
const nMinusd2 = normalCDF(-d2);
const callPrice =
spotPrice * Math.exp(-dividendYield * timeToExpiry) * nd1 -
strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * nd2;
const putPrice =
strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * nMinusd2 -
spotPrice * Math.exp(-dividendYield * timeToExpiry) * nMinusd1;
const intrinsicValueCall = Math.max(spotPrice - strikePrice, 0);
const intrinsicValuePut = Math.max(strikePrice - spotPrice, 0);
const timeValueCall = callPrice - intrinsicValueCall;
const timeValuePut = putPrice - intrinsicValuePut;
return {
callPrice,
putPrice,
intrinsicValueCall,
intrinsicValuePut,
timeValueCall,
timeValuePut,
};
}
export function impliedVolatility(
price: number,
S: number,
K: number,
T: number,
r: number,
isCall = true
): number {
// …Newton–Raphson on σ to match blackScholesPrice
let sigma = 0.2; // Initial guess for volatility
const tolerance = 1e-6;
const maxIterations = 100;
let iteration = 0;
let priceDiff = 1; // Initialize to a non-zero value
while (Math.abs(priceDiff) > tolerance && iteration < maxIterations) {
const params: OptionParameters = {
spotPrice: S,
strikePrice: K,
timeToExpiry: T,
riskFreeRate: r,
volatility: sigma,
};
const calculatedPrice = isCall ? blackScholes(params).callPrice : blackScholes(params).putPrice;
priceDiff = calculatedPrice - price;
// Calculate Vega
const greeks = calculateGreeks(params, isCall ? 'call' : 'put');
const vega = greeks.vega * 100; // Convert from percentage to absolute
if (vega === 0) {
break; // Avoid division by zero
}
sigma -= priceDiff / vega; // Update volatility estimate
iteration++;
}
if (iteration === maxIterations) {
console.warn('Implied volatility calculation did not converge');
}
if (sigma < 0) {
console.warn('Calculated implied volatility is negative, returning 0');
return 0;
}
if (sigma > 10) {
console.warn('Calculated implied volatility is too high, returning 10');
return 10; // Cap at a reasonable maximum
}
if (isNaN(sigma)) {
console.warn('Calculated implied volatility is NaN, returning 0');
return 0;
}
return sigma;
}
/**
* Calculate option Greeks using Black-Scholes model
*/
export function calculateGreeks(
params: OptionParameters,
optionType: 'call' | 'put' = 'call'
): GreeksCalculation {
const {
spotPrice,
strikePrice,
timeToExpiry,
riskFreeRate,
volatility,
dividendYield = 0,
} = params;
if (timeToExpiry <= 0) {
return {
delta:
optionType === 'call'
? spotPrice > strikePrice
? 1
: 0
: spotPrice < strikePrice
? -1
: 0,
gamma: 0,
theta: 0,
vega: 0,
rho: 0,
};
}
const d1 =
(Math.log(spotPrice / strikePrice) +
(riskFreeRate - dividendYield + 0.5 * volatility * volatility) * timeToExpiry) /
(volatility * Math.sqrt(timeToExpiry));
const d2 = d1 - volatility * Math.sqrt(timeToExpiry);
const nd1 = normalCDF(d1);
const nd2 = normalCDF(d2);
const npd1 = normalPDF(d1);
// Delta
const callDelta = Math.exp(-dividendYield * timeToExpiry) * nd1;
const putDelta = Math.exp(-dividendYield * timeToExpiry) * (nd1 - 1);
const delta = optionType === 'call' ? callDelta : putDelta;
// Gamma (same for calls and puts)
const gamma =
(Math.exp(-dividendYield * timeToExpiry) * npd1) /
(spotPrice * volatility * Math.sqrt(timeToExpiry));
// Theta
const term1 =
-(spotPrice * npd1 * volatility * Math.exp(-dividendYield * timeToExpiry)) /
(2 * Math.sqrt(timeToExpiry));
const term2Call = riskFreeRate * strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * nd2;
const term2Put =
-riskFreeRate * strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(-d2);
const term3 =
dividendYield *
spotPrice *
Math.exp(-dividendYield * timeToExpiry) *
(optionType === 'call' ? nd1 : normalCDF(-d1));
const theta =
optionType === 'call' ? (term1 - term2Call + term3) / 365 : (term1 + term2Put + term3) / 365;
// Vega (same for calls and puts)
const vega =
(spotPrice * Math.exp(-dividendYield * timeToExpiry) * npd1 * Math.sqrt(timeToExpiry)) / 100;
// Rho
const callRho = (strikePrice * timeToExpiry * Math.exp(-riskFreeRate * timeToExpiry) * nd2) / 100;
const putRho =
(-strikePrice * timeToExpiry * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(-d2)) / 100;
const rho = optionType === 'call' ? callRho : putRho;
return {
delta,
gamma,
theta,
vega,
rho,
};
}
/**
* Calculate implied volatility using Newton-Raphson method
*/
export function calculateImpliedVolatility(
marketPrice: number,
spotPrice: number,
strikePrice: number,
timeToExpiry: number,
riskFreeRate: number,
optionType: 'call' | 'put' = 'call',
dividendYield: number = 0,
initialGuess: number = 0.2,
tolerance: number = 1e-6,
maxIterations: number = 100
): ImpliedVolatilityResult {
let volatility = initialGuess;
let iterations = 0;
let converged = false;
for (let i = 0; i < maxIterations; i++) {
iterations = i + 1;
const params: OptionParameters = {
spotPrice,
strikePrice,
timeToExpiry,
riskFreeRate,
volatility,
dividendYield,
};
const pricing = blackScholes(params);
const theoreticalPrice = optionType === 'call' ? pricing.callPrice : pricing.putPrice;
const priceDiff = theoreticalPrice - marketPrice;
if (Math.abs(priceDiff) < tolerance) {
converged = true;
break;
}
// Calculate vega for Newton-Raphson
const greeks = calculateGreeks(params, optionType);
const vega = greeks.vega * 100; // Convert back from percentage
if (Math.abs(vega) < 1e-10) {
break; // Avoid division by zero
}
volatility = volatility - priceDiff / vega;
// Keep volatility within reasonable bounds
volatility = Math.max(0.001, Math.min(volatility, 10));
}
return {
impliedVolatility: volatility,
iterations,
converged,
};
}
/**
* Binomial option pricing model
*/
export function binomialOptionPricing(
params: OptionParameters,
optionType: 'call' | 'put' = 'call',
americanStyle: boolean = false,
steps: number = 100
): OptionPricing {
const {
spotPrice,
strikePrice,
timeToExpiry,
riskFreeRate,
volatility,
dividendYield = 0,
} = params;
const dt = timeToExpiry / steps;
const u = Math.exp(volatility * Math.sqrt(dt));
const d = 1 / u;
const p = (Math.exp((riskFreeRate - dividendYield) * dt) - d) / (u - d);
const discount = Math.exp(-riskFreeRate * dt);
// Create price tree
const stockPrices: number[][] = [];
for (let i = 0; i <= steps; i++) {
stockPrices[i] = [];
for (let j = 0; j <= i; j++) {
stockPrices[i][j] = spotPrice * Math.pow(u, i - j) * Math.pow(d, j);
}
}
// Calculate option values at expiration
const optionValues: number[][] = [];
for (let i = 0; i <= steps; i++) {
optionValues[i] = [];
}
for (let j = 0; j <= steps; j++) {
if (optionType === 'call') {
optionValues[steps][j] = Math.max(stockPrices[steps][j] - strikePrice, 0);
} else {
optionValues[steps][j] = Math.max(strikePrice - stockPrices[steps][j], 0);
}
}
// Work backwards through the tree
for (let i = steps - 1; i >= 0; i--) {
for (let j = 0; j <= i; j++) {
// European option value
const holdValue =
discount * (p * optionValues[i + 1][j] + (1 - p) * optionValues[i + 1][j + 1]);
if (americanStyle) {
// American option - can exercise early
const exerciseValue =
optionType === 'call'
? Math.max(stockPrices[i][j] - strikePrice, 0)
: Math.max(strikePrice - stockPrices[i][j], 0);
optionValues[i][j] = Math.max(holdValue, exerciseValue);
} else {
optionValues[i][j] = holdValue;
}
}
}
const price = optionValues[0][0];
const intrinsicValue =
optionType === 'call'
? Math.max(spotPrice - strikePrice, 0)
: Math.max(strikePrice - spotPrice, 0);
const timeValue = price - intrinsicValue;
if (optionType === 'call') {
return {
callPrice: price,
putPrice: 0, // Not calculated
intrinsicValueCall: intrinsicValue,
intrinsicValuePut: 0,
timeValueCall: timeValue,
timeValuePut: 0,
};
} else {
return {
callPrice: 0, // Not calculated
putPrice: price,
intrinsicValueCall: 0,
intrinsicValuePut: intrinsicValue,
timeValueCall: 0,
timeValuePut: timeValue,
};
}
}
/**
* Monte Carlo option pricing
*/
export function monteCarloOptionPricing(
params: OptionParameters,
optionType: 'call' | 'put' = 'call',
numSimulations: number = 100000
): OptionPricing {
const {
spotPrice,
strikePrice,
timeToExpiry,
riskFreeRate,
volatility,
dividendYield = 0,
} = params;
let totalPayoff = 0;
for (let i = 0; i < numSimulations; i++) {
// Generate random price path
const z = boxMullerTransform();
const finalPrice =
spotPrice *
Math.exp(
(riskFreeRate - dividendYield - 0.5 * volatility * volatility) * timeToExpiry +
volatility * Math.sqrt(timeToExpiry) * z
);
// Calculate payoff
const payoff =
optionType === 'call'
? Math.max(finalPrice - strikePrice, 0)
: Math.max(strikePrice - finalPrice, 0);
totalPayoff += payoff;
}
const averagePayoff = totalPayoff / numSimulations;
const price = averagePayoff * Math.exp(-riskFreeRate * timeToExpiry);
const intrinsicValue =
optionType === 'call'
? Math.max(spotPrice - strikePrice, 0)
: Math.max(strikePrice - spotPrice, 0);
const timeValue = price - intrinsicValue;
if (optionType === 'call') {
return {
callPrice: price,
putPrice: 0,
intrinsicValueCall: intrinsicValue,
intrinsicValuePut: 0,
timeValueCall: timeValue,
timeValuePut: 0,
};
} else {
return {
callPrice: 0,
putPrice: price,
intrinsicValueCall: 0,
intrinsicValuePut: intrinsicValue,
timeValueCall: 0,
timeValuePut: timeValue,
};
}
}
/**
* Calculate option portfolio risk metrics
*/
export function calculateOptionPortfolioRisk(
positions: Array<{
optionType: 'call' | 'put';
quantity: number;
params: OptionParameters;
}>
): {
totalDelta: number;
totalGamma: number;
totalTheta: number;
totalVega: number;
totalRho: number;
portfolioValue: number;
} {
let totalDelta = 0;
let totalGamma = 0;
let totalTheta = 0;
let totalVega = 0;
let totalRho = 0;
let portfolioValue = 0;
for (const position of positions) {
const greeks = calculateGreeks(position.params, position.optionType);
const pricing = blackScholes(position.params);
const optionPrice = position.optionType === 'call' ? pricing.callPrice : pricing.putPrice;
totalDelta += greeks.delta * position.quantity;
totalGamma += greeks.gamma * position.quantity;
totalTheta += greeks.theta * position.quantity;
totalVega += greeks.vega * position.quantity;
totalRho += greeks.rho * position.quantity;
portfolioValue += optionPrice * position.quantity;
}
return {
totalDelta,
totalGamma,
totalTheta,
totalVega,
totalRho,
portfolioValue,
};
}
/**
* Volatility surface interpolation
*/
export function interpolateVolatilitySurface(
strikes: number[],
expiries: number[],
volatilities: number[][],
targetStrike: number,
targetExpiry: number
): number {
// Simplified bilinear interpolation
// In production, use more sophisticated interpolation methods
// Find surrounding points
let strikeIndex = 0;
let expiryIndex = 0;
for (let i = 0; i < strikes.length - 1; i++) {
if (targetStrike >= strikes[i] && targetStrike <= strikes[i + 1]) {
strikeIndex = i;
break;
}
}
for (let i = 0; i < expiries.length - 1; i++) {
if (targetExpiry >= expiries[i] && targetExpiry <= expiries[i + 1]) {
expiryIndex = i;
break;
}
}
// Bilinear interpolation
const x1 = strikes[strikeIndex];
const x2 = strikes[strikeIndex + 1];
const y1 = expiries[expiryIndex];
const y2 = expiries[expiryIndex + 1];
const q11 = volatilities[expiryIndex][strikeIndex];
const q12 = volatilities[expiryIndex + 1][strikeIndex];
const q21 = volatilities[expiryIndex][strikeIndex + 1];
const q22 = volatilities[expiryIndex + 1][strikeIndex + 1];
const wx = (targetStrike - x1) / (x2 - x1);
const wy = (targetExpiry - y1) / (y2 - y1);
return q11 * (1 - wx) * (1 - wy) + q21 * wx * (1 - wy) + q12 * (1 - wx) * wy + q22 * wx * wy;
}
// Helper functions
/**
* Normal cumulative distribution function
*/
function normalCDF(x: number): number {
return 0.5 * (1 + erf(x / Math.sqrt(2)));
}
/**
* Normal probability density function
*/
function normalPDF(x: number): number {
return Math.exp(-0.5 * x * x) / Math.sqrt(2 * Math.PI);
}
/**
* Error function approximation
*/
function erf(x: number): number {
// Abramowitz and Stegun approximation
const a1 = 0.254829592;
const a2 = -0.284496736;
const a3 = 1.421413741;
const a4 = -1.453152027;
const a5 = 1.061405429;
const p = 0.3275911;
const sign = x >= 0 ? 1 : -1;
x = Math.abs(x);
const t = 1.0 / (1.0 + p * x);
const y = 1.0 - ((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t * Math.exp(-x * x);
return sign * y;
}
/**
* Box-Muller transformation for normal random numbers
*/
function boxMullerTransform(): number {
let u1 = Math.random();
const u2 = Math.random();
// Ensure u1 is not zero
while (u1 === 0) {
u1 = Math.random();
}
return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
}
/**
* Prices a straddle option strategy
*/
export function straddle(params: OptionParameters): {
callPrice: number;
putPrice: number;
strategyCost: number;
} {
const callOption = blackScholes(params);
const putOption = blackScholes(params);
const strategyCost = callOption.callPrice + putOption.putPrice;
return {
callPrice: callOption.callPrice,
putPrice: putOption.putPrice,
strategyCost: strategyCost,
};
}
/**
* Prices a strangle option strategy
*/
export function strangle(
callParams: OptionParameters,
putParams: OptionParameters
): { callPrice: number; putPrice: number; strategyCost: number } {
const callOption = blackScholes(callParams);
const putOption = blackScholes(putParams);
const strategyCost = callOption.callPrice + putOption.putPrice;
return {
callPrice: callOption.callPrice,
putPrice: putOption.putPrice,
strategyCost: strategyCost,
};
}
/**
* Prices a butterfly option strategy
*/
export function butterfly(
lowerStrikeParams: OptionParameters,
middleStrikeParams: OptionParameters,
upperStrikeParams: OptionParameters
): {
lowerCallPrice: number;
middleCallPrice: number;
upperCallPrice: number;
strategyCost: number;
} {
const lowerCall = blackScholes(lowerStrikeParams);
const middleCall = blackScholes(middleStrikeParams);
const upperCall = blackScholes(upperStrikeParams);
const strategyCost = lowerCall.callPrice - 2 * middleCall.callPrice + upperCall.callPrice;
return {
lowerCallPrice: lowerCall.callPrice,
middleCallPrice: middleCall.callPrice,
upperCallPrice: upperCall.callPrice,
strategyCost: strategyCost,
};
}
/**
* Prices a condor option strategy
*/
export function condor(
lowerStrikeParams: OptionParameters,
middleLowerStrikeParams: OptionParameters,
middleUpperStrikeParams: OptionParameters,
upperStrikeParams: OptionParameters
): {
lowerCallPrice: number;
middleLowerCallPrice: number;
middleUpperCallPrice: number;
upperCallPrice: number;
strategyCost: number;
} {
const lowerCall = blackScholes(lowerStrikeParams);
const middleLowerCall = blackScholes(middleLowerStrikeParams);
const middleUpperCall = blackScholes(middleUpperStrikeParams);
const upperCall = blackScholes(upperStrikeParams);
const strategyCost =
lowerCall.callPrice -
middleLowerCall.callPrice -
middleUpperCall.callPrice +
upperCall.callPrice;
return {
lowerCallPrice: lowerCall.callPrice,
middleLowerCallPrice: middleLowerCall.callPrice,
middleUpperCallPrice: middleUpperCall.callPrice,
upperCallPrice: upperCall.callPrice,
strategyCost: strategyCost,
};
}
/**
* Calculates combined Greeks for an option strategy
*/
export function calculateStrategyGreeks(
positions: Array<{
optionType: 'call' | 'put';
quantity: number;
params: OptionParameters;
}>
): GreeksCalculation {
let totalDelta = 0;
let totalGamma = 0;
let totalTheta = 0;
let totalVega = 0;
let totalRho = 0;
for (const position of positions) {
const greeks = calculateGreeks(position.params, position.optionType);
totalDelta += greeks.delta * position.quantity;
totalGamma += greeks.gamma * position.quantity;
totalTheta += greeks.theta * position.quantity;
totalVega += greeks.vega * position.quantity;
totalRho += greeks.rho * position.quantity;
}
return {
delta: totalDelta,
gamma: totalGamma,
theta: totalTheta,
vega: totalVega,
rho: totalRho,
};
}
/**
* Black-Scholes option pricing model with greeks
*/
export function blackScholesWithGreeks(
params: OptionParameters,
optionType: 'call' | 'put' = 'call'
): { pricing: OptionPricing; greeks: GreeksCalculation } {
const pricing = blackScholes(params);
const greeks = calculateGreeks(params, optionType);
return { pricing, greeks };
}
/**
* Calculates the breakeven point for a call option at expiration
*/
export function callBreakeven(strikePrice: number, callPrice: number): number {
return strikePrice + callPrice;
}
/**
* Calculates the breakeven point for a put option at expiration
*/
export function putBreakeven(strikePrice: number, putPrice: number): number {
return strikePrice - putPrice;
}
/**
* Estimates the probability of profit for a call option at expiration
*/
export function callProbabilityOfProfit(
spotPrice: number,
strikePrice: number,
timeToExpiry: number,
riskFreeRate: number,
volatility: number
): number {
const d1 =
(Math.log(spotPrice / strikePrice) +
(riskFreeRate + 0.5 * volatility * volatility) * timeToExpiry) /
(volatility * Math.sqrt(timeToExpiry));
return normalCDF(d1);
}
/**
* Estimates the probability of profit for a put option at expiration
*/
export function putProbabilityOfProfit(
spotPrice: number,
strikePrice: number,
timeToExpiry: number,
riskFreeRate: number,
volatility: number
): number {
const d1 =
(Math.log(spotPrice / strikePrice) +
(riskFreeRate + 0.5 * volatility * volatility) * timeToExpiry) /
(volatility * Math.sqrt(timeToExpiry));
return 1 - normalCDF(d1);
}

View file

@ -1,940 +0,0 @@
import { ulcerIndex } from './risk-metrics';
/**
* Performance Metrics and Analysis
* Comprehensive performance measurement tools for trading strategies and portfolios
*/
// import type { PortfolioMetrics } from '@stock-bot/types';
// Define PortfolioMetrics locally until it's added to types library
export interface PortfolioMetrics {
totalValue: number;
totalReturn: number;
totalReturnPercent: number;
dailyReturn: number;
dailyReturnPercent: number;
maxDrawdown: number;
sharpeRatio: number;
beta: number;
alpha: number;
volatility: number;
}
export interface TradePerformance {
totalTrades: number;
winningTrades: number;
losingTrades: number;
winRate: number;
averageWin: number;
averageLoss: number;
largestWin: number;
largestLoss: number;
profitFactor: number;
expectancy: number;
averageTradeReturn: number;
consecutiveWins: number;
consecutiveLosses: number;
}
export interface DrawdownAnalysis {
maxDrawdown: number;
maxDrawdownDuration: number;
averageDrawdown: number;
drawdownPeriods: Array<{
start: Date;
end: Date;
duration: number;
magnitude: number;
}>;
}
export interface ReturnAnalysis {
totalReturn: number;
annualizedReturn: number;
compoundAnnualGrowthRate: number;
volatility: number;
annualizedVolatility: number;
skewness: number;
kurtosis: number;
bestMonth: number;
worstMonth: number;
positiveMonths: number;
negativeMonths: number;
}
/**
* Calculate comprehensive trade performance metrics
*/
export function analyzeTradePerformance(
trades: Array<{ pnl: number; date: Date }>
): TradePerformance {
if (trades.length === 0) {
return {
totalTrades: 0,
winningTrades: 0,
losingTrades: 0,
winRate: 0,
averageWin: 0,
averageLoss: 0,
largestWin: 0,
largestLoss: 0,
profitFactor: 0,
expectancy: 0,
averageTradeReturn: 0,
consecutiveWins: 0,
consecutiveLosses: 0,
};
}
const winningTrades = trades.filter(trade => trade.pnl > 0);
const losingTrades = trades.filter(trade => trade.pnl < 0);
const totalWins = winningTrades.reduce((sum, trade) => sum + trade.pnl, 0);
const totalLosses = Math.abs(losingTrades.reduce((sum, trade) => sum + trade.pnl, 0));
const averageWin = winningTrades.length > 0 ? totalWins / winningTrades.length : 0;
const averageLoss = losingTrades.length > 0 ? totalLosses / losingTrades.length : 0;
const largestWin = winningTrades.length > 0 ? Math.max(...winningTrades.map(t => t.pnl)) : 0;
const largestLoss = losingTrades.length > 0 ? Math.min(...losingTrades.map(t => t.pnl)) : 0;
const profitFactor = totalLosses > 0 ? totalWins / totalLosses : totalWins > 0 ? Infinity : 0;
const winRate = winningTrades.length / trades.length;
const expectancy = winRate * averageWin - (1 - winRate) * averageLoss;
const totalPnL = trades.reduce((sum, trade) => sum + trade.pnl, 0);
const averageTradeReturn = totalPnL / trades.length;
// Calculate consecutive wins/losses
let consecutiveWins = 0;
let consecutiveLosses = 0;
let currentWinStreak = 0;
let currentLossStreak = 0;
for (const trade of trades) {
if (trade.pnl > 0) {
currentWinStreak++;
currentLossStreak = 0;
consecutiveWins = Math.max(consecutiveWins, currentWinStreak);
} else if (trade.pnl < 0) {
currentLossStreak++;
currentWinStreak = 0;
consecutiveLosses = Math.max(consecutiveLosses, currentLossStreak);
}
}
return {
totalTrades: trades.length,
winningTrades: winningTrades.length,
losingTrades: losingTrades.length,
winRate,
averageWin,
averageLoss,
largestWin,
largestLoss,
profitFactor,
expectancy,
averageTradeReturn,
consecutiveWins,
consecutiveLosses,
};
}
/**
* Analyze drawdown characteristics
*/
export function analyzeDrawdowns(
equityCurve: Array<{ value: number; date: Date }>
): DrawdownAnalysis {
if (equityCurve.length < 2) {
return {
maxDrawdown: 0,
maxDrawdownDuration: 0,
averageDrawdown: 0,
drawdownPeriods: [],
};
}
const first = equityCurve[0];
if (!first) {
return { maxDrawdown: 0, maxDrawdownDuration: 0, averageDrawdown: 0, drawdownPeriods: [] };
}
let peak = first.value;
let peakDate = first.date;
let maxDrawdown = 0;
let maxDrawdownDuration = 0;
const drawdownPeriods: Array<{
start: Date;
end: Date;
duration: number;
magnitude: number;
}> = [];
let currentDrawdownStart: Date | null = null;
const drawdowns: number[] = [];
for (let i = 1; i < equityCurve.length; i++) {
const current = equityCurve[i];
if (!current) {
continue;
}
if (current.value > peak) {
// New peak - end any current drawdown
if (currentDrawdownStart) {
const prev = equityCurve[i - 1];
if (!prev) {
continue;
}
const drawdownMagnitude = (peak - prev.value) / peak;
const duration = Math.floor(
(prev.date.getTime() - currentDrawdownStart.getTime()) / (1000 * 60 * 60 * 24)
);
drawdownPeriods.push({
start: currentDrawdownStart,
end: prev.date,
duration,
magnitude: drawdownMagnitude,
});
drawdowns.push(drawdownMagnitude);
maxDrawdownDuration = Math.max(maxDrawdownDuration, duration);
currentDrawdownStart = null;
}
peak = current.value;
peakDate = current.date;
} else {
// In drawdown
if (!currentDrawdownStart) {
currentDrawdownStart = peakDate;
}
const drawdown = (peak - current.value) / peak;
maxDrawdown = Math.max(maxDrawdown, drawdown);
}
}
// Handle ongoing drawdown
if (currentDrawdownStart) {
const lastPoint = equityCurve[equityCurve.length - 1];
if (!lastPoint) {
return { maxDrawdown, maxDrawdownDuration, averageDrawdown: 0, drawdownPeriods };
}
const drawdownMagnitude = (peak - lastPoint.value) / peak;
const duration = Math.floor(
(lastPoint.date.getTime() - currentDrawdownStart.getTime()) / (1000 * 60 * 60 * 24)
);
drawdownPeriods.push({
start: currentDrawdownStart,
end: lastPoint.date,
duration,
magnitude: drawdownMagnitude,
});
drawdowns.push(drawdownMagnitude);
maxDrawdownDuration = Math.max(maxDrawdownDuration, duration);
}
const averageDrawdown =
drawdowns.length > 0 ? drawdowns.reduce((sum, dd) => sum + dd, 0) / drawdowns.length : 0;
return {
maxDrawdown,
maxDrawdownDuration,
averageDrawdown,
drawdownPeriods,
};
}
/**
* Analyze return characteristics
*/
export function analyzeReturns(
returns: Array<{ return: number; date: Date }>,
periodsPerYear: number = 252
): ReturnAnalysis {
if (returns.length === 0) {
return {
totalReturn: 0,
annualizedReturn: 0,
compoundAnnualGrowthRate: 0,
volatility: 0,
annualizedVolatility: 0,
skewness: 0,
kurtosis: 0,
bestMonth: 0,
worstMonth: 0,
positiveMonths: 0,
negativeMonths: 0,
};
}
const returnValues = returns.map(r => r.return);
// Calculate basic statistics
const totalReturn = returnValues.reduce((product, ret) => product * (1 + ret), 1) - 1;
const averageReturn = returnValues.reduce((sum, ret) => sum + ret, 0) / returnValues.length;
const annualizedReturn = Math.pow(1 + averageReturn, periodsPerYear) - 1;
// Calculate CAGR
const years = returns.length / periodsPerYear;
const cagr = years > 0 ? Math.pow(1 + totalReturn, 1 / years) - 1 : 0;
// Calculate volatility
const variance =
returnValues.reduce((sum, ret) => sum + Math.pow(ret - averageReturn, 2), 0) /
(returnValues.length - 1);
const volatility = Math.sqrt(variance);
const annualizedVolatility = volatility * Math.sqrt(periodsPerYear);
// Calculate skewness and kurtosis
const skewness = calculateSkewness(returnValues);
const kurtosis = calculateKurtosis(returnValues);
// Monthly analysis
const monthlyReturns = aggregateMonthlyReturns(returns);
const bestMonth = monthlyReturns.length > 0 ? Math.max(...monthlyReturns) : 0;
const worstMonth = monthlyReturns.length > 0 ? Math.min(...monthlyReturns) : 0;
const positiveMonths = monthlyReturns.filter(ret => ret > 0).length;
const negativeMonths = monthlyReturns.filter(ret => ret < 0).length;
return {
totalReturn,
annualizedReturn,
compoundAnnualGrowthRate: cagr,
volatility,
annualizedVolatility,
skewness,
kurtosis,
bestMonth,
worstMonth,
positiveMonths,
negativeMonths,
};
}
/**
* Calculate rolling performance metrics
*/
export function calculateRollingMetrics(
returns: number[],
windowSize: number,
metricType: 'sharpe' | 'volatility' | 'return' = 'sharpe'
): number[] {
if (returns.length < windowSize) {
return [];
}
const rollingMetrics: number[] = [];
for (let i = windowSize - 1; i < returns.length; i++) {
const window = returns.slice(i - windowSize + 1, i + 1);
switch (metricType) {
case 'sharpe':
rollingMetrics.push(calculateSharpeRatio(window));
break;
case 'volatility':
rollingMetrics.push(calculateVolatility(window));
break;
case 'return': {
const avgReturn = window.reduce((sum, ret) => sum + ret, 0) / window.length;
rollingMetrics.push(avgReturn);
break;
}
}
}
return rollingMetrics;
}
/**
* Calculate performance attribution
*/
export function strategyPerformanceAttribution(
portfolioReturns: number[],
benchmarkReturns: number[],
sectorWeights: number[],
sectorReturns: number[]
): {
allocationEffect: number;
selectionEffect: number;
interactionEffect: number;
totalActiveReturn: number;
} {
if (portfolioReturns.length !== benchmarkReturns.length) {
throw new Error('Portfolio and benchmark returns must have same length');
}
const portfolioReturn =
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
const benchmarkReturn =
benchmarkReturns.reduce((sum, ret) => sum + ret, 0) / benchmarkReturns.length;
let allocationEffect = 0;
let selectionEffect = 0;
let interactionEffect = 0;
for (let i = 0; i < sectorWeights.length; i++) {
const portfolioWeight = sectorWeights[i];
const sectorReturn = sectorReturns[i];
if (portfolioWeight === undefined || sectorReturn === undefined) {
continue;
}
const benchmarkWeight = 1 / sectorWeights.length; // Assuming equal benchmark weights
// Allocation effect: (portfolio weight - benchmark weight) * (benchmark sector return - benchmark return)
allocationEffect += (portfolioWeight - benchmarkWeight) * (sectorReturn - benchmarkReturn);
// Selection effect: benchmark weight * (portfolio sector return - benchmark sector return)
selectionEffect += benchmarkWeight * (sectorReturn - sectorReturn); // Simplified
// Interaction effect: (portfolio weight - benchmark weight) * (portfolio sector return - benchmark sector return)
interactionEffect += (portfolioWeight - benchmarkWeight) * (sectorReturn - sectorReturn); // Simplified
}
const totalActiveReturn = portfolioReturn - benchmarkReturn;
return {
allocationEffect,
selectionEffect,
interactionEffect,
totalActiveReturn,
};
}
/**
* Calculate Omega ratio
*/
export function omegaRatio(returns: number[], threshold: number = 0): number {
if (returns.length === 0) {
return 0;
}
const gains = returns
.filter(ret => ret > threshold)
.reduce((sum, ret) => sum + (ret - threshold), 0);
const losses = returns
.filter(ret => ret < threshold)
.reduce((sum, ret) => sum + Math.abs(ret - threshold), 0);
return losses === 0 ? Infinity : gains / losses;
}
/**
* Calculate gain-to-pain ratio
*/
export function gainToPainRatio(returns: number[]): number {
if (returns.length === 0) {
return 0;
}
const totalGain = returns.reduce((sum, ret) => sum + ret, 0);
const totalPain = returns.filter(ret => ret < 0).reduce((sum, ret) => sum + Math.abs(ret), 0);
return totalPain === 0 ? (totalGain > 0 ? Infinity : 0) : totalGain / totalPain;
}
/**
* Calculate Martin ratio (modified Sharpe with downside deviation)
*/
export function martinRatio(returns: number[], riskFreeRate: number = 0): number {
if (returns.length === 0) {
return 0;
}
const averageReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const downsideReturns = returns.filter(ret => ret < riskFreeRate);
if (downsideReturns.length === 0) {
return Infinity;
}
const downsideDeviation = Math.sqrt(
downsideReturns.reduce((sum, ret) => sum + Math.pow(ret - riskFreeRate, 2), 0) / returns.length
);
return downsideDeviation === 0 ? Infinity : (averageReturn - riskFreeRate) / downsideDeviation;
}
/**
* Calculate comprehensive portfolio metrics
*/
export function calculateStrategyMetrics(
equityCurve: Array<{ value: number; date: Date }>,
benchmarkReturns?: number[],
riskFreeRate: number = 0.02
): PortfolioMetrics {
if (equityCurve.length < 2) {
return {
totalValue: 0,
totalReturn: 0,
totalReturnPercent: 0,
dailyReturn: 0,
dailyReturnPercent: 0,
maxDrawdown: 0,
sharpeRatio: 0,
beta: 0,
alpha: 0,
volatility: 0,
};
}
const returns = [];
for (let i = 1; i < equityCurve.length; i++) {
const current = equityCurve[i];
const previous = equityCurve[i - 1];
if (!current || !previous) {
continue;
}
const ret = (current.value - previous.value) / previous.value;
returns.push(ret);
}
const lastPoint = equityCurve[equityCurve.length - 1];
const firstPoint = equityCurve[0];
if (!lastPoint || !firstPoint) {
return {
totalValue: 0,
totalReturn: 0,
totalReturnPercent: 0,
dailyReturn: 0,
dailyReturnPercent: 0,
maxDrawdown: 0,
sharpeRatio: 0,
beta: 0,
alpha: 0,
volatility: 0,
};
}
const totalValue = lastPoint.value;
const totalReturn = totalValue - firstPoint.value;
const totalReturnPercent = (totalReturn / firstPoint.value) * 100;
const dailyReturn = returns[returns.length - 1] || 0;
const dailyReturnPercent = dailyReturn * 100;
const maxDrawdown = analyzeDrawdowns(equityCurve).maxDrawdown;
const sharpeRatio = calculateSharpeRatio(returns, riskFreeRate);
const volatility = calculateVolatility(returns);
let beta = 0;
let alpha = 0;
if (benchmarkReturns && benchmarkReturns.length === returns.length) {
beta = calculateBeta(returns, benchmarkReturns);
alpha = calculateAlpha(returns, benchmarkReturns, riskFreeRate);
}
return {
totalValue,
totalReturn,
totalReturnPercent,
dailyReturn,
dailyReturnPercent,
maxDrawdown,
sharpeRatio,
beta,
alpha,
volatility,
};
}
/**
* Calculate Calmar Ratio
*/
export function calmarRatio(
returns: number[],
equityCurve: Array<{ value: number; date: Date }>,
riskFreeRate: number = 0
): number {
const maxDrawdown = analyzeDrawdowns(equityCurve).maxDrawdown;
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
return maxDrawdown === 0 ? 0 : (avgReturn - riskFreeRate) / maxDrawdown;
}
/**
* Calculate Sterling Ratio
*/
export function sterlingRatio(
returns: number[],
equityCurve: Array<{ value: number; date: Date }>,
riskFreeRate: number = 0
): number {
const averageDrawdown = analyzeDrawdowns(equityCurve).averageDrawdown;
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
return averageDrawdown === 0 ? 0 : (avgReturn - riskFreeRate) / averageDrawdown;
}
/**
* Calculate Information Ratio
*/
export function informationRatio(portfolioReturns: number[], benchmarkReturns: number[]): number {
if (portfolioReturns.length !== benchmarkReturns.length) {
throw new Error('Portfolio and benchmark returns must have the same length.');
}
const excessReturns = portfolioReturns.map((portfolioReturn, index) => {
const benchmark = benchmarkReturns[index];
return benchmark !== undefined ? portfolioReturn - benchmark : 0;
});
const trackingError = calculateVolatility(excessReturns);
const avgExcessReturn = excessReturns.reduce((sum, ret) => sum + ret, 0) / excessReturns.length;
return trackingError === 0 ? 0 : avgExcessReturn / trackingError;
}
// Treynor Ratio is already exported from risk-metrics
/**
* Calculate Jensen's Alpha (same as Alpha, but included for clarity)
*/
export function jensensAlpha(
portfolioReturns: number[],
marketReturns: number[],
riskFreeRate: number
): number {
return calculateAlpha(portfolioReturns, marketReturns, riskFreeRate);
}
/**
* Calculate Capture Ratio (Up Capture and Down Capture)
*/
export function captureRatio(
portfolioReturns: number[],
benchmarkReturns: number[]
): { upCaptureRatio: number; downCaptureRatio: number } {
let upCapture = 0;
let downCapture = 0;
let upMarketPeriods = 0;
let downMarketPeriods = 0;
for (let i = 0; i < portfolioReturns.length; i++) {
const benchmarkReturn = benchmarkReturns[i];
const portfolioReturn = portfolioReturns[i];
if (benchmarkReturn === undefined || portfolioReturn === undefined) {
continue;
}
if (benchmarkReturn > 0) {
upCapture += portfolioReturn;
upMarketPeriods++;
} else if (benchmarkReturn < 0) {
downCapture += portfolioReturn;
downMarketPeriods++;
}
}
const upCaptureRatio =
upMarketPeriods > 0
? upCapture /
upMarketPeriods /
(benchmarkReturns.filter(r => r > 0).reduce((sum, r) => sum + r, 0) / upMarketPeriods)
: 0;
const downCaptureRatio =
downMarketPeriods > 0
? downCapture /
downMarketPeriods /
(benchmarkReturns.filter(r => r < 0).reduce((sum, r) => sum + r, 0) / downMarketPeriods)
: 0;
return { upCaptureRatio, downCaptureRatio };
}
/**
* Calculate Sortino Ratio
*/
export function sortinoRatio(returns: number[], riskFreeRate: number = 0): number {
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const downsideReturns = returns.filter(ret => ret < riskFreeRate);
const downsideDeviation = Math.sqrt(
downsideReturns.reduce((sum, ret) => sum + Math.pow(ret - riskFreeRate, 2), 0) / returns.length
);
return downsideDeviation === 0 ? 0 : (avgReturn - riskFreeRate) / downsideDeviation;
}
/**
* Calculate Tail Ratio
*/
export function tailRatio(returns: number[], tailPercent: number = 0.1): number {
const numReturns = returns.length;
const tailSize = Math.floor(numReturns * tailPercent);
if (tailSize === 0) {
return 0;
}
const sortedReturns = [...returns].sort((a, b) => a - b);
const worstTail = sortedReturns.slice(0, tailSize);
const bestTail = sortedReturns.slice(numReturns - tailSize);
const avgWorst = worstTail.reduce((sum, ret) => sum + ret, 0) / tailSize;
const avgBest = bestTail.reduce((sum, ret) => sum + ret, 0) / tailSize;
return avgWorst === 0 ? 0 : avgBest / Math.abs(avgWorst);
}
/**
* Calculate Rolling Beta
*/
export function calculateRollingBeta(
portfolioReturns: number[],
marketReturns: number[],
windowSize: number
): number[] {
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < windowSize) {
return [];
}
const rollingBetas: number[] = [];
for (let i = windowSize; i <= portfolioReturns.length; i++) {
const portfolioWindow = portfolioReturns.slice(i - windowSize, i);
const marketWindow = marketReturns.slice(i - windowSize, i);
rollingBetas.push(calculateBeta(portfolioWindow, marketWindow));
}
return rollingBetas;
}
/**
* Calculate Ulcer Performance Index (UPI)
*/
export function ulcerPerformanceIndex(
returns: number[],
equityCurve: Array<{ value: number; date: Date }>,
riskFreeRate: number = 0
): number {
const ui = ulcerIndex(equityCurve);
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
return ui === 0 ? 0 : (avgReturn - riskFreeRate) / ui;
}
/**
* Calculate Rolling Alpha
*/
export function calculateRollingAlpha(
portfolioReturns: number[],
marketReturns: number[],
riskFreeRate: number,
windowSize: number
): number[] {
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < windowSize) {
return [];
}
const rollingAlphas: number[] = [];
for (let i = windowSize; i <= portfolioReturns.length; i++) {
const portfolioWindow = portfolioReturns.slice(i - windowSize, i);
const marketWindow = marketReturns.slice(i - windowSize, i);
rollingAlphas.push(calculateAlpha(portfolioWindow, marketWindow, riskFreeRate));
}
return rollingAlphas;
}
/**
* Calculate Time Weighted Rate of Return (TWRR)
*/
export function timeWeightedRateOfReturn(
cashFlows: Array<{ amount: number; date: Date; value: number }>
): number {
if (cashFlows.length < 2) {
return 0;
}
const first = cashFlows[0];
if (!first) {
return 0;
}
let totalReturn = 1;
let previousValue = first.value;
for (let i = 1; i < cashFlows.length; i++) {
const current = cashFlows[i];
if (!current) {
continue;
}
const periodReturn =
(current.value - previousValue - current.amount) / (previousValue + current.amount);
totalReturn *= 1 + periodReturn;
previousValue = current.value;
}
return totalReturn - 1;
}
/**
* Calculate Money Weighted Rate of Return (MWRR) - Approximation using IRR
*/
export function moneyWeightedRateOfReturn(
cashFlows: Array<{ amount: number; date: Date; value: number }>
): number {
if (cashFlows.length === 0) {
return 0;
}
const first = cashFlows[0];
if (!first) {
return 0;
}
// Approximate MWRR using Internal Rate of Return (IRR)
// This requires a numerical method or library for accurate IRR calculation
// This is a simplified example and may not be accurate for all cases
let totalCashFlow = 0;
let totalWeightedCashFlow = 0;
const startDate = first.date.getTime();
for (const cf of cashFlows) {
const timeDiff = (cf.date.getTime() - startDate) / (1000 * 60 * 60 * 24 * 365); // Years
totalCashFlow += cf.amount;
totalWeightedCashFlow += cf.amount * timeDiff;
}
// Simplified approximation: MWRR ≈ totalCashFlow / totalWeightedCashFlow - 1
return totalWeightedCashFlow === 0 ? 0 : totalCashFlow / totalWeightedCashFlow - 1;
}
// Helper functions
function calculateSharpeRatio(returns: number[], riskFreeRate: number = 0): number {
if (returns.length < 2) {
return 0;
}
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance =
returns.reduce((sum, ret) => sum + Math.pow(ret - avgReturn, 2), 0) / (returns.length - 1);
const stdDev = Math.sqrt(variance);
return stdDev === 0 ? 0 : (avgReturn - riskFreeRate) / stdDev;
}
function calculateVolatility(returns: number[]): number {
if (returns.length < 2) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance =
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
return Math.sqrt(variance);
}
function calculateBeta(portfolioReturns: number[], marketReturns: number[]): number {
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < 2) {
return 0;
}
const portfolioMean =
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length;
let covariance = 0;
let marketVariance = 0;
for (let i = 0; i < portfolioReturns.length; i++) {
const portfolioReturn = portfolioReturns[i];
const marketReturn = marketReturns[i];
if (portfolioReturn === undefined || marketReturn === undefined) {
continue;
}
const portfolioDiff = portfolioReturn - portfolioMean;
const marketDiff = marketReturn - marketMean;
covariance += portfolioDiff * marketDiff;
marketVariance += marketDiff * marketDiff;
}
covariance /= portfolioReturns.length - 1;
marketVariance /= marketReturns.length - 1;
return marketVariance === 0 ? 0 : covariance / marketVariance;
}
function calculateAlpha(
portfolioReturns: number[],
marketReturns: number[],
riskFreeRate: number
): number {
const portfolioMean =
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length;
const beta = calculateBeta(portfolioReturns, marketReturns);
return portfolioMean - (riskFreeRate + beta * (marketMean - riskFreeRate));
}
function calculateSkewness(returns: number[]): number {
if (returns.length < 3) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
return 0;
}
const skew =
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 3), 0) / returns.length;
return skew;
}
function calculateKurtosis(returns: number[]): number {
if (returns.length < 4) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
return 0;
}
const kurt =
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 4), 0) / returns.length;
return kurt - 3; // Excess kurtosis
}
function aggregateMonthlyReturns(returns: Array<{ return: number; date: Date }>): number[] {
const monthlyReturns: { [key: string]: number } = {};
for (const ret of returns) {
const monthKey = `${ret.date.getFullYear()}-${ret.date.getMonth()}`;
if (!monthlyReturns[monthKey]) {
monthlyReturns[monthKey] = 1;
}
monthlyReturns[monthKey] *= 1 + ret.return;
}
return Object.values(monthlyReturns).map(cumReturn => cumReturn - 1);
}

View file

@ -1,592 +0,0 @@
/**
* Portfolio Analytics
* Advanced portfolio analysis and optimization tools
*/
import { OHLCVData, PriceData } from './index';
export interface PortfolioPosition {
symbol: string;
shares: number;
price: number;
value: number;
weight: number;
}
export interface PortfolioAnalysis {
totalValue: number;
totalReturn: number;
volatility: number;
sharpeRatio: number;
maxDrawdown: number;
var95: number;
beta: number;
alpha: number;
treynorRatio: number;
informationRatio: number;
trackingError: number;
}
export interface AssetAllocation {
symbol: string;
targetWeight: number;
currentWeight: number;
difference: number;
rebalanceAmount: number;
}
export interface PortfolioOptimizationResult {
weights: number[];
expectedReturn: number;
volatility: number;
sharpeRatio: number;
symbols: string[];
}
/**
* Calculate portfolio value and weights
*/
export function calculatePortfolioMetrics(positions: PortfolioPosition[]): {
totalValue: number;
weights: number[];
concentrationRisk: number;
} {
const totalValue = positions.reduce((sum, pos) => sum + pos.value, 0);
const weights = positions.map(pos => pos.value / totalValue);
// Calculate Herfindahl-Hirschman Index for concentration risk
const concentrationRisk = weights.reduce((sum, weight) => sum + weight * weight, 0);
return {
totalValue,
weights,
concentrationRisk,
};
}
/**
* Calculate portfolio returns from position returns
*/
export function calculatePortfolioReturns(assetReturns: number[][], weights: number[]): number[] {
if (assetReturns.length === 0 || weights.length !== assetReturns[0].length) {
return [];
}
const portfolioReturns: number[] = [];
for (let i = 0; i < assetReturns.length; i++) {
let portfolioReturn = 0;
for (let j = 0; j < weights.length; j++) {
portfolioReturn += weights[j] * assetReturns[i][j];
}
portfolioReturns.push(portfolioReturn);
}
return portfolioReturns;
}
/**
* Mean-Variance Optimization (Markowitz)
*/
export function markowitzOptimization(
expectedReturns: number[],
covarianceMatrix: number[][],
riskFreeRate: number = 0.02,
riskAversion: number = 1
): PortfolioOptimizationResult {
const n = expectedReturns.length;
// Simplified optimization using equal weights as baseline
// In production, use proper quadratic programming solver
const weights = new Array(n).fill(1 / n);
const expectedReturn = weights.reduce((sum, weight, i) => sum + weight * expectedReturns[i], 0);
// Calculate portfolio variance
let portfolioVariance = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
portfolioVariance += weights[i] * weights[j] * covarianceMatrix[i][j];
}
}
const volatility = Math.sqrt(portfolioVariance);
const sharpeRatio = volatility > 0 ? (expectedReturn - riskFreeRate) / volatility : 0;
return {
weights,
expectedReturn,
volatility,
sharpeRatio,
symbols: [], // Would be filled with actual symbols
};
}
/**
* Black-Litterman Model
*/
export function blackLittermanOptimization(
marketCaps: number[],
covarianceMatrix: number[][],
views: Array<{ assets: number[]; expectedReturn: number; confidence: number }>,
riskAversion: number = 3,
riskFreeRate: number = 0.02
): PortfolioOptimizationResult {
const n = marketCaps.length;
// Calculate market weights
const totalMarketCap = marketCaps.reduce((sum, cap) => sum + cap, 0);
const marketWeights = marketCaps.map(cap => cap / totalMarketCap);
// Implied equilibrium returns
const equilibriumReturns: number[] = [];
for (let i = 0; i < n; i++) {
let equilibriumReturn = 0;
for (let j = 0; j < n; j++) {
equilibriumReturn += riskAversion * covarianceMatrix[i][j] * marketWeights[j];
}
equilibriumReturns.push(equilibriumReturn);
}
// Simplified BL implementation - in production use proper matrix operations
const weights = [...marketWeights]; // Start with market weights
const expectedReturn = weights.reduce(
(sum, weight, i) => sum + weight * equilibriumReturns[i],
0
);
let portfolioVariance = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
portfolioVariance += weights[i] * weights[j] * covarianceMatrix[i][j];
}
}
const volatility = Math.sqrt(portfolioVariance);
const sharpeRatio = volatility > 0 ? (expectedReturn - riskFreeRate) / volatility : 0;
return {
weights,
expectedReturn,
volatility,
sharpeRatio,
symbols: [],
};
}
/**
* Risk Parity Portfolio
*/
export function riskParityOptimization(covarianceMatrix: number[][]): PortfolioOptimizationResult {
const n = covarianceMatrix.length;
// Start with equal weights
let weights = new Array(n).fill(1 / n);
// Iterative optimization for equal risk contribution
const maxIterations = 100;
const tolerance = 1e-8;
for (let iter = 0; iter < maxIterations; iter++) {
const riskContributions = calculateRiskContributions(weights, covarianceMatrix);
const totalRisk = Math.sqrt(calculatePortfolioVariance(weights, covarianceMatrix));
const targetRiskContribution = totalRisk / n;
let converged = true;
const newWeights = [...weights];
for (let i = 0; i < n; i++) {
const diff = riskContributions[i] - targetRiskContribution;
if (Math.abs(diff) > tolerance) {
converged = false;
// Simple adjustment - in production use proper optimization
newWeights[i] *= 1 - (diff / totalRisk) * 0.1;
}
}
// Normalize weights
const sum = newWeights.reduce((s, w) => s + w, 0);
weights = newWeights.map(w => w / sum);
if (converged) {
break;
}
}
const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix);
const volatility = Math.sqrt(portfolioVariance);
return {
weights,
expectedReturn: 0, // Not calculated for risk parity
volatility,
sharpeRatio: 0,
symbols: [],
};
}
/**
* Calculate risk contributions for each asset
*/
export function calculateRiskContributions(
weights: number[],
covarianceMatrix: number[][]
): number[] {
const n = weights.length;
const riskContributions: number[] = [];
const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix);
const portfolioVolatility = Math.sqrt(portfolioVariance);
for (let i = 0; i < n; i++) {
let marginalContribution = 0;
for (let j = 0; j < n; j++) {
marginalContribution += weights[j] * covarianceMatrix[i][j];
}
const riskContribution = (weights[i] * marginalContribution) / portfolioVolatility;
riskContributions.push(riskContribution);
}
return riskContributions;
}
/**
* Calculate portfolio variance
*/
export function calculatePortfolioVariance(
weights: number[],
covarianceMatrix: number[][]
): number {
const n = weights.length;
let variance = 0;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
variance += weights[i] * weights[j] * covarianceMatrix[i][j];
}
}
return variance;
}
/**
* Portfolio rebalancing analysis
*/
export function calculateRebalancing(
currentPositions: PortfolioPosition[],
targetWeights: number[],
totalValue: number
): AssetAllocation[] {
if (currentPositions.length !== targetWeights.length) {
throw new Error('Number of positions must match number of target weights');
}
return currentPositions.map((position, index) => {
const currentWeight = position.value / totalValue;
const targetWeight = targetWeights[index];
const difference = targetWeight - currentWeight;
const rebalanceAmount = difference * totalValue;
return {
symbol: position.symbol,
targetWeight,
currentWeight,
difference,
rebalanceAmount,
};
});
}
/**
* Factor model analysis (Fama-French)
*/
export function famaFrenchAnalysis(
portfolioReturns: number[],
marketReturns: number[],
smbReturns: number[], // Small minus Big
hmlReturns: number[], // High minus Low
riskFreeRate: number = 0.02
): {
alpha: number;
marketBeta: number;
sizeBeta: number;
valueBeta: number;
rSquared: number;
} {
const n = portfolioReturns.length;
// Excess returns
const excessPortfolioReturns = portfolioReturns.map(r => r - riskFreeRate);
const excessMarketReturns = marketReturns.map(r => r - riskFreeRate);
// Simple linear regression (in production, use proper multiple regression)
const meanExcessPortfolio = excessPortfolioReturns.reduce((sum, r) => sum + r, 0) / n;
const meanExcessMarket = excessMarketReturns.reduce((sum, r) => sum + r, 0) / n;
const meanSMB = smbReturns.reduce((sum, r) => sum + r, 0) / n;
const meanHML = hmlReturns.reduce((sum, r) => sum + r, 0) / n;
// Calculate market beta
let covariance = 0;
let marketVariance = 0;
for (let i = 0; i < n; i++) {
const portfolioDiff = excessPortfolioReturns[i] - meanExcessPortfolio;
const marketDiff = excessMarketReturns[i] - meanExcessMarket;
covariance += portfolioDiff * marketDiff;
marketVariance += marketDiff * marketDiff;
}
const marketBeta = marketVariance > 0 ? covariance / marketVariance : 0;
const alpha = meanExcessPortfolio - marketBeta * meanExcessMarket;
return {
alpha,
marketBeta,
sizeBeta: 0, // Simplified - would need proper regression
valueBeta: 0, // Simplified - would need proper regression
rSquared: 0, // Simplified - would need proper regression
};
}
/**
* Portfolio performance attribution
*/
export function performanceAttribution(
portfolioReturns: number[],
benchmarkReturns: number[],
sectorWeights: number[][],
sectorReturns: number[][]
): {
totalActiveReturn: number;
allocationEffect: number;
selectionEffect: number;
interactionEffect: number;
} {
const n = portfolioReturns.length;
const portfolioReturn = portfolioReturns.reduce((sum, r) => sum + r, 0) / n;
const benchmarkReturn = benchmarkReturns.reduce((sum, r) => sum + r, 0) / n;
const totalActiveReturn = portfolioReturn - benchmarkReturn;
// Simplified attribution analysis
let allocationEffect = 0;
let selectionEffect = 0;
let interactionEffect = 0;
// This would require proper implementation with sector-level analysis
// For now, return the total active return distributed equally
allocationEffect = totalActiveReturn * 0.4;
selectionEffect = totalActiveReturn * 0.4;
interactionEffect = totalActiveReturn * 0.2;
return {
totalActiveReturn,
allocationEffect,
selectionEffect,
interactionEffect,
};
}
/**
* Calculate Efficient Frontier points
*/
export function calculateEfficientFrontier(
returns: number[][], // Array of return series for each asset
symbols: string[],
riskFreeRate: number = 0.02,
numPoints: number = 50
): Array<{
weights: number[];
expectedReturn: number;
volatility: number;
sharpeRatio: number;
}> {
if (returns.length !== symbols.length || returns.length < 2) {
return [];
}
const n = returns.length;
const results: Array<{
weights: number[];
expectedReturn: number;
volatility: number;
sharpeRatio: number;
}> = [];
// Calculate expected returns and covariance matrix
const expectedReturns = returns.map(
assetReturns => assetReturns.reduce((sum, ret) => sum + ret, 0) / assetReturns.length
);
const covarianceMatrix = calculateCovarianceMatrix(returns);
// Generate target returns from min to max expected return
const minReturn = Math.min(...expectedReturns);
const maxReturn = Math.max(...expectedReturns);
const returnStep = (maxReturn - minReturn) / (numPoints - 1);
for (let i = 0; i < numPoints; i++) {
const targetReturn = minReturn + i * returnStep;
// Find minimum variance portfolio for target return using quadratic programming (simplified)
const weights = findMinimumVarianceWeights(expectedReturns, covarianceMatrix, targetReturn);
if (weights && weights.length === n) {
const portfolioReturn = weights.reduce((sum, w, j) => sum + w * expectedReturns[j], 0);
const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix);
const portfolioVolatility = Math.sqrt(portfolioVariance);
const sharpeRatio =
portfolioVolatility > 0 ? (portfolioReturn - riskFreeRate) / portfolioVolatility : 0;
results.push({
weights,
expectedReturn: portfolioReturn,
volatility: portfolioVolatility,
sharpeRatio,
});
}
}
return results.sort((a, b) => a.volatility - b.volatility);
}
/**
* Find Minimum Variance Portfolio
*/
export function findMinimumVariancePortfolio(
returns: number[][],
symbols: string[]
): PortfolioOptimizationResult | null {
if (returns.length !== symbols.length || returns.length < 2) {
return null;
}
const covarianceMatrix = calculateCovarianceMatrix(returns);
const n = returns.length;
// For minimum variance portfolio: w = (Σ^-1 * 1) / (1' * Σ^-1 * 1)
// Simplified implementation using equal weights as starting point
const weights = new Array(n).fill(1 / n);
// Iterative optimization (simplified)
for (let iter = 0; iter < 100; iter++) {
const gradient = calculateVarianceGradient(weights, covarianceMatrix);
const stepSize = 0.01;
// Update weights
for (let i = 0; i < n; i++) {
weights[i] -= stepSize * gradient[i];
}
// Normalize weights to sum to 1
const weightSum = weights.reduce((sum, w) => sum + w, 0);
for (let i = 0; i < n; i++) {
weights[i] = Math.max(0, weights[i] / weightSum);
}
}
const expectedReturns = returns.map(
assetReturns => assetReturns.reduce((sum, ret) => sum + ret, 0) / assetReturns.length
);
const portfolioReturn = weights.reduce((sum, w, i) => sum + w * expectedReturns[i], 0);
const portfolioVariance = calculatePortfolioVariance(weights, covarianceMatrix);
const portfolioVolatility = Math.sqrt(portfolioVariance);
const sharpeRatio = portfolioVolatility > 0 ? portfolioReturn / portfolioVolatility : 0;
return {
weights,
expectedReturn: portfolioReturn,
volatility: portfolioVolatility,
sharpeRatio,
symbols,
};
}
// Helper functions for portfolio optimization
function calculateCovarianceMatrix(returns: number[][]): number[][] {
const n = returns.length;
const matrix: number[][] = [];
for (let i = 0; i < n; i++) {
matrix[i] = [];
for (let j = 0; j < n; j++) {
matrix[i][j] = calculateCovariance(returns[i], returns[j]);
}
}
return matrix;
}
function calculateCovariance(x: number[], y: number[]): number {
if (x.length !== y.length || x.length < 2) {
return 0;
}
const n = x.length;
const meanX = x.reduce((sum, val) => sum + val, 0) / n;
const meanY = y.reduce((sum, val) => sum + val, 0) / n;
return x.reduce((sum, val, i) => sum + (val - meanX) * (y[i] - meanY), 0) / (n - 1);
}
// calculatePortfolioVariance is already exported above
function calculateVarianceGradient(weights: number[], covarianceMatrix: number[][]): number[] {
const n = weights.length;
const gradient: number[] = [];
for (let i = 0; i < n; i++) {
let grad = 0;
for (let j = 0; j < n; j++) {
grad += 2 * weights[j] * covarianceMatrix[i][j];
}
gradient[i] = grad;
}
return gradient;
}
function findMinimumVarianceWeights(
expectedReturns: number[],
covarianceMatrix: number[][],
targetReturn: number
): number[] | null {
const n = expectedReturns.length;
// Simplified implementation - in practice would use quadratic programming solver
// Start with equal weights and adjust
const weights = new Array(n).fill(1 / n);
// Iterative adjustment to meet target return constraint
for (let iter = 0; iter < 50; iter++) {
const currentReturn = weights.reduce((sum, w, i) => sum + w * expectedReturns[i], 0);
const returnDiff = targetReturn - currentReturn;
if (Math.abs(returnDiff) < 0.001) {
break;
}
// Adjust weights proportionally to expected returns
const totalExpectedReturn = expectedReturns.reduce((sum, r) => sum + Math.abs(r), 0);
for (let i = 0; i < n; i++) {
const adjustment = (returnDiff * Math.abs(expectedReturns[i])) / totalExpectedReturn;
weights[i] = Math.max(0, weights[i] + adjustment * 0.1);
}
// Normalize weights
const weightSum = weights.reduce((sum, w) => sum + w, 0);
if (weightSum > 0) {
for (let i = 0; i < n; i++) {
weights[i] /= weightSum;
}
}
}
return weights;
}

View file

@ -1,581 +0,0 @@
/**
* Position Sizing Calculations
* Risk-based position sizing methods for trading strategies
*/
export interface PositionSizeParams {
accountSize: number;
riskPercentage: number;
entryPrice: number;
stopLoss: number;
leverage?: number;
}
export interface KellyParams {
winRate: number;
averageWin: number;
averageLoss: number;
}
export interface VolatilityParams {
price: number;
volatility: number;
targetVolatility: number;
lookbackDays: number;
}
/**
* Calculate position size based on fixed risk percentage
*/
export function fixedRiskPositionSize(params: PositionSizeParams): number {
const { accountSize, riskPercentage, entryPrice, stopLoss, leverage = 1 } = params;
// Input validation
if (accountSize <= 0 || riskPercentage <= 0 || entryPrice <= 0 || leverage <= 0) {
return 0;
}
if (entryPrice === stopLoss) {
return 0;
}
const riskAmount = accountSize * (riskPercentage / 100);
const riskPerShare = Math.abs(entryPrice - stopLoss);
const basePositionSize = riskAmount / riskPerShare;
return Math.floor(basePositionSize * leverage);
}
/**
* Calculate position size using Kelly Criterion
*/
export function kellyPositionSize(params: KellyParams, accountSize: number): number {
const { winRate, averageWin, averageLoss } = params;
// Validate inputs
if (averageLoss === 0 || winRate <= 0 || winRate >= 1 || averageWin <= 0) {
return 0;
}
const lossRate = 1 - winRate;
const winLossRatio = averageWin / Math.abs(averageLoss);
// Correct Kelly formula: f = (bp - q) / b
// where: b = win/loss ratio, p = win rate, q = loss rate
const kellyFraction = (winRate * winLossRatio - lossRate) / winLossRatio;
// Cap Kelly fraction to prevent over-leveraging (max 25% of Kelly recommendation)
const cappedKelly = Math.max(0, Math.min(kellyFraction * 0.25, 0.25));
return accountSize * cappedKelly;
}
/**
* Calculate fractional Kelly position size (more conservative)
*/
export function fractionalKellyPositionSize(
params: KellyParams,
accountSize: number,
fraction: number = 0.25
): number {
// Input validation
if (fraction <= 0 || fraction > 1) {
return 0;
}
const fullKelly = kellyPositionSize(params, accountSize);
return fullKelly * fraction;
}
/**
* Calculate position size based on volatility targeting
*/
export function volatilityTargetPositionSize(
params: VolatilityParams,
accountSize: number
): number {
const { price, volatility, targetVolatility } = params;
// Input validation
if (volatility <= 0 || price <= 0 || targetVolatility <= 0 || accountSize <= 0) {
return 0;
}
const volatilityRatio = targetVolatility / volatility;
const basePositionValue = accountSize * Math.min(volatilityRatio, 2); // Cap at 2x leverage
return Math.floor(basePositionValue / price);
}
/**
* Calculate equal weight position size
*/
export function equalWeightPositionSize(
accountSize: number,
numberOfPositions: number,
price: number
): number {
// Input validation
if (numberOfPositions <= 0 || price <= 0 || accountSize <= 0) {
return 0;
}
const positionValue = accountSize / numberOfPositions;
return Math.floor(positionValue / price);
}
/**
* Calculate position size based on Average True Range (ATR)
*/
export function atrBasedPositionSize(
accountSize: number,
riskPercentage: number,
atrValue: number,
atrMultiplier: number = 2,
price: number
): number {
if (atrValue === 0 || price === 0) {
return 0;
}
const riskAmount = accountSize * (riskPercentage / 100);
const stopDistance = atrValue * atrMultiplier;
const positionSize = riskAmount / stopDistance;
// Return position size in shares, not dollars
return Math.floor(positionSize);
}
/**
* Calculate position size using Van Tharp's expectancy
*/
export function expectancyPositionSize(
accountSize: number,
winRate: number,
averageWin: number,
averageLoss: number,
maxRiskPercentage: number = 2
): number {
// Input validation
if (accountSize <= 0 || winRate <= 0 || winRate >= 1 || averageWin <= 0 || averageLoss === 0) {
return 0;
}
const expectancy = winRate * averageWin - (1 - winRate) * Math.abs(averageLoss);
if (expectancy <= 0) {
return 0;
}
// Scale position size based on expectancy relative to average loss
// Higher expectancy relative to risk allows for larger position
const expectancyRatio = expectancy / Math.abs(averageLoss);
const riskPercentage = Math.min(expectancyRatio * 0.5, maxRiskPercentage);
const positionValue = accountSize * (riskPercentage / 100);
return positionValue;
}
/**
* Calculate optimal position size using Monte Carlo simulation
*/
export function monteCarloPositionSize(
accountSize: number,
historicalReturns: number[],
simulations: number = 1000,
confidenceLevel: number = 0.95
): number {
if (historicalReturns.length === 0) {
return 0;
}
const outcomes: number[] = [];
const mean = historicalReturns.reduce((sum, ret) => sum + ret, 0) / historicalReturns.length;
const variance =
historicalReturns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) /
historicalReturns.length;
const stdDev = Math.sqrt(variance);
// Test different position sizes (as fraction of account)
const testFractions = [0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.25];
let optimalFraction = 0;
let bestSharpe = -Infinity;
for (const fraction of testFractions) {
const simOutcomes: number[] = [];
for (let i = 0; i < simulations; i++) {
let portfolioValue = accountSize;
// Simulate trades over a period
for (let j = 0; j < 50; j++) {
// 50 trades
const randomReturn =
historicalReturns[Math.floor(Math.random() * historicalReturns.length)];
const positionReturn = randomReturn * fraction;
portfolioValue = portfolioValue * (1 + positionReturn);
}
simOutcomes.push(portfolioValue);
}
// Calculate Sharpe ratio for this fraction
const avgOutcome = simOutcomes.reduce((sum, val) => sum + val, 0) / simOutcomes.length;
const returns = simOutcomes.map(val => (val - accountSize) / accountSize);
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const returnStdDev = Math.sqrt(
returns.reduce((sum, ret) => sum + Math.pow(ret - avgReturn, 2), 0) / returns.length
);
const sharpe = returnStdDev > 0 ? avgReturn / returnStdDev : -Infinity;
if (sharpe > bestSharpe) {
bestSharpe = sharpe;
optimalFraction = fraction;
}
}
return accountSize * optimalFraction;
}
/**
* Calculate position size based on Sharpe ratio optimization
*/
export function sharpeOptimizedPositionSize(
accountSize: number,
expectedReturn: number,
volatility: number,
riskFreeRate: number = 0.02,
maxLeverage: number = 3
): number {
// Input validation
if (volatility <= 0 || accountSize <= 0 || expectedReturn <= riskFreeRate || maxLeverage <= 0) {
return 0;
}
// Kelly criterion with Sharpe ratio optimization
const excessReturn = expectedReturn - riskFreeRate;
const kellyFraction = excessReturn / (volatility * volatility);
// Apply maximum leverage constraint
const constrainedFraction = Math.max(0, Math.min(kellyFraction, maxLeverage));
return accountSize * constrainedFraction;
}
/**
* Fixed fractional position sizing
*/
export function fixedFractionalPositionSize(
accountSize: number,
riskPercentage: number,
stopLossPercentage: number,
price: number
): number {
// Input validation
if (stopLossPercentage <= 0 || price <= 0 || riskPercentage <= 0 || accountSize <= 0) {
return 0;
}
const riskAmount = accountSize * (riskPercentage / 100);
const stopLossAmount = price * (stopLossPercentage / 100);
return Math.floor(riskAmount / stopLossAmount);
}
/**
* Volatility-adjusted position sizing
*/
export function volatilityAdjustedPositionSize(
accountSize: number,
targetVolatility: number,
assetVolatility: number,
price: number
): number {
// Input validation
if (assetVolatility <= 0 || price <= 0 || targetVolatility <= 0 || accountSize <= 0) {
return 0;
}
const volatilityRatio = targetVolatility / assetVolatility;
const cappedRatio = Math.min(volatilityRatio, 3); // Cap at 3x leverage
const positionValue = accountSize * cappedRatio;
return Math.floor(positionValue / price);
}
/**
* Calculate position size with correlation adjustment
*/
export function correlationAdjustedPositionSize(
basePositionSize: number,
existingPositions: Array<{ size: number; correlation: number }>,
maxCorrelationRisk: number = 0.3
): number {
if (existingPositions.length === 0 || basePositionSize <= 0) {
return basePositionSize;
}
// Calculate portfolio correlation risk
// This should consider the correlation between the new position and existing ones
const totalCorrelationRisk = existingPositions.reduce((total, position) => {
// Weight correlation by position size relative to new position
const relativeSize = position.size / (basePositionSize + position.size);
return total + relativeSize * Math.abs(position.correlation);
}, 0);
// Adjust position size based on correlation risk
const correlationAdjustment = Math.max(0.1, 1 - totalCorrelationRisk / maxCorrelationRisk);
return Math.floor(basePositionSize * correlationAdjustment);
}
/**
* Calculate portfolio heat (total risk across all positions)
*/
export function calculatePortfolioHeat(
positions: Array<{ value: number; risk: number }>,
accountSize: number
): number {
// Input validation
if (accountSize <= 0 || positions.length === 0) {
return 0;
}
const totalRisk = positions.reduce((sum, position) => {
// Ensure risk values are positive
return sum + Math.max(0, position.risk);
}, 0);
return Math.min((totalRisk / accountSize) * 100, 100); // Cap at 100%
}
/**
* Dynamic position sizing based on market conditions
*/
export function dynamicPositionSize(
basePositionSize: number,
marketVolatility: number,
normalVolatility: number,
drawdownLevel: number,
maxDrawdownThreshold: number = 0.1
): number {
// Input validation
if (basePositionSize <= 0 || marketVolatility <= 0 || normalVolatility <= 0) {
return 0;
}
if (drawdownLevel < 0 || maxDrawdownThreshold <= 0) {
return basePositionSize;
}
// Volatility adjustment - reduce size when volatility is high
const volatilityAdjustment = Math.min(normalVolatility / marketVolatility, 2); // Cap at 2x
// Drawdown adjustment - reduce size as drawdown increases
const normalizedDrawdown = Math.min(drawdownLevel / maxDrawdownThreshold, 1);
const drawdownAdjustment = Math.max(0.1, 1 - normalizedDrawdown);
const adjustedSize = basePositionSize * volatilityAdjustment * drawdownAdjustment;
return Math.floor(Math.max(0, adjustedSize));
}
/**
* Calculate maximum position size based on liquidity
*/
export function liquidityConstrainedPositionSize(
desiredPositionSize: number,
averageDailyVolume: number,
maxVolumePercentage: number = 0.05,
price: number
): number {
if (averageDailyVolume === 0 || price === 0) {
return 0;
}
const maxShares = averageDailyVolume * maxVolumePercentage;
return Math.min(desiredPositionSize, maxShares);
}
/**
* Multi-timeframe position sizing
*/
export function multiTimeframePositionSize(
accountSize: number,
shortTermSignal: number, // -1 to 1
mediumTermSignal: number, // -1 to 1
longTermSignal: number, // -1 to 1
baseRiskPercentage: number = 1
): number {
// Input validation
if (accountSize <= 0 || baseRiskPercentage <= 0) {
return 0;
}
// Clamp signals to valid range
const clampedShort = Math.max(-1, Math.min(1, shortTermSignal));
const clampedMedium = Math.max(-1, Math.min(1, mediumTermSignal));
const clampedLong = Math.max(-1, Math.min(1, longTermSignal));
// Weight the signals (long-term gets higher weight)
const weightedSignal = clampedShort * 0.2 + clampedMedium * 0.3 + clampedLong * 0.5;
// Adjust risk based on signal strength
const adjustedRisk = baseRiskPercentage * Math.abs(weightedSignal);
return accountSize * (adjustedRisk / 100);
}
/**
* Risk parity position sizing
*/
export function riskParityPositionSize(
assets: Array<{ volatility: number; price: number }>,
targetRisk: number,
accountSize: number
): number[] {
if (assets.length === 0) {
return [];
}
// Calculate inverse volatility weights
const totalInverseVol = assets.reduce((sum, asset) => {
if (asset.volatility === 0) {
return sum;
}
return sum + 1 / asset.volatility;
}, 0);
if (totalInverseVol === 0) {
return assets.map(() => 0);
}
return assets.map(asset => {
if (asset.volatility === 0 || asset.price === 0) {
return 0;
}
// Calculate weight based on inverse volatility
const weight = 1 / asset.volatility / totalInverseVol;
// The weight itself already accounts for risk parity
// We just need to scale by target risk once
const positionValue = accountSize * weight * targetRisk;
return Math.floor(positionValue / asset.price);
});
}
/**
* Validate position size against risk limits
*/
export function validatePositionSize(
positionSize: number,
price: number,
accountSize: number,
maxPositionPercentage: number = 10,
maxLeverage: number = 1
): { isValid: boolean; adjustedSize: number; violations: string[] } {
const violations: string[] = [];
let adjustedSize = positionSize;
// Check maximum position percentage
const positionValue = positionSize * price;
const positionPercentage = (positionValue / accountSize) * 100;
if (positionPercentage > maxPositionPercentage) {
violations.push(`Position exceeds maximum ${maxPositionPercentage}% of account`);
adjustedSize = (accountSize * maxPositionPercentage) / 100 / price;
}
// Check leverage limits
const leverage = positionValue / accountSize;
if (leverage > maxLeverage) {
violations.push(`Position exceeds maximum leverage of ${maxLeverage}x`);
adjustedSize = Math.min(adjustedSize, (accountSize * maxLeverage) / price);
}
// Check minimum position size
if (adjustedSize < 1 && adjustedSize > 0) {
violations.push('Position size too small (less than 1 share)');
adjustedSize = 0;
}
return {
isValid: violations.length === 0,
adjustedSize: Math.max(0, adjustedSize),
violations,
};
}
/**
* Optimal F position sizing (Ralph Vince's method)
*/
export function optimalFPositionSize(
accountSize: number,
historicalReturns: number[],
maxIterations: number = 100
): number {
if (historicalReturns.length === 0 || accountSize <= 0) {
return 0;
}
// Convert returns to P&L per unit
const pnlValues = historicalReturns.map(ret => ret * 1000); // Assuming $1000 per unit
let bestF = 0;
let bestTWR = 0; // Terminal Wealth Relative
// Test different f values (0.01 to 1.00)
for (let f = 0.01; f <= 1.0; f += 0.01) {
let twr = 1.0;
let valid = true;
for (const pnl of pnlValues) {
const hpr = 1 + (f * pnl) / 1000; // Holding Period Return
if (hpr <= 0) {
valid = false;
break;
}
twr *= hpr;
}
if (valid && twr > bestTWR) {
bestTWR = twr;
bestF = f;
}
}
// Apply safety factor
const safeF = bestF * 0.75; // 75% of optimal f for safety
return accountSize * safeF;
}
/**
* Secure F position sizing (safer version of Optimal F)
*/
export function secureFPositionSize(
accountSize: number,
historicalReturns: number[],
confidenceLevel: number = 0.95
): number {
if (historicalReturns.length === 0 || accountSize <= 0) {
return 0;
}
// Sort returns to find worst-case scenarios
const sortedReturns = [...historicalReturns].sort((a, b) => a - b);
const worstCaseIndex = Math.floor((1 - confidenceLevel) * sortedReturns.length);
const worstCaseReturn = sortedReturns[worstCaseIndex];
// Calculate maximum position size that won't bankrupt at confidence level
const maxLoss = Math.abs(worstCaseReturn);
const maxRiskPercentage = 0.02; // Never risk more than 2% on worst case
if (maxLoss === 0) {
return accountSize * 0.1;
} // Default to 10% if no historical losses
const secureF = Math.min(maxRiskPercentage / maxLoss, 0.25); // Cap at 25%
return accountSize * secureF;
}

View file

@ -1,481 +0,0 @@
/**
* Risk Metrics and Analysis
* Comprehensive risk measurement tools for portfolio and trading analysis
*/
import type { RiskMetrics } from '@stock-bot/types';
/**
* Calculate Value at Risk (VaR) using historical simulation
*/
export function valueAtRisk(returns: number[], confidenceLevel: number = 0.95): number {
if (returns.length === 0) {
return 0;
}
const sortedReturns = [...returns].sort((a, b) => a - b);
const index = Math.floor((1 - confidenceLevel) * sortedReturns.length);
return sortedReturns[index] || 0;
}
/**
* Calculate Conditional Value at Risk (CVaR/Expected Shortfall)
*/
export function conditionalValueAtRisk(returns: number[], confidenceLevel: number = 0.95): number {
if (returns.length === 0) {
return 0;
}
const sortedReturns = [...returns].sort((a, b) => a - b);
const cutoffIndex = Math.floor((1 - confidenceLevel) * sortedReturns.length);
if (cutoffIndex === 0) {
return sortedReturns[0] || 0;
}
const tailReturns = sortedReturns.slice(0, cutoffIndex);
return tailReturns.reduce((sum, ret) => sum + ret, 0) / tailReturns.length;
}
/**
* Calculate parametric VaR using normal distribution
*/
export function parametricVaR(
returns: number[],
confidenceLevel: number = 0.95,
portfolioValue: number = 1
): number {
if (returns.length === 0) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance =
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
const stdDev = Math.sqrt(variance);
// Z-score for confidence level (normal distribution)
const zScore = getZScore(confidenceLevel);
return portfolioValue * (mean - zScore * stdDev);
}
/**
* Calculate maximum drawdown
*/
export function maxDrawdown(equityCurve: number[]): number {
if (equityCurve.length < 2) {
return 0;
}
let maxDD = 0;
const first = equityCurve[0];
if (first === undefined) {
return 0;
}
let peak = first;
for (let i = 1; i < equityCurve.length; i++) {
const current = equityCurve[i];
if (current === undefined) {
continue;
}
if (current > peak) {
peak = current;
} else {
const drawdown = (peak - current) / peak;
maxDD = Math.max(maxDD, drawdown);
}
}
return maxDD;
}
/**
* Calculate downside deviation
*/
export function downsideDeviation(returns: number[], targetReturn: number = 0): number {
if (returns.length === 0) {
return 0;
}
const downsideReturns = returns.filter(ret => ret < targetReturn);
if (downsideReturns.length === 0) {
return 0;
}
const sumSquaredDownside = downsideReturns.reduce(
(sum, ret) => sum + Math.pow(ret - targetReturn, 2),
0
);
return Math.sqrt(sumSquaredDownside / returns.length);
}
/**
* Calculate Sharpe ratio
*/
export function sharpeRatio(returns: number[], riskFreeRate: number = 0): number {
if (returns.length < 2) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance =
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
return 0;
}
return (mean - riskFreeRate) / stdDev;
}
/**
* Calculate beta coefficient
*/
export function beta(portfolioReturns: number[], marketReturns: number[]): number {
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < 2) {
return 0;
}
const n = portfolioReturns.length;
const portfolioMean = portfolioReturns.reduce((sum, ret) => sum + ret, 0) / n;
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / n;
let covariance = 0;
let marketVariance = 0;
for (let i = 0; i < n; i++) {
const portfolioReturn = portfolioReturns[i];
const marketReturn = marketReturns[i];
if (portfolioReturn === undefined || marketReturn === undefined) {
continue;
}
const portfolioDiff = portfolioReturn - portfolioMean;
const marketDiff = marketReturn - marketMean;
covariance += portfolioDiff * marketDiff;
marketVariance += marketDiff * marketDiff;
}
return marketVariance === 0 ? 0 : covariance / marketVariance;
}
/**
* Calculate alpha
*/
export function alpha(
portfolioReturns: number[],
marketReturns: number[],
riskFreeRate: number = 0
): number {
const portfolioMean =
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length;
const portfolioBeta = beta(portfolioReturns, marketReturns);
return portfolioMean - (riskFreeRate + portfolioBeta * (marketMean - riskFreeRate));
}
/**
* Calculate Treynor ratio
*/
export function treynorRatio(
portfolioReturns: number[],
marketReturns: number[],
riskFreeRate: number = 0
): number {
const portfolioBeta = beta(portfolioReturns, marketReturns);
if (portfolioBeta === 0) {
return 0;
}
const portfolioMean =
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
return (portfolioMean - riskFreeRate) / portfolioBeta;
}
/**
* Calculate tracking error
*/
export function trackingError(portfolioReturns: number[], benchmarkReturns: number[]): number {
if (portfolioReturns.length !== benchmarkReturns.length || portfolioReturns.length === 0) {
return 0;
}
const activeReturns = portfolioReturns.map((ret, i) => {
const benchmark = benchmarkReturns[i];
return benchmark !== undefined ? ret - benchmark : 0;
});
const mean = activeReturns.reduce((sum, ret) => sum + ret, 0) / activeReturns.length;
const variance =
activeReturns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) /
(activeReturns.length - 1);
return Math.sqrt(variance);
}
/**
* Calculate volatility (standard deviation of returns)
*/
export function volatility(returns: number[]): number {
if (returns.length < 2) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance =
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
return Math.sqrt(variance);
}
/**
* Calculate annualized volatility
*/
export function annualizedVolatility(returns: number[], periodsPerYear: number = 252): number {
return volatility(returns) * Math.sqrt(periodsPerYear);
}
/**
* Calculate skewness (measure of asymmetry)
*/
export function skewness(returns: number[]): number {
if (returns.length < 3) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
return 0;
}
const skew =
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 3), 0) / returns.length;
return skew;
}
/**
* Calculate kurtosis (measure of tail heaviness)
*/
export function kurtosis(returns: number[]): number {
if (returns.length < 4) {
return 0;
}
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
const stdDev = Math.sqrt(variance);
if (stdDev === 0) {
return 0;
}
const kurt =
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 4), 0) / returns.length;
return kurt - 3; // Excess kurtosis (subtract 3 for normal distribution baseline)
}
/**
* Calculate comprehensive risk metrics
*/
export function calculateRiskMetrics(
returns: number[],
equityCurve: number[],
marketReturns?: number[],
riskFreeRate: number = 0
): RiskMetrics {
if (returns.length === 0) {
return {
var95: 0,
var99: 0,
cvar95: 0,
maxDrawdown: 0,
volatility: 0,
downside_deviation: 0,
calmar_ratio: 0,
sortino_ratio: 0,
beta: 0,
alpha: 0,
sharpeRatio: 0,
treynorRatio: 0,
trackingError: 0,
informationRatio: 0,
};
}
const portfolioVolatility = volatility(returns);
const portfolioMean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
// Calculate VaR
const var95Value = valueAtRisk(returns, 0.95);
const var99Value = valueAtRisk(returns, 0.99);
const cvar95Value = conditionalValueAtRisk(returns, 0.95);
// Calculate max drawdown
const maxDD = maxDrawdown(equityCurve);
// Calculate downside deviation
const downsideDeviationValue = downsideDeviation(returns);
// Calculate ratios
const calmarRatio = maxDD > 0 ? portfolioMean / maxDD : 0;
const sortinoRatio =
downsideDeviationValue > 0 ? (portfolioMean - riskFreeRate) / downsideDeviationValue : 0;
const sharpeRatio =
portfolioVolatility > 0 ? (portfolioMean - riskFreeRate) / portfolioVolatility : 0;
let portfolioBeta = 0;
let portfolioAlpha = 0;
let portfolioTreynorRatio = 0;
let portfolioTrackingError = 0;
let informationRatio = 0;
if (marketReturns && marketReturns.length === returns.length) {
portfolioBeta = beta(returns, marketReturns);
portfolioAlpha = alpha(returns, marketReturns, riskFreeRate);
portfolioTreynorRatio = treynorRatio(returns, marketReturns, riskFreeRate);
portfolioTrackingError = trackingError(returns, marketReturns);
informationRatio = portfolioTrackingError > 0 ? portfolioAlpha / portfolioTrackingError : 0;
}
return {
var95: var95Value,
var99: var99Value,
cvar95: cvar95Value,
maxDrawdown: maxDD,
volatility: portfolioVolatility,
downside_deviation: downsideDeviationValue,
calmar_ratio: calmarRatio,
sortino_ratio: sortinoRatio,
beta: portfolioBeta,
alpha: portfolioAlpha,
sharpeRatio,
treynorRatio: portfolioTreynorRatio,
trackingError: portfolioTrackingError,
informationRatio,
};
}
/**
* Helper function to get Z-score for confidence level
* This implementation handles arbitrary confidence levels
*/
function getZScore(confidenceLevel: number): number {
// First check our lookup table for common values (more precise)
const zScores: { [key: string]: number } = {
'0.90': 1.282,
'0.95': 1.645,
'0.975': 1.96,
'0.99': 2.326,
'0.995': 2.576,
};
const key = confidenceLevel.toString();
if (zScores[key]) {
return zScores[key];
}
// For arbitrary confidence levels, use approximation
if (confidenceLevel < 0.5) {
return -getZScore(1 - confidenceLevel);
}
if (confidenceLevel >= 0.999) {
return 3.09;
} // Cap at 99.9% for numerical stability
// Approximation of inverse normal CDF
const y = Math.sqrt(-2.0 * Math.log(1.0 - confidenceLevel));
return (
y -
(2.515517 + 0.802853 * y + 0.010328 * y * y) /
(1.0 + 1.432788 * y + 0.189269 * y * y + 0.001308 * y * y * y)
);
}
/**
* Calculate portfolio risk contribution
*/
export function riskContribution(
weights: number[],
covarianceMatrix: number[][],
portfolioVolatility: number
): number[] {
const n = weights.length;
const contributions: number[] = [];
for (let i = 0; i < n; i++) {
let marginalContribution = 0;
const row = covarianceMatrix[i];
if (!row) {
continue;
}
for (let j = 0; j < n; j++) {
const weight = weights[j];
const covariance = row[j];
if (weight !== undefined && covariance !== undefined) {
marginalContribution += weight * covariance;
}
}
const weight = weights[i];
if (weight !== undefined && portfolioVolatility !== 0) {
const contribution = (weight * marginalContribution) / Math.pow(portfolioVolatility, 2);
contributions.push(contribution);
}
}
return contributions;
}
/**
* Calculate Ulcer Index
*/
export function ulcerIndex(equityCurve: Array<{ value: number; date: Date }>): number {
if (equityCurve.length === 0) {
return 0;
}
let sumSquaredDrawdown = 0;
const first = equityCurve[0];
if (!first) {
return 0;
}
let peak = first.value;
for (const point of equityCurve) {
peak = Math.max(peak, point.value);
const drawdownPercent = ((peak - point.value) / peak) * 100;
sumSquaredDrawdown += drawdownPercent * drawdownPercent;
}
return Math.sqrt(sumSquaredDrawdown / equityCurve.length);
}
/**
* Calculate risk-adjusted return (RAR)
*/
export function riskAdjustedReturn(
portfolioReturn: number,
portfolioRisk: number,
riskFreeRate: number = 0
): number {
if (portfolioRisk === 0) {
return 0;
}
return (portfolioReturn - riskFreeRate) / portfolioRisk;
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,621 +0,0 @@
/**
* Volatility Models
* Advanced volatility modeling and forecasting tools
*/
// Local interface definition to avoid circular dependency
interface OHLCVData {
open: number;
high: number;
low: number;
close: number;
volume: number;
timestamp: Date;
}
export interface GARCHParameters {
omega: number; // Constant term
alpha: number; // ARCH parameter
beta: number; // GARCH parameter
logLikelihood: number;
aic: number;
bic: number;
}
export interface VolatilityEstimates {
closeToClose: number;
parkinson: number;
garmanKlass: number;
rogersSatchell: number;
yangZhang: number;
}
export interface VolatilityRegime {
regime: number;
startDate: Date;
endDate: Date;
averageVolatility: number;
observations: number;
}
export interface VolatilityTerm {
maturity: number; // Days to maturity
impliedVolatility: number;
confidence: number;
}
export interface HestonParameters {
kappa: number; // Mean reversion speed
theta: number; // Long-term variance
sigma: number; // Volatility of variance
rho: number; // Correlation
v0: number; // Initial variance
logLikelihood: number;
}
/**
* Calculate realized volatility using different estimators
*/
export function calculateRealizedVolatility(
ohlcv: OHLCVData[],
annualizationFactor: number = 252
): VolatilityEstimates {
if (ohlcv.length < 2) {
throw new Error('Need at least 2 observations for volatility calculation');
}
const n = ohlcv.length;
let closeToCloseSum = 0;
let parkinsonSum = 0;
let garmanKlassSum = 0;
let rogersSatchellSum = 0;
let yangZhangSum = 0;
// Calculate log returns and volatility estimators
for (let i = 1; i < n; i++) {
const prev = ohlcv[i - 1];
const curr = ohlcv[i];
// Close-to-close
const logReturn = Math.log(curr.close / prev.close);
closeToCloseSum += logReturn * logReturn;
// Parkinson estimator
const logHighLow = Math.log(curr.high / curr.low);
parkinsonSum += logHighLow * logHighLow;
// Garman-Klass estimator
const logOpenClose = Math.log(curr.close / curr.open);
garmanKlassSum +=
0.5 * logHighLow * logHighLow - (2 * Math.log(2) - 1) * logOpenClose * logOpenClose;
// Rogers-Satchell estimator
const logHighOpen = Math.log(curr.high / curr.open);
const logHighClose = Math.log(curr.high / curr.close);
const logLowOpen = Math.log(curr.low / curr.open);
const logLowClose = Math.log(curr.low / curr.close);
rogersSatchellSum += logHighOpen * logHighClose + logLowOpen * logLowClose;
// Yang-Zhang estimator components
const overnight = Math.log(curr.open / prev.close);
yangZhangSum += overnight * overnight + rogersSatchellSum / i; // Simplified for brevity
}
return {
closeToClose: Math.sqrt((closeToCloseSum / (n - 1)) * annualizationFactor),
parkinson: Math.sqrt((parkinsonSum / (n - 1) / (4 * Math.log(2))) * annualizationFactor),
garmanKlass: Math.sqrt((garmanKlassSum / (n - 1)) * annualizationFactor),
rogersSatchell: Math.sqrt((rogersSatchellSum / (n - 1)) * annualizationFactor),
yangZhang: Math.sqrt((yangZhangSum / (n - 1)) * annualizationFactor),
};
}
/**
* Estimate GARCH(1,1) model parameters
*/
export function estimateGARCH(
returns: number[],
maxIterations: number = 100,
tolerance: number = 1e-6
): GARCHParameters {
const n = returns.length;
// Initial parameter estimates
let omega = 0.01;
let alpha = 0.05;
let beta = 0.9;
// Calculate unconditional variance
const meanReturn = returns.reduce((sum, r) => sum + r, 0) / n;
const unconditionalVar =
returns.reduce((sum, r) => sum + Math.pow(r - meanReturn, 2), 0) / (n - 1);
let logLikelihood = -Infinity;
for (let iter = 0; iter < maxIterations; iter++) {
const variances: number[] = [unconditionalVar];
let newLogLikelihood = 0;
// Calculate conditional variances
for (let t = 1; t < n; t++) {
const prevVar = variances[t - 1];
const prevReturn = returns[t - 1] - meanReturn;
const currentVar = omega + alpha * prevReturn * prevReturn + beta * prevVar;
variances.push(Math.max(currentVar, 1e-8)); // Ensure positive variance
// Add to log-likelihood
const currentReturn = returns[t] - meanReturn;
newLogLikelihood -=
0.5 *
(Math.log(2 * Math.PI) +
Math.log(currentVar) +
(currentReturn * currentReturn) / currentVar);
}
// Check for convergence
if (Math.abs(newLogLikelihood - logLikelihood) < tolerance) {
break;
}
logLikelihood = newLogLikelihood;
// Simple gradient update (in practice, use more sophisticated optimization)
const gradientStep = 0.001;
omega = Math.max(0.001, omega + gradientStep);
alpha = Math.max(0.001, Math.min(0.999, alpha + gradientStep));
beta = Math.max(0.001, Math.min(0.999 - alpha, beta + gradientStep));
}
// Calculate information criteria
const k = 3; // Number of parameters
const aic = -2 * logLikelihood + 2 * k;
const bic = -2 * logLikelihood + k * Math.log(n);
return {
omega,
alpha,
beta,
logLikelihood,
aic,
bic,
};
}
/**
* Calculate EWMA volatility
*/
export function calculateEWMAVolatility(
returns: number[],
lambda: number = 0.94,
annualizationFactor: number = 252
): number[] {
const n = returns.length;
const volatilities: number[] = [];
// Initialize with sample variance
const meanReturn = returns.reduce((sum, r) => sum + r, 0) / n;
let variance = returns.reduce((sum, r) => sum + Math.pow(r - meanReturn, 2), 0) / (n - 1);
for (let t = 0; t < n; t++) {
if (t > 0) {
const prevReturn = returns[t - 1] - meanReturn;
variance = lambda * variance + (1 - lambda) * prevReturn * prevReturn;
}
volatilities.push(Math.sqrt(variance * annualizationFactor));
}
return volatilities;
}
/**
* Identify volatility regimes
*/
export function identifyVolatilityRegimes(
returns: number[],
numRegimes: number = 3,
windowSize: number = 60
): VolatilityRegime[] {
// Calculate rolling volatility
const rollingVol: number[] = [];
const timestamps: Date[] = [];
for (let i = windowSize - 1; i < returns.length; i++) {
const window = returns.slice(i - windowSize + 1, i + 1);
const mean = window.reduce((sum, r) => sum + r, 0) / window.length;
const variance =
window.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / (window.length - 1);
rollingVol.push(Math.sqrt(variance * 252)); // Annualized
timestamps.push(new Date(Date.now() + i * 24 * 60 * 60 * 1000)); // Mock timestamps
}
// Simple k-means clustering on absolute returns
const absReturns = returns.map(ret => Math.abs(ret));
const sortedReturns = [...absReturns].sort((a, b) => a - b);
// Define regime thresholds
const thresholds: number[] = [];
for (let i = 1; i < numRegimes; i++) {
const index = Math.floor((i / numRegimes) * sortedReturns.length);
thresholds.push(sortedReturns[index]);
}
// Classify returns into regimes
const regimeSequence = absReturns.map(absRet => {
for (let i = 0; i < thresholds.length; i++) {
if (absRet <= thresholds[i]) {
return i;
}
}
return numRegimes - 1;
});
// Calculate regime statistics
const regimes: VolatilityRegime[] = [];
for (let regime = 0; regime < numRegimes; regime++) {
const regimeIndices = regimeSequence
.map((r, idx) => (r === regime ? idx : -1))
.filter(idx => idx !== -1);
if (regimeIndices.length > 0) {
const regimeVolatilities = regimeIndices.map(idx =>
idx < rollingVol.length ? rollingVol[idx] : 0
);
const avgVol =
regimeVolatilities.reduce((sum, vol) => sum + vol, 0) / regimeVolatilities.length;
regimes.push({
regime,
startDate: new Date(Date.now()),
endDate: new Date(Date.now() + regimeIndices.length * 24 * 60 * 60 * 1000),
averageVolatility: avgVol,
observations: regimeIndices.length,
});
}
}
return regimes;
}
/**
* Calculate volatility term structure
*/
export function calculateVolatilityTermStructure(
spotVol: number,
maturities: number[],
meanReversion: number = 0.5
): VolatilityTerm[] {
return maturities.map(maturity => {
// Simple mean reversion model for term structure
const timeToMaturity = maturity / 365; // Convert to years
const termVolatility = spotVol * Math.exp(-meanReversion * timeToMaturity);
return {
maturity,
impliedVolatility: Math.max(termVolatility, 0.01), // Floor at 1%
confidence: Math.exp(-timeToMaturity), // Confidence decreases with maturity
};
});
}
/**
* Calculate volatility smile/skew parameters
*/
export function calculateVolatilitySmile(
strikes: number[],
spotPrice: number,
impliedVols: number[]
): {
atmVolatility: number;
skew: number;
convexity: number;
riskReversal: number;
} {
if (strikes.length !== impliedVols.length || strikes.length < 3) {
throw new Error('Need at least 3 strikes with corresponding implied volatilities');
}
// Find ATM volatility
const atmIndex = strikes.reduce(
(closest, strike, idx) =>
Math.abs(strike - spotPrice) < Math.abs(strikes[closest] - spotPrice) ? idx : closest,
0
);
const atmVolatility = impliedVols[atmIndex];
// Calculate skew (derivative at ATM)
let skew = 0;
if (atmIndex > 0 && atmIndex < strikes.length - 1) {
const deltaStrike = strikes[atmIndex + 1] - strikes[atmIndex - 1];
const deltaVol = impliedVols[atmIndex + 1] - impliedVols[atmIndex - 1];
skew = deltaVol / deltaStrike;
}
// Calculate convexity (second derivative)
let convexity = 0;
if (atmIndex > 0 && atmIndex < strikes.length - 1) {
const h = strikes[atmIndex + 1] - strikes[atmIndex];
convexity =
(impliedVols[atmIndex + 1] - 2 * impliedVols[atmIndex] + impliedVols[atmIndex - 1]) / (h * h);
}
// Risk reversal (put-call vol difference)
const otmPutIndex = strikes.findIndex(strike => strike < spotPrice * 0.9);
const otmCallIndex = strikes.findIndex(strike => strike > spotPrice * 1.1);
let riskReversal = 0;
if (otmPutIndex !== -1 && otmCallIndex !== -1) {
riskReversal = impliedVols[otmCallIndex] - impliedVols[otmPutIndex];
}
return {
atmVolatility,
skew,
convexity,
riskReversal,
};
}
/**
* Estimate Heston stochastic volatility model parameters
*/
export function estimateHestonParameters(
returns: number[],
maxIterations: number = 100
): HestonParameters {
const n = returns.length;
if (n < 10) {
throw new Error('Need at least 10 observations for Heston parameter estimation');
}
// Initial parameter estimates
let kappa = 2.0; // Mean reversion speed
let theta = 0.04; // Long-term variance
let sigma = 0.3; // Volatility of variance
let rho = -0.5; // Correlation
let v0 = 0.04; // Initial variance
// Calculate sample statistics for initialization
const meanReturn = returns.reduce((sum, r) => sum + r, 0) / n;
const sampleVariance = returns.reduce((sum, r) => sum + Math.pow(r - meanReturn, 2), 0) / (n - 1);
theta = sampleVariance;
v0 = sampleVariance;
let logLikelihood = -Infinity;
for (let iter = 0; iter < maxIterations; iter++) {
let newLogLikelihood = 0;
let currentVariance = v0;
for (let t = 1; t < n; t++) {
const dt = 1.0; // Assuming daily data
const prevReturn = returns[t - 1];
// Euler discretization of variance process
const dW1 = Math.random() - 0.5; // Simplified random shock
const dW2 = rho * dW1 + Math.sqrt(1 - rho * rho) * (Math.random() - 0.5);
const varianceChange =
kappa * (theta - currentVariance) * dt +
sigma * Math.sqrt(Math.max(currentVariance, 0)) * dW2;
currentVariance = Math.max(currentVariance + varianceChange, 0.001);
// Log-likelihood contribution (simplified)
const expectedReturn = meanReturn;
const variance = currentVariance;
if (variance > 0) {
newLogLikelihood -= 0.5 * Math.log(2 * Math.PI * variance);
newLogLikelihood -= (0.5 * Math.pow(returns[t] - expectedReturn, 2)) / variance;
}
}
// Check for convergence
if (Math.abs(newLogLikelihood - logLikelihood) < 1e-6) {
break;
}
logLikelihood = newLogLikelihood;
// Simple parameter updates (in practice, use maximum likelihood estimation)
const learningRate = 0.001;
kappa = Math.max(0.1, Math.min(10, kappa + learningRate));
theta = Math.max(0.001, Math.min(1, theta + learningRate));
sigma = Math.max(0.01, Math.min(2, sigma + learningRate));
rho = Math.max(-0.99, Math.min(0.99, rho + learningRate * 0.1));
v0 = Math.max(0.001, Math.min(1, v0 + learningRate));
}
return {
kappa,
theta,
sigma,
rho,
v0,
logLikelihood,
};
}
/**
* Calculate volatility risk metrics
*/
export function calculateVolatilityRisk(
returns: number[],
confidenceLevel: number = 0.05
): {
volatilityVaR: number;
expectedShortfall: number;
maxVolatility: number;
volatilityVolatility: number;
} {
// Calculate rolling volatilities
const windowSize = 30;
const volatilities: number[] = [];
for (let i = windowSize - 1; i < returns.length; i++) {
const window = returns.slice(i - windowSize + 1, i + 1);
const mean = window.reduce((sum, r) => sum + r, 0) / window.length;
const variance =
window.reduce((sum, r) => sum + Math.pow(r - mean, 2), 0) / (window.length - 1);
volatilities.push(Math.sqrt(variance * 252)); // Annualized
}
// Sort volatilities for VaR calculation
const sortedVols = [...volatilities].sort((a, b) => b - a); // Descending order
const varIndex = Math.floor(confidenceLevel * sortedVols.length);
const volatilityVaR = sortedVols[varIndex];
// Expected shortfall (average of worst volatilities)
const esVols = sortedVols.slice(0, varIndex + 1);
const expectedShortfall = esVols.reduce((sum, vol) => sum + vol, 0) / esVols.length;
// Maximum volatility
const maxVolatility = Math.max(...volatilities);
// Volatility of volatility
const meanVol = volatilities.reduce((sum, vol) => sum + vol, 0) / volatilities.length;
const volVariance =
volatilities.reduce((sum, vol) => sum + Math.pow(vol - meanVol, 2), 0) /
(volatilities.length - 1);
const volatilityVolatility = Math.sqrt(volVariance);
return {
volatilityVaR,
expectedShortfall,
maxVolatility,
volatilityVolatility,
};
}
/**
* Fix Yang-Zhang volatility calculation
*/
export function calculateYangZhangVolatility(
ohlcv: OHLCVData[],
annualizationFactor: number = 252
): number {
if (ohlcv.length < 2) {
throw new Error('Need at least 2 observations for Yang-Zhang volatility calculation');
}
const n = ohlcv.length;
let overnightSum = 0;
let openToCloseSum = 0;
let rogersSatchellSum = 0;
for (let i = 1; i < n; i++) {
const prev = ohlcv[i - 1];
const curr = ohlcv[i];
// Overnight return (close to open)
const overnight = Math.log(curr.open / prev.close);
overnightSum += overnight * overnight;
// Open to close return
const openToClose = Math.log(curr.close / curr.open);
openToCloseSum += openToClose * openToClose;
// Rogers-Satchell component
const logHighOpen = Math.log(curr.high / curr.open);
const logHighClose = Math.log(curr.high / curr.close);
const logLowOpen = Math.log(curr.low / curr.open);
const logLowClose = Math.log(curr.low / curr.close);
rogersSatchellSum += logHighOpen * logHighClose + logLowOpen * logLowClose;
}
// Yang-Zhang estimator
const k = 0.34 / (1.34 + (n + 1) / (n - 1)); // Drift adjustment factor
const yangZhangVariance =
overnightSum / (n - 1) +
(k * openToCloseSum) / (n - 1) +
((1 - k) * rogersSatchellSum) / (n - 1);
return Math.sqrt(yangZhangVariance * annualizationFactor);
}
/**
* Parkinson volatility estimator
*/
export function parkinsonVolatility(ohlcv: OHLCVData[], annualizationFactor: number = 252): number {
if (ohlcv.length < 2) {
return 0;
}
const sum = ohlcv.slice(1).reduce((acc, curr) => {
const range = Math.log(curr.high / curr.low);
return acc + range * range;
}, 0);
return Math.sqrt((sum / (ohlcv.length - 1)) * annualizationFactor);
}
/**
* Black-Scholes option pricing model
*/
function blackScholes(
spotPrice: number,
strikePrice: number,
timeToExpiry: number,
volatility: number,
riskFreeRate: number,
optionType: 'call' | 'put'
): number {
const d1 =
(Math.log(spotPrice / strikePrice) +
(riskFreeRate + 0.5 * volatility * volatility) * timeToExpiry) /
(volatility * Math.sqrt(timeToExpiry));
const d2 = d1 - volatility * Math.sqrt(timeToExpiry);
if (optionType === 'call') {
return (
spotPrice * normalCDF(d1) -
strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(d2)
);
} else {
return (
strikePrice * Math.exp(-riskFreeRate * timeToExpiry) * normalCDF(-d2) -
spotPrice * normalCDF(-d1)
);
}
}
/**
* Normal cumulative distribution function
*/
function normalCDF(x: number): number {
const a1 = 0.254829592;
const a2 = -0.284496736;
const a3 = 1.421060743;
const a4 = -1.453152027;
const a5 = 1.061405429;
const p = 0.3275911;
const sign = x < 0 ? -1 : 1;
const absX = Math.abs(x);
const t = 1 / (1 + p * absX);
const y =
1 -
(a1 * t + a2 * t * t + a3 * t * t * t + a4 * t * t * t * t + a5 * t * t * t * t * t) *
Math.exp((-absX * absX) / 2);
return 0.5 * (1 + sign * y);
}
/**
* Forecast volatility using EWMA
*/
export function forecastVolatilityEWMA(
volatilities: number[],
lambda: number = 0.94,
forecastHorizon: number = 1
): number {
if (volatilities.length === 0) {
return 0;
}
let forecast = volatilities[volatilities.length - 1];
for (let i = 0; i < forecastHorizon; i++) {
forecast = lambda * forecast + (1 - lambda) * forecast; // Using the last value as the long-term average
}
return forecast;
}

View file

@ -1,56 +1,48 @@
/**
* Date and time utilities for working with market data
*/
export const dateUtils = {
/**
* Check if a date is a trading day (Monday-Friday, non-holiday)
* This is a simplified implementation - a real version would check market holidays
*/
isTradingDay(date: Date): boolean {
const day = date.getDay();
return day > 0 && day < 6; // Mon-Fri
},
function valid(date: Date): Date {
if (!Number.isFinite(date.getTime())) {
throw new RangeError('Invalid UTC date');
}
return date;
}
/**
* Get the next trading day from a given date
*/
getNextTradingDay(date: Date): Date {
const nextDay = new Date(date);
nextDay.setDate(nextDay.getDate() + 1);
/** Weekdays in UTC, NOT an exchange calendar: holidays and venue sessions are not modeled. */
function isWeekday(date: Date): boolean {
const day = valid(date).getUTCDay();
return day > 0 && day < 6;
}
while (!this.isTradingDay(nextDay)) {
nextDay.setDate(nextDay.getDate() + 1);
}
function shiftWeekday(date: Date, direction: 1 | -1): Date {
const result = new Date(valid(date).getTime());
do {
result.setUTCDate(result.getUTCDate() + direction);
} while (!isWeekday(result));
return result;
}
return nextDay;
},
function parseDate(value: string): Date {
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) {
throw new RangeError('Expected YYYY-MM-DD');
}
const date = valid(new Date(`${value}T00:00:00.000Z`));
if (date.toISOString().slice(0, 10) !== value) {
throw new RangeError('Invalid calendar date');
}
return date;
}
/**
* Get the previous trading day from a given date
*/
getPreviousTradingDay(date: Date): Date {
const prevDay = new Date(date);
prevDay.setDate(prevDay.getDate() - 1);
while (!this.isTradingDay(prevDay)) {
prevDay.setDate(prevDay.getDate() - 1);
}
return prevDay;
},
/**
* Format a date as YYYY-MM-DD
*/
formatDate(date: Date): string {
const parts = date.toISOString().split('T');
return parts[0] ?? '';
},
/**
* Parse a date string in YYYY-MM-DD format
*/
parseDate(dateStr: string): Date {
return new Date(dateStr);
},
export const utcDates = {
isWeekday,
nextWeekday: (date: Date): Date => shiftWeekday(date, 1),
previousWeekday: (date: Date): Date => shiftWeekday(date, -1),
formatDate: (date: Date): string => valid(date).toISOString().slice(0, 10),
parseDate,
};
/** @deprecated Compatibility names only. These are UTC weekdays, never verified trading sessions. */
export const dateUtils = {
isTradingDay: utcDates.isWeekday,
getNextTradingDay: utcDates.nextWeekday,
getPreviousTradingDay: utcDates.previousWeekday,
formatDate: utcDates.formatDate,
parseDate: utcDates.parseDate,
};

View file

@ -5,7 +5,7 @@ import type { LoggerLike } from '@stock-bot/logger';
* Drop-in replacement for native fetch with additional features
*/
export interface BunRequestInit extends RequestInit {
interface BunRequestInit extends RequestInit {
proxy?: string;
}

View file

@ -1,190 +0,0 @@
import { defined } from '@stock-bot/invariants';
/**
* Generic utility functions that work with standardized types
* These functions demonstrate how to use generic types with OHLCV data
*/
import type { HasClose, HasOHLC, HasVolume, OHLCV } from '@stock-bot/types';
/**
* 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(defined(data[i]).high - defined(data[i]).low);
} else {
const current = defined(data[i]);
const previous = defined(data[i - 1]);
const tr = Math.max(
current.high - current.low,
Math.abs(current.high - previous.close),
Math.abs(current.low - previous.close)
);
result.push(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 = defined(closes[i]);
const previous = defined(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 = defined(closes[i]);
const previous = defined(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] = [];
}
defined(grouped[item.symbol]).push(item);
}
return grouped;
}
/**
* Convert timestamp to Date for OHLCV data
*/
export function convertTimestamps(data: OHLCV[]): Array<OHLCV & { date: Date }> {
return data.map(item => ({
...item,
date: new Date(item.timestamp),
}));
}

View file

@ -1,7 +1,5 @@
export * from './calculations/index';
export * from './assertions';
export * from './common';
export * from './dateUtils';
export * from './generic-functions';
export * from './fetch';
export * from './user-agent';
export { fetch } from './fetch';
export type { FetchOptions } from './fetch';
export { getRandomUserAgent } from './user-agent';
export { createProxyUrl, sleep } from './common';
export { dateUtils, utcDates } from './dateUtils';

View file

@ -0,0 +1,117 @@
import { describe, expect, it } from 'bun:test';
import { createProxyUrl, sleep } from '@stock-bot/utils/common';
import { dateUtils, utcDates } from '@stock-bot/utils/dates';
describe('restored general utilities', () => {
describe('common utilities', () => {
it('should create proxy URL with auth', () => {
const proxy = {
protocol: 'http',
host: '192.168.1.1',
port: 8080,
username: 'user',
password: 'pass',
};
const url = createProxyUrl(proxy);
expect(url).toBe('http://user:pass@192.168.1.1:8080');
});
it('should create proxy URL without auth', () => {
const proxy = {
protocol: 'socks5',
host: '192.168.1.1',
port: 1080,
};
const url = createProxyUrl(proxy);
expect(url).toBe('socks5://192.168.1.1:1080');
});
it('should sleep for specified milliseconds', async () => {
const start = Date.now();
await sleep(100);
const elapsed = Date.now() - start;
expect(elapsed).toBeGreaterThanOrEqual(90);
});
it('UTC weekday helpers preserve the supplied instant time and never mutate inputs', () => {
const friday = new Date('2024-03-08T23:30:00.000Z');
expect(utcDates.nextWeekday(friday).toISOString()).toBe('2024-03-11T23:30:00.000Z');
expect(friday.toISOString()).toBe('2024-03-08T23:30:00.000Z');
expect(utcDates.previousWeekday(new Date('2024-03-11T23:30:00Z')).toISOString()).toBe(
'2024-03-08T23:30:00.000Z'
);
// Christmas is a weekday, not a promise that any particular exchange is open.
expect(utcDates.isWeekday(new Date('2023-12-25T00:00:00Z'))).toBe(true);
const detached = utcDates.nextWeekday;
expect(detached(friday).getUTCDay()).toBe(1);
});
it('strict UTC dates reject invalid inputs and impossible calendar dates', () => {
expect(utcDates.parseDate('2024-02-29').toISOString()).toBe('2024-02-29T00:00:00.000Z');
for (const value of ['2023-02-29', '2024-02-30', '2024-13-01', '2024-01-01T00:00:00Z', '']) {
expect(() => utcDates.parseDate(value)).toThrow();
}
expect(() => utcDates.nextWeekday(new Date(NaN))).toThrow();
expect(() => utcDates.formatDate(new Date(NaN))).toThrow();
});
it('proxy credentials remain encoded and sleep remains asynchronous', async () => {
expect(
createProxyUrl({
protocol: 'http',
host: 'localhost',
port: 8080,
username: 'a@b',
password: 'p:/?',
})
).toBe('http://a%40b:p%3A%2F%3F@localhost:8080');
const wait = sleep(0);
expect(wait).toBeInstanceOf(Promise);
await wait;
});
});
describe('date utilities', () => {
it('should check if date is trading day', () => {
const monday = new Date('2023-12-25'); // Monday
const saturday = new Date('2023-12-23'); // Saturday
const sunday = new Date('2023-12-24'); // Sunday
expect(dateUtils.isTradingDay(monday)).toBe(true);
expect(dateUtils.isTradingDay(saturday)).toBe(false);
expect(dateUtils.isTradingDay(sunday)).toBe(false);
});
it('should get next trading day', () => {
const friday = new Date('2023-12-22'); // Friday
const nextDay = dateUtils.getNextTradingDay(friday);
expect(nextDay.getUTCDay()).toBe(1); // Monday
});
it('should get previous trading day', () => {
const monday = new Date('2023-12-25'); // Monday
const prevDay = dateUtils.getPreviousTradingDay(monday);
expect(prevDay.getUTCDay()).toBe(5); // Friday
});
it('should format date as YYYY-MM-DD', () => {
const date = new Date('2023-12-25T10:30:00Z');
const formatted = dateUtils.formatDate(date);
expect(formatted).toBe('2023-12-25');
});
it('should parse date from string', () => {
const date = dateUtils.parseDate('2023-12-25');
expect(date.getUTCFullYear()).toBe(2023);
expect(date.getUTCMonth()).toBe(11); // 0-based
expect(date.getUTCDate()).toBe(25);
});
});
});

View file

@ -1,13 +1,15 @@
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
import { fetch } from '../src/fetch';
import { fetch } from '@stock-bot/utils/fetch';
describe('Enhanced Fetch', () => {
let originalFetch: typeof globalThis.fetch;
let originalDebug: typeof console.debug;
let mockFetch: any;
let mockLogger: any;
beforeEach(() => {
originalFetch = globalThis.fetch;
originalDebug = console.debug;
mockFetch = mock(() => Promise.resolve(new Response('test')));
globalThis.fetch = mockFetch;
@ -20,6 +22,7 @@ describe('Enhanced Fetch', () => {
afterEach(() => {
globalThis.fetch = originalFetch;
console.debug = originalDebug;
});
describe('basic fetch', () => {
@ -209,8 +212,6 @@ describe('Enhanced Fetch', () => {
await fetch('https://api.example.com/data');
expect(consoleSpy).toHaveBeenCalledTimes(2); // Request and response
console.debug = originalFetch as any;
});
});

View file

@ -1,5 +1,5 @@
import { describe, expect, it } from 'bun:test';
import { getRandomUserAgent } from '../src/user-agent';
import { getRandomUserAgent } from '@stock-bot/utils/user-agent';
describe('User Agent', () => {
describe('getRandomUserAgent', () => {

View file

@ -1,232 +0,0 @@
import { describe, expect, it } from 'bun:test';
import {
calculateLogReturns,
calculateReturns,
calculateSMA,
calculateTrueRange,
calculateTypicalPrice,
calculateVWAP,
convertTimestamps,
// Common utilities
createProxyUrl,
// Date utilities
dateUtils,
// Generic functions
extractCloses,
extractOHLC,
extractVolumes,
filterBySymbol,
filterByTimeRange,
groupBySymbol,
sleep,
} from '../src/index';
describe('Utility Functions', () => {
describe('common utilities', () => {
it('should create proxy URL with auth', () => {
const proxy = {
protocol: 'http',
host: '192.168.1.1',
port: 8080,
username: 'user',
password: 'pass',
};
const url = createProxyUrl(proxy);
expect(url).toBe('http://user:pass@192.168.1.1:8080');
});
it('should create proxy URL without auth', () => {
const proxy = {
protocol: 'socks5',
host: '192.168.1.1',
port: 1080,
};
const url = createProxyUrl(proxy);
expect(url).toBe('socks5://192.168.1.1:1080');
});
it('should sleep for specified milliseconds', async () => {
const start = Date.now();
await sleep(100);
const elapsed = Date.now() - start;
expect(elapsed).toBeGreaterThanOrEqual(90);
expect(elapsed).toBeLessThan(200);
});
});
describe('date utilities', () => {
it('should check if date is trading day', () => {
const monday = new Date('2023-12-25'); // Monday
const saturday = new Date('2023-12-23'); // Saturday
const sunday = new Date('2023-12-24'); // Sunday
expect(dateUtils.isTradingDay(monday)).toBe(true);
expect(dateUtils.isTradingDay(saturday)).toBe(false);
expect(dateUtils.isTradingDay(sunday)).toBe(false);
});
it('should get next trading day', () => {
const friday = new Date('2023-12-22'); // Friday
const nextDay = dateUtils.getNextTradingDay(friday);
expect(nextDay.getDay()).toBe(1); // Monday
});
it('should get previous trading day', () => {
const monday = new Date('2023-12-25'); // Monday
const prevDay = dateUtils.getPreviousTradingDay(monday);
expect(prevDay.getDay()).toBe(5); // Friday
});
it('should format date as YYYY-MM-DD', () => {
const date = new Date('2023-12-25T10:30:00Z');
const formatted = dateUtils.formatDate(date);
expect(formatted).toBe('2023-12-25');
});
it('should parse date from string', () => {
const date = dateUtils.parseDate('2023-12-25');
expect(date.getFullYear()).toBe(2023);
expect(date.getMonth()).toBe(11); // 0-based
expect(date.getDate()).toBe(25);
});
});
describe('generic functions', () => {
const testData = [
{ open: 100, high: 105, low: 98, close: 103, volume: 1000 },
{ open: 103, high: 107, low: 101, close: 105, volume: 1200 },
{ open: 105, high: 108, low: 104, close: 106, volume: 1100 },
];
it('should extract close prices', () => {
const closes = extractCloses(testData);
expect(closes).toEqual([103, 105, 106]);
});
it('should extract OHLC data', () => {
const ohlc = extractOHLC(testData);
expect(ohlc.opens).toEqual([100, 103, 105]);
expect(ohlc.highs).toEqual([105, 107, 108]);
expect(ohlc.lows).toEqual([98, 101, 104]);
expect(ohlc.closes).toEqual([103, 105, 106]);
});
it('should extract volumes', () => {
const volumes = extractVolumes(testData);
expect(volumes).toEqual([1000, 1200, 1100]);
});
it('should calculate SMA', () => {
const sma = calculateSMA(testData, 2);
expect(sma).toHaveLength(2);
expect(sma[0]).toBe(104);
expect(sma[1]).toBe(105.5);
});
it('should calculate typical price', () => {
const typical = calculateTypicalPrice(testData);
expect(typical[0]).toBeCloseTo((105 + 98 + 103) / 3);
expect(typical[1]).toBeCloseTo((107 + 101 + 105) / 3);
expect(typical[2]).toBeCloseTo((108 + 104 + 106) / 3);
});
it('should calculate true range', () => {
const tr = calculateTrueRange(testData);
expect(tr).toHaveLength(3);
expect(tr[0]).toBe(7); // 105 - 98
});
it('should calculate returns', () => {
const returns = calculateReturns(testData);
expect(returns).toHaveLength(2);
expect(returns[0]).toBeCloseTo((105 - 103) / 103);
expect(returns[1]).toBeCloseTo((106 - 105) / 105);
});
it('should calculate log returns', () => {
const logReturns = calculateLogReturns(testData);
expect(logReturns).toHaveLength(2);
expect(logReturns[0]).toBeCloseTo(Math.log(105 / 103));
expect(logReturns[1]).toBeCloseTo(Math.log(106 / 105));
});
it('should calculate VWAP', () => {
const vwap = calculateVWAP(testData);
expect(vwap).toHaveLength(3);
expect(vwap[0]).toBeGreaterThan(0);
});
});
describe('OHLCV data operations', () => {
const ohlcvData = [
{
symbol: 'AAPL',
open: 100,
high: 105,
low: 98,
close: 103,
volume: 1000,
timestamp: 1000000,
},
{
symbol: 'GOOGL',
open: 200,
high: 205,
low: 198,
close: 203,
volume: 2000,
timestamp: 1000000,
},
{
symbol: 'AAPL',
open: 103,
high: 107,
low: 101,
close: 105,
volume: 1200,
timestamp: 2000000,
},
];
it('should filter by symbol', () => {
const filtered = filterBySymbol(ohlcvData, 'AAPL');
expect(filtered).toHaveLength(2);
expect(filtered.every(item => item.symbol === 'AAPL')).toBe(true);
});
it('should filter by time range', () => {
const filtered = filterByTimeRange(ohlcvData, 1500000, 2500000);
expect(filtered).toHaveLength(1);
expect(filtered[0].timestamp).toBe(2000000);
});
it('should group by symbol', () => {
const grouped = groupBySymbol(ohlcvData);
expect(grouped['AAPL']).toHaveLength(2);
expect(grouped['GOOGL']).toHaveLength(1);
});
it('should convert timestamps to dates', () => {
const converted = convertTimestamps(ohlcvData);
expect(converted[0].date).toBeInstanceOf(Date);
expect(converted[0].date.getTime()).toBe(1000000);
});
});
});

View file

@ -10,20 +10,11 @@
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"],
"references": [
{
"path": "../core/types"
},
{
"path": "../core/cache"
},
{
"path": "../core/config"
},
{
"path": "../core/logger"
},
{
"path": "../../libs/core/invariants"
"path": "../core/invariants"
}
]
}