Example #1
0
    def test_calendar_observance_dates(self):
        # Test for issue 11477
        USFedCal = get_calendar("USFederalHolidayCalendar")
        holidays0 = USFedCal.holidays(datetime(2015, 7, 3), datetime(2015, 7, 3))  # <-- same start and end dates
        holidays1 = USFedCal.holidays(datetime(2015, 7, 3), datetime(2015, 7, 6))  # <-- different start and end dates
        holidays2 = USFedCal.holidays(datetime(2015, 7, 3), datetime(2015, 7, 3))  # <-- same start and end dates

        tm.assert_index_equal(holidays0, holidays1)
        tm.assert_index_equal(holidays0, holidays2)
Example #2
0
def get_holidays(start_date, end_date):
    # Implement from here https://stackoverflow.com/questions/33094297/create-trading-holiday-calendar-with-pandas/36525605#36525605
    cal = get_calendar('USFederalHolidayCalendar')  # Create calendar instance
    trading_cal = HolidayCalendarFactory('TradingCalendar', cal, GoodFriday)
    # new instance of class
    newcal = trading_cal()
    newcal.rules.pop(7)  # Remove Columbus Day rule
    newcal.rules.pop(7)  # Remove Veteran's Day rule
    holidays = newcal.holidays(start=start_date, end=end_date).to_pydatetime()
    #    holidays = np.append(holidays, dt.datetime.strptime(bush_holiday, '%Y-%m-%d'))
    return holidays
Example #3
0
    def test_calendar_observance_dates(self):
        # Test for issue 11477
        USFedCal = get_calendar('USFederalHolidayCalendar')
        holidays0 = USFedCal.holidays(datetime(2015, 7, 3), datetime(
            2015, 7, 3))  # <-- same start and end dates
        holidays1 = USFedCal.holidays(datetime(2015, 7, 3), datetime(
            2015, 7, 6))  # <-- different start and end dates
        holidays2 = USFedCal.holidays(datetime(2015, 7, 3), datetime(
            2015, 7, 3))  # <-- same start and end dates

        tm.assert_index_equal(holidays0, holidays1)
        tm.assert_index_equal(holidays0, holidays2)
Example #4
0
    def remove_holidays(self, exclusion_list=[]):
        for i in exclusion_list:
            self.exclusion.append(i)
        holiday_list = []
        for i in self.holidays:
            if i.name not in self.exclusion:
                holiday_list.append(i)
        self.holidays = holiday_list

        class CustomCal(AbstractHolidayCalendar):
            rules = self.holidays

        self.cal = get_calendar('CustomCal')
        self.bday = cbd(calendar=self.cal)
Example #5
0
def test_holidays_within_dates(holiday, start, expected):
    # see gh-11477
    #
    # Fix holiday behavior where holiday.dates returned dates outside
    # start/end date, or observed rules could not be applied because the
    # holiday was not in the original date range (e.g., 7/4/2015 -> 7/3/2015).
    if isinstance(holiday, str):
        calendar = get_calendar("USFederalHolidayCalendar")
        holiday = calendar.rule_from_name(holiday)

    if isinstance(expected, str):
        expected = [Timestamp(expected)]

    _check_holiday_results(holiday, start, start, expected)
def test_holidays_within_dates(holiday, start, expected):
    # see gh-11477
    #
    # Fix holiday behavior where holiday.dates returned dates outside
    # start/end date, or observed rules could not be applied because the
    # holiday was not in the original date range (e.g., 7/4/2015 -> 7/3/2015).
    if isinstance(holiday, str):
        calendar = get_calendar("USFederalHolidayCalendar")
        holiday = calendar.rule_from_name(holiday)

    assert list(holiday.dates(start, start)) == expected

    # Verify that timezone info is preserved.
    assert list(
        holiday.dates(utc.localize(Timestamp(start)), utc.localize(Timestamp(start)))
    ) == [utc.localize(dt) for dt in expected]
Example #7
0
def test_calendar_observance_dates():
    # see gh-11477
    us_fed_cal = get_calendar("USFederalHolidayCalendar")
    holidays0 = us_fed_cal.holidays(datetime(2015, 7, 3), datetime(
        2015, 7, 3))  # <-- same start and end dates
    holidays1 = us_fed_cal.holidays(datetime(2015, 7, 3), datetime(
        2015, 7, 6))  # <-- different start and end dates
    holidays2 = us_fed_cal.holidays(datetime(2015, 7, 3), datetime(
        2015, 7, 3))  # <-- same start and end dates

    # These should all produce the same result.
    #
    # In addition, calling with different start and end
    # dates should not alter the output if we call the
    # function again with the same start and end date.
    tm.assert_index_equal(holidays0, holidays1)
    tm.assert_index_equal(holidays0, holidays2)
Example #8
0
def test_calendar_observance_dates():
    # see gh-11477
    us_fed_cal = get_calendar("USFederalHolidayCalendar")
    holidays0 = us_fed_cal.holidays(datetime(2015, 7, 3), datetime(
        2015, 7, 3))  # <-- same start and end dates
    holidays1 = us_fed_cal.holidays(datetime(2015, 7, 3), datetime(
        2015, 7, 6))  # <-- different start and end dates
    holidays2 = us_fed_cal.holidays(datetime(2015, 7, 3), datetime(
        2015, 7, 3))  # <-- same start and end dates

    # These should all produce the same result.
    #
    # In addition, calling with different start and end
    # dates should not alter the output if we call the
    # function again with the same start and end date.
    tm.assert_index_equal(holidays0, holidays1)
    tm.assert_index_equal(holidays0, holidays2)
Example #9
0
    def test_holidays_within_dates(self):
        # Fix holiday behavior found in #11477
        # where holiday.dates returned dates outside start/end date
        # or observed rules could not be applied as the holiday
        # was not in the original date range (e.g., 7/4/2015 -> 7/3/2015)
        start_date = datetime(2015, 7, 1)
        end_date = datetime(2015, 7, 1)

        calendar = get_calendar('USFederalHolidayCalendar')
        new_years = calendar.rule_from_name('New Years Day')
        july_4th = calendar.rule_from_name('July 4th')
        veterans_day = calendar.rule_from_name('Veterans Day')
        christmas = calendar.rule_from_name('Christmas')

        # Holiday: (start/end date, holiday)
        holidays = {USMemorialDay: ("2015-05-25", "2015-05-25"),
                    USLaborDay: ("2015-09-07", "2015-09-07"),
                    USColumbusDay: ("2015-10-12", "2015-10-12"),
                    USThanksgivingDay: ("2015-11-26", "2015-11-26"),
                    USMartinLutherKingJr: ("2015-01-19", "2015-01-19"),
                    USPresidentsDay: ("2015-02-16", "2015-02-16"),
                    GoodFriday: ("2015-04-03", "2015-04-03"),
                    EasterMonday: [("2015-04-06", "2015-04-06"),
                                   ("2015-04-05", [])],
                    new_years: [("2015-01-01", "2015-01-01"),
                                ("2011-01-01", []),
                                ("2010-12-31", "2010-12-31")],
                    july_4th: [("2015-07-03", "2015-07-03"),
                               ("2015-07-04", [])],
                    veterans_day: [("2012-11-11", []),
                                   ("2012-11-12", "2012-11-12")],
                    christmas: [("2011-12-25", []),
                                ("2011-12-26", "2011-12-26")]}

        for rule, dates in compat.iteritems(holidays):
            empty_dates = rule.dates(start_date, end_date)
            assert empty_dates.tolist() == []

            if isinstance(dates, tuple):
                dates = [dates]

            for start, expected in dates:
                if len(expected):
                    expected = [Timestamp(expected)]
                self.check_results(rule, start, start, expected)
