# [原]量化投资教程：用R语言打造量化分析Web平台

HarryZhu

## 什么是quantmod

quantmod就是提供给宽客们使用的专业模块，Quantmod本身提供强大的数据接入能力，默认是雅虎财经的数据源，此外quantmod还以绘制专业的行情分析图表以及各种技术指标计算等功能著称，常常只要几行函数就能完成从数据获取和处理到画图的复杂功能，其工作效率之高让行家里手都觉得膛目结舌。

## 利用API读取在线行情

### 代码

``````# 加载quantmod包
if(!require(quantmod)){
install.packages("quantmod")
}
# 股票行情匹配函数
Quote = function(code){
index = match(code,universes)
temp = lapply(universes,get)
return(temp[[index]])
}
# 基本配置
universes <<- c("000001.SZ","QIHU","MOMO")
from = "2015-01-04"
to = Sys.Date() # 结束时间设为当前日期
src= "yahoo" # 来源雅虎财经

# 行情加载 速度有点慢，耐心等待
quantmod::getSymbols(universes,from=from,to=to,src=src)

# 绘制行情

## 利用CSV读取离线行情

### 代码

``````# 加载 zoo 时间序列包
library(zoo)
library(quantmod)
# 配置文件路径
filePath = '/Users/harryzhu/temp.csv'
# 读取CSV并转化时间格式
csv\$LZ_GPA_QUOTE_TCLOSE <- as.POSIXct(as.character(csv\$LZ_GPA_QUOTE_TCLOSE),tz="",format="%Y%m%d")
# 转化为zoo类型
# 转化我xts类型
payh =as.xts(temp[,1]);colnames(payh)="Close"
# 制图
chartSeries(payh,name="000001.SZ")
# 添加MACD曲线

## Web应用构建

### ui.R

``````library(shiny)

# 为应用程序定义UI，演示R包quantmod作图功能
shinyUI(
navbarPage("R quantmod Demonstration for Data Products Class", inverse=FALSE,

tabPanel("Documentation",
fluidPage(
verticalLayout(
h2("How to use the R quantmod Demonstration App", align="center"),
hr(),
h3("Directions"),
p("To get started using this application, you'll need to look at the banner line above titled \"R quantmod Demonstration for Data Products Class\" and click \"Demo\".  This will take you to the application itself.  You can click \"Documentation\" to return to this screen."),
p("The application begins by displaying the stock symbol \"^DJI\" which represents the Dow Jones Industrial Average.  You can enter whatever stock symbol you would like (without the caret \"^\") and the graph will update accordingly.  If your stock symbol is not valid - no graph will display"),
p("There are 3 other areas you can play with to change the current display for the selected stock:"),
tags\$ol(tags\$li("Date Range - you can change the date range selected for the price display"),
tags\$li("Chart Theme - you can change how the graph is diplayed by choosing a supported theme"),
tags\$li("Add Optional Technical Analysis Overlays - you can add additional chart items that will calculate some industry analytics and overlay them on the existing chart.  Also a small warning here - some analytics require at least 3 months of data.  If you don't have at least 3 months of data selected in the date range - you may get an error in display of the graph.")),

p("The graph will immediately respond to any changes you make.  Feel free to experiment and explore this application based on R, Shiny, and the quantmod package for R!"),
br(),
p("This application was written for the project in the Coursera course \"Developing Data Products\". It is an example of how to use the quantmod package within R, and what some of its capabilities are."),
p("The app starts by providing a user interface that collects a stock symbol, date range, and optional analytics to perform on the provided stock symbol.  When anything changes in the user interface, the application reacts to the changes by updating the graphs calculated by the server code."),
tags\$ol(tags\$li("Input"), tags\$ul(tags\$li("Stock Symbol - textInput()"), tags\$li("Date Range - dateRangeInput()"), tags\$li("Chart Theme - radioButtions()"), tags\$li("Technical Analysis - checkBoxGroupInput()")),
tags\$li("Operation/Calculation", tags\$ul(tags\$li("Call to getSymbols() to retrieve data"), tags\$li("preparation of variables for graphic display"))),
tags\$li("Reactive Output"), tags\$ul(tags\$li("Call to render graph calculations within the quantmod libraries"), tags\$li("Display of the rendered graph"))),
hr(),
h3("Application Source Code"),
h4("ui.R"),
pre(includeText("ui.R")),
h4("server.R"),
pre(includeText("server.R")),
p("Note: Some code used in this demo is based on the Shiny quantmod tutorial but was not copied wholesale.  The work demonstrated above represents a significant departure from the tutorial.")
)
)
),
tabPanel("Demo",

fluidPage(

# 应用程序标题
#titlePanel("R quantmod Demonstration"),

# 为 quantmod 绘图功能提供参数入口的输入栏
sidebarLayout(
sidebarPanel(
textInput("stock", "Enter a stock symbol", value = "^DJI", width = "30%"),
#      submitButton(text="Get Stock Quote"),
br(),
dateRangeInput("dtRange", "Date Range", start = Sys.Date()-90, end = NULL, min = NULL, max = NULL, format = "yyyy-mm-dd", startview = "month", weekstart = 0, language = "en", separator = " to ", width = NULL),
hr(),
c("White" = "white",
"White Mono" = "white.mono",
"Black" = "black",
"Black Mono" = "black.mono",
"Beige" = "beige",
"WSJ"= "wsj"
)),
checkboxGroupInput("ta", "Add Optional Technical Analysis Overlays:",
"Double Expotential Moving Average" = "addDEMA()",
"Expotential Volume Weighted Moving Average" = "addEVWMA()",
"Moving Average Convergence Divergence" = "addMACD()",
"Parabolic Stop and Reversal Indicator" = "addSAR()",
))

)
),
# 作图
mainPanel(
plotOutput("distPlot", height="885px")
#      ,textOutput("dispPrint")
)
)
)
)
)
)``````

### server.R

``````library(shiny)
library(quantmod)
options("getSymbols.warning4.0"=FALSE)

# Define server logic required to draw a histogram
shinyServer(function(input, output) {

# Expression that generates the stock chart plot. The expression is
# wrapped in a call to renderPlot to indicate that:
#
#  1) It is "reactive" and therefore should re-execute automatically
#     when inputs change
#  2) Its output type is a plot
sSymbol <- reactive({
tryCatch({
suppressWarnings(getSymbols(input\$stock, from=input\$dtRange[1], to=input\$dtRange[2],
auto.assign = FALSE))
}, error = function(err) {
return(NULL)
})
})

output\$distPlot <- renderPlot({
if (!is.null(input\$ta)) {
for (ta in input\$ta) {
taStr<-paste(taStr, paste(";", ta))
}
}

if(!is.null(sSymbol())) {
chartSeries(sSymbol(), name=input\$stock, TA=taStr, theme=chartTheme(input\$theme))
}
})

output\$dispPrint <- renderPrint({
print(sSymbol())
})
})``````

2.2k 声望
2.2k 粉丝
0 条评论