-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dual Axis Chart.R
54 lines (48 loc) · 1.66 KB
/
Dual Axis Chart.R
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
53
54
suppressPackageStartupMessages({
library(quantmod)
library(dplyr)
library(ggplot2)
})
tickers <- c("WFG", "^GSPC")
start_date <- "2022-04-10"
portfolioPrices <- NULL
for (Ticker in tickers) {
portfolioPrices <- cbind(portfolioPrices,
getSymbols(Ticker,
from = start_date,
src = "yahoo",
auto.assign=FALSE)[,4])
}
head(portfolioPrices)
portfolioPrices <- portfolioPrices[apply(portfolioPrices,
1,
function(x) all(!is.na(x))),]
colnames(portfolioPrices) <- c("WFG",
"GSPC")
portfolioReturns <- ROC(portfolioPrices,
type = "discrete")
autoplot(portfolioReturns,
facets = NULL) +
scale_color_manual(values = c(WFG = "black",
GSPC = "red")) +
ggtitle("Stock Returns") +
theme_bw()
Prices <- fortify(portfolioPrices)
(fac <- with(Prices,
range(WFG)/range(GSPC)))
#> [1] 0.01676810 0.02124536
fac <- max(fac)
ggplot(data = Prices, aes(Index, WFG)) +
geom_line(aes(color = "WFG")) +
geom_line(aes(y = GSPC * fac,
color = "GSPC")) +
scale_x_date(date_breaks = "1 year",
date_labels = "%b %Y") +
scale_color_manual(values = c(WFG = "red",
GSPC = "black")) +
scale_y_continuous(sec.axis = sec_axis(~ . / fac,
name = "S&P 500 Closes")) +
labs(x = "Date", y = "WFG Close Price",
color = "") +
ggtitle("Stock Price") +
theme_bw()