Example #10
0
    def test_holidays_within_dates(self):
        # Fix holiday behavior found in #11477
        # where holiday.dates returned dates outside start/end date
        # or observed rules could not be applied as the holiday
        # was not in the original date range (e.g., 7/4/2015 -> 7/3/2015)
        start_date = datetime(2015, 7, 1)
        end_date = datetime(2015, 7, 1)

        calendar = get_calendar('USFederalHolidayCalendar')
        new_years = calendar.rule_from_name('New Years Day')
        july_4th = calendar.rule_from_name('July 4th')
        veterans_day = calendar.rule_from_name('Veterans Day')
        christmas = calendar.rule_from_name('Christmas')

        # Holiday: (start/end date, holiday)
        holidays = {USMemorialDay: ("2015-05-25", "2015-05-25"),
                    USLaborDay: ("2015-09-07", "2015-09-07"),
                    USColumbusDay: ("2015-10-12", "2015-10-12"),
                    USThanksgivingDay: ("2015-11-26", "2015-11-26"),
                    USMartinLutherKingJr: ("2015-01-19", "2015-01-19"),
                    USPresidentsDay: ("2015-02-16", "2015-02-16"),
                    GoodFriday: ("2015-04-03", "2015-04-03"),
                    EasterMonday: [("2015-04-06", "2015-04-06"),
                                   ("2015-04-05", [])],
                    new_years: [("2015-01-01", "2015-01-01"),
                                ("2011-01-01", []),
                                ("2010-12-31", "2010-12-31")],
                    july_4th: [("2015-07-03", "2015-07-03"),
                               ("2015-07-04", [])],
                    veterans_day: [("2012-11-11", []),
                                   ("2012-11-12", "2012-11-12")],
                    christmas: [("2011-12-25", []),
                                ("2011-12-26", "2011-12-26")]}

        for rule, dates in compat.iteritems(holidays):
            empty_dates = rule.dates(start_date, end_date)
            assert empty_dates.tolist() == []

            if isinstance(dates, tuple):
                dates = [dates]

            for start, expected in dates:
                if len(expected):
                    expected = [Timestamp(expected)]
                self.check_results(rule, start, start, expected)
Example #11
0
    def __init__(self, bt_start=9, bt_close=17, exclusion_list=[]):
        self.bt_start = bt_start
        self.bt_close = bt_close
        self.bt_len = self.bt_close - self.bt_start
        self.exclusion = []
        self.holidays = [
            Holiday('NewYearsDay', month=1, day=1, observance=nearest_workday),
            USMartinLutherKingJr, USPresidentsDay, GoodFriday, USMemorialDay,
            Holiday('USIndependenceDay',
                    month=7,
                    day=4,
                    observance=nearest_workday), USLaborDay, USThanksgivingDay,
            Holiday('Christmas', month=12, day=25, observance=nearest_workday)
        ]

        class CustomCal(AbstractHolidayCalendar):
            rules = self.holidays

        self.cal = get_calendar('CustomCal')
        self.bday = cbd(calendar=self.cal)
def getBusinessDayRange(start_date, num_of_days):
    
    #Create calendar instance
    cal = get_calendar('USFederalHolidayCalendar')
    #Remove Veteran's Day rule
    cal.rules.pop(7)       
    #Remove Columbus Day rule                       
    cal.rules.pop(6) 
    
    #print cal.holidays(datetime(2014, 12, 31), datetime(2016, 12, 31))
    #can be used to notify us when holidays are coming up
    
    #Sets up a trading calendar                      
    businessHolidayCal = HolidayCalendarFactory('BusinessHolidayCalendar', cal, GoodFriday) 
    
    #creates the trading calendar offset
    businessDay = CustomBusinessDay(cal = businessHolidayCal())
    
    dates = pd.date_range(start_date, periods=5, freq=businessDay).to_series()
    return dates
Example #13
0
    def get_calendar(self):
        """
        Get date data to track weekends, holidays, quarter, etc
        Store in database table dbo_DateDim
        """
        # drop data from table each time program is run
        truncate_query = 'TRUNCATE TABLE dbo_datedim'
        self.engine.execute(truncate_query)

        # 3 years of past data and up to 1 year of future forecasts
        begin = date.today() - timedelta(days=self.datalength)
        end = date.today() + timedelta(days=365)

        # list of US holidays
        cal = get_calendar('USFederalHolidayCalendar')  # Create calendar instance
        cal.rules.pop(7)   # Remove Veteran's Day
        cal.rules.pop(6)   # Remove Columbus Day
        tradingCal = HolidayCalendarFactory('TradingCalendar', cal, GoodFriday)   # Good Friday is OFF in Stock Market

        # new instance of class for STOCK MARKET holidays
        tradingHolidays = tradingCal()
        holidays = tradingHolidays.holidays(begin, end)

        # 3 years of past data
        day = date.today() - timedelta(days=self.datalength)

        while day < end:
            date_query = 'INSERT INTO dbo_datedim VALUES({},{},{},{},{},{})'   # insert query into the database
            day = day + timedelta(days=1)
            day_str = "'" + str(day) + "'"
            qtr = (int((day.month - 1) / 3)) + 1    # calculate quarter value

            # check if the day is a weekend?
            weekend = (1 if day.isoweekday() == 6 or day.isoweekday() == 7 else 0)

            # is day a holiday in US (NY day, MLK, President's Day, Good Friday, Memorial Day,
            # July 4, Labor Day, Thanksgiving, Christmas
            isholiday = (1 if day in holidays else 0)
            date_query = date_query.format(day_str, day.year, day.month, qtr, weekend, isholiday)
            self.engine.execute(date_query)
