【问题标题】:Extracting data from Yahoo Finance从雅虎财经中提取数据
【发布时间】:2020-01-24 13:25:07
【问题描述】:

我创建了下面的代码,可以很好地从雅虎财经获取特定公司的一些数据(股票价格和交易量)。我的挑战是我只有 100 个观察值。我想获取那里的所有数据。

我应该如何调整代码来实现这一点? 谢谢。

library(rvest)
library(tidyverse)

x <- 'SAP'
wb <- paste0('https://finance.yahoo.com/quote/', x, '/history?p=', x)

browseURL(wb)

read_html(wb) %>%
  html_node(css =  "table") %>%
  html_table %>%
  as_tibble -> df

【问题讨论】:

  • 您可以考虑使用 R quantmod 包从 Yahoo 下载数据。它可以快速下载某个日期范围内股票列表的价格和数量数据。

标签: r web-scraping rvest


【解决方案1】:

页面上实际上有一个指向可下载 csv 的链接。您可以在下载之前在 R 中指定公司和时间段等。

唯一的问题是 url 需要包含一个名为“crumbs”的参数,它实际上是您的会话 ID,您需要从页面中获取它来构建 url。

我已经编写了一个函数来完成这一切。您需要做的就是提供公司名称,它将提供过去 15 年左右的所有财务记录作为数据框。

  get_financial_data <- function(company)
  {
    tmp <- tempfile()
    yahoo <- httr::handle('https://finance.yahoo.com/quote/')

    'https://finance.yahoo.com/quote/' %>%
    paste0(company)                    %>%
    paste0('/history?p=')              %>%
    paste0(company)                    %>%
    httr::GET(handle = yahoo)          %>%
    httr::content("text")               -> raw_html

    strsplit(raw_html, "crumb\":\"")   %>%
    unlist                             %>%
    strsplit("\"")                     %>%
    lapply(`[`, 1)                     %>%
    unlist                             %>%
    table                              %>%
    sort                               %>%
    rev                                %>%
    names                              %>%
    `[`(2)                             %>% 
    paste0("https://query1.finance.yahoo.com/v7/finance/download/", company, 
          "?period1=1079873500&period2=1579873500&interval=1d&events=history&crumb=", .) %>%
    httr::GET(handle = yahoo) %>%
    httr::content("text", encoding = "UTF-8") %>%
    writeBin(tmp, useBytes = T)

    suppressWarnings(read.csv(tmp) %>% tibble::as_tibble())
  }

现在你可以这样做了:

get_financial_data("SAP")
#> # A tibble: 3,988 x 7
#>    Date        Open  High   Low Close Adj.Close  Volume
#>    <fct>      <dbl> <dbl> <dbl> <dbl>     <dbl>   <int>
#>  1 2004-03-22  37.4  37.5  36.7  37.3      29.3 1717600
#>  2 2004-03-23  37.8  37.9  37.4  37.5      29.5 1417500
#>  3 2004-03-24  37.4  38.1  37.2  37.5      29.5 1682500
#>  4 2004-03-25  37.9  38.9  37.9  38.8      30.4 2233800
#>  5 2004-03-26  37.9  38.2  37.5  37.9      29.8 3343500
#>  6 2004-03-29  38.6  39.3  38.6  38.8      30.5 1886800
#>  7 2004-03-30  38.8  39.3  38.8  39.1      30.7  997900
#>  8 2004-03-31  39.5  39.8  39.3  39.3      30.9 1818600
#>  9 2004-04-01  39.8  40.6  39.8  40.6      31.9 2570600
#> 10 2004-04-02  40.9  41.3  40.6  41.1      32.3 1708200
#> # ... with 3,978 more rows

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2021-08-03
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    相关资源
    最近更新 更多