-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathplotly_yield_curve.R
More file actions
executable file
·52 lines (45 loc) · 1.13 KB
/
Copy pathplotly_yield_curve.R
File metadata and controls
executable file
·52 lines (45 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# plotly interactive yield curve
# from: https://gist.github.com/timelyportfolio/4da9d6b6c89cce26effabccca30124dd
library(plotly)
library(dplyr)
library(tidyr)
library(purrr)
library(quantmod)
library(magrittr)
# get yields from St. Louis Fed FRED
yield_curve <- list("DTB3", "DGS2", "DGS5", "DGS10", "DGS30") %>%
map(
~getSymbols(.x, auto.assign=FALSE, src="FRED")
) %>%
do.call(merge,.)
# create our 3d surface yield curve
yield_curve["1980::"] %>%
# convert to numeric matrix
data.matrix() %>%
# transpose
t() %>%
# draw our Plotly 3d surface
plot_ly(
x=as.Date(index(yield_curve["1980::"])),
y=c(0.25,2,5,10,30),
z=.,
type="surface"
) %>%
plotly::layout(
scene=list(
xaxis=list(title="date"),
yaxis=list(title="term"),
zaxis=list(title="yield")
)
)
# 3d scatter chart
yield_curve_tidy <- yield_curve %>%
data.frame() %>%
add_rownames(var="date") %>%
gather(symbol,yield,-date) %>%
mutate(term=c(0.25,5,10,30)[match(symbol,paste0(c("IRX","FVX","TNX","TYX"),".Close"))])
yield_curve_tidy %>%
plot_ly(
x=date, y=yield, z=term,
group=symbol, type="scatter3d"
)