Last active
February 20, 2025 21:41
-
-
Save basnijholt/693363051f7d705e5355ecca8f6e2b28 to your computer and use it in GitHub Desktop.
rolling-average-ticker-price.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /// script | |
# dependencies = [ | |
# "yfinance", | |
# ] | |
# /// | |
import yfinance as yf | |
from datetime import datetime, date | |
import argparse | |
import pandas as pd | |
def _get_past_trading_date(trading_days_ago: int) -> date: | |
"""Calculates a date in the past, considering only trading days. | |
Parameters | |
---------- | |
trading_days_ago | |
The number of trading days ago. | |
Returns | |
------- | |
date | |
The past date. | |
""" | |
today = pd.Timestamp(datetime.today()) | |
past_date = today - pd.tseries.offsets.BusinessDay(n=trading_days_ago) | |
return past_date.date() | |
def get_average_stock_price(ticker: str, trading_days_ago: int) -> float | None: | |
"""Calculates the average stock price (closing price) of a given ticker over a specified period. | |
Parameters | |
---------- | |
ticker | |
The stock ticker symbol (e.g., 'MSFT'). | |
trading_days_ago | |
The number of days in the past to calculate the average from. | |
Returns | |
------- | |
float | None | |
The average closing price, or None if data is unavailable. | |
""" | |
start_date = _get_past_trading_date(trading_days_ago) | |
end_date = _get_past_trading_date(0) | |
data = yf.download(ticker, start=start_date, end=end_date) | |
if data.empty: | |
return None | |
average_price = data["Close"].mean() | |
return average_price | |
def main() -> None: | |
"""Main function.""" | |
parser = argparse.ArgumentParser( | |
description="Calculate the average stock price of a given ticker over a specified period." | |
) | |
parser.add_argument("--ticker", type=str, help="The stock ticker symbol (e.g., MSFT)") | |
parser.add_argument("--days", type=int, help="The number of days in the past") | |
args = parser.parse_args() | |
average_price = get_average_stock_price(args.ticker, args.days) | |
if average_price is not None: | |
print( | |
f"The average closing price of {args.ticker} over the last {args.days} trading days is: " | |
f"${float(average_price):.2f}" # Explicitly cast to float | |
) | |
else: | |
print(f"Could not retrieve data for {args.ticker}") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment