ta-lib

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

ta-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 (
TA-Lib
on PyPI, imported as
talib
) provides:
  • 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-Lib
,导入时使用
talib
)提供:
  • 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
undefined
TA-Lib要求先安装底层的C语言库:
bash
undefined

macOS

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

CriterionTA-Libpandas-ta
SpeedC-optimized, 10-100x fasterPure Python, slower on large data
Candlestick patterns61 built-in patternsLimited pattern support
InstallationRequires C library
pip install
only
API styleNumPy arraysDataFrame
.ta
accessor
Indicator count150+130+
StreamingSingle-value update possibleRecompute entire series
DependenciesC lib + numpypandas 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-Libpandas-ta
速度C语言优化,速度快10-100倍纯Python实现,处理大数据时速度较慢
K线形态内置61种形态形态支持有限
安装需要安装C语言库仅需
pip install
API风格基于NumPy数组DataFrame的
.ta
访问器
指标数量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 talib
python
import numpy as np
import talib

Create 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)
undefined
doji = talib.CDLDOJI(open_, high, low, close) hammer = talib.CDLHAMMER(open_, high, low, close) engulfing = talib.CDLENGULFING(open_, high, low, close)
undefined

Function 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:
  • +100
    = bullish pattern detected
  • -100
    = bearish pattern detected
  • 0
    = no pattern
python
undefined
61种用于检测K线形态的函数。所有函数均返回整数数组:
  • +100
    = 检测到看涨形态
  • -100
    = 检测到看跌形态
  • 0
    = 未检测到形态
python
undefined

Single 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
NaN
for the initial lookback period of each indicator. Always account for this:
python
rsi = talib.RSI(close, timeperiod=14)
TA-Lib会在每个指标的初始回溯期返回
NaN
值。务必对此进行处理:
python
rsi = talib.RSI(close, timeperiod=14)

First 14 values will be NaN

前14个值为NaN

valid_rsi = rsi[~np.isnan(rsi)]
undefined
valid_rsi = rsi[~np.isnan(rsi)]
undefined

Solana Token Data

Solana代币数据

When using TA-Lib with Solana token OHLCV data:
  • Ensure arrays are
    float64
    dtype — TA-Lib requires this
  • 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数据时:
  • 确保数组为
    float64
    数据类型——TA-Lib要求此类型
  • 传入TA-Lib前按时间戳升序排序
  • 计算指标前处理低流动性代币数据中的缺口
python
undefined

Convert 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)
undefined
close = df["close"].values.astype(np.float64) high = df["high"].values.astype(np.float64) low = df["low"].values.astype(np.float64)
undefined

Integration 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 ta

pandas-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
undefined
ta.Imports["talib"] = True # 强制使用TA-Lib后端 df.ta.rsi(length=14) # 如果可用,底层会使用TA-Lib
undefined

With vectorbt

与vectorbt集成

vectorbt integrates with TA-Lib for fast backtesting:
python
import vectorbt as vbt
vectorbt与TA-Lib集成以实现快速回测:
python
import vectorbt as vbt

Use 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)
undefined
rsi = vbt.talib("RSI").run(close, timeperiod=14) entries = rsi.real_crossed_below(30) exits = rsi.real_crossed_above(70)
undefined

With Birdeye/DexScreener Data

与Birdeye/DexScreener数据集成

Fetch OHLCV data from API skills, then process with TA-Lib:
python
undefined
从API技能获取OHLCV数据,然后用TA-Lib处理:
python
undefined

After 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)
undefined
close = np.array(ohlcv_data["close"], dtype=np.float64) rsi = talib.RSI(close, timeperiod=14)
undefined

Listing Available Functions

列出可用函数

python
import talib
python
import talib

All 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"])
undefined
info = talib.abstract.Function("RSI").info print(info["display_name"], info["group"])
undefined

Files

文件说明

FileDescription
references/function_reference.md
Most useful functions by category with syntax and parameters
references/candlestick_patterns.md
All 61 candlestick patterns grouped by type with reliability ratings
scripts/compute_indicators.py
Computes common indicators with TA-Lib/fallback comparison
scripts/pattern_scanner.py
Scans OHLCV data for all 61 candlestick patterns
文件描述
references/function_reference.md
按类别划分的最实用函数列表,包含语法和参数说明
references/candlestick_patterns.md
全部61种K线形态按类型分组,包含可靠性评级
scripts/compute_indicators.py
使用TA-Lib计算常见指标,并提供降级方案对比
scripts/pattern_scanner.py
扫描OHLCV数据以识别全部61种K线形态