Using the Yahoo finance stock API with PHP

Using the Yahoo finance stock API to firstly get stock ticker symbols and then the stock price with PHP.

The Yahoo finance API is a fast and free method to query the stock market for pricing and volume information.

stock api php get price

If you already know your chosen stock symbol/s then you can skip this first part, as it consists of fetching all equity stock symbols.

Getting stock symbols

The API search for stock symbols is this URL:

https://query1.finance.yahoo.com/v1/finance/lookup?formatted=true&lang=en-US&region=US&query={LETTER}*&type=equity&count=3000&start=0

You cannot actually search for all, you have to search every letter for ticker symbols that contain it at least once, hence putting * after the letter.

To loop through a to z with PHP:

foreach (range('a', 'z') as $letter) {

}

Now to incorporate the API call,  returning its data and iterating through the array of each result:

foreach (range('a', 'z') as $letter) {
    $url = "https://query1.finance.yahoo.com/v1/finance/lookup?formatted=true&lang=en-US&region=US&query=$letter*&type=equity&count=3000&start=0";
    $data = json_decode(file_get_contents($url), true);
    foreach ($data['finance']['result'][0]['documents'] as $ticker) {
        $ticker_symbol = $ticker['symbol'];
    }
}

You can now store the ticker symbols in a database or an even quicker method is to store them all in an array and then save the array as a JSON file.

$ticker_array = array();
foreach (range('a', 'z') as $letter) {
    $url = "https://query1.finance.yahoo.com/v1/finance/lookup?formatted=true&lang=en-US&region=US&query=$letter*&type=equity&count=3000&start=0";
    $data = json_decode(file_get_contents($url), true);
    foreach ($data['finance']['result'][0]['documents'] as $ticker) {
        $ticker_array[] = $ticker['symbol'];
    }
}

$fp = fopen("tickers.json", "w");
fwrite($fp, json_encode($ticker_array));
fclose($fp);

The file is called tickers.json

Finally, with the collection of ticker symbols they can be used in the main API call which will return all live data along with certain historic.

Loading the tickers JSON file and looping through each symbol:

$data = json_decode(file_get_contents("tickers.json"), true);
foreach ($data as $ticker) {
    echo $ticker . '<br>';
}

Getting the stock data

Now to include the API call which is this URL:

https://query1.finance.yahoo.com/v8/finance/chart/{SYMBOL}?region=US&lang=en-US&includePrePost=false&interval=1h&useYfid=true&range=1d

SYMBOL will be getting replaced with the ticker symbol as the array gets looped through.

Click the spoiler below to see a call output example for GME

GME API call output
{
  "chart": {
    "result": [
      {
        "meta": {
          "currency": "USD",
          "symbol": "GME",
          "exchangeName": "NYQ",
          "instrumentType": "EQUITY",
          "firstTradeDate": 1013610600,
          "regularMarketTime": 1614632402,
          "gmtoffset": -18000,
          "timezone": "EST",
          "exchangeTimezoneName": "America/New_York",
          "regularMarketPrice": 120.4,
          "chartPreviousClose": 101.74,
          "previousClose": 101.74,
          "scale": 3,
          "priceHint": 2,
          "currentTradingPeriod": {
            "pre": {
              "timezone": "EST",
              "start": 1614675600,
              "end": 1614695400,
              "gmtoffset": -18000
            },
            "regular": {
              "timezone": "EST",
              "start": 1614695400,
              "end": 1614718800,
              "gmtoffset": -18000
            },
            "post": {
              "timezone": "EST",
              "start": 1614718800,
              "end": 1614733200,
              "gmtoffset": -18000
            }
          },
          "tradingPeriods": [
            [
              {
                "timezone": "EST",
                "start": 1614609000,
                "end": 1614632400,
                "gmtoffset": -18000
              }
            ]
          ],
          "dataGranularity": "1h",
          "range": "1d",
          "validRanges": [
            "1d",
            "5d",
            "1mo",
            "3mo",
            "6mo",
            "1y",
            "2y",
            "5y",
            "10y",
            "ytd",
            "max"
          ]
        },
        "timestamp": [
          1614609000,
          1614612600,
          1614616200,
          1614619800,
          1614623400,
          1614627000,
          1614630600
        ],
        "indicators": {
          "quote": [
            {
              "open": [
                105.11000061035156,
                103.04900360107422,
                107.0833969116211,
                110.94419860839844,
                110.2699966430664,
                112.78289794921875,
                123.6500015258789
              ],
              "high": [
                112.0,
                109.4000015258789,
                119.77989959716797,
                113.29989624023438,
                114.44000244140625,
                133.99000549316406,
                126.0
              ],
              "volume": [
                9838204,
                3677893,
                9228730,
                3675054,
                3688134,
                12139018,
                5916729
              ],
              "low": [
                99.97000122070312,
                102.5,
                105.5999984741211,
                107.25,
                109.80000305175781,
                112.78289794921875,
                116.0
              ],
              "close": [
                103.1500015258789,
                107.2968978881836,
                110.94840240478516,
                110.17250061035156,
                112.77010345458984,
                123.73989868164062,
                119.48999786376953
              ]
            }
          ]
        }
      }
    ],
    "error": null
  }
}

Add in a fetch and decode on the API call to get the stock price data. This example will get the current market price (as $current):

$data = json_decode(file_get_contents("tickers.json"), true);
foreach ($data as $ticker) {
    $url = "https://query1.finance.yahoo.com/v8/finance/chart/$ticker?region=US&lang=en-US&includePrePost=false&interval=1h&useYfid=true&range=1d";
    $stock_data = json_decode(file_get_contents($url), true);
    $current = $stock_data['chart']['result'][0]['meta']['regularMarketPrice'];
}

You can now store and/or use the data as you please.