Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Quantitative Technical Indicators

Python Quantitative Technical Indicators

Technical indicators are mathematical transforms of price and volume series, compressing raw market data into a few comparable numbers.

This chapter is not content with "calling a library to get numbers": the four most common indicators, MACD, RSI, Bollinger Bands and ATR, are all derived by hand, and finally pandas-ta is used to verify the hand-written results.


Classification of Technical Indicators

The hundreds of technical indicators boil down to four categories:

Category Question Answered Representative Indicators
Trend-following Which direction the price is moving MA, MACD, DMI
Momentum The strength of moves and overbought/oversold conditions RSI, KDJ, ROC
Volatility How violently the price fluctuates ATR, Bollinger Bands, historical volatility
Volume The heat of capital participation OBV, volume moving average

The four indicators in this chapter happen to cover the first three categories. Before starting, standardize the data: use Moutai's 2023-2024 adjusted closing prices (for the importance of adjustment, seeFundamentals of Financial Markets).

Example

import

yfinance

as

yf

Use adjusted closing prices consistently

close

=

yf.

download

(

"600519.SS"

,

start

=

"2023-01-01"

,

end

=

"2024-12-31"

,

                    progress

=

False

,

multi_level_index

=

False

)

[

"Close"

]


MACD: A Dialogue Between Fast and Slow Trends

MACD (Moving Average Convergence Divergence) consists of three lines, computed using only the exponential moving average ewm:

Component Compute Meaning
DIF (fast line) EMA(12) - EMA(26) The deviation of the short-term trend from the long-term trend
DEA (slow line) EMA(9) of DIF The smoothing of DIF itself
MACD histogram 2 × (DIF - DEA) The divergence between the fast and slow lines (domestic software conventionally multiplies by 2)

Example

Fast line DIF: the difference between the 12-day EMA and the 26-day EMA

ema12

=

close.

ewm

(

span

=

12

,

adjust

=

False

)

.

mean

(

)

ema26

=

close.

ewm

(

span

=

26

,

adjust

=

False

)

.

mean

(

)

dif

=

ema12 - ema26

Slow line DEA: the 9-day EMA of DIF

dea

=

dif.

ewm

(

span

=

9

,

adjust

=

False

)

.

mean

(

)

MACD histogram: domestic charting software conventionally multiplies by 2

hist

=

2

(

dif - dea

)

macd

=

pd.

DataFrame

(

{

"DIF"

: dif

,

"DEA"

: dea

,

"MACD"

: hist

}

)

print

(

macd.

tail

(

3

)

.

round

(

2

)

.

to_string

(

)

)

Count the golden crosses and death crosses over two years

cross_up

=

(

(

dif

dea

)

&

(

dif.

shift

(

1

)

<=

dea

)

)

.

sum

(

)

cross_dn

=

(

(

dif

<

dea

)

&

(

dif.

shift

(

1

)

=

dea

)

)

.

sum

(

)

print

(

f

"Golden crosses in two years: {cross_up}, death crosses: {cross_dn}"

)

The output is shown below:



             DIF  DEA  MACD

Date

2024-12-26  4.68  2.71  3.95

2024-12-27  4.65  3.09  3.10

2024-12-30  4.27  3.33  1.88

两年内金叉 29 次,死叉 28 次

ewm is key: the span parameter corresponds to the moving average's "period", and adjust=False keeps it consistent with charting software.

Plot price and MACD as two stacked subplots:

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

fig

,

(

ax1

,

ax2

)

=

plt.

subplots

(

2

,

1

,

figsize

=

(

12

,

8

)

,

sharex

=

True

,

                               gridspec_kw

=

{

"height_ratios"

:

[

2

,

1

]

}

)

ax1.

plot

(

close.

index

,

close.

values

,

color

=

"#1f2933"

,

         linewidth

=

1.2

,

label

=

"Close"

)

ax1.

set_title

(

"Maotai (600519.SS) Close and MACD (12, 26, 9)"

)

ax1.

set_ylabel

(

"Price (CNY)"

)

ax1.

legend

(

)

ax1.

grid

(

alpha

=

0.25

)

MACD histogram: green for positive values, red for negative

bar_colors

=

np.

where

(

hist

=

0

,

"#14805e"

,

"#c0563f"

)

ax2.

bar

(

hist.

index

,

hist.

values

,

color

=

bar_colors

,

width

=

1.0

)

ax2.

plot

(

dif.

index

,

dif.

values

,

color

=

"#1f2933"

,

linewidth

=

1.0

,

label

=

"DIF"

)

ax2.

plot

(

dea.

index

,

dea.

values

,

color

=

"#e0a458"

,

linewidth

=

1.0

,

label

=

"DEA"

)

ax2.

axhline

(

0

,

color

=

"#8a95a1"

,

linewidth

=

0.8

)

ax2.

set_ylabel

(

"MACD"

)

ax2.

legend

(

)

ax2.

grid

(

alpha

=

0.25

)

fig.

tight_layout

(

)

plt.

show

(

)

Run the code above and the output chart is as follows:

MACD Indicator Chart

Note the 29 golden crosses in two years: DIF/DEA crossovers are far more frequent than moving-average golden crosses. Using them directly as trading signals creates a lot of noise; live trading usually adds a trend filter.


RSI: A Thermometer for Overbought and Oversold

RSI (Relative Strength Index) measures the share of upward force over a period, ranging from 0 to 100:

Example

Daily up/down moves

delta

=

close.

diff

(

)

gain

=

delta.

clip

(

lower

=

0

)

   

Upward magnitude, recorded as 0 on down days

loss

=

-delta.

clip

(

upper

=

0

)

   

Downward magnitude, recorded as 0 on up days

Wilder smoothing (equivalent to an EMA with alpha=1/14), the standard RSI algorithm

avg_gain

=

gain.

ewm

(

alpha

=

1

/

14

,

adjust

=

False

)

.

mean

(

)

avg_loss

=

loss.

ewm

(

alpha

=

1

/

14

,

adjust

=

False

)

.

mean

(

)

rs

=

avg_gain / avg_loss

rsi

=

100

100

/

(

1

)

print

(

"Latest 3-day RSI:"

)

print

(

rsi.

tail

(

3

)

.

round

(

2

)

.

to_string

(

)

)

The output is shown below:



最新 3 日 RSI:

Date

2024-12-26    52.32

2024-12-27    52.63

2024-12-30    51.40

RSI above 70 is conventionally called overbought and below 30 oversold; Moutai's latest RSI is around 51, in the neutral zone.

Note: RSI has two smoothing methods, Wilder smoothing and a simple average, so different software may give different values. This chapter uses Wilder smoothing, consistent with mainstream charting software.


Bollinger Bands: A Channel Drawn by Volatility

Bollinger Bands consist of a middle band (20-day moving average) and upper/lower bands (middle +/- 2 standard deviations); the channel width expands and contracts automatically with volatility:

Example

Middle band: 20-day simple moving average

mid

=

close.

rolling

(

20

)

.

mean

(

)

Standard deviation measures volatility

std

=

close.

rolling

(

20

)

.

std

(

)

upper

=

mid +

2

Upper band

lower

=

mid -

2

Lower band

boll

=

pd.

DataFrame

(

{

"Upper"

: upper

,

"Mid"

: mid

,

"Lower"

: lower

}

)

print

(

boll.

tail

(

3

)

.

round

(

2

)

.

to_string

(

)

)

The output is shown below:



              Upper      Mid    Lower

Date

2024-12-26  1461.87  1427.79  1393.71

2024-12-27  1463.02  1429.05  1395.08

2024-12-30  1463.56  1430.15  1396.75

Example

fig

,

ax

=

plt.

subplots

(

figsize

=

(

12

,

6

)

)

ax.

plot

(

close.

index

,

close.

values

,

color

=

"#1f2933"

,

        linewidth

=

1.2

,

label

=

"Close"

)

ax.

plot

(

mid.

index

,

mid.

values

,

color

=

"#e0a458"

,

        linewidth

=

1.2

,

label

=

"Middle Band (MA20)"

)

ax.

plot

(

upper.

index

,

upper.

values

,

color

=

"#14805e"

,

        linewidth

=

1.0

,

linestyle

=

"--"

,

label

=

"Upper Band"

)

ax.

plot

(

lower.

index

,

lower.

values

,

color

=

"#c0563f"

,

        linewidth

=

1.0

,

linestyle

=

"--"

,

label

=

"Lower Band"

)

ax.

fill_between

(

lower.

index

,

lower.

values

,

upper.

values

,

                color

=

"#14805e"

,

alpha

=

0.06

)

ax.

set_title

(

"Maotai: Bollinger Bands (20, 2)"

)

ax.

set_xlabel

(

"Date"

)

ax.

set_ylabel

(

"Price (CNY)"

)

ax.

legend

(

)

ax.

grid

(

alpha

=

0.25

)

plt.

show

(

)

Run the code above and the output chart is as follows:

Bollinger Band Channel Chart

Price touching the lower band means a large short-term deviation from the mean, which is exactly the entry basis of theMean Reversion Strategydiscussed later.


ATR: How Much the Price Moves in Yuan

ATR (Average True Range) turns "how big today's move was" into a concrete number in yuan, a classic basis for setting stop-loss distances.

It is based on the True Range (TR), the maximum of the following three:

TR Candidate Compute Scenario Covered
Today's range High - Low A normal trading day
Gap up |High - Previous Close| Opening with a gap up
Gap down |Low - Previous Close| Opening with a gap down

