Philadelphia Reflections

The musings of a physician who has served the community for over six decades

Related Topics

George (3)
It's often desirable to get live financial data and everyone knows. XML is the thing to use but actually writing programs that work takes a bit of trouble. Plus, once you've got the data you need to display it.

Get Historical Stock Data in PHP (single date; from Yahoo Finance)

This PHP function returns data for a stock on a single specific date, using Yahoo Finance's CSV data.

I use file_get_contents; some servers will force you to use CURL.

<?php
//
// Takes in a symbol and a date;
// returns the Yahoo Finance Historical data for that single date
// If there's no data, the array is empty.
//
/*

$quote = YahooHistoricalStockQuote("VTI", strtotime("2009-09-11"));
print_r($quote);

Array
(
    [Open] => 53.14
    [High] => 53.32
    [Low] => 52.80
    [Close] => 53.08
    [Volume] => 1291300
    [Adj Close] => 49.43
)

*/

function YahooHistoricalStockQuote($Symbol, $QuoteDate)
{
  $month = date("m", $QuoteDate)-1; $day = date("d", $QuoteDate); $year = date("Y", $QuoteDate);

  $url = "http://ichart.finance.yahoo.com/table.csv?s=$Symbol&a=$month&b=$day&c=$year&d=$month&e=$day&f=$year&g=d&ignore=.csv";

  $return_data = @file_get_contents($url);
  $parts       = explode(",", $return_data);

  $data['Open']      = $parts[7];
  $data['High']      = $parts[8];
  $data['Low']       = $parts[9];
  $data['Close']     = $parts[10];
  $data['Volume']    = $parts[11];
  $data['Adj Close'] = $parts[12];

  return $data;
}
?>

My thanks to Encode / Decode HTML Entities

 

Please Let Us Know What You Think

 
 

(HTML tags provide better formatting)