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

Python Quantitative Introductory Example

Python Quantitative Introductory Example

In this chapter we directly run through the first complete quantitative strategy with about 20 lines of Python code.

You'll experience the full quantitative trading workflow: acquire data, compute signals, visualize buy/sell points; first build an overall understanding, with principles and details filled in by later chapters.


What is the dual moving average strategy?

The dual moving average strategy (Moving Average Crossover) is the most classic introductory quantitative strategy; its idea is just one sentence:

Buy when the short-term moving average crosses above the long-term one (golden cross), sell when it crosses below (death cross).

A moving average is the average of the past N days' closing prices; it filters out daily noise and reveals the trend.

The short-term moving average reacts faster than the long-term one; when it crosses the long-term one from below upward, it means recent prices are strengthening and the trend may reverse upward - this is the "golden cross" buy signal; the opposite is the "death cross" sell signal.

Price Time Golden cross - buy Death cross - sell LEGEND Short-term moving average (MA50) Long-term moving average (MA200) Buy point (golden cross) Sell point (death cross)

The short-term moving average is more sensitive to price, so it always crosses above and below the long-term one; each crossing corresponds to a potential rebalancing opportunity.

Tip: the dual moving average is a trend-following strategy; it performs well in clearly trending markets, but frequently gives false signals in choppy, range-bound markets. No strategy makes money in every market condition - this is the first thing to understand when learning quant.


Preparation

This example needs 4 libraries; install them first (for environment setup see the earlier Python Virtual Environment Setup The difference between Anaconda Environment Setup two articles, either one is fine):



pip install pandas numpy matplotlib yfinance

library Purpose
yfinance Fetch historical financial data for stocks, indices, etc. from Yahoo Finance
pandas Data processing and analysis; this example uses it to compute moving averages and signals
numpy Fundamental numerical computing library, the underlying dependency of pandas
matplotlib Plot trend charts and buy/sell signal charts

Step 1: acquire stock data

We take Kweichow Moutai (A-share code 600519, code 600519.SS on Yahoo Finance) as an example, fetching daily data from May 2022 to December 2023:

Example

import

yfinance

as

yf

Stock code: 600519 is Kweichow Moutai, the .SS suffix denotes the Shanghai Stock Exchange

symbol

=

"600519.SS"

Download daily data for the specified time range

multi_level_index=False makes the returned table use single-level column names, easier for beginners

data

=

yf.

download

(

symbol

,

start

=

"2022-05-01"

,

end

=

"2023-12-01"

,

                   progress

=

False

,

multi_level_index

=

False

)

View the first 5 rows: includes open, high, low, close, volume

print

(

data.

head

(

)

)

The output is shown below:



                 Close         High          Low         Open    Volume

Date

2022-05-05  1587.689087  1616.210448  1580.757515  1581.639101  3366094

2022-05-06  1549.660645  1572.132020  1539.289240  1568.666234  2859618

2022-05-09  1514.224854  1538.424794  1502.124883  1538.424794  3035182

2022-05-10  1526.489136  1542.711757  1473.612320  1486.567923  4011919

2022-05-11  1528.053467  1545.753979  1514.224929  1516.817780  3031267

What's returned is a date-indexed table (Pandas DataFrame), each row is a trading day - this is the rawest "material" of quant.

Note: the code by default uses adjusted prices to compute moving averages, avoiding price-gap distortion from dividends and ex-rights. More details on data acquisition (parameters, adjustment, A-share code rules) will beFetching Financial Datacovered in detail in one chapter.


Step 2: compute moving averages and generate signals

Use pandas' rolling().mean() to compute rolling moving averages, then use conditional logic to generate buy/sell signals:

Example

import

numpy

as

np

Compute short-term (50-day) and long-term (200-day) moving averages

data

[

"MA50"

]

=

data

[

"Close"

]

.

rolling

(

window

=

50

)

.

mean

(

)

data

[

"MA200"

]

=

data

[

"Close"

]

.

rolling

(

window

=

200

)

.

mean

(

)

Generate position signals: record 1 (holding) when the short-term MA is above the long-term MA, otherwise -1 (out of market)

data

[

"Signal"

]

=

np.

where

(

data

[

"MA50"

]

data

[

"MA200"

]

,

1

,

1

)

diff() computes the difference between adjacent signal rows: +2 means a golden cross just occurred, -2 means a death cross just occurred

data

[

"Position"

]

=

data

[

"Signal"

]

.

diff

(

)

