Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
braverock
GitHub Repository: braverock/portfolioanalytics
Path: blob/master/sandbox/RFinance2014/R/charting.R
1433 views
1
nvd3WeightsPlot <- function(object,
2
type=c("stackedAreaChart", "multiBarChart")
3
){
4
type <- match.arg(type)
5
6
# extract the weights and turn into a data.frame
7
weights <- extractWeights(object)
8
weights.df <- reshape2::melt(
9
data.frame(date=format(index(weights)), weights),
10
id.vars = 1,
11
variable.name = "stock",
12
value.name = "weight"
13
)
14
weights.df$date <- as.Date(weights.df$date)
15
16
# plot
17
n1 <- rCharts::nPlot(
18
weight ~ date,
19
group = "stock",
20
data = weights.df,
21
type = type
22
)
23
n1$xAxis(
24
tickFormat = "#!function(d){
25
return d3.time.format('%b %Y')(new Date(d * 24 * 60 * 60 * 1000))
26
}!#"
27
)
28
n1$yAxis(
29
tickFormat = "#!function(d){
30
return d3.format('0.2%')(d)
31
}!#"
32
)
33
return(n1)
34
}
35
36
nvd3RiskPlot <- function(object,
37
type=c("stackedAreaChart", "multiBarChart")
38
){
39
type <- match.arg(type)
40
41
# extract the risk budget pct_contrib and turn into a data.frame
42
tmp <- extractObjectiveMeasures(object)
43
rb <- tmp[,grep("pct_contrib", colnames(tmp))]
44
colnames(rb) <- gsub("^.*\\.", "", colnames(rb))
45
rb.df <- reshape2::melt(
46
data.frame(date=as.Date(format(index(rb))), rb),
47
id.vars = 1,
48
variable.name = "fund",
49
value.name = "risk"
50
)
51
52
# plot
53
n1 <- rCharts::nPlot(
54
risk ~ date,
55
group = "fund",
56
data = rb.df,
57
type = type
58
)
59
n1$xAxis(
60
tickFormat = "#!function(d){
61
return d3.time.format('%b %Y')(new Date(d * 24 * 60 * 60 * 1000))
62
}!#"
63
)
64
n1$yAxis(
65
tickFormat = "#!function(d){
66
return d3.format('0.2%')(d)
67
}!#"
68
)
69
return(n1)
70
}
71
72
# require(rCharts)
73
# weights <- extractWeights(opt.minVarSample)
74
# weights.df <- reshape2::melt(
75
# data.frame(
76
# date=format(index(weights)),
77
# weights
78
# ),
79
# id.vars = 1,
80
# variable.name = "stock",
81
# value.name = "weight"
82
# )
83
#
84
# d1 <- dPlot(
85
# weight ~ date,
86
# groups = "stock",
87
# data = weights.df,
88
# type = "bubble" #area, bar, or bubble
89
# )
90
# d1$xAxis(
91
# type = "addTimeAxis",
92
# inputFormat = "%Y-%m-%d",
93
# outputFormat = "%b %Y"
94
# )
95
# d1$yAxis(
96
# outputFormat = "0.2%",
97
# orderBy = "weight"
98
# )
99
# d1
100