Automating Python Scripts for Stock Prices
Suppose you have a portfolio of stock investments. To analyze the daily stock prices, you must go to a stock price tracking website like Yahoo Finance. However creating a simple script can help you automatically fetch opening and closing prices of a stock ticker. How can we automate this task using Python?
Creating the script
Let us first start by creating a Python script and importing our libraries.import
import yfinance as yf
from datetime import datetime
import pandas as pd
We will then create a function to fetch a stock price of the current date.
def fetch_stock_prices(symbol):
# Get the current date
current_day = datetime.now().strftime("%Y-%m-%d")
# Fetch data for the specified symbol for the current day
stock_data = yf.download(symbol, start=current_day, end=current_day)
# Extract the opening and closing prices
opening_prices = stock_data['Open']
closing_prices = stock_data['Close']
return opening_prices, closing_prices
This function first converts the current day’s date to a string. It then uses the (yfinance) Python library to pull stock details of any stock symbol with the current day as the start and end date.
The variables (opening_prices) and (closing prices) are then used to save the opening and closing prices.
The (return) method returns the prices.
Now we need to concatenate the data and make sure we get the required data. For this, we write a main function.
def main():
# List of stock symbols
symbols = ["AAPL", "MSFT","GOOGL"]
schema = {'Date': 'datetime64[ns]', 'Symbol': 'str', 'Opening Price': 'float', 'Closing Price': 'float'}
dataframe = pd.DataFrame(columns=schema.keys()).astype(schema)
# Print the opening and closing prices
for symbol in symbols:
opening_prices, closing_prices = fetch_stock_prices(symbol)
data = pd.DataFrame.from_dict({'Date': datetime.now(),
'Symbol': symbol,
'Opening Price': opening_prices,
'Closing Price': closing_prices
})
dataframe = pd.concat([dataframe, data], ignore_index=True)
# Check if the existing file exists
try:
existing_data = pd.read_excel('stock_prices.xlsx')
dataframe = pd.concat([dataframe, existing_data.astype(dataframe.dtypes)], ignore_index=True)
except FileNotFoundError:
pass
# Save the dataframe to the existing or new Excel file
dataframe.to_excel('stock_prices.xlsx', index=False)
We start our main function with a list of stock symbols.
A Pandas DataFrame (dataframe) is created to store the fetched stock prices. The script iterates over each symbol in the list using a for loop.
For each symbol, it calls the fetch_stock_prices function to get the opening and closing prices for the current date. For each symbol, a new DataFrame (data) is created with columns: Date, Symbol, Opening Price, and Closing Price.
The newly fetched data is then concatenated with the existing data in the main data frame (dataframe). The script attempts to read an existing Excel file (stock_prices.xlsx). If the file exists, it loads its data into a data frame (existing_data).
The existing data is then concatenated with the new data to ensure that all data is retained.
领英推荐
Finally, the combined data frame is saved to an Excel file (stock_prices.xlsx) using the to_excel method, and the index parameter is set to False to avoid saving row indices.
if __name__ == "__main__":
This block ensures that the main the function is executed only if the script is run directly (not imported as a module). Now, when you run this script, it will fetch the opening and closing prices for the specified stock symbols, update the existing data (if any), and save the consolidated data to an Excel file. Make sure to install the necessary libraries (yfinance and pandas) before running the script.
Creating a Batch File
We will first create a batch file to execute the Python script. For this, we open Notepad and create a new file with the following content:
@echo off
python C:\path\to\your\script.py
Replace C:\path\to\your\script.py with the full path to your Python script.
Save the file with a .bat extension, for example, run_script.bat. Double-click the batch file to make sure it runs your Python script successfully. This ensures that the batch file is working as expected.
Scheduling Your Script
Conclusion
Automating the task of fetching daily stock prices using a Python script and scheduling it with Windows Task Scheduler provides a convenient and efficient way to stay consistently updated on your investment portfolio. By seamlessly integrating data retrieval and scheduling, this approach minimizes manual effort, ensuring that you receive timely information without the need for constant oversight.
Data Engineer | Data Scientist
1 年Automating the stock prices fetching from Yahoo finance API makes it easy to keep track of our investments.