This script fetches historical stock data from Yahoo Finance for a given ticker symbol and saves it to a CSV file. It also prints the last 30 days of data to the console.
Before running the script, ensure you have Python installed. You will also need to install the following Python libraries:
- pandas
- yfinance
You can install them using pip:
pip install pandas yfinanceTo run the script, execute it from your terminal and provide a stock ticker symbol as a command-line argument.
python fetch_stock_data.py <TICKER_SYMBOL>Replace <TICKER_SYMBOL> with the stock ticker you are interested in (e.g., AAPL, MSFT, GOOG).
Example:
python fetch_stock_data.py AAPLThis command will:
- Fetch the last 1 year of historical daily data for Apple Inc. (AAPL).
- Print the last 30 days of this data to your console.
- Save the complete fetched historical data to a file named
AAPL_historical_data.csvin the same directory where the script is located.
- Console: Displays the last 30 days of historical data for the specified ticker.
- CSV File: A file named
<TICKER_SYMBOL>_historical_data.csv(e.g.,AAPL_historical_data.csv) will be created, containing the Date, Open, High, Low, Close, Volume, Dividends, and Stock Splits for the past year.
If an invalid ticker symbol is provided, or if data cannot be fetched for other reasons (e.g., network issues, delisted ticker), the script will print an error message to the console and will not create a CSV file.