SVN

SVN

For those who are given access to an AQ project or AlgoQuant (AQ) itself in svn repository, you need a software to check out code from the source control. If you are a Windows user, we recommend you to use ​TortoiseSVN; if you are a Mac user, you may try ​Versions. The following instructions assume that you are a Windows user.

  1. Browse to a folder where you would like to save the project.
  2. Right click any empty space in Windows explorer to bring up the context sensitive menu.
  3. Hit “TortoiseSVN -> Repo-browser”.
  1. Type in the svn path given to you, e.g., the link in the picture shown below.

AQ Project

AlgoQuant

  1. Right click on “trunk”, and hit “Checkout”.
  1. Fill out the Checkout dialogue, and hit “OK”. This will start downloading the project to your chosen location.

You will need to use a Java IDE such as NetBeans or Eclipse to open the project. See the setup guide for an example.

When you open the blank AQ project, you will see this project in your NetBeans. There are two example classes already in the project for your reference. The dependencies on AlgoQuant and SuanShu and other 3rd party libraries are already set up. NetBeans (Maven) will automatically download these libraries for you.

FAQs

FAQs

[ultimate-faqs]

Demo

Demo

After the initial setup, you can run demo programs included in the sub-project algoquant-demo. Source files that end in “…Demo.java” (e.g, RunAllDemo.java), are executable programs for demonstration.

To run a demo program, you right click on it and hit Run File (or SHIFT+F6).

Economic Factor Model

Economic Factor Model

In factor model, the stock return is estimated by the product of factor premium (payoff to risk)  and factor exposure (exposure to risk). In economic factor model, we assume the factor premium is known value for the market which can be calculated from given data. And the factor exposure, which is stock’s sensitivity to factor premium, needs to be estimated by the regression of stock return on factor premium.

Unlike fundamental factor model, factor premium of economic factor model can not only be return of stock’s factors such as fundamental, momentum or quality factors, but also economic data, like inflation rate, interest rate, GDP and so on.

There are 3 steps to estimate stock future return by economic factor model:

  1. Calculate factor premium:
    For stock’s factors like fundamental or technical factors, we need to first identify the stock universe. After construct zero-investment portfolio for each factor, the portfolio return will be consider as the factor premium / return.
  2. Estimate factor exposure:
    Factor exposure in economic factor model will be determined by time series regression of stock returns on factor premiums. By repeating the regression for each stocks, we will able to get regression coefficients (factor exposures) for each factor of each stock.
  3. Estimate stock return and covariance matrix:
    Once we have factor premium and factor exposure, we can use them to estimate stock’s future return and covariance matrix.

Stock Universe

We select the stock universe for zero-investment portfolios similar to Fama & French’s method:
1. Belong to NYSE, NASDAQ and AMEX
2. Common stocks
3. Stocks’ unadjusted prices are larger than $1 to prevent them turn into OTC stocks in a short period

Zero-investment portfolio

After selected the stock universe, we can construct zero-investment portfolio for each factor.:
1. At each end of June, we rank all stocks in stock universe in terms of the factor
2. We can create high-exposure(top 30%) and low-exposure(bottom 30%) stock portfolios by value‐weighting.
3. Calculate the difference of these two portfolio return as the zero-investment portfolio return.

 

Intra-day Volatility Arbitrage Strategy (VolArb)

Intra-day Volatility Arbitrage Strategy (VolArb)

It has been long observed (Lo and MacKinlay 1988) that, for a mean-reverting process, the high frequency volatility is bigger than the low frequency volatility, hence an arbitrage opportunity. For instance, the daily volatility > monthly volatility > yearly volatility. Conceivably, we may make a profit by buying the bigger volatility and selling the smaller volatility. In fact, we can mathematically compute the expected P&L for any price process.

The success of the VolArb strategy depends on

  • Finding or constructing a piece-wise mean-reverting or slowly-moving-mean asset
  • Trading the “right” volatility difference(s)

Each of the two topics is an important subject in its own right.

We have extensively evaluated the performance of VolArb on trading currency pairs in many settings, taking into account bid-ask. For low frequency trading, the P&L is above 6% of the maximal exposure with a max draw down of 2 – 3%. The Sharpe ratio ranges from 2 to 3. For higher frequency trading, e.g., intra-day, the P&L ranges from 20% – 40% of the maximal exposure with a max draw down of 2 – 8%. The Sharpe ratio is above 2.