Example

ATR needs high, low and close prices; be sure to use unadjusted data consistently

ohlc

=

yf.

download

(

"600519.SS"

,

start

=

"2023-01-01"

,

end

=

"2024-12-31"

,

                   auto_adjust

=

False

,

progress

=

False

,

                   multi_level_index

=

False

)

high

,

low

,

close_u

=

ohlc

[

"High"

]

,

ohlc

[

"Low"

]

,

ohlc

[

"Close"

]

TR: take the maximum of the three candidates

tr

=

pd.

concat

(

[

    high - low

,

   

(

high - close_u.

shift

(

)

)

.

abs

(

)

,

   

(

low - close_u.

shift

(

)

)

.

abs

(

)

,

]

,

axis

=

1

)

.

max

(

axis

=

1

)

Wilder smoothing gives ATR

atr

=

tr.

ewm

(

alpha

=

1

/

14

,

adjust

=

False

)

.

mean

(

)

print

(

"Latest 3-day TR/ATR:"

)

print

(

pd.

DataFrame

(

{

"TR"

: tr

,

"ATR14"

: atr

}

)

.

tail

(

3

)

.

round

(

2

)

.

to_string

(

)

)

The output is shown below:



最新 3 日 TR/ATR:

               TR  ATR14

Date

2024-12-26  15.78  28.23

2024-12-27  16.50  27.40

2024-12-30  18.96  26.79

Moutai's ATR is about 27 yuan, meaning an average true daily move of around 27 yuan. How far should the stop be? Many trend strategies use a rule like "2x ATR" so the stop distance matches the instrument's actual volatility.

Common pitfall: ATR must be computed from high/low/close prices on the same basis. Mixing adjusted closes with unadjusted highs produces wildly wrong TR values.


Verifying Hand-Written Results with pandas-ta

Writing it yourself is for understanding; for daily use you can rely on existing libraries. pandas-ta provides vectorized implementations of over a hundred indicators:



# Note: pandas-ta 0.4.x requires Python 3.10 or higher

# If Python version is insufficient, use uv for one-click switching (see the virtual environment article): uv venv --python 3.12

pip install pandas-ta

Recompute the same indicators with pandas-ta and compare with the hand-written results (note that pandas-ta requires lowercase column names):

Example

import

pandas_ta

as

ta

macd_ta

=

ta.

macd

(

close

)

                   

Returns three columns: DIF/DEA/histogram

rsi_ta

=

ta.

rsi

(

close

,

length

=

14

)

bb_ta

=

ta.

bbands

(

close

,

length

=

20

,

std

=

2

)

 

Returns five columns including the upper, middle and lower bands

print

(

"MACD DIF manual/pandas_ta:"

,

round

(

dif.

iloc

[

1

]

,

4

)

,

     

"/"

,

round

(

macd_ta

[

"MACD_12_26_9"

]

.

iloc

[

1

]

,

4

)

)

print

(

"MACD DEA manual/pandas_ta:"

,

round

(

dea.

iloc

[

1

]

,

4

)

,

     

"/"

,

round

(

macd_ta

[

"MACDs_12_26_9"

]

.

iloc

[

1

]

,

4

)

)

print

(

"RSI14 manual/pandas_ta:"

,

round

(

rsi.

iloc

[

1

]

,

4

)

,

     

"/"

,

round

(

rsi_ta.

iloc

[

1

]

,

4

)

)

print

(

"Bollinger upper band manual/pandas_ta:"

,

round

(

upper.

iloc

[

1

]

,

4

)

,

     

"/"

,

round

(

bb_ta

[

"BBU_20_2.0_2.0"

]

.

iloc

[

1

]

,

4

)

)

print

(

"Bollinger lower band manual/pandas_ta:"

,

round

(

lower.

iloc

[

1

]

,

4

)

,

     

"/"

,

round

(

bb_ta

[

"BBL_20_2.0_2.0"

]

.

iloc

[

1

]

,

4

)

)

The output is shown below:



MACD  DIF 手写/pandas_ta: 4.2672 / 4.2672

MACD  DEA 手写/pandas_ta: 3.3281 / 3.3281

RSI14 手写/pandas_ta: 51.4014 / 51.4014

布林上轨 手写/pandas_ta: 1463.5587 / 1463.5587

布林下轨 手写/pandas_ta: 1396.7471 / 1396.7471

All five sets of values match exactly; the hand-written implementation holds up to verification.

Another veteran option, TA-Lib, is more powerful (including pattern recognition) but depends on a C library and is troublesome to install; pandas-ta is pure Python and more worry-free for personal research.

Lesson learned: during verification, feeding adjusted prices to ATR and unadjusted prices to MACD once made the indicators disagree. Input basis for indicator calculation must be consistent; this pitfall is far more common than the algorithm itself.