Skip to content

Instantly share code, notes, and snippets.

@BazzalSeed
Last active July 12, 2023 03:37
Show Gist options
  • Save BazzalSeed/ba198f566468be23cc2f3d6f904d850f to your computer and use it in GitHub Desktop.
Save BazzalSeed/ba198f566468be23cc2f3d6f904d850f to your computer and use it in GitHub Desktop.

Usage

Dumb python script to get the monthly average closing price of a ticker. For example

python monthly_average.py FB --date 2020-05

will give you the monthly average close price for May.2020 for Facebook.

Setup

  1. setup virtualenv with python >= 2.7.15 [optional]
  2. run pip install -r requirements.txt
  3. run script
import yfinance as yf
import calendar
import argparse
import arrow
def get_start_end(date):
"""
Takes a date and returns the first and last date of that month.
"""
start_date = arrow.get(date.strftime("%Y-%m"))
end_date = start_date.shift(
days=calendar.monthrange(start_date.year, start_date.month)[1] - 1
)
return start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d")
def get_close_average(start, end, stock_name):
"""
Fetches the history for a stock for a specific date range and
returns the average of 'Close' price.
"""
ticker = yf.Ticker(stock_name)
df = ticker.history(stock_name, start=start, end=end)
return df["Close"].mean()
def run(args):
"""
Main function to fetch and print the average close price.
If date is not provided, the current date is used.
"""
date = arrow.get(args.date) if args.date else arrow.utcnow()
start, end = get_start_end(date)
value = get_close_average(start, end, args.stock_name)
value = round(value, 3) # formatting to 3 decimal points
print(f"Average Close Price of {args.stock_name} is {value} from {start} to {end}")
if __name__ == "__main__":
# Argument parser setup
parser = argparse.ArgumentParser(
description="Get the calendar monthly close average"
)
parser.add_argument("stock_name")
parser.add_argument("--date", help="the date in the format of YYYY-MM")
# Parse the arguments and run the main function
args = parser.parse_args()
run(args)
yfinance==0.2.22
arrow==0.15.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment