Yahoo API的PHP代码,用于下载CSV文件 [英] PHP code for Yahoo API for downloading CSV file

查看:82
本文介绍了Yahoo API的PHP代码,用于下载CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用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不起作用

但是我一定会误解该过程是什么,因为我总是会收到一条错误消息,指出它无法打开流: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无法下载数据."$ lf;$ iLoop = $ iLoop +1;睡眠(1);} 

解决方案

我现在设法下载了股价历史记录.目前,我仅获取当前价格数据,但我的下载方法会收到过去一年的历史数据.(即,直到Yahoo决定在数据上放置其他一些块).我的解决方案使用"simple_html_dom.php"解析器,该解析器已添加到我的/includes文件夹中.这是代码(从哈佛CS50课程的原始版本修改而来,我向像我这样的初学者推荐):

 函数查找($ symbol){//拒绝以^开头的符号如果(preg_match("/^ \ ^/",$ symbol)){返回false;}//拒绝包含逗号的符号如果(preg_match("/,/",$ symbol)){返回false;}//价格历史记录主体$ sym = $ symbol;$ yahooURL ='https://finance.yahoo.com/quote/'.$sym.'/history?p ='.$ sym;//获取股票名称$ data = file_get_contents($ yahooURL);$ title = preg_match('/< title [^>] *>(.*?)< \/title>/ims',$ data,$ matches)吗?$ matches [1]:空;$ title = preg_replace('/[[a-zA-Z0-9 \.\ |] * \ |/','',$ title);$ title = preg_replace('/Stock \-Yahoo Finance/','',$ title);$ name = $ title;//获取价格数据-使用simple_html_dom.php(添加到/include)$ body = file_get_html($ yahooURL);$ tables = $ body-> find('table');$ dom =新的DOMDocument();$ elements [] = null;$ dom-> loadHtml($ tables [1]);$ x =新的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);//将股票作为关联数组返回返回 [符号" =>$符号,名称" =>$ name,价格" =>$ close,打开" =>$ open,高" =>$高,低" =>$ low,"vol" =>$ vol,"date" =>$ date];} 

I have been using the Yahoo Financial API to download historical stock data from Yahoo. As has been reported on this site, as of mid May, the old API was discontinued. There have been many posts addressed the the form of the new call, e.g.:

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

As well as methods for obtaining the crumb:

Yahoo Finance URL not working

But I must be misunderstanding what the procedure is as I always get an error saying that it "Failed to open stream: HTTP request failed. HTTP/1.0 201 Unauthorized".

Below is my code. Any and all assistance is welcome. I have to admit that I am an old Fortran programmer and my coding reflects this.

Good Roads

Bill

$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);
}

解决方案

I've now managed to download share price history. At the moment I'm only taking the current price figures but my download method receives historical data for the past year. (i.e. until Yahoo decides to put some other block on the data). My solution uses the "simple_html_dom.php" parser which I've added to my /includes folder. Here is the code (modified from the original version from the Harvard CS50 course which I recommend for beginners like me):

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
   ];
}

这篇关于Yahoo API的PHP代码,用于下载CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