从ALPHA VANTAGE API进行JSON解析

时间:2019-07-09 23:05:06

标签: json

我从ALPHA VANTAGE Api获得了一些库存数据。我确实获得了整个JSON数据,但是我在获取具体内容(“时间序列(每日)”的低,高和开放部分)时遇到了问题:这是我的代码:   func updateStockData(json:JSON){

    if json["Time Series (Daily)"].string != nil {
      let open = json["Time Series (Daily)"][0][0]
      print("open======open")
      print(open)
      let high = json["Time Series (Daily)"][0][1]
      print(high)
      let low = json["Time Series (Daily)"][0][2]
      print(low)
        self.pricePriceLabel.text = "Open: " + open.string! + "$"

         self.highLable.text = "High: " + high.string! + "$"

        self.lowLabel.text = "Low: " + low.string! + "$"
    } else {
         self.bitcoinPriceLabel.text = "Unavailable"
          self.lowLabel.text = "Unavailable"
          self.highLable.text = "Unavailable"
    }

这是我必须从中获取的json数据:

 {
"Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "HBAN",
    "3. Last Refreshed": "2019-07-09 15:54:10",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2019-07-09": {
        "1. open": "13.6400",
        "2. high": "13.8900",
        "3. low": "13.6000",
        "4. close": "13.8500",
        "5. volume": "5543590"
    },
    "2019-07-08": {
        "1. open": "13.8000",
        "2. high": "13.9000",
        "3. low": "13.6600",
        "4. close": "13.7300",
        "5. volume": "10355636"
    },
    "2019-07-05": {
        "1. open": "13.9500",
        "2. high": "14.1600",
        "3. low": "13.8400",
        "4. close": "13.9200",
        "5. volume": "7398341"
    },.......

我在做什么错

3 个答案:

答案 0 :(得分:1)

您最好的选择可能是使用 Pandas 数据框,因为它们更易于导航。

# ///////////////////////////////////////////////////////////
# FUNCTIONS FOR ALPHA VANTAGE
# ///////////////////////////////////////////////////////////
TIME_SERIES_INTRADAY = 'TIME_SERIES_INTRADAY'
TIME_SERIES_INTRADAY_EXTENDED = 'TIME_SERIES_INTRADAY_EXTENDED'
TIME_SERIES_DAILY = 'TIME_SERIES_DAILY'
TIME_SERIES_DAILY_ADJUSTED = 'TIME_SERIES_DAILY_ADJUSTED'
TIME_SERIES_WEEKLY = 'TIME_SERIES_WEEKLY'
TIME_SERIES_WEEKLY_ADJUSTED = 'TIME_SERIES_WEEKLY_ADJUSTED'
TIME_SERIES_MONTHLY = 'TIME_SERIES_MONTHLY'
TIME_SERIES_MONTHLY_ADJUSTED = 'TIME_SERIES_MONTHLY_ADJUSTED'

# ///////////////////////////////////////////////////////////
# TIME SERIES FOR STOCK DATA
# ///////////////////////////////////////////////////////////
ONEMIN = 'Time Series (1min)'
FIVEMIN = 'Time Series (5min)'
FIVETEENMIN = 'Time Series (15min)'
THIRTYMIN = 'Time Series (30min)'
HOUR = 'Time Series (60min)'
FIVEMIN = 'Time Series (5min)'
DAILY = 'Time Series (Daily)' 
WEEKLY = 'Weekly Time Series'
WEEKLY_ADJ = 'Weekly Adjusted Time Series'
MONTLY = 'Monthly Time Series'
MONTLY_ADJ = 'Monthly Adjusted Time Series'

# /////////////////////////////////////////////////////////
# query timeseries stock data of selected type ////////////
# /////////////////////////////////////////////////////////
def query_timeseries_data(func, symbol, outputsize='full', datatype='json', apikey='YOURKEYHERE'):
    data = {
        "function": func, # Here you can put any of the 'funcs' above
        "symbol": symbol,
        "outputsize": outputsize, # (full) and (compact) are accepted
        "datatype": datatype,
        "apikey": apikey
    }
    return requests.get("https://www.alphavantage.co/query", data).json()

# /////////////////////////////////////////////////////////
# convert timeseries stock data of selected type to json //
# /////////////////////////////////////////////////////////
def get_timeseries_dataframe(json, type):
    df = pd.DataFrame.from_dict(json[type], orient= 'index')
    df.index =  pd.to_datetime(df.index, format='%Y-%m-%d')
    
    df = df.rename(columns={ '1. open': 'Open', '2. high': 'High', '3. low': 'Low', '4. close': 'Close', '5. volume': 'Volume'})
    df = df.astype({'Open': 'float64', 'High': 'float64', 'Low': 'float64','Close': 'float64','Volume': 'float64',})
    df = df[[ 'Open', 'High', 'Low', 'Close', 'Volume']]
    return df

# Now all you have to do is actually call the funcs
response_json = query_timeseries_data(TIME_SERIES_DAILY, 'MSFT')
sockprice_dataframe = get_timeseries_dataframe(response_json, DAILY)

我在另一个线程上找到了这段代码并使它更容易使用,它非常有效

答案 1 :(得分:0)

数据不是数组,而是所有对象,因此您需要通过键而不是通过索引来引用元素。这是经过调整以适合您的代码:

if json["Time Series (Daily)"].string != nil {
  // Flatten the object keys and take the first one
  const firstDate = Object.keys(json["Time Series (Daily)"][0])
  let open = json["Time Series (Daily)"][firstDate]["1. open"]
  print("open======open")
  print(open)
  let high = json["Time Series (Daily)"][firstDate]["2. high"]
  print(high)
  let low = json["Time Series (Daily)"][firstDate]["3. low"]
  print(low)
    self.pricePriceLabel.text = "Open: " + open.string! + "$"

     self.highLable.text = "High: " + high.string! + "$"

    self.lowLabel.text = "Low: " + low.string! + "$"
} else {
     self.bitcoinPriceLabel.text = "Unavailable"
      self.lowLabel.text = "Unavailable"
      self.highLable.text = "Unavailable"
}

答案 2 :(得分:0)

下面是我编写的一项功能,可以轻松地从Alpha Vantage中提取历史股价。您要做的就是插入您的符号和令牌。有关提取Alpha Vantage数据的更多功能,请随时查看我的链接:https://github.com/hklchung/StockPricePredictor/blob/master/2020/alphavantage_funcs.py

def request_stock_price_hist(symbol, token, sample = False):
    if sample == False:
        q_string = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={}&outputsize=full&apikey={}'
    else:
        q_string = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol={}&apikey={}'

    print("Retrieving stock price data from Alpha Vantage (This may take a while)...")
    r = requests.get(q_string.format(symbol, token))
    print("Data has been successfully downloaded...")
    date = []
    colnames = list(range(0, 7))
    df = pd.DataFrame(columns = colnames)
    print("Sorting the retrieved data into a dataframe...")
    for i in tqdm(r.json()['Time Series (Daily)'].keys()):
        date.append(i)
        row = pd.DataFrame.from_dict(r.json()['Time Series (Daily)'][i], orient='index').reset_index().T[1:]
        df = pd.concat([df, row], ignore_index=True)
    df.columns = ["open", "high", "low", "close", "adjusted close", "volume", "dividend amount", "split cf"]
    df['date'] = date
    return df