0

Hi I have a problem with this piece of code that needs to get stock prices based on a defined time period and a ticker code. The program actually works when I use my IEX API KEY, but not when I use my TEST IEX API KEY, I get the following error message

Unable to read URL: https://cloud.iexapis.com/stable/stock/market/batch?symbols=AAPL&types=chart&range=1y&token=Tpk_157dbb6ac5914bb6b5e309b5eb1484f5

Response Text: b'Test tokens may only be used in the sandbox environment. Please use https://sandbox.iexapis.com' error

'''
How to download stock data
'''

import pandas as pd
import pandas_datareader.data as web
import datetime as dt
from datetime import datetime
import os

os.environ["IEX_API_KEY"] = "Tpk_157dbb6ac5914bb6b5e309b5eb1484f5"

def get_stock_data():
    tickers = ['AAPL'] #capitalize tickers

    start = dt.datetime(2019,1,1) # can import 5 years max with iex
    end = dt.datetime.today()

    if not os.path.exists('stockdata'):
        os.makedirs('stockdata')

    for ticker in tickers:

        print(ticker)
        try :
            df = web.DataReader(ticker, "iex", start, end)
            print(df.head())
            df.to_csv('stockdata/{}.to_csv'.format(ticker))
            print(ticker, 'downloaded')
        except Exception as  e:
            print(e, 'error')

get_stock_data()

I probably should have told the API that this is the iexcloud-sandbox that I need to access,as described in the Error Message, but the description link dosent say anything about it: https://intercom.help/iexcloud/en/articles/2915433-testing-with-the-iex-cloud-sandbox and I don't know how get it to work, can anybody help?

jhjorsal
  • 197
  • 3
  • 10
  • The error literally spells out for you what you need to do. If you want to use the test key, you have to make API calls to https://sandbox.iexapis.com instead of https://cloud.iexapis.com – Ofer Sadan Nov 22 '19 at 19:45

3 Answers3

3

Set your IEX_API_VERSION environment variable to iexcloud-sandbox:

os.environ['IEX_API_VERSION'] = 'iexcloud-sandbox'

Reference: https://github.com/addisonlynch/iexfinance/blob/7cf902e275f3f84b2892b87ff072fa1808926c15/docs/source/sandbox.rst

cameronhr
  • 46
  • 2
0

I was having the same issue as you and this worked for me:

import os
os.environ['IEX_SANDBOX'] = 'enable'

During the DataReader call, there is a check for this environment variable, and if you have set it to 'enable', then it will choose the sandbox URL.

Community
  • 1
  • 1
  • 1
    While this code may solve the question, [including an explanation](https://meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Brian61354270 Apr 17 '20 at 17:35
0

The reason why python os.getenv("IEX_SANDBOX")=="enable" works. The following code was retrieved from pdr_DataReader/iex/daily.py/IEXDailyReader itself.

        if os.getenv("IEX_SANDBOX") == "enable":
            self.sandbox = True
        else:
            self.sandbox = False
        self.api_key = api_key
        super(IEXDailyReader, self).__init__(
            symbols=symbols,
            start=start,
            end=end,
            retry_count=retry_count,
            pause=pause,
            session=session,
            chunksize=chunksize,
        )

    @property
    def default_start_date(self):
        today = datetime.date.today()
        return today - datetime.timedelta(days=365 * 15)

    @property
    def url(self):
        """API URL"""
        if self.sandbox is True:
            return "https://sandbox.iexapis.com/stable/stock/market/batch"
        else:
            return "https://cloud.iexapis.com/stable/stock/market/batch"