References

VolArb P&L

​Poterba and Summers

Lo, A. W. and C. MacKinlay (1988) “The Size and Power of the Variance Ratio Tests in Finite Samples: A Monte Carlo Investigation” Journal of Econometrics 40, 203-38.

​On H-volatility in financial mathematics

Code

http://redmine.numericalmethod.com/projects/public/repository/svn-algoquant/show/core/src/main/java/com/numericalmethod/algoquant/model/volarb

Elliott Pairs Trading Model, 2005

Elliott Pairs Trading Model, 2005

This paper models the spread of a pair (or any mean reverting synthetic asset) as a discrete Ornstein-Uhlenbeck (O-U) process. It then uses the Kalman filter to estimated the “true” (or hidden) price for the spread. When the observed price is bigger than the estimated true price by a threshold, we sell; otherwise we buy. The threshold and average holding time of a trade can be computed from the properties of the O-U process.

The paper describes two ways to estimate the parameters in the state process (for the spread):

  1. Shumway and Stoffer (1982) smoother approach (offline)
  2. Elliott and Krishnamurthy (1999) filter approach (online)

Notes

There seems to be some typos in the equations in the 2nd approach (the online algorithm) in the original publication.

References

http://www.tandfonline.com/doi/pdf/10.1080/14697680500149370

​http://editorialexpress.com/cgi-bin/conference/download.cgi?db_name=QMF2004&paper_id=138

​http://www-stat.wharton.upenn.edu/~steele/Courses/434/434Context/PairsTrading/PairsTrading.html

Code

http://redmine.numericalmethod.com/projects/public/repository/svn-algoquant/show/core/src/main/java/com/numericalmethod/algoquant/model/elliott2005

Identifying Small Mean Reverting Portfolios, d’Aspremont, 2008

Identifying Small Mean Reverting Portfolios, d’Aspremont, 2008

The Eigenvalue Problem, Section 3.2, d’Aspremont2008

The original problem in section 3.2, d’Aspremont2008 is to find the maximum \(\lambda\) so that:

\(\det(\lambda B-A)=0\)

In d’Aspremont2008 the author transforms the above problem into the following problem, with an additional cardinality constraint.

\(\lambda_{max}(A,B)=\max_{x\in\mathbb{R}^{n}}\frac{x^{T}Ax}{x^{T}Bx}\)

 \(s.t. \quad card(x)\leq k\)

 \(||x||_{2}=1\)

This problem is equivalent to:

\(\max_{X\in S^{n}}\frac{Tr(AX)}{Tr(BX)}\)

\(s.t. \quad card(X) \leq k^{2}\)

\(Tr(X)=1\)

\(X\geq 0\)

\(rank(X)=1\)

where \(X=xx^{T}\).

Problem 1

In d’Aspremont2008, the author points out that the cardinality constraint can be relaxed to \(1^{T}|X|1\leq k^{2}\). This new constraint is not in the SDP standard form, and thus requires transformation before using an SDP solver. Even so, this relaxation has two drawbacks:

  1. To transform \(1^{T}|X|1\leq k^{2}\) into the standard form, two new \(n\) by \(n\) variable matrices are introduced. Let \(X=U-V\), where \(U_{i,j}\geq0\) and \(V_{i,j}\geq0\). This transformation avoids the absolute sign on \(X\) but the new constraints \(U_{i,j}\geq0\) and \(V_{i,j}\geq0\) can not be transformed to the standard form without adding at least \(n(n+1)\) new constraints. If the dimension of \(X\) is 100 by 100, this transformation will add ten thousand new constraints to the optimization problem.
  2. The constraint \(1^{T}|X|1\leq k^{2}\) is a relaxation of the cardinal constraint. In d’Aspremont2008 the author points out that due to this relaxation, the final solution \(X\) may have a higher rank than one. It is thus possible that the cardinality of \(X\) is bigger than \(k^{2}\). Because an interior point algorithm maximizes the objective function by searching the interior of a feasible region, the probability that it returns a high rank solution is not low.

Due to these two drawbacks, we suggest to solve Problem 1 without relaxation and instead follow Dattorro2005. After using the same transformation in d’Aspremont2008 (equation 12), the problem we are trying to solve is:

\(\max_{Y\in S^{n}}Tr(AY)\)

\(s.t. \quad card(Y)\leq k^{2}\)

\(Tr(BY)\)

\(Y\geq0\)

\(rank(Y)=1\)

where \(Y=\frac{X}{Tr(BX)}\).

Problem 2

The difficulties in solving Problem 2 lie in the rank constraint and cardinality constraint. They are discussed in the next section.

Handle Rank and Cardinality Constraints

2.1 Rank Constraint

According to Chapter 4.4 of Dattorro2005 (P308), the rank constraint is equivalent to an optimization problem. For example, consider the following rank-constrained problem (note that this problem is not related to Problem 2 in section 1.)

\(find_{X\in S^{n}}X\)

\(s.t.\quad Tr(AX)=b\)

\(X\geq0\)

\(rank(X)=1\)

(original problem)

This rank constrained problem is equivalent to the following two problems:

\(\min_{X\in S^{n}}Tr(WX)\)

\(s.t.\; Tr(AX)=b\)

\(X\geq0\)

(sub-problem 1)

\(\min_{W\in S^{n}}Tr(WX^{*})\)

\(s.t.\; 0\leq W\leq I\)

\(Tr(W)=n-1\)

where \(X^{*}\) is the solution to sub-problem 1.

Sub-problem 2

The solving procedure (Chapter 4.4 of Dattorro2005 (P308)) is first assuming \(W\) is a zero matrix and then solve sub-problem 1 to get \(X^{*}\). \(X^{*}\) is used in sub-problem 2 to solve for latex W$. Then the objective function in sub-problem 1 can be updated with the new \(W\); \(X\) is calculated again. Repeat. The procedure stops when \(Tr(WX)=0\).

Sub-problem 2 actually has a closed form solution, so there is no need to iteratively solve sub-problem 2. As pointed out in Chapter 4.4 of Dattorro2005 (P308), the solution to sub-problem 2 is not unique. And, solving the problem using a closed form solution is not always the fastest, i.e. it may take fewer iterations to solve sub-problems 1 and 2 than by directly solving sub-problem 2. However, in our experiments when closed form solution is used, the total iteration number is not big.

The close form solution to sub-problem 2 can be computed as follow: suppose the diagonal decomposition is \(X^{*}=Q^{T}\Lambda Q\), and let \(U=Q[1:n;2:n]\), then the solution to sub-problem 2 is \(W^{*}=UU^{T}\).

2.2 Cardinality Constraint

Using a very similar procedure described in section 2.1, the cardinal constraint can be transformed into an optimization problem which has a closed form solution (Chapter 4.5, Dattorro2005 (P344)). For example, consider a simple SDP problem with a cardinality constraint (note that this problem is not related to Problem 2 in section 1, and we assume \(X = xx^{T}\).):

\(find_{X\in S^{n}}X\)

\(s.t.\; Tr(AX)=b\)

\(X\geq0\)

\(card(X)\leq k^{2}\)

(original problem)

The above problem is equivalent to the following two problems:

\(\min_{X\in S^{n}}Tr(DX)\)

\(s.t. \; Tr(AX)=b\)

\(X\geq0\)

(sub-problem 1)

\(\min_{D\in n\times n\; diagonal\;matrix}Tr(DX^{*})\)

\(s.t.\;0\leq D\leq I\)

\(Tr(D)=n-k\)

In sub-problem 1 and 2, \(D\) is a diagonal matrix.

sub-problem 2

The solving procedure is same as that of the rank constraint. First we assume \(D\) is a zero matrix and calculate \(X^{*}\) from sub-problem 1. Then diagonal matrix \(D\) can be calculated by solving sub-problem 2 with updated \(X^{*}\). The procedure repeats until when \(Tr(DX)=0\).

As in rank constraint, the solution to sub-problem 2 is not unique. A closed form solution exists, but it is not guaranteed to be the fastest. The closed form solution: \(D\) is a diagonal matrix and \(D_{i,i}=1\) if \(X^{*}_{i,i}\) is smaller than the \((n-k )th\) smallest value of\(\{X_{1,1}^{*},X_{2,2}^{*},\cdots,X_{n,n}^{*}\}\), otherwise \(D_{i,i}=0\).

3. Solution to Problem 2

To solve Problem 2 in section 2, two new variables \(W\) and \(D\) are added to the problem. \(W\) is added to restrict the rank of \(Y\) and \(D\) is added to restrict the cardinality of \(Y\). Although two new variable matrices are added, from section 2 we can see that the computation burden does not increase much, because \(W\) and \(D\) have close form solutions.

