R Shiny中基于移动平均线预测时出现unused argument (.)错误求助
解决Shiny中基于移动平均线金融预测的“unused argument (.)”错误
错误根源
你遇到的“unused argument (.)”错误是明确的笔误:在R Studio可运行的代码中,你用ts()函数将移动平均线向量转换为时间序列对象,但在Shiny Server代码里误写成了调用反应式函数dataInput()。dataInput()是一个不需要参数的反应式表达式,通过管道%>%传入df$MA10会导致它无法识别这个额外参数,从而抛出错误。
具体修正步骤
修正时间序列转换代码
将错误的代码行:ts<- df$MA10%>%dataInput()替换为和R Studio逻辑一致的时间序列转换代码:
ts <- df$MA10 %>% ts()处理NA值
TTR::SMA()计算的前99个值(n=100)为NA,直接传给forecast()会报错,需要先移除缺失值:ts <- df$MA10 %>% na.omit() %>% ts()完善renderPlot输出逻辑
Shiny的renderPlot()需要实际生成绘图对象,原代码仅返回fma不会自动绘图,需添加plot()函数:plot(fma, xlab = "Days", ylab = "Closing prices", main = "100 days forecast based on moving average")
修正后的完整Server代码
output$forecast<- renderPlot({ req(input$dates, dataInput()) # 同时依赖数据输入,确保数据加载完成 df <- data.frame(dataInput()) names(df) <- c("Open", "High", "Low", "Close", "Volume", "Adjusted") df$Date <- as.Date(rownames(df)) df$MA10 <- TTR::SMA(df$Close, n = 100) # 修正时间序列转换并处理NA ts <- df$MA10 %>% na.omit() %>% ts() fma <- forecast(ts, h=100) # 生成绘图输出 plot(fma, xlab = "Days", ylab = "Closing prices", main = "100 days forecast based on moving average") })
额外优化建议
- 在Shiny应用开头加载所有依赖库:
library(quantmod) library(TTR) library(forecast) library(dplyr) - 移除
dataInput()中的isolate(),否则反应式不会响应输入变化,导致数据无法更新:dataInput <- reactive({ req(input$symb, input$dates) getSymbols(input$symb, src="yahoo", from = input$dates[1], to = input$dates[2], warnings = FALSE, auto.assign = FALSE) })
内容的提问来源于stack exchange,提问作者magiccarrot
相关产品推荐
相关产品推荐

