Python API Reference

TechKit Python bindings provide high-performance technical analysis with NumPy integration.

Installation

pip install techkit

Requirements:

  • Python 3.10+

  • NumPy >= 1.21.0 (installed automatically)

Quick Reference

Object-Oriented API

from techkit import SMA, EMA, RSI, MACD, BBANDS

# Create indicator
sma = SMA(period=20)

# Incremental update
result = sma.update(price)
if result.valid:
    print(result.value)

# Batch calculation
import numpy as np
prices = np.array([...])
values = sma.calculate(prices)

TA-Lib Compatible API

from techkit import talib_compat as ta

# Same signatures as TA-Lib
sma = ta.SMA(prices, timeperiod=20)
rsi = ta.RSI(prices, timeperiod=14)
macd, signal, hist = ta.MACD(prices)
upper, middle, lower = ta.BBANDS(prices)

Module: techkit

Result Classes

IndicatorResult

@dataclass
class IndicatorResult:
    value: float    # Calculated value
    valid: bool     # True if valid, False during warmup
    
    def __bool__(self) -> bool:
        return self.valid

Usage:

result = sma.update(100.0)
if result:  # Uses __bool__
    print(f"SMA: {result.value}")

MACDResult

@dataclass
class MACDResult:
    macd: float       # MACD line
    signal: float     # Signal line
    histogram: float  # Histogram
    valid: bool
    
    def __iter__(self):
        return iter([self.macd, self.signal, self.histogram])

Usage:

result = macd.update(price)
if result.valid:
    m, s, h = result  # Tuple unpacking via __iter__

BBandsResult

@dataclass
class BBandsResult:
    upper: float
    middle: float
    lower: float
    valid: bool

StochResult

@dataclass  
class StochResult:
    k: float
    d: float
    valid: bool

Base Indicator Class

class Indicator:
    def update(self, value: float) -> IndicatorResult:
        """Update with single value (close price)."""
        
    def update_ohlcv(self, open: float, high: float, low: float, 
                     close: float, volume: float) -> IndicatorResult:
        """Update with OHLCV bar."""
        
    def calculate(self, data: np.ndarray) -> np.ndarray:
        """Batch calculate. Returns NaN for warmup period."""
        
    def reset(self) -> None:
        """Reset indicator state."""
        
    @property
    def lookback(self) -> int:
        """Number of bars before first valid output."""
        
    @property
    def name(self) -> str:
        """Indicator name."""
        
    @property
    def is_ready(self) -> bool:
        """True if indicator has produced valid output."""

Indicator Classes

Moving Averages

Class

Constructor

Input

Description

SMA

SMA(period=20)

close

Simple Moving Average

EMA

EMA(period=20)

close

Exponential Moving Average

WMA

WMA(period=20)

close

Weighted Moving Average

DEMA

DEMA(period=20)

close

Double EMA

TEMA

TEMA(period=20)

close

Triple EMA

KAMA

KAMA(period=30)

close

Kaufman Adaptive MA

TRIMA

TRIMA(period=30)

close

Triangular MA

T3

T3(period=5, vfactor=0.7)

close

T3 Moving Average

Momentum Indicators

Class

Constructor

Input

Description

RSI

RSI(period=14)

close

Relative Strength Index

MACD

MACD(fast=12, slow=26, signal=9)

close

MACD (3 outputs)

STOCH

STOCH(k=14, k_slow=3, d=3)

OHLCV

Stochastic (2 outputs)

ADX

ADX(period=14)

OHLCV

Average Directional Index

CCI

CCI(period=20)

OHLCV

Commodity Channel Index

WILLR

WILLR(period=14)

OHLCV

Williams %R

MFI

MFI(period=14)

OHLCV

Money Flow Index

MOM

MOM(period=10)

close

Momentum

ROC

ROC(period=10)

close

Rate of Change

APO

APO(fast=12, slow=26)

close

Absolute Price Oscillator

PPO

PPO(fast=12, slow=26)

close

Percentage Price Oscillator

CMO

CMO(period=14)

close

Chande Momentum Oscillator

TRIX

TRIX(period=30)

close

Triple Exponential Average

AROON

AROON(period=14)

OHLCV

Aroon Indicator (2 outputs)

ULTOSC

ULTOSC(p1=7, p2=14, p3=28)

