2015年4月28日 星期二

PHP:取得股票報價

一直都想嘗試用機器學習去建議股票買入賣出。在嘗試之前,需要拿點數據測試。但要如何取得?答案是 Yahoo API。以下簡單的 PHP 程式能獲取當天的股票報價:
<?php

$stock = "2628.HK";
$api = "https://query.yahooapis.com/v1/public/yql?q=".
       urlencode("select * from yahoo.finance.quotes").
       urlencode(" where symbol in ('$stock')").
       "&format=json&diagnostics=true".
       "&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";

//-----------------------------------------------------------------------------
try  {
    $rawData = file_get_contents($api);
    $jsonData = json_decode($rawData);

    $quote = $jsonData->query->results->quote;
    echo("Price: ".$quote->LastTradePriceOnly);

}  catch (Exception $e)  {
    echo($e->getMessage());
}

?>

傳回 JSON 結果:
{
    "query":{
        "count":1,
        "created":"2015-04-28T13:39:43Z",
        "lang":"en-US",
        "diagnostics":{
            "url":[{
                "execution-start-time":"0",
                "execution-stop-time":"74",
                "execution-time":"74",
                "content":"http://www.datatables.org/yahoo/finance/yahoo.finance.quotes.xml"
            },
            {
                "execution-start-time":"80",
                "execution-stop-time":"159",
                "execution-time":"79",
                "content":"http://download.finance.yahoo.com/d/quotes.csv?f=aa2bb2b3b4cc1c3c4c6c8dd1d2ee1e7e8e9ghjkg1g3g4g5g6ii5j1j3j4j5j6k1k2k4k5ll1l2l3mm2m3m4m5m6m7m8nn4opp1p2p5p6qrr1r2r5r6r7ss1s7t1t7t8vv1v7ww1w4xy&s=2628.HK"
            }],
            "publiclyCallable":"true",
            "cache":{
                "execution-start-time":"79",
                "execution-stop-time":"80",
                "execution-time":"1",
                "method":"GET",
                "type":"MEMCACHED",
                "content":"5d1e1de680846a307c9874dc3d6878dc"
            },
            "query":{
                "execution-start-time":"80",
                "execution-stop-time":"159",
                "execution-time":"79",
                "params":"{
                    url=[http://download.finance.yahoo.com/d/quotes.csv?f=aa2bb2b3b4cc1c3c4c6c8dd1d2ee1e7e8e9ghjkg1g3g4g5g6ii5j1j3j4j5j6k1k2k4k5ll1l2l3mm2m3m4m5m6m7m8nn4opp1p2p5p6qrr1r2r5r6r7ss1s7t1t7t8vv1v7ww1w4xy&s=2628.HK]
                }",
                "content":"select * from csv where url=@url and columns='Ask,AverageDailyVolume,Bid,AskRealtime,BidRealtime,BookValue,Change&PercentChange,Change,Commission,Currency,ChangeRealtime,AfterHoursChangeRealtime,DividendShare,LastTradeDate,TradeDate,EarningsShare,ErrorIndicationreturnedforsymbolchangedinvalid,EPSEstimateCurrentYear,EPSEstimateNextYear,EPSEstimateNextQuarter,DaysLow,DaysHigh,YearLow,YearHigh,HoldingsGainPercent,AnnualizedGain,HoldingsGain,HoldingsGainPercentRealtime,HoldingsGainRealtime,MoreInfo,OrderBookRealtime,MarketCapitalization,MarketCapRealtime,EBITDA,ChangeFromYearLow,PercentChangeFromYearLow,LastTradeRealtimeWithTime,ChangePercentRealtime,ChangeFromYearHigh,PercebtChangeFromYearHigh,LastTradeWithTime,LastTradePriceOnly,HighLimit,LowLimit,DaysRange,DaysRangeRealtime,FiftydayMovingAverage,TwoHundreddayMovingAverage,ChangeFromTwoHundreddayMovingAverage,PercentChangeFromTwoHundreddayMovingAverage,ChangeFromFiftydayMovingAverage,PercentChangeFromFiftydayMovingAverage,Name,Notes,Open,PreviousClose,PricePaid,ChangeinPercent,PriceSales,PriceBook,ExDividendDate,PERatio,DividendPayDate,PERatioRealtime,PEGRatio,PriceEPSEstimateCurrentYear,PriceEPSEstimateNextYear,Symbol,SharesOwned,ShortRatio,LastTradeTime,TickerTrend,OneyrTargetPrice,Volume,HoldingsValue,HoldingsValueRealtime,YearRange,DaysValueChange,DaysValueChangeRealtime,StockExchange,DividendYield'"
            },
            "javascript":{
                "execution-start-time":"78",
                "execution-stop-time":"169",
                "execution-time":"91",
                "instructions-used":"63309",
                "table-name":"yahoo.finance.quotes"
            },
            "user-time":"170",
            "service-time":"154",
            "build-version":"0.2.100"
        },
        "results":{
            "quote":{
                "symbol":"2628.HK",
                "Ask":null,
                "AverageDailyVolume":"41728600",
                "Bid":null,
                "AskRealtime":null,
                "BidRealtime":null,
                "BookValue":"1.62",
                "Change_PercentChange":"-0.10 - -0.26%",
                "Change":"-0.10",
                "Commission":null,
                "Currency":"HKD",
                "ChangeRealtime":null,
                "AfterHoursChangeRealtime":null,
                "DividendShare":"0.38",
                "LastTradeDate":"4/28/2015",
                "TradeDate":null,
                "EarningsShare":"1.43",
                "ErrorIndicationreturnedforsymbolchangedinvalid":null,
                "EPSEstimateCurrentYear":"0.89",
                "EPSEstimateNextYear":null,
                "EPSEstimateNextQuarter":"0.00",
                "DaysLow":"37.50",
                "DaysHigh":"38.45",
                "YearLow":"19.72",
                "YearHigh":"41.00",
                "HoldingsGainPercent":null,
                "AnnualizedGain":null,
                "HoldingsGain":null,
                "HoldingsGainPercentRealtime":null,
                "HoldingsGainRealtime":null,
                "MoreInfo":null,
                "OrderBookRealtime":null,
                "MarketCapitalization":"1076.89B",
                "MarketCapRealtime":null,
                "EBITDA":"7.06B",
                "ChangeFromYearLow":"18.38",
                "PercentChangeFromYearLow":"+93.20%",
                "LastTradeRealtimeWithTime":null,
                "ChangePercentRealtime":null,
                "ChangeFromYearHigh":"-2.90",
                "PercebtChangeFromYearHigh":"-7.07%",
                "LastTradeWithTime":"3:59pm - 38.10",
                "LastTradePriceOnly":"38.10",
                "HighLimit":null,
                "LowLimit":null,
                "DaysRange":"37.50 - 38.45",
                "DaysRangeRealtime":null,
                "FiftydayMovingAverage":"35.06",
                "TwoHundreddayMovingAverage":"29.53",
                "ChangeFromTwoHundreddayMovingAverage":"8.57",
                "PercentChangeFromTwoHundreddayMovingAverage":"+29.01%",
                "ChangeFromFiftydayMovingAverage":"3.04",
                "PercentChangeFromFiftydayMovingAverage":"+8.67%",
                "Name":"CHINA LIFE",
                "Notes":null,
                "Open":"38.40",
                "PreviousClose":"38.20",
                "PricePaid":null,
                "ChangeinPercent":"-0.26%",
                "PriceSales":"15.18",
                "PriceBook":"23.55",
                "ExDividendDate":"6/3/2014",
                "PERatio":"26.78",
                "DividendPayDate":null,
                "PERatioRealtime":null,
                "PEGRatio":"0.00",
                "PriceEPSEstimateCurrentYear":null,
                "PriceEPSEstimateNextYear":null,
                "PriceEPSEstimateNextYear":null,
                "Symbol":"2628.HK",
                "SharesOwned":null,
                "ShortRatio":"0.00",
                "LastTradeTime":"3:59pm",
                "TickerTrend":null,
                "OneyrTargetPrice":null,
                "Volume":"35734538",
                "HoldingsValue":null,
                "HoldingsValueRealtime":null,
                "YearRange":"19.72 - 41.00",
                "DaysValueChange":null,
                "DaysValueChangeRealtime":null,
                "StockExchange":"HKG",
                "DividendYield":"1.23",
                "PercentChange":"-0.26%"
            }
        }
    }
}

只要在服務器設定 Cronjob 每天獲取數據,並儲存到資料庫,日後便能拿來使用。

沒有留言: