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

Python Quantitative Finance Libraries

Python Quantitative Finance Libraries

This chapter introduces commonly used Python libraries in quantitative finance and demonstrates two backtesting frameworks in depth: zipline and Backtrader.


Overview of Common Quant Libraries

Grouped by purpose, the libraries commonly used in quant research are these:

library Purpose Install Command
zipline Event-driven backtesting framework, produced by Quantopian conda install -c conda-forge zipline
Backtrader A full-featured Python backtesting framework with an active community pip install backtrader
QuantLib Pricing of financial instruments and financial calculations (options, bonds, etc.) pip install QuantLib
TA-Lib Technical indicator library with over 150 built-in indicators pip install TA-Lib
pyfolio Portfolio performance analysis, integrable with backtesting frameworks to generate analysis reports pip install pyfolio
statsmodels Statistical modeling: linear regression, time-series analysis, etc. pip install statsmodels

This chapter focuses on the first two backtesting frameworks; the rest are introduced as needed in their respective topics.


zipline

zipline is an open-source framework for quantitative finance research and algorithmic trading, developed by Quantopian, providing researchers with a full toolchain to build, test and execute quant trading strategies.

Note: the Quantopian platform shut down in 2020, and the official zipline is stuck at 1.3.0 with poor compatibility with newer Python. For new projects, prefer the community-maintained zipline-reloaded, or use Backtrader introduced below. This section is kept to help when reading existing material.

Installation

zipline has many dependencies; it is recommended to use Anaconda for installation to avoid dependency conflicts:



conda install -c conda-forge zipline

Preparing the Data Bundle

zipline backtests need a data bundle in a specific format; the quandl data source is commonly used.

First log in to the quandl websiteregister and get an api key, then set the environment variable:



# Windows System

set QUANDL_API_KEY=你的key



# macOS / Linux system

export QUANDL_API_KEY=你的key

Download the data bundle:



zipline ingest -b quandl

Query the downloaded data bundles:



zipline bundles

The output is as follows:



csvdir 

quandl 2023-12-09 06:02:03.178299

quandl 2023-12-09 05:59:04.273082

quandl 2023-12-09 05:54:57.277732

quandl 2023-12-09 05:52:15.532504

quandl 2023-12-09 03:32:03.853032

quantopian-quandl 

Writing and Running a Strategy

A zipline strategy is a Python script centered on two functions: initialize (initialization) and handle_data (called every trading day):

Example

from

zipline.

api

import

order

,

record

,

symbol

def

initialize

(

context

)

:

   

Executed once at the start of the backtest for initialization

   

pass

def

handle_data

(

context

,

data

)

:

   

Executed once per trading day: buy 10 shares of Apple at the current price

    order

(

symbol

(

'AAPL'

)

,

10

)

   

Record the AAPL price of the day for later analysis

    record

(

AAPL

=

data.

current

(

symbol

(

'AAPL'

)

,

'price'

)

)

order(symbol('AAPL'), 10) means buying 10 shares of Apple stock at the current price on every trading day.

record(...) records the day's price so the price curve can be plotted after the backtest.

Run the backtest with the zipline run command:



zipline run -f my_strategy.py --start 2016-1-1 --end 2018-1-1 -o buyapple_out.pickle --no-benchmark

The output is as follows:



Simulated 503 trading days

 first open: 2016-01-04 14:30:00+00:00

 last close: 2017-12-29 21:00:00+00:00

Command Parameters Description
-f my_strategy.py Specify the strategy file
--start / --end Specify the backtest start and end dates
-o buyapple_out.pickle Specify the output file, where trade records and performance data are saved
--no-benchmark Do not set a performance benchmark

Reading the Backtest Results

The backtest result is a pickle file, read with the standard-library pickle module:

Example

import

pickle

Specify the pickle file path

pickle_file_path

=

'buyapple_out.pickle'

Open in binary read-only mode and deserialize

with

open

(

pickle_file_path

,

'rb'

)

as

file

:

    buyapple_out_data

=

pickle

.

load

(

file

)

Print the loaded data, including daily trade and performance details

print

(

buyapple_out_data

)

The output is a DataFrame indexed by day, containing fields such as daily P&L (pnl), position market value and leverage:



                                        period_open              period_close  short_value          pnl  long_exposure  ...  max_leverage  excess_return treasury_period_return trading_days  period_label

2016-01-04 21:00:00+00:00 2016-01-04 14:31:00+00:00 2016-01-04 21:00:00+00:00          0.0      0.00000            0.0  ...      0.000000            0.0                    0.0            1       2016-01


Backtrader

Backtrader is one of the most active Python backtesting frameworks today: pure Python, easy to install, well documented, and supporting multi-market backtesting for stocks, futures, cryptocurrencies and more.

Install as follows:



pip install backtrader

Core Concepts

Backtrader's architecture revolves around several core objects:

object Role
Cerebro The "brain" of the backtest engine, responsible for loading data and strategies and driving the whole backtest
Data Feed Data feed, supplying market data in formats such as pandas DataFrame to the engine
Strategy Strategy class; the engine calls its next() method bar by bar, and trading logic is written here
Indicator Indicators (e.g. SMA, CrossOver); once declared, the engine automatically computes and aligns them
Broker Simulated broker, managing capital, order matching and commissions
Analyzer Analyzers, automatically computing performance data such as return, drawdown and trade count

