Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/sandbox/scriptMF.R
1433 views
1
library(PortfolioAnalytics)
2
3
# Use edhec data
4
data(edhec)
5
6
R <- edhec[,1:10]
7
8
# Dimensions of data
9
m <- nrow(R)
10
N <- ncol(R)
11
12
# Number of factors to use
13
k <- 3
14
15
##### Step 1 #####
16
fit <- statistical.factor.model(R, k)
17
names(fit)
18
beta <- fit$factor_loadings
19
f <- fit$factor_realizations
20
res <- fit$residuals
21
22
##### Step 2 #####
23
# Compute the moments of the factors and idiosyncratic risk factors
24
# Note: The idiosyncratic factors are the residuals in the model (i.e. the
25
# unexplained asset return variation)
26
27
# Check for equality with functions from Kris Boudt and functions I have
28
# included in the package
29
30
# residual moments
31
denom <- m - k - 1
32
stockM2 <- colSums(res^2) / denom
33
stockM3 <- colSums(res^3) / denom
34
stockM4 <- colSums(res^4) / denom
35
36
# Compute the centered factors
37
# f.centered <- center(f)
38
39
# factor moments
40
# (k x k)
41
factorM2 <- cov(f)
42
43
# (k x k^2)
44
factorM3 <- PerformanceAnalytics:::M3.MM(f)
45
46
# (k x k^3)
47
factorM4 <- PerformanceAnalytics:::M4.MM(f)
48
49
##### Step 3 #####
50
# Compute the covariance, coskewness, and cokurtosis estimates from the statistical
51
# factor model.
52
53
# covariance matrix
54
all.equal(
55
PortfolioAnalytics:::covarianceMF(beta, stockM2, factorM2),
56
extractCovariance(fit)
57
)
58
59
# coskewness matrix
60
all.equal(
61
PortfolioAnalytics:::coskewnessMF(beta, stockM3, factorM3),
62
extractCoskewness(fit)
63
)
64
65
# cokurtosis matrix
66
all.equal(
67
PortfolioAnalytics:::cokurtosisMF(beta, stockM2,stockM4, factorM2, factorM4),
68
extractCokurtosis(fit)
69
)
70
71