OHLCV

Ultimate Oscillator

Volatility Indicators

Class

Constructor

Input

Description

ATR

ATR(period=14)

OHLCV

Average True Range

NATR

NATR(period=14)

OHLCV

Normalized ATR

TRANGE

TRANGE()

OHLCV

True Range

BBANDS

BBANDS(period=20, std_up=2.0, std_dn=2.0)

close

Bollinger Bands (3 outputs)

Volume Indicators

Class

Constructor

Input

Description

OBV

OBV()

OHLCV

On Balance Volume

AD

AD()

OHLCV

Accumulation/Distribution

ADOSC

ADOSC(fast=3, slow=10)

OHLCV

A/D Oscillator

Statistics Functions

Class

Constructor

Input

Description

STDDEV

STDDEV(period=5, nbdev=1.0)

close

Standard Deviation

VAR

VAR(period=5)

close

Variance

LINEARREG

LINEARREG(period=14)

close

Linear Regression

LINEARREG_SLOPE

LINEARREG_SLOPE(period=14)

close

Regression Slope

LINEARREG_INTERCEPT

LINEARREG_INTERCEPT(period=14)

close

Regression Intercept

LINEARREG_ANGLE

LINEARREG_ANGLE(period=14)

close

Regression Angle

TSF

TSF(period=14)

close

Time Series Forecast

BETA

BETA(period=5)

close + close

Beta Coefficient

CORREL

CORREL(period=30)

close + close

Pearson Correlation

MIN

MIN(period=30)

close

Minimum Value

MAX

MAX(period=30)

close

Maximum Value

SUM

SUM(period=30)

close

Sum over Period

MINMAX

MINMAX(period=30)

close

Min and Max (2 outputs)

Risk Metrics

Class

Constructor

Input

Description

SharpeRatio

SharpeRatio(period=252, rfr=0.0, annualization=252)

returns

Rolling Sharpe Ratio

SortinoRatio

SortinoRatio(period=252, rfr=0.0, target=0.0, annualization=252)

returns

Sortino Ratio

MaxDrawdown

MaxDrawdown()

price

Maximum Drawdown

Drawdown

Drawdown()

price

Drawdown Series

CalmarRatio

CalmarRatio(period=756, annualization=252)

returns

Calmar Ratio

HistoricalVaR

HistoricalVaR(period=252, confidence=0.95)

returns

Historical VaR

CVaR

CVaR(period=252, confidence=0.95)

returns

Conditional VaR

Volatility Models

Class

Constructor

Input

Description

EWMAVolatility

EWMAVolatility(lambda=0.94, annualization=252)

returns

EWMA Volatility

RealizedVolatility

RealizedVolatility(period=20, annualization=252)

returns

Realized Volatility

ParkinsonVolatility

ParkinsonVolatility(period=20, annualization=252)

OHLCV

Parkinson Volatility

GARCHVolatility

GARCHVolatility(omega=0.000001, alpha=0.09, beta=0.90, annualization=252)

returns

GARCH(1,1) Volatility

Pattern Recognition

Class

Constructor

Input

Description

HarmonicPattern

HarmonicPattern(deviation_pct=5.0, tolerance=0.03, max_bars=100)

OHLCV

Harmonic Patterns

ChartPattern

ChartPattern(min_bars=20, max_bars=200, tolerance=0.03)

OHLCV

Chart Patterns

ZigZag

ZigZag(deviation_pct=5.0, depth=10)

OHLCV

ZigZag Indicator

SwingHighLow

SwingHighLow(left_bars=5, right_bars=5)

OHLCV

Swing Detection

PivotPoints

PivotPoints(type='classic')

OHLCV

Pivot Points

Candlestick Patterns (61 patterns)

All CDL classes follow the same interface:

from techkit import CDL_DOJI, CDL_HAMMER, CDL_ENGULFING

doji = CDL_DOJI()
result = doji.calculate_ohlcv(open, high, low, close, volume)
# result: array of signals (+100 bullish, -100 bearish, 0 none)

Chain Class

