Python API 参考

TechKit Python 绑定提供高性能技术分析,支持 NumPy 集成。

安装

pip install techkit

要求:

  • Python 3.10+

  • NumPy >= 1.21.0(自动安装)

快速参考

面向对象 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 兼容 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)

模块:techkit

结果类

IndicatorResult

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

用法:

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])

用法:

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

基础指标类

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."""

指标类

移动平均线

Class

Constructor

Input

Description

SMA

SMA(period=20)

close

简单移动平均线

EMA

EMA(period=20)

close

指数移动平均线

WMA

WMA(period=20)

close

加权移动平均线

DEMA

DEMA(period=20)

close

双指数移动平均线

TEMA

TEMA(period=20)

close

三指数移动平均线

KAMA

KAMA(period=30)

close

考夫曼自适应移动平均线

TRIMA

TRIMA(period=30)

close

三角移动平均线

T3

T3(period=5, vfactor=0.7)

close

T3 移动平均线

动量指标

Class

Constructor

Input

Description

RSI

RSI(period=14)

close

相对强弱指数

MACD

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

close

MACD(3 个输出)

STOCH

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

OHLCV

随机指标(2 个输出)

ADX

ADX(period=14)

OHLCV

平均趋向指数

CCI

CCI(period=20)

OHLCV

商品通道指数

WILLR

WILLR(period=14)

OHLCV

威廉指标 %R

MFI

MFI(period=14)

OHLCV

资金流量指标

MOM

MOM(period=10)

close

动量指标

ROC

ROC(period=10)

close

变动率

APO

APO(fast=12, slow=26)

close

绝对价格振荡器

PPO

PPO(fast=12, slow=26)

close

百分比价格振荡器

CMO

CMO(period=14)

close

钱德动量振荡器

TRIX

TRIX(period=30)

close

三重指数平均

AROON

AROON(period=14)

OHLCV

Aroon 指标(2 个输出)

ULTOSC

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

OHLCV

终极振荡器

波动率指标

Class

Constructor

Input

Description

ATR

ATR(period=14)

OHLCV

平均真实波幅

NATR

NATR(period=14)

OHLCV

标准化 ATR

TRANGE

TRANGE()

OHLCV

真实波幅

BBANDS

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

close

布林带(3 个输出)

成交量指标

Class

Constructor

Input

Description

OBV

OBV()

OHLCV

能量潮

AD

AD()

OHLCV

累积/派发线

ADOSC

ADOSC(fast=3, slow=10)

OHLCV

A/D 振荡器

统计函数

Class

Constructor

Input

Description

STDDEV

STDDEV(period=5, nbdev=1.0)

close

标准差

VAR

VAR(period=5)

close

方差

LINEARREG

LINEARREG(period=14)

close

线性回归

LINEARREG_SLOPE

LINEARREG_SLOPE(period=14)

close

回归斜率

LINEARREG_INTERCEPT

LINEARREG_INTERCEPT(period=14)

close

回归截距

LINEARREG_ANGLE

LINEARREG_ANGLE(period=14)

close

回归角度

TSF

TSF(period=14)

close

时间序列预测

BETA

BETA(period=5)

close + close

贝塔系数

CORREL

CORREL(period=30)

close + close

皮尔逊相关系数

MIN

MIN(period=30)

close

最小值

MAX

MAX(period=30)

close

最大值

SUM

SUM(period=30)

close

周期内求和

MINMAX

MINMAX(period=30)

close

最小值和最大值(2 个输出)

风险指标

Class

Constructor

Input

Description

SharpeRatio

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

returns

滚动夏普比率

SortinoRatio

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

returns

索提诺比率

MaxDrawdown

MaxDrawdown()

price

最大回撤

Drawdown

Drawdown()

price

回撤序列

CalmarRatio

CalmarRatio(period=756, annualization=252)

returns

卡玛比率

HistoricalVaR

HistoricalVaR(period=252, confidence=0.95)

returns

历史 VaR

CVaR

CVaR(period=252, confidence=0.95)

returns

条件 VaR

波动率模型

Class

Constructor

Input

Description

EWMAVolatility

EWMAVolatility(lambda=0.94, annualization=252)

returns

EWMA 波动率

RealizedVolatility

RealizedVolatility(period=20, annualization=252)

returns

已实现波动率

ParkinsonVolatility

ParkinsonVolatility(period=20, annualization=252)

OHLCV

帕金森波动率

GARCHVolatility

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

returns

GARCH(1,1) 波动率

形态识别

Class

Constructor

Input

Description

HarmonicPattern

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

OHLCV

谐波形态

ChartPattern

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

OHLCV

图表形态

ZigZag

ZigZag(deviation_pct=5.0, depth=10)

OHLCV

之字转向指标

SwingHighLow

SwingHighLow(left_bars=5, right_bars=5)

OHLCV

摆动高低点检测

PivotPoints

PivotPoints(type='classic')

OHLCV

枢轴点

K 线形态(61 种形态)

所有 CDL 类遵循相同的接口:

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 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: ...

模块:techkit.talib_compat

TA-Lib 的即插即用替代品。相同的函数签名。

从 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

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

动量指标

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

波动率

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

成交量

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

统计

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

价格变换

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

数学运算符

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

希尔伯特变换

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]

形态识别

所有 61 种 K 线形态函数均可用:

  • CDL_DOJI, CDL_HAMMER, CDL_ENGULFING

  • 签名:CDL_*(open, high, low, close)

  • 返回:np.ndarray,值为 +100(看涨)、-100(看跌)或 0(无)

输入类型

所有函数接受:

  • 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)

类型提示

TechKit 包含类型存根,提供完整的 IDE 支持。

# 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([...]))

与 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'
    )
)

性能提示

  1. 回测时优先使用批量计算而非增量更新

   # Fast
   values = SMA(20).calculate(large_array)
   
   # Slower
   sma = SMA(20)
   values = [sma.update(p).value for p in large_array]
  1. 复用指标实例

   sma = SMA(20)
   for symbol in symbols:
       sma.reset()
       values = sma.calculate(data[symbol])
  1. 使用 NumPy 数组而非列表

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

版本信息

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