Last active
November 4, 2017 12:14
-
-
Save jcefoli/9c67c4d5b0a9136df6e5b82af4ab28e6 to your computer and use it in GitHub Desktop.
Return Latest Numerical Stock/Mutual Fund Price from Alphavantage API in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
#Usage http://localhost/get_stockclose.php?symbol=msft | |
#You need an API Key from www.alphavantage.co (update it on line 29) | |
#Mutual Fund data is delayed one day | |
#Get Symbol from query string | |
if (!isset($_GET['symbol'])){ | |
echo "Ticker Symbol Missing. Make sure your requests ends in ?symbol=xyz"; | |
exit; | |
}else{ | |
$symbol = $_GET['symbol']; | |
$tickerLength = strlen($symbol); | |
} | |
#Detect Mutual Funds and set variables to generate proper API request | |
if ($tickerLength == 5) { | |
$function = "TIME_SERIES_DAILY"; | |
$dataIndexName = "Time Series (Daily)"; | |
$interval = "1day"; | |
}else{ | |
$function = "TIME_SERIES_INTRADAY"; | |
$dataIndexName = "Time Series (1min)"; | |
$interval = "1min"; | |
} | |
#API Request | |
function getQuote($function, $dataIndexName, $interval){ | |
$curl = curl_init(); | |
curl_setopt_array($curl, array( | |
CURLOPT_URL=> "https://www.alphavantage.co/query?function=$function&symbol=$symbol&interval=$interval&apikey=YOUR_API_KEY_HERE", | |
CURLOPT_RETURNTRANSFER=>true, | |
//CURLOPT_CAINFO=>"C:\bin\curl-ca-bundle.crt" //Only for local development to validate https cert | |
)); | |
$curlResponse = curl_exec($curl); | |
curl_close($curl); | |
return $curlResponse; | |
} | |
#Retry Curl Request to get Last Refreshed date from API Response (To fix Excel clobbering issue) | |
do { | |
$curlResponse = getQuote($function, $dataIndexName, $interval); | |
$json = json_decode($curlResponse, true); | |
#Debugging stuff to make sense of the mess of the JSON response they provide | |
//print_r(array_keys($json)); | |
//print_r(array_keys($json["Time Series (Daily)"])); | |
if (isset($json["Meta Data"]["3. Last Refreshed"])) { | |
$lastRefreshed = $json["Meta Data"]["3. Last Refreshed"]; | |
}else{ | |
#Sometimes this fires when Excel tosses tons of async requests at this script | |
$lastRefreshed = "Error"; | |
} | |
} while ($lastRefreshed == "Error"); | |
#Get the Asset Price from the API Response | |
$stockLatestPrice = $json[$dataIndexName][$lastRefreshed]["4. close"]; | |
#Print the Asset Price | |
echo $stockLatestPrice; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment