Quantitative Trading Toolkit (Tongdaxin, Tonghuashun, WenHua MyLanguage, etc.)

Official Introduction

MyTT is the Swiss Army knife for your quantitative toolbox—refined and efficient. It seamlessly ports indicator formulas from Tongdaxin, Ths (Tonghuashun), and Whaley language into Python with minimal effort. The core library consists of a single file, only about 100 lines of code, implementing all common indicators such as MACD, RSI, BOLL, ATR, KDJ, CCI, PSY, etc., fully encapsulated using NumPy and Pandas functions. It’s concise, high-performance, and extremely convenient for applications in stock market technical analysis, automated trading systems, cryptocurrency (e.g., BTC) quantification, and more. A mini Python library packed with most essential stock market indicators.

license

Features

  • Lightweight Core Library: The entire project is contained in one file: MyTT.py. No installation or configuration required. You can freely customize it and use it instantly via from MyTT import *.

  • Human-Friendly Code: No fancy programming tricks—easy to understand even for beginners. Users can easily add new indicators and immediately apply them in their projects.

  • No Need to Install TA-Lib: Pure Python implementation avoids the notorious difficulties many users face when installing the TA-Lib library.

  • Fully Compatible Syntax: Directly compatible with Tongdaxin and Tonghuashun indicator syntax. New indicators typically require no modifications and can be used directly.

  • Ultra-High Performance: Avoids loops entirely; leverages built-in NumPy and Pandas functions for fast computation across all indicators.

  • Sequence Input → Sequence Output: Like the Talib library, accepts multi-day input data and outputs full sequences of indicator values—ideal for plotting and trend analysis.

  • High Accuracy: Indicator results match those from Tongdaxin, Tonghuashun, Xueqiu, and other platforms up to two decimal places.

  • Advanced Version Available: MyTT_plus includes advanced and experimental functions for complex use cases.

  • Supports Legacy Python 2: For older environments using Python 2 with legacy Pandas versions, use MyTT_python2.

Let’s Start With a Simple Example

# Demonstration: Fetching Cryptocurrency Market Data and Computing Indicators
from hb_hq_api import *         # Cryptocurrency market data library
from MyTT import *              # MyTT library for trading indicators

# Fetch 120 days of BTC/USDT data
df = get_price('btc.usdt', count=120, frequency='1d')  # '1d' means daily, '4h' means 4-hour

# ----------- df result looks like the table below (similar for stocks) -------------------------------------------
open close high low vol
2021-05-16 48983.62 47738.24 49800.00 46500.0 1.333333e+09
2021-05-17 47738.24 43342.50 48098.66 42118.0 3.353662e+09
2021-05-18 43342.50 44093.24 45781.52 42106.0 1.793267e+09
# ------- Now that we have data, let’s get started -------------
CLOSE = df.close.values; OPEN = df.open.values           # Define base data — any sequence input works  
HIGH = df.high.values; LOW = df.low.values             # e.g., CLOSE=list(df.close) would work the same

MA5 = MA(CLOSE, 5)                                     # Get 5-day moving average sequence
MA10 = MA(CLOSE, 10)                                   # Get 10-day moving average sequence

print('BTC 5-day MA:', MA5[-1])                        # Print latest value only
print('BTC 10-day MA:', RET(MA10))                     # RET(MA10) == MA10[-1]
print('Did 5-day MA cross above 10-day MA today?', RET(CROSS(MA5, MA10)))
print('Have last 5 closing prices all been above 10-day MA?', EVERY(CLOSE > MA10, 5))

Installation Methods

  • Direct Copy: Simply copy MyTT.py into your project directory and import with from MyTT import * to access all functions.

  • Standard Package Installation: Use pip: pip install MyTT

from MyTT import *                 # Import MyTT library (note capitalization)
S = np.random.randint(1, 99, [10])  # Generate a sequence of 10 random integers between 1 and 99
EMA(S, 6)                          # Compute 6-period EMA on sequence S

Tutorials and Application Examples

Some Utility Functions in the MyTT Library

  • Value N Days Ago: REF
REF(CLOSE, 1)              # Closing price sequence shifted back by one day
  • Simple Moving Average: MA
MA(CLOSE, 5)               # 5-day simple moving average of closing prices
  • Exponential Moving Average: EMA
EMA(CLOSE, 5)              # For accuracy, EMA requires at least ~120 periods
  • Chinese-style SMA: SMA
SMA(CLOSE, 5)              # For accuracy, SMA also requires at least ~120 periods
  • Standard Deviation over N Days: STD
STD(CLOSE, 5)              # Standard deviation of closing prices over 5 days
  • Average Absolute Deviation: AVEDEV
AVEDEV(CLOSE, 5)           # Average of absolute differences between each value and the mean
  • Golden Cross Detection: CROSS
CROSS(MA(CLOSE, 5), MA(CLOSE, 10))   # Detect if 5-day MA crosses above 10-day MA
  • Element-wise Max/Min of Two Sequences: MAX, MIN
MAX(OPEN, CLOSE)           # Higher of open or close — top of candle body
  • Count Days Meeting Condition Over N Days: COUNT
COUNT(CLOSE > OPEN, 10)    # Number of bullish days (close > open) in the last 10 days
  • Check If All N Days Meet Condition: EVERY
EVERY(CLOSE > OPEN, 5)     # True if all of the last 5 days were bullish
  • Check Condition From Day A to Day B Ago: LAST
LAST(CLOSE > OPEN, 5, 3)   # Were all days from 5 days ago to 3 days ago bullish?
  • Check If Condition Was Met At Least Once in N Days: EXIST
EXIST(CLOSE > OPEN, 5)     # Was there at least one bullish day in the last 5 days?
  • Bars Since Last Condition Met: BARSLAST
BARSLAST(CLOSE / REF(CLOSE) >= 1.1)  # Days since last time price increased by 10% or more (limit-up)
  • Linear Regression Slope of Sequence: SLOPE
SLOPE(MA(CLOSE,10), 5)     # Slope of 10-day MA over the last 5 days (i.e., direction of trend)
  • Predicted Value via Linear Regression: FORCAST
FORCAST(CLOSE, 20)         # Forecast tomorrow's closing price based on past 20 days
  • Highest Value Over N Days: HHV
HHV(MAX(OPEN, CLOSE), 20)  # Highest candle body top over the last 20 days
  • Lowest Value Over N Days: LLV
LLV(MIN(OPEN, CLOSE), 60)  # Lowest candle body bottom over the last 60 days
  • Conditional IF Statement: IF
IF(OPEN > CLOSE, OPEN, CLOSE)  # Returns OPEN if open > close, else returns CLOSE

Implementation of Specific Indicators Using MyTT Utility Functions (More Can Be Added Manually)

def MACD(CLOSE, SHORT=12, LONG=26, M=9):    # For precision matching Xueqiu to 2 decimal places, use at least 120 days of CLOSE
    DIF = EMA(CLOSE, SHORT) - EMA(CLOSE, LONG)
    DEA = EMA(DIF, M)
    MACD = (DIF - DEA) * 2
    return RD(DIF), RD(DEA), RD(MACD)
def KDJ(CLOSE, HIGH, LOW, N=9, M1=3, M2=3):
    RSV = (CLOSE - LLV(LOW, N)) / (HHV(HIGH, N) - LLV(LOW, N)) * 100
    K = EMA(RSV, (M1*2-1))
    D = EMA(K, (M2*2-1))
    J = K*3 - D*2
    return K, D, J
def RSI(CLOSE, N=24):                     # RSI indicator
    DIF = CLOSE - REF(CLOSE, 1)
    return RD(SMA(MAX(DIF, 0), N) / SMA(ABS(DIF), N) * 100)
def WR(CLOSE, HIGH, LOW, N=10, N1=6):    # Williams %R Indicator
    WR = (HHV(HIGH, N) - CLOSE) / (HHV(HIGH, N) - LLV(LOW, N)) * 100
    WR1 = (HHV(HIGH, N1) - CLOSE) / (HHV(HIGH, N1) - LLV(LOW, N1)) * 100
    return RD(WR), RD(WR1)
def BIAS(CLOSE, L1=6, L2=12, L3=24):      # BIAS Deviation Rate
    BIAS1 = (CLOSE - MA(CLOSE, L1)) / MA(CLOSE, L1) * 100
    BIAS2 = (CLOSE - MA(CLOSE, L2)) / MA(CLOSE, L2) * 100
    BIAS3 = (CLOSE - MA(CLOSE, L3)) / MA(CLOSE, L3) * 100
    return RD(BIAS1), RD(BIAS2), RD(BIAS3)
def BOLL(CLOSE, N=20, P=2):                # Bollinger Bands
    MID = MA(CLOSE, N)
    UPPER = MID + STD(CLOSE, N) * P
    LOWER = MID - STD(CLOSE, N) * P
    return RD(UPPER), RD(MID), RD(LOWER)
def PSY(CLOSE, N=12, M=6):                 # Psychological Line (PSY)
    PSY = COUNT(CLOSE > REF(CLOSE, 1), N) / N * 100
    PSYMA = MA(PSY, M)
    return RD(PSY), RD(PSYMA)
def CCI(CLOSE, HIGH, LOW, N=14):            # Commodity Channel Index (CCI)
    TP = (HIGH + LOW + CLOSE) / 3
    return (TP - MA(TP, N)) / (0.015 * AVEDEV(TP, N))
def ATR(CLOSE, HIGH, LOW, N=20):           # Average True Range
    TR = MAX(MAX((HIGH - LOW), ABS(REF(CLOSE, 1) - HIGH)), ABS(REF(CLOSE, 1) - LOW))
    return MA(TR, N)
