Showing posts with label Optimization. Show all posts
Showing posts with label Optimization. Show all posts

Friday, April 5, 2013

Mock Trading: 2 Equity Allocation

Second part of the mock trading involves allocation of the equity. The details below is what we did in choosing the stocks and its weights.

Fund Size Description and Client Requirements - This contains the necessary requirements for the fund. This is necessary as policy statement goes.

Philippine Stock Market Outlook - As we recall, we found out that Consumer Staples, Utilities, Financials, Real Estate and Tourism are the sectors that are favorable to invest in. Moreover, analyzing the PSEi risk return statistics using monthly rolling annual log returns, each sector has something to give as the stock market today is very attractive. Applying the optimizer, by minimizing the variance subject to the constraints by the fund and client requirements and expected return greater than 15%, we found out that it is advisable to invest in Holding firms, Mining and oil and Services.

Stock Selection Screening - Furthermore, we analyzed each stock per sector that is found in the PSE. The bullets below are the things that we did in our analysis.
  • Fundamentals - we analyzed each of the stocks by using different ratios based on whether the stock is Cheap or Not, its Liquidity, Leverage, Growth and if it pays Dividend or not. Also, specific ratios are used depending on what sector we are analyzing. ie. for banks, we used P/B as for holding firms we used P/B and P/E.
  • Technicals - we just looked at the periods from 2007 onwards whether the stocks  is a bull or in the bear market
  • Risk Return Statistics - here we looked at the volatility, mean return and the sharpe ratio like what we did above in the Phil Stock Market outlook. 
  • Other Analyst Consensus - we also considered other analyst consensus using Reuters.
  • Optimization per Sector - same as Phil stock market outlook, we use the optimizer in each stocks per sector to minimize risk subject to the return greater that 15% and fund and client requirements. It determines the possible weights for each stocks and the stocks that we can pick for the investment. 
After all the analyzing, we found out that some of the weights considered in the optimization did not coincide to the other analyses. As such, we override the values of the optimization as to give in to the consideration mostly on the fundamentals. With so much contemplation, we choose stocks in the PSEi and added more stocks that we think are attractive. We did this so that we really have a very diversified portfolio. Also, we based our weights on the Stock Screening Process and the Portfolio manager had the final say. Final picks and weights are in Slide 14 to 16. 

In choosing those stocks, we are glad to report that after doing the correlation matrix, most of them are uncorrelated and we had a portfolio return of 24.66, which is above the said requirements. 

Thursday, February 14, 2013

PCA and FA II

As the book by watsham tells us, PCA has two objectives:

  • to reduce the dimensionality
  • to interpret data.
Now I got confused with the reducing the dimensionality. As far as i know, it can only reduce linear combinations as non significant proportions of variability are eliminated. So I looked it up in myriad sources and found how can it actually reduce the dimensions.

This is how I got enlightened:

Let's say I have 100 stocks returns in an index and wanted to reduce or squeeze it into two or three variables. Since I have 100 stock returns, then I have also 100 principal components. The first of which (who has the highest eigenvalue) accounts for the highest variance and the 100th principal component accounts for the least as it is already ranked.  Note that what PCA do is it makes the principal components uncorrelated to each other. That means that even if the returns (input) itself is highly correlated as assumed, the principal components(output) which explains the variance are not.

There are two ways to do PCA. First is the eigenvalue decomposition (in the previous posts) and the other is  the singular value decomposition (still have to to research on this). Once we figure out the PC's that explain the majority of the variance, those PC's can serve as dependent variables in a regression. 

How is it different to factor analysis?

Even though PCAs appears to have "mathematically intuition", it is somehow lacks to have the "economic intuition". As I have understood, the PCA is only a subset of FA. FA group together variables according to its variability and in assumption that those variables are somewhat related or show characteristics that are the same.

Sources:
CAPM vs APT:
http://www.r-bloggers.com/principal-component-analysis-use-extended-to-financial-economics-part-2/

http://programming-r-pro-bro.blogspot.com/2011/10/principal-component-analysis-use.html

PCA and FA I

Principal Components Analysis 
    - answers the question " what are the major contributors to the overall variability?"
    - so we look at the "dependent" variables and analyze them


