ValueError: The Quandl API key must be provided either through the api_key variable or through the environmental variable QUANDL_API_KEY.
I am trying to retrieve some simple stock data from Quandl. I have put in the actual API key instead of the x in the below example code below but I am still getting errors. Am I missing out on something?
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
style.use('ggplot')
symbol = 'AAPL'
api_key = 'x'
start = dt.datetime(2015, 1, 1)
end = dt.datetime.now()
df = web.DataReader(symbol, 'quandl', start, end, api_key)
print(df.head())
From the quandl docs:
AUTHENTICATION The Quandl Python module is free but you must have a
Quandl API key in order to download data. To get your own API key, you
will need to create a free Quandl account and set your API key.
After importing the Quandl module, you can set your API key with the
following command: quandl.ApiConfig.api_key = "YOURAPIKEY"
So you will need to pip install and import quandl. Then you can set the api_key attribute as above.
If you only want to get the data from Quandl, maybe you can try another approach.
import pandas as pd
import Quandl
api_key = 'yoursuperamazingquandlAPIkey'
df = Quandl.get('heregoesthequandlcode', authtoken = api_key)
print(df.head())
Related
I've been trying to work on some beginner/entry level python projects for a resume (working with WIN10) and I've been running into the same constant error. I've been trying to pull info from yahoo finance and I get this error, no matter how I rework my code:
import pandas_datareader as web
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import datetime as dt
start = dt.datetime(2018,1,1)
end = dt.datetime.now()
tickers = ["FB", "GS", "NVDA", "MSFT", "TSLA", "AAPL", "CCL", "BA"]
colnames = []
for ticker in tickers:
data = web.DataReader(ticker, "yahoo", start, end)
if len(colnames) == 0:
combined = data[['Adj Close']].copy()
else:
combined = combined.join(data['Adj Close'])
colnames.append(ticker)
combined.columns = colnames
print(combined)
RemoteDataError: Unable to read URL: https://finance.yahoo.com/quote/FB/history?period1=1514779200&period2=1652673599&interval=1d&frequency=1d&filter=history
I looked around and saw that yahoo finance changed it's structure for python, so I then tried changing the format or my code, still got the error. I tried installing suggested libraries to fix it, and while it says that their installed, I can't use the libraries because it says that module isn't found.
I've looked at other Stack posts and none of the solutions are helping.
I am trying to use json_normalize to parse data from the yahoo financials package. Seem to be running into an issue when trying to separate the columns out from the last object, a variable date. Each date I believe is a dictionary, which contains various balance sheet line items.
My code is:
import json
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import yfinance as yf
from yahoofinancials import YahooFinancials
tickerinput = "AAPL"
ticker = yf.Ticker(tickerinput)
tickerfin = YahooFinancials(tickerinput)
balancesheet = tickerfin.get_financial_stmts('annual', 'balance')
''' Flattening w json_normalize'''
balsheet = pd.json_normalize(balancesheet, record_path=['balanceSheetHistory', tickerinput])
I have also tried using this below code but receive a key error, despite it being in the original JSON output.
balsheet = pd.json_normalize(balancesheet, record_path=['balanceSheetHistory', tickerinput], meta=['2021-09-25', ['totalLiab','totalStockholderEquity','totalAssets','commonStock','otherCurrentAssets','retainedEarnings','otherLiab','treasuryStock','otherAssets','cash','totalCurrentLiabilities','shortLongTermDebt','otherStockholderEquity','propertyPlantEquipment','totalCurrentAssets','longTermInvestments','netTangibleAssets','shortTermInvestments','netReceivables','longTermDebt','inventory','accountsPayable']], errors='ignore')
The main issue is that I am returned the below data frame:
Returned dataframe from balsheet
Sample Output of the JSON file:
JSON Output (balancesheet variable)
Can you please help me with this code. Error is posted below the code.
import pandas as pd
import pandas_datareader.data as web
import numpy as np
FB = web.YahooOptions('FB')
for exp in FB.expiry_dates:
print(exp.isoformat())
error:
RemoteDataError: Unable to read URL: https://query1.finance.yahoo.com/v7/finance/options/FB
Response Text:
b'Forbidden'
from module release page:
v0.6.0 (January 24, 2018)
Highlights include:
Immediate deprecation of Yahoo!, Google Options and Quotes and EDGAR. The end points behind these APIs have radically changed and the
existing readers require complete rewrites. In the case of most Yahoo!
data the endpoints have been removed. PDR would like to restore these
features, and pull requests are welcome.
so I won't expect that works
to do what you want directly using pandas:
import pandas as pd
from datetime import datetime
df = pd.read_json('https://query1.finance.yahoo.com/v7/finance/options/FB')
for date in df['optionChain'][1][0]['expirationDates']:
print(datetime.fromtimestamp(date).isoformat())
output:
>>>
2022-01-13T20:00:00
2022-01-20T20:00:00
2022-01-27T20:00:00
2022-02-03T20:00:00
2022-02-10T20:00:00
2022-02-17T20:00:00
2022-02-24T20:00:00
2022-03-03T20:00:00
2022-03-17T21:00:00
2022-04-13T21:00:00
2022-05-19T21:00:00
2022-06-16T21:00:00
2022-07-14T21:00:00
2022-09-15T21:00:00
2023-01-19T20:00:00
2023-03-16T21:00:00
2023-06-15T21:00:00
2024-01-18T20:00:00
2026-02-20T20:00:00
Process finished with exit code 0
# Import DataReader
from pandas_datareader.data import DataReader
# Import date
from datetime import date
# Set start and end dates
start = date(2016,1,1)
end = date(2016,12,31)
# Set the ticker
ticker = "AAPL"
# Set the data source
data_source = "iex"
# Import the stock prices
stock_prices = DataReader(ticker, data_source, start, end)
# Display and inspect the result
print(stock_prices.head())
stock_prices.info()
I can import DataReader and use 'iex' in a virtual environment easily but when I'm trying to do the same in my python interpreter I got a ValueError Exception also it asks for the IEX cloud API key. I haven't heard the term before even from my instructor. Please explain me what it is, also how to implement so that I can get rid of this error.
Error I have got!
Code:
import pandas as pd
import quandl
quandl.ApiConfig.api_key = 'wsnt2aKcnkNMJjdqqwTz'
pd = quandl.get('BATS / BATS_GOOGL')
print(df.head())
Error:
NotFoundError: (Status 400) (Quandl Error QECx01) We could not recognize the URL you requested: /api/v3/datasets/BATS / BATS_GOOGL/data. Please check your URL and try again.
You should not use spaces in the path; also, you should not use pd as a variable name (remember, you have imported pandas as pd), plus that, as is now, you are asking for the head() of a dataframe df that is nowhere defined.
Try with
df = quandl.get('BATS/BATS_GOOGL')