class Chain:
    """Chain multiple indicators together.
    
    Output of first indicator feeds into second, etc.
    Useful for smoothing or combining indicators.
    
    Example:
        >>> # Smoothed RSI: RSI(14) -> EMA(9)
        >>> chain = Chain([RSI(14), EMA(9)])
        >>> result = chain.update(price)
        
        >>> # Batch
        >>> smoothed = chain.calculate(prices)
    """
    
    def __init__(self, indicators: List[Indicator]): ...
    def update(self, value: float) -> IndicatorResult: ...
    def calculate(self, data: np.ndarray) -> np.ndarray: ...
    def reset(self) -> None: ...

Module: techkit.talib_compat

Drop-in replacement for TA-Lib. Same function signatures.

Migration from TA-Lib

# Before (TA-Lib)
import talib
sma = talib.SMA(prices, timeperiod=20)
macd, signal, hist = talib.MACD(prices)

# After (TechKit)
from techkit import talib_compat as ta
sma = ta.SMA(prices, timeperiod=20)  # Same!
macd, signal, hist = ta.MACD(prices)  # Same!

Function Reference

Overlap Studies

Function

Signature

Returns

SMA

SMA(real, timeperiod=30)

np.ndarray

EMA

EMA(real, timeperiod=30)

np.ndarray

WMA

WMA(real, timeperiod=30)

np.ndarray

DEMA

DEMA(real, timeperiod=30)

np.ndarray

TEMA

TEMA(real, timeperiod=30)

np.ndarray

KAMA

KAMA(real, timeperiod=30)

np.ndarray

TRIMA

TRIMA(real, timeperiod=30)

np.ndarray

T3

T3(real, timeperiod=5, vfactor=0.7)

np.ndarray

BBANDS

BBANDS(real, timeperiod=5, nbdevup=2.0, nbdevdn=2.0, matype=0)

Tuple[3]

SAR

SAR(high, low, acceleration=0.02, maximum=0.2)

np.ndarray

MIDPOINT

MIDPOINT(real, timeperiod=14)

np.ndarray

MIDPRICE

MIDPRICE(high, low, timeperiod=14)

np.ndarray

Momentum Indicators

Function

Signature

Returns

RSI

RSI(real, timeperiod=14)

np.ndarray

MACD

MACD(real, fastperiod=12, slowperiod=26, signalperiod=9)

Tuple[3]

STOCH

STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)

Tuple[2]

ADX

ADX(high, low, close, timeperiod=14)

np.ndarray

CCI

CCI(high, low, close, timeperiod=14)

np.ndarray

WILLR

WILLR(high, low, close, timeperiod=14)

np.ndarray

MFI

MFI(high, low, close, volume, timeperiod=14)

np.ndarray

MOM

MOM(real, timeperiod=10)

np.ndarray

ROC

ROC(real, timeperiod=10)

np.ndarray

ROCP

ROCP(real, timeperiod=10)

np.ndarray

ROCR

ROCR(real, timeperiod=10)

np.ndarray

ROCR100

ROCR100(real, timeperiod=10)

np.ndarray

APO

APO(real, fastperiod=12, slowperiod=26)

np.ndarray

PPO

PPO(real, fastperiod=12, slowperiod=26)

np.ndarray

CMO

CMO(real, timeperiod=14)

np.ndarray

TRIX

TRIX(real, timeperiod=30)

np.ndarray

ULTOSC

ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28)

np.ndarray

AROON

AROON(high, low, timeperiod=14)

Tuple[2]

AROONOSC

AROONOSC(high, low, timeperiod=14)

np.ndarray

BOP

BOP(open, high, low, close)

np.ndarray

Volatility

Function

Signature

Returns

ATR

ATR(high, low, close, timeperiod=14)

np.ndarray

NATR

NATR(high, low, close, timeperiod=14)

np.ndarray

TRANGE

TRANGE(high, low, close)

np.ndarray

Volume

Function

Signature

Returns

OBV

OBV(close, volume)

np.ndarray

AD

AD(high, low, close, volume)

np.ndarray

ADOSC

ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10)

np.ndarray

Statistics

Function

Signature

Returns

STDDEV

STDDEV(real, timeperiod=5, nbdev=1.0)

np.ndarray

VAR

VAR(real, timeperiod=5)

np.ndarray

LINEARREG

LINEARREG(real, timeperiod=14)

np.ndarray

LINEARREG_SLOPE

LINEARREG_SLOPE(real, timeperiod=14)

np.ndarray

