[Uwgarp-commits] r168 - pkg/GARPFRM/demo

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Wed Apr 16 07:47:40 CEST 2014


Author: tfillebeen
Date: 2014-04-16 07:47:38 +0200 (Wed, 16 Apr 2014)
New Revision: 168

Modified:
   pkg/GARPFRM/demo/CAPM_TF.R
   pkg/GARPFRM/demo/DelineatingEfficientPortfolios.R
   pkg/GARPFRM/demo/EWMA.R
   pkg/GARPFRM/demo/EstimatingVolatilitiesCorrelation.R
   pkg/GARPFRM/demo/MonteCarloMethods.R
   pkg/GARPFRM/demo/backtest_VaR.R
   pkg/GARPFRM/demo/bootstrap.R
Log:
Added some comments

Modified: pkg/GARPFRM/demo/CAPM_TF.R
===================================================================
--- pkg/GARPFRM/demo/CAPM_TF.R	2014-04-15 23:12:16 UTC (rev 167)
+++ pkg/GARPFRM/demo/CAPM_TF.R	2014-04-16 05:47:38 UTC (rev 168)
@@ -1,6 +1,6 @@
-
-
 # 'Load the GARPFRM package and CRSP dataset for CAPM analysis.
+# Standard Capital Asset Pricing Model (CAPM) fitting and testing using CRSP data. 
+# Where CAPM describes the relationship between risk and expected return.
 suppressMessages(library(GARPFRM))
 options(digits=3)
 data(crsp.short)
@@ -12,22 +12,17 @@
 # Plot first four stocks from 
 plot.zoo(stock.df[,1:4], main="First Four Large Cap Returns")
 
-
-
 # Illustrate the type of data being analzyed: start-end dates.
 start(stock.df[,1:4])
 end(stock.df[,1:4])
 # Count the number of rows: sample size.
 nrow(stock.df)
 
-
-
 # Excess Returns initialized before utilizing in CAPM
 exReturns <- Return.excess(stock.df, rfr)
 colnames(exReturns)= c(colnames(stock.df))
 
 
-
 # Univariate CAPM
 uv <- CAPM(exReturns[,1], mrkt)
 getStatistics(uv)
@@ -35,8 +30,6 @@
 # Plot data with regression line
 plot(uv)
 
-
-
 # MLM CAPM for AMAT, AMGN, and CAT
 mlm <- CAPM(exReturns[,1:3], mrkt)
 getStatistics(mlm)
@@ -44,9 +37,8 @@
 # Plot data with regression line
 plot(mlm)
 
-
-
-# For uv
+# For uv example
+# Estimate CAPM with α = 0 & β = 1 for asset
 getBetas(uv)
 getAlphas(uv)
 hypTest(uv, significanceLevel=0.05)
@@ -55,8 +47,8 @@
 getAlphas(mlm)
 hypTest(mlm, significanceLevel=0.05)
 
-
-
+# The CAPM function can handle multiple assets at once, 
+# and will cycle through each asset one at a time and output the results.
 # MLM CAPM
 mlm <- CAPM(exReturns[,], mrkt)
 
@@ -64,8 +56,9 @@
 chartSML(mlm)
 
 
-
 # Load FED consumption data: CONS
+# To illustate the power of the CAPM model 
+# test its relationship with explanatory variable con- sumption.
 data(consumption)
 
 # Convert to yearmon index and align consumption and mrkt
@@ -77,6 +70,4 @@
 coef(summary(capm.cons))
 
 # Plot data with regression line
-plot(capm.cons)
-
-
+plot(capm.cons)
\ No newline at end of file

Modified: pkg/GARPFRM/demo/DelineatingEfficientPortfolios.R
===================================================================
--- pkg/GARPFRM/demo/DelineatingEfficientPortfolios.R	2014-04-15 23:12:16 UTC (rev 167)
+++ pkg/GARPFRM/demo/DelineatingEfficientPortfolios.R	2014-04-16 05:47:38 UTC (rev 168)
@@ -1,10 +1,6 @@
-
-
 library(knitr)
 opts_chunk$set(tidy=FALSE, warning=FALSE, fig.width=5, fig.height=5)
 
-
-
 suppressPackageStartupMessages(library(GARPFRM))
 
 # Colonel Motors expected return
@@ -25,10 +21,10 @@
 # Create a vector of portfolio weights
 X_C <- seq(from=0, to=1, by=0.2)
 
-# Calculate the portfolio expected return
+# Calculate the portfolio expected return (ρ = −1)
 R_P <- portReturnTwoAsset(R_C, R_S, X_C)
 
