ta-lib
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chineseta-lib — C-Optimized Technical Analysis
ta-lib — 基于C语言优化的技术分析库
TA-Lib (Technical Analysis Library) is a C library with a Python wrapper providing 150+ technical analysis functions and 61 candlestick pattern recognition functions. It is the industry standard for performance-critical indicator computation, used in production trading systems where pandas-ta or pure-Python alternatives are too slow.
TA-Lib(技术分析库)是一个C语言库,配有Python封装器,提供150余种技术分析函数和61种K线形态识别功能。它是性能关键型指标计算的行业标准,被用于生产级交易系统中——在这些场景下,pandas-ta或纯Python替代方案的速度太慢。
What TA-Lib Is
TA-Lib是什么
TA-Lib was originally written in C for financial market data analysis. The Python wrapper ( on PyPI, imported as ) provides:
TA-Libtalib- 150+ indicator functions across overlap, momentum, volume, volatility, cycle, and math categories
- 61 candlestick pattern recognition functions — the most comprehensive pattern library available
- C-speed computation — 10-100x faster than pure-Python equivalents on large datasets
- Two APIs: a function API (pass arrays directly) and an abstract API (pass dict of arrays)
- NumPy native — all inputs and outputs are NumPy arrays
TA-Lib最初是为金融市场数据分析用C语言编写的。Python封装器(PyPI上的,导入时使用)提供:
TA-Libtalib- 150余种指标函数,涵盖重叠指标、动量指标、成交量指标、波动率指标、周期指标和数学运算类别
- 61种K线形态识别函数——目前功能最全面的形态识别库
- C语言级计算速度——在处理大型数据集时,比纯Python实现快10-100倍
- 两种API:函数式API(直接传入数组)和抽象API(传入数组字典)
- 原生支持NumPy——所有输入和输出均为NumPy数组
Installation
安装
TA-Lib requires the underlying C library to be installed first:
bash
undefinedTA-Lib要求先安装底层的C语言库:
bash
undefinedmacOS
macOS
brew install ta-lib
uv pip install TA-Lib numpy pandas
brew install ta-lib
uv pip install TA-Lib numpy pandas
Ubuntu/Debian
Ubuntu/Debian
sudo apt-get install -y ta-lib
uv pip install TA-Lib numpy pandas
sudo apt-get install -y ta-lib
uv pip install TA-Lib numpy pandas
From source (any platform)
从源码安装(任意平台)
wget https://github.com/ta-lib/ta-lib/releases/download/v0.6.4/ta-lib-0.6.4-src.tar.gz
tar -xzf ta-lib-0.6.4-src.tar.gz
cd ta-lib-0.6.4
./configure --prefix=/usr/local
make && sudo make install
uv pip install TA-Lib numpy pandas
If the C library is not installed, `import talib` will fail with an `ImportError`. The scripts in this skill include fallback logic for environments without TA-Lib installed.wget https://github.com/ta-lib/ta-lib/releases/download/v0.6.4/ta-lib-0.6.4-src.tar.gz
tar -xzf ta-lib-0.6.4-src.tar.gz
cd ta-lib-0.6.4
./configure --prefix=/usr/local
make && sudo make install
uv pip install TA-Lib numpy pandas
如果未安装C语言库,`import talib`会抛出`ImportError`错误。本技能中的脚本包含了针对未安装TA-Lib环境的降级逻辑。When to Use TA-Lib vs pandas-ta
何时选择TA-Lib vs pandas-ta
| Criterion | TA-Lib | pandas-ta |
|---|---|---|
| Speed | C-optimized, 10-100x faster | Pure Python, slower on large data |
| Candlestick patterns | 61 built-in patterns | Limited pattern support |
| Installation | Requires C library | |
| API style | NumPy arrays | DataFrame |
| Indicator count | 150+ | 130+ |
| Streaming | Single-value update possible | Recompute entire series |
| Dependencies | C lib + numpy | pandas only |
Use TA-Lib when:
- Processing millions of bars or running backtests at scale
- You need candlestick pattern recognition (TA-Lib is unmatched here)
- You are building a production pipeline where latency matters
- You need cycle indicators (Hilbert Transform family)
Use pandas-ta when:
- You want DataFrame-native convenience
- Installation simplicity matters (no C dependency)
- You need indicators not in TA-Lib (pandas-ta has some extras)
| 评判标准 | TA-Lib | pandas-ta |
|---|---|---|
| 速度 | C语言优化,速度快10-100倍 | 纯Python实现,处理大数据时速度较慢 |
| K线形态 | 内置61种形态 | 形态支持有限 |
| 安装 | 需要安装C语言库 | 仅需 |
| API风格 | 基于NumPy数组 | DataFrame的 |
| 指标数量 | 150+ | 130+ |
| 流处理 | 支持单值更新 | 需重新计算整个序列 |
| 依赖项 | C库 + numpy | 仅依赖pandas |
选择TA-Lib的场景:
- 处理数百万条K线数据或大规模回测
- 需要K线形态识别功能(TA-Lib在这方面无可匹敌)
- 构建对延迟敏感的生产级流水线
- 需要周期指标(希尔伯特变换系列)
选择pandas-ta的场景:
- 希望使用DataFrame原生的便捷操作
- 重视安装简便性(无C语言依赖)
- 需要TA-Lib中没有的指标(pandas-ta包含一些额外指标)
Quick Start
快速开始
python
import numpy as np
import talibpython
import numpy as np
import talibCreate sample data
创建示例数据
close = np.random.randn(100).cumsum() + 50
high = close + np.abs(np.random.randn(100))
low = close - np.abs(np.random.randn(100))
open_ = close + np.random.randn(100) * 0.5
volume = np.random.randint(1000, 10000, 100).astype(float)
close = np.random.randn(100).cumsum() + 50
high = close + np.abs(np.random.randn(100))
low = close - np.abs(np.random.randn(100))
open_ = close + np.random.randn(100) * 0.5
volume = np.random.randint(1000, 10000, 100).astype(float)
Function API — pass arrays directly
函数式API — 直接传入数组
rsi = talib.RSI(close, timeperiod=14)
macd, signal, hist = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
upper, middle, lower = talib.BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2)
atr = talib.ATR(high, low, close, timeperiod=14)
rsi = talib.RSI(close, timeperiod=14)
macd, signal, hist = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
upper, middle, lower = talib.BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2)
atr = talib.ATR(high, low, close, timeperiod=14)
Candlestick patterns — return +100 (bullish), -100 (bearish), or 0
K线形态识别 — 返回+100(看涨形态)、-100(看跌形态)或0
doji = talib.CDLDOJI(open_, high, low, close)
hammer = talib.CDLHAMMER(open_, high, low, close)
engulfing = talib.CDLENGULFING(open_, high, low, close)
undefineddoji = talib.CDLDOJI(open_, high, low, close)
hammer = talib.CDLHAMMER(open_, high, low, close)
engulfing = talib.CDLENGULFING(open_, high, low, close)
undefinedFunction API vs Abstract API
函数式API vs 抽象API
Function API (Recommended)
函数式API(推荐)
Call functions directly with NumPy arrays:
python
import talib
rsi = talib.RSI(close, timeperiod=14)
sma = talib.SMA(close, timeperiod=20)
upper, mid, lower = talib.BBANDS(close)直接调用函数并传入NumPy数组:
python
import talib
rsi = talib.RSI(close, timeperiod=14)
sma = talib.SMA(close, timeperiod=20)
upper, mid, lower = talib.BBANDS(close)Abstract API
抽象API
Pass a dictionary of arrays and get results by name:
python
from talib import abstract
inputs = {"open": open_, "high": high, "low": low, "close": close, "volume": volume}传入数组字典并按名称获取结果:
python
from talib import abstract
inputs = {"open": open_, "high": high, "low": low, "close": close, "volume": volume}Call by function name
按函数名称调用
rsi = abstract.RSI(inputs, timeperiod=14)
macd = abstract.MACD(inputs) # returns (macd, signal, hist)
The abstract API is useful for dynamic indicator selection (e.g., looping over a list of indicator names).rsi = abstract.RSI(inputs, timeperiod=14)
macd = abstract.MACD(inputs) # 返回(macd, signal, hist)
抽象API适用于动态选择指标的场景(例如,遍历指标名称列表)。Function Groups
函数分组
TA-Lib organizes functions into these groups:
TA-Lib将函数分为以下组别:
Overlap Studies
重叠指标研究
Moving averages and envelope indicators that overlay price charts.
python
sma = talib.SMA(close, timeperiod=20)
ema = talib.EMA(close, timeperiod=12)
upper, mid, lower = talib.BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2)
sar = talib.SAR(high, low, acceleration=0.02, maximum=0.2)
mama, fama = talib.MAMA(close, fastlimit=0.5, slowlimit=0.05)叠加在价格图表上的移动平均线和包络线指标。
python
sma = talib.SMA(close, timeperiod=20)
ema = talib.EMA(close, timeperiod=12)
upper, mid, lower = talib.BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2)
sar = talib.SAR(high, low, acceleration=0.02, maximum=0.2)
mama, fama = talib.MAMA(close, fastlimit=0.5, slowlimit=0.05)Momentum Indicators
动量指标
Oscillators and trend-strength measures.
python
rsi = talib.RSI(close, timeperiod=14)
macd, signal, hist = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
slowk, slowd = talib.STOCH(high, low, close)
cci = talib.CCI(high, low, close, timeperiod=14)
willr = talib.WILLR(high, low, close, timeperiod=14)
adx = talib.ADX(high, low, close, timeperiod=14)
mfi = talib.MFI(high, low, close, volume, timeperiod=14)震荡指标和趋势强度度量。
python
rsi = talib.RSI(close, timeperiod=14)
macd, signal, hist = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9)
slowk, slowd = talib.STOCH(high, low, close)
cci = talib.CCI(high, low, close, timeperiod=14)
willr = talib.WILLR(high, low, close, timeperiod=14)
adx = talib.ADX(high, low, close, timeperiod=14)
mfi = talib.MFI(high, low, close, volume, timeperiod=14)Volume Indicators
成交量指标
Volume-based analysis functions.
python
obv = talib.OBV(close, volume)
ad = talib.AD(high, low, close, volume)
adosc = talib.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10)基于成交量的分析函数。
python
obv = talib.OBV(close, volume)
ad = talib.AD(high, low, close, volume)
adosc = talib.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10)Volatility Indicators
波动率指标
Measures of price variability.
python
atr = talib.ATR(high, low, close, timeperiod=14)
natr = talib.NATR(high, low, close, timeperiod=14)
trange = talib.TRANGE(high, low, close)价格波动程度的度量。
python
atr = talib.ATR(high, low, close, timeperiod=14)
natr = talib.NATR(high, low, close, timeperiod=14)
trange = talib.TRANGE(high, low, close)Pattern Recognition (Candlestick)
形态识别(K线)
61 functions that detect candlestick patterns. All return integer arrays:
- = bullish pattern detected
+100 - = bearish pattern detected
-100 - = no pattern
0
python
undefined61种用于检测K线形态的函数。所有函数均返回整数数组:
- = 检测到看涨形态
+100 - = 检测到看跌形态
-100 - = 未检测到形态
0
python
undefinedSingle patterns
单个形态识别
doji = talib.CDLDOJI(open_, high, low, close)
hammer = talib.CDLHAMMER(open_, high, low, close)
engulfing = talib.CDLENGULFING(open_, high, low, close)
doji = talib.CDLDOJI(open_, high, low, close)
hammer = talib.CDLHAMMER(open_, high, low, close)
engulfing = talib.CDLENGULFING(open_, high, low, close)
Scan all 61 patterns at once
一次性扫描全部61种形态
candle_names = talib.get_function_groups()["Pattern Recognition"]
for name in candle_names:
func = getattr(talib, name)
result = func(open_, high, low, close)
hits = np.nonzero(result)[0]
if len(hits) > 0:
print(f"{name}: {len(hits)} detections")
See `references/candlestick_patterns.md` for the full list of 61 patterns with reliability ratings and crypto relevance.candle_names = talib.get_function_groups()["Pattern Recognition"]
for name in candle_names:
func = getattr(talib, name)
result = func(open_, high, low, close)
hits = np.nonzero(result)[0]
if len(hits) > 0:
print(f"{name}: {len(hits)} detections")
查看`references/candlestick_patterns.md`获取全部61种形态的完整列表,包括可靠性评级和加密货币相关性说明。Math Transform & Math Operators
数学变换与数学运算
Mathematical functions (sin, cos, ln, etc.) and operators (add, sub, mult, div) on arrays. Rarely used directly but available.
针对数组的数学函数(正弦、余弦、对数等)和运算符(加、减、乘、除)。很少直接使用,但已提供支持。
Crypto Considerations
加密货币相关注意事项
24/7 Markets
7×24小时市场
- Candlestick patterns designed for traditional markets with opening/closing gaps may behave differently on crypto's continuous markets
- Gap-based patterns (morning star, evening star) are less reliable without session gaps
- Body-ratio patterns (doji, hammer, engulfing) still work well on any timeframe
- 为传统市场(存在开盘/收盘缺口)设计的K线形态在加密货币的连续市场中表现可能不同
- 基于缺口的形态(晨星、夜星)在无时段缺口的情况下可靠性较低
- 基于实体比例的形态(十字星、锤子线、吞噬形态)在任何时间框架下仍能良好工作
Timeframe Selection
时间框架选择
- 1m-5m: Patterns are noisy; combine with volume confirmation
- 15m-1h: Good for intraday signals on high-cap tokens
- 4h-1d: Most reliable for pattern recognition
- Tip: Higher timeframes produce fewer but more reliable pattern signals
- 1分钟-5分钟:形态信号噪音大;需结合成交量确认
- 15分钟-1小时:适合高市值代币的日内信号
- 4小时-1天:形态识别的可靠性最高
- 提示:更高时间框架产生的信号更少,但可靠性更强
NaN Handling
NaN值处理
TA-Lib returns for the initial lookback period of each indicator. Always account for this:
NaNpython
rsi = talib.RSI(close, timeperiod=14)TA-Lib会在每个指标的初始回溯期返回值。务必对此进行处理:
NaNpython
rsi = talib.RSI(close, timeperiod=14)First 14 values will be NaN
前14个值为NaN
valid_rsi = rsi[~np.isnan(rsi)]
undefinedvalid_rsi = rsi[~np.isnan(rsi)]
undefinedSolana Token Data
Solana代币数据
When using TA-Lib with Solana token OHLCV data:
- Ensure arrays are dtype — TA-Lib requires this
float64 - Sort by timestamp ascending before passing to TA-Lib
- Handle gaps in low-liquidity token data before computing indicators
python
undefined当使用TA-Lib处理Solana代币的OHLCV数据时:
- 确保数组为数据类型——TA-Lib要求此类型
float64 - 传入TA-Lib前按时间戳升序排序
- 计算指标前处理低流动性代币数据中的缺口
python
undefinedConvert to float64 for TA-Lib compatibility
转换为float64以兼容TA-Lib
close = df["close"].values.astype(np.float64)
high = df["high"].values.astype(np.float64)
low = df["low"].values.astype(np.float64)
undefinedclose = df["close"].values.astype(np.float64)
high = df["high"].values.astype(np.float64)
low = df["low"].values.astype(np.float64)
undefinedIntegration with Other Skills
与其他技能集成
With pandas-ta
与pandas-ta集成
pandas-ta can use TA-Lib as a backend when installed, getting C-speed through the pandas-ta API:
python
import pandas_ta as ta当安装TA-Lib后,pandas-ta可将其作为后端,通过pandas-ta API获得C语言级速度:
python
import pandas_ta as tapandas-ta auto-detects TA-Lib and uses it for supported indicators
pandas-ta会自动检测TA-Lib,并对支持的指标使用它
Set explicitly:
显式设置:
ta.Imports["talib"] = True # Force TA-Lib backend
df.ta.rsi(length=14) # Uses TA-Lib under the hood if available
undefinedta.Imports["talib"] = True # 强制使用TA-Lib后端
df.ta.rsi(length=14) # 如果可用,底层会使用TA-Lib
undefinedWith vectorbt
与vectorbt集成
vectorbt integrates with TA-Lib for fast backtesting:
python
import vectorbt as vbtvectorbt与TA-Lib集成以实现快速回测:
python
import vectorbt as vbtUse TA-Lib indicators in vectorbt
在vectorbt中使用TA-Lib指标
rsi = vbt.talib("RSI").run(close, timeperiod=14)
entries = rsi.real_crossed_below(30)
exits = rsi.real_crossed_above(70)
undefinedrsi = vbt.talib("RSI").run(close, timeperiod=14)
entries = rsi.real_crossed_below(30)
exits = rsi.real_crossed_above(70)
undefinedWith Birdeye/DexScreener Data
与Birdeye/DexScreener数据集成
Fetch OHLCV data from API skills, then process with TA-Lib:
python
undefined从API技能获取OHLCV数据,然后用TA-Lib处理:
python
undefinedAfter fetching OHLCV from birdeye-api or dexscreener-api
从birdeye-api或dexscreener-api获取OHLCV数据后
close = np.array(ohlcv_data["close"], dtype=np.float64)
rsi = talib.RSI(close, timeperiod=14)
undefinedclose = np.array(ohlcv_data["close"], dtype=np.float64)
rsi = talib.RSI(close, timeperiod=14)
undefinedListing Available Functions
列出可用函数
python
import talibpython
import talibAll function groups
所有函数分组
groups = talib.get_function_groups()
for group, funcs in groups.items():
print(f"{group}: {len(funcs)} functions")
groups = talib.get_function_groups()
for group, funcs in groups.items():
print(f"{group}: {len(funcs)} functions")
All function names
所有函数名称
all_funcs = talib.get_functions()
print(f"Total: {len(all_funcs)} functions")
all_funcs = talib.get_functions()
print(f"Total: {len(all_funcs)} functions")
Info about a specific function
获取特定函数的信息
info = talib.abstract.Function("RSI").info
print(info["display_name"], info["group"])
undefinedinfo = talib.abstract.Function("RSI").info
print(info["display_name"], info["group"])
undefinedFiles
文件说明
| File | Description |
|---|---|
| Most useful functions by category with syntax and parameters |
| All 61 candlestick patterns grouped by type with reliability ratings |
| Computes common indicators with TA-Lib/fallback comparison |
| Scans OHLCV data for all 61 candlestick patterns |
| 文件 | 描述 |
|---|---|
| 按类别划分的最实用函数列表,包含语法和参数说明 |
| 全部61种K线形态按类型分组,包含可靠性评级 |
| 使用TA-Lib计算常见指标,并提供降级方案对比 |
| 扫描OHLCV数据以识别全部61种K线形态 |