Sample Application:

  • Age Groups as variable - who among the age group contributes more. 
  • What moves the bond return the most? 
    • First, we make a lot of guesses on the x's variables such as:
      • tenor
      • coupon rate
      • yield
      • credit rating
      • duration
      • demand for the bond
      • inflation expectation
      • supply
      • money supply
      • political stability
      • GDP expectation
    • Next, we eliminate the some of the variables based on redundancy, data, etc.
      • credit ratings are all risk free (means 0 variance), so we eliminate it.
      • demand and supply are related. It can be considered as one. 
      • political stability is not measurable.
    • Then, we determine the data for the other variables as they are measurable
      • tenor
      • coupon rate
      • yield
      • duration
      • demand and supply for the bond - bid ask spread
      • inflation expectation - BSP futures curve or consensus estimate for GDP
      • money supply - entry growth BSP
      • GDP expectation 
    • we now can apply PCA to the variables
Applying PCA to the x variables
  • From the variance-covariance matrix, we get the correlation matrix. It is so because the data needs to be normalized first and we are able to achieve it by dividing the data by the standard deviation. And correlation matrix is the standardized form of the variance-covariance matrix.
  • Then get eigenvectors and the eigenvalues.
    • Eigenvectors - produce the matrix of linear combinations 
    • Eigenvalues - its total sum is the total number of variables in the standardized matrix
    • each eigenvector (linear combination) has its own eigenvalue 
  • Interpretation of the eigenvectors and the eigenvalues
    • divide the each eigenvalue by its sum gives us the proportion that eigenvector accounts to the total variance. The higher the proportion the more significant its contribution to the total variability. 
    • Some says that getting eigenvalues greater than 1 are the ones that are significant. So we disregard the ones that are less than one since they are not significant.
  • As application in portfolio management, this gives the portfolio manager the opportunity to adjust the weights of the portfolio components so as to reduce the element of risk.
  Factor Analysis
  • main focus: summarization and data reduction
  • Given the variables, it answers the question "What drives the variables?"
  • this analysis is an ends by itself  or can be a part of a process
  • Stock = A Factor1 + B Factor2 + C Factor3, where the factors are the groups.
Example: 

Given stocks 1-10, (in the dummy stocks excel, and quant prof) we apply factor analysis. First we get the correlation matrix from group statistics, and then apply factor analysis with the correlation matrix.

From the unrotated loadings, we determine each group or factor by ranking as shown on the example below.


There are other ways to get the factor analysis. What is important is that we know how to analyze the data given.

This can be one of the individual projects. can also be ANOVA, test of hypothesis, etc.

PCA and FA application - factoranalysis.xlsx

Consider the linear combinations of 3 factors given below. We assumed that there are 3 factors affecting stockA, B and C.


For Problem1, we want to find the weights to invest in stock A,B and C, considering equal returns for the three stocks. For Problem2, we want to find the weights to invest in stock A,B and C, considering only Stock C returns. This is called one factor analysis. For Problem3, we want to find the weights to invest in stock A,B and C, considering only Stock A and half of Stock C returns. The problem is summarized on the table below.

 Solution:

To solve for the weights, we used the "matrix OLS" as a solution.
\[\hat{y} = \hat{x}\hat{b} \to \hat{b} = \hat{x}^{-1}\hat{y}\]
 In this case $\hat{y}$ is our expected returns, $\hat{b}$ is our weights and \hat{x} is the factors affecting the returns.

With problem 1, we applied multi-factor sensitivity as all of the factors and stocks are considered. After solving for the weights, we have to buy 47% of stock A, sell 77% of stock B and buy 145% of Stock C. Also it is found that we have to borrow 15% since the total sum of the weights is 115%.

Problem 2 only considered Stock C. When we do this, one factor sensitivity is used. As a result in finding for the weights, we have to sell 145% and 174% for stocks A and C respectively. (Can we sell what we don't have??) The total sum of the weights are 9% meaning it is not fully allocated.
 

Problem 3 considers a return for Stock A and half of Stock C only. This results to allocating 60%, 130% and -134% to the stocks A, B and C respectively. Total sum of the weights is 55% which pertains to the total allocation.



Sources: ppt class presentations, class lectures and quantprof VBA

PCA and FA Intro

Difference between PCA and FA to Others

Recall:

Multiple Regression (MR): relationship between an exogenous variable and many endogenous variable

Cointegration: endogenous variables are stationary (means the joint probability distribution does not shift through time and space, mean and variance remain constant throughout time and position)

Mean-Variance Analysis: measures the total collective variability of a group of variables, without specifically identifying which subgroups contribute to that variability

PCA and FA
  • compared to MR examines only the endogenous variables
  • compared to Cointegration it may not need to be stationary
  • compared to Mean-Variance Analysis, PCA identify and rank subgroups and their contribution to the total variability
  • Both uses variance-covariance matrix
Characteristics of Mutivariate Statistics
  • Volatility in the multivariate structure
  • Correlation or colinearity between variables
Principal Components Analysis

- volatility of multivariate structure is measured and analyzed
- total variability is measured by the sum of the eigenvalues (sum of the diagonals in the matrix)

Factor Analysis
- correlation between the variables of  a multivariate structure is analyzed

Sources: Quantitative Methods in Finance by Watsham and Parramore

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

VBA: Matrix Operations

Since I still don't know how to let the user specify the "range" in a matrix, but I was eager to do something productive, here's what I came up with:

Given to Matrices, find:

1. Sum
2. Scalar Multiplication
3. Matrix Multiplication
4. Inverse
5. Transpose

I'm having difficulty with Inverse as I am having a runtime error '1004': Unable to get the MInverse property of the WorksheetFunction class. somehow, the help button doesn't work. I do know the code is correct. I just have to get why I am having such errors.


Sub MatrixPractice()
    
    matrixA = Range("A1:J10")
    matrixB = Range("L1:U10")

    
    'Count Rows and Columns
    rA = Range("A1:J10").Rows.Count
    rB = Range("L1:U10").Rows.Count
    
    cA = Range("A1:J10").Columns.Count
    cB = Range("L1:U10").Columns.Count
    
    'checker for same m x n
    If Not rA = rB And cA = cB Then
        MsgBox "can't do operations with the two matrices"
        Exit Sub
    Else
        r = rA
        c = cA
    End If
    
    'Sum
    sum = Range("B14:K23")
    Range("A13") = "Sum"
    For i = 1 To r
        For j = 1 To c
            sum(i, j) = matrixA(i, j) + matrixB(i, j)
        Next j
    Next i
    Range("B14:K23") = sum
    
    'Multiplication
    scalarM = Range("B26:K35")
    Range("A25") = "Scalar Multiplication"
    For i = 1 To r
        For j = 1 To c
            scalarM(i, j) = matrixA(i, j) * matrixB(i, j)
        Next j
    Next i
    Range("B26:K35") = scalarM
    
    'Mmult
    MMult = Application.WorksheetFunction.MMult(matrixA, matrixB)
    Range("A37") = "Matrix Multiplication"
    Range("B38:K47") = MMult
    
    'Inverse have to work on it
    'inv = Application.WorksheetFunction.MInverse(matrixB)
    'Range("A49") = "Matrix B Inverse"
    'Range("B50:K59") = inv

    'Transpose
    tran = Application.WorksheetFunction.Transpose(matrixB)
    Range("A61") = "Matrix B Transpose"
    Range("B62:K71") = tran

End Sub




Friday, February 1, 2013

VB: Covariance Matrix

This is getting the Covariance Matrix using the Record Macro. It is to analyze how it is being done in VBA.

Sub CovMatrix()
'
' CovMatrix Macro
' Fixed, Relative References is not used
'
    Range("B2").Select
    ActiveCell.FormulaR1C1 = "Covariance Matrix given Prices"
    
    'Prices
    Range("B4").Select
    ActiveCell.FormulaR1C1 = "1. Get the Prices"
    Range("B6").Select
    Sheets("Sheet1").Select
    Range("K100").Select
    ActiveWindow.SmallScroll Down:=-24
    ActiveWindow.ScrollRow = 46
    ActiveWindow.ScrollRow = 45
    ActiveWindow.ScrollRow = 43
    ActiveWindow.ScrollRow = 41
    ActiveWindow.ScrollRow = 39
    ActiveWindow.ScrollRow = 38
    ActiveWindow.ScrollRow = 36
    ActiveWindow.ScrollRow = 34
    ActiveWindow.ScrollRow = 32
    ActiveWindow.ScrollRow = 30
    ActiveWindow.ScrollRow = 28
    ActiveWindow.ScrollRow = 25
    ActiveWindow.ScrollRow = 23
    ActiveWindow.ScrollRow = 21
    ActiveWindow.ScrollRow = 18
    ActiveWindow.ScrollRow = 16
    ActiveWindow.ScrollRow = 14
    ActiveWindow.ScrollRow = 12
    ActiveWindow.ScrollRow = 10
    ActiveWindow.ScrollRow = 7
    ActiveWindow.ScrollRow = 6
    ActiveWindow.ScrollRow = 4
    ActiveWindow.ScrollRow = 2
    ActiveWindow.ScrollRow = 1
    Range("B2").Select
    Range(Selection, Selection.End(xlToRight)).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Sheets("VBA").Select
    ActiveSheet.Paste
    Range("N4").Select
    Application.CutCopyMode = False
    
    'Returns
    ActiveCell.FormulaR1C1 = "2. Change it into Returns"
    Range("N7").Select
    ActiveCell.FormulaR1C1 = "=RC[-12]/R[-1]C[-12]-1"
    Range("N7").Select
    Selection.Copy
    Range("N8:W104").Select
    ActiveSheet.Paste
    Range("O7:W7").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False
    
    'Averages
    Range("Y4").Select
    ActiveCell.FormulaR1C1 = "3.Get the Averages"
    Range("Y7").Select
    ActiveCell.FormulaR1C1 = "=AVERAGE(RC[-11]:R[97]C[-11])"
    Range("Y7").Select
    Selection.Copy
    Range("Z7:AH7").Select
    ActiveSheet.Paste
    Range("Y7:AH7").Select
    Application.CutCopyMode = False
    
    'Mean adjusted Return
    Range("AJ4").Select
    ActiveCell.FormulaR1C1 = "4.Mean Adjusted Returns"
    Range("AJ7").Select
    ActiveCell.FormulaR1C1 = "=RC[-22]-R7C[-11]"
    Range("AJ7").Select
    Selection.Copy
    Range("AJ8:AJ104").Select
    ActiveSheet.Paste
    Range("AK7:AS104").Select
    ActiveSheet.Paste
    Range("AU5").Select
    Application.CutCopyMode = False
    
    'covariance Matrix
    Range("AU4").Select
    ActiveCell.FormulaR1C1 = "5. Get the Covariance matrix"
    Range("AU7:BD16").Select
    Selection.FormulaArray = _
        "=MMULT(TRANSPOSE(RC[-11]:R[97]C[-2]),RC[-11]:R[97]C[-2])/(COUNT(RC[-11]:R[97]C[-11])-1)"
    ActiveWindow.ScrollRow = 75
    ActiveWindow.ScrollRow = 74
    ActiveWindow.ScrollRow = 73
    ActiveWindow.ScrollRow = 72
    ActiveWindow.ScrollRow = 71
    ActiveWindow.ScrollRow = 70
    ActiveWindow.ScrollRow = 69
    ActiveWindow.ScrollRow = 67
    ActiveWindow.ScrollRow = 66
    ActiveWindow.ScrollRow = 65
    ActiveWindow.ScrollRow = 64
    ActiveWindow.ScrollRow = 62
    ActiveWindow.ScrollRow = 60
    ActiveWindow.ScrollRow = 58
    ActiveWindow.ScrollRow = 57
    ActiveWindow.ScrollRow = 55
    ActiveWindow.ScrollRow = 54
    ActiveWindow.ScrollRow = 53
    ActiveWindow.ScrollRow = 52
    ActiveWindow.ScrollRow = 50
    ActiveWindow.ScrollRow = 49
    ActiveWindow.ScrollRow = 48
    ActiveWindow.ScrollRow = 47
    ActiveWindow.ScrollRow = 46
    ActiveWindow.ScrollRow = 45
    ActiveWindow.ScrollRow = 44
    ActiveWindow.ScrollRow = 43
    ActiveWindow.ScrollRow = 42
    ActiveWindow.ScrollRow = 41
    ActiveWindow.ScrollRow = 40
    ActiveWindow.ScrollRow = 38
    ActiveWindow.ScrollRow = 37
    ActiveWindow.ScrollRow = 35
    ActiveWindow.ScrollRow = 33
    ActiveWindow.ScrollRow = 32
    ActiveWindow.ScrollRow = 30
    ActiveWindow.ScrollRow = 28
    ActiveWindow.ScrollRow = 26
    ActiveWindow.ScrollRow = 25
    ActiveWindow.ScrollRow = 23
    ActiveWindow.ScrollRow = 21
    ActiveWindow.ScrollRow = 19
    ActiveWindow.ScrollRow = 17
    ActiveWindow.ScrollRow = 15
    ActiveWindow.ScrollRow = 14
    ActiveWindow.ScrollRow = 12
    ActiveWindow.ScrollRow = 11
    ActiveWindow.ScrollRow = 10
    ActiveWindow.ScrollRow = 9
    ActiveWindow.ScrollRow = 8
    ActiveWindow.ScrollRow = 7
    ActiveWindow.ScrollRow = 6
    ActiveWindow.ScrollRow = 5
    ActiveWindow.ScrollRow = 4
    ActiveWindow.ScrollRow = 3
    ActiveWindow.ScrollRow = 2
    ActiveWindow.ScrollRow = 1
    ActiveWindow.LargeScroll ToRight:=-1
    ActiveWindow.ScrollColumn = 12
    ActiveWindow.ScrollColumn = 14
    ActiveWindow.ScrollColumn = 15
    ActiveWindow.ScrollColumn = 16
    ActiveWindow.ScrollColumn = 17
    ActiveWindow.ScrollColumn = 18
    ActiveWindow.ScrollColumn = 19
    ActiveWindow.ScrollColumn = 20
    ActiveWindow.ScrollColumn = 21
End Sub

Thinking of a dynamic way to program this Covariance. Somehow copy and paste seems to be the easier way. Though when reading the code by itself and applying it using relative references, it doesn't make sense. So I have to go back to arrays and matrices.

MPT and Asset Allocation

Modern Portfolio Theory

It's a good thing the group reported  Modern Portfolio Theory.

Additional Information:
  • In the optimization $\text{min } \sigma = w^T V w $, the inputs in the diagonal of the covariance matrix $V$ are variances.
  • It is important to ask the questions: How did they defined the data used? What constitutes returns? It is not that simple and we have to be objective. We must based it on empirical data and past research.
  • What is the use of the Tangency Portfolio? Why is CAL included in the efficient frontier graph?     
    The edited graph are copied in Wiki.

    • Every stock's expected return is determined by its beta with the tangent portfolio
    • Tangent portfolio by definition has the highest SR
    • MPT shows only one method of diversifying: managing risk and return. IRL, there are other ways such as go in and out of the market. Since, CAL connects the risk free rate to the tangency portfolio. The highlighted portion is the combination of the risk-free rate and the tangent portfolio which is found to be a way to diversify with a lower risk and still be in the efficient frontier. 
  • Any of the portfolios in the upper portion of the $y^2$ curve can beat the market.
  • SML - because everyone is buying the market, risk is how much is the market exposure. 
  • Empirical data and results shows that MPT is just as it is, a theory. No one can really define and measure the "global market". Some even tested the capacity of CAPM and it doesn't work.

Exercises - found in MPT.xlsm for more info


1. Optimization $\text{min } \sigma = w^T V w $ in Excel. 


2. Covariance

Ways of getting covariance:

In class, we got the covariance of two stocks using the long way and the short way. Details are in the excel sheet. It contains 10 stock returns with an n of 99.
  • =COVARIANCE.S(array1, array2)
  • =COVARIANCE.P(array1, array2)
  • =SUM(x-u_x)(y-u_y)/n
Covariance Matrix

It was also analyzed how the covariance came up to be. 
  • It is the matrix multiplication of the mean adjusted return transpose by the mean adjusted return then divided the number of returns
  • In short: =mmult(MARTranspose, MAR)/N
Somehow, there are some discrepancies on the numbers I computed for the matrix to the QuantProf, the predefined function made my my prof. But it is very small. Later I found out that some defined =mmult(MARTranspose, MAR)/(N-1) to solve for the covariance matrix.

Other references: Quantitative Methods in Finance by Watsham 


Asset Allocation
  • Policy Statement should be there in every portfolio.
  • Over long periods of time, sizable allocation to equity will improve results.
  • Asset allocation determines your return. It is the overall asset allocation that is important.
Other references involve the previous research material used and a ppt presentation made by another group.

Searching for Alpha

Good reference: Searching for Alpha by Ben Warwick
  • History of Finance: Review
  • Important people that helped in shaping up the Finance world
  • We are trying to figure out how to deal with our investments. Are we satisfied with the the allocation? To what degree is the market predictable? 
  • Instead of looking for the weights, we look at alpha.
    • where alpha is the excess returns, y-intercepts
    • beta is the slope.
  • Hunt for a better 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)

LP: Simplex Method

Maximization

How lucky my sister was for waking me up at the middle at the night to teach her the simplex method, in the matrix way for her exam in a few hours. How luckier I am, it is one of the class topics we were about to discuss allowing me to recall on some things. 

Here is a simple maximization problem from her book. All we needed to do after the first table is to make the $2$ x $2$ matrix on the upper left an identity matrix and the last $1$ x $2$ matrix on the lower left, zeroes. Remember that these are equations so the "elimination via matrix" is applied.



Minimization

For minimization problems, a little tweaking is needed. Example, if you are given
 \[ \text{min } z = 0.15x_1+0.12x_2\]
with constraints
\[ \begin{split} 60x_1 +60x_2 & \geq 300 \\ 12x_1 + 6x_2 & \geq 36 \\ 10x_1 + 30x_2 & \geq 90 \end{split} \]
then we have the matrix
\[ \begin{bmatrix} 60 & 60 & \vdots & 300 \\ 12 & 6 & \vdots & 36 \\ 10 & 30 & \vdots & 90 \\ \cdots &\cdots & \vdots & \cdots \\ 0.15 & 0.12 & \vdots & 0\\ \end{bmatrix} \]
The transpose of this matrix will give you a maximization problem and the rest of the process is the same as earlier.  

Application - Simplex method Application varies from business to business and are commonly used.

Links for more info is provided below: 
http://pages.intnet.mu/cueboy/education/notes/algebra/simplex.htm
http://college.cengage.com/mathematics/larson/elementary_linear/5e/students/ch08-10/chap_9_3.pdf
http://college.cengage.com/mathematics/larson/elementary_linear/5e/students/ch08-10/chap_9_4.pdf

Wednesday, January 30, 2013

VBA: Numerical Methods

The best way that I can learn VB is by practice and just get on with it. I never realized that starting something and ending something is harder than the in between process. Good thing it is object-oriented and somehow close to Java. They are almost alike. But not all. Sobrang nangapa ako sa codes and shortcuts. It's been a very long time since I did some programming.

VBA Shorcuts
  • Alt-F11 - Activate VBE
  • F5 - Execute Module
The formulas are assumed to be correct. If I put on another char like $y$ in the formula, there will be an error. I can't seem to fix this. Here are the codes:

Colorit.bas


Something Fun. Coloring the highlighted Red. Just learning on the buttons.

Sub Red()
'
' Red Macro
'
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 192
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Sub

Sub NoFill()
'
' NoFill Macro
'
'
    With Selection.Interior
        .Pattern = xlNone
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
End Sub

Bisection.bas

This contain some of the functions found in the other methods. i didn't include it anymore in the other methods.


Sub Bisectiontest()
    
    'ASSUME THAT THE FORMULA IS CORRECT
    '0nly after 1000 iterations of f(x) = 0
    
    form = Range("D4")
    a = Range("E6").Value
    b = Range("E7").Value
     
    'checks the inputs
    If Inputx(form, 0, a, b) = False Then
        MsgBox "Please check your inputs"
        Exit Sub
    'wrong property of bisection
    ElseIf Px(form, a) * Px(form, b) > 0 Then
        MsgBox "Please change your interval"
        Exit Sub
    Else
        'applying the method
        Call Bisection(form, a, b)
    End If
    
End Sub

Public Function Inputx(form, form2, a, b) As Boolean
    'Missing input
    If form = "" Or form2 = "" Or a = "" Or b = "" Then
        Inputx = False
    'wrong input on interval
    ElseIf a Like "[A-Z,a-z]" Or b Like "[A-Z,a-z]" Then
        Inputx = False
    Else
        Inputx = True
    End If
    
End Function

Public Function Px(f, x)
    'This is to evaluate the x variable only
    
    'replacing x with the value
    f1 = Application.WorksheetFunction.Substitute(f, "x", x)
    
    'evaluate the string
    Px = Evaluate(f1)
    
End Function

