Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get RealTime stock price using yahoo finance

I have several requirement which are listed below.

  1. Get Real Time stock price without page refresh or ajax. (ie. yahoo finance, they get latest stock price without page refresh and ajax call)
  2. Get stock price from as much as stock market like BSE, NSC etc..

Right now using following code i am able to get stock price but either i have to refresh the page or call to ajax and in both case it take 20 to 30 seconds but in many finance site they can update price by each second without using ajax.

<?php
/**
 * Class to fetch stock data from Yahoo! Finance
 *
 */

    class YahooStock {

        /**
         * Array of stock code
         */
        private $stocks = array();

        /**
         * Parameters string to be fetched  
         */
        private $format;

        /**
         * Populate stock array with stock code
         *
         * @param string $stock Stock code of company   
         * @return void
         */
        public function addStock($stock)
        {
            $this->stocks[] = $stock;
        }

        /**
         * Populate parameters/format to be fetched
         *
         * @param string $param Parameters/Format to be fetched
         * @return void
         */
        public function addFormat($format)
        {
            $this->format = $format;
        }

        /**
         * Get Stock Data
         *
         * @return array
         */
        public function getQuotes()
        {       
            $result = array();     
            $format = $this->format;

            foreach ($this->stocks as $stock)
            {           
                /**
                 * fetch data from Yahoo!
                 * s = stock code
                 * f = format
                 * e = filetype
                 */
                $s = file_get_contents("http://finance.yahoo.com/d/quotes.csv?s=$stock&f=$format&e=.csv");

                /**
                 * convert the comma separated data into array
                 */
                $data = explode( ',', $s);

                /**
                 * populate result array with stock code as key
                 */
                $result[$stock] = $data;
            }
            return $result;
        }
    }
    $objYahooStock = new YahooStock;

    /**
        Add format/parameters to be fetched

        s = Symbol
        n = Name
        l1 = Last Trade (Price Only)
        d1 = Last Trade Date
        t1 = Last Trade Time
        c = Change and Percent Change
        v = Volume
     */
    $objYahooStock->addFormat("snl1d1t1cv");

    /**
        Add company stock code to be fetched

        msft = Microsoft
        amzn = Amazon
        yhoo = Yahoo
        goog = Google
        aapl = Apple   
     */
    $objYahooStock->addStock("msft");
    $objYahooStock->addStock("amzn");
    $objYahooStock->addStock("yhoo");
    $objYahooStock->addStock("goog");
    $objYahooStock->addStock("vgz");
    $objYahooStock->addStock("FB");
    /**
     * Printing out the data
     */
    ?>
    <table width="100%">
    <tr>
        <th>Row</th>
        <th>Code</th>
        <th>Name</th>
        <th>Last Trade Price</th>
        <th>Last Trade Time</th>
        <th>Change and Percent Change</th>
        <th>Volume</th>
    </tr>
    <?php
    foreach( $objYahooStock->getQuotes() as $code => $stock)
    {
        ?>
        <tr>
            <td><?php //print_r($stock); ?></td>
            <td><?php echo $stock[0]; ?></td>
            <td><?php echo $stock[1]; ?></td>
            <td><?php echo $stock[2]; ?></td>
            <td><?php echo $stock[3]; ?></td>
            <td><?php echo $stock[4]; ?></td>
            <td><?php echo $stock[5]; ?></td>
            <td><?php echo $stock[6]; ?></td>
        </tr>

        <?php
    }
?>
    </table>
like image 214
Dipen Avatar asked Jan 17 '14 07:01

Dipen


2 Answers

<?php

class U_Yahoo{

    private function file_get_contents_curl($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_URL, $url);

        $data = curl_exec($ch);
        curl_close($ch);

        return $data;
    }

    //return the history quote from the simbol, default begin date is 90 day ago, the default end is today
    public function getHistoryQuote($symbol, $begin = 90, $end = 0){
        if(!$begin && !$end)
            $begin = $end = 0;

        $begin = Date('Y-m-d', strtotime("-{$begin} days"));
        $end = Date('Y-m-d', strtotime("-{$end} days"));
        $url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22$symbol%22%20and%20startDate%20%3D%20%22$begin%22%20and%20endDate%20%3D%20%22$end%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
        $jason_obj = json_decode( $this->file_get_contents_curl($url) );
        return $jason_obj->query->results->quote;
    }

    //return not just the quote but others informations too
    public function getCurrentData($symbol){
        $is_array = is_array($symbol);

        $imp_symbol = ($is_array)? implode('%22%2C%22', $symbol) : $symbol;

        $url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote%20where%20symbol%20in%20(%22$imp_symbol%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
        $jason_obj = json_decode( $this->file_get_contents_curl($url) );

        $result = $jason_obj->query->results->quote;

        return (is_array($symbol) and (count($symbol) == 1))? [$result] : $result;
    }

    //return all quotes from the param $symbol passed, if symbol is array, it will return other array indexed by the symbols
    public function getCurrentQuote($symbol){
        if(is_array($symbol)){
            $symbol = empty($symbol)? ['GOOG'] : $symbol;
            $data = $this->getCurrentData($symbol);
            $result = [];

            for ($c = 0; $c < count($data); $c++) { 
                $result[$data[$c]->Symbol] = $data[$c]->LastTradePriceOnly;
            }

            return $result;
        }else
            return $this->getCurrentData($symbol)->LastTradePriceOnly;
    }

}

How use:

$yahoo = new U_Yahoo();
var_dump( $yahoo->getCurrentQuote('GOOG') );
var_dump( $yahoo->getCurrentQuote(['GOOG', 'YHOO']) );

var_dump( $yahoo->getCurrentData(['GOOG', 'YHOO']) );

var_dump( $yahoo->getHistoryQuote('YHOO', 20, 0) );
like image 192
Doglas Avatar answered Sep 20 '22 00:09

Doglas


well, in your approach, the stock price fetching is triggered by the client (the user's browser). So there is no way to trigger it outside page refresh or AJAX.

However, your server could fetch those data, irrespective of users. Something like:

data source <----> your backend server fetching the data ---> your database <---- your frontend web server <---> users

Backend and frontend servers can be the same server but with different processes.

like image 26
Pixou Avatar answered Sep 18 '22 00:09

Pixou