added calcs
This commit is contained in:
parent
ef12c9d308
commit
7886b7cfa5
10 changed files with 4331 additions and 0 deletions
835
libs/utils/src/calculations/correlation-analysis.ts
Normal file
835
libs/utils/src/calculations/correlation-analysis.ts
Normal file
|
|
@ -0,0 +1,835 @@
|
|||
/**
|
||||
* Correlation Analysis Module
|
||||
*
|
||||
* Provides comprehensive correlation and covariance analysis tools for financial time series.
|
||||
* Includes correlation matrices, rolling correlations, regime-dependent correlations,
|
||||
* and advanced correlation modeling techniques.
|
||||
*/
|
||||
|
||||
export interface CorrelationResult {
|
||||
correlation: number;
|
||||
pValue: number;
|
||||
significance: boolean;
|
||||
confidenceInterval?: [number, number];
|
||||
}
|
||||
|
||||
export interface CorrelationMatrix {
|
||||
matrix: number[][];
|
||||
labels: string[];
|
||||
eigenvalues: number[];
|
||||
eigenvectors: number[][];
|
||||
conditionNumber: number;
|
||||
}
|
||||
|
||||
export interface RollingCorrelationResult {
|
||||
correlations: number[];
|
||||
timestamps: Date[];
|
||||
average: number;
|
||||
volatility: number;
|
||||
min: number;
|
||||
max: number;
|
||||
}
|
||||
|
||||
export interface CovarianceMatrix {
|
||||
matrix: number[][];
|
||||
labels: string[];
|
||||
volatilities: number[];
|
||||
correlations: number[][];
|
||||
eigenvalues: number[];
|
||||
determinant: number;
|
||||
}
|
||||
|
||||
export interface CorrelationBreakdown {
|
||||
linear: number;
|
||||
nonlinear: number;
|
||||
tail: number;
|
||||
rank: number;
|
||||
}
|
||||
|
||||
export interface DynamicCorrelationModel {
|
||||
parameters: number[];
|
||||
correlations: number[];
|
||||
logLikelihood: number;
|
||||
aic: number;
|
||||
bic: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Pearson correlation coefficient between two time series
|
||||
*/
|
||||
export function pearsonCorrelation(
|
||||
x: number[],
|
||||
y: number[]
|
||||
): CorrelationResult {
|
||||
if (x.length !== y.length || x.length < 2) {
|
||||
throw new Error('Arrays must have same length and at least 2 observations');
|
||||
}
|
||||
|
||||
const n = x.length;
|
||||
const sumX = x.reduce((a, b) => a + b, 0);
|
||||
const sumY = y.reduce((a, b) => a + b, 0);
|
||||
const sumXY = x.reduce((sum, xi, i) => sum + xi * y[i], 0);
|
||||
const sumX2 = x.reduce((sum, xi) => sum + xi * xi, 0);
|
||||
const sumY2 = y.reduce((sum, yi) => sum + yi * yi, 0);
|
||||
|
||||
const numerator = n * sumXY - sumX * sumY;
|
||||
const denominator = Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY));
|
||||
|
||||
const correlation = denominator === 0 ? 0 : numerator / denominator;
|
||||
|
||||
// Calculate statistical significance (t-test)
|
||||
const df = n - 2;
|
||||
const tStat = correlation * Math.sqrt(df / (1 - correlation * correlation));
|
||||
const pValue = 2 * (1 - studentTCDF(Math.abs(tStat), df));
|
||||
const significance = pValue < 0.05;
|
||||
|
||||
// Calculate confidence interval (Fisher transformation)
|
||||
const z = 0.5 * Math.log((1 + correlation) / (1 - correlation));
|
||||
const seZ = 1 / Math.sqrt(n - 3);
|
||||
const zLower = z - 1.96 * seZ;
|
||||
const zUpper = z + 1.96 * seZ;
|
||||
const confidenceInterval: [number, number] = [
|
||||
(Math.exp(2 * zLower) - 1) / (Math.exp(2 * zLower) + 1),
|
||||
(Math.exp(2 * zUpper) - 1) / (Math.exp(2 * zUpper) + 1)
|
||||
];
|
||||
|
||||
return {
|
||||
correlation,
|
||||
pValue,
|
||||
significance,
|
||||
confidenceInterval
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Spearman rank correlation coefficient
|
||||
*/
|
||||
export function spearmanCorrelation(x: number[], y: number[]): CorrelationResult {
|
||||
if (x.length !== y.length || x.length < 2) {
|
||||
throw new Error('Arrays must have same length and at least 2 observations');
|
||||
}
|
||||
|
||||
// Convert to ranks
|
||||
const xRanks = getRanks(x);
|
||||
const yRanks = getRanks(y);
|
||||
|
||||
return pearsonCorrelation(xRanks, yRanks);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Kendall's tau correlation coefficient
|
||||
*/
|
||||
export function kendallTau(x: number[], y: number[]): CorrelationResult {
|
||||
if (x.length !== y.length || x.length < 2) {
|
||||
throw new Error('Arrays must have same length and at least 2 observations');
|
||||
}
|
||||
|
||||
const n = x.length;
|
||||
let concordant = 0;
|
||||
let discordant = 0;
|
||||
|
||||
for (let i = 0; i < n - 1; i++) {
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
const xDiff = x[i] - x[j];
|
||||
const yDiff = y[i] - y[j];
|
||||
|
||||
if (xDiff * yDiff > 0) {
|
||||
concordant++;
|
||||
} else if (xDiff * yDiff < 0) {
|
||||
discordant++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const correlation = (concordant - discordant) / (n * (n - 1) / 2);
|
||||
|
||||
// Approximate p-value for large samples
|
||||
const variance = (2 * (2 * n + 5)) / (9 * n * (n - 1));
|
||||
const z = correlation / Math.sqrt(variance);
|
||||
const pValue = 2 * (1 - normalCDF(Math.abs(z)));
|
||||
const significance = pValue < 0.05;
|
||||
|
||||
return {
|
||||
correlation,
|
||||
pValue,
|
||||
significance
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate correlation matrix for multiple time series
|
||||
*/
|
||||
export function correlationMatrix(
|
||||
data: number[][],
|
||||
labels: string[] = [],
|
||||
method: 'pearson' | 'spearman' | 'kendall' = 'pearson'
|
||||
): CorrelationMatrix {
|
||||
const n = data.length;
|
||||
|
||||
if (labels.length === 0) {
|
||||
labels = Array.from({ length: n }, (_, i) => `Series${i + 1}`);
|
||||
}
|
||||
|
||||
const matrix: number[][] = Array(n).fill(null).map(() => Array(n).fill(0));
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
if (i === j) {
|
||||
matrix[i][j] = 1;
|
||||
} else {
|
||||
let corrResult: CorrelationResult;
|
||||
switch (method) {
|
||||
case 'spearman':
|
||||
corrResult = spearmanCorrelation(data[i], data[j]);
|
||||
break;
|
||||
case 'kendall':
|
||||
corrResult = kendallTau(data[i], data[j]);
|
||||
break;
|
||||
default:
|
||||
corrResult = pearsonCorrelation(data[i], data[j]);
|
||||
}
|
||||
matrix[i][j] = corrResult.correlation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate eigenvalues and eigenvectors
|
||||
const { eigenvalues, eigenvectors } = eigenDecomposition(matrix);
|
||||
|
||||
// Calculate condition number
|
||||
const conditionNumber = Math.max(...eigenvalues) / Math.min(...eigenvalues.filter(x => x > 1e-10));
|
||||
|
||||
return {
|
||||
matrix,
|
||||
labels,
|
||||
eigenvalues,
|
||||
eigenvectors,
|
||||
conditionNumber
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate rolling correlation between two time series
|
||||
*/
|
||||
export function rollingCorrelation(
|
||||
x: number[],
|
||||
y: number[],
|
||||
window: number,
|
||||
timestamps?: Date[]
|
||||
): RollingCorrelationResult {
|
||||
if (x.length !== y.length || window > x.length) {
|
||||
throw new Error('Invalid input parameters');
|
||||
}
|
||||
|
||||
const correlations: number[] = [];
|
||||
const resultTimestamps: Date[] = [];
|
||||
|
||||
for (let i = window - 1; i < x.length; i++) {
|
||||
const xWindow = x.slice(i - window + 1, i + 1);
|
||||
const yWindow = y.slice(i - window + 1, i + 1);
|
||||
|
||||
const corr = pearsonCorrelation(xWindow, yWindow).correlation;
|
||||
correlations.push(corr);
|
||||
|
||||
if (timestamps) {
|
||||
resultTimestamps.push(timestamps[i]);
|
||||
} else {
|
||||
resultTimestamps.push(new Date(i));
|
||||
}
|
||||
}
|
||||
|
||||
const average = correlations.reduce((a, b) => a + b, 0) / correlations.length;
|
||||
const variance = correlations.reduce((sum, corr) => sum + Math.pow(corr - average, 2), 0) / correlations.length;
|
||||
const volatility = Math.sqrt(variance);
|
||||
const min = Math.min(...correlations);
|
||||
const max = Math.max(...correlations);
|
||||
|
||||
return {
|
||||
correlations,
|
||||
timestamps: resultTimestamps,
|
||||
average,
|
||||
volatility,
|
||||
min,
|
||||
max
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate covariance matrix
|
||||
*/
|
||||
export function covarianceMatrix(data: number[][], labels: string[] = []): CovarianceMatrix {
|
||||
const n = data.length;
|
||||
|
||||
if (labels.length === 0) {
|
||||
labels = Array.from({ length: n }, (_, i) => `Series${i + 1}`);
|
||||
}
|
||||
|
||||
// Calculate means
|
||||
const means = data.map(series => series.reduce((a, b) => a + b, 0) / series.length);
|
||||
|
||||
// Calculate covariance matrix
|
||||
const matrix: number[][] = Array(n).fill(null).map(() => Array(n).fill(0));
|
||||
const m = data[0].length; // Number of observations
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
let covariance = 0;
|
||||
for (let k = 0; k < m; k++) {
|
||||
covariance += (data[i][k] - means[i]) * (data[j][k] - means[j]);
|
||||
}
|
||||
matrix[i][j] = covariance / (m - 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate volatilities (standard deviations)
|
||||
const volatilities = data.map((series, i) => Math.sqrt(matrix[i][i]));
|
||||
|
||||
// Calculate correlation matrix from covariance matrix
|
||||
const correlations: number[][] = Array(n).fill(null).map(() => Array(n).fill(0));
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
correlations[i][j] = matrix[i][j] / (volatilities[i] * volatilities[j]);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate eigenvalues
|
||||
const { eigenvalues } = eigenDecomposition(matrix);
|
||||
|
||||
// Calculate determinant
|
||||
const determinant = eigenvalues.reduce((prod, val) => prod * val, 1);
|
||||
|
||||
return {
|
||||
matrix,
|
||||
labels,
|
||||
volatilities,
|
||||
correlations,
|
||||
eigenvalues,
|
||||
determinant
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate partial correlation controlling for other variables
|
||||
*/
|
||||
export function partialCorrelation(
|
||||
x: number[],
|
||||
y: number[],
|
||||
controls: number[][]
|
||||
): CorrelationResult {
|
||||
// Use matrix operations to calculate partial correlation
|
||||
const n = x.length;
|
||||
const k = controls.length;
|
||||
|
||||
// Build design matrix
|
||||
const X = Array(n).fill(null).map(() => Array(k + 1).fill(1));
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < k; j++) {
|
||||
X[i][j + 1] = controls[j][i];
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate residuals for x and y after regressing on controls
|
||||
const xResiduals = calculateResiduals(x, X);
|
||||
const yResiduals = calculateResiduals(y, X);
|
||||
|
||||
return pearsonCorrelation(xResiduals, yResiduals);
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for correlation regime changes
|
||||
*/
|
||||
export function correlationRegimeAnalysis(
|
||||
x: number[],
|
||||
y: number[],
|
||||
window: number = 60
|
||||
): {
|
||||
regimes: { start: number; end: number; correlation: number }[];
|
||||
breakpoints: number[];
|
||||
stability: number;
|
||||
} {
|
||||
const rollingCorr = rollingCorrelation(x, y, window);
|
||||
const correlations = rollingCorr.correlations;
|
||||
|
||||
// Detect regime changes using CUSUM test
|
||||
const breakpoints: number[] = [];
|
||||
const threshold = 2.0; // CUSUM threshold
|
||||
|
||||
let cusum = 0;
|
||||
const mean = correlations.reduce((a, b) => a + b, 0) / correlations.length;
|
||||
|
||||
for (let i = 1; i < correlations.length; i++) {
|
||||
cusum += correlations[i] - mean;
|
||||
if (Math.abs(cusum) > threshold) {
|
||||
breakpoints.push(i);
|
||||
cusum = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Build regimes
|
||||
const regimes: { start: number; end: number; correlation: number }[] = [];
|
||||
let start = 0;
|
||||
|
||||
for (const breakpoint of breakpoints) {
|
||||
const regimeCorr = correlations.slice(start, breakpoint);
|
||||
const avgCorr = regimeCorr.reduce((a, b) => a + b, 0) / regimeCorr.length;
|
||||
|
||||
regimes.push({
|
||||
start,
|
||||
end: breakpoint,
|
||||
correlation: avgCorr
|
||||
});
|
||||
start = breakpoint;
|
||||
}
|
||||
|
||||
// Add final regime
|
||||
if (start < correlations.length) {
|
||||
const regimeCorr = correlations.slice(start);
|
||||
const avgCorr = regimeCorr.reduce((a, b) => a + b, 0) / regimeCorr.length;
|
||||
|
||||
regimes.push({
|
||||
start,
|
||||
end: correlations.length,
|
||||
correlation: avgCorr
|
||||
});
|
||||
}
|
||||
|
||||
// Calculate stability measure
|
||||
const regimeVariances = regimes.map(regime => {
|
||||
const regimeCorr = correlations.slice(regime.start, regime.end);
|
||||
const mean = regime.correlation;
|
||||
return regimeCorr.reduce((sum, corr) => sum + Math.pow(corr - mean, 2), 0) / regimeCorr.length;
|
||||
});
|
||||
|
||||
const stability = 1 / (1 + regimeVariances.reduce((a, b) => a + b, 0) / regimeVariances.length);
|
||||
|
||||
return {
|
||||
regimes,
|
||||
breakpoints,
|
||||
stability
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate tail correlation using copula methods
|
||||
*/
|
||||
export function tailCorrelation(
|
||||
x: number[],
|
||||
y: number[],
|
||||
threshold: number = 0.05
|
||||
): {
|
||||
upperTail: number;
|
||||
lowerTail: number;
|
||||
symmetric: boolean;
|
||||
} {
|
||||
const n = x.length;
|
||||
const upperThreshold = 1 - threshold;
|
||||
const lowerThreshold = threshold;
|
||||
|
||||
// Convert to uniform marginals
|
||||
const xRanks = getRanks(x).map(rank => rank / n);
|
||||
const yRanks = getRanks(y).map(rank => rank / n);
|
||||
|
||||
// Upper tail correlation
|
||||
let upperCount = 0;
|
||||
let upperTotal = 0;
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
if (xRanks[i] > upperThreshold) {
|
||||
upperTotal++;
|
||||
if (yRanks[i] > upperThreshold) {
|
||||
upperCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const upperTail = upperTotal > 0 ? upperCount / upperTotal : 0;
|
||||
|
||||
// Lower tail correlation
|
||||
let lowerCount = 0;
|
||||
let lowerTotal = 0;
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
if (xRanks[i] < lowerThreshold) {
|
||||
lowerTotal++;
|
||||
if (yRanks[i] < lowerThreshold) {
|
||||
lowerCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const lowerTail = lowerTotal > 0 ? lowerCount / lowerTotal : 0;
|
||||
|
||||
// Test for symmetry
|
||||
const symmetric = Math.abs(upperTail - lowerTail) < 0.1;
|
||||
|
||||
return {
|
||||
upperTail,
|
||||
lowerTail,
|
||||
symmetric
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamic Conditional Correlation (DCC) model estimation
|
||||
*/
|
||||
export function dccModel(
|
||||
data: number[][],
|
||||
maxIter: number = 100,
|
||||
tolerance: number = 1e-6
|
||||
): DynamicCorrelationModel {
|
||||
const n = data.length;
|
||||
const T = data[0].length;
|
||||
|
||||
// Initialize parameters [alpha, beta]
|
||||
let params = [0.01, 0.95];
|
||||
|
||||
// Standardize data (assume unit variance for simplicity)
|
||||
const standardizedData = data.map(series => {
|
||||
const mean = series.reduce((a, b) => a + b, 0) / series.length;
|
||||
const variance = series.reduce((sum, x) => sum + Math.pow(x - mean, 2), 0) / (series.length - 1);
|
||||
const std = Math.sqrt(variance);
|
||||
return series.map(x => (x - mean) / std);
|
||||
});
|
||||
|
||||
let correlations: number[] = [];
|
||||
let logLikelihood = -Infinity;
|
||||
|
||||
for (let iter = 0; iter < maxIter; iter++) {
|
||||
const [alpha, beta] = params;
|
||||
|
||||
// Calculate dynamic correlations
|
||||
correlations = [];
|
||||
|
||||
// Initialize with unconditional correlation
|
||||
const unconditionalCorr = pearsonCorrelation(standardizedData[0], standardizedData[1]).correlation;
|
||||
let Qt = unconditionalCorr;
|
||||
|
||||
let newLogLikelihood = 0;
|
||||
|
||||
for (let t = 1; t < T; t++) {
|
||||
// Update correlation
|
||||
const prevShock = standardizedData[0][t-1] * standardizedData[1][t-1];
|
||||
Qt = (1 - alpha - beta) * unconditionalCorr + alpha * prevShock + beta * Qt;
|
||||
|
||||
correlations.push(Qt);
|
||||
|
||||
// Add to log-likelihood
|
||||
const det = 1 - Qt * Qt;
|
||||
if (det > 0) {
|
||||
newLogLikelihood -= 0.5 * Math.log(det);
|
||||
newLogLikelihood -= 0.5 * (
|
||||
Math.pow(standardizedData[0][t], 2) +
|
||||
Math.pow(standardizedData[1][t], 2) -
|
||||
2 * Qt * standardizedData[0][t] * standardizedData[1][t]
|
||||
) / det;
|
||||
}
|
||||
}
|
||||
|
||||
// Check convergence
|
||||
if (Math.abs(newLogLikelihood - logLikelihood) < tolerance) {
|
||||
break;
|
||||
}
|
||||
|
||||
logLikelihood = newLogLikelihood;
|
||||
|
||||
// Simple gradient update (in practice, use more sophisticated optimization)
|
||||
params[0] = Math.max(0.001, Math.min(0.999, params[0] + 0.001));
|
||||
params[1] = Math.max(0.001, Math.min(0.999 - params[0], params[1] + 0.001));
|
||||
}
|
||||
|
||||
// Calculate information criteria
|
||||
const k = 2; // Number of parameters
|
||||
const aic = -2 * logLikelihood + 2 * k;
|
||||
const bic = -2 * logLikelihood + k * Math.log(T);
|
||||
|
||||
return {
|
||||
parameters: params,
|
||||
correlations,
|
||||
logLikelihood,
|
||||
aic,
|
||||
bic
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Test for Granger causality in correlations
|
||||
*/
|
||||
export function grangerCausalityTest(
|
||||
x: number[],
|
||||
y: number[],
|
||||
maxLag: number = 5
|
||||
): {
|
||||
xCausesY: { fStatistic: number; pValue: number; significant: boolean };
|
||||
yCausesX: { fStatistic: number; pValue: number; significant: boolean };
|
||||
optimalLag: number;
|
||||
} {
|
||||
let bestLag = 1;
|
||||
let minAIC = Infinity;
|
||||
|
||||
// Find optimal lag
|
||||
for (let lag = 1; lag <= maxLag; lag++) {
|
||||
const aic = calculateVARModel(x, y, lag).aic;
|
||||
if (aic < minAIC) {
|
||||
minAIC = aic;
|
||||
bestLag = lag;
|
||||
}
|
||||
}
|
||||
|
||||
// Test x -> y causality
|
||||
const fullModel = calculateVARModel(x, y, bestLag);
|
||||
const restrictedModelY = calculateARModel(y, bestLag);
|
||||
|
||||
const fStatX = ((restrictedModelY.rss - fullModel.rssY) / bestLag) / (fullModel.rssY / (x.length - 2 * bestLag - 1));
|
||||
const pValueX = 1 - fCDF(fStatX, bestLag, x.length - 2 * bestLag - 1);
|
||||
|
||||
// Test y -> x causality
|
||||
const restrictedModelX = calculateARModel(x, bestLag);
|
||||
|
||||
const fStatY = ((restrictedModelX.rss - fullModel.rssX) / bestLag) / (fullModel.rssX / (x.length - 2 * bestLag - 1));
|
||||
const pValueY = 1 - fCDF(fStatY, bestLag, x.length - 2 * bestLag - 1);
|
||||
|
||||
return {
|
||||
xCausesY: {
|
||||
fStatistic: fStatX,
|
||||
pValue: pValueX,
|
||||
significant: pValueX < 0.05
|
||||
},
|
||||
yCausesX: {
|
||||
fStatistic: fStatY,
|
||||
pValue: pValueY,
|
||||
significant: pValueY < 0.05
|
||||
},
|
||||
optimalLag: bestLag
|
||||
};
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
function getRanks(arr: number[]): number[] {
|
||||
const sorted = arr.map((val, idx) => ({ val, idx })).sort((a, b) => a.val - b.val);
|
||||
const ranks = new Array(arr.length);
|
||||
|
||||
for (let i = 0; i < sorted.length; i++) {
|
||||
ranks[sorted[i].idx] = i + 1;
|
||||
}
|
||||
|
||||
return ranks;
|
||||
}
|
||||
|
||||
function studentTCDF(t: number, df: number): number {
|
||||
// Approximation for Student's t CDF
|
||||
const x = df / (t * t + df);
|
||||
return 1 - 0.5 * betaIncomplete(df / 2, 0.5, x);
|
||||
}
|
||||
|
||||
function normalCDF(z: number): number {
|
||||
return 0.5 * (1 + erf(z / Math.sqrt(2)));
|
||||
}
|
||||
|
||||
function erf(x: number): number {
|
||||
// Approximation of error function
|
||||
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;
|
||||
}
|
||||
|
||||
function betaIncomplete(a: number, b: number, x: number): number {
|
||||
// Simplified beta incomplete function
|
||||
if (x === 0) return 0;
|
||||
if (x === 1) return 1;
|
||||
|
||||
// Use continued fraction approximation
|
||||
let result = 0;
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const term = Math.pow(x, a + i) * Math.pow(1 - x, b) / (a + i);
|
||||
result += term;
|
||||
if (Math.abs(term) < 1e-10) break;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function eigenDecomposition(matrix: number[][]): { eigenvalues: number[]; eigenvectors: number[][] } {
|
||||
// Simplified eigenvalue decomposition (for symmetric matrices)
|
||||
const n = matrix.length;
|
||||
|
||||
// Power iteration for largest eigenvalue
|
||||
const eigenvalues: number[] = [];
|
||||
const eigenvectors: number[][] = [];
|
||||
|
||||
for (let k = 0; k < Math.min(n, 3); k++) { // Calculate first 3 eigenvalues
|
||||
let v = Array(n).fill(1 / Math.sqrt(n));
|
||||
let lambda = 0;
|
||||
|
||||
for (let iter = 0; iter < 100; iter++) {
|
||||
const Av = matrix.map(row => row.reduce((sum, val, i) => sum + val * v[i], 0));
|
||||
const newLambda = Av.reduce((sum, val, i) => sum + val * v[i], 0);
|
||||
const norm = Math.sqrt(Av.reduce((sum, val) => sum + val * val, 0));
|
||||
|
||||
if (norm === 0) break;
|
||||
|
||||
v = Av.map(val => val / norm);
|
||||
|
||||
if (Math.abs(newLambda - lambda) < 1e-10) break;
|
||||
lambda = newLambda;
|
||||
}
|
||||
|
||||
eigenvalues.push(lambda);
|
||||
eigenvectors.push([...v]);
|
||||
|
||||
// Deflate matrix for next eigenvalue
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
matrix[i][j] -= lambda * v[i] * v[j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { eigenvalues, eigenvectors };
|
||||
}
|
||||
|
||||
function calculateResiduals(y: number[], X: number[][]): number[] {
|
||||
// Simple linear regression to calculate residuals
|
||||
const n = y.length;
|
||||
const k = X[0].length;
|
||||
|
||||
// Calculate (X'X)^-1 X' y
|
||||
const XtX = Array(k).fill(null).map(() => Array(k).fill(0));
|
||||
const Xty = Array(k).fill(0);
|
||||
|
||||
// X'X
|
||||
for (let i = 0; i < k; i++) {
|
||||
for (let j = 0; j < k; j++) {
|
||||
for (let t = 0; t < n; t++) {
|
||||
XtX[i][j] += X[t][i] * X[t][j];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// X'y
|
||||
for (let i = 0; i < k; i++) {
|
||||
for (let t = 0; t < n; t++) {
|
||||
Xty[i] += X[t][i] * y[t];
|
||||
}
|
||||
}
|
||||
|
||||
// Solve for beta (simplified - assumes invertible)
|
||||
const beta = solveLinearSystem(XtX, Xty);
|
||||
|
||||
// Calculate residuals
|
||||
const residuals: number[] = [];
|
||||
for (let t = 0; t < n; t++) {
|
||||
let fitted = 0;
|
||||
for (let i = 0; i < k; i++) {
|
||||
fitted += X[t][i] * beta[i];
|
||||
}
|
||||
residuals.push(y[t] - fitted);
|
||||
}
|
||||
|
||||
return residuals;
|
||||
}
|
||||
|
||||
function solveLinearSystem(A: number[][], b: number[]): number[] {
|
||||
// Gaussian elimination (simplified)
|
||||
const n = A.length;
|
||||
const augmented = A.map((row, i) => [...row, b[i]]);
|
||||
|
||||
// Forward elimination
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
const factor = augmented[j][i] / augmented[i][i];
|
||||
for (let k = i; k <= n; k++) {
|
||||
augmented[j][k] -= factor * augmented[i][k];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Back substitution
|
||||
const x = Array(n).fill(0);
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
x[i] = augmented[i][n];
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
x[i] -= augmented[i][j] * x[j];
|
||||
}
|
||||
x[i] /= augmented[i][i];
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
function calculateVARModel(x: number[], y: number[], lag: number): {
|
||||
rssX: number;
|
||||
rssY: number;
|
||||
aic: number;
|
||||
} {
|
||||
// Simplified VAR model calculation
|
||||
const n = x.length - lag;
|
||||
|
||||
// Build design matrix
|
||||
const X = Array(n).fill(null).map(() => Array(2 * lag + 1).fill(1));
|
||||
const yX = Array(n).fill(0);
|
||||
const yY = Array(n).fill(0);
|
||||
|
||||
for (let t = 0; t < n; t++) {
|
||||
yX[t] = x[t + lag];
|
||||
yY[t] = y[t + lag];
|
||||
|
||||
for (let l = 0; l < lag; l++) {
|
||||
X[t][1 + l] = x[t + lag - 1 - l];
|
||||
X[t][1 + lag + l] = y[t + lag - 1 - l];
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate residuals for both equations
|
||||
const residualsX = calculateResiduals(yX, X);
|
||||
const residualsY = calculateResiduals(yY, X);
|
||||
|
||||
const rssX = residualsX.reduce((sum, r) => sum + r * r, 0);
|
||||
const rssY = residualsY.reduce((sum, r) => sum + r * r, 0);
|
||||
|
||||
const k = 2 * lag + 1;
|
||||
const aic = n * Math.log(rssX + rssY) + 2 * k;
|
||||
|
||||
return { rssX, rssY, aic };
|
||||
}
|
||||
|
||||
function calculateARModel(y: number[], lag: number): { rss: number } {
|
||||
const n = y.length - lag;
|
||||
|
||||
// Build design matrix
|
||||
const X = Array(n).fill(null).map(() => Array(lag + 1).fill(1));
|
||||
const yVec = Array(n).fill(0);
|
||||
|
||||
for (let t = 0; t < n; t++) {
|
||||
yVec[t] = y[t + lag];
|
||||
|
||||
for (let l = 0; l < lag; l++) {
|
||||
X[t][1 + l] = y[t + lag - 1 - l];
|
||||
}
|
||||
}
|
||||
|
||||
const residuals = calculateResiduals(yVec, X);
|
||||
const rss = residuals.reduce((sum, r) => sum + r * r, 0);
|
||||
|
||||
return { rss };
|
||||
}
|
||||
|
||||
function fCDF(f: number, df1: number, df2: number): number {
|
||||
// Approximation for F distribution CDF
|
||||
if (f <= 0) return 0;
|
||||
if (f === Infinity) return 1;
|
||||
|
||||
const x = df2 / (df2 + df1 * f);
|
||||
return 1 - betaIncomplete(df2 / 2, df1 / 2, x);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue