Playing with Pandas_TA: One-stop mastering technical analysis indicators

67458a1f70a1b69f826fa63f9d0be523.png

01

introduction

Pandas_TA - a library that combines the powerful data processing capabilities of pandas with technical analysis, aiming to provide a simple and efficient tool set for financial market analysts and traders, so as to help them more easily apply various Technical analysis indicators. pandas_ta provides users with the ability to run technical indicator calculations directly on DataFrames, avoiding complex data transformation and preprocessing steps.

This library contains a wide range of classic and modern technical indicators ranging from simple moving averages to complex oscillators and momentum indicators. Further exploration and experimentation with market data using pandas_ta becomes intuitive for anyone familiar with pandas operations. Whether you are an experienced quantitative trader or a novice learning technical analysis, pandas_ta can add tremendous value to your data analysis workflow.

Before starting to use pandas_ta, first make sure you have pandas installed. If you haven't already, you can easily install it via pip: pip install pandas_ta. Import the libraries that will be used later.

import qstock as qs
import pandas_ta as ta
import matplotlib.pyplot as plt
#正常显示画图时出现的中文和负号
from pylab import mpl
mpl.rcParams['font.sans-serif']=['SimHei']
mpl.rcParams['axes.unicode_minus']=False
#以中国平安股票数据为例,获取后复权价格
df0=qs.get_data('中国平安',start='20200807',end='20230807',fqt=2)[['open','high','low','close','volume']]
#df0.tail()

For TA-Lib, please refer to the following tweets:

[Teach you by hand] TA-Lib, a sharp tool for stock market technical analysis (1)

[Teach you by hand] TA-Lib, a sharp tool for stock market technical analysis (2)

16a472bfb302e4eed5894a00f5d111ef.png

02

Basic technical indicators

Technical indicators are the core of technical analysis. They are mathematically calculated indices based on historical prices, trading volume or other market activity and are used to predict market movements, identify trends and determine buy and sell points. Next, this article will explore how to use pandas_ta to calculate these key indicators, and gain a deeper understanding of their meaning and application.

01

Moving Averages

Moving averages are one of the most commonly used technical indicators. It helps us determine the direction of the market and filter out short-term price fluctuations. Moving averages include Simple Moving Average (SMA) and Exponential Moving Average (EMA). The SMA is calculated based on the average closing price over a specified period of time. When the price is above the SMA, it can be seen as an uptrend, and when the price is below the SMA, it can be seen as a downtrend. Some traders also use two SMAs (such as 50-day and 200-day) to identify golden crosses or death crosses. Similar to SMA, but EMA weights recent prices. It is more sensitive and reacts more quickly to price changes. Since the EMA is more responsive to the latest price movements, it is often used to track short-term price dynamics. Traders may use both SMA and EMA to judge market dynamics.

df=df0.copy(deep=True) #复制一个dataframe
#简单移动平均线 (SMA)
df.ta.sma(close='close', length=20,append=True)
#指数移动平均线 (EMA)
df.ta.ema(20,append=True)
#查看df后三行数据
#df.tail(3)

The close and length keyword parameters can be omitted, such as df.ta.sma(20), and the number of days considered can be adjusted through the length parameter. append=True means to add on the dataframe after calculating the indicator.

02

Relative Strength Index (RSI)

RSI, Relative Strength Index, is a momentum oscillator that measures the speed and change in asset price movements. The RSI value ranges from 0 to 100, and 70 and 30 are usually used as the boundaries of overbought and oversold. That is to say, when the RSI value exceeds 70, it may indicate that an asset is overbought; when it is below 30, it may indicate that the asset is overbought. was oversold.

df.ta.rsi(14)

By default, RSI uses 14 days of data. The number of days can be adjusted by the length parameter.

03

MACD indicator

MACD, Moving Average Convergence Divergence, the MACD line is the difference between two EMAs (usually 12 days and 26 days), and the signal line is the EMA of the MACD line (usually 9 days). The difference (MACD Histogram) represents the difference between the MACD line and the signal line. MACD can help identify the momentum of an asset. When the MACD line is above the signal line, it may indicate that the asset is in an uptrend; otherwise, it may be in a downtrend.

macd=df.ta.macd(fast=12, slow=26, signal=9)
#df.ta.macd(12, 26, 9)
macd.tail(3)
date MACD_12_26_9 MACDh_12_26_9 MACDs_12_26_9
2023-08-03 2.366621 0.911380 1.455242
2023-08-04 2.431577 0.781069 1.650509
2023-08-07 2.422850 0.617873 1.804977

The length of the moving average can be adjusted by the fast, slow and signal parameters. Column names MACD_12_26_9, MACDh_12_26_9, MACDs_12_26_9 represent MACD line, divergence (MACD bar) and signal line, respectively. The high and low of the MACD column shows the trend of the market, a positive value indicates an upward trend, and a negative value indicates a downward trend. Of course, MACD also has certain limitations, such as hysteresis and false signal generation.

04

Bollinger Bands

The Bollinger Bands are composed of three lines: the middle track is the N-day SMA; the upper track is the middle track plus K times the standard deviation; the lower track is the middle track minus K times the standard deviation.

Bollinger Bands measure price volatility. When the price hits the upper line, it may mean that the asset is overbought, and when the price hits the lower line, it may mean that the asset is oversold. The width (bandwidth) of Bollinger Bands can also be used to measure the volatility of the market.

Implementation in pandas_ta:

#查看布林带指标数据最后几行
df.ta.bbands(20,1.5).tail()
date BBL_20_1.5 BBM_20_1.5 BBU_20_1.5 BBB_20_1.5 BBP_20_1.5
2023-08-03 123.777886 129.768 135.758114 9.232035 1.077785
2023-08-04 124.077091 130.237 136.396909 9.459537 0.940997
2023-08-07 124.644280 130.746 136.847720 9.333700 0.870715

The length controls the period of the SMA, and the std parameter determines the multiple of the standard deviation. By default, length=5 and std=2. The data column names BBL_20_1.5, BBM_20_1.5, BBU_20_1.5, BBB_20_1.5, and BBP_20_1.5 represent the lower track, middle track, upper track and width of the Bollinger Bands with 1.5 times the standard deviation of the 20-day cycle, respectively.

05

Average True Range (ATR)

ATR (Average True Range), which measures price volatility, is the average value of the true range in the past N days. The true range is the maximum of three: the difference between today's high and low, the difference between today's high and yesterday's close, and the difference between today's low and yesterday's close. ATR is a tool for assessing asset volatility and is usually used to set stop loss points or adjust trading strategies.

Implementation in pandas_ta:

df.ta.atr()

Adjust the number of days by the length parameter, the default is 14 days.

06

stochastic oscillator

Stochastic Oscillator (Stochastic Oscillator), also known as KD indicator, consists of a %K line and a %D line. The "%K" line represents the difference between the latest price and the recent lowest price, and the ratio of the recent highest and lowest price difference. The %D line has the same algorithm, but the "recent" time frame is three times larger. When the %K line is above the %D line and both are above 80, it may indicate that the asset is overbought; when the %K line is below the %D line and both are below 20, it may indicate that the asset is oversold.

Implementation in pandas_ta:

df.ta.stoch().tail(3)
date STOCHk_14_3_3 STOCHd_14_3_3
2023-08-03 74.558960 77.844537
2023-08-04 74.721922 74.907307
2023-08-07 75.509888 74.930257

The number of days in the calculation formula can be adjusted by the k, d and smooth_k parameters. The column names STOCHk_14_3_3 and STOCHd_14_3_3 represent the K and D values ​​of k, d and smooth_k with default parameters of 14, 3 and 3, respectively.

07

Chaikin Money Flow (CMF)

The full name of CMF is Chaikin Money Flow, which is an indicator used to measure the strength of capital inflow and outflow from the market, and the calculation method is based on accumulated capital flow.

A positive value may indicate money flowing into the market (buying pressure), while a negative value may indicate money flowing out of the market (selling pressure).

Implementation in pandas_ta:

df.ta.cmf()

Adjust the number of days by the length parameter, the default is 20 days.

08

Commodity Channel Index (CCI)

Commodity Channel Index, CCI, Commodity Channel Index, measures the degree of difference between commodity prices and their average prices. The calculation method is the current price minus the average price of the past N days, and then divided by the average absolute deviation. The CCI is primarily used to determine when a price is overbought or oversold. If the CCI value is greater than 100, it may indicate that the price is overbought; if the CCI value is less than -100, it may indicate that the price is oversold.

Implementation in pandas_ta:

df.ta.cci().tail()

Adjust the number of days by the length parameter, the default is 20 days.

pandas_ta makes the calculated indicators added to the dataframe of df through the parameter append=True, we calculate the above indicators and add them to df, the code is as follows:

df=df0.copy(deep=True) #复制一个dataframe
#简单移动平均线 (SMA)
df.ta.sma(close='close', length=20,append=True)
#指数移动平均线 (EMA)
df.ta.ema(20,append=True)
#RSI指标
df.ta.rsi(append=True)
#MACD指标
df.ta.macd(append=True)
#布林带
df.ta.bbands(20,1.5,append=True)
#平均真实波幅
df.ta.atr(append=True)
#随机指标
df.ta.stoch(append=True)
#Chaikin 资金流 (CMF)
df.ta.cmf(append=True)
#商品通道指数(CCI)
df.ta.cci(append=True)
#查看df后三行数据
df.tail(3)

In practice, technical traders often use multiple technical indicators in combination to gain deeper insights into the market. pandas_ta not only provides the calculation of these basic indicators, but also allows you to customize parameters and strategies to make your technical analysis more accurate and personalized.

ca056d9486b9d867c9eb67bec05e82d4.png

03

Strategy function of pandas_ta

pandas_ta not only provides various technical analysis tools, but also provides a powerful strategy function. This allows users to quickly add multiple technical indicators to the data frame without specifying them one by one. Next, we'll dive into this feature and learn how to take advantage of it. In pandas_ta, a strategy is a set of predefined technical indicators. This allows the user to apply multiple indicators at once without calling each function separately.

01

built-in strategy

3de18d31b0cb84e38443d88f71fe7709.png

pandas_ta provides the following built-in strategies:

(1) all: Add all available technical indicators at one time. df.ta.strategy('all')

df1=df0.copy()
df1.ta.strategy('all')
print(df1.columns)
#输出结果:

Index(['open', 'high', 'low', 'close', 'volume', 'ABER_ZG_5_15',
       'ABER_SG_5_15', 'ABER_XG_5_15', 'ABER_ATR_5_15', 'ACCBL_20',
       ...
       'VIDYA_14', 'VTXP_14', 'VTXM_14', 'VWAP_D', 'VWMA_10', 'WCP',
       'WILLR_14', 'WMA_10', 'ZL_EMA_10', 'ZS_30'],
      dtype='object', length=223)

The output gets 223 column names, except for 'open', 'high', 'low', 'close', and 'volume', a total of 218 technical indicator eigenvalues ​​are obtained (note that a single indicator may get multiple Eigenvalues, such as Bollinger Bands, MACD, etc.).

(2) candles: Add indicators related to candlestick chart patterns.

df2=df0.copy()
df2.ta.strategy('candles')
print(df2.columns)
print(f'指标特征个数:{len(df2.columns)-5}')

Using the candles strategy, the following indicators can be obtained:

  • CDL_DOJI_10_0.1 : This is an indicator for identifying Doji candlestick patterns. A Doji pattern is when the opening and closing prices are equal (or nearly equal) for a certain period of time. This indicator will flag such formations. The parameter 10_0.1 may be used to control the accuracy of recognition, but the specific details will vary with the version of the library.

  • CDL_INSIDE : This is an indicator for identifying Inside Bar candlestick patterns. The inside bar pattern means that within a certain period of time, both the highest price and the lowest price are lower than the highest price and the lowest price of the previous day. This usually indicates a period of indecision in the market.

  • open_Z_30_1, high_Z_30_1, low_Z_30_1, close_Z_30_1: These are the Z-Score (Z-score) metrics that measure how far a data point is from the mean in standard deviation. Z-Score can help identify outliers and determine the relative location of data points. Here, they are applied to the Open, High, Low and Close prices respectively. 30_1 probably refers to the window size and moving step used when calculating the Z-Score, but the specific details will vary by version of the library.

  • HA_open, HA_high, HA_low, HA_close : These are the four elements of the Heikin-Ashi candlestick. Heikin-Ashi candlesticks are a variation of candlestick charts that use averages to smooth price data, resulting in clearer, easier-to-understand trendlines. These four indicators represent the open, high, low and close prices of the Heikin-Ashi candlestick chart respectively.

(3) momentum: Add technical indicators related to momentum.

df3=df0.copy()
df3.ta.strategy('momentum')
print(df3.columns)
print(f'指标特征个数:{len(df3.columns)-5}')

Here is a detailed description of these indicators:

  • AO_5_34 : Awesome Oscillator, a technical analysis indicator based on market momentum, calculated as the short-term (usually 5 period) and long-term (usually 34 period) midpoint price (the average of the highest price and the lowest price) difference.

  • APO_12_26 : Absolute Price Oscillator, a price oscillator that measures momentum by calculating the difference between two moving averages with different periods.

  • BIAS_SMA_26: Bias, the deviation rate, measures how far the current price deviates from a certain moving average.

  • BOP : Balance of Power, equity balance indicator, measures the balance of buying and selling power, and helps investors understand the supply and demand relationship in the market.

  • AR_26 and BR_26 : popularity index and willingness index respectively, AR is the ratio of the total price from the opening to the high point of the number of rising days to the total price of the opening to the low point of the number of falling days, BR is the closing to the total price of the number of rising days within a period of time The ratio of the total price from the high to the total price from the close to the low for the number of down days.

  • CCI_14_0.015 : Commodity Channel Index, Commodity Channel Index, measures the degree of price deviation from its average price.

  • CFO_9 : Chande Forecast Oscillator, Chande Forecast Oscillator, used to predict the future trend of the market.

  • CG_10 : Center of Gravity, the center of gravity indicator, predicts the change point of the price trend.

  • CMO_14 : Chande Momentum Oscillator, Chande Momentum Oscillator, measures the momentum of the market.

  • COPC_11_14_10 : Coppock Curve, Coppock curve, mainly used to capture the reversal of the bottom.

  • CTI_12 : Comparative Volatility Index, comparative volatility index, used to compare the size of price changes.

  • ER_10 : Efficiency Ratio, the efficiency ratio, measures the efficiency of the market, that is, the speed of price changes.

  • BULLP_13 and BEARP_13 : Represents the percentage of long momentum and the percentage of short momentum respectively.

  • FISHERT_9_1 and FISHERTs_9_1: Fisher Transform, Fisher Transform, used to determine the height and width of the price distribution.

  • INERTIA_20_14 : Inertia, an inertial indicator used to measure the strength of price trends.

  • K_9_3, D_9_3, J_9_3 : respectively represent the K line, D line and J line of the Stochastic Oscillator.

  • KST_10_15_20_30_10_10_10_15 and KSTs_9: Know Sure Thing, used to identify turning points in price momentum.

  • MACD_12_26_9, MACDh_12_26_9, MACDs_12_26_9 : represent MACD line, MACD histogram and signal line respectively.

  • MOM_10 : Momentum, a momentum indicator, measures the price change relative to the price a certain period of time ago.

  • PGO_14 : Pretty Good Oscillator, used to measure price changes relative to the price some time ago.

  • PPO_12_26_9, PPOh_12_26_9, PPOs_12_26_9 : Percentage Price Oscillator, a percentage price oscillator that calculates the difference between the moving averages of two periods and expresses it as a percentage.

  • PSL_12 : Percentage of Stocks above a Level, the percentage of stocks above a certain level.

  • PVO_12_26_9, PVOh_12_26_9, PVOs_12_26_9 : Percentage Volume Oscillator, a percentage volume oscillator that measures changes in volume.

  • QQE_14_5_4.236, QQE_14_5_4.236_RSIMA, QQEl_14_5_4.236, QQEs_14_5_4.236 : QQE, quantification and facilitation indicators, used to judge the overbought and oversold status of the market.

  • ROC_10 : Rate of Change, the rate of change, measures the price change relative to the price a period of time ago.

  • RSI_14 : Relative Strength Index, Relative Strength Index, measures the overbought and oversold status of the market.

  • RSX_14 : Relative Strength Index Smoothed, a smoothed relative strength index used to measure the rate of change of prices.

  • RVGI_14_4 and RVGIs_14_4 : Relative Vigor Index, Relative Vigor Index, measures the vitality of prices by comparing the opening and closing prices of the trading day.

  • SLOPE_1 : Slope, the slope, measures the slope of the trend line and is used to determine the direction of the trend.

  • SMI_5_20_5, SMIs_5_20_5, SMIo_5_20_5: Stochastic Momentum Index, Stochastic Momentum Index, used to determine the momentum of the price.

  • SQZ_20_2.0_20_1.5, SQZ_ON, SQZ_OFF, SQZ_NO, SQZPRO_20_2.0_20_2_1.5_1, SQZPRO_ON_WIDE,SQZPRO_ON_NORMAL,SQZPRO_ON_NARROW, SQZPRO_OFF, SQZPRO_NO: Squeeze and Squeeze Pro, Squeeze and Squeeze Pro, Used to measure the strength of market volatility.

  • STC_10_12_26_0.5, STCmacd_10_12_26_0.5, STCstoch_10_12_26_0.5: Schaff Trend Cycle, Schaff trend cycle, is an improved MACD indicator.

  • STOCHk_14_3_3, STOCHd_14_3_3, STOCHRSIk_14_14_3_3, STOCHRSId_14_14_3_3: Stochastic Oscillator and Stochastic RSI, Stochastic Oscillator and Stochastic Relative Strength Index, used to determine the overbought and oversold status of the market.

  • TRIX_30_9 and TRIXs_30_9: TRIX, Triple Exponential Smoothed Average, used to determine the trend of prices.

  • TSI_13_25_13 and TSIs_13_25_13: True Strength Index, the real strength index, used to measure the momentum of the price.

  • UO_7_14_28: Ultimate Oscillator, the Ultimate Oscillator, is an oscillator integrated over multiple periods.

  • WILLR_14: Williams %R, Williams indicator, used to measure the overbought and oversold state of the market.

(4) overlap: add technical indicators that overlap with the price.

df4=df0.copy()
df4.ta.strategy('overlap')
print(df4.columns)
print(f'指标特征个数:{len(df4.columns)-5}')

Here is a detailed description of these indicators:

  • ALMA_10_6.0_0.85: Arnaud Legoux Moving Average, a moving average used to reduce noise and smooth price data.

  • DEMA_10: Double Exponential Moving Average, double exponential moving average, trying to eliminate the lag of single exponential moving average.

  • EMA_10: Exponential Moving Average, an exponential moving average, is more sensitive to recent data than a simple moving average.

  • FWMA_10: Fractal Weighted Moving Average, fractal weighted moving average, a moving average that gives more weight to recent data.

  • HILO_13_21, HILOl_13_21, HILOs_13_21: High-Low Channel, high-low channel indicators, including the high point, low point and span of the channel.

  • HL2, HLC3, OHLC4: represent the average of the highest and lowest prices, the average of the highest, lowest and closing prices, and the average of the opening, highest, lowest and closing prices, respectively.

  • HMA_10: Hull Moving Average, Hull moving average, trying to eliminate lag and improve sensitivity.

  • ISA_9, ISB_26, ITS_9, IKS_26, ICS_26: are part of Ichimoku Cloud respectively, including conversion line, baseline, leading span A, leading span B and delay span.

  • JMA_7_0: Jurik Moving Average, Jurik moving average, a method of smoothing and forecasting time series data.

  • KAMA_10_2_30: Kaufman's Adaptive Moving Average, Kaufman's adaptive moving average, automatically adjusts its smoothing coefficient according to market volatility.

  • LR_14: Linear Regression, linear regression, used to find price trends.

  • MCGD_10: McGinley Dynamic, McGinley Dynamic Line, is a moving average that automatically adjusts its speed to reflect market speed.

  • MIDPOINT_2 and MIDPRICE_2: the average of the highest price and the lowest price in the past period of time, and the middle price of the highest price and the lowest price in the past period of time, respectively.

  • PWMA_10: Pot Weighted Moving Average, displacement weighted moving average, is a weighted moving average.

  • RMA_10: Rolling Moving Average, rolling moving average, a common moving average.

  • SINWMA_14: Sine Weighted Moving Average, sine weighted moving average, a special weighted average method.

  • SMA_10: Simple Moving Average, simple moving average, the most common moving average.

  • SSF_10_2: Smoothed Simple Filter, a smoothing simple filter for smoothing price data.

  • SUPERT_7_3.0, SUPERTd_7_3.0, SUPERTl_7_3.0, SUPERTs_7_3.0: Super Trend, super trend indicators, used to track trends.

  • SWMA_10: Sine Weighted Moving Average, sine weighted moving average, a special weighted average method.

  • T3_10_0.7: Triple Exponential Moving Average, triple exponential moving average, try to reduce lag and increase smoothness.

  • TEMA_10: Triple Exponential Moving Average, triple exponential moving average, try to reduce lag and increase smoothness.

  • TRIMA_10: Triangular Moving Average, a triangular moving average, a weighted average that gives more weight to the data in the data set.

  • VIDYA_14: Variable Index Dynamic Average, variable index dynamic average, an adaptive moving average.

  • VWAP_D: Volume Weighted Average Price, volume weighted average price, is an average price calculated by price and volume.

  • VWMA_10: Volume Weighted Moving Average, volume weighted moving average, is a moving average that takes volume into account.

  • WCP: Weighted Close Price, weighted closing price, a price indicator that gives more weight to the closing price.

  • WMA_10: Weighted Moving Average, weighted moving average, a weighted moving average.

  • ZL_EMA_10: Zero Lag Exponential Moving Average, zero lag exponential moving average, trying to eliminate lag.

(5) performance: Add indicators related to asset performance.

df5=df0.copy()
df5.ta.strategy('performance')
print(df5.columns)
print(f'指标特征个数:{len(df5.columns)-5}')
  • LOGRET_1: This is the calculation of the log return. The logarithmic rate of return is a measure of investment returns and is mainly used for financial time series data because it has good statistical properties. The formula for calculating the logarithmic rate of return is: log(Pt / Pt-1), where Pt represents the price at time t, and Pt-1 represents the price at time t-1. Separate calculation: df5.ta.log_return()

  • PCTRET_1: This is the calculation of percentage return, also known as simple return. It is calculated as: (Pt / Pt-1) - 1, which is very similar to the formula for the log return, but without the log transformation. The percentage return visually represents the percentage change in price from t-1 to t. Separate calculation: df5.ta.percent_return(), equivalent to df5.close.pct_change()

The main difference between the two is that for small changes, the two have almost the same value, but for large changes, the logarithmic return will be smaller than the percentage return. In addition, the logarithmic rate of return is time-varying, making it more convenient when performing time series analysis.

(6) statistics: Add statistics related indicators.

df6=df0.copy()
df6.ta.strategy('statistics')
print(df6.columns)
print(f'指标特征个数:{len(df6.columns)-5}')
  • ENTP_10: This refers to the Shannon entropy of the closing price sequence within a 10-day time window, which is used to measure the complexity or uncertainty of the price sequence.

  • KURT_30: This is the kurtosis value of the 30-day closing price series, which is used to measure the "tail-heavy" degree of the closing price distribution.

  • MAD_30: This is the mean absolute deviation of the 30-day series of closing prices.

  • MEDIAN_30: This is the median of the 30-day closing price series.

  • QTL_30_0.5: This is the second quartile, or median, of the 30-day series of closing prices.

  • SKEW_30: This is the skewness of the 30-day closing price series, which measures the symmetry of the closing price distribution.

  • STDEV_30: This is the standard deviation of the 30-day closing price series, used to measure the dispersion of the closing price distribution.

  • TOS_STDEVALL_LR, TOS_STDEVALL_L_1, TOS_STDEVALL_U_1, TOS_STDEVALL_L_2, TOS_STDEVALL_U_2, TOS_STDEVALL_L_3, TOS_STDEVALL_U_3: These are values ​​obtained by a certain calculation method, but I did not find specific definitions and explanations.

  • VAR_30: This is the variance of the 30-day closing price series, which is used to measure the dispersion of the closing price distribution.

  • ZS_30: This may be the Z-Score of the 30-day closing price series, which is used to measure the position of each closing price relative to the average of the 30-day closing prices.

(7) trend: Add technical indicators related to price trends.

df7=df0.copy()
df7.ta.strategy('trend')
print(df7.columns)
print(f'指标特征个数:{len(df7.columns)-5}')
  • ADX_14: Average Directional Index, developed by Welles Wilder to measure the strength of market trends.

  • DMP_14, DMN_14: These two indicators are Directional Movement Plus and Directional Movement Minus, which are two key components used to calculate ADX.

  • AMATe_LR_8_21_2, AMATe_SR_8_21_2: These two are the long-term and short-term versions of the AMAT buy and sell trigger lines, which generate trade signals based on market momentum.

  • AROOND_14, AROONU_14: Aroon Up and Down Indicators, developed by Tushar Chande, are used to determine whether a market is in an up, down or sideways trend, and the strength of the trend.

  • AROONOSC_14: The Aroon Oscillator is the difference between the up and down of the AROON, which is used to measure the trend strength of the market.

  • CHOP_14_1_100: Shock indicator, used to measure whether the market is in a state of shock.

  • CKSPl_10_3_20, CKSPs_10_3_20: These two indicators are Cheking stochastic indicators, which calculate the momentum of the market based on past price movements.

  • LDECAY_5: A linear decay indicator that measures the number of days the price has fallen from its peak.

  • DEC_1: Decrease in price for one day.

  • DPO_20: Discrete Oscillator for finding cyclical price patterns.

  • INC_1: Price increment for one day.

  • PSARl_0.02_0.2, PSARs_0.02_0.2, PSARaf_0.02_0.2, PSARr_0.02_0.2: Parabolic Stop and Reverse indicators, used to determine the trend of the market.

  • QS_10: Quantitative analysis indicators.

  • TTM_TRND_6: TTM Trend, TTM trend indicator, used to determine the trend of the market.

  • VHF_28: Vertical Horizontal Filter to determine if the market is trending or oscillating.

  • VTXP_14, VTXM_14: Positive and negative versions of the trend transition indicator, used to detect trend changes in the market.

(8) Volatility: Add indicators related to price volatility.

df8=df0.copy()
df8.ta.strategy('volatility')
print(df8.columns)
print(f'指标特征个数:{len(df8.columns)-5}')
  • ABER_ZG_5_15, ABER_SG_5_15, ABER_XG_5_15, ABER_ATR_5_15: These are similar volatility measures to Bollinger Bands, but use a different centerline and bandwidth calculation method.

  • ACCBL_20, ACCBM_20, ACCBU_20: These are the lower, middle and upper bounds of the cumulative Bollinger Bands.

  • ATRr_14: This is the rate of change of the 14-day Average True Range.

  • BBL_5_2.0, BBM_5_2.0, BBU_5_2.0, BBB_5_2.0, BBP_5_2.0: These are the lower limit, middle line, upper limit, width and percentage of the 5-day Bollinger Bands.

  • DCL_20_20, DCM_20_20, DCU_20_20: These are the lower, middle and upper limits of the 20-day Donch Channel.

  • HWM, HWU, HWL: These are High Water Mark, High Water Mark Upper and High Water Mark Lower.

  • KCLe_20_2, KCBe_20_2, KCUe_20_2: These are the lower, middle and upper limits of the Kierland Channel on the 20th.

  • MASSI_9_25: This is the moving average slope index.

  • NATR_14: This is the 14-day Normalized Average True Range.

  • PDIST: This is price distance.

  • RVI_14: This is the 14-day Relative Volatility Index.

  • THERMO_20_2_0.5, THERMOma_20_2_0.5, THERMOl_20_2_0.5, THERMOs_20_2_0.5: These are the parameters of the thermogram indicators.

  • TRUERANGE_1: This is the 1-day true range.

  • UI_14: This is the 14th Uncertainty Index.

(9) volume: Add indicators related to transaction volume.

df9=df0.copy()
df9.ta.strategy('volume')
print(df9.columns)
print(f'指标特征个数:{len(df9.columns)-5}')
  • AD: The Accumulation/Distribution Line (Accumulation/Distribution Line) is an indicator that combines volume and price, and is used to measure the inflow or outflow of funds. It combines price and volume to show whether money is flowing in or out.

  • ADOSC_3_10: This is an accumulation/distribution line in the form of an oscillator, using two EMAs of different periods (3 and 10 in this case) for comparison.

  • OBV: On-Balance Volume is a traffic indicator calculated by accumulating trading volume.

  • OBV_min_2, OBV_max_2: This is to calculate the minimum and maximum values ​​of OBV in the past 2 periods.

  • OBVe_4, OBVe_12: This is the exponential moving average of the OBV indicator.

  • AOBV_LR_2, AOBV_SR_2: This is the long-term and short-term average shock value calculated based on OBV.

  • CMF_20: Chaikin Money Flow, is an oscillator developed by Marc Chaikin that represents the inflow or outflow of money for a specified period (in this example 20 days).

  • EFI_13: Elder's Force Index, is an oscillator developed by Alexander Elder that combines price and volume to measure market power.

  • EOM_14_100000000: Ease of Movement, easy to move indicator, is an indicator developed by Richard W. Arms Jr. that combines price and volume to show the ease of price movement.

  • KVO_34_55_13, KVOs_34_55_13: Klinger Volume Oscillator, is an oscillator developed by Stephen J. Klinger that measures long-term and short-term volume changes.

  • MFI_14: Money Flow Index, Money Flow Index, is an oscillator that combines price and trading volume.

  • NVI_1, PVI_1: Negative Volume Index and Positive Volume Index, negative trading volume index and positive trading volume index, measure the price change when the trading volume falls and rises.

  • PVOL: This is an indicator of price multiplied by transaction volume, representing the total transaction value of the market.

  • PVR: Price/Volume Ratio.

  • PVT: Price-Volume Trend, a momentum indicator that combines price and volume.

02

custom strategy

cd1ddbb3360d72e2f8005647d4f7518e.png

In addition to the above built-in strategies, pandas_ta also allows users to create custom strategies. This can be done by combining different technical indicators. The biggest advantage of using the strategy feature is that it provides an efficient way to add multiple technical indicators. This is especially useful for beginners as it allows them to quickly start analyzing without having to have a deep understanding of how each indicator works. In addition, policies provide an organizational method to help users identify the metrics they are interested in and create custom sets as needed.

Application example: Visual analysis of technical indicators. Use the pandas_ta custom strategy to obtain common technical indicators and visualize them.

#df.tail()

# 定义自定义策略
my_strategy = ta.Strategy(
    name="My Strategy",
    description="Combination of SMA, Bollinger Bands, MACD, RSI and OBV",
    ta=[
        {"kind": "sma", "length": 20}, # 20日简单移动平均线
        {"kind": "ema", "length": 50}, # 50日简单移动平均线
        {"kind": "bbands", "length": 20}, # 布林带
        {"kind": "macd", "fast": 12, "slow": 26, "signal": 9}, # MACD
        {"kind": "rsi"}, # RSI
        {"kind": "adx"},
        {"kind": "atr"},
        {"kind": "aroon"},
        {"kind": "obv"} # OBV
    ]
)

# 在df中应用自定义策略
df=df0.copy()
df.ta.strategy(my_strategy)
#可视化部分代码较长,此处省略,完整代码见知识星球。

3d88fd678d9df4fe890aee93729cb984.png

cc57bebae70ff47570d390d2d2edd27e.png

04

epilogue

After a detailed exploration and learning of the pandas_ta library, this article explains in detail how to use the library for technical analysis, from the calculation of basic technical indicators, to the construction of complex custom strategies, and then to the drawing of technical analysis charts, so that readers can clearly Understand and practice.

In technical analysis, pandas_ta is undoubtedly one of the powerful and easy-to-use tools in the Python community. It enables data scientists, quantitative researchers and traders to perform complex technical analysis in a more concise and intuitive way. Although there are many similarities with TA-Lib, pandas_ta shows greater advantages in many scenarios with its richer technical indicators and stronger customization capabilities.

Of course, no tool is perfect, and neither is pandas_ta. For some specific technical indicators, TA-Lib may be more comprehensive. In addition, although the API of pandas_ta is designed to be quite user-friendly, some additional learning and practice may be required when using certain functions. Technical analysis is not only a tool or method, but also a way of thinking that requires continuous learning and improvement. I hope this article can provide some help and inspiration for readers on their technical analysis journey!

References: https://github.com/twopirllc/pandas-ta

1dbbcf5a17f39953358cff66ab6dd070.png

About Python Financial Quantification

e70d1ebb5b7c5b0fcd1099fac968eed4.png

Focus on sharing the application of Python in the field of financial quantification. Joining Knowledge Planet, you can get free qstock source code, more than 30 g of quantitative investment video materials, quantitative finance-related PDF materials, official account articles Python complete source code, direct communication with bloggers, answering questions, etc. Add personal WeChat sky2blue2 to get a 15% discount.

68e72c035d25583beece18d41b9af4dd.jpeg

Guess you like

Origin blog.csdn.net/ndhtou222/article/details/132157873