Thursday, February 7, 2013

Portfolio Optimization Problems

Portfolio Optimization is a way to determine the weights to be allocated in each investment so that the amount of expected return and the level of risk optimally meets the investor's objective. To do that, we can either maximize the returns subject to the maximum level of risk or minimize the risk subject to the acceptable level of expected return.

LP Application

From the book, the applications of LP and Non LP in Finance involves portfolio selection. The construction of the portfolios is within the framework of CAPM and details can be found in the book as to how it was derived. It can maximize the expected return while controlling systematic risk.

Sample: Given 3 assets portfolio
\[ \text{Max (return)} = 0.11W_a +0.15W_b+0.08W_c\]
subject to:
  1. $W_a+1.2W_b+0.9W_c \le 1.1$
  2. $0 \le W_a, W_b, W_c \le 1$
  3. $W_a + W_b + W_c = 1$
Explanation:
  • The expected return of the individual assets A, B and C are 0.11, 0.15 and 0.08 respectively.
  • Constraint 1 tell us that the individual risks $\beta_a$, $\beta_b$ and $\beta_c$ for the assets are 1, 1.2 and 0.9 respectively. It also tells us that the portfolio risk or $\beta$ must not exceed 1.1.
  • Constraint 2 tell us that all assets must have non negative weights
  • Constraint 3 tells us that the funds must be fully invested for sum of the weights is equal to 1.
This can be solved using Graphical Method or the Simplex Method. Consequently, the objective function and constraints can still be reduced into much simpler form when $W_c=1-W_a-W_b$ is substituted to each of the equations.

\[ \text{Max (return)} =0.03W_a+0.07W_b+0.8\]
subject to:
  1. $0.1W_a+0.3W_b = 0.2$
  2. $ W_a + W_b = 1$
Note that the individual expected returns and asset \betas are fixed subject to portfolio manager point of view because they are determined by the market. Weightings on the other hand are variable and at the discretion of the portfolio manager as it can be adjusted in order to achieve the objective. Therefore, the portfolio return and the portfolio risk can be engineered by the portfolio manager by adjusting the proportions of each asset in the portfolio.

Non LP Application

Investor requirements usually constrain the selection process. Thus, they can require that the risk to be minimized subject to the greater or acceptable level of expected return. Since the risk is a quadratic function of the variance of the security returns, a non LP optimization is needed. In mathematical terms, three asset portfolio optimization can be formally written as
\[ \text{Min} Z = W^T V W \]
subject to
  1. $W_a+W_b+W_c = 1$
  2. $W_aE(r_a)+W_bE(r_b)+W_cE(r_c) \ge R$
The objective function may look familiar as it is the variance of the portfolio. We are after all minimizing risk. The first constraint tells us that we want the assets to be fully invested. And the second constraint explains that we want the portfolio return to be greater than or equal to the minimum level of expected return.

Sample: Given a three asset portfolio whose
\[ V = \begin{bmatrix}
0.00015 & 0.0005 & -0.00007 \\
0.00005 & 0.00025 & -0.00003 \\
-0.0007 & 0.00003 & 0.00010
\end{bmatrix}\]
then, we have

\[ \text{Min} Z = W^T V W \]
subject to
  1. $W_a+W_b+W_c = 1$
  2. $0.11W_a+0.15W_b+0.08W_c \ge 0.11$
Here, we assume that the negative positions in each assets are not possible. We can also transform the OF function into
\[ \begin{align} \text{Min} Z &= 0.00015W_a^2 + 0.00025W_b^2+0.00010W_c^2\\
 &+0.00010W_aW_b-0.00014W_aW_c-0.0006W_bW_c \end{align}\]
subject to
  1. $W_a+W_b+W_c = 1$
  2. $0.11W_a+0.15W_b+0.08W_c \ge 0.11$
Source: Quantitative Methods in Finance by Watsham and Parramore

LP and Non-LP Issues

Linear Programming

  • Mathematical method used for optimization problems
  • Main applications are to maximize profits and minimize costs
  • Objective function is linear when:
    • Optimum always attained at constraint boundaries
    • A local optimum is also global optinum
  • Other applications
    • operational research - solve multi-commodity flow issues and network flow
    • strategic games - chess, manufacturing, resource conservation, transportation systems for buses and trains, and military budgeting
    • microeconomics
  • Assumptions:
    • all variables have non-negative values
    • A negative value will be written as a function of two non negative values
      • ie. If $x = -5$, then we let $x_1 = 0$, $x_2=5$ and assign $x = x_1 - x_2$
  • Advantages:
    • Works with inequalities with non negative coefficients. As long as the inequalities are changed into standard form
    • The simplex algorithm can determine if there is no solution to the problem (if pivot can't be made)
    • Algorithm is easy to program in a computer
  • Disadvantages:
    • The algorithm becomes inefficient if too many variables are used. It may require an exponential number of steps.
    • Strict inequalities might not work in LP
  • Example: same example as earlier, using x as the first pivot

Non Linear LP
  • Objective function is non linear when:
    • Optimum may be interior as well as at boundaries of constraint 
    • A local optimum is not necessarily the global optinum
  • Nonlinearity came from
    • multiplication of variables: economies of scale, transaction costs
    • quadratic terms: variances, interest rates mean-variance optimization
    • nonlinear functions: quantiles in common risk measures
  • Approach to nonlinear optimization: iterative method
    • Basic Numerical methods: Solving for non linear functions
    • Other methods: 
      • Steepest Descent Method
      • Newton's Method 
      • Quasi-Newton Method
      • Lagrange multipliers 
      • Conjugate Gradient Method
      • Penalty Function Method
  • In general, optimization problems are unsolvable.
  • "It's the user's responsibility to choose an algorithm that is appropriate for the specific applications
Take-aways
  • revised way of pivoting starting with $x$ in the simplex method
  • What if the constraints are less than the unknown? Will there be a difference in the simplex method?
  • Always check on the assumptions coz it might not gonna work because of wrong constraints
  • the answer might not be exactly the solution to the problem at hand. We might be creating more problems than the solution of the problems
  • Portfolio optimization technique - "robustness"
  • The methods are just tools for the user to use. The question is, is the user using the right tools for the problem at hand?

Resources: Class groups ppt.

History of Finance - Review

Based on Statistics, we can't be always at the top. Whatever we do, we influence the market. So we can't all be winners.
  • Pre-Markowitz - make money if your an insider.
    • Gerald Loeb 
      • the battle for investment survival
      • put all your eggs into one basket
    • John Maynard Keynes
      • Psychological Principle
      • The Greater Fool theory
      • Beauty Contest Analogue 
        •  based on perception, we ask the question: what will the judges judge?
        • what do you think the others will think?
        • even if I bought at a high price, some other fool will buy at a higher price
  • Markowtiz 
    • Issue before: How to measure returns
    • he introduced risk and how to put up a portfolio and maximize returns
    • significant is within the utility curve
    • Markowitz Paradox - utility curves 
  • Asset universe
    • Markowitz -diversification as the risk averse technique
    • James Tobins
      • optimum portfolio
      • don't put your eggs into one basket
      • reduce risk using the combination of the risk free rate and others
      • we can go outside the Markowitz area
      • Simplifying calculus - efficient frontiers labours on calculus
    • William Sharpe
      • Main feature is the stock market itself
      • risk that can be diversified away
      • CAPM - Eugene Fama uses the term "one factor model" to describe Sharpe's
  • Efficient Market
    • Prices fluctuate ramdomly
    • Eugene Fama - EMH, 1970
  • 1974
    • Paul Samuelson
      • calls for a benchmark
      • if can't beat them, join them
      • "Market Portfolio"
    • Charles Elis
      • Mimic the market - as a proxy for the market
      • the use of "index funds"
        • it manages the portfolio and costs
        • it means no more of the excess returns

Trying to figure out: How to deal with your investments by exerting Alpha.

Alpha - 
need not to look for weights
  • Beta - horizontal
  • Alpha - y - intercepts ( excess returns)
  • To what degree is the market beatable? Can the market be beaten
Hunt for a better mouse trap
  • Multi-factor model 
  • Macro-economic Factor Model
    • GDP+Analysis => asset allocation
    • Industry => asset allocation
  • Search for Arbitrage opportunities (buy and sell) and convergence trade (put and call options)
  • Search for market anomalies (e.g January effect, small cap effect, low P/B ratios)
  • Value vs growth Stocks, underlying stocks Not the company itself
  • Contrary strategies
  • Risk minimizing modeling (VAR)
References: Searching for Alpha by Ben Warwick
Films: Inside Job, Margin Call, Wall Street Never Sleeps, Wall Street, Too Big to Fail 

Monday, February 4, 2013

Averages, Covariance and Correlation

Recall:

These are some of the important group statistics for portfolio optimization.

1. Averages - a $1$ x $n$ matrix whose inputs are the average of each stocks.
2. Covariance Matrix - the vector product of the mean returns transpose and the mean return itself
3. Correlation Matrix  - $ {cov_{ij}} / {\sqrt{cov_{ii}cov_{jj}}} $

Using functions in VBA

Sub cov()
    Dim str As String
    str = Range("D3")
    
    'calling returns
    ret = Range(str)

    'counting columns
    c = UBound(ret, 2)
    
    'Writing Output
    
    Range("B5") = "Averages"
        'writing answer to averages
        Range("B6").Select
        ActiveCell.Range(Cells(1, 1), Cells(1, c)) = AveM(ret) 'it calls for the function Ave and paste it to a

    Range("B8") = "Covariance Matrix"
        'writing answer to covariance
        Range("B9").Select
        ActiveCell.Range(Cells(1, 1), Cells(c, c)) = CovarianceM(ret)
    
    Range("B" & 10 + c) = "Correlation Matrix"
        'writing answer to correlation
        Range("B" & 11 + c).Select
        cv = CovarianceM(ret)
        ActiveCell.Range(Cells(1, 1), Cells(c, c)) = CorrelationM(cv)
End Sub

Function AveM(ret)
    'summing up all values in each stock and then dividing it by the total number of returns
    
    'counting rows and columns
    r = UBound(ret)
    c = UBound(ret, 2)
        
    'creates 1xc array
    a = Range(Cells(1, 1), Cells(1, c))
    
    'summing up all values in row, then divide it by the row
    For j = 1 To c
        s = 0
        For i = 1 To r
            s = ret(i, j) + s
        Next i
        a(1, j) = s / r
    Next j
        'returns a as the average
        AveM = a
End Function

Function CovarianceM(ret)
    'covariance matrix  = (mean returns transpose x mean returns)/(n-1)
    
    'count rows and columns
    r = UBound(ret)
    c = UBound(ret, 2)
    
    'create dummy range for mean returns
    mret = Range(Cells(1, 1), Cells(r, c))
    
    'create dummy range for average and run the function Ave
    a = Range(Cells(1, 1), Cells(1, c))
    a = AveM(ret)
    
    'solving for mean returns
    For i = 1 To r
        For j = 1 To c
            mret(i, j) = ret(i, j) - a(1, j)
        Next j
    Next i
    
    'solving for transpose and the covariance matrix
    trans = Application.WorksheetFunction.Transpose(mret)
    covm = Application.WorksheetFunction.MMult(trans, mret)
    For i = 1 To c
        For j = 1 To c
            covm(i, j) = covm(i, j) / (r - 1)
        Next j
    Next i
    
    'returning the covariance matrix
    CovarianceM = covm
    
End Function

Function CorrelationM(covm)
    'Correlation Matrix cor_ij = cov_ij / [sqrt(cov_ii)*sqrt(cov_jj)]
    
    'count rows only since covm is an nxn matrix
    r = UBound(covm)
    
    'creating dummy range for cor_ij
    cor = Range(Cells(1, 1), Cells(r, r))
    
    'solving for correlation matrix
    For i = 1 To r
        For j = 1 To r
            cor(i, j) = covm(i, j) / (covm(i, i) * covm(j, j)) ^ (1 / 2)
        Next j
    Next i
    
    CorrelationM = cor
End Function


VBA: Matrix Lecture


Sub matrixP()

'putting the to matrix in an array
a = Range("b3:d5")
b = Range("g3:i5")

'applying matrix multiplication
m = Application.WorksheetFunction.MMult(a, b)
Range("b8:d10") = m

'counting rows and columns
r = Range("b3:d5").Rows.Count
c = Range("b3:d5").Columns.Count

'scalar multiplication
'has to define the array first

cvm = Range("B12:d14")
For i = 1 To r
    For j = 1 To c
        cvm(i, j) = m(i, j) / r
    Next j
Next i
Range("B12:d14") = cvm

________________________________________________________

End Sub

Sub Lecture()
'getting the average

'define returns
a = Range("b3:d5")

'define mean adjusted return
MARM = Range("b9:d11")


For j = 1 To 3
    'average
    m = 0
    For i = 1 To 3
        m = m + a(i, j)
    Next i
    ave = m / 3
    Range("a7").Offset(0, j - 1).Value = ave

    'mean returns
    For kount = 1 To 3
        MARM(kount, j) = a(kount, j) - ave
    Next kount
Next j

Range("B9:D11") = MARM


End Sub
________________________________________________________
Sub Macro3()

'diagonals 1-10
For i = 1 To 10
    Range("a1").Offset(i - 1, i - 1).Value = i
Next i


End Sub
________________________________________________________

Sub Macro4()

'row 10x1, 1-10
For i = 1 To 10
    Range("a" & i) = i
Next i

End Sub

VBA: Covariance Matrix 3

applying what we learned in class to the covariance matrix

This code contains:  averages, mean returns, covariance matrix and changing price to returns.

Sub Cov3()

    Dim ws As Worksheet
    Set ws = Sheets.Add
       
    ws.Range("A1") = "Covariance Matrix"

    ws.Range("A3") = "Prices:"
   
    'prices
    p = Worksheets("Sheet1").Range("B2:K100")
   
    'counting rows and columns
    r = Worksheets("Sheet1").Range("B2:K100").Rows.Count
    c = Worksheets("Sheet1").Range("B2:K100").Columns.Count
   
    'pasting price to ws
    ws.Range("A5").Select
    Set ans = ActiveCell.Range(Cells(1, 1), Cells(r, c))
    ans.Value = p
   
    'Returns
    ws.Range("M3") = "Returns"
       
    'rows of return
    r = r - 1
   
    ret = Range("M6:V103")
    For i = 1 To r
        For j = 1 To c
            ret(i, j) = p(i + 1, j) / p(i, j) - 1
        Next j
    Next i
    Range("M6:V103") = ret
   
    'getting the averages and mean returns
    ws.Range("X3") = "Average"
    ws.Range("AI3") = "Mean Returns"
   
    mret = ws.Range("AI6:AR103")
   
    For j = 1 To c
        'average
        s = 0
        For i = 1 To r
            s = s + ret(i, j)
        Next i
        ave = s / r
        Range("X6").Offset(0, j - 1).Value = ave

        'mean returns
        For kount = 1 To r
        mret(kount, j) = ret(kount, j) - ave
        Next kount
    Next j
   
    ws.Range("AI6:AR103") = mret
       
    'getting the covariance matrix
    ws.Range("AT3") = "Covariance"
    trans = Application.WorksheetFunction.Transpose(mret)
    covm = Application.WorksheetFunction.MMult(trans, mret)
    For i = 1 To c
        For j = 1 To c
            covm(i, j) = covm(i, j) / (r - 1)
        Next j
    Next i
   
    Range("AT6").Select
    Set ans = ActiveCell.Range(Cells(1, 1), Cells(c, c))
    ans.Value = covm
   
End Sub

Saturday, February 2, 2013

VBA: Covariance Matrix 2


Here is the second attempt in programming the covariance matrix. I still have problems with getting the returns and dynamic averages.


Sub COV2M()

    Dim ws As Worksheet
    Set ws = Sheets.Add
        
    ws.Range("A1") = "Covariance Matrix"

    ws.Range("A3") = "Prices:"
    
    'prices
    p = Worksheets("Sheet1").Range("B2:K100")
    
    'counting rows and columns
    r = Worksheets("Sheet1").Range("B2:K100").Rows.Count
    c = Worksheets("Sheet1").Range("B2:K100").Columns.Count
    
    'pasting price to ws
    ws.Range("A5").Select
    Set ans = ActiveCell.Range(Cells(1, 1), Cells(r, c))
    ans.Value = p
    
    'Returns
    ws.Range("M3") = "Returns"
        
    'rows of return
    r = r - 1
    
    ret = Range("M6:V103")
    For i = 1 To r
        For j = 1 To c
            ret(i, j) = p(i + 1, j) / p(i, j) - 1
        Next j
    Next i
    Range("M6:V103") = ret
    
    'getting the averages
    ws.Range("X3") = "Average"
    ave = ws.Range("X6:AG6")
    For j = 1 To c
        s = 0
        For i = 1 To r
            s = ret(i, j) + s
        Next i
        ave(1, j) = s / r
    Next j
    ws.Range("X6:AG6") = ave
    
    'getting the mean Returns
    ws.Range("AI3") = "Mean Returns"
    mret = ws.Range("AI6:AR103")
    For i = 1 To r
        For j = 1 To c
            mret(i, j) = ret(i, j) - ave(1, j)
        Next j
    Next i
    ws.Range("AI6:AR103") = mret
    
    'getting the covariance matrix
    ws.Range("AT3") = "Covariance"
    trans = Application.WorksheetFunction.Transpose(mret)
    covm = Application.WorksheetFunction.MMult(trans, mret)
    For i = 1 To c
        For j = 1 To c
            covm(i, j) = covm(i, j) / (r - 1)
        Next j
    Next i
    
    Range("AT6").Select
    Set ans = ActiveCell.Range(Cells(1, 1), Cells(c, c))
    ans.Value = covm
    
End Sub