2014-01-24 49 views
0

我想应用用户定义的函数augenSpike通过存储在环境中的一组代码,但不知何故,它不工作。如果有人可以帮助这个入门水平R用户,我会非常感激......使用适用于R与用户定义的功能

library(quantmod) 

slideapply <- function(x, n, FUN=sd) { 
    v <- c(rep(NA, length(x))) 
    for (i in n:length(x)) { 
    v[i] <- FUN(x[(i-n+1):i]) 
    } 
    return(v) 
} 

augenSpike <- function(x, n=20) { 
    prchg <- c(NA, diff(x)) 
    lgchg <- c(NA, diff(log(x))) 
    stdevlgchg <- slideapply(lgchg, n, sd) 
    stdpr <- x * stdevlgchg 
    #shuffle things up one 
    stdpr <- c(NA, stdpr[-length(stdpr)]) 
    spike <- prchg/stdpr 
    return(spike) 
} 
myenv <- new.env() 
# environment used to store tickers 
tickers <- c("PBR", "AAPL", "MSFT", "GOOG") 
getSymbols(tickers, env= myenv) 
sp <-tickers['2013/2014'] 
asp <- augenSpike(as.vector(Cl(sp))) 
sp$spike <- asp 


## Create a vector of colors selected based on whether x is <0 or >0 
## (FALSE + 1 -> 1 -> "blue"; TRUE + 1 -> 2 -> "red") 
cols <- c("blue", "red") [(sp$spike > 0) + 1] 

barplot(sp['2013-2014']$spike, col= cols, main="Augen Price Spike", xlab="Time Daily",ylab="Price Spike in Std Dev") 
abline(h = 2, col = "red") 
abline(h = 0, col = "black") 
abline(h = -2, col = "red") 
+0

你能提供这个问题的降低的例子吗? – weitzner

+0

我想通过myenv中存储的代码重复幻灯片应用程序和AugenSpike函数。问题是,我不知道如何正确使用eapply函数和我的代价。谢谢 –

回答

0

在提供的代码片段,sp是NA,这将导致Cl(sp)失败。原因是tickers仍然是一个字符串矢量,而不是表示股票代码的xts对象。由于使用自定义环境,xts对象无法访问。在没有该环境的情况下,以股票符号命名的新变量将添加到范围中。您可以创建xts对象的辅助矢量,然后使用'2013/2014'下标。下面的脚本应该做你想要什么:

library(quantmod) 

slideapply <- function(x, n, FUN=sd) { 
    v <- c(rep(NA, length(x))) 
    for (i in n:length(x)) { 
    v[i] <- FUN(x[(i-n+1):i]) 
    } 
    return(v) 
} 

augenSpike <- function(x, n=20) { 
    prchg <- c(NA, diff(x)) 
    lgchg <- c(NA, diff(log(x))) 
    stdevlgchg <- slideapply(lgchg, n, sd) 
    stdpr <- x * stdevlgchg 
    #shuffle things up one 
    stdpr <- c(NA, stdpr[-length(stdpr)]) 
    spike <- prchg/stdpr 
    return(spike) 
} 

tickers <- c("PBR", "AAPL", "MSFT", "GOOG") 
getSymbols(tickers) 
ticker_symbols <- c(PBR, AAPL, MSFT, GOOG) 

sp <-ticker_symbols['2013/2014'] 
asp <- augenSpike(as.vector(Cl(sp))) 
sp$spike <- asp 


## Create a vector of colors selected based on whether x is <0 or >0 
## (FALSE + 1 -> 1 -> "blue"; TRUE + 1 -> 2 -> "red") 
cols <- c("blue", "red") [(sp$spike > 0) + 1] 

barplot(sp['2013-2014']$spike, col= cols, main="Augen Price Spike", xlab="Time Daily",ylab="Price Spike in Std Dev") 
abline(h = 2, col = "red") 
abline(h = 0, col = "black") 
abline(h = -2, col = "red") 

将会产生这个可爱的图形:Output from R script

+0

在上面的代码中它不能是NA,代码运行完美,除了它不读取环境中的所有代码。无论如何,无论如何感谢 –

+0

我已经更新这个帖子,包括脚本的修改版本,应该做你想做的。 – weitzner