How do I input stock data from a list in python for Alpha Vantage

33 views Asked by At

I am new to Python but understand programming concepts from way back. I am trying to use Alpha Vantage to get stock data for analysis. So far I have been able to pull what I need for one stock at a time, asking the user for input:

import pandas as pd

from alpha_vantage.timeseries import TimeSeries
import time
api_key = 'QLIFIFQWRVWXRA4U'
STOCK = str(input('What stock do you want to search?    '))
ts = TimeSeries(key=api_key, output_format='pandas')
data, meta_data =  ts.get_daily(symbol=STOCK, outputsize = 'compact')
print(data)

What I need to figure out how to do is instead of asking for the user to enter data have a file with multiple stocks (for example, say the Fortune 500) so the program searches for one after the other. Later I can use all that data to search for what I want. So for example a list might be:

MSFT, F, GM, BROS

I would want it to input MSFT on its own instead of asking me for input. It gets me the data, then runs for F. And so on.

I can figure out how to handle the output, getting the input has me stuck.

Thanks in advance.

I have not known where to start past my asking for user input manually.

1

There are 1 answers

0
hteza On

Let's say if the user were to create a text file reading "MSFT, F, GM, BROS", you can read that text into your python environment using native function open.

STOCKS = open(path_to_text, "r").read()

It will set the variable STOCKS as a str "MSFT, F, GM, BROS".

For the function ts.get_daily(symbol=STOCK, outputsize = 'compact'), it requires the STOCK to be the ticker, so you need a loop to add one ticker as a time.

ou can split string at commas using STOCKS.split(",") so that it will give you a list of stocks ["MSFT ", "F ", "GM ", "BROS"]. You will notice the white psaces in each tickers since they are considered strings as well therefore you need to remove them.Using list comprehension, it will be STOCKS = [i.strip() for i in STOCKS.split(",")].

Now you can feed one ticker as a time into your function using a forward loop.

for STOCK in STOCKS:
   data, meta_data =  ts.get_daily(symbol=STOCK, outputsize = 'compact')
   print(data)

Please note that it will be printing the data then overwriting it every loop. So consider saving it inside a dictionary.

STOCK_DATA = dict()
for STOCK in STOCKS:
   fetched_data = dict()
   fetched_data["data"], fetched_data["meta_data"] =  ts.get_daily(symbol=STOCK, outputsize = 'compact')
   STOCK_DATA[STOCK] = fetched_data
   print(fetched_data["data"])

Afterwards, you can find specific datapoints at STOCK_DATA["MSFT"] or STOCK["MSFT"]["data"]. There are other ways of achieving the same results using libraries such as pandas but I prefer working as native as possible.