Build quantitative system | customized quantitative transaction back testing framework

Time:2020-9-30

When we develop a trading strategy and need to backtest the strategy, we need a backtesting framework. At present, there are many mature backtesting frameworks and various platforms. These frameworks or platforms have their own advantages and disadvantages, and can not meet everyone’s needs. In order to run through the knowledge points of quantitative trading, consolidate the learning content better, and build a suitable framework for ourselves in the future, we will learn how to customize the quantitative transaction back testing framework in this note.

To complete the backtesting of a strategy, generally speaking, it includes the following steps:

  • Get market data. We take the stock market data as an example, at least we need to obtain the closing price, opening price, highest price, lowest price and trading volume. Generally, we divide the data into two parts according to time: one is the data of strategy training set and the other is the data of strategy test set.
  • The signal of timing strategy is generated. We take the timing strategy in the column as an example to generate a sequence of trading signals on the training set data. A more comprehensive strategy should include profit stop loss mechanism, parameter optimization measures and so on.
  • Output strategy back test report. First, set the initial fund for backtesting, and then buy and sell stocks according to the trading signals. We can choose to buy / sell the whole position or use the position management function. Finally, the backtesting index is used to evaluate the effect of the strategy. The back test indicators include the rate of return on funds, the comparison with the benchmark return, the maximum withdrawal of funds, the maximum withdrawal of the rise and fall, etc. Of course, in the actual transaction, there are transaction fees and sliding points, which need to be considered if it is closer to reality.
  • Visualization strategy backtesting effect. Visualization is very important in the process of data analysis in various fields, which can show the meaning behind the data most intuitively. Here, we can visualize the revenue curve and the maximum withdrawal curve to evaluate the strategy operation more intuitively.

Get the stock trading data interface getstockdatapi. The interface is introduced as follows:

#For data acquisition interface, please refer to "automatic download of stock trading data"
#Input parameters
#: param data: Code Stock Code
#: param data: start start date, the default is January 1, 2010
#: param data: start start date, the default is January 1, 2010
#Output parameters
#   :return data: df_ Stock data in dataframe format after Recon regularization
#Note: this interface is stock ex right data

The interface routine is as follows. After calling, it will return the closing price, opening price, highest price, lowest price and trading volume:

df_stock = GetStockDatApi("000876.SZ", '20170101', '20200101')
"""
             High    Low   Open  Close     Volume
trade_date                                       
2017-01-03   8.12   8.07   8.07   8.12  179801.01
2017-01-04   8.16   8.09   8.13   8.15  166242.35
2017-01-05   8.23   8.13   8.15   8.17  222902.53
2017-01-06   8.19   8.12   8.18   8.13  128549.96
2017-01-09   8.15   8.08   8.13   8.13  136700.04
...           ...    ...    ...    ...        ...
2019-12-25  18.79  18.44  18.59  18.60  207776.34
2019-12-26  18.76  18.46  18.69  18.60  189935.42
2019-12-27  19.43  18.58  18.74  19.28  504214.70
2019-12-30  19.50  18.92  19.24  19.38  379296.95
2019-12-31  20.31  19.55  19.55  19.95  562873.40

[731 rows x 5 columns]
"""

The timing strategy signal generation interface, here is to calculate the n-day breakthrough signal calndayssignal. The interface is introduced as follows:

#For the calculation of n-day breakthrough signal interface, please refer to the trend breakthrough timing strategy
#Input parameters
#Stock data: stock data
#: param data: N1 policy parameter, the default value is 15
#: param data: N2 policy parameter, the default value is 5
#Output parameters
#Datareturn: stock trading format

The interface routine is as follows:

df_stock = CalNdaysSignal(df_stock, N1=15, N2=5)

The stock data returned after calling the interface is as follows:

"""
             High    Low   Open  Close     Volume  N1_High  N2_Low  signal
trade_date                                                                
2017-01-03   8.12   8.07   8.07   8.12  179801.01     8.12    8.12     1.0
2017-01-04   8.16   8.09   8.13   8.15  166242.35     8.15    8.12     1.0
2017-01-05   8.23   8.13   8.15   8.17  222902.53     8.17    8.12     1.0
2017-01-06   8.19   8.12   8.18   8.13  128549.96     8.17    8.12     1.0
2017-01-09   8.15   8.08   8.13   8.13  136700.04     8.17    8.07     1.0
...           ...    ...    ...    ...        ...      ...     ...     ...
2019-12-25  18.79  18.44  18.59  18.60  207776.34    21.53   18.36     0.0
2019-12-26  18.76  18.46  18.69  18.60  189935.42    21.53   18.36     0.0
2019-12-27  19.43  18.58  18.74  19.28  504214.70    21.03   18.36     0.0
2019-12-30  19.50  18.92  19.24  19.38  379296.95    20.71   18.36     0.0
2019-12-31  20.31  19.55  19.55  19.95  562873.40    20.31   18.44     0.0

[731 rows x 8 columns]
"""

Timing strategy is integrated into risk management factors to generate transaction signal interface. The interface is introduced as follows:

#The introduction of risk management factors on the basis of n-day breakthrough timing strategy can refer to ATR stop win and stop loss risk strategy
#Input parameters
#Stock data: stock data
#: param data: N1 policy parameter, the default value is 15
#: param data: N2 policy parameter, the default value is 5
#   :param data: n_ Loss stop loss strategy parameter, the default value is 0.8
#   :param data: n_ Win stop profit strategy parameter, the default value is 2
#Output parameters
#: return data: stock data in dataframe format with trading signal added after regularization
#Note: this interface is stock ex right data

The interface routine is as follows:

df_stock = CalNdaysStopSignal(df_stock, N1=15, N2=5, n_loss=0.8, n_win=2)

After calling the interface, the stop gain and stop loss signals are as follows:

"""
17-03-09 buy price: 8.16 stop loss selling price: 8.06
17-03-28 purchase price: 8.24 stop loss selling price: 8.16
17-06-16 purchase price: 8.07 stop loss selling price: 7.98
17-07-04 buy price: 8.31 stop loss selling price: 8.17
17-11-14 purchase price: 7.74 stop loss selling price: 7.62
17-11-23 purchase price: 7.95 stop loss selling price: 7.77
18-02-01 buy price: 8.32 stop loss selling price: 8.04
18-05-30 purchase price: 7.34 stop loss selling price: 7.02
18-07-19 purchase price: 6.53 stop loss selling price: 6.33
18-11-20 purchase price: 6.83 stop loss selling price: 6.64
18-12-06 buy price: 7.52 stop loss selling price: 7.27
19-01-08 buy price: 7.82 stop loss selling price: 7.6
19-02-28 purchase price: 11.18 stop loss selling price: 10.6
19-03-13 purchase price: 14.22 stop loss selling price: 12.8
19-04-11 purchase price: 14.84 stop loss selling price: 14.03
19-05-07 purchase price: 17.31 stop loss selling price: 16.15
19-06-06 buy price: 20.6 stop loss selling price: 18.67
19-07-18 purchase price: 20.25 stop loss selling price: 19.1
19-09-06 purchase price: 19.51 stop loss selling price: 18.48
19-10-17 purchase price: 18.85 stop loss selling price: 18.25
19-10-31 purchase price: 23.13 stop loss selling price: 22.06 
"""

The stock data returned after calling the interface is as follows:

"""
              High    Low   Open  Close   ...    N1_High  N2_Low  atr14  signal
trade_date                               ...                                  
2017-01-03   8.12   8.07   8.07   8.12   ...       8.12    8.12   0.10     0.0
2017-01-04   8.16   8.09   8.13   8.15   ...       8.15    8.12   0.10     0.0
2017-01-05   8.23   8.13   8.15   8.17   ...       8.17    8.12   0.10     0.0
2017-01-06   8.19   8.12   8.18   8.13   ...       8.17    8.12   0.10     0.0
2017-01-09   8.15   8.08   8.13   8.13   ...       8.17    8.12   0.10     0.0
...           ...    ...    ...    ...   ...        ...     ...    ...     ...
2019-12-25  18.79  18.44  18.59  18.60   ...      21.60   18.36   0.72     0.0
2019-12-26  18.76  18.46  18.69  18.60   ...      21.53   18.36   0.69     0.0
2019-12-27  19.43  18.58  18.74  19.28   ...      21.53   18.36   0.70     0.0
2019-12-30  19.50  18.92  19.24  19.38   ...      21.03   18.36   0.69     0.0
2019-12-31  20.31  19.55  19.55  19.95   ...      20.71   18.36   0.71     0.0

[731 rows x 9 columns]
"""

The output strategy backtest report interface is introduced as follows:

#For the implementation of simple strategy back testing interface, please refer to the "drawing of strategic returns under the trading range"
#Input parameters
#Stock data and trading signals
#   :param data: code_ Name stock name
#   :param data: cash_ Hold back testing fund
#Output parameters
#: return data: add stock data in dataframe format of backtest results

The interface routine is as follows:

Df_ stock = SimpleBackTest(df_ Stock, "new hope", 100000)

After calling the interface, it can print out the final fund, benchmark yield, stock trading records and other backtesting results.