def BBI(CLOSE, M1=3, M2=6, M3=12, M4=20):   # Bull and Bear Index (BBI)
    return (MA(CLOSE, M1) + MA(CLOSE, M2) + MA(CLOSE, M3) + MA(CLOSE, M4)) / 4
def TAQ(HIGH, LOW, N):                      # Donchian Channel (Turtle Trading), simple yet powerful across market cycles
    UP = HHV(HIGH, N)
    DOWN = LLV(LOW, N)
    MID = (UP + DOWN) / 2
    return UP, MID, DOWN
def KTN(CLOSE, HIGH, LOW, N=20, M=10):     # Keltner Channel, N=20 days, ATR=10 days
    MID = EMA((HIGH + LOW + CLOSE) / 3, N)
    ATRN = ATR(CLOSE, HIGH, LOW, M)
    UPPER = MID + 2 * ATRN
    LOWER = MID - 2 * ATRN
    return UPPER, MID, LOWER
def TRIX(CLOSE, M1=12, M2=20):              # Triple Exponential Moving Average
    TR = EMA(EMA(EMA(CLOSE, M1), M1), M1)
    TRIX = (TR - REF(TR, 1)) / REF(TR, 1) * 100
    TRMA = MA(TRIX, M2)
    return TRIX, TRMA
def BRAR(OPEN, CLOSE, HIGH, LOW, M1=26):    # BRAR - Market Sentiment Indicator
    AR = SUM(HIGH - OPEN, M1) / SUM(OPEN - LOW, M1) * 100
    BR = SUM(MAX(0, HIGH - REF(CLOSE, 1)), M1) / SUM(MAX(0, REF(CLOSE, 1) - LOW), M1) * 100
    return AR, BR
def MTM(CLOSE, N=12, M=6):                  # Momentum Indicator
    MTM = CLOSE - REF(CLOSE, N)
    MTMMA = MA(MTM, M)
    return MTM, MTMMA
def ROC(CLOSE, N=12, M=6):                  # Rate of Change Indicator
    ROC = 100 * (CLOSE - REF(CLOSE, N)) / REF(CLOSE, N)
    MAROC = MA(ROC, M)
    return ROC, MAROC
def EXPMA(CLOSE, N1=12, N2=50):             # Exponential Moving Average Indicator
    return EMA(CLOSE, N1), EMA(CLOSE, N2)
def OBV(CLOSE, VOL):                        # On-Balance Volume Indicator
    return SUM(IF(CLOSE > REF(CLOSE,1), VOL, IF(CLOSE < REF(CLOSE,1), -VOL, 0)), 0) / 10000
def MFI(CLOSE, HIGH, LOW, VOL, N=14):            # MFI indicator is the RSI indicator based on volume
    TYP = (HIGH + LOW + CLOSE) / 3
    V1 = SUM(IF(TYP > REF(TYP, 1), TYP * VOL, 0), N) / SUM(IF(TYP < REF(TYP, 1), TYP * VOL, 0), N)  
    return 100 - (100 / (1 + V1))
  • For more indicators, see the library file MyTT.py

Due to syntax differences: =: is invalid in Python — use = instead. Logical AND is &, logical OR is |

# ThinkScript function: VAR1:=(C>REF(C,1) AND C>REF(C,2));
# Python equivalent:
VAR1 = ((CLOSE > REF(CLOSE, 1)) & (CLOSE > REF(CLOSE, 2)))

# Price above 10-day MA and 10-day MA above 20-day MA
Python version: (CLOSE > MA(CLOSE, 10)) & (MA(CLOSE, 10) > MA(CLOSE, 20))

# Bullish candle OR close higher than previous close
Python version: (CLOSE > OPEN) | (CLOSE > REF(CLOSE, 1))

BOLL Band Indicator - Data Extraction and Plotting Example (Shanghai Composite Index)

up, mid, lower = BOLL(CLOSE)                                        # Get Bollinger Band data

plt.figure(figsize=(15,8))  
plt.plot(CLOSE, label='SSE Index')    ; plt.plot(up, label='Upper Band')        # Plotting
plt.plot(mid, label='Middle Band');   plt.plot(lower, label='Lower Band')
Boll Band

Donchian Channel Indicator Calculation and Visualization (CSI 300 Index)

up, mid, down = TAQ(HIGH, LOW, 20)                                    # Get Donchian Channel data — simple yet powerful across market cycles
plt.figure(figsize=(15,8))  
plt.plot(CLOSE, label='CSI 300 Index')                                  
plt.plot(up, label='Donchian - Upper'); plt.plot(mid, label='Donchian - Middle'); plt.plot(down, label='Donchian - Lower')
taq

Required Third-party Libraries (No need for ta-lib; all indicators only require pandas)

  • pandas

Code Contributors

Flame, jqz1226, stanene, bcq

Other Open Source Projects by the Team - If this project helps you, please click ★Star in the top right corner to support us!



Star History

Star History Chart