
R Programming Assignment Solution on Markowitz Efficient Set
- 20th Jan, 2022
- 00:05 AM
#From Session you can choose Set Working Directory #Alternatively you can use setwd to set the working directory #Pay close attention to the direction of the slash "/" #The first time through you will need to install.packages(" ") listed in the library statements #R-code for Assignment #setwd("~/Desktop/FINA") library(timeSeries) library(fPortfolio) library(quantmod) library(caTools) library(dplyr) library(PerformanceAnalytics) library(ggplot2) library(tidyverse) library(tidyquant) library(timetk) library(lubridate) #If your data is in long format (i.e., a panel), the code below reads in the returns #I use the "ymd" function from the lubridate package to convert the date stored as an integer to #a date that R will recognize. I then use the SPREAD function #to reshape the data so that each firm's returns are in a column #You can directly reference a variable in a file as filename$VariableName returns<-read.csv("1589309519_StockReturns.csv") returns$Date <- ymd(returns$Date) #this code will convert a panel to a set of columns #the %>% is handy and tells R to take the file retuns and passes it to the SPREAD function #the %>% is called a "pipe" is comes with the package "dplyr" and "tidyverse". Tidyverse gives #us a whole array of functions for data manipulation #returns <- returns %>% spread(TICKER, RET ) #If the returns are in a column you can use the below code to read in the .csv fle returns<-read.csv("1589309519_StockReturns.csv") returns$Date <- ymd(returns$Date) returns = subset(returns, Date < "2015-01-01") #The returns[,-1] reads all rows and skips the first column, and then we tell it which variable is the Date returns<-timeSeries(returns[,-1],charvec=returns$Date) #portfolioFrontier is a package thqt will generate the entire efficient set #The output of this package is stored in an object call effFrontier #Set Portfolio specifications - in this case the risk-free rate tgSpec<-portfolioSpec() setRiskFreeRate(tgSpec)<- 0.02/12 effFrontier <- portfolioFrontier(returns, spec= tgSpec, constraints = "LongOnly") # plot frontier - simple and interactive #'Options #'1: Plot Efficient Frontier #'2: Plot Minimum Variance Portfolio #'3: Plot Tangency Portfolio #'4: Plot Risk Returns of Each Asset #'5: Plot Equal Weights Portfolio #'6: Plot Two Asset Frontiers (Long) #'7: Plot Monte Carlo Portfolios #'8: Plot Sharpe Ratio plot(effFrontier,c(1,2,3,4,6)) #tailored Plot much more flexible version of plot tailoredFrontierPlot(object=effFrontier,sharpeRatio = FALSE) #Plot Frontier Weights (Can Adjust Number of Points) frontierWeights <- getWeights(effFrontier) # get allocations for each instrument for each point on the efficient frontier tickers <- colnames(frontierWeights) risk_return <- frontierPoints(effFrontier) write.csv(risk_return, "risk_return.csv") write.csv(frontierWeights,"frontier_weights.csv") #Output Correlation cor_matrix <- cor(returns) cov_matrix <- cov(returns) write.csv(cov_matrix, "covmatrix.csv") write.csv(cor_matrix,"corr_matrix.csv") cov_matrix #Annualize Data riskReturnPoints <- frontierPoints(effFrontier) # get risk and return values for points on the efficient frontier annualizedPoints <- data.frame(targetRisk=riskReturnPoints[, "targetRisk"] * sqrt(12), targetReturn=riskReturnPoints[,"targetReturn"] * 12) plot(annualizedPoints) # plot Sharpe ratios for each point on the efficient frontier riskFreeRate <- 0.02 plot((annualizedPoints[,"targetReturn"]-riskFreeRate) / annualizedPoints[,"targetRisk"], xlab="point on efficient frontier", ylab="Sharpe ratio") #Plot Frontier Weights (Need to transpose matrix first) barplot(t(frontierWeights), main="Frontier Weights", col=cm.colors(ncol(frontierWeights)+2), legend=colnames(frontierWeights)) #Get Minimum Variance Port, Tangency Port, etc. mvp <- minvariancePortfolio(returns, spec=portfolioSpec(), constraints="LongOnly") mvp tangencyPort <- tangencyPortfolio(returns, spec=portfolioSpec(), constraints="LongOnly") tangencyPort mvpweights <- getWeights(mvp) tangencyweights <- getWeights(tangencyPort) #Extract value at risk covRisk(returns, mvpweights) varRisk(returns, mvpweights, alpha = 0.05) cvarRisk(returns, mvpweights, alpha = 0.05) #Plot MVP Weights: Basic Graphs barplot(mvpweights, main="Minimum Variance Portfolio Weights", xlab="Assset", ylab="Weight In Portfolio (%)", col=cm.colors(ncol(frontierWeights)+2), legend=colnames(weights)) pie(mvpweights, col=cm.colors(ncol(frontierWeights)+2)) #ggplot MVP Weights df <- data.frame(mvpweights) assets <- colnames(frontierWeights) ggplot(data=df, aes(x=assets, y=mvpweights, fill=assets)) + geom_bar(stat="identity", position=position_dodge(),colour="black") + geom_text(aes(label=sprintf("%.02f %%",mvpweights*100)), position=position_dodge(width=0.9), vjust=-0.25, check_overlap = TRUE) + ggtitle("Minimum Variance Portfolio Optimal Weights")+ theme(plot.title = element_text(hjust = 0.5)) + labs(x= "Assets", y = "Weight (%)") dft <- data.frame(tangencyweights) assets <- colnames(frontierWeights) ggplot(data=dft, aes(x=assets, y=tangencyweights, fill=assets)) + geom_bar(stat="identity", position=position_dodge(),colour="black") + geom_text(aes(label=sprintf("%.02f %%",tangencyweights*100)), position=position_dodge(width=0.9), vjust=-0.25, check_overlap = TRUE) + ggtitle("Tangency Portfolio Weights")+ theme(plot.title = element_text(hjust = 0.5)) + labs(x= "Assets", y = "Weight (%)") #ggplot Pie bar <- ggplot(df, aes(x = "", y = mvpweights, fill=assets)) + geom_bar(width= 1, stat="identity") + ggtitle("Minimum Variance Portfolio Weights")+ theme(plot.title = element_text(hjust = 0.5)) pie <- bar + coord_polar("y", start=0) pie + scale_fill_brewer(palette="Blues")+ theme_minimal() bar <- ggplot(dft, aes(x = "", y = tangencyweights, fill=assets)) + geom_bar(width= 1, stat="identity") + ggtitle("Tangency Portfolio Weights")+ theme(plot.title = element_text(hjust = 0.5)) pie <- bar + coord_polar("y", start=0) pie + scale_fill_brewer(palette="Blues")