import datetime as dt
import pandas_market_calendars as mcal
def get_latest_trading_day(date, excg='NYSE'):
'''Return the nearest trading day before a given date (if it is not a trading day)'''
# Exchange trading calendar
nyse = mcal.get_calendar(excg)
start_date = date - dt.timedelta(days=15)
end_date = date + dt.timedelta(days=15)
valid_days = nyse.schedule(start_date=start_date, end_date=end_date).index
# Find the nearest trading day
while date not in valid_days:
date = date - dt.timedelta(days=1)
return date