Just for fun, lets use a little web voodoo to combine Yahoo Finance data with Google Charts. Why?… because we can. All we need is a little PHP, a web server, and a URL. The goal is to download Yahoo Finance daily price data for two stocks, convert it to an array of daily returns, and plot the results using Google Charts simply by calling a URL. For instance, to produce this:

We just need to type this into our browser: http://stotastic.com/php/scatterPlot.php?tick1=BP&tick2=SPY&mm=01&dd=01&yyyy=2008
Where tick1 and tick2 are the stock tickers; and mm, dd, yyyy represent the starting date from which data is grabbed. So lets dig in and find out how PHP is used to make all this web magic work.

PHP Code

First, we need a function that downloads the data from Yahoo Finance.

// read in Yahoo finance, parse, and return array
function yahoo_get_adjclose($ticker, $mm, $dd, $yyyy) {
  // subtract 1 from mm since January is 0
  $mm = $mm-1;
 
  $url = "http://ichart.finance.yahoo.com/table.csv?s=$ticker&a=$mm&b=$dd&c=$yyyy";
  $ticker_data = CSV_to_array(file_get_contents($url));
 
  // extract adjusted close and reverse data
  // last row excluded since blank after parse
  $rowcount = count($ticker_data);
  for($i=($rowcount-2); $i>1; $i--){
    $ticker_adjclose[] = (float)$ticker_data[$i][6];
  } 
 
  return($ticker_adjclose);
}

Notice that we called a utility function to convert the data from a CSV to an array. We need this function because the data is returned from Yahoo Finance in a CSV and needs to be parsed into an array to be useful to us.

// function to parse CSV and return array
function CSV_to_array($strData) {
 
  $arrRows = explode("\n", $strData);
  foreach($arrRows as $strRow){
    $arrReturn[] = explode(",", $strRow);
  }
 
  return $arrReturn;
}

Also, in order to convert an array of daily close prices to returns, we’ll use the following utility function.

// convert value to log return
function log_return($x){
  for($i=0; $i<(count($x)-1); $i++){
    $r[] = log($x[$i+1]/$x[$i]);
  }
  return $r;
}

Finally, we put the above code to work by taking in a GET request, using the above functions to download Yahoo Finance data and convert it to an array of returns, send the data to Google in a POST request, and pass on the resulting image back to the user. The reason we are sending a POST request to send the data to Google rather than a GET is because we will be exceeding the data size of a GET request. More info on how to send a POST request to Google can be found here.

header('content-type: image/png'); 
$url = 'http://chart.apis.google.com/chart'; 
 
// get variables
$ticker1 = $_GET["tick1"];
$ticker2 = $_GET["tick2"];
$mm = $_GET["mm"];
$dd = $_GET["dd"];
$yyyy = $_GET["yyyy"];
$title = "Daily Return (%)";
 
// limit date to keep data size transfer down
$year_limit = (int)date("Y")-2;
if($yyyy<$year_limit) {
  $mm = 01;
  $dd = 01;
  $yyyy = 2008;
}
 
// read in Yahoo Finance data
$ticker1_data = yahoo_get_adjclose($ticker1, $mm, $dd, $yyyy);
$ticker2_data = yahoo_get_adjclose($ticker2, $mm, $dd, $yyyy);
 
// calculate log returns
$x = log_return($ticker1_data);
$y = log_return($ticker2_data);
 
// scale data to 1 to 100 range
$xmax = ceil(max($x)*10)/10;
$xmin = floor(min($x)*10)/10;
$ymax = ceil(max($y)*10)/10;
$ymin = floor(min($y)*10)/10;
 
foreach($x as $val){
  $xscaled[] = round(($val-$xmin)/($xmax-$xmin)*1000)/10;
}
 
foreach($y as $val){
  $yscaled[] = round(($val-$ymin)/($ymax-$ymin)*1000)/10;
}
 
// calculate chart range params
$xrange_max = $xmax*100;
$xrange_min = $xmin*100;
$yrange_max = $xmax*100;
$yrange_min = $xmin*100;
 
$xdash = 100/(($xrange_max - $xrange_min)/5);
$ydash = 100/(($yrange_max - $yrange_min)/5);
 
// Add chart array with data and params 
$chart = array( 
  'cht' => 's', 
  'chs' => '400x400', 
  'chd' => "t:".implode(",",$xscaled)."|".implode(",",$yscaled),
  'chxt' => "x,x,y,y",
  'chxr' => "0,$xrange_min,$xrange_max,5|2,$yrange_min,$yrange_max,5",
  'chm' => "o,3399FF,0,-1,5", 
  'chg' => "$xdash,$ydash", 
  'chtt' => "$title", 
  'chxl' => "1:|$ticker1|3:|$ticker2|",
  'chxp' => "1,50|3,50");
 
// Send the request, and print out the returned bytes. 
$context = stream_context_create( 
  array('http' => array( 
    'method' => 'POST', 
    'content' => http_build_query($chart)))); 
fpassthru(fopen($url, 'r', false, $context));

And there you have it! Google performs very little data processing, probably in order to keep server capacity down; therefore, a big chunk of the code above is needed to scale and format the data before sending it to Google. Take my server for a spin by typing something like this into your browser: http://stotastic.com/php/scatterPlot.php?tick1=JPM&tick2=GS&mm=01&dd=01&yyyy=2009, but please be kind to my server! (there is a GET sanitizing step I’m not showing in the code above).

13 Responses to “Yahoo Finance and Google Charts Mashup using PHP”

  1. i found your site through search engine.i like your web
    page content and very attractive theme.really i like this
    it.

    Thanks.:)

  2. Cher Doemelt says:

    Hi, I just like your writings. Keep up with writing and we hope to hear more from you soon.

    all the best

  3. Chris says:

    Hi,

    I’m extremely interested in implementing this on to my site. Would you be able to assist? Could you send me the php file?

    info@derailedcapitalism.com

    Thanks,
    Chris

  4. I don’t even know how I finished up right here, but I thought this submit was once good. I don’t understand who you might be but certainly you are going to a well-known blogger if you aren’t already ;) Cheers!

  5. Trorbiniany says:

    Сколько вас всего? спросила Даша.
    Благие… вздрогнул бизнесмен. Что же еще?
    Здравствуй, Дарв, мрачно поздоровался гость. Сейчас будешь говорить, что ты предупреждал, что наш путь тупиковый и так далее?
    Хозяин… прохрипел он. Там… Там…
    А по шее? мрачно спросила женщина, пренебрежительно глянув на хихикающего парня.

    Строгая диета
    Диета при псориазе
    Углеводная диета
    Диета меню на неделю
    Лечение диетой

    Белковая диета для похудения
    Диета при язве
    Как похудеть за месяц
    Как похудеть за 2 месяца
    Диет клиник

    Таблица диеты
    Тарасова татьяна анатольевна похудела
    Индивидуальная диета
    Здоровье с еленой малышевой похудеть
    Диета 12

    Диета при язве двенадцатиперстной кишки
    Похудеть на гречке
    Луковая диета
    Диета екатерины
    Способы похудеть быстро

    Способы похудеть быстро
    Японская диета отзывы
    Татьяна тарасова похудела на 30
    Яичная диета на 4 недели
    Кремлевская диета меню на месяц

    Как похудеть без диет
    Диеты для похудения отзывы
    Диета бородиной ксении бесплатно
    Диета на овсянке
    Гречневая диета до и после

    Диета
    Диета 4
    Результаты после гречневой диеты
    За сколько можно похудеть
    Похудеть малышева

    Диета онлайн
    Диета кг за неделю
    Диета при запорах
    Диета при холецистите
    Безуглеводная диета таблица

    Кремлевская диета
    Книга похудеть навсегда
    Похудеть активированный уголь
    Инна воловичева диета
    Как похудела татьяна тарасова

    Таблица диеты
    Диета мухиной
    Новые диеты
    Диета бессолевая
    Диета на воде

    Диета ковалькова
    Меню для диеты
    Королева диета отзывы
    Диеты при болезнях
    Диета 12 дней

    Уксус похудеть
    Диета кима
    Диета маргариты королевой 9 дней
    Эффект диета
    Кремлевская диета меню

  6. Wow, superb blog layout! How lengthy have you been blogging for? you make blogging glance easy. The overall look of your web site is wonderful, as smartly the content!

  7. daffie0 says:

    Hi all!
    Take a dose of levitra 25 to 60 minutes before you wish to have sex with your partner. herbal
    Goodluck!!!
    ____________________________
    cheap credit :)

  8. Heyyy. Are you looking for a Assisted Living Facilities?

  9. Angelo Bauce says:

    I have read several good stuff here. Definitely price bookmarking for revisiting. I wonder how a lot attempt you set to create the sort of excellent informative site.

  10. Rajandran R says:

    Hi,

    I’m extremely interested in implementing this on to my site. Would you be able to assist? Could you send me the php file?

    rajandran@gmail.com

    Thanks,
    Rajandran R

  11. Elie Cottage says:

    What else is there…

    I’m sure there was an article on The Sun on this topic….

  12. jobs for high school students – Search for Jobs on our web site, we supply several great links towards the greatest and biggest Portals to finding a Job as a high school student!

  13. An fascinating dialogue is value comment. I believe that you must write extra on this matter, it may not be a taboo topic however usually persons are not enough to speak on such topics. To the next. Cheers

Leave a Reply