-# Calculate the portfolio standard deviation
+# Calculate the portfolio standard deviation (ρ = 0)
 sigma_P <- portSDTwoAsset(R_C, R_S, X_C, sigma_C, sigma_S, rho)
 
 # Combine the portfolio returns and standard deviations in a data.frame object.
@@ -38,14 +34,12 @@
 colnames(df) <- X_C
 df
 
-
-
+# Plot the portfolio return and standard deviation to 
+# understand the risk and return of the portfolio
 # Create and plot the efficient frontier object
 ef <- efficientFrontierTwoAsset(R_C, R_S, sigma_C, sigma_S, rho)
 plot(ef)
 
-
-
 # Correlation coefficient
 rho <- -1
 
@@ -62,14 +56,10 @@
 colnames(df) <- X_C
 df
 
-
-
 # Create and plot the efficient frontier object
 ef <- efficientFrontierTwoAsset(R_C, R_S, sigma_C, sigma_S, rho)
 plot(ef)
 
-
-
 # Correlation coefficient
 rho <- 0
 
@@ -86,15 +76,10 @@
 colnames(df) <- X_C
 df
 
-
-
 # Create and plot the efficient frontier object
 ef <- efficientFrontierTwoAsset(R_C, R_S, sigma_C, sigma_S, rho)
 plot(ef)
 
-
-
-
 minRisk <- function(R_A, R_B, sigma_A, sigma_B, rho){
   top_term <- sigma_B^2 - sigma_A * sigma_B * rho
   bottom_term <- sigma_A^2 + sigma_B^2 - 2 * sigma_A * sigma_B * rho
@@ -112,13 +97,9 @@
               portfolio_sd=port_sd))
 }
 
-
-
 minRisk(R_C, R_S, sigma_C, sigma_S, rho)
 
-
-
-# Correlation coefficient
+# Correlation coefficient (ρ = 0.5)
 rho <- 0.5
 
 # Calculate the portfolio expected return
@@ -134,18 +115,12 @@
 colnames(df) <- X_C
 df
 
-
-
 # Create and plot the efficient frontier object
 ef <- efficientFrontierTwoAsset(R_C, R_S, sigma_C, sigma_S, rho)
 plot(ef)
 
-
-
 minRisk(R_C, R_S, sigma_C, sigma_S, rho)
 
-
-
 X_C <- seq(from=0, to=1, by=0.01)
 R_P <- portReturnTwoAsset(R_C, R_S, X_C)
 # rho = 1
@@ -168,7 +143,7 @@
        lty=rep(1, 4), bty="n")
 
 
-
+# The Efficient Frontier with Short Sales Allowed
 # correlation coefficient
 rho <- 0.5
 
@@ -188,8 +163,6 @@
 colnames(df) <- X_C
 print(df, digits=4)
 
-
-
 # Create and plot the efficient frontier object
 ef_short <- efficientFrontierTwoAsset(R_C, R_S, sigma_C, sigma_S, rho, 
                                       allowShorting=TRUE)
@@ -240,26 +213,19 @@
 # Calculate the allocation and values for the minimum variance portfolio
 minRisk(R_SP, R_int, sigma_SP, sigma_int, rho)
 
-
-
 ef <- efficientFrontierTwoAsset(R_SP, R_int, sigma_SP, sigma_int, rho, rf=0.05)
 plot(ef)
 
-
-
+# Extended Examples for Portfolios with Multiple Assets
 data(crsp_weekly)
 R_large <- largecap_weekly[,1:5]
 R_mid <- midcap_weekly[,1:5]
 R_small <- smallcap_weekly[,1:5]
 
-
-
 # Create and plot an efficient frontier of large cap stocks
 ef_large <- efficientFrontier(R_large)
 plot(ef_large, main="Large Cap Efficient Frontier", cexAssets=0.6)
 
-
-
 # Create an efficient frontier object with box constraints
 # Add box constraints such that each asset must have a weight greater than 15%
 # and less than 55%
@@ -286,6 +252,4 @@
 efGroup <- efficientFrontier(R, groupList=groups, 
                              groupMin=groupMin, 
                              groupMax=groupMax)
-plot(efGroup, labelAssets=FALSE)
-
-
+plot(efGroup, labelAssets=FALSE)
\ No newline at end of file

Modified: pkg/GARPFRM/demo/EWMA.R
===================================================================
--- pkg/GARPFRM/demo/EWMA.R	2014-04-15 23:12:16 UTC (rev 167)
+++ pkg/GARPFRM/demo/EWMA.R	2014-04-16 05:47:38 UTC (rev 168)
@@ -6,6 +6,9 @@
 # Use the first 5 assets in largecap.ts for the returns data
 R <- largecap_weekly[, 1:5]
 
+# The Exponentially Weighted Moving Average (EWMA) Model is a special case of a weighted 
+# moving average where the weights αi decrease exponentially as we move backwards through 
+# time. Greater weights are given to more recent observations.
 # Estimate volatility via EWMA
 volEst <- EWMA(R[,1], lambda=NULL, initialWindow=52, n=26, type="volatility")
 volEst
@@ -45,4 +48,4 @@
 
 # Plot the correlation estimate between ORCL and EMC
 # Note that we are passing the covEst object created by the EWMA function
-plot(corEst, assets=c("ORCL", "EMC"))
+plot(corEst, assets=c("ORCL", "EMC"))
\ No newline at end of file

Modified: pkg/GARPFRM/demo/EstimatingVolatilitiesCorrelation.R
===================================================================
--- pkg/GARPFRM/demo/EstimatingVolatilitiesCorrelation.R	2014-04-15 23:12:16 UTC (rev 167)
+++ pkg/GARPFRM/demo/EstimatingVolatilitiesCorrelation.R	2014-04-16 05:47:38 UTC (rev 168)
@@ -1,36 +1,25 @@
-
-
 library(knitr)
 opts_chunk$set(cache=TRUE, tidy=FALSE, warning=FALSE, fig.width=5, fig.height=5)
 
-
-
+# Exponentially Weighted Moving Average Model
 suppressPackageStartupMessages(library(GARPFRM))
 data(crsp_weekly)
 
 # Use the weekly MSFT returns
 R <- largecap_weekly[, "MSFT"]
 
-
-
 lambda <- 0.94
 initialWindow <- 15
 volEst <- EWMA(R, lambda, initialWindow, type="volatility")
 volEst
 
-
-
 vol <- realizedVol(R, n=5)
 
-
-
 plot(vol, main="EWMA Volatility Estimate vs. Realized Volatility")
 lines(volEst$estimate, col="red")
 legend("topright", legend=c("Realized Volatility", "EWMA Volatility Estimate"), 
        col=c("black", "red"), lty=c(1,1), cex=0.8, bty="n")
 
-
-
 # Estimate lambda
 # Use initialWindow = 15 for the EWMA volatility estimate and
 # n = 5 to calculate the realized volatility
@@ -40,8 +29,6 @@
 volEst2 <- EWMA(R, lambda, initialWindow, type="volatility")
 volEst2
 
-
-
 # Realized volatility
 plot(vol, main="EWMA Volatility Estimate vs. Realized Volatility")
 # EWMA volatility estimate, lambda = 0.94
@@ -53,8 +40,6 @@
                             "EWMA Volatility, lambda = 0.7359253"),
        col=c("black", "red", "blue"), lty=c(1, 1, 1), cex=0.7, bty="n")
 
-
-
 # Use the first 2 columns of the large cap weekly returns
 R <- largecap_weekly[,1:2]
 initialWindow <- 52
@@ -62,14 +47,10 @@
 covEst
 plot(covEst, main="EWMA Estimated Covariance")
 
-
-
 corEst <- EWMA(R, lambda=NULL, initialWindow, n=10, "correlation")
 corEst
 plot(corEst, main="EWMA Estimated Correlation")
 
-
-
 # Use the first 4 columns of the largecap_weekly dataset
 R <- largecap_weekly[,1:4]
 
@@ -83,8 +64,6 @@
 covEst <- EWMA(R, lambda, initialWindow, type="covariance")
 covEst
 
-
-
 # calculate the sample covariance matrix
 sample_cor <- cor(R)
 sample_cor
@@ -95,11 +74,10 @@
 corEst <- EWMA(R, lambda, initialWindow, type="correlation")
 corEst
 
-
-
 # Use the weekly MSFT returns
 R <- largecap_weekly[,"MSFT"]
 
+# The GARCH(1,1) Model: Estimating GARCH(1,1) Parameters
 # Specify and fit the MSFT returns to a standard ARMA(0,0)-GARCH(1,1) model
 # Note that the default is ARMA(1,1)-GARCH(1,1) so we only need to change
 # the ARMA order. The default arguments were chosen to be consistent with the 
@@ -115,24 +93,15 @@
 # Show the summary results of the fit
 fit
 
-
-
+# Using GARCH(1,1) to Forecast Future Volatility
 # n period ahead forecast
 forecast10 <- forecast(model, nAhead=10)
 forecast10
 
-
-
 plot(forecast10, which=3)
 
-
-
 model11 <- uvGARCH(R, armaOrder=c(0,0), outSample=100)
 forecast2 <- forecast(model11, nRoll=10)
 forecast2
 
-
-
-plot(forecast2, which=4)
-
-
+plot(forecast2, which=4)
\ No newline at end of file

Modified: pkg/GARPFRM/demo/MonteCarloMethods.R
===================================================================
--- pkg/GARPFRM/demo/MonteCarloMethods.R	2014-04-15 23:12:16 UTC (rev 167)
+++ pkg/GARPFRM/demo/MonteCarloMethods.R	2014-04-16 05:47:38 UTC (rev 168)
@@ -1,11 +1,9 @@
-
-
 library(knitr)
 opts_chunk$set(tidy=FALSE, warning=FALSE, fig.width=5, fig.height=5)
 
-
-
 suppressPackageStartupMessages(library(GARPFRM))
+
+# Monte Carlo: Geometric Brownian Motion (GBM) mode
 # drift rate
 mu <- 0
 
@@ -36,10 +34,10 @@
   S[i] <- S[i-1] + S[i-1] * (mu_dt + sig_dt * eps[i-1])
 }
 head(S)
+
+# Plot Simulated Price Path
 plot(S, main="Simulated Price Path", type="l")
 
-
-
 # Allocate a vector to hold the prices
 S1 <- vector("numeric", N+1)
 S1[1] <- S0
@@ -54,8 +52,6 @@
 head(S1)
 plot(S1, main="Simulated Price Path", type="l")
 
-
-
 mu <- 0.05
 sigma <- 0.15
 N <- 10000
@@ -67,15 +63,11 @@
 mcSim <- monteCarlo(mu, sigma, N, time, steps, startingValue)
 summary(endingPrices(mcSim))
 
-
-
 par(mfrow=c(2,1))
 plot(mcSim)
 plotEndingPrices(mcSim)
 par(mfrow=c(1,1))
 
-
-
 data(crsp_weekly)
 R.MSFT <- largecap_weekly[, "MSFT"]
 
@@ -98,8 +90,6 @@
 bootS1 <- S.p * cumprod(1 + sample(coredata(R.MSFT), nAhead, TRUE))
 bootS1
 
-
-
 # Number of boostrap replications
 rep <- 10000
 
@@ -116,8 +106,6 @@
 # Standard error of Bootstrapped VaR
 sd(out)
 
-
-
 R <- largecap_weekly[,1:4]
 
 # function to calculate the annualized StdDev using the most recent n periods
@@ -182,6 +170,4 @@
 
 # Benchmark these functions
 # library(rbenchmark)
-# benchmark(bootPar(), bootSeq(), replications=1)[,1:4]
-
-
+# benchmark(bootPar(), bootSeq(), replications=1)[,1:4]
\ No newline at end of file

Modified: pkg/GARPFRM/demo/backtest_VaR.R
===================================================================
--- pkg/GARPFRM/demo/backtest_VaR.R	2014-04-15 23:12:16 UTC (rev 167)
+++ pkg/GARPFRM/demo/backtest_VaR.R	2014-04-16 05:47:38 UTC (rev 168)
@@ -38,5 +38,4 @@
 # Backtest GARCH Model VaR
 garchModel <- uvGARCH(R[, "MSFT"], armaOrder=c(0,0))
 btVaR.GARCH <- backtestVaR.GARCH(garchModel, p=0.95, refitEvery=5, window=100)
-btVaR.GARCH
-
+btVaR.GARCH
\ No newline at end of file

Modified: pkg/GARPFRM/demo/bootstrap.R
===================================================================
--- pkg/GARPFRM/demo/bootstrap.R	2014-04-15 23:12:16 UTC (rev 167)
+++ pkg/GARPFRM/demo/bootstrap.R	2014-04-16 05:47:38 UTC (rev 168)
@@ -1,3 +1,5 @@
+# Bootstrapping is a statistical method for estimating the sampling 
+# distribution of an estimator by sampling with replacement from the original sample.
 # bootstrap
 library(GARPFRM)
 data(crsp_weekly)
@@ -38,6 +40,7 @@
 bootCov(R[,1:2])
 bootCov(R)
 
+# Here is an example of how to calculate historical Value-at-Risk with bootstrapped returns.
 # Bootstrap Value-at-Risk (VaR) estimate using the VaR function from
 # PerformanceAnalytics.
 bootVaR(R[,1], p=0.9, method="historical")
@@ -49,5 +52,4 @@
 # Expected Tail Loss (ETL).
 bootES(R[,1], p=0.9, method="gaussian")
 bootES(R[,1], p=0.92, method="historical", invert=FALSE)
-bootES(R, p=0.9, method="historical")
-
+bootES(R, p=0.9, method="historical")
\ No newline at end of file



More information about the Uwgarp-commits mailing list