Python Quantitative Finance Libraries

Learn some commonly used Python libraries in the field of quantitative finance, such as:

  • zipline: A library for backtesting and implementing trading algorithms, installation command:pip install zipline。

  • Quantlib: A library for pricing financial instruments and performing financial calculations, installation command:pip install Quantlib。

  • TA-Lib: A library for technical analysis, installation command:pip install TA-Lib。

  • pyfolio: Is a library for evaluating portfolio performance, it can integrate with backtesting tools such as zipline, providing tools for analyzing portfolio returns, risk, etc., installation command:pip install pyfolio。

  • statsmodels: Is a library for estimating statistical models, including linear regression, time series analysis, etc. In quantitative finance, it can be used to build and test trading strategies, installation command:pip install statsmodels。


zipline

Zipline is an open-source framework for quantitative finance research and algorithmic trading.

It was developed by Quantopian, aiming to provide researchers and developers with a convenient tool for building, testing, and executing quantitative trading strategies.

Before using Zipline, please make sure you have installed the library. You can install it using the following command:

conda install -c conda-forge zipline

Here we useAnacondato install Zipline, to avoid weird problems later.

Next, we log in toquandlthe official website, register, and get the API key:https://data.nasdaq.com/account/profile。

Then set the API key and download the data package. The specific commands are as follows:

set QUANDL_API_KEY=your_key

For macOS systems, use the following command:

export QUANDL_API_KEY=your_key-zZQN

Download data package:

zipline ingest -b quandl

Query data package:

# zipline bundles
csvdir <no ingestions>
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 <no ingestions>

Now, let's use Zipline for a simple test.

The following is a simple Zipline strategy script for backtesting stock trading:

Example

from zipline.api import order, record, symbol


def initialize(context):
    pass


def handle_data(context, data):
    order(symbol('AAPL'), 10)
    record(AAPL=data.current(symbol('AAPL'), 'price'))

The above is a simple strategy that buys 10 shares of Apple stock at the current price on each trading day, and records the current AAPL price for each trading day.

  • order(symbol('AAPL'), 10): This line means buying 10 shares of Apple Inc. (AAPL) stock at the current price on each trading day.symbol('AAPL')Used to obtain the stock symbol for AAPL.

  • record(AAPL=data.current(symbol('AAPL'), 'price')): This line records the current price of AAPL on each trading day.data.current(symbol('AAPL'), 'price')Used to get the current stock price of AAPL.

Then execute the following command:

# zipline run -f my_strategy.py --start 2016-1-1 --end 2018-1-1 -o buyapple_out.pickle --no-benchmark
Simulated 503 trading days
 first open: 2016-01-04 14:30:00+00:00
 last close: 2017-12-29 21:00:00+00:00

After successful execution, it will generatebuyapple_out.picklefile, we can usepicklemodule to read it.

Command description:

  • zipline run:Start Zipline to run the backtest.

  • -f my_strategy.py:Specify the strategy file. In this example,my_strategy.pyis the Python file containing the strategy you wrote.

  • --start 2016-1-1and--end 2018-1-1:Specify the start and end dates of the backtest. In this example, the backtest time range is from January 1, 2016 to January 1, 2018.

  • -o buyapple_out.pickle:Specify the name of the output file. In this example, the backtest results will be saved asbuyapple_out.picklefile. This file contains various output information of the backtest, such as trade records, performance metrics, etc.

  • --no-benchmark:Disable benchmark. In backtesting, sometimes a benchmark is used to compare the performance of the strategy. Using--no-benchmarkoption means no benchmark is used.

The pickle module is used to serialize and deserialize objects, making it convenient to save objects to a file or load objects from a file.

The following demonstrates how to read the content of the buyapple_out.pickle file:

Example

import pickle

# Specify the pickle file path
pickle_file_path = 'buyapple_out.pickle'

# Read the pickle file
with open(pickle_file_path, 'rb') as file:
    buyapple_out_data = pickle.load(file)

# Print the read data
print(buyapple_out_data)

The output is as follows:

                                        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
2016-01-05 21:00:00+00:00 2016-01-05 14:31:00+00:00 2016-01-05 21:00:00+00:00  
Other Extensions