Este es un envoltorio de pitón para TA-libs basado en Cython en lugar de Swig. De la página de inicio:
TA-LIB es ampliamente utilizado por los desarrolladores de software comerciales que requieren realizar un análisis técnico de los datos del mercado financiero.
- Incluye más de 150 indicadores como ADX, MACD, RSI, Bandas estocásticas, Bollinger, etc.
- Reconocimiento de patrones de velas
- API de código abierto para C/C ++, Java, Perl, Python y 100% gestionado .NET .NET
Las fijaciones originales de Python incluidas con TA-libs usan Swig, que desafortunadamente son difíciles de instalar y no son tan eficientes como podrían ser. Por lo tanto, este proyecto utiliza Cython y Numpy para unirse de manera eficiente y limpia a TA-lib, produciendo resultados 2-4 veces más rápido que la interfaz SWIG.
Además, este proyecto también admite el uso de las bibliotecas Polares y Pandas.
Puede instalar desde Pypi:
$ python -m pip install TA-Lib
O consulte las fuentes y ejecute setup.py
usted mismo:
$ python setup.py install
También parece posible instalar a través de Conda Forge:
$ conda install -c conda-forge ta-lib
Para usar TA-LIB para Python, debe instalarse la TA-LIB. Probablemente debería seguir sus instrucciones de instalación para su plataforma, pero algunas sugerencias se incluyen a continuación como referencia.
Algunos usuarios de Conda Forge han informado que el éxito instaló la biblioteca Ta-Lib C subyacente utilizando el paquete LBTA-LIB:
$ conda install -c conda-forge libta-lib
Simplemente puede instalar usando HomeBrew:
$ brew install ta-lib
Si está utilizando Apple Silicon, como los procesadores M1 y la creación de proyectos caseros de arquitectura mixta, es posible que desee asegurarse de que se esté construyendo para su arquitectura:
$ arch -arm64 brew install ta-lib
Y tal vez pueda configurarlos antes de instalar con pip
:
$ export TA_INCLUDE_PATH="$(brew --prefix ta-lib)/include"
$ export TA_LIBRARY_PATH="$(brew --prefix ta-lib)/lib"
También puede encontrar esto útil, particularmente si ha probado varias instalaciones diferentes sin éxito:
$ your-arm64-python -m pip install --no-cache-dir ta-lib
Descargue Ta-Lib-0.4.0-MSVC.Zip y Unzip a C:ta-lib
.
Este es un lanzamiento binario de 32 bits. Si desea usar Python de 64 bits, deberá construir una versión de 64 bits de la biblioteca. Algunas instrucciones no oficiales para construir en Windows 10 o Windows 11 de 64 bits, aquí como referencia:
- Descargar y descifrar
ta-lib-0.4.0-msvc.zip
- Mueva la carpeta descomprimida
ta-lib
aC:
- Descargar e instalar Visual Studio Community (2015 o posterior)
- Recuerde seleccionar la función
[Visual C++]
- Biblioteca de construcción de ta-liber
- Desde el menú de inicio de Windows, iniciar
[x64 Native Tools Command Prompt]
- Mover a
C:ta-libcmakecdrwin32msvc
- Construir la biblioteca
nmake
También puede probar estas ruedas binarias de ventanas no oficiales para 32 bits y 64 bits:
https://github.com/cgohlke/talib-build/
Descargar ta-lib-0.4.0-src.tar.gz y:
$ tar -xzf ta-lib-0.4.0-src.tar.gz
$ cd ta-lib/
$ ./configure --prefix=/usr
$ make
$ sudo make install
Si construye
TA-Lib
usandomake -jX
fallará, ¡pero eso está bien! Simplemente vuelvamake -jX
seguido de[sudo] make install
.
Nota: Si su ruta de directorio incluye espacios, la instalación probablemente fallará No such file or directory
.
Si obtienes una advertencia que se ve así:
setup.py:79: UserWarning: Cannot find ta-lib library, installation may fail.
warnings.warn('Cannot find ta-lib library, installation may fail.')
Esto típicamente significa setup.py
no puede encontrar la biblioteca TA-Lib
subyacente, una dependencia que debe instalarse.
Si instaló la biblioteca TA-Lib
subyacente con un prefijo personalizado (por ejemplo, con ./configure --prefix=$PREFIX
), entonces cuando vaya a instalar este envoltorio de Python, puede especificar rutas de búsqueda adicionales para encontrar la biblioteca e incluir archivos e incluir archivos Para la biblioteca TA-Lib
subyacente utilizando las variables de entorno TA_LIBRARY_PATH
y TA_INCLUDE_PATH
:
$ export TA_LIBRARY_PATH= $PREFIX /lib
$ export TA_INCLUDE_PATH= $PREFIX /include
$ python setup.py install # or pip install ta-lib
A veces, la instalación producirá errores de compilación como este:
talib/_ta_lib.c:601:10: fatal error: ta-lib/ta_defs.h: No such file or directory
601 | #include "ta-lib/ta_defs.h"
| ^~~~~~~~~~~~~~~~~~
compilation terminated.
o:
common.obj : error LNK2001: unresolved external symbol TA_SetUnstablePeriod
common.obj : error LNK2001: unresolved external symbol TA_Shutdown
common.obj : error LNK2001: unresolved external symbol TA_Initialize
common.obj : error LNK2001: unresolved external symbol TA_GetUnstablePeriod
common.obj : error LNK2001: unresolved external symbol TA_GetVersionString
Esto generalmente significa que no puede encontrar la biblioteca TA-Lib
subyacente, una dependencia que debe instalarse. En Windows, esto podría ser causado por la instalación de la distribución binaria de 32 bits de la biblioteca TA-Lib
subyacente, pero tratando de usarla con Python de 64 bits.
A veces, la instalación fallará con errores como este:
talib/common.c:8:22: fatal error: pyconfig.h: No such file or directory
#include "pyconfig.h"
^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
Esto generalmente significa que necesita los encabezados de Python, y debe ejecutar algo como:
$ sudo apt-get install python3-dev
A veces, construir la biblioteca TA-Lib
subyacente tiene errores que se ejecutan make
que se vean así:
../libtool: line 1717: cd: .libs/libta_lib.lax/libta_abstract.a: No such file or directory
make[2]: *** [libta_lib.la] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all-recursive] Error 1
Esto podría significar que la ruta del directorio a la biblioteca TA-Lib
subyacente tiene espacios en los nombres de los directorio. Intente ponerlo en un camino que no tenga espacios e intente nuevamente.
A veces puede obtener este error ejecutándose setup.py
:
/usr/include/limits.h:26:10: fatal error: bits/libc-header-start.h: No such file or directory
#include <bits/libc-header-start.h>
^~~~~~~~~~~~~~~~~~~~~~~~~~
Es probable que este sea un problema para tratar de compilar para una plataforma de 32 bits pero sin los encabezados apropiados. Es posible que encuentre algo de éxito mirando la primera respuesta a esta pregunta.
Si recibe un error en macOS como este:
code signature in <141BC883-189B-322C-AE90-CBF6B5206F67>
'python3.9/site-packages/talib/_ta_lib.cpython-39-darwin.so' not valid for
use in process: Trying to load an unsigned library)
Puede mirar esta pregunta y usar xcrun codesign
para solucionarla.
Si se pregunta por qué STOCHRSI
le da resultados diferentes de lo que espera, probablemente desee STOCH
aplique a RSI
, que es un poco diferente al STOCHRSI
que STOCHF
aplica a RSI
: RSI:
>> > import talib
>> > import numpy as np
>> > c = np . random . randn ( 100 )
# this is the library function
>> > k , d = talib . STOCHRSI ( c )
# this produces the same result, calling STOCHF
>> > rsi = talib . RSI ( c )
>> > k , d = talib . STOCHF ( rsi , rsi , rsi )
# you might want this instead, calling STOCH
>> > rsi = talib . RSI ( c )
>> > k , d = talib . STOCH ( rsi , rsi , rsi )
Si la compilación parece colgar, es posible que esté funcionando en una VM con no suficiente memoria: pruebe 1 GB o 2 GB.
Si recibe errores de "permiso denegado" como este, es posible que deba darle a su usuario acceso a la ubicación donde se instala la biblioteca Ta-Lib C subyacente, o instalarla en una ubicación accesible para el usuario.
talib/_ta_lib.c:747:28: fatal error: /usr/include/ta-lib/ta_defs.h: Permission denied
#include "ta-lib/ta-defs.h"
^
compilation terminated
error: command 'gcc' failed with exit status 1
Si tiene problemas para compilar la biblioteca Ta-Lib C subyacente en ARM64, es posible que deba configurarlo con un tipo de compilación explícito antes de ejecutar la instalación make
and make install
, por ejemplo:
$ ./configure --build=aarch64-unknown-linux-gnu
Esto es causado por el archivo config.guess
antiguo, por lo que otra forma de resolver esto es copiar una versión más nueva de config.guess en las fuentes subyacentes de la biblioteca Ta-Lib C:
$ cp /usr/share/automake-1.16/config.guess /path/to/extracted/ta-lib/config.guess
Y luego vuelva a ejecutar Configurar:
$ ./configure
Si tiene problemas para usar Pyinstaller y obtenga un error que se vea así:
...site-packagesPyInstallerloaderpyimod03_importers.py", line 493, in exec_module
exec(bytecode, module.__dict__)
File "talib__init__.py", line 72, in <module>
ModuleNotFoundError: No module named 'talib.stream'
Entonces, tal vez pueda usar el argumento --hidden-import
para solucionar esto:
$ pyinstaller --hidden-import talib.stream "replaceToYourFileName.py"
Si desea usar numpy<2
, entonces debe usar ta-lib<0.5
.
Si desea usar numpy>=2
, debe usar ta-lib>=0.5
.
Si tiene problemas para hacer que el código se funcione autocompletaciones en el código de Visual Studio, se hizo una sugerencia para buscar la configuración de la extensión Python
y una opción para Language Server
, y cambiarlo desde Default
(lo que significa Pylance if it is installed, Jedi otherwise
, para establecer manualmente Jedi
y las terminaciones deberían funcionar.
Similar a TA-LIB, la API de la función proporciona un envoltorio ligero de los indicadores de TA-TA expuestos.
Cada función devuelve una matriz de salida y tiene valores predeterminados para sus parámetros, a menos que se especifique como argumentos de palabras clave. Por lo general, estas funciones tendrán un período inicial "Lookback" (un número requerido de observaciones antes de que se genere una salida) establecido en NaN
.
Por conveniencia, la API de la función es compatible con numpy.ndarray
y pandas.Series
y polars.Series
Inputs.
Todos los siguientes ejemplos usan la API de la función:
import numpy as np
import talib
close = np . random . random ( 100 )
Calcule un promedio móvil simple de los precios cerrados:
output = talib . SMA ( close )
Calculando las bandas de Bollinger, con un promedio móvil exponencial triple:
from talib import MA_Type
upper , middle , lower = talib . BBANDS ( close , matype = MA_Type . T3 )
Calcular el impulso de los precios cerrados, con un período de tiempo de 5:
output = talib . MOM ( close , timeperiod = 5 )
La biblioteca subyacente de Ta-Lib C maneja los Nan de una manera a veces sorprendente al propagar típicamente a Nan al final de la salida, por ejemplo:
>> > c = np . array ([ 1.0 , 2.0 , 3.0 , np . nan , 4.0 , 5.0 , 6.0 ])
>> > talib . SMA ( c , 3 )
array ([ nan , nan , 2. , nan , nan , nan , nan ])
Puede comparar eso con una media de lanza de pandas, donde su enfoque es emitir NAN hasta que se observen suficientes valores de "respaldo" para generar nuevas salidas:
>> > c = pandas . Series ([ 1.0 , 2.0 , 3.0 , np . nan , 4.0 , 5.0 , 6.0 ])
>> > c . rolling ( 3 ). mean ()
0 NaN
1 NaN
2 2.0
3 NaN
4 NaN
5 NaN
6 5.0
dtype : float64
Si ya está familiarizado con el uso de la API de la función, debe sentirse en casa usando la API abstracta.
Cada función toma una colección de entradas con nombre, un dict
de numpy.ndarray
o pandas.Series
o polars.Series
, o un pandas.DataFrame
o polars.DataFrame
. Si se proporciona un pandas.DataFrame
o polars.DataFrame
, la salida se devuelve como el mismo tipo con columnas de salida con nombre.
Por ejemplo, se podrían proporcionar entradas para los datos típicos "OHLCV":
import numpy as np
# note that all ndarrays must be the same length!
inputs = {
'open' : np . random . random ( 100 ),
'high' : np . random . random ( 100 ),
'low' : np . random . random ( 100 ),
'close' : np . random . random ( 100 ),
'volume' : np . random . random ( 100 )
}
Las funciones se pueden importar directamente o instanciarse por nombre:
from talib import abstract
# directly
SMA = abstract . SMA
# or by name
SMA = abstract . Function ( 'sma' )
A partir de ahí, llamar a las funciones es básicamente lo mismo que la API de la función:
from talib . abstract import *
# uses close prices (default)
output = SMA ( inputs , timeperiod = 25 )
# uses open prices
output = SMA ( inputs , timeperiod = 25 , price = 'open' )
# uses close prices (default)
upper , middle , lower = BBANDS ( inputs , 20 , 2.0 , 2.0 )
# uses high, low, close (default)
slowk , slowd = STOCH ( inputs , 5 , 3 , 0 , 3 , 0 ) # uses high, low, close by default
# uses high, low, open instead
slowk , slowd = STOCH ( inputs , 5 , 3 , 0 , 3 , 0 , prices = [ 'high' , 'low' , 'open' ])
Se agregó una API de transmisión experimental que permite a los usuarios calcular el último valor de un indicador. Esto puede ser más rápido que usar la API de la función, por ejemplo, en una aplicación que recibe datos de transmisión y quiere saber solo el valor del indicador actualizado más reciente.
import talib
from talib import stream
close = np . random . random ( 100 )
# the Function API
output = talib . SMA ( close )
# the Streaming API
latest = stream . SMA ( close )
# the latest value is the same as the last output value
assert ( output [ - 1 ] - latest ) < 0.00001
Podemos mostrar todas las funciones de TA respaldadas por TA-lib, ya sea como una list
o como un dict
clasificado por el grupo (por ejemplo, "estudios de superposición", "indicadores de impulso", etc.):
import talib
# list of functions
for name in talib . get_functions ():
print ( name )
# dict of functions by group
for group , names in talib . get_function_groups (). items ():
print ( group )
for name in names :
print ( f" { name } " )
BBANDS Bollinger Bands
DEMA Double Exponential Moving Average
EMA Exponential Moving Average
HT_TRENDLINE Hilbert Transform - Instantaneous Trendline
KAMA Kaufman Adaptive Moving Average
MA Moving average
MAMA MESA Adaptive Moving Average
MAVP Moving average with variable period
MIDPOINT MidPoint over period
MIDPRICE Midpoint Price over period
SAR Parabolic SAR
SAREXT Parabolic SAR - Extended
SMA Simple Moving Average
T3 Triple Exponential Moving Average (T3)
TEMA Triple Exponential Moving Average
TRIMA Triangular Moving Average
WMA Weighted Moving Average
ADX Average Directional Movement Index
ADXR Average Directional Movement Index Rating
APO Absolute Price Oscillator
AROON Aroon
AROONOSC Aroon Oscillator
BOP Balance Of Power
CCI Commodity Channel Index
CMO Chande Momentum Oscillator
DX Directional Movement Index
MACD Moving Average Convergence/Divergence
MACDEXT MACD with controllable MA type
MACDFIX Moving Average Convergence/Divergence Fix 12/26
MFI Money Flow Index
MINUS_DI Minus Directional Indicator
MINUS_DM Minus Directional Movement
MOM Momentum
PLUS_DI Plus Directional Indicator
PLUS_DM Plus Directional Movement
PPO Percentage Price Oscillator
ROC Rate of change : ((price/prevPrice)-1)*100
ROCP Rate of change Percentage: (price-prevPrice)/prevPrice
ROCR Rate of change ratio: (price/prevPrice)
ROCR100 Rate of change ratio 100 scale: (price/prevPrice)*100
RSI Relative Strength Index
STOCH Stochastic
STOCHF Stochastic Fast
STOCHRSI Stochastic Relative Strength Index
TRIX 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA
ULTOSC Ultimate Oscillator
WILLR Williams' %R
AD Chaikin A/D Line
ADOSC Chaikin A/D Oscillator
OBV On Balance Volume
HT_DCPERIOD Hilbert Transform - Dominant Cycle Period
HT_DCPHASE Hilbert Transform - Dominant Cycle Phase
HT_PHASOR Hilbert Transform - Phasor Components
HT_SINE Hilbert Transform - SineWave
HT_TRENDMODE Hilbert Transform - Trend vs Cycle Mode
AVGPRICE Average Price
MEDPRICE Median Price
TYPPRICE Typical Price
WCLPRICE Weighted Close Price
ATR Average True Range
NATR Normalized Average True Range
TRANGE True Range
CDL2CROWS Two Crows
CDL3BLACKCROWS Three Black Crows
CDL3INSIDE Three Inside Up/Down
CDL3LINESTRIKE Three-Line Strike
CDL3OUTSIDE Three Outside Up/Down
CDL3STARSINSOUTH Three Stars In The South
CDL3WHITESOLDIERS Three Advancing White Soldiers
CDLABANDONEDBABY Abandoned Baby
CDLADVANCEBLOCK Advance Block
CDLBELTHOLD Belt-hold
CDLBREAKAWAY Breakaway
CDLCLOSINGMARUBOZU Closing Marubozu
CDLCONCEALBABYSWALL Concealing Baby Swallow
CDLCOUNTERATTACK Counterattack
CDLDARKCLOUDCOVER Dark Cloud Cover
CDLDOJI Doji
CDLDOJISTAR Doji Star
CDLDRAGONFLYDOJI Dragonfly Doji
CDLENGULFING Engulfing Pattern
CDLEVENINGDOJISTAR Evening Doji Star
CDLEVENINGSTAR Evening Star
CDLGAPSIDESIDEWHITE Up/Down-gap side-by-side white lines
CDLGRAVESTONEDOJI Gravestone Doji
CDLHAMMER Hammer
CDLHANGINGMAN Hanging Man
CDLHARAMI Harami Pattern
CDLHARAMICROSS Harami Cross Pattern
CDLHIGHWAVE High-Wave Candle
CDLHIKKAKE Hikkake Pattern
CDLHIKKAKEMOD Modified Hikkake Pattern
CDLHOMINGPIGEON Homing Pigeon
CDLIDENTICAL3CROWS Identical Three Crows
CDLINNECK In-Neck Pattern
CDLINVERTEDHAMMER Inverted Hammer
CDLKICKING Kicking
CDLKICKINGBYLENGTH Kicking - bull/bear determined by the longer marubozu
CDLLADDERBOTTOM Ladder Bottom
CDLLONGLEGGEDDOJI Long Legged Doji
CDLLONGLINE Long Line Candle
CDLMARUBOZU Marubozu
CDLMATCHINGLOW Matching Low
CDLMATHOLD Mat Hold
CDLMORNINGDOJISTAR Morning Doji Star
CDLMORNINGSTAR Morning Star
CDLONNECK On-Neck Pattern
CDLPIERCING Piercing Pattern
CDLRICKSHAWMAN Rickshaw Man
CDLRISEFALL3METHODS Rising/Falling Three Methods
CDLSEPARATINGLINES Separating Lines
CDLSHOOTINGSTAR Shooting Star
CDLSHORTLINE Short Line Candle
CDLSPINNINGTOP Spinning Top
CDLSTALLEDPATTERN Stalled Pattern
CDLSTICKSANDWICH Stick Sandwich
CDLTAKURI Takuri (Dragonfly Doji with very long lower shadow)
CDLTASUKIGAP Tasuki Gap
CDLTHRUSTING Thrusting Pattern
CDLTRISTAR Tristar Pattern
CDLUNIQUE3RIVER Unique 3 River
CDLUPSIDEGAP2CROWS Upside Gap Two Crows
CDLXSIDEGAP3METHODS Upside/Downside Gap Three Methods
BETA Beta
CORREL Pearson's Correlation Coefficient (r)
LINEARREG Linear Regression
LINEARREG_ANGLE Linear Regression Angle
LINEARREG_INTERCEPT Linear Regression Intercept
LINEARREG_SLOPE Linear Regression Slope
STDDEV Standard Deviation
TSF Time Series Forecast
VAR Variance