Skip to content

Instantly share code, notes, and snippets.

@bwiggs
Created October 30, 2012 15:13
Show Gist options
  • Save bwiggs/3980827 to your computer and use it in GitHub Desktop.
Save bwiggs/3980827 to your computer and use it in GitHub Desktop.
Stock Quote Retreiver Model for CakePHP project
<?php
/**
* Model that handles the Stock quote.
*/
class StockQuote extends AppModel {
/**
* update() - main method called by cron jobs and task schedulers to update
* latest stock quote information
*/
public function update() {
$this->_updateStockQuoteCSV();
$this->_updateStockChartImage();
}
/**
* Deletes any cached services responses for StockQuotes. This is specifically
* for the client application, not involved with any service calls to 3rd
* parties.
*/
private function deleteStockQuoteCache(){
App::import('core', 'Folder');
$Folder = new Folder();
$Folder->delete(WWW_ROOT . 'cache/services/day/' . (string)date("Y-m-d") . '.json');
}
/**
* Handles calling the third party api, retreives and stores stock quote
* information as well as saves the data to a csv file in the webroot
* directory.
*/
public function _updateStockQuoteCSV() {
$fileName = APP."webroot/assets/quotes.csv";
$file = fopen($fileName, 'w') or die("Couldn't open file $fileName for writing.");
$data = file_get_contents('http://download.finance.yahoo.com/d/quotes.csv?s=GOOGA&f=nl1t1cpobb6aa5a2mw&e=.csv');
$parts= preg_split('/,/', $data);
$dateTime = new DateTime("now", new DateTimeZone('America/New_York'));
$trade_date=date("Y-m-d");
$result=$this->findByTradeDate($trade_date);
if(isset($result['StockQuote']))
{
$this->updateAll(array('StockQuote.raw' => "'".$data."'",'trade_time' => $parts[2], 'value'=> $parts[1],'value_change'=>$parts[3]), array('StockQuote.trade_date' => $trade_date));
}
else
{
$this->create();
$this->set(array('raw' => $data, 'trade_date' => $trade_date, 'trade_time' => $parts[2], 'value'=> $parts[1],'value_change'=>$parts[3]));
$this->save();
}
fwrite($file, $data);
fclose($file);
$this->deleteStockQuoteCache();
}
/**
* Updates the stock chart image from the 3rd party api. Stores it locally
* on the filesystem for use on the client application.
*/
public function _updateStockChartImage() {
$ch = curl_init ("http://chart.finance.yahoo.com/c/1y/m/GOOG?lang=en-US&region=US");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$rawdata=curl_exec ($ch);
curl_close($ch);
$fileName = APP."webroot/assets/stock_chart.png";
$fp = fopen($fileName,'w');
fwrite($fp, $rawdata);
fclose($fp);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment