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

Python Quantitative Financial Market Fundamentals

Python Quantitative Financial Market Fundamentals

Beyond code, quant traders must understand the market's own rules: what assets can be traded, when trading is allowed, why prices gap, and what each trade costs.

These rules directly determine how a strategy is written; a backtest that ignores T+1 and price limits produces untrustworthy conclusions.


Major Asset Classes

The objects of quant trading are various financial assets; the common ones are these:

Asset What It Is Risk Level
Stocks Certificates of company ownership; returns come from price differences and dividends Medium-high
Bonds Debt instruments that repay principal and interest at maturity; prices move inversely with interest rates Low
Mutual Funds / ETFs Collective investment in a basket of assets; ETFs can be traded on-exchange like stocks Depends on the underlying assets
Futures Standardized contracts to buy or sell at a set price at a future date, with built-in leverage and two-way trading High
Options Buying "the right to buy or sell at an agreed price in the future"; the buyer's maximum loss is the premium High (the seller's risk is extreme)
Forex The exchange of currencies between countries; the world's largest trading market Medium-high
Cryptocurrencies Traded 24/7, with no price limits and extreme volatility Extremely high

This tutorial's examples focus on stocks, which are also the most suitable instrument for individuals starting in quant.


A-Share Trading Rules

Before writing a strategy, memorize a few hard rules of A-shares:

Rule Content Impact on Strategies
Trading Hours Weekdays 9:30-11:30 and 13:00-15:00 Daily strategies are based on the "trading day" unit
T+1 Stocks bought today can only be sold the next day You cannot buy and sell on the same day; intraday round-trips are restricted
Price Limits Main Board +/-10%, ChiNext/STAR Market +/-20%, ST stocks +/-5% You cannot buy at the limit-up or sell at the limit-down; a backtest must simulate this
Minimum Unit Buys must be integer multiples of 100 shares (1 lot); sells may be fewer than 100 shares Position sizing must be rounded to lots
Minimum Price Tick 0.01 yuan Limit order prices can only fall on the 0.01 grid

Among these, price limits affect backtesting the most: on a limit-down day a stock "cannot be sold", so actual execution may diverge from the signal; rigorous backtesting frameworks handle this specifically.

Comparison of Major Global Market Rules

Rule A-shares Hong Kong stocks US stocks Cryptocurrencies
Settlement System T+1 T+2 trading, intraday round-trips allowed T+1 settlement, intraday round-trips allowed Real-time
Price Limit ±10% / ±20% None (with a market-circuit mechanism) None (with a circuit-breaker mechanism) None
Minimum Unit 100 shares 1 lot (varies by stock) 1 share (fractional shares supported) Any quantity
Short Selling Securities lending (restricted) Can be sold short Can be sold short Contracts can be shorted
Trading Hours 4.5 hours/day 5.5 hours/day 6.5 hours/day 7×24

Tip: market differences mean strategies cannot be copied directly. An intraday strategy validated on US stocks hits the T+1 restriction on A-shares; A-share price limits simply do not exist in crypto markets. When porting strategies across markets, check the rules table first.


Price Adjustment: A Prerequisite Before Backtesting

Chapter 6 mentioned adjustment when introducing data acquisition; here it is explained thoroughly.

After a listed company pays dividends or bonus shares, the stock price shows an artificial "gap down" on the ex-dividend date: for example, with a 25-yuan dividend per share, the opening price on the ex-date is directly about 25 yuan below the previous close.

This gap is not a market decline; if you compute returns directly from unadjusted prices, every dividend would be mistaken for a crash.

Adjustment is the process of removing this artificial gap; two common conventions are used:

Convention Approach Purpose
Forward adjustment Using the current price as the base, adjusting historical prices backward For charting and computing returns; the most commonly used
Backward adjustment Using the first listing day as the base, adjusting forward Computing long-term true total return
No adjustment Raw prices Viewing historical actual transaction prices

Hands-On Verification: Moutai's Dividend Gap

Kweichow Moutai went ex-dividend on June 30, 2023, paying about 25.9 yuan per share. Compare the unadjusted and adjusted prices around the ex-date:

Example

import

yfinance

as

yf

auto_adjust=False returns both the unadjusted Close and the adjusted Adj Close

df

=

yf.

download

(

"600519.SS"

,

start

=

"2023-06-01"

,

end

=

"2023-07-15"

,

                 auto_adjust

=

False

,

progress

=

False

,

multi_level_index

=

False

)

print

(

df

[

[

"Close"

,

"Adj Close"

]

]

.

round

(

2

)

.

to_string

(

)

)

View the dividend record

print

(

yf.

Ticker

(

"600519.SS"

)

.

dividends

.

loc

[

"2023"

]

.

to_string

(

)

)

The output is as follows (excerpt around the ex-dividend date):



             Close  Adj Close

Date

2023-06-27  1711.05    1513.83

2023-06-28  1728.38    1529.16

2023-06-29  1713.71    1516.19

2023-06-30  1691.00    1519.06

2023-07-03  1724.10    1548.80

2023-07-04  1730.60    1554.63



2023-06-30    25.911

The unadjusted Close fell from 1713.71 to 1691.00 on June 30, seemingly down 1.3%; but the adjusted Adj Close actually rose from 1516.19 to 1519.06, meaning holders on the ex-date really made money, with the dividend already pocketed.

Plotting the two price curves from 2019 to 2024 together makes the many "fake drops" on ex-dividend dates clearly visible:

Example

import

yfinance

as

yf

import

matplotlib.

pyplot

as

plt

df

=

yf.

download

(

"600519.SS"

,

start

=

"2019-01-01"

,

end

=

"2024-12-31"

,

                 auto_adjust

=

False

,

progress

=

False

,

multi_level_index

=

False

)

plt.

figure

(

figsize

=

(

12

,

6

)

)

plt.

plot

(

df.

index

,

df

[

"Close"

]

,

label

=

"Close (Unadjusted)"

,

         color

=

"#1f2933"

,

linewidth

=

1.2

)

plt.

plot

(

df.

index

,

df

[

"Adj Close"

]

,

label

=

"Adj Close (Adjusted)"

,

         color

=

"#14805e"

,

linewidth

=

1.2

)

plt.

title

(

"Maotai (600519.SS): Close vs Adj Close 2019-2024"

)

plt.

xlabel

(

"Date"

)

plt.

ylabel

(

"Price (CNY)"

)

plt.

legend

(

)

plt.

grid

(

alpha

=

0.25

)

plt.

show

(

)

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

Moutai Unadjusted and Adjusted Price Comparison

The gaps in both curves appear on the dividend ex-dates around June each year. The unadjusted curve "falls more" the further you go, purely an illusion from accumulated dividends.

Conclusion: always use adjusted prices for returns, moving averages and backtesting; look at unadjusted prices only to see "how much money actually traded at in history". yfinance controls this with the auto_adjust parameter, AKShare with adjust="qfq" (forward) / "hfq" (backward); seeFetching Financial Data.


Trading Costs: The Invisible Opponent of a Strategy

No trade in a backtest is free; the main costs of A-share trading are as follows:

Cost Rate Charged On
Commission Commonly 0.025% to 0.03%, with most brokers imposing a 5-yuan minimum Both buy and sell sides
Stamp duty 0.05% Sell side only
Transfer fee 0.001% Both buy and sell sides
Slippage No fixed value; depends on liquidity Implicit cost

About 0.06% to 0.1% combined for both sides, plus 0.05% stamp duty on the sell side.

Another view: one full buy-sell cycle loses about 0.13% to 0.16%. A strategy with 100x annual turnover loses 13% to 16% of returns to costs alone.

Note: the above rates are subject to the latest announcements from brokers and exchanges. Slippage is the deviation between the actual fill price and the signal price; in illiquid stocks or fast-moving markets it can far exceed commissions.When backtesting,be sure to set rates consistent with reality.