Buy Me a Coffee? Your support is much appreciated!



Source Code

import os
import time
from datetime import datetime
import argparse
import pandas as pd # pip install pandas

def download_stock_historical_price(ticker, period1, period2, interval):
    try:
        period1_converted = int(time.mktime(datetime.strptime(period1, '%Y-%m-%d').timetuple()))
        period2_converted = int(time.mktime(datetime.strptime(period2, '%Y-%m-%d').timetuple()))
        data_file_name = f'{ticker}_{period1}_{period2}_{interval}.csv'
        base_url = 'https://query1.finance.yahoo.com/v7/finance/download/'
        url = f'{base_url}{ticker}?period1={period1_converted}&period2={period2_converted}&interval={interval}&includeAdjustedClose=True'    
        print(f'Downloading file from URL: {url}')
        df = pd.read_csv(url)
        df.to_csv(os.path.join(os.getcwd(), data_file_name), index=False)
        print('File download complete')
    except Exception as e:
        print(e)

stock_price_parser = argparse.ArgumentParser(prog='stock_price_downloader', usage='%(prog)s ticker period1 period2 interval', description='Download U.S. stock historical price')

# add the arguments
stock_price_parser.add_argument('ticker', type=str, help='ticker name')
stock_price_parser.add_argument('period1', type=str, help='yyyy-mm-dd')
stock_price_parser.add_argument('period2', type=str, help='yyyy-mm-dd')
stock_price_parser.add_argument('interval', type=str, help='Please enter one of the following: 1d, 1wk, 1mo')

args = stock_price_parser.parse_args()
download_stock_hsitorical_price(args.ticker, args.period1, args.period2, args.interval)