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.:
As well as methods for obtaining the crumb:
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);
}