Private Sub Bisection(form, a, b)
    
    Static counter As Integer
    xn = (a + b) / 2
    fa = Px(form, a)
    fxn = Px(form, xn)
    fb = Px(form, b)
    
    'stop with 1000 iteration
    counter = counter + 1
    If counter = 1000 Then
       Range("F9").Value = xn
        Exit Sub
    Else
    
    'checker for next iteration
    'assigning new a or b
    
        If fa = 0 Then
            Range("F9").Value = a
        ElseIf fxn = 0 Then
            Range("F9").Value = xn
        ElseIf fb = 0 Then
            Range("F9").Value = b
        ElseIf fa * fxn < 0 Then
            b1 = xn
            Call Bisection(form, a, b1)
        Else
            a1 = xn
            Call Bisection(form, a1, b)
        End If
    End If
End Sub

Newton.bas


Sub Newtontest()
    'ASSUME THAT THE FORMULAS inputed are CORRECT
    '0nly after 1000 iterations of f(x) = 0
    
    form = Range("E5")
    form2 = Range("E6")
    a = Range("F8").Value
     
    'checks the inputs
    If Inputx(form, form2, a, 0) = False Then
        MsgBox "Please check your inputs"
        Exit Sub
    'property of newton
    ElseIf Px(form2, a) = 0 Then
        MsgBox "Please change your x. The first derivative is 0."
        Exit Sub
    Else
        'applying the method
        Call Newton(form, form2, a)
    End If
End Sub

Private Sub Newton(form, form2, a)
    
    Static counter As Integer
    
    f = Px(form, a)
    fprime = Px(form2, a)
    
    'stop with 1000 iteration
    counter = counter + 1
    If Not counter = 1000 Then
        'checker for next iteration
        'assigning new xn
        If f = 0 Then
            Range("G10").Value = a
        Else
            xn = a - (f / fprime)
            Call Newton(form, form2, xn)
        End If
    Else
        Range("G10").Value = a
        Exit Sub
    End If
End Sub

Secant.bas


Sub Secanttest()
    'ASSUME THAT THE FORMULAS inputed are CORRECT
    '0nly after 1000 iterations of f(x) = 0
    
    form = Range("E5")
    x1 = Range("F7").Value
    x2 = Range("F8").Value
    
    'checks the inputs
    If Inputx(form, 0, x1, x2) = False Then
        MsgBox "Please check your inputs"
        Exit Sub
    'property of secant
    ElseIf Px(form, x1) = Px(form, x2) Then
        MsgBox "f(x1) = f(x2). Please change your points"
        Exit Sub
    Else
        'applying the method
        Call Secant(form, x1, x2)
    End If
End Sub

Private Sub Secant(form, x1, x2)
    
    Static counter As Integer
    
    f1 = Px(form, x1)
    f2 = Px(form, x2)
    
    'stop with 1000 iteration
    counter = counter + 1
    If Not counter = 1000 Then
        'checker for next iteration
        'assigning new xn
        If f1 = 0 Then
            Range("G10").Value = x1
        ElseIf f2 = 0 Then
            Range("G10").Value = x2
        Else
            xn = x2 - f2 * ((x2 - x1) / (f2 - f1))
            Call Secant(form, x2, xn)
        End If
    Else
        Range("G10").Value = x2
        Exit Sub
    End If
End Sub

Fixedpoint.bas


Sub Fixedpointtest()
    'ASSUME THAT THE FORMULAS inputed are CORRECT
    '0nly after 1000 iterations of f(x) = 0
    
    form = Range("E5")
    form2 = Range("E6")
    a = Range("F8").Value
     
    'checks the inputs
    If Inputx(form, form2, a, 0) = False Then
        MsgBox "Please check your inputs"
        Exit Sub
    Else
        'applying the method
        Call Fixedpoint(form, form2, a)
    End If
End Sub

Private Sub Fixedpoint(form, form2, a)
    
    Static counter As Integer
    
    f = Px(form, a)
    g = Px(form2, a)
    
    'stop with 1000 iteration
    counter = counter + 1
    If Not counter = 1000 Then
        'checker for next iteration
        'assigning new xn
        If f = g Then
            Range("G10").Value = a
        Else
            xn = g
            Call Fixedpoint(form, form2, xn)
        End If
    Else
        Range("G10").Value = a
        Exit Sub
    End If
End Sub

I realized how i missed programming. Its so much different that recording it into a macro. Although that helps but you can't define a function or apply my own kinda style in programming. Maybe a mixture of the two can help me this time.