How to write and append stock data for multiple tickers from Yahoo Finance url?

634 Views Asked by At

I have the following code and need to download data for multiple tickers from yahoo url:

import time
import datetime
import pandas as pd

#read ticker symbols from a file to a python list object named ticker
symbols = []
with open('ticker_list.csv') as f:
    symbol = [row.split()[0] for row in f]
f.close

period1 = int(time.mktime(datetime.datetime(2020, 12, 1, 23, 59).timetuple()))
period2 = int(time.mktime(datetime.datetime(2020, 12, 31, 23, 59).timetuple()))
interval = '1d' # 1d, 1wk, 1m

xlwriter = pd.ExcelWriter('Stock_Price_sample.xlsx', engine='xlsxwriter')
for ticker in symbols:
    query_string = f'https://query1.finance.yahoo.com/v7/finance/download/{ticker}?period1={period1}&period2={period2}&interval={interval}&events=history&includeAdjustedClose=true'
    df = pd.read_csv(query_string)
    append_df.to_excel(xlwriter, sheet_name='Sheet1', index=False)
    
xlwriter.save()

For example, in the ticker_list.csv file I have the following ticker: MSFT, AAPL, TSLA, etc.

I am not able to download the stock data and append them to an excel writer. It gives me a blank page. Any help how to solve this or alternative technique will be appreciated.

1

There are 1 best solutions below

1
Gri Ma On

You can use yahooquery or yfinance for this task.