Example: Backtesting a Dual Moving Average Strategy

Redo the previous chapter's dual moving average strategy with Backtrader: buy when the 10-day MA crosses above the 30-day MA, sell when it crosses below:

Example

import

backtrader

as

bt

import

yfinance

as

yf

Strategy class: inherit from bt.Strategy

class

SmaCross

(

bt.

Strategy

)

:

   

Strategy parameters, adjustable externally via params to avoid hardcoding

    params

=

dict

(

fast

=

10

,

slow

=

30

)

   

def

init

(

self

)

:

       

Short-term and long-term simple moving averages

       

self

.

fast_ma

=

bt.

ind

.

SMA

(

period

=

self

.

p

.

fast

)

       

self

.

slow_ma

=

bt.

ind

.

SMA

(

period

=

self

.

p

.

slow

)

       

Crossover indicator: greater than 0 on a golden cross, less than 0 on a death cross

       

self

.

crossover

=

bt.

ind

.

CrossOver

(

self

.

fast_ma

,

self

.

slow_ma

)

   

def

next

(

self

)

:

       

No position and a golden cross appears -> buy 10 shares

       

if

not

self

.

position

and

self

.

crossover

0

:

           

self

.

buy

(

size

=

10

)

       

Holding a position and a death cross appears -> sell everything

       

elif

self

.

position

and

self

.

crossover

<

0

:

           

self

.

close

(

)

Fetch data with yfinance and convert it into a Backtrader data feed

data

=

yf.

download

(

"600519.SS"

,

start

=

"2021-01-01"

,

end

=

"2023-12-31"

,

                   auto_adjust

=

False

,

progress

=

False

,

multi_level_index

=

False

)

feed

=

bt.

feeds

.

PandasData

(

dataname

=

data

)

Assemble the backtest engine

cerebro

=

bt.

Cerebro

(

)

cerebro.

adddata

(

feed

)

                           

Add data

cerebro.

addstrategy

(

SmaCross

)

                   

Add the strategy

cerebro.

broker

.

setcash

(

100000.0

)

               

Initial capital of 100,000 yuan

cerebro.

broker

.

setcommission

(

commission

=

0.0003

)

 

Commission of 0.03%

print

(

"Initial Market Value: %.2f"

% cerebro.

broker

.

getvalue

(

)

)

cerebro.

run

(

)

                                   

Run the backtest

print

(

"Final Market Value: %.2f"

% cerebro.

broker

.

getvalue

(

)

)

The output is shown below:



初始市值: 100000.00

最终市值: 100434.33

The strategy made a small profit of 434 yuan over three years. Compared with the hand-written vectorized backtest in the previous chapter, Backtrader handled details like matching timing, commissions and capital usage for us; that is exactly the value of a framework.

Note: this example buys 10 shares per order; at Moutai's price of about 1,800 yuan that ties up about 18,000 yuan, so 100,000 yuan of initial capital is enough. If changed to buying 100 shares at once (about 180,000 yuan), the order would be rejected outright by the engine for insufficient funds. Also, the minimum A-share trading unit is 1 lot (100 shares); this example does not round to lots, for simplicity.

Backtrader also ships with rich built-in analyzers; a single line of code outputs a full performance report:

Example

Add analyzers before cerebro.run()

cerebro.

addanalyzer

(

bt.

analyzers

.

SharpeRatio

,

timeframe

=

bt.

TimeFrame

.

Days

)

 

Sharpe Ratio

cerebro.

addanalyzer

(

bt.

analyzers

.

DrawDown

)

                                 

Drawdown analysis

cerebro.

addanalyzer

(

bt.

analyzers

.

TradeAnalyzer

)

                           

Trade statistics

After running, extract the analyzer output from the result

result

=

cerebro.

run

(

)

print

(

"Sharpe Ratio:"

,

result

[

0

]

.

analyzers

.

sharperatio

.

get_analysis

(

)

[

"sharperatio"

]

)

print

(

"Maximum Drawdown: %.2f%%"

% result

[

0

]

.

analyzers

.

drawdown

.

get_analysis

(

)

.

max

.

drawdown

)

You can also plot interactive backtest charts (a popup showing the equity curve and trade points)

cerebro.plot()

The output is as follows (this example has a very light position of only 10 shares, so drawdown and Sharpe values are for demonstration only):



夏普比率: -0.01632125043146268

最大回撤: 3.78%


How to Choose a Backtesting Framework

Framework Advantage Suitable scenarios
Hand-written pandas backtest Fully transparent, the best way to understand the principles Learning stage, quickly validating simple ideas
Backtrader Easy to install, complete docs, active community The main backtesting framework for individual researchers
zipline Highly engineered, in the same lineage as the Quantopian research system For reading existing material; new projects should use zipline-reloaded
VectorBT Vectorized computing, extremely fast batch parameter optimization Large-scale parameter scans and strategy screening

Advice: start with hand-written backtests, then switch to Backtrader for daily research once you understand the principles. However mature the framework, it cannot replace your vigilance against traps like look-ahead bias and overfitting.

A reminder again: all content in this tutorial is for technical learning only and does not constitute any investment advice.