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

Python Quantitative Trading

Python Quantitative Trading

Python quantitative trading refers to using the Python programming language and related libraries and tools to analyze financial market data, develop strategies, and execute trades.

Python has become one of the preferred programming languages for quantitative trading thanks to its concise, easy-to-learn syntax, powerful ecosystem, and rich set of financial libraries.

Quantitative trading is widely used in finance; it lets traders formulate and execute strategies systematically, improving trading efficiency and making decisions more scientific.

Quantification mainly uses mathematical and statistical methods and computer technology to perform quantitative analysis of financial markets, so as to formulate and execute trading strategies.

For more Python quantitative trading content, see:Python Quantitative Trading。


Examples

Next let's look at a simple Python quantitative application example: a moving average strategy implemented with Yahoo Finance data.

The basic idea of this strategy is to generate buy and sell signals by comparing short-term and long-term moving averages.

Before working through this simple example, you need to install three packages:

pip install pandas yfinance matplotlib

Package descriptions:

Get historical stock data

Use yfinance to fetch historical stock data; here is a simple example:

Example

import

yfinance

as

yf

Fetch the stock data

symbol

=

"600519.SS"

start_date

=

"2022-01-01"

end_date

=

"2023-01-01"

data

=

yf.

download

(

symbol

,

start

=

start_date

,

end

=

end_date

)

print

(

data.

head

(

)

)

The output is shown below:


                  Open         High          Low        Close    Adj Close   Volume
Date                                                                               
2022-01-04  2055.00000  2068.949951  2014.000000  2051.229980  1973.508057  3384262
2022-01-05  2045.00000  2065.000000  2018.000000  2024.000000  1947.309937  2839551
2022-01-06  2022.01001  2036.000000  1938.510010  1982.219971  1907.112915  5179475
2022-01-07  1975.00000  1988.880005  1939.319946  1942.000000  1868.416870  2981669
2022-01-10  1928.01001  1977.000000  1917.550049  1966.000000  1891.507446  2962670

Simple data analysis and visualization

Use pandas for data analysis and matplotlib for visualization:

Example

import

yfinance

as

yf

import

pandas

as

pd

import

matplotlib.

pyplot

as

plt

Fetch the stock data

symbol

=

"600519.SS"

start_date

=

"2022-01-01"

end_date

=

"2023-01-01"

data

=

yf.

download

(

symbol

,

start

=

start_date

,

end

=

end_date

)

Simple data analysis

print

(

data.

describe

(

)

)

Plot the stock price trend

data

[

'Close'

]

.

plot

(

figsize

=

(

10

,

6

)

,

label

=

symbol

)

plt.

title

(

f

"{symbol} Stock Price"

)

plt.

xlabel

(

"Date"

)

plt.

ylabel

(

"Price"

)

plt.

legend

(

)

plt.

show

(

)

The trend chart is shown below:

Backtesting a moving average crossover strategy

Backtesting is the process of simulating and evaluating a trading strategy on historical market data.

Here is a simple example of backtesting a moving average crossover strategy: buy when the 50-day moving average crosses above the 200-day moving average, and sell when it crosses below. The strategy's output includes metrics such as total return, annualized return and maximum drawdown.

Example

import

yfinance

as

yf

import

pandas

as

pd

import

matplotlib.

pyplot

as

plt

Fetch the stock data

symbol

=

"600519.SS"

start_date

=

"2021-01-01"

end_date

=

"2023-01-01"

data

=

yf.

download

(

symbol

,

start

=

start_date

,

end

=

end_date

)

Compute the moving averages

data

[

'SMA_50'

]

=

data

[

'Close'

]

.

rolling

(

window

=

50

)

.

mean

(

)

data

[

'SMA_200'

]

=

data

[

'Close'

]

.

rolling

(

window

=

200

)

.

mean

(

)

Initialize the crossover signal column

data

[

'Signal'

]

=

0

Compute the crossover signals

data.

loc

[

data

[

'SMA_50'

]

data

[

'SMA_200'

]

,

'Signal'

]

=

1

data.

loc

[

data

[

'SMA_50'

]

<

data

[

'SMA_200'

]

,

'Signal'

]

=

1

Compute the daily returns

data

[

'Daily_Return'

]

=

data

[

'Close'

]

.

pct_change

(

)

Compute the returns of the strategy signals (shift(1) avoids look-ahead bias)

data

[

'Strategy_Return'

]

=

data

[

'Signal'

]

.

shift

(

1

)

[

'Daily_Return'

]

Compute the cumulative return

data

[

'Cumulative_Return'

]

=

(

1

[

'Strategy_Return'

]

)

.

cumprod

(

)

Print the strategy performance

strategy_performance

=

{

   

'Total Return'

: data

[

'Cumulative_Return'

]

.

iloc

[

1

]

1

,

   

'Annualized Return'

:

(

data

[

'Cumulative_Return'

]

.

iloc

[

1

]

**

(

252

/

len

(

data

)

)

)

1

,

   

'Max Drawdown'

:

(

data

[

'Cumulative_Return'

]

/ data

[

'Cumulative_Return'

]

.

cummax

(

)

1

)

.

min

(

)

,

}

print

(

"Strategy performance:"

)

for

key

,

value

in

strategy_performance.

items

(

)

:

   

print

(

f

"{key}: {value:.4f}"

)

Plot the cumulative return curve

plt.

figure

(

figsize

=

(

10

,

6

)

)

plt.

plot

(

data

[

'Cumulative_Return'

]

,

label

=

'Strategy Cumulative Return'

,

color

=

'b'

)

plt.

plot

(

data

[

'Close'

]

/ data

[

'Close'

]

.

iloc

[

0

]

,

label

=

'Stock Cumulative Return'

,

color

=

'g'

)

plt.

title

(

"Cumulative Return of Strategy vs. Stock"

)

plt.

xlabel

(

"Date"

)

plt.

ylabel

(

"Cumulative Return"

)

plt.

legend

(

)

plt.

show

(

)

The chart is shown below:

Note that this is only a simple example; real applications require more sophisticated strategies and many more considerations.