LINEARREG_INTERCEPT

LINEARREG_INTERCEPT(real, timeperiod=14)

np.ndarray

LINEARREG_ANGLE

LINEARREG_ANGLE(real, timeperiod=14)

np.ndarray

TSF

TSF(real, timeperiod=14)

np.ndarray

BETA

BETA(high, low, timeperiod=5)

np.ndarray

CORREL

CORREL(high, low, timeperiod=30)

np.ndarray

Price Transform

Function

Signature

Returns

AVGPRICE

AVGPRICE(open, high, low, close)

np.ndarray

MEDPRICE

MEDPRICE(high, low)

np.ndarray

TYPPRICE

TYPPRICE(high, low, close)

np.ndarray

WCLPRICE

WCLPRICE(high, low, close)

np.ndarray

Math Operators

Function

Signature

Returns

MIN

MIN(real, timeperiod=30)

np.ndarray

MAX

MAX(real, timeperiod=30)

np.ndarray

SUM

SUM(real, timeperiod=30)

np.ndarray

MINMAX

MINMAX(real, timeperiod=30)

Tuple[2]

MIDPOINT

MIDPOINT(real, timeperiod=14)

np.ndarray

Hilbert Transform

Function

Signature

Returns

HT_DCPERIOD

HT_DCPERIOD(real)

np.ndarray

HT_DCPHASE

HT_DCPHASE(real)

np.ndarray

HT_TRENDMODE

HT_TRENDMODE(real)

np.ndarray

HT_TRENDLINE

HT_TRENDLINE(real)

np.ndarray

HT_PHASOR

HT_PHASOR(real)

Tuple[2]

HT_SINE

HT_SINE(real)

Tuple[2]

Pattern Recognition

All 61 candlestick pattern functions are available:

  • CDL_DOJI, CDL_HAMMER, CDL_ENGULFING, etc.

  • Signature: CDL_*(open, high, low, close)

  • Returns: np.ndarray with +100 (bullish), -100 (bearish), or 0 (none)

Input Types

All functions accept:

  • numpy.ndarray

  • pandas.Series

  • list

import numpy as np
import pandas as pd
from techkit import talib_compat as ta

# All work
ta.SMA(np.array([1, 2, 3]), 2)
ta.SMA(pd.Series([1, 2, 3]), 2)
ta.SMA([1, 2, 3], 2)

Type Hints

TechKit includes type stubs for full IDE support.

# Type checking works
from techkit import SMA, RSI
import numpy as np

sma: SMA = SMA(20)
result = sma.update(100.0)  # result: IndicatorResult
values: np.ndarray = sma.calculate(np.array([...]))

Working with Pandas

import pandas as pd
import numpy as np
from techkit import SMA, RSI, MACD, BBANDS

# Load data
df = pd.read_csv('ohlcv.csv')

# Add indicators
df['SMA_20'] = SMA(20).calculate(df['close'].values)
df['SMA_50'] = SMA(50).calculate(df['close'].values)
df['RSI'] = RSI(14).calculate(df['close'].values)

# Multi-output
macd, signal, hist = MACD().calculate(df['close'].values)
df['MACD'] = macd
df['MACD_Signal'] = signal
df['MACD_Hist'] = hist

upper, middle, lower = BBANDS().calculate(df['close'].values)
df['BB_Upper'] = upper
df['BB_Middle'] = middle
df['BB_Lower'] = lower

# Generate signals
df['Signal'] = np.where(
    (df['RSI'] < 30) & (df['close'] < df['BB_Lower']),
    'BUY',
    np.where(
        (df['RSI'] > 70) & (df['close'] > df['BB_Upper']),
        'SELL',
        'HOLD'
    )
)

Performance Tips

  1. Batch over incremental for backtesting:

   # Fast
   values = SMA(20).calculate(large_array)
   
   # Slower
   sma = SMA(20)
   values = [sma.update(p).value for p in large_array]
  1. Reuse indicator instances:

   sma = SMA(20)
   for symbol in symbols:
       sma.reset()
       values = sma.calculate(data[symbol])
  1. Use NumPy arrays not lists:

   # Fast
   prices = np.array(price_list)
   
   # Slower  
   prices = price_list  # Will be converted internally

Version Information

import techkit
print(techkit.__version__)  # "1.2.1"