@vesper85/technical-indicators
v0.1.6
Published
Technical indicators library for financial analysis
Maintainers
Readme
@osiris-ai/technical-indicators
A library for calculating technical indicators used in financial analysis and trading.
Installation
pnpm add @osiris-ai/technical-indicatorsUsage
Using Individual Functions
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]Using TechnicalAnalysisService
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)Input/Output Types
Input Types
Individual Functions:
- Price arrays:
number[]- Array of closing prices, highs, lows, etc. - Volume arrays:
number[]- Array of volume values - Parameters:
TAParams- Object containing indicator-specific parameters
TechnicalAnalysisService:
- Data:
OHLCV[]- Array of OHLCV objectsinterface OHLCV { timestamp: number; open: number; high: number; low: number; close: number; volume: number; } - Indicator:
string- Indicator name with parameters (e.g.,"rsi_14","macd_12_26_9") - Params:
TAParams & { component?: string }- Additional parameters and optional component selector
Output Types
Single Value Indicators (return number):
- RSI, EMA, SMA, ATR, ADX, OBV, CCI, MFI, VWAP, WilliamsR, ROC, PSAR, WMA
Multi-Value Indicators (return number[]):
- MACD:
[MACD, signal, histogram] - Bollinger Bands:
[upper, middle, lower] - Stochastic:
[%K, %D] - Stochastic RSI:
[%K, %D] - Keltner Channels:
[upper, lower, middle]
Examples
// 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)Available Indicators
- SMA (Simple Moving Average) -
calculateSMA - EMA (Exponential Moving Average) -
calculateEMA - RSI (Relative Strength Index) -
calculateRSI - MACD (Moving Average Convergence Divergence) -
calculateMACD - ATR (Average True Range) -
calculateATR - Bollinger Bands -
calculateBollingerBands - ADX (Average Directional Index) -
calculateADX - Stochastic -
calculateStochastic - OBV (On-Balance Volume) -
calculateOBV - CCI (Commodity Channel Index) -
calculateCCI - MFI (Money Flow Index) -
calculateMFI - VWAP (Volume Weighted Average Price) -
calculateVWAP - Williams %R -
calculateWilliamsR - Stochastic RSI -
calculateStochasticRSI - ROC (Rate of Change) -
calculateROC - Parabolic SAR -
calculateParabolicSAR - Keltner Channels -
calculateKeltnerChannels - WMA (Weighted Moving Average) -
calculateWMA
Adding New Technical Indicators
Follow this checklist when adding a new technical indicator:
1. Update Indicator Lists
- [ ] Add indicator name to
supportedIndicatorsarray insrc/indicators/index.ts - [ ] If indicator has multiple components (e.g., MACD, Bollinger Bands), add entry to
availableComponentsobject
2. Implement Calculation Function
- [ ] Create
calculate[IndicatorName]function insrc/indicators/index.ts - [ ] Define function signature with appropriate input arrays and
TAParams - [ ] Return type:
numberfor single value,number[]for multi-value indicators - [ ] Add parameter validation (check required params, minimum data length)
- [ ] Use
technicalindicatorslibrary for calculation - [ ] Return the last calculated value (for single) or array of values (for multi-value)
3. Integrate with Service
- [ ] Add case in
calculate()method switch statement insrc/index.ts - [ ] Handle component selection if indicator has multiple components
- [ ] Extract appropriate price arrays (closes, highs, lows, volumes) from OHLCV data
4. Add Parameter Extraction
- [ ] 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
5. Testing & Documentation
- [ ] Test with sample data
- [ ] Verify error handling for insufficient data
- [ ] Update this README with the new indicator
- [ ] Add example usage in README
Example: Adding a New Indicator
// 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
# Install dependencies
pnpm install
# Build the package
pnpm build
# Watch mode
pnpm build:watch
# Type check
pnpm type-check
# Lint
pnpm lintLicense
MIT
