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 |
|---|---|---|---|
|
|
close |
简单移动平均线 |
|
|
close |
指数移动平均线 |
|
|
close |
加权移动平均线 |
|
|
close |
双指数移动平均线 |
|
|
close |
三指数移动平均线 |
|
|
close |
考夫曼自适应移动平均线 |
|
|
close |
三角移动平均线 |
|
|
close |
T3 移动平均线 |
动量指标
Class |
Constructor |
Input |
Description |
|---|---|---|---|
|
|
close |
相对强弱指数 |
|
|
close |
MACD(3 个输出) |
|
|
OHLCV |
随机指标(2 个输出) |
|
|
OHLCV |
平均趋向指数 |
|
|
OHLCV |
商品通道指数 |
|
|
OHLCV |
威廉指标 %R |
|
|
OHLCV |
资金流量指标 |
|
|
close |
动量指标 |
|
|
close |
变动率 |
|
|
close |
绝对价格振荡器 |
|
|
close |
百分比价格振荡器 |
|
|
close |
钱德动量振荡器 |
|
|
close |
三重指数平均 |
|
|
OHLCV |
Aroon 指标(2 个输出) |
|
|
OHLCV |
终极振荡器 |
波动率指标
Class |
Constructor |
Input |
Description |
|---|---|---|---|
|
|
OHLCV |
平均真实波幅 |
|
|
OHLCV |
标准化 ATR |
|
|
OHLCV |
真实波幅 |
|
|
close |
布林带(3 个输出) |
成交量指标
Class |
Constructor |
Input |
Description |
|---|---|---|---|
|
|
OHLCV |
能量潮 |
|
|
OHLCV |
累积/派发线 |
|
|
OHLCV |
A/D 振荡器 |
统计函数
Class |
Constructor |
Input |
Description |
|---|---|---|---|
|
|
close |
标准差 |
|
|
close |
方差 |
|
|
close |
线性回归 |
|
|
close |
回归斜率 |
|
|
close |
回归截距 |
|
|
close |
回归角度 |
|
|
close |
时间序列预测 |
|
|
close + close |
贝塔系数 |
|
|
close + close |
皮尔逊相关系数 |
|
|
close |
最小值 |
|
|
close |
最大值 |
|
|
close |
周期内求和 |
|
|
close |
最小值和最大值(2 个输出) |
风险指标
Class |
Constructor |
Input |
Description |
|---|---|---|---|
|
|
returns |
滚动夏普比率 |
|
|
returns |
索提诺比率 |
|
|
price |
最大回撤 |
|
|
price |
回撤序列 |
|
|
returns |
卡玛比率 |
|
|
returns |
历史 VaR |
|
|
returns |
条件 VaR |
波动率模型
Class |
Constructor |
Input |
Description |
|---|---|---|---|
|
|
returns |
EWMA 波动率 |
|
|
returns |
已实现波动率 |
|
|
OHLCV |
帕金森波动率 |
|
|
returns |
GARCH(1,1) 波动率 |
形态识别
Class |
Constructor |
Input |
Description |
|---|---|---|---|
|
|
OHLCV |
谐波形态 |
|
|
OHLCV |
图表形态 |
|
|
OHLCV |
之字转向指标 |
|
|
OHLCV |
摆动高低点检测 |
|
|
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 |
|---|---|---|
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
Tuple[3] |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
动量指标
Function |
Signature |
Returns |
|---|---|---|
|
|
np.ndarray |
|
|
Tuple[3] |
|
|
Tuple[2] |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
Tuple[2] |
|
|
np.ndarray |
|
|
np.ndarray |
波动率
Function |
Signature |
Returns |
|---|---|---|
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
成交量
Function |
Signature |
Returns |
|---|---|---|
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
统计
Function |
Signature |
Returns |
|---|---|---|
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
价格变换
Function |
Signature |
Returns |
|---|---|---|
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
数学运算符
Function |
Signature |
Returns |
|---|---|---|
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
Tuple[2] |
|
|
np.ndarray |
希尔伯特变换
Function |
Signature |
Returns |
|---|---|---|
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
np.ndarray |
|
|
Tuple[2] |
|
|
Tuple[2] |
形态识别
所有 61 种 K 线形态函数均可用:
CDL_DOJI,CDL_HAMMER,CDL_ENGULFING等签名:
CDL_*(open, high, low, close)返回:
np.ndarray,值为 +100(看涨)、-100(看跌)或 0(无)
输入类型
所有函数接受:
numpy.ndarraypandas.Serieslist
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'
)
)
性能提示
回测时优先使用批量计算而非增量更新:
# Fast
values = SMA(20).calculate(large_array)
# Slower
sma = SMA(20)
values = [sma.update(p).value for p in large_array]
复用指标实例:
sma = SMA(20)
for symbol in symbols:
sma.reset()
values = sma.calculate(data[symbol])
使用 NumPy 数组而非列表:
# Fast
prices = np.array(price_list)
# Slower
prices = price_list # Will be converted internally
版本信息
import techkit
print(techkit.__version__) # "1.2.1"