0

I have this code that requests the information of the stock MSFT (Microsoft), the request goes right and i get all the data i need on it, however it i want to get the latest stock price (in python it sorts it out latest to oldest however i do not want to take the data off the top because some languages do not sort it out for me) in the result given below, there are multiple dates eg:

{u'2019-10-08':

Now i want to find the latest date in the json data and print THAT out.

I am using Alpha advantage to get this data, there is nothing wrong with the given data.

import requests,json

func = 'function=TIME_SERIES_DAILY'
sym = 'symbol=MSFT'
inter = 'interval=10min'
apikey = 'apikey=**********'
url = 'https://www.alphavantage.co/query?'+func+'&'+sym+'&'+inter+'&'+apikey

resp = requests.get(url)
data = json.loads(resp.content)
d = data['Time Series (Daily)']

# print (d['2020-01-03']) #<- date
# print (max(d.values()))  # does not give the expected data (i think because the date is in a string)

print (d)

Shortened Result:

{u'Meta Data': {u'1. Information': u'Daily Prices (open, high, low, close) and Volumes', u'4. 
Output Size': u'Compact', u'5. Time Zone': u'US/Eastern', u'2. Symbol': u'MSFT', u'3. Last 
Refreshed': u'2020-01-03'}, u'Time Series (Daily)': {u'2019-10-08': {u'5. volume': u'26783336',
 u'4. close': u'135.6700', u'2. high': u'137.7600', u'1. open': u'137.0800', u'3. low': u'135.6200'}}

I have looked through many answers and some of them unanswered or few in different languages, I have spend some time trying to get the solution to this.

CDJB
  • 14,043
  • 5
  • 29
  • 55
beepbeep-boop
  • 204
  • 1
  • 2
  • 11

1 Answers1

3

If I understand the question correctly, you could do the following using datetime.strptime(). Note that in your case, as @Iguananaut pointed out, the date format is in lexicographical order, so you could just use maxdate = max(d).

from datetime import datetime

maxdate = max((x for x in d.keys()), key=lambda x: datetime.strptime(x, "%Y-%m-%d"))

print(maxdate)
print(d[maxdate])

Which gives me output:

2020-01-03
{'1. open': '158.3200',
 '2. high': '159.9450',
 '3. low': '158.0600',
 '4. close': '158.6200',
 '5. volume': '21121681'}
CDJB
  • 14,043
  • 5
  • 29
  • 55
  • This is not even necessary since if the dates are in YYYY-mm-dd format they are already lexicographically ordered. – Iguananaut Jan 06 '20 at 12:41
  • I updated my answer to reference this and provide a solution without `datetime` - I think it's still worth including the `datetime` solution though. – CDJB Jan 06 '20 at 12:44