Skip to content

How to ...#

... do certain things with the library.


NOTICE

Thanks to all those that have sponsored and dontated to the library in the past! Your support has been greatly appreciated! 🙏

However, future releases are on definite hold until 100+ donations of $150+ have been received via Buy Me a Coffee.

Help keep this library and application the best in it's class!

General#

How to get the Pandas TA version?
1
2
3
import pandas_ta as ta

print(ta.version)
How to get the TA Categories?
1
2
3
4
5
6
7
8
import pandas as pd
import pandas_ta as ta

df = pd.DataFrame()
categories = df.ta.categories()

# Or as a Dict Keys
ta.Category.keys()
How to get a list of indicators?
import pandas as pd
import pandas_ta as ta

df = pd.DataFrame()

# Print the list of all the available indicators
df.ta.indicators()

# Or as a Dict where keys are categories
ta.Category

# Get a list of all the available indicators
ind_list = df.ta.indicators(as_list=True)

# Exclude a category of indicators
ind_list = df.ta.indicators(exclude=ta.Category["cycles"])
How to add and remove constants to a DataFrame?
import pandas as pd
import pandas_ta as ta

df = pd.DataFrame()

# Add constant '1' to the DataFrame
df.ta.constants(True, [1])
# Remove constant '1' to the DataFrame
df.ta.constants(False, [1])

# Adding constants for charting
import numpy as np
chart_lines = np.append(np.arange(-4, 5, 1), np.arange(-100, 110, 10))
df.ta.constants(True, chart_lines)
# Removing some constants from the DataFrame
df.ta.constants(False, np.array([-60, -40, 40, 60]))
How to reverse the DataFrame?
1
2
3
4
5
import pandas as pd
import pandas_ta as ta

df = # ohlcv where datetime index is latest to oldest
df = df.ta.reverse()

Indicators#

How to add Candle Patterns to a DataFrame?
# Note: TA Lib must be installed for all patterns
import pandas as pd
import pandas_ta as ta

df = pd.DataFrame()

# Get all candle patterns. The default
df = df.ta.cdl_pattern(name="all")
# OR using the "ta" extension
df.ta.cdl_pattern(append=True)

# A single pattern
df = df.ta.cdl_pattern(name="doji")
# OR using the "ta" extension
df.ta.cdl_pattern(name="doji", append=True)

# Multiple patterns
df = df.ta.cdl_pattern(name=["doji", "inside"])
# OR using the "ta" extension
df.ta.cdl_pattern(name"doji", "inside"], append=True)
How to use Volume Profile?

vp or "Volume Profile" is unique among the indicators.

import pandas as pd
import pandas_ta as ta

df = pd.DataFrame()

# Default
vp = ta.vp(df.Close, df.Volume)

# For more info, see
help(ta.vp)

Misc#

How to change the case of the DataFrame Columns?
1
2
3
4
5
6
7
8
# Lower
df.columns = df.columns.str.lower()

# Upper
df.columns = df.columns.str.upper()

# Title
df.columns = df.columns.str.title()
How to create and use a Custom/Private Directory?

This is an example ni.py file to put in the custom directory to verify the custom directory is working properly.

ni.py
# -*- coding: utf-8 -*-
from pandas import Series
from pandas_ta._typing import DictLike, Int, IntFloat
from pandas_ta.ma import ma
from pandas_ta.utils import v_mamode, v_offset, v_pos_default, v_series

def ni(
    close: Series, length: Int = None,
    centered: bool = False, mamode: str = None,
    offset: Int = None, **kwargs: DictLike
):
    """Example indicator (NI)

    Is an indicator provided solely as an example

    Sources:
        [Custom Directory - Issue 264](https://github.com/twopirllc/pandas-ta/issues/264)

    Parameters:
        close (pd.Series): Series of 'close's
        length (int): It's period. Default: ```20```
        mamode (str): Chosen Moving Average. Default: ```"sma"```
        centered (bool): Shift the ni back by ```int(0.5 * length) + 1```.
            Default: ```False```
        offset (int): How many periods to offset the result.
            Default: ```0```

    Other Parameters:
        fillna (value, optional): Replaces ```na```'s with ```value```.

    Returns:
        (pd.Series): Custom Indicator Example Series.
    """    # Validate Arguments
    length = v_pos_default(length, 20)
    close = v_series(close, length)

    if close is None:
        return

    mamode = v_mamode(mamode, "sma")
    offset = v_offset(offset)

    # Calculate Result
    ma = ma(mamode, close, length=length, **kwargs)

    t = int(0.5 * length) + 1
    ni = close - ma.shift(t)
    if centered:
        ni = (close.shift(t) - ma).shift(-t)

    # Offset
    if offset != 0:
        ni = ni.shift(offset)

    # Handle fills
    if "fillna" in kwargs:
        ni.fillna(kwargs["fillna"], inplace=True)

    # Name and Categorize it
    ni.name = f"ni_{length}"
    ni.category = "trend"

    return ni


# - Define a matching class method --------------------------------------------

def ni_method(self, length=None, offset=None, **kwargs):
    close = self._get_column(kwargs.pop("close", "close"))
    result = ni(close=close, length=length, offset=offset, **kwargs)
    return self._post_process(result, **kwargs)



This is a detailed process of what creating a custom directory does.


import os
import pandas as pd
import pandas_ta as ta

from os.path import abspath, join, expanduser
from pandas_ta.custom import create_dir, import_dir

# Create an empty directory on your machine where you want to work
# with your indicators. Invoke pandas_ta.custom.import_dir once to
# pre-populate it with sub-folders for all available indicator
# categories, e.g.:

ta_dir = abspath(join(expanduser("~"), "my_indicators"))
create_dir(ta_dir)

# Add/Create your own custom indicator e.g. by copying existing ones
# from pandas_ta core module and modifying them.

# IMPORTANT: Each custom indicator must have a unique name and have both
# a) a function named exactly as the module, e.g. 'ni' if the
#    module is ni.py
# b) a matching method used by AnalysisIndicators named as the module but
#    ending with '_method'. E.g. 'ni_method'

# In essence these modules should look exactly like the standard
# indicators available in categories under the pandas_ta/src/ folders.
# The only difference will be an addition of a matching class method.

# For an example of the correct structure, look at the example ni.py
# in the examples folder.

# The ni.py indicator is a trend indicator so therefore we drop it
# into the sub-folder named trend. Thus we have a folder structure
# like this:

# ~/my_indicators/
# │
# ├── candles/
# .
# .
# └── trend/
# .      └── ni.py
# .
# └── volume/

# Now dynamically load all custom indicators located in designated
# indicators directory:

import_dir(ta_dir)

# If the custom indicator(s) loaded successfully, then it should
# behave exactly like all other native indicators in pandas_ta,
# including help functions.
How to run a speed_test?
1
2
3
4
5
# Verbose basic Speed Test without talib
speedsdf = ta.speed_test(df, talib=False, verbose=True)

# For more options:
help(ta.speed_test)



"Buy Me A Coffee"