循环通过new.env()R(quantmod)

时间:2017-06-03 14:54:21

标签: r loops quantmod

我是R,loop和quantmod的新手。 我正在尝试构建一个可以更容易用于计算的数据库(以列格式)。

我想知道如何使用“循环”来自动化下面的过程。 我只是将两个数据集绑定在一起。

正如您所看到的,我使用rbind,Google和Apple股票价格绑定了两个数据集。如果我有100只股票,这个过程需要很长时间,因此我想知道如何自动化这个过程?

library(quantmod)
tickers<- c("AAPL", "GOOG")
all<- new.env()
getSymbols(tickers,src="google", env = all, from = Sys.Date()-100, to = Sys.Date())

apple_share<- all$AAPL
colnames(apple_share)<- c("Open", "High", "Low", "Close", "Volume")
apple_share$Ticker<- rep(1, nrow(apple_share))

google_share<- all$GOOG
colnames(google_share)<- c("Open", "High", "Low", "Close", "Volume")
google_share$Ticker<- rep(2, nrow(google_share))

combined_data<- rbind(apple_share,google_share)

非常感谢,

Shoups

2 个答案:

答案 0 :(得分:1)

创建包tidyquant完全是为了您所要求的任务而创建的。假设您将quantmod软件包更新为版本0.4-9,再次允许从YAHOO下载价格,tq_get函数将下载数据,并且通过“按符号分组”,您将获得所需的输出。

> library(tidyquant)
stocks <- c("AAPL", "GOOG", "NFLX") %>%
     tq_get(get  = "stock.prices",
            from = "2010-01-01",
            to   = "2015-12-31") %>%
     group_by(symbol)

> stocks
Source: local data frame [4,527 x 8]
Groups: symbol [3]

# A tibble: 4,527 x 8
   symbol       date   open   high    low  close    volume
    <chr>     <date>  <dbl>  <dbl>  <dbl>  <dbl>     <dbl>
 1   AAPL 2010-01-04 213.43 214.50 212.38 214.01 123432400
 2   AAPL 2010-01-05 214.60 215.59 213.25 214.38 150476200
 3   AAPL 2010-01-06 214.38 215.23 210.75 210.97 138040000
 4   AAPL 2010-01-07 211.75 212.00 209.05 210.58 119282800
 5   AAPL 2010-01-08 210.30 212.00 209.06 211.98 111902700
 6   AAPL 2010-01-11 212.80 213.00 208.45 210.11 115557400
 7   AAPL 2010-01-12 209.19 209.77 206.42 207.72 148614900
 8   AAPL 2010-01-13 207.87 210.93 204.10 210.65 151473000
 9   AAPL 2010-01-14 210.11 210.46 209.02 209.43 108223500
10   AAPL 2010-01-15 210.93 211.60 205.87 205.93 148516900
# ... with 4,517 more rows, and 1 more variables: adjusted <dbl>

答案 1 :(得分:0)

我们可以使用NUMERIC

获取值
// displays event listings on browse.html - modified 3/6/17
   events.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
    var eventkey = childSnapshot.key;
    var eventdata = childSnapshot.val();

    // listing data to be displayed
    var browsetitle = childSnapshot.val().title; // added this
    var browsecity = childSnapshot.val().city; // added this

    var card = document.createElement('div');
    card.setAttribute('class', 'card');
    document.body.appendChild(card);

    var cardtitle = document.createElement('p');
    cardtitle.innerHTML = browsetitle + browsecity; // added this
    card.appendChild(cardtitle);  

   console.log(eventdata); // changed this to see what was going on
    });
 });