错误:无法在Shiny app中找到股票预测模型

时间:2016-09-15 21:59:19

标签: shiny prediction stock

我的任务是采用股票预测模型并将其置于Shiny中。我对R的成功起伏不定。代码有点混乱,但希望能够超越这一点,并尝试将其清理为更好的代码。

我收到错误

Error: could not find function "myATR"

这似乎是来自这一行,我正在构建一个公式字符串以赋予指定模型。

这是

formula <- as.formula(paste0("Next(Cl(",symbol(),"),",i,") ~ Delt(Cl(",symbol(),"),k=1)+myATR(",symbol(),")+myADX(",symbol(),")+myEMV(",symbol(),")+myVolat(",symbol(),")+myMACD(",symbol(),")+mySAR(",symbol(),")+runMean(Cl(",symbol(),"))"))

公式myATV在代码中定义为

myATR   <- function(x) ATR(HLC(x))[,'atr']

我很难过,不知道怎么回答这个问题。我已将我的ui.R和server.R包括在内。

ui.R
    # Stock Symbols
    # #####
    # AAPL - Apple Inc.
    # GOOGL - Alphabet Inc.
    # ORCL - Oracle Corporation
    # FB - Facebook, Inc.
    # TWTR - Twitter Inc

    shinyUI(fluidPage(
        titlePanel("Stock Tickers and Prediction Models, Predicting Future Close Prices"),
            sidebarLayout(
                sidebarPanel(
                    selectInput("symbolID", label= "Select ticker", 
                        choices = list("XXII" = 1, "GOOGL" = 2, "ORCL" = 3, "MSFT" = 4, "AIG" = 5)),
                    selectInput("modelID", label= "Select ticker", 
                        choices = list("svm" = 1, "random forest" = 2, "neural network"  = 3))
        ),

        mainPanel(
            plotOutput("Graph"),
            tableOutput("getsymbols"),
            tableOutput("Predictions")
        )
      )
    ))

server.R

    library(shiny)
    library(quantmod) 
    library(e1071) 
    library(nlme)
    library(earth)
    library(xts)

    # for stock symbols
    symbols = {}

    # for model symbols
    models = {}

    # end date and start dates based on system time
    endDate = as.Date(Sys.Date() - 1, format = "%Y-%M-%D")
    startDate = as.Date(endDate - 1000, format = "%Y-%M-%D")

    myATR   <- function(x) ATR(HLC(x))[,'atr']
    myADX   <- function(x) ADX(HLC(x))[,'ADX']
    myEMV   <- function(x) EMV(cbind(Hi(x),Lo(x)),Vo(x))[,2]
    myMACD  <- function(x) MACD(Cl(x))[,2]
    mySAR   <- function(x) SAR(cbind(Hi(x),Cl(x))) [,1]
    myVolat <- function(x) volatility(OHLC(x),calc="garman")[,1]

    shinyServer(function(input, output){
        inputSymbols <- reactive({
            if (input$symbolID == 1) { 
                symbols = 'XXII'  
            } else if (input$symbolID == 2) { 
                symbols = 'GOOGL'  
            } else if (input$symbolID == 3) { 
                symbols = 'ORCL'  
            } else if (input$symbolID == 4) { 
                symbols = 'MSFT'  
            } else if (input$symbolID == 5) {
                symbols = 'AIG'  
            }

            getSymbols(symbols, src = "yahoo", from = startDate, to = endDate, auto.assign = FALSE)
        })

        symbol <- reactive({
            if (input$symbolID == 1) { 
                symbols = 'XXII'  
            } else if (input$symbolID == 2) { 
                symbols = 'GOOGL'  
            } else if (input$symbolID == 3) { 
                symbols = 'ORCL'  
            } else if (input$symbolID == 4) { 
                symbols = 'MSFT'  
            } else if (input$symbolID == 5) {
                symbols = 'AIG'  
            }

            symbols
        })

        model <- reactive({
            if (input$modelID == 1) { 
                models = 1  
            } else if (input$modelID == 2) { 
                models = 2  
            } else if (input$modelID == 3) { 
                models = 3
            } 

            models
        })
        #model <- reactive(input@model)


        # graph output
        output$Graph <- renderPlot({
            chartSeries(inputSymbols(), subset = paste(endDate - 30, endDate, sep = "/"), type = 'line', theme = 'white')
        })

        #output$getsymbols = renderPrint({symbol()})

        output$Predictions <- renderTable({
            getSymbols(symbol())

            #Obtain prediction model for a given iteration
            GetPredModel <- function(i){
                formula <- as.formula(paste0("Next(Cl(",symbol(),"),",i,") ~ Delt(Cl(",symbol(),"),k=1)+myATR(",symbol(),")+myADX(",symbol(),")+myEMV(",symbol(),")+myVolat(",symbol(),")+myMACD(",symbol(),")+mySAR(",symbol(),")+runMean(Cl(",symbol(),"))"))
                #formula <- as.formula(paste0("Next(Cl(",symbol(),")",",",i,") ~ Delt(Cl(",symbol(),"),k=1)+myATR(",symbol(),")+myADX(",symbol(),")+myEMV(",symbol(),")+myVolat(",symbol(),")+myMACD(",symbol(),")+mySAR(",symbol(),")+runMean(Cl(",symbol(),"))"))
                m <- specifyModel(formula)
                data <- as.data.frame(modelData(m))
                return(data)
            } 

            #Derive max data available
            maxdate<-max(index(get(symbol())))

            #Define prediction as xts object  
            prediction<-xts()
            n=1
            while(n<=5){

                data<-GetPredModel(n)
                formula <- as.formula(paste0("Next.Cl.",symbol(),".",n," ~ ."))  
                set.seed(1234)

                # pick model
                if (model() == 1) { 
                    res <- svm(formula,data,cost=10,gamma=0.01)
                } else if (model() == 2) { 
                    res<- randomForest(formula,data,na.action = na.omit, ntree=200)
                } else if (model() == 3) { 
                    res<-nnet(formula,data, size=10, decay=0.01, maxit=1000, linout=T, trace=F) 
                }

                pred_date<-as.Date(maxdate) + n
                p <- predict(res,data[as.character(maxdate),])
                #print(pred_date)
                names(p)<-c(as.character(pred_date))
                prediction<-rbind(as.xts(cbind(p)),prediction)

                n = n + 1
            }
        })
    })

2 个答案:

答案 0 :(得分:0)

当我尝试使用应用功能nnet时,无法找到randomForest。你错过了这两个套餐吗?

答案 1 :(得分:0)

以下是按工作顺序提交的内容。根据mRcSchwering,范围问题很重要。希望这有助于某人。

library(shiny)
library(quantmod) 
library(e1071) 
library(nlme)
library(xts)
library(DMwR)
library(TTR)
library(nnet)
library(randomForest)
library(gridExtra)

myATR   <- function(x) ATR(HLC(x))[,'atr']
myADX   <- function(x) ADX(HLC(x))[,'ADX']
myEMV   <- function(x) EMV(cbind(Hi(x),Lo(x)),Vo(x))[,2]
myMACD  <- function(x) MACD(Cl(x))[,2]
mySAR   <- function(x) SAR(cbind(Hi(x),Cl(x))) [,1]
myVolat <- function(x) volatility(OHLC(x),calc="garman")[,1]

assign("myATR", myATR, envir = .GlobalEnv)
assign("myADX", myADX, envir = .GlobalEnv)
assign("myEMV", myEMV, envir = .GlobalEnv)
assign("myMACD", myMACD, envir = .GlobalEnv)
assign("mySAR", mySAR, envir = .GlobalEnv)
assign("myVolat", myVolat, envir = .GlobalEnv)

#Obtain prediction model for a given iteration
GetPredModel <- function(i, stockName){
  formula <- as.formula(paste0("Next(Cl(",stockName,")",",",i,") ~ Delt(Cl(",stockName,"),k=1)+myATR(",stockName,")+myADX(",stockName,")+myEMV(",stockName,")+myVolat(",stockName,")+myMACD(",stockName,")+mySAR(",stockName,")+runMean(Cl(",stockName,"))"))
  m <- specifyModel(formula)
  data <- as.data.frame(modelData(m))
  return(data)
} 

shinyServer(function(input, output){

    # graph output
    output$Graph <- renderPlot({

      stockName = input$symbolID
      modelID = input$modelID

      # end date and start dates based on system time
      endDate = as.Date(Sys.Date() - 1, format = "%Y-%M-%D")
      startDate = as.Date(endDate - 180, format = "%Y-%M-%D")

      # Plot the actual stock price
      chartData <- getSymbols(stockName, src = "yahoo", from = startDate, to = endDate, auto.assign = FALSE)
      chartSeries(chartData, subset = paste(endDate - 30, endDate, sep = "/"), type = 'line', theme = 'white')

    })


    # Calculate forecast and plot forecast
    output$Predictions <- renderPlot({

      stockName = input$symbolID
      modelID = input$modelID

      # end date and start dates based on system time
      endDate = as.Date(Sys.Date() - 1, format = "%Y-%M-%D")
      startDate = as.Date(endDate - 180, format = "%Y-%M-%D")

      #Derive max data available
      maxdate<-max(index(getSymbols(stockName, auto.assign = FALSE)))

      #Define prediction as xts object  
      prediction<-xts()
      n=1
      while(n<=5){

        data<-GetPredModel(n, stockName)
        formula <- as.formula(paste0("Next.Cl.",stockName,".",n," ~ ."))  
        set.seed(1234)

        # pick model
        if (modelID == 1) { 
          res <- svm(formula,data,cost=10,gamma=0.01)
        } else if (modelID == 2) { 
          res<- randomForest(formula,data,na.action = na.omit, ntree=200)
        } else if (modelID == 3) { 
          res<-nnet(formula,data, size=10, decay=0.01, maxit=1000, linout=T, trace=F) 
        }

        pred_date<-as.Date(maxdate) + n
        p <- predict(res,data[as.character(maxdate),])
        if (modelID == 3){
            p <- p[,1]
        }
        #print(pred_date)
        names(p)<-c(as.character(pred_date))
        prediction<-rbind(as.xts(cbind(p)),prediction)

        n = n + 1
      }

      plot(prediction)

      #grid.arrange(pActual, pPredict, ncol= 1)

    })
})