Skip to content

seagochen/pandas-ta

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

50 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Technical Analysis Library in Python

Example Chart

Technical Analysis (TA) is an easy to use library that is built upon Python's Pandas library with more than 60 Indicators. These indicators are comminly used for financial time series datasets with columns or labels similar to: datetime, open, high, low, close, volume, et al. Many commonly used indicators are included, such as: Moving Average Convergence Divergence (MACD), Hull Exponential Moving Average (HMA), Bollinger Bands (BBANDS), On-Balance Volume (OBV), Aroon Oscillator (AROON) and more.

This version contains both the orignal code branch as well as a newly refactored branch with the option to use Pandas DataFrame Extension mode. All the indicators return a named Series or a DataFrame in uppercase underscore parameter format. For example, MACD(fast=12, slow=26, signal=9) will return a DataFrame with columns: ['MACD_12_26_9', 'MACDH_12_26_9', 'MACDS_12_26_9'].

New Changes

  • At 70+ indicators.
  • Abbreviated Indicator names as listed below.
  • Extended Pandas DataFrame as 'ta'. See examples below.
  • Parameter names are more consistent.
  • Refactoring indicators into categories similar to TA-lib.

What is a Pandas DataFrame Extension?

A Pandas DataFrame Extension, extends a DataFrame allowing one to add more functionality and features to Pandas to suit your needs. As such, it is now easier to run Technical Analysis on existing Financial Time Series without leaving the current DataFrame. This extension by default returns the Indicator result or, inclusively, it can append the result to the existing DataFrame by including the parameter 'append=True' in the method call. See examples below.

Getting Started and Examples

Requirements

  • Python 3.7+
  • pandas >= 2.0.0
  • numpy >= 1.23.0

Installation (python 3)

$ pip install pandas_ta

Latest Version

$ pip install -U git+https://github.com/twopirllc/pandas-ta.git

Or Install from Source

$ git clone https://github.com/twopirllc/pandas-ta.git
$ cd pandas-ta
$ pip install -r requirements.txt
$ pip install -e .

Quick Start using the DataFrame Extension

Prepare Your Data

Your DataFrame should have the following columns (case-insensitive):

  • datetime or date (optional, but recommended as index)
  • open - Opening price
  • high - High price
  • low - Low price
  • close - Closing price
  • volume - Trading volume
import pandas as pd
import pandas_ta as ta

# Example 1: Load data from CSV
df = pd.read_csv('symbol.csv', sep=',')
# Make sure datetime is the index
df.set_index('date', inplace=True)

# Example 2: Create sample data
df = pd.DataFrame({
    'open': [100, 101, 102, 103, 104],
    'high': [102, 103, 104, 105, 106],
    'low': [99, 100, 101, 102, 103],
    'close': [101, 102, 103, 104, 105],
    'volume': [1000, 1100, 1200, 1300, 1400]
})

# Example 3: Load data from yfinance (requires: pip install yfinance)
# import yfinance as yf
# df = yf.download('AAPL', start='2020-01-01', end='2023-12-31')
# df.columns = df.columns.str.lower()  # Convert to lowercase

Using the DataFrame Extension

# Method 1: Calculate indicators and append to DataFrame
df.ta.sma(length=20, append=True)  # 20-period Simple Moving Average
df.ta.ema(length=50, append=True)  # 50-period Exponential Moving Average
df.ta.rsi(length=14, append=True)  # 14-period Relative Strength Index

# Method 2: Calculate indicators and return as separate Series/DataFrame
macd = df.ta.macd(fast=12, slow=26, signal=9)  # Returns DataFrame with MACD, MACDH, MACDS
print(macd.head())

# Method 3: Calculate multiple indicators at once
df.ta.sma(length=20, append=True)
df.ta.bbands(length=20, stdev=2, append=True)  # Bollinger Bands
df.ta.atr(length=14, append=True)  # Average True Range

# View the updated DataFrame with new indicator columns
print(df.tail())

# Calculate Returns and append to the df DataFrame
df.ta.log_return(cumulative=True, append=True)
df.ta.percent_return(cumulative=True, append=True)

# New Columns with results
print(df.columns)

Using Custom Column Names

If your DataFrame uses different column names (e.g., 'Open', 'High', 'Low', 'Close', 'Volume'):

# Specify custom column names
df.ta.sma(close='Close', length=20, append=True)
df.ta.bbands(close='Close', length=20, append=True)
df.ta.rsi(close='Close', length=14, append=True)

# For indicators requiring multiple columns
df.ta.macd(close='Close', fast=12, slow=26, signal=9, append=True)
df.ta.adx(high='High', low='Low', close='Close', length=14, append=True)

Using Indicators Directly (Without DataFrame Extension)

import pandas_ta as ta

# Calculate indicators without DataFrame extension
sma_20 = ta.sma(df['close'], length=20)
ema_50 = ta.ema(df['close'], length=50)
rsi_14 = ta.rsi(df['close'], length=14)

# For indicators requiring multiple columns
macd_df = ta.macd(df['close'], fast=12, slow=26, signal=9)
bbands_df = ta.bbands(df['close'], length=20, stdev=2)
atr_series = ta.atr(high=df['high'], low=df['low'], close=df['close'], length=14)

# Add results back to DataFrame manually
df['SMA_20'] = sma_20
df['RSI_14'] = rsi_14

Common Use Cases

# 1. Moving Average Crossover Strategy
df.ta.sma(length=20, append=True)
df.ta.sma(length=50, append=True)
df['signal'] = 0
df.loc[df['SMA_20'] > df['SMA_50'], 'signal'] = 1
df.loc[df['SMA_20'] < df['SMA_50'], 'signal'] = -1

# 2. RSI Overbought/Oversold
df.ta.rsi(length=14, append=True)
df['rsi_signal'] = 0
df.loc[df['RSI_14'] > 70, 'rsi_signal'] = -1  # Overbought
df.loc[df['RSI_14'] < 30, 'rsi_signal'] = 1   # Oversold

# 3. Bollinger Bands Breakout
bbands = df.ta.bbands(length=20, stdev=2, append=True)
df['bb_signal'] = 0
df.loc[df['close'] > df['BBU_20_2.0'], 'bb_signal'] = 1  # Price above upper band
df.loc[df['close'] < df['BBL_20_2.0'], 'bb_signal'] = -1  # Price below lower band

# 4. Volume Analysis
df.ta.obv(append=True)  # On-Balance Volume
df.ta.ad(append=True)   # Accumulation/Distribution
df.ta.cmf(length=20, append=True)  # Chaikin Money Flow

Module and Indicator Help

import pandas as pd
import pandas_ta as ta

# Help about this, 'ta', extension
help(pd.DataFrame().ta)

# List of all indicators
pd.DataFrame().ta.indicators()

# Help about the log_return indicator
help(ta.log_return)

# Help about the log_return indicator as a DataFrame Extension
help(pd.DataFrame().ta.log_return)

Technical Analysis Indicators (by Category)

Momentum (18)

  • Awesome Oscillator: ao
  • Absolute Price Oscillator: apo
  • Balance of Power: bop
  • Commodity Channel Index: cci
  • Chande Momentum Oscillator: cmo
  • Coppock Curve: coppock
  • KST Oscillator: kst
  • Moving Average Convergence Divergence: macd
  • Momentum: mom
  • Percentage Price Oscillator: ppo
  • Rate of Change: roc
  • Relative Strength Index: rsi
  • Stochastic Oscillator: stoch
  • Trix: trix
  • True strength index: tsi
  • Ultimate Oscillator: uo
  • Williams %R: willr
  • Connors RSI: connorsrsi
Moving Average Convergence Divergence (MACD)
Example MACD

Overlap (23)

  • Double Exponential Moving Average: dema
  • Exponential Moving Average: ema
  • Fibonacci's Weighted Moving Average: fwma
  • High-Low Average: hl2
  • High-Low-Close Average: hlc3
    • Commonly known as 'Typical Price' in Technical Analysis literature
  • Hull Exponential Moving Average: hma
  • Ichimoku Kinkō Hyō: ichimoku
    • Use: help(ta.ichimoku). Returns two DataFrames.
  • Linear Regression: linreg
  • Midpoint: midpoint
  • Midprice: midprice
  • Open-High-Low-Close Average: ohlc4
  • Pascal's Weighted Moving Average: pwma
  • William's Moving Average: rma
  • Simple Moving Average: sma
  • T3 Moving Average: t3
  • Triple Exponential Moving Average: tema
  • Triangular Moving Average: trima
  • Volume Weighted Average Price: vwap
  • Volume Weighted Moving Average: vwma
  • Weighted Moving Average: wma
  • Zero Lag Moving Average: zlma
  • Kaufman Adaptive Moving Average: kama
  • Williams Alligator: alligator
Simple Moving Averages (SMA) and Bollinger Bands (BBANDS)
Example Chart

Performance (2)

Use parameter: cumulative=True for cumulative results.

  • Log Return: log_return
  • Percent Return: percent_return
Percent Return (Cumulative) with Simple Moving Average (SMA)
Example Cumulative Percent Return

Statistics (8)

  • Kurtosis: kurtosis
  • Mean Absolute Deviation: mad
  • Median: median
  • Quantile: quantile
  • Skew: skew
  • Standard Deviation: stdev
  • Variance: variance
  • Z Score: zscore
Z Score
Example Z Score

Trend (10)

  • Average Directional Movement Index: adx
  • Aroon Oscillator: aroon
  • Decreasing: decreasing
  • Detrended Price Oscillator: dpo
  • Increasing: increasing
  • Q Stick: qstick
  • Vortex: vortex
  • Parabolic SAR: psar
  • Supertrend: supertrend
  • Schaff Trend Cycle: stc
Average Directional Movement Index (ADX)
Example ADX

Volatility (9)

  • Acceleration Bands: accbands
  • Average True Range: atr
  • Bollinger Bands: bbands
  • Donchian Channel: donchian
  • Keltner Channel: kc
  • Mass Index: massi
  • Normalized Average True Range: natr
  • True Range: true_range
  • Choppiness Index: chop
Average True Range (ATR)
Example ATR

Volume (12)

  • Accumulation/Distribution Index: ad
  • Accumulation/Distribution Oscillator: adosc
  • Chaikin Money Flow: cmf
  • Elder's Force Index: efi
  • Ease of Movement: eom
  • Money Flow Index: mfi
  • Negative Volume Index: nvi
  • On-Balance Volume: obv
  • Positive Volume Index: pvi
  • Price-Volume: pvol
  • Price Volume Trend: pvt
  • Volume Profile: vp
On-Balance Volume (OBV)
Example OBV

Inspiration

Please leave any comments, feedback, or suggestions.

About

An easy to use Python 3 Pandas Extension with 70+Technical Analysis Indicators

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Python 100.0%