This script fetches historical stock data for a given stock symbol and date range from Yahoo Finance. It uses the yfinance library to retrieve the data and pandas to handle it. The script provides a command-line interface (CLI) for easy usage.
-
Python 3.x
-
The following Python libraries are required:
yfinancepandas
You can install them using pip:
pip install yfinance pandas
To run the script, use the following command structure from your terminal:
python stock_data.py <SYMBOL> <START_DATE> <END_DATE>Where:
<SYMBOL>: The stock symbol you want to fetch data for (e.g.,AAPL,MSFT,GOOGL).<START_DATE>: The beginning of the date range for the historical data. Must be in YYYY-MM-DD format.<END_DATE>: The end of the date range for the historical data. Must be in YYYY-MM-DD format.
Fetching Apple Inc. (AAPL) data for January 2023:
python stock_data.py AAPL 2023-01-01 2023-01-31Fetching Microsoft Corp. (MSFT) data for a specific period in June 2022:
python stock_data.py MSFT 2022-06-01 2022-06-10If the data is fetched successfully, the script will print the historical stock data to the console in a tabular format. Here's a snippet of what it might look like:
Data for AAPL from 2023-01-01 to 2023-01-05:
Open High ... Dividends Stock Splits
Date ...
2023-01-03 00:00:00-05:00 128.613985 129.226052 ... 0.0 0.0
2023-01-04 00:00:00-05:00 125.267339 127.014709 ... 0.0 0.0
... (more data rows) ...
(Note: The actual columns and data may vary slightly based on the information provided by Yahoo Finance.)
The script includes error handling for various situations:
- Invalid Date Format: If the
START_DATEorEND_DATEis not in theYYYY-MM-DDformat, the script will print an error message and exit:Error: Date format must be YYYY-MM-DD. - Invalid Symbol / No Data: If the stock symbol is invalid, or if no data is found for the given symbol and date range, an appropriate message will be printed to the console:
or
Error fetching data for symbol INVALID_SYMBOL: <Error details from yfinance>No data found for symbol AAPL from 1950-01-01 to 1950-01-05.
The project includes a suite of unit tests to ensure the script's functionality. To run these tests, navigate to the project directory in your terminal and execute:
python -m unittest test_stock_data.pyThis will run the tests defined in test_stock_data.py and report the results.