"""
New hope back test results
Final capital: 132180.0
Benchmark yield: 0.8988989891622865
Strategic yield: 0.046179711142093044
Maximum retreat point: Trade_ date 2019-10-18    0.58
"""
"""
Purchase of 12300 shares of new hope on 17-01-03
12300 shares of new hope were sold on January 13, 2007
Purchase of 12100 shares of new hope on 17-02-10
12100 shares of new hope were sold on March 10, 17
Purchase of 11700 shares of new hope on March 24, 2007
11700 shares of new hope were sold on March 31, 17
Purchase of 11600 shares of new hope on June 13, 2007
11600 shares of new hope were sold on July 18, 2007
Purchase of 12500 shares of new hope on 17-11-03
Sold 12500 shares of new hope on December 1, 2007
Purchase of 12000 shares of new hope on 18-01-08
12000 shares of new hope were sold on February 2, 18
Purchase of 13300 shares of new hope on 18-05-17
13300 shares of new hope were sold on May 31, 2008
Purchase of 14500 shares of new hope on July 16, 2008
14500 shares of new hope were sold on August 2, 2008
Purchase of 14600 shares of new hope on 18-11-05
14600 shares of new hope were sold on November 28, 2008
Purchase of 14500 shares of new hope on November 29, 2008
Selling 14500-18 new shares
Purchase of 13400 shares of new hope on 19-01-07
13400 shares of new hope were sold on March 15, 19
Purchase of 11100 shares of new hope on April 3, 19
11100 shares of new hope were sold on April 12, 19
Purchase of new hope 9400 shares on May 6, 2009
9400 shares of new hope sold on May 9, 2009
Purchase of 7300 shares of new hope on May 31
7300 shares of new hope were sold on June 24, 19
Purchase of 6500 shares of new hope on July 16
6500 shares of new hope were sold on July 23, 19
Purchase of 6200 shares of new hope
6200 shares of new hope sold on September 19
Buy 6100 shares of new hope on October 11, 19
6100 shares of new hope were sold on October 21, 19
Purchase of new hope 6000 shares on October 22
New hope 6000 shares sold on November 18
"""

In addition, the return value of the interface adds dynamic backtesting data of each trading day on the basis of stock data in dataframe format.

"""
               total  per_total  max_total  Close  max_close  trend_profit  benchmark_profit
trade_date                                                                                  
2017-01-03   99997.0       1.00    99997.0   8.12       8.12           NaN               NaN
2017-01-04  100367.0       1.00   100367.0   8.15       8.15      3.69e-03          3.69e-03
2017-01-05  100613.0       1.00   100613.0   8.17       8.17      2.45e-03          2.45e-03
2017-01-06  100120.0       1.00   100613.0   8.13       8.17     -4.91e-03         -4.91e-03
2017-01-09  100120.0       1.00   100613.0   8.13       8.17      0.00e+00          0.00e+00
...              ...        ...        ...    ...        ...           ...               ...
2019-12-25  146829.0       0.74   198468.0  18.60      23.20      0.00e+00          3.77e-03
2019-12-26  146829.0       0.74   198468.0  18.60      23.20      0.00e+00          0.00e+00
2019-12-27  146829.0       0.74   198468.0  19.28      23.20      0.00e+00          3.59e-02
2019-12-30  146829.0       0.74   198468.0  19.38      23.20      0.00e+00          5.17e-03
2019-12-31  146829.0       0.74   198468.0  19.95      23.20      0.00e+00          2.90e-02

[731 rows x 7 columns]
"""

This interface outputs the results of backtesting in the form of chart. The interface is introduced as follows:

#For the implementation of simple strategy back testing interface, please refer to the "drawing of strategic returns under the trading range"
#Input parameters
#   :param data: df_ Stockload stock data / trading signal / back test result data
#   :param data: code_ Name stock name

The interface routine is as follows:

DrawBackTest(df_ Stock, "new hope"

After calling the interface, the back test results are output in the form of chart.

Build quantitative system | customized quantitative transaction back testing framework

The above knowledge points are all covered in the book. Here we match the knowledge points with the position in the column. We hope that through this part of content, we can have a more overall grasp of the backtesting of quantitative trading.

More information on the above contents, welcome to WeChat official account. The lantern master takes you to quantify transactions with Python!

Recommended Today

PHP 12th week function learning record

sha1() effect sha1()Function to evaluate the value of a stringSHA-1Hash. usage sha1(string,raw) case <?php $str = “Hello”; echo sha1($str); ?> result f7ff9e8b7bb2e09b70935a5d785e0cc5d9d0abf0 sha1_file() effect sha1_file()Function calculation fileSHA-1Hash. usage sha1_file(file,raw) case <?php $filename = “test.txt”; $sha1file = sha1_file($filename); echo $sha1file; ?> result aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d similar_text() effect similar_text()Function to calculate the similarity between two strings. usage similar_text(string1,string2,percent) case […]