Search code examples
pythonjsonstockquotesalpha-vantage

Alpha Vantage for loop TypeError: string indices must be integers


I have been trying to get the for each loop to go through the data and output the keys and values for specific days like 2020-04-03. But I keep getting the following error: TypeError: string indices must be integers

My code:

import time
from alpha_vantage.timeseries import TimeSeries
import json

key = 'Your key here'
ts = TimeSeries(key)
ko, meta = ts.get_daily(symbol='KO')

ko_info = json.dumps(ko, indent = 2, sort_keys = True)

data = json.loads(ko_info)

print(data)
print(type(data))

ko_org = json.dumps(data, indent = 2, sort_keys = True)
print(ko_org)
print(type(ko_org))

for x in ko_org['2020-04-01']:
    print(x['1. open'])

Data:

{
  "2019-11-11": {
    "1. open": "52.3300",
    "2. high": "52.3700",
    "3. low": "51.7750",
    "4. close": "51.8400",
    "5. volume": "8198125"
  },
  "2019-11-12": {
    "1. open": "51.9100",
    "2. high": "51.9100",
    "3. low": "51.5831",
    "4. close": "51.7100",
    "5. volume": "12656881"
  },
  "2019-11-13": {
    "1. open": "52.1800",
    "2. high": "52.4500",.....

Solution

  • A few things:

    1. The python Alpha Vantage wrapper returns the data in json, so there is no need to do:
    ko_info = json.dumps(ko, indent = 2, sort_keys = True)
    
    data = json.loads(ko_info)
    
    print(data)
    print(type(data))
    
    ko_org = json.dumps(data, indent = 2, sort_keys = True)
    print(ko_org)
    print(type(ko_org))
    

    As it is redundant, so we can scrap all that.

    1. As @Psidom said, you cannot loop through a string of json.dumps like that, however we can loop through the dict/json we get from the regular returned data, as such:
    for x in ko:
        if x == '2020-04-01':
            print(ko[x])
    

    This reads "for every date x in all the data returned, if date x is '2020-04-01' print the quote from that date"

    We put it all together to get:

    import time
    from alpha_vantage.timeseries import TimeSeries
    
    key = 'Your key here'
    ts = TimeSeries(key)
    ko, meta = ts.get_daily(symbol='KO')
    
    for x in ko:
        if x == '2020-04-01':
            print(ko[x])