Reputation: 1
I am trying to extract data using API from the web. What I am trying to do is call for the current/historical stock prices of certain company and store the information in a dataframe or a sqlite database. I have a code where I can call for information for one company. But how do I create a loop where I can substitute the ticker symbol (a list of codes representing each company’s name – for which I have a separate dataframe) of each company and store its prices. The intention is to store prices of ALL companies (~500) in one dataframe under their ticker symbol. Here is the code that I have to pull the price of one stock.
data=requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=NSE:HDFCBANK&outputsize=full&apikey={}'.format(api_key))
I need to replace NSE:HDFCBANK with a list of other tickers in another dataframe which has list like this
df1 = {'Ticker': ['HDFCBANK', 'SBIN', 'ADANIGAS', 'BAJAJAUTO'],
'Name': ['Hdfc Bank', 'State Bank of India', 'Adani Gas', 'Bajaj Auto']}
df1 = pd.DataFrame(df1, columns = ['Ticker', 'Name'])
df1
Very new to Python. Will much appreciate your help. Thanks.
Upvotes: 0
Views: 194
Reputation: 56
Similar to a list, you can iterate over elements in a column of a dataframe. You can replace the ticker symbol using .format()
just like you already have done with your api_key
(Values get placed in the respective {}
present in the string).
prices = []
for ticker in df1.Ticker:
data=requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=NSE:{}&outputsize=full&apikey={}'.format(ticker, api_key))
prices.append(data.json()['Time Series (Daily)']['2020-04-30']['1. open'])
df = pd.DataFrame({'symbol':df1.Ticker, 'price':prices})
Upvotes: 1