Technical indicators library for financial analysis
npm install @vesper85/technical-indicatorsA library for calculating technical indicators used in financial analysis and trading.
``bash`
pnpm add @osiris-ai/technical-indicators
`typescript
import { calculateSMA, calculateRSI, calculateMACD } from '@osiris-ai/technical-indicators';
// Simple Moving Average
const closes = [100, 102, 101, 105, 107, 109, 108];
const sma = calculateSMA(closes, { period: 5 });
console.log(sma); // 106.4 (single number)
// RSI
const rsi = calculateRSI(closes, { period: 14 });
console.log(rsi); // 65.5 (single number)
// MACD (returns array)
const macd = calculateMACD(closes, {
fastPeriod: 12,
slowPeriod: 26,
signalPeriod: 9
});
console.log(macd); // [0.5, 0.3, 0.2] - [MACD, signal, histogram]
`
`typescript
import { TechnicalAnalysisService } from '@osiris-ai/technical-indicators';
import { Logger } from '@osiris-ai/logger';
const service = new TechnicalAnalysisService({ logger: new Logger() });
// OHLCV data format
const ohlcvData = [
{
timestamp: 1640995200000,
open: 100,
high: 105,
low: 99,
close: 103,
volume: 1000000
},
// ... more candles
];
// Calculate RSI
const rsi = service.calculate('rsi_14', ohlcvData, { period: 14 });
console.log(rsi); // 65.5
// Calculate MACD with component selection
const macdSignal = service.calculate(
'macd_12_26_9',
ohlcvData,
{ component: 'signal' }
);
console.log(macdSignal); // 0.3 (just the signal line)
`
Individual Functions:
- Price arrays: number[] - Array of closing prices, highs, lows, etc.number[]
- Volume arrays: - Array of volume valuesTAParams
- Parameters: - Object containing indicator-specific parameters
TechnicalAnalysisService:
- Data: OHLCV[] - Array of OHLCV objects`
typescript`
interface OHLCV {
timestamp: number;
open: number;
high: number;
low: number;
close: number;
volume: number;
}
string
- Indicator: - Indicator name with parameters (e.g., "rsi_14", "macd_12_26_9")TAParams & { component?: string }
- Params: - Additional parameters and optional component selector
Single Value Indicators (return number):
- RSI, EMA, SMA, ATR, ADX, OBV, CCI, MFI, VWAP, WilliamsR, ROC, PSAR, WMA
Multi-Value Indicators (return number[]):[MACD, signal, histogram]
- MACD: [upper, middle, lower]
- Bollinger Bands: [%K, %D]
- Stochastic: [%K, %D]
- Stochastic RSI: [upper, lower, middle]
- Keltner Channels:
`typescript
// Single value output
const rsi: number = calculateRSI([100, 102, 101, 105, 107], { period: 5 });
// Result: 65.5
// Array output - MACD
const macd: number[] = calculateMACD(closes, {
fastPeriod: 12,
slowPeriod: 26,
signalPeriod: 9
});
// Result: [0.5, 0.3, 0.2]
// Array output - Bollinger Bands
const bb: number[] = calculateBollingerBands(closes, {
period: 20,
stdDev: 2
});
// Result: [110.5, 105.0, 99.5] // [upper, middle, lower]
// Using component selector with service
const upperBand: number = service.calculate(
'bb_20_2',
ohlcvData,
{ component: 'upper' }
);
// Result: 110.5 (just the upper band)
`
- SMA (Simple Moving Average) - calculateSMAcalculateEMA
- EMA (Exponential Moving Average) - calculateRSI
- RSI (Relative Strength Index) - calculateMACD
- MACD (Moving Average Convergence Divergence) - calculateATR
- ATR (Average True Range) - calculateBollingerBands
- Bollinger Bands - calculateADX
- ADX (Average Directional Index) - calculateStochastic
- Stochastic - calculateOBV
- OBV (On-Balance Volume) - calculateCCI
- CCI (Commodity Channel Index) - calculateMFI
- MFI (Money Flow Index) - calculateVWAP
- VWAP (Volume Weighted Average Price) - calculateWilliamsR
- Williams %R - calculateStochasticRSI
- Stochastic RSI - calculateROC
- ROC (Rate of Change) - calculateParabolicSAR
- Parabolic SAR - calculateKeltnerChannels
- Keltner Channels - calculateWMA
- WMA (Weighted Moving Average) -
Follow this checklist when adding a new technical indicator:
array in src/indicators/index.ts
- [ ] If indicator has multiple components (e.g., MACD, Bollinger Bands), add entry to availableComponents object$3
- [ ] Create calculate[IndicatorName] function in src/indicators/index.ts
- [ ] Define function signature with appropriate input arrays and TAParams
- [ ] Return type: number for single value, number[] for multi-value indicators
- [ ] Add parameter validation (check required params, minimum data length)
- [ ] Use technicalindicators library for calculation
- [ ] Return the last calculated value (for single) or array of values (for multi-value)$3
- [ ] Add case in calculate() method switch statement in src/index.ts
- [ ] Handle component selection if indicator has multiple components
- [ ] Extract appropriate price arrays (closes, highs, lows, volumes) from OHLCV data$3
- [ ] Add case in extractIndicatorParams() method if indicator uses parameterized naming (e.g., rsi_14)
- [ ] Parse parameters from indicator string format
- [ ] Return base indicator name and extracted parameters$3
- [ ] Test with sample data
- [ ] Verify error handling for insufficient data
- [ ] Update this README with the new indicator
- [ ] Add example usage in README$3
`typescript
// 1. Add to supportedIndicators
export const supportedIndicators = [..., "newindicator"] as const;// 2. Implement function
export function calculateNewIndicator(
closes: number[],
params: TAParams
): number {
const period = params.period;
if (!period) {
throw new Error("Period is required for NewIndicator");
}
if (closes.length < period) {
throw new Error(
Insufficient data: need ${period}, got ${closes.length});
}
const values = TI.NewIndicator.calculate({ values: closes, period });
const last = values[values.length - 1];
if (!last) {
throw new Error("Failed to calculate NewIndicator");
}
return last;
}// 3. Add to service switch
case "newindicator":
return calculateNewIndicator(closes, finalParams);
// 4. Add parameter extraction if needed
case "newindicator":
if (!parts || !parts[0])
throw new Error(
Period is required for newindicator);
return { base, params: { period: parseInt(parts[0]) } };
`Development
`bash
Install dependencies
pnpm installBuild the package
pnpm buildWatch mode
pnpm build:watchType check
pnpm type-checkLint
pnpm lint
``MIT