# Tag Archives: Programming

## Portfolio Optimization with fPortfolio

fPortfolio contains a number of function to make portfolio optimization easier. I can compare the results I get from the functions in fPortfolio to the results from my function from the previous post. I don’t expect them to be exactly the same, but they should be broadly similar.

First, install and load the package:
install.packages(‘fPortfolio’)
library(‘fPortfolio’)

Next, you need to build a returns matrix for the securities you are interested in. You can create return vectors for the different tickers (using methods from an earlier post) and then combine them together using cbind(). The function I wrote in the previous post also returns a matrix of security returns, so you can just use that code as well.

This is the function for the tangency or (highest Sharpe ratio) portfolio:
tangencyPortfolio(as.timeSeries(matrix),constraints=’maxW[1:9]=0.2′)

Here I set the same constraints as in the function I wrote. maxW[1:9]=0.2 says that for securities from 1 to 9 (which is all of them) set the maximum weight for each of them as 20%.

The output from this function call is:

Title:
MV Tangency Portfolio
Estimator: covEstimator
Optimize: minRisk
Constraints: maxW

Portfolio Weights:
0.0000                0.0000                 0.2000                0.0335         0.2000
0.2000               0.1760                  0.1905               0.0000

Covariance Risk Budgets:
0.0000                0.0000                0.1301               0.0286           0.1409
0.2407               0.1773                0.2823                0.0000

Target Return and Risks:
mean        mu        Cov      Sigma      CVaR       VaR
0.0006   0.0006  0.0161   0.0161   0.0398   0.0224

This obviously runs much faster, and gives greater and more readable information than the function I wrote. Oh well. It is interesting to see that the weights given for a couple of the securities are different. Not having read the code written by the authors of this function, I am more inclined to trust the results of the brute force function I wrote, however the difference is most likely due to different covariance estimation methods/procedures.

It is commonly known that portfolio weights in a Markowitz mean-variance optimization framework are very sensitive to the estimated means and covariances, and even differences in rounding can lead to fairly different weights. Also, technically, we are supposed to be using expected returns as input and not historical returns. Using historical returns assumes that the returns of each period are independent, come from the same distribution and sample the true distribution of the security. All of these assumptions can be very easily shown to be false.

In the next post, I will experiment with some of the graphs and plots we can make using fPortfolio.

Filed under Finance, Portfolio Optimization

## Portfolio Optimization

Changing tracks, I want to now look at portfolio optimization. Although this is very different from developing trading strategies, it is useful to know how to construct minimum-variance portfolios and the like, if only for curiosity’s sake. Also, just a -I hope unnecessary- note, portfolio optimization and parameter optimization (which I covered in the last post) are two completely different things.

Minimum-variance portfolio optimization has a lot of problems associated with it, but it makes for a good starting point as it is the most commonly discussed optimization technique in classroom-finance. One of my biggest issues is with the measurement of risk via volatility. Security out-performance contributes as much to volatility -hence risk- as security under-performance, which ideally shouldn’t be the case.

First, install the package tseries:
install.packages(‘tseries’)

The function of interest is portfolio.optim(). I decided to write my own function to enter in a vector of tickers, start and end dates for the dataset, min and max weight constraints and short-selling constraints. This function first processes the data and then passes it to portfolio.optim to determine the minimum variance portfolio for a given level of return. It then cycles through increasingly higher returns to check how high the Sharpe ratio can go.

Here is the code with comments:

```minVarPortfolio= function(tickers,start='2000-01-01',end=Sys.Date(),
riskfree=0,short=TRUE,lowestWeight=-1,highestWeight=1){

require(tseries)

#Initialize all the variables we will be using. returnMatrix is
#initailized as a vector,with length equal to one of the input
#ticker vectors (dependent on the start and end dates).
#Sharpe is set to 0. The weights vector is set equal in
#length to the number of tickers. The portfolio is set to
#NULL. A 'constraint' variable is created to pass on the
#short parameter to the portfolio.optim function. And vectors
#are created with the low and high weight restrictions, which
#are then passed to the portfolio.optim function as well. ##

returnMatrix=vector(length=length(getSymbols(tickers[1],
auto.assign=FALSE,from=start,to=end)))
sharpe=0
weights=vector(,length(tickers))
port=NULL
constraint=short
lowVec=rep(lowestWeight,length(tickers))
hiVec=rep(highestWeight,length(tickers))

#This is a for-loop which cycles through the tickers, calculates
#their return, and stores the returns in a matrix, adding
#the return vector for each ticker to the matrix

for(i in 1:length(tickers)){
temp=getSymbols(tickers[i],auto.assign=FALSE,from=start,to=end)
if(i==1){
}
else{
}
}

returnMatrix[is.na(returnMatrix)]=0
it

#This for-loop cycles through returns to test the portfolio.optim function
#for the highest Sharpe ratio.
for(j in 1:100){

#Stores the log of the return in retcalc
retcalc=log((1+j/100))
retcalc=retcalc/252
print(paste("Ret Calc:",retcalc))

#Tries to see if the specified return from retcalc can result
#in an efficient portfolio
try(port<-portfolio.optim(returnMatrix,pm=retcalc,shorts=constraint,
reslow=lowVec,reshigh=hiVec,riskfree=riskfree),silent=T)

#If the portfolio exists, it is compared against previous portfolios
#for different returns using the #Sharpe ratio. If it has the highest
#Sharpe ratio, it is stored and the old one is discarded.
if(!is.null(port)){
print('Not Null')
sd=port\$ps
tSharpe=((retcalc-riskfree)/sd)
print(paste("Sharpe",tSharpe))

if(tSharpe>sharpe){
sharpe=tSharpe
weights=port\$pw
}}

}
print(paste('Sharpe:', sharpe))
print(rbind(tickers,weights))
return(returnMatrix)

}```

Created by Pretty R at inside-R.org

This code works fine except for when the restrictions are too strict, the portfolio.optim function can’t find a minimum variance portfolio. This happens if the optimum portfolio has negative returns, which my code doesn’t test for. For this reason, I wanted to try out other ways of finding the highest Sharpe portfolio. There are numerous tutorials out there on how to do this. Some of them are:

After I run my function, with the following tickers and constraints:

matrix=minVarPortfolio(c(‘NVDA’, ‘YHOO’, ‘GOOG’, ‘CAT’, ‘BNS’, ‘POT’, ‘STO’, ‘MBT’ ,’SNE’),lowestWeight=0,highestWeight=0.2,start=’2000-01-01′, end=’2013-06-01′)

This is the output I get:

[1] “Sharpe: 0.177751547083007”

tickers                “NVDA”                                   “YHOO”                        “GOOG”
weights “-1.58276161084957e-19”      “2.02785605793095e-17”           “0.2”
tickers                 “CAT”                                       “BNS”                           “POT”
weights “0.104269676769825”                           “0.2”                             “0.2”

tickers                 “STO”                                       “MBT”
weights “0.189985091184918”             “0.105745232045257”

tickers                 “SNE”
weights “-2.85654465380669e-17”

The ‘e-XX’ weights basically indicate a weighting of zero on that particular security (NVDA, YHOO and SNE above). In the next post I will look at how all this can be done using a package called ‘fPortfolio’. Happy trading!