Example #14
0
 def test_rule_from_name(self):
     USFedCal = get_calendar('USFederalHolidayCalendar')
     assert USFedCal.rule_from_name('Thanksgiving') == USThanksgivingDay
Example #15
0
## compounded
## get the variables needed:
## 1 year zero coupon (for annual Sortino/information/Sharpe ratio)
zc01 = zc['SVENY01']
## 30 year zero coupon, the instrument we are interested in
zc30 = zc['SVENY30']
## the market price of the bond:
par_val = 1000
p30 = par_val / (1 + zc30 / 100)**30

## Find a start date; Ideally this would be a treasury auction date?
start_date = '1985-12-02'
## suitable end date
end_date = '2019-12-02'
#cal = USFederalHolidayCalendar()
cal = get_calendar('USFederalCalendar')

first_bday_of_month = [
    get_business_day(d).date()
    for d in pd.date_range(start_date, end_date, freq='BMS')
]

## cash; start with initial pool of money
c = 200
## invested amount; set at 200 for now
inv = 200
## array with maturity dates of bonds, number of bonds;
## Just automatically initialize with 30 years to maturity for now
mdate = np.array(first_bday_of_month) + relativedelta(years=30)
nbonds = np.zeros(len(first_bday_of_month))
## As we loop through the dates, if a maturity date now falls at or before
Example #16
0
    def test_get_calendar(self):
        class TestCalendar(AbstractHolidayCalendar):
            rules = []

        calendar = get_calendar('TestCalendar')
        assert TestCalendar == calendar.__class__
Example #17
0
def test_get_calendar():
    class TestCalendar(AbstractHolidayCalendar):
        rules = []

    calendar = get_calendar("TestCalendar")
    assert TestCalendar == calendar.__class__
Example #18
0
def num_nyse_trading_days(start_date, end_date):
    """
    This function calculates the number of trading days, inclusive, between
    two dates.
    :param start_date: String; the starting date. Has the following format:
    'YYYY-mm-dd'.
    :param end_date: String; the ending date. Has the following format:
    'YYYY-mm-dd'. Can also be None.
    :return: Int; the number of trading days between the two dates.
    """
    """
    Solution for number of trading days found on two stackoverflow posts:
    https://stackoverflow.com/questions/44822697/business-days-between-two-dates-excluding-holidays-in-python
    https://stackoverflow.com/questions/33094297/create-trading-holiday-calendar-with-pandas
    This code isn't perfect because it is directly modifying the USFederal...
    calendar. As in, if I wanted to use it again, I'd have to add back in
    Veteran's Day and Columbus day (that's why I only remove them once).
    To be honest I spent an obnoxious amount of time on this function, trying
    to figure out how to calculate the number of nyse trading days between
    two dates (not just business days, as that's a different question), and
    ultimately I just wanted a solution that would work, even if it was a
    solution that is modifying code I shouldn't be editing. 
    """

    if end_date is None:
        # In this case we weren't given an end date so the end date is assumed
        # to be the current time. Thus we need to find the current time in EST.
        tz = timezone('America/New_York')
        if datetime.datetime.now(tz).time() < datetime.time(9):
            # If it is before 9:00 EST, then the difference is the current date
            # minus the starting date minus 1, because the trading day hasn't
            # started yet.
            end_date = datetime.datetime.now(tz) - datetime.timedelta(days=1)
            end_date = end_date.strftime("%Y-%m-%d")
        else:
            # Else the difference is the current date minus the start date.
            end_date = datetime.datetime.now(tz).strftime("%Y-%m-%d")

    cal = get_calendar('USFederalHolidayCalendar')  # Create calendar
    if len(cal.rules) == 10:
        # If there are 10 rules, then we know we haven't modified this calendar
        # yet.
        # We need to modify this calendar because Veteran's Day and Columbus
        # Day are both trading days.
        cal.rules.pop(7)  # Remove Veteran's Day rule
        cal.rules.pop(6)  # Remove Columbus Day rule
    # Create the calendar from the rules we have.
    tradingCal = HolidayCalendarFactory('TradingCalendar', cal, GoodFriday)
    trading_days = CustomBusinessDay(calendar=tradingCal())
    calendar = pd.date_range(start=start_date, end=end_date,
                             freq=trading_days).to_pydatetime()

    res = len(calendar)
    if datetime.datetime(2018, 12, 5) in calendar:
        # In this case, we need to subtract one because the nyse closed
        # on december 5th, 2018, to mourn George H.W. Bush's death.
        res -= 1
        # Not an elegant solution, but I wasn't sure how else to do it and
        # it seems pretty effective for the days that I'm working with.

    return res