Print the dates of all golden crosses (buys) and death crosses (sells)

print

(

"Golden cross (buy):"

,

[

str

(

d.

date

(

)

)

for

d

in

data

[

data

[

"Position"

]

==

2

]

.

index

]

)

print

(

"Death cross (sell):"

,

[

str

(

d.

date

(

)

)

for

d

in

data

[

data

[

"Position"

]

==

2

]

.

index

]

)

The output is shown below:



金叉(买入): ['2023-02-27', '2023-07-25']

死叉(卖出): ['2023-05-29']

The strategy issued a buy signal at the end of February 2023, sold at the end of May, and bought again at the end of July.

In just a few lines of code, a strategy's "brain" is complete. Turning a trading idea into computable signals is exactly the most core step of quant.

Note: moving-average calculation needs enough historical data; the 200-day MA requires at least 200 rows before it produces values, so the earlier rows will be NaN (empty), which is normal.


Step 3: visualize buy/sell points

Plot the closing price, two moving averages, and buy/sell signals on one chart to visually inspect the strategy's behavior:

Example

import

matplotlib.

pyplot

as

plt

plt.

figure

(

figsize

=

(

12

,

6

)

)

Plot closing price and the two moving averages

plt.

plot

(

data

[

"Close"

]

,

label

=

"Close Price"

,

linewidth

=

1

)

plt.

plot

(

data

[

"MA50"

]

,

label

=

"MA50"

,

linewidth

=

1.2

)

plt.

plot

(

data

[

"MA200"

]

,

label

=

"MA200"

,

linewidth

=

1.2

)

Mark buy points: on the golden-cross day, a green upward triangle

buy_points

=

data

[

data

[

"Position"

]

==

2

]

plt.

scatter

(

buy_points.

index

,

buy_points

[

"MA50"

]

,

            marker

=

"^"

,

color

=

"g"

,

s

=

120

,

label

=

"Buy Signal"

,

zorder

=

3

)

Mark sell points: on the death-cross day, a red downward triangle

sell_points

=

data

[

data

[

"Position"

]

==

2

]

plt.

scatter

(

sell_points.

index

,

sell_points

[

"MA50"

]

,

            marker

=

"v"

,

color

=

"r"

,

s

=

120

,

label

=

"Sell Signal"

,

zorder

=

3

)

plt.

title

(

"Maotai (600519.SS) Dual Moving Average Strategy"

)

plt.

xlabel

(

"Date"

)

plt.

ylabel

(

"Price (CNY)"

)

plt.

legend

(

)

plt.

show

(

)

Run the code above and the output chart is below; green triangles are buy signals, red triangles are sell signals, click the image to enlarge:

You can see buy points all appear after the short-term MA crosses above the long-term one, and sell points after it crosses below; the strategy's behavior fully matches our defined rules.


Does this strategy actually make money?

Plotting buy/sell points is only the first step; whether the strategy makes money needs a rigorous answer.

This question needs to be answered withWhen backtesting,to address: put these rules on historical data to simulate trading, compute performance metrics like annualized return, max drawdown, Sharpe ratio, and only then can you scientifically evaluate the strategy.

Reminder: never trade with real money just because the strategy looks accurate on a chart. For a strategy that hasn't been backtested, hasn't accounted for transaction costs, and hasn't been out-of-sample validated, live-trading losses are highly likely.


More common quantitative strategies

The dual moving average is just the entry-level model of the quant world. The table below lists common quantitative strategy types to help you build a strategy map; most of these ideas will be practiced in later chapters:

Strategy type Core idea Typical method
Trend following Once a price trend forms it tends to persist for a while Dual moving average, Turtle trading rules, breakout strategy
Mean reversion Prices revert to the mean after deviating too far Bollinger Bands, pairs trading, statistical arbitrage
Momentum strategy Assets that performed strongly in the past continue to strengthen for a while Rank by recent gains, buy the strong portfolio
Market neutral Go long and short simultaneously, stripping out the overall market's up/down influence A portfolio that goes long strong stocks and shorts weak ones
Event-driven After specific events, prices have predictable reactions Trade by monitoring events like earnings reports and index rebalancing
Machine learning strategy Learn patterns from large amounts of data to predict future trends Regression, classification, or deep learning models
High-frequency trading Exploit tiny price differences in very short time windows, trading quickly and in large volume Market-making strategies, cross-exchange arbitrage

Strategy forms can vary endlessly, but the evaluation criteria are unified: they must pass thorough backtesting and risk-management checks.