nickmccullum / algorithmic-trading-python

The repository for freeCodeCamp's YouTube course, Algorithmic Trading in Python
2.43k stars 2.42k forks source link

Looping Through The Tickers in Our List of Stocks doesn't work #44

Open mpquochung opened 1 year ago

mpquochung commented 1 year ago

I got this error when running the code: image I have tried several things but doesn't work. Anyone help me pls! P/S: this loop can only create 134 tickers, does this mean something happened with the 135th?

npomfret commented 1 year ago

The sample code isn't ideal as the response to the batch request may have symbols missing. I think it's better to loop over the symbols in the response rather than the symbols in the request. Something like...

stocks = pd.read_csv('sp_500_stocks.csv')
all_symbols = stocks['Ticker']
step = 100

my_columns = [... whatever]
df = pd.DataFrame(columns=my_columns)

for i in range(0, len(all_symbols), step):
    symbols = all_symbols[i:i + step]
    symbols_text = ','.join(symbols)

    url = f'{base_url}/stable/whatever...'
    response = session.get(url)
    data = response.json()
    for symbol in data:
        quote = data[symbol]['quote']
        ... etc

(also note, the above code has a greatly simplified 'chunking' mechanism and achieves everything in a single loop)