# Database transaction back test series 3: multi factor alpha strategy optimal factor weight

Time：2021-4-14

In the second part of this series（Multi factor alpha strategy backtesting）In this paper, we test the four quantitative factors of the U.S. stock market. Here, we’ll use the built-inquadprogFunction to optimize the mean variance of each factor weight to determine the best factor weight.

After the script provided in the second part of this series is executed, the data table factorpnl will store the daily income of each factor. The following script is based on the data table factorpnl.

``````retMatrix=matrix(select C0, C1, C2, C3 from factorPnl)
H = cross(covar, retMatrix, retMatrix)
f=-0.25*each(avg, retMatrix)
A=-(1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 \$4:4)
b=-0.1*1 1 1 1
Aeq=matrix(,,,)
beq=
result=quadprog(H, f, A, b, Aeq, beq)
result``````

This code solves the following optimization problems: Here our objective function is to maximize (1 / 4)Expected return – 1 / 2At the same time, the weight sum of the four factors is 1, and the minimum weight of each factor is 10%. H is the variance covariance matrix of four factor returns. Note that h, a and AEQ must be matrices with equal number of columns; F, B and BEQ must be vectors. A is a negative identity matrix, which is used with B to ensure that the weight of each factor is greater than 10%. For details of the quadprog function, please refer toDolphin DB user development document quadprog

Result  gives the optimal factor weight based on the given optimization conditions. The results are as follows

``[0.3612, 0.1, 0.438804, 0.1]``

In the script provided in the second part of this series,

``signalNames = `signal_mom`signal_vol`signal_beta`signal_size``

Therefore, the best weight is 36.1% momentum factor, 10% volatility factor, 43.9% beta factor and 10% market value factor.

The above calculation uses data from all historical periods. You can also select the data of the last 10 years for calculation. Just make the following changes to the first line of the above script:

``retMatrix=matrix(select C0, C1, C2, C3 from factorPnl where date>=2007.01.01)``

The results are as follows

``[0.19277, 0.1, 0.1, 0.60723]``

Therefore, the best weight is 19.3% momentum factor, 10% volatility factor, 10% beta factor and 60.7% market value factor.

It can be seen that the historical period of mean variance optimization has an important impact on the results.

## Installation and configuration of node.js and NPM

Installation of node.js CentOS installation: \$ dnf module list nodejs \$ dnf module install nodejs:14 Windows installation: https://nodejs.org/en/download/ To view the installed version: \$ node -v NPM installation Node.js has a built-in NPM package management tool, which does not need to be installed separately. To view the installed version: \$ npm -v Upgrade NPM to […]