Example #19
0
    def test_get_calendar(self):
        class TestCalendar(AbstractHolidayCalendar):
            rules = []

        calendar = get_calendar('TestCalendar')
        self.assertEqual(TestCalendar, calendar.__class__)
print(" Resuming:"+str(resume))



#print(tickers)
#exit()


os.environ['polygon_api_key'] = "jg0i3J_ZFD1_v4wBRQFEzp9NHDlYwHQff5_8_u"
polygon_api_key = os.environ.get("polygon_api_key", "my-api-key")

# dd=datetime(2020, 3, 25,4,0,0)			#starting on date at 4am			
# dd = dd.strftime("%Y-%m-%d %H:%M:%S") 	#start date as string

#calculate holidays
cal = get_calendar('USFederalHolidayCalendar')  # Create calendar instance
cal.rules.pop(7)                                # Remove Veteran's Day rule
cal.rules.pop(6)                                # Remove Columbus Day rule
tradingCal = HolidayCalendarFactory('TradingCalendar', cal, GoodFriday)
#print (tradingCal.rules)

#new instance of class
cal1 = tradingCal()
holiday_dates = cal1.holidays(datetime(2020, 1, 1), datetime(2020, 12, 31))


dstart = datetime.strptime(dateStart, '%Y-%m-%d')	#start market day at 4am
dend = datetime.strptime(dateEnd, '%Y-%m-%d')	#start market day at 4am

date_rng = pd.bdate_range(datetime(dstart.year,dstart.month,dstart.day), datetime(dend.year,dend.month,dend.day),  holidays=holiday_dates, freq='C', weekmask = None)
#print (date_rng)
Example #21
0
    def test_get_calendar(self):
        class TestCalendar(AbstractHolidayCalendar):
            rules = []

        calendar = get_calendar('TestCalendar')
        assert TestCalendar == calendar.__class__
Example #22
0
 def test_rule_from_name(self):
     USFedCal = get_calendar("USFederalHolidayCalendar")
     self.assertEqual(USFedCal.rule_from_name("Thanksgiving"), USThanksgivingDay)
Example #23
0
def test_rule_from_name():
    us_fed_cal = get_calendar("USFederalHolidayCalendar")
    assert us_fed_cal.rule_from_name("Thanksgiving") == USThanksgivingDay
Example #24
0
    def test_get_calendar(self):
        class TestCalendar(AbstractHolidayCalendar):
            rules = []

        calendar = get_calendar("TestCalendar")
        self.assertEqual(TestCalendar, calendar.__class__)
Example #25
0
 def test_rule_from_name(self):
     USFedCal = get_calendar('USFederalHolidayCalendar')
     assert USFedCal.rule_from_name('Thanksgiving') == USThanksgivingDay
Example #26
0
 def test_rule_from_name(self):
     USFedCal = get_calendar('USFederalHolidayCalendar')
     self.assertEqual(USFedCal.rule_from_name('Thanksgiving'),
                      USThanksgivingDay)
Example #27
0
def test_rule_from_name():
    us_fed_cal = get_calendar("USFederalHolidayCalendar")
    assert us_fed_cal.rule_from_name("Thanksgiving") == USThanksgivingDay
Example #28
0
'''@bday.py
@author: Z Hu
@date: April,2016

generate market days for U.S. equity.

@potential bug: the market calendar was different back to 20 century..

'''

from pandas.tseries.holiday import get_calendar, HolidayCalendarFactory, GoodFriday
from datetime import datetime,date,timedelta

calendar = get_calendar('USFederalHolidayCalendar')
calendar.rules.pop(6)
calendar.rules.pop(7)
trading_calendar = HolidayCalendarFactory('TradingCalendar',calendar,GoodFriday)


nYears = 50

output = trading_calendar()
start = datetime(2030-nYears,1,1)
end = datetime(2030,1,1)
holidays = output.holidays(start,end)


numdays = 365*nYears + nYears/4 +1
base = date(2030,1,1)
date_list = [base - timedelta(days=x) for x in range(0, numdays)]