【问题标题】:PHP code for Yahoo API for downloading CSV file用于下载 CSV 文件的 Yahoo API 的 PHP 代码
【发布时间】:2017-10-30 04:41:25
【问题描述】:

我一直在使用 Yahoo Financial API 从 Yahoo 下载历史股票数据。正如本网站所报道的,截至 5 月中旬,旧 API 已停止使用。有很多帖子针对新呼叫的形式,例如:

https://query1.finance.yahoo.com/v7/finance/download/AAPL?period1=315561600&period2=1496087439&interval=1d&events=history&crumb=XXXXXXXXXXX

以及获取面包屑的方法:

Yahoo Finance URL not working

但我一定是误解了程序是什么,因为我总是收到一条错误消息,说“无法打开流:HTTP 请求失败。HTTP/1.0 201 未授权”。

下面是我的代码。欢迎任何和所有的帮助。我不得不承认我是一个老 Fortran 程序员,我的编码反映了这一点。

好路

比尔

$ticker = "AAPL";
$yahooURL="https://finance.yahoo.com/quote/" .$ticker ."/history";
$body=file_get_contents($yahooURL);
$headers=$http_response_header;
$icount = count($headers);
for($i = 0; $i < $icount; $i ++)
{
    $istart = -1;
    $istop = -1;
    $istart = strpos($headers[$i], "Set-Cookie: B=");
    $istop = strpos($headers[$i], "&b=");
    if($istart > -1 && $istop > -1)
    {
        $Cookie = substr ( $headers[$i] ,$istart+14,$istop - ($istart + 14));
    }
}

$istart = strpos($body,"CrumbStore") + 22;
$istop = strpos($body,'"', $istart);
$Crumb = substr ( $body ,$istart,$istop - $istart);

$iMonth = 1;
$iDay = 1;
$iYear = 1980;
$timestampStart = mktime(0,0,0,$iMonth,$iDay,$iYear);
$timestampEnd = time();

$url =  "https://query1.finance.yahoo.com/v7/finance/download/".$ticker."?period1=".$timestampStart."&period2=".$timestampEnd."&interval=1d&events=history&crumb=".$Cookie."";

while (!copy($url, $newfile) && $iLoop < 10)
{
    if($iLoop == 9) echo "Failed to download data." .$lf;
    $iLoop = $iLoop + 1;
    sleep(1);
}

【问题讨论】:

标签: php csv yahoo-finance


【解决方案1】:

我现在已经成功下载了股价历史记录。目前我只采用当前的价格数据,但我的下载方法会收到过去一年的历史数据。 (即,直到雅虎决定在数据上放置一些其他块)。 我的解决方案使用我添加到 /includes 文件夹的“simple_html_dom.php”解析器。 这是代码(根据哈佛 CS50 课程的原始版本修改,我推荐给像我这样的初学者):

function lookup($symbol)
{
// reject symbols that start with ^
   if (preg_match("/^\^/", $symbol))
   {
       return false;
   }
// reject symbols that contain commas
   if (preg_match("/,/", $symbol))
   {
       return false;
   }
   // body of price history search
$sym = $symbol;
   $yahooURL='https://finance.yahoo.com/quote/'.$sym.'/history?p='.$sym;

// get stock name
$data = file_get_contents($yahooURL);
    $title = preg_match('/<title[^>]*>(.*?)<\/title>/ims', $data, $matches) ? $matches[1] : null;

$title = preg_replace('/[[a-zA-Z0-9\. \| ]* \| /','',$title);
$title = preg_replace('/ Stock \- Yahoo Finance/','',$title);
$name = $title;

// get price data - use simple_html_dom.php (added to /include)
$body=file_get_html($yahooURL);
$tables = $body->find('table');
$dom = new DOMDocument();
$elements[] = null;
$dom->loadHtml($tables[1]); 
$x = new DOMXpath($dom);
$i = 0;
foreach($x->query('//td') as $td){
        $elements[$i] = $td -> textContent." ";
    $i++;
}
$open = floatval($elements[1]); 
$high = floatval($elements[2]);
$low = floatval($elements[3]);
$close = floatval($elements[5]);
$vol = str_replace( ',', '', $elements[6]);
$vol = floatval($vol);
$date = date('Y-m-d');
$datestamp = strtotime($date);
$date = date('Y-m-d',$datestamp);
   // return stock as an associative array
   return [
        "symbol" => $symbol,
        "name" => $name,
        "price" => $close,
        "open" => $open,
        "high" => $high,
        "low" => $low,
        "vol" => $vol,
        "date" => $date
   ];
}

【讨论】:

    【解决方案2】:

    @Craig Cocca 这并不完全是重复的,因为您提供的参考给出了 python 中的解决方案,对于我们这些使用 php 但尚未学习 python 的人来说并没有多大帮助。我很乐意看到 php 的解决方案。我检查了雅虎页面并且能够提取面包屑,但无法弄清楚如何将其放入流和 GET 调用中。 我最近(失败)的努力是:

            $headers = [
            "Accept" => "*/*",
            "Connection" => "Keep-Alive",
            "User-Agent" => sprintf("curl/%s", curl_version()["version"])       
        ];
    
        // open connection to Yahoo
        $context = stream_context_create([
            "http" => [
                "header" => (implode(array_map(function($value, $key) { return sprintf("%s: %s\r\n", $key, $value); }, $headers, array_keys($headers))))."Cookie: $Cookie",
                "method" => "GET"
            ]
        ]);
        $handle = @fopen("https://query1.finance.yahoo.com/v7/finance/download/{$symbol}?period1={$date_now}&period2={$date_now}&interval=1d&events=history&crumb={$Crumb}", "r", false, $context);
        if ($handle === false)
        {
            // trigger (big, orange) error
            trigger_error("Could not connect to Yahoo!", E_USER_ERROR);
            exit;
        } 
    
        // download first line of CSV file
        $data = fgetcsv($handle);
    

    这两个日期是 unix 编码的日期,即: $date_now = strtotime($date);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-05
      • 2015-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多