Gaurav Gupta, MBA, CFA, FRM, CAIA, PMP
Gaurav Gupta, MBA, CFA, FRM, CAIA, PMP
  • About
  • Certifications/Accomplishments
  • Models
    • MS Excel - VBA
    • Power BI >
      • Euro Debt Crisis
      • PMO Metrics
      • Sales - Geography
      • UK Bank Customers
    • R (RStudio) >
      • Simulation for Teller Wait Times at a Bank
      • Portfolio Construction Using R
  • Articles
    • Financial Advice
  • Organizations
  • Media And Publications
  • Contact
  • About
  • Certifications/Accomplishments
  • Models
    • MS Excel - VBA
    • Power BI >
      • Euro Debt Crisis
      • PMO Metrics
      • Sales - Geography
      • UK Bank Customers
    • R (RStudio) >
      • Simulation for Teller Wait Times at a Bank
      • Portfolio Construction Using R
  • Articles
    • Financial Advice
  • Organizations
  • Media And Publications
  • Contact
Portfolio Construction using R
Portfolio_Management.R
library(timeSeries)
## Warning: package 'timeSeries' was built under R version 3.1.2
## Loading required package: timeDate
## Warning: package 'timeDate' was built under R version 3.1.2
library(fPortfolio)
## Warning: package 'fPortfolio' was built under R version 3.1.2
## Loading required package: fBasics
## Warning: package 'fBasics' was built under R version 3.1.2
## 
## 
## Rmetrics Package fBasics
## Analysing Markets and calculating Basic Statistics
## Copyright (C) 2005-2014 Rmetrics Association Zurich
## Educational Software for Financial Engineering and Computational Science
## Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY.
## https://www.rmetrics.org --- Mail to: [email protected]
## Loading required package: fAssets
## Warning: package 'fAssets' was built under R version 3.1.2
## 
## 
## Rmetrics Package fAssets
## Analysing and Modeling Financial Assets
## Copyright (C) 2005-2014 Rmetrics Association Zurich
## Educational Software for Financial Engineering and Computational Science
## Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY.
## https://www.rmetrics.org --- Mail to: [email protected]
## 
## 
## Rmetrics Package fPortfolio
## Portfolio Optimization
## Copyright (C) 2005-2014 Rmetrics Association Zurich
## Educational Software for Financial Engineering and Computational Science
## Rmetrics is free software and comes with ABSOLUTELY NO WARRANTY.
## https://www.rmetrics.org --- Mail to: [email protected]
library(quantmod)
## Warning: package 'quantmod' was built under R version 3.1.2
## Loading required package: xts
## Warning: package 'xts' was built under R version 3.1.2
## Loading required package: zoo
## Warning: package 'zoo' was built under R version 3.1.2
## 
## Attaching package: 'zoo'
## 
## The following object is masked from 'package:timeSeries':
## 
##     time<-
## 
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## Loading required package: TTR
## Warning: package 'TTR' was built under R version 3.1.2
## 
## Attaching package: 'TTR'
## 
## The following object is masked from 'package:fBasics':
## 
##     volatility
## 
## Version 0.4-0 included new data defaults. See ?getSymbols.
library(caTools)
## Warning: package 'caTools' was built under R version 3.1.2
library(timeDate)
library(knitr)
## Warning: package 'knitr' was built under R version 3.1.2
TickerList<-c("SPY","WWE","LNKD","AMZN","BOE","WMT","BABA","KO","BAC","FB","HD","HOG","TWTR")

ClosingPricesRead<-NULL
for (Ticker in TickerList)
  ClosingPricesRead<-cbind(ClosingPricesRead,
      getSymbols.yahoo(Ticker, from="1950-01-01",verbose=FALSE, auto.assign=FALSE)[,4])

#keep only the dates that have closing prices for all the tickers
ClosingPrices<-ClosingPricesRead[apply(ClosingPricesRead,1,function(x)all(!is.na(x))),]

#convert prices to daily returns
returns<-as.timeSeries(tail(ClosingPrices,-1)/as.numeric(head(ClosingPrices,-1))-1)

Frontier<-portfolioFrontier(returns)
#names(plot((Frontier)))
plot(Frontier,1) # Plot EF
plot(Frontier,2) # Min. Risk Portfolio
plot(Frontier,3) # Tangency Portfolio
plot(Frontier,4) # Risk/Return of Single Assets
plot(Frontier,5) # Equal Weights Portfolio
plot(Frontier,6) # Two Asset Frontiers(Long Only)
plot(Frontier,7) # Monte Carlo Portfolios
plot(Frontier,8) # MArkowitz PF Only

#get the means and covariance matrix of the price returns
#names(getStatistics(Frontier))
getStatistics(Frontier)$mean
##     SPY.Close     WWE.Close    LNKD.Close    AMZN.Close     BOE.Close 
##  0.0005958962 -0.0019466564  0.0019450267 -0.0008530650 -0.0009477436 
##     WMT.Close    BABA.Close      KO.Close     BAC.Close      FB.Close 
##  0.0018781501  0.0020260373  0.0003911629  0.0009501479  0.0006844107 
##      HD.Close     HOG.Close    TWTR.Close 
##  0.0017801718  0.0008797936 -0.0045745298
cor(returns)
##            SPY.Close   WWE.Close  LNKD.Close AMZN.Close  BOE.Close
## SPY.Close  1.0000000  0.24899139  0.48436740 0.41305296 0.72241901
## WWE.Close  0.2489914  1.00000000  0.30133834 0.13835408 0.08138650
## LNKD.Close 0.4843674  0.30133834  1.00000000 0.46141464 0.32434108
## AMZN.Close 0.4130530  0.13835408  0.46141464 1.00000000 0.33182575
## BOE.Close  0.7224190  0.08138650  0.32434108 0.33182575 1.00000000
## WMT.Close  0.4248750 -0.07629585  0.10297325 0.39179731 0.24041028
## BABA.Close 0.4044309  0.29584219  0.34129413 0.20829848 0.31853948
## KO.Close   0.2567614  0.10069373 -0.03055834 0.03870129 0.05659792
## BAC.Close  0.7492623  0.25551614  0.26438661 0.23636029 0.56698639
## FB.Close   0.5533405  0.33492177  0.48346490 0.32291386 0.43152330
## HD.Close   0.6591608  0.04906058  0.31082645 0.39033258 0.55410273
## HOG.Close  0.6385693 -0.01388373  0.33405098 0.44031692 0.54462776
## TWTR.Close 0.3353428  0.29520744  0.36925097 0.27322641 0.24553190
##              WMT.Close BABA.Close    KO.Close BAC.Close    FB.Close
## SPY.Close   0.42487500  0.4044309  0.25676135 0.7492623  0.55334053
## WWE.Close  -0.07629585  0.2958422  0.10069373 0.2555161  0.33492177
## LNKD.Close  0.10297325  0.3412941 -0.03055834 0.2643866  0.48346490
## AMZN.Close  0.39179731  0.2082985  0.03870129 0.2363603  0.32291386
## BOE.Close   0.24041028  0.3185395  0.05659792 0.5669864  0.43152330
## WMT.Close   1.00000000  0.1199689  0.36897638 0.3400061  0.23506166
## BABA.Close  0.11996887  1.0000000 -0.13165589 0.2972917  0.30788080
## KO.Close    0.36897638 -0.1316559  1.00000000 0.2185564 -0.01513403
## BAC.Close   0.34000608  0.2972917  0.21855639 1.0000000  0.38113965
## FB.Close    0.23506166  0.3078808 -0.01513403 0.3811396  1.00000000
## HD.Close    0.51102822  0.2667712  0.10749395 0.5757504  0.45958061
## HOG.Close   0.29112534  0.2385422 -0.16274569 0.5382613  0.41192386
## TWTR.Close  0.12214179  0.3180954  0.10209176 0.1073537  0.55352305
##              HD.Close   HOG.Close TWTR.Close
## SPY.Close  0.65916081  0.63856934  0.3353428
## WWE.Close  0.04906058 -0.01388373  0.2952074
## LNKD.Close 0.31082645  0.33405098  0.3692510
## AMZN.Close 0.39033258  0.44031692  0.2732264
## BOE.Close  0.55410273  0.54462776  0.2455319
## WMT.Close  0.51102822  0.29112534  0.1221418
## BABA.Close 0.26677120  0.23854216  0.3180954
## KO.Close   0.10749395 -0.16274569  0.1020918
## BAC.Close  0.57575036  0.53826135  0.1073537
## FB.Close   0.45958061  0.41192386  0.5535231
## HD.Close   1.00000000  0.63833023  0.2913843
## HOG.Close  0.63833023  1.00000000  0.1949419
## TWTR.Close 0.29138426  0.19494193  1.0000000
#to plot annualized return and risk
#convert from daily to annual returns and risk 
#EF using annualized risk and return

riskReturnPoints<-frontierPoints(Frontier) #risk and return points on the EF
annualizedPoints<-data.frame(targetRisk=riskReturnPoints[,"targetRisk"]*sqrt(252),
                             targetReturn=riskReturnPoints[,"targetReturn"]*252)
plot(annualizedPoints)

#plot Sharpe ratios for each point on the EF
riskFreeRate<-0
plot((annualizedPoints[,"targetReturn"]-riskFreeRate)/annualizedPoints[,"targetRisk"], xlab="point on EF", ylab="Sharpe Ratio")

#plot the allocation to each stock for each point on the efficient frontier
weightsPlot(Frontier)

#(weightsPlot(Frontier))$minRisk

allocations <-getWeights(Frontier@portfolio)# get allocations for each stock
colnames(allocations)<-TickerList
barplot(t(allocations),col=rainbow(ncol(allocations)+2),legend=colnames(allocations))

#write.csv(annualizedPoints, file="annualReturns.csv")
#getwd() #the location of file

#examine the efficient frontier for portfolios with different constrants
constraints<-"minW[1:length(TickerList)]=-1"
Frontier<-portfolioFrontier(returns ,constraints=constraints)
Frontier.LongOnly<-portfolioFrontier(returns)

riskReturnPoints<-frontierPoints(Frontier)
annualizedPoints<-data.frame(targetRisk=riskReturnPoints[,"targetRisk"]*sqrt(252),
                             targetReturn=riskReturnPoints[,"targetReturn"]*252)
riskReturnPoints.LongOnly<-frontierPoints(Frontier.LongOnly)
annualizedPoints.LongOnly<-data.frame(targetRisk=riskReturnPoints.LongOnly[,"targetRisk"]*sqrt(252),
                                      targetReturn=riskReturnPoints.LongOnly[,"targetReturn"]*252)

xlimit<-range(annualizedPoints[,1],annualizedPoints.LongOnly[,1])
ylimit<-range(annualizedPoints[,2],annualizedPoints.LongOnly[,2])

plot(annualizedPoints.LongOnly,xlim=xlimit,ylim=ylimit,pch=16,col="blue")
points(annualizedPoints, col="red", pch=16)

legend("right",legend=c("long only","constrained"),col=c("blue","red"), pch= 14)

#red allows both long and short positions

#other type of constraints
constraints<-c("minW[1:length(TickerList)]=-1.0","maxW[1:length(TickerList)]=.60")
Frontier<-portfolioFrontier(returns ,constraints=constraints)
Frontier.LongOnly<-portfolioFrontier(returns)

riskReturnPoints<-frontierPoints(Frontier)
annualizedPoints<-data.frame(targetRisk=riskReturnPoints[,"targetRisk"]*sqrt(252),
                             targetReturn=riskReturnPoints[,"targetReturn"]*252)
riskReturnPoints.LongOnly<-frontierPoints(Frontier.LongOnly)
annualizedPoints.LongOnly<-data.frame(targetRisk=riskReturnPoints.LongOnly[,"targetRisk"]*sqrt(252),
                                      targetReturn=riskReturnPoints.LongOnly[,"targetReturn"]*252)

xlimit<-range(annualizedPoints[,1],annualizedPoints.LongOnly[,1])
ylimit<-range(annualizedPoints[,2],annualizedPoints.LongOnly[,2])

plot(annualizedPoints.LongOnly,xlim=xlimit,ylim=ylimit,pch=16,col="blue")
points(annualizedPoints, col="red", pch=16)

legend("right",legend=c("long only","constrained"),col=c("blue","red"), pch= 14)

#New Allocations
allocations <-getWeights(Frontier@portfolio)# get allocations for each stock
colnames(allocations)<-TickerList
barplot(t(allocations),col=rainbow(ncol(allocations)+2),legend=colnames(allocations))

#Long Only Allocation Chart
Frontier<-portfolioFrontier(returns)
allocations <-getWeights(Frontier@portfolio)# get allocations for each stock
colnames(allocations)<-TickerList
barplot(t(allocations),col=rainbow(ncol(allocations)+2),legend=colnames(allocations))

Proudly powered by Weebly