- # 准备
- install.packages("tidyquant")
- library(tidyverse)
- library(tidyquant)
由于附件无法重复上传,请到我的帖子数据所在下载。
- # load ShangHai index data
- load("SHDX2017.RData")
一、美式K线图
- # barchart:geom_barchart()
- SHDX2017 %>%
- ggplot(aes(x = date, y = close)) +
- geom_barchart(aes(open = open, high = high, low = low, close = close),
- color_up = "darkred", color_down = "darkgreen", size = 1) +
- labs(title = "SHDX Bar Chart", y = "Closing Price", x = "") +
- coord_x_date(xlim = c("2017-08-01", "2017-12-31"),
- ylim = c(3200, 3500)) +
- theme_tq()
二、蜡烛图
- # Candlestick:geom_candlestick()
- SHDX2017 %>%
- ggplot(aes(x = date, y = close)) +
- geom_candlestick(aes(open = open, high = high, low = low, close = close),
- color_up = "darkred", color_down = "darkgreen",
- fill_up = "darkred", fill_down = "darkgreen") +
- labs(title = "SHDX Candlestick Chart",
- y = "Closing Price", x = "") +
- coord_x_date(xlim = c("2017-08-01", "2017-12-31"), ylim = c(3200, 3500)) +
- theme_tq()
三、加移动平均线
- # Moving Average lines:geom_ma()
- SHDX2017 %>%
- ggplot(aes(x = date, y = close)) +
- geom_candlestick(aes(open = open, high = high, low = low, close = close),
- color_up = "darkred", color_down = "darkgreen",
- fill_up = "darkred", fill_down = "darkgreen") +
- geom_ma(ma_fun = SMA, n = 5, color = "darkblue", size = 1) +
- labs(title = "SHDX Candlestick Chart",
- y = "Closing Price", x = "") +
- coord_x_date(xlim = c("2017-08-01", "2017-12-31"), ylim = c(3200, 3500)) +
- theme_tq()
四、加布林通道线
- # Moving Average lines:geom_bbands()
- SHDX2017 %>%
- ggplot(aes(x = date, y = close, open = open,
- high = high, low = low, close = close)) +
- geom_candlestick(aes(open = open, high = high, low = low, close = close),
- color_up = "darkred", color_down = "darkgreen",
- fill_up = "darkred", fill_down = "darkgreen") +
- geom_bbands(ma_fun = SMA, sd = 2, n = 20) +
- labs(title = "SHDX Candlestick Chart",
- y = "Closing Price", x = "") +
- coord_x_date(xlim = c("2017-08-01", "2017-12-31"), ylim = c(3200, 3500)) +
- theme_tq()
其实tidyquant强大的地方并非是可视化,可视化只是其顺带做了几个函数,以后有机会再向大家介绍其他方面。