Solving Problem 2 is equivalent to solving the following three problems:

\(\max_{Y\in S^{n}}Tr(AY)-w_{1}Tr(WY)-w_{2}Tr(DY)\)

\(s.t. \; Tr(BY)=1\)

\(Y\geq0\)

(Problem 3.1)

\(\min_{W\in S^{n}}Tr(WY^{*})\)

\(s.t.\; 0\leq W\leq I\)

\(Tr(W)=n-1\)

(Problem, 3.2)

\(\min_{D\in n\times n\; diagonal\;matrix}Tr(DY^{*})\)

\(s.t.\;0\leq D\leq I\)

\(Tr(D)=n-k\)

(Problem 3.3)

In Problem 3.1, \(w_{1}\) and \(w_{2}\) are penalties imposed on the rank and cardinality constraints.

The solving procedure is as follow:

  1. Solve Problem 3.1 assuming \(W\) and \(D\) are zero matrices. Denote the solution as \(Y^{*}\).
  2. Solve Problem 3.2 using \(Y^{*}\) from step 1. Denote the solution as \(W^{*}\).
  3. Solve Problem 3.3 using \(Y^{*}\) from step 1. Denote the solution as \(D^{*}\).
  4. Check \(Tr(W^{*}Y^{*})\) and \(Tr(D^{*}Y^{*})\) if they are small enough. If yes, the computation finishes, \(Y^{*}\) is the final solution. Otherwise, go to step 1 and solve Problem 3.1 updating latex W=W^{*}$ and \(D=D^{*}\). Repeat steps 1 – 4.

4. Numerical Example

The original problem is to find the maximum \(\lambda\) so that \(\det(\lambda B-A)=0\), therefore with the help of an orthogonal matrix \(Q\), we construct \(A\) and \(B\) as follow:

\(A=Q^{T}diag(20,8,4)Q\)

\(B=Q^{T}diag(2,3,5)Q\)

Because \(A\) and \(B\) are constructed by the same orthogonal matrix \(Q\), the value of \(\lambda\) should be \(10\), \(8/3\) and \(4/5\).

The actual value of \(Q\), \(A\) and \(B\) are:

\(Q=\left(\begin{array}{ccc}-0.33&0.59&0.74\\-0.59&-0.74&0.33\\-0.74&0.33&-0.59\end{array}\right)\)\(A=\left(\begin{array}{ccc}7.89&4.07&2.13\\4.07&10.0&6.19\\2.13&6.19&14.1\end{array}\right)\)\(B=\left(\begin{array}{ccc}3.98&0.29&-1.11\\ 0.29&2.87&-0.82\\-1.11&-0.82&3.16\end{array}\right)\)

The results when \(k=1\), \(w_{1}=5\), \(w_{2}=225\) are:

\(Y=\left(\begin{array}{ccc} 0.000& 0.000& 0.010\\ 0.000&0.001&0.015\\ 0.010&0.015&0.331\end{array}\right)\)\(rank(Y)=1\)

Recall in d’Aspremont2008 \(X=xx^{T}\), and we assume \(Y=\frac{X}{Tr(BX)}\). The cardinality of vector \(x\) recovered from \(Y\) is 1. Only the third entry of \(x\) is nonzero.

References

  1. [d’Aspremont2008] d’Aspremont, A., “Identifying Small Mean Reverting Portfolios”, 2008.
  2. [Dattorro2005] Dattorro, Jon, “Section 4. Semidefinite programming”, Convex Optimization and Euclidean Distance Geometry, Meboo Publishing. 2005, v2013.03.30.

Infantino’s PCA Model, 2010

Infantino’s PCA Model, 2010

This model, from a large group of stocks e.g., S&P 500, computes, using ​Principal Component Analysis, the common factors that drive stock returns and filters out noises. We can then estimate the short term expected returns for each individual stock, hence a trading decision.

Moreover, the model proposes a way to use intraday volatility to estimate which of the two regimes we are in: mean-reversion or momentum.

Combining the estimated expected returns with the regime indicator, we do mean-reversion when the intraday volatility is small, and trend following when the intraday volatility is big.

References

​Developing high-frequency equities trading models

Code

http://redmine.numericalmethod.com/projects/public/repository/svn-algoquant/show/core/src/main/java/com/numericalmethod/algoquant/model/infantino2010

Markowitz Portfolio Theory

Markowitz Portfolio Theory

Harry Markowitz introduced and later won the Nobel Prize for the Modern Portfolio Theory in his 1952 article and 1959 book. His theory attempts to maximize portfolio expected return for a given amount of portfolio risk, or equivalently minimize risk for a given level of expected return, by carefully choosing the proportions of various assets.

The mathematical formulation is the following.

We solve a quadratic programming problem to find the portfolios weights (ω’s) that maximize this objective function, where λ is the risk-adverse coefficient between 0 and ∞.

\(R^T w – \lambda \times w^T \Sigma w\)

One (unity) constraint is:

\(\sum_i w_i = 1\)

In additional, AlgoQuant lets you put any (reasonable) constraints on the ω’s as you like. For example, one common constraint is to disallow short selling. That is,

\(w_i \ge 0\)

References

​http://en.wikipedia.org/wiki/Modern_Portfolio_Theory

Demo

An online demo is available.

Code

http://redmine.numericalmethod.com/projects/public/repository/svn-algoquant/show/core/src/main/java/com/numericalmethod/algoquant/model/portfoliooptimization/markowitz

http://redmine.numericalmethod.com/projects/public/repository/svn-algoquant/entry/core/src/main/java/com/numericalmethod/algoquant/model/portfoliooptimization/markowitz/MarkowitzUtils.java

http://redmine.numericalmethod.com/projects/public/repository/svn-algoquant/entry/core/src/main/java/com/numericalmethod/algoquant/model/portfoliooptimization/markowitz/MarkowitzPortfolio.java

Factor Model

Factor Model

The central idea of modern financial economics: The average return of a stock is the payoff for taking risk.

Factor Premium & Factor Exposure

Given a stock and a risk factor,Factor Premium quantifies the payoff to an investor who takes on this risk by buying the stock.Factor Exposure quantifies the exposure of the stock to this risk.Average stock return per this risk[box]average stock return = factor exposure X factor premium

Mathematics

Suppose we have N stocks whose returns depend on K factors.

  • the factor premiums for the K factors: \(f_1, cdots , f_K\)
  • the factor exposures of stock i: \(beta_{i1}, cdots, beta_{iK}\)

The return on stock i, \(r_i\)” , can be written as \(r_{i} = alpha_{i} + beta_{i1}f_1 + cdots + beta_{iK}f_K + epsilon_{i}\)

The average stock return is \(E(r_i) = mathbf{beta_i}’E(mathbf{f})\)

where, \(mathbf{f} = {left( alpha_i, f_1, cdots,f_K right)}’\), \(mathbf{beta_i} = {left( 1, beta_{i1}, cdots,beta_{iK} right)}’\)

Finding Factor Premium

Since return (\(r_i\)) and factor exposures (\(beta_{i1}, cdots, beta_{iK}\)) of the N stocks are known, we can compute, at any time point, the factor premiums (\(f_{1}, cdots, f_{k}\)) from the stock return equation using the ​OLS (Ordinary Least Square) ​regression.

\(r_{i} = alpha_{i} + beta_{i1}f_1 + cdots + beta_{iK}f_K + epsilon_{i}\)

Panel Regression

However, knowing the factor premiums on separate time points (e.g. each month or season) would not be helpful for prediction and analysis. We would like to know whether there exist stable factor premiums for a longer time period (e.g. 2~3 years).

Given there are N stocks over T time periods, \(left { (r_{11}, cdots, r_{N1}), cdots,(r_{1T}, cdots,r_{NT}) right }\)

Factor exposures of N stocks over T time periods, \(left { (beta_{11}, cdots, beta_{N1}), cdots, (beta_{1T}, cdots,beta_{NT}) right }\)

We can estimate the factor premiums (f) from the following equation using OLS regression,

\(r_{it} = beta’_{it}f + epsilon_{it}\)

Our Implementation in Algoquant

AlgoQuant has a package on QEPM to model factors, exposure and premium. We currently support the computation of premiums using cross-sectional or panel regressions (factor premiums on separate time points).

Reference

​Ludwig B Chincarini and Daehwan Kim, Quantitative Equity Portfolio Management: An Active Approach to Portfolio Construction and Management, McGraw-Hill Library of Investment and Finance, 2006.