Reputation: 3
I am getting shares prices using the Alpha Vantage API and I am able to get the most recent price easily enough. But I want to get the price from five entries back.
This is the start of the array I am working with
{
"Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. Symbol": "IBM",
"3. Last Refreshed": "2021-02-22",
"4. Output Size": "Compact",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2021-02-22": {
"1. open": "118.5000",
"2. high": "121.1250",
"3. low": "118.4400",
"4. close": "120.8600",
"5. volume": "5838841"
},
"2021-02-19": {
"1. open": "120.7500",
"2. high": "120.7600",
"3. low": "118.3800",
"4. close": "118.9900",
"5. volume": "6578741"
},
and this is the clunky code I have been using,
which gets the first day,
turns it into a time,
takes seven days off (since they exchange is closed on weekends) and works with the revised date.
$getstocksapi = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=".$stock[$x]."&outputsize=compact&apikey=mycode;
$currentprices = file_get_contents($getstocksapi);
$currentprices = json_decode($currentprices,true);
$dateToCheck =($currentprices['Meta Data']['3. Last Refreshed']);
$oldDateToCheck = strtotime($dateToCheck);
$oldDateToCheck = ($oldDateToCheck - 60 * 60 * 24 * 7);
$oldDateToCheck = date("Y-m-d", $oldDateToCheck);
$dayEnd[$x] = ($currentprices['Time Series (Daily)'][$dateToCheck]['4. close']);
$thenDayEnd[$x] = ($currentprices['Time Series (Daily)'][$oldDateToCheck]['4. close']);
Is there a more elegant way, perhaps using array_slice that I can get the most recent closing price and then the one from five entries down?
Upvotes: 0
Views: 80
Reputation: 2987
From the comment, the number index does not work because it still does not have number index. To re-index you can use function array_values()
.
$currentprices = json_decode($data, true);
$timeSeriesDaily = array_values($currentprices['Time Series (Daily)']);
Then $timeSeriesDaily
will be the same array but with number index instead and you can access the 5th index with the following.
echo $timeSeriesDaily[4]['4. close'];
Upvotes: 1