【Application】Is TQuant Lab Measuring Stock a Buy? Backtest performance of measuring stocks

TEJ 台灣經濟新報
TEJ-API Financial Data Analysis
6 min readApr 17, 2024

--

Measuring stock
Photo by Nick Chong on Unsplash

Highlight

  • Article Difficulty: ★☆☆☆☆
  • Should measuring stocks be bought? Explore the relationship between measuring shares and weighted compensation.
  • You can use the TQuant Lab backtesting platform to write, buy, sell, and dispose of stocks and backtest risk and performance.

Introduction

What are measuring stocks? The stock index deals with stocks with abnormal trading conditions. What is abnormal trading status? The stock exchange has a classification mechanism. Before a stock is included in the “Measuring Stocks” list, it will be listed as “Attention Stocks” for a period of time. The “Attention Stocks” selection criteria are actually precursors to abnormal trading conditions. “Attention stocks” are defined as stocks that may be classified as attention stocks if their cumulative rise or fall in six days exceeds 25%. This kind of abnormal trading situation is usually based on several conditions, such as the range of increase and decrease, turnover rate, and whether the trading volume is reported to be significant. The competent authorities have formulated this cooling mechanism for warning handling to reduce investor risks and avoid overheating.

The stock 00940, which has recently gained significant attention, has also been noticed by the competent authorities. Despite not being listed on the market yet, it has managed to raise over 170 billion. If it does get listed, given its current popularity, it could be classified as a note stock or even a measuring stock by the authorities. This raises the question of whether measuring stocks are a terrible investment target. To answer this, we will conduct a simple buy and hold backtest on the performance of measuring stocks.

Measuring stock data selection

  • We will search for all stocks listed as measuring stocks by the Financial Supervisory Commission from 2020/01/01 to 2023/12/31 as investment targets.

Editing Environment and Module Requirements

This article uses Windows and Jupyter Notebook as the editor.

Data Importation

import os
import pandas as pd
import TejToolAPI
from zipline.data import bundles
from logbook import Logger, StderrHandler, ERROR
from zipline.sources.TEJ_Api_Data import get_universe

os.environ['TEJAPI_KEY'] = "your key"
os.environ['TEJAPI_BASE'] = "https://api.tej.com.tw"

start = '2020-01-01'
end = '2023-12-31'
pool = get_universe(start, end, mkt = ['TWSE', 'OTC'], stktp_c = '普通股')

os.environ['mdate'] = start + ' ' + end
os.environ['ticker'] = ' '.join(pool) + ' ' + 'IR0001'

!zipline ingest -b tquant

The data period is from 2020–01–01 to 2023–12–31, and the weighted return index IR0001 is added as a market comparison.

Establishing the initialize Function

The initialize() function is used to define the daily trading environment before the start of trading. In this example, we set:

  • Slippage cost
  • Commission fees
  • Returns index (IR0001) as the benchmark index
from zipline.api import *
from zipline.finance import commission, slippage

bundle_data = bundles.load('tquant')
universe = bundle_data.asset_finder.retrieve_all(bundle_data.asset_finder.equities_sids)
tickers = [col.symbol for col in universe]

def initialize(context):
set_slippage(slippage.VolumeShareSlippage(volume_limit = 0.025, price_impact = 0.1))
set_commission(commission.Custom_TW_Commission(min_trade_cost = 20, discount = 1.0, tax = 0.003))
set_benchmark(symbol('IR0001'))
context.asset = [symbol(i) for i in tickers]
context.rules = ['處置股票(Disposition Securities)'] #Looking for targets for measuring stocks
context.has_ordered = []

Creating the before_trading_start Function

before_trading_start() is similar to handle_data(). It is called daily after the start of backtesting and is mainly responsible for setting trading strategies, placing orders, and recording trading information.

def before_trading_start(context, data):

for ticker in context.asset:
annotation = data.current(ticker, 'annotation')

#If it is a measuring stock, place an order and add new stocks to the account
if isinstance(annotation, str) and any(s in annotation for s in context.rules) and not ticker in context.has_ordered:
order(ticker, 1000)
context.has_ordered.append(ticker)

#If it is already on your account, you will not buy it.
elif ticker in context.has_ordered:
order(ticker, 0)

#If the stocks have been removed and measured, the stocks in the account will be cleared.
else:
if ticker in set(context.portfolio.positions.keys()): # The stock target of the position held before the current day
order_target(ticker, 0)
context.has_ordered.remove(ticker)

Executing the Trading Strategy

Run_algorithm() is used to execute the momentum factor strategy as configured. The trading period is set from start_dt (2020-01-01) to end_dt (2023-12-31), using the dataset tquant, with initial capital of ten million dollars. The output results represent daily performance and trading details.

from zipline import run_algorithm
from zipline.utils.calendar_utils import get_calendar

start_date = pd.Timestamp(start, tz = 'utc')
end_date = pd.Timestamp(end, tz = 'utc')
capital_base = 1e7
calendar_name = 'TEJ'

results = run_algorithm(
start = start_date,
end = end_date,
initialize=initialize,
bundle='tquant',
capital_base=capital_base,
data_frequency='daily',
before_trading_start = before_trading_start,
trading_calendar=get_calendar(calendar_name)
)
results
Measuring stock
Trading Details

So, is TQuant Lab Measuring Stock a Buy? Performance Evaluation Using Pyfolio

import pyfolio as pf
from pyfolio.utils import extract_rets_pos_txn_from_zipline

returns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(results)
benchmark_rets = results.benchmark_return

# Creating a Full Tear Sheet
pf.create_full_tear_sheet(returns, positions = positions, transactions = transactions,
benchmark_rets = benchmark_rets,
round_trips=False)
Measuring stock
Backtesting Performance Compared to Benchmark

As seen from the chart above, we have obtained an annualized return of approximately 19.71% during these 46 months through buying and selling measuring stocks, and the cumulative return is approximately 100%. The performance is barely in line with the market. However, buying and selling measuring stocks is a riskier investment strategy than the broader market. Because the characteristic of measuring stocks is that the buying and selling time is longer, investors cannot conduct transactions promptly, resulting in a lower willingness to hold. Therefore, when a stock falls into a period of decline, the decline will be significantly more significant than the broader market, resulting in sluggish strategy performance. The competent authorities will list a stock as a measuring stock because the turnover and increase rates are too abnormal compared with past performance. Therefore, before buying an overheated stock, you must first anticipate whether the stock will be listed as a note or measuring stock by the regulatory authorities to avoid exposure to more significant risks than other stocks.

Measuring stock
Monthly Return Variation Chart

As seen from the chart above, the monthly return of the investment strategy of buying and selling measuring stocks is poor and has a very high rate of negative returns. Investors will be under considerable pressure when adopting this investment strategy.

Conclusion

In this implementation, we selected measuring stocks as investment targets and used TQuant Lab to conduct a backtest performance analysis of buying, selling, and holding targets. Judging from the study’s results, measuring stocks’ annual return and cumulative return rates are barely the same as those of the broader market, but the risks investors bear are pretty high. When two groups of investment strategies have the same profit, investors should choose the investment target with lower risk as the investment target to avoid the problem of mismatch between risk and return.

The author believes that blindly following overheated stocks will be extremely risky. Buffett once said: “Others are fearful, and I am greedy.” This means that when others enter the market with a hot head, you follow; when others are bullish, you also Follow the stop loss, but the real winner is not to look at the current situation but to look carefully from a distance. Therefore, investors should think from a long-term perspective and avoid unthinkingly following market fluctuations. Evaluating and considering multiple perspectives when purchasing a stock is essential to ensure you are making an informed investment decision.

Therefore, readers interested in various trading backtesting scenarios are welcome to purchase relevant solutions from TQuant Lab to construct their trading strategies using high-quality databases.

This is a gentle reminder that this strategy is for reference only and does not represent advice on commodities or investments.

GitHub Source Code

Extended Reading

About

--

--

TEJ 台灣經濟新報
TEJ-API Financial Data Analysis

TEJ 為台灣本土第一大財經資訊公司,成立於 1990 年,提供金融市場基本分析所需資訊,以及信用風險、法遵科技、資產評價、量化分析及 ESG 等解決方案及顧問服務。鑒於財務金融領域日趨多元與複雜,TEJ 結合實務與學術界的精英人才,致力於開發機器學習、人工智慧 AI 及自然語言處理 NLP 等新技術,持續提供創新服務