Back to Community
How to determine if a day is the last trading day of the month?

Previously I've invoked

date_rules.month_end().get_nth_to_last_trading_day_of_month(aDatetime)  

but there was a change in the Quantopian API and now you have also to pass to that method the TradingEnvironment as argument.
See this extract from zipline:

    def get_last_trading_day_of_month(self, dt, env):  
        self.month = dt.month

        if dt.month == 12:  
            # Roll the year foward and start in January.  
            year = dt.year + 1  
            month = 1  
        else:  
            # Increment the month in the same year.  
            year = dt.year  
            month = dt.month + 1

        self.last_day = env.previous_trading_day(  
            dt.replace(year=year, month=month, day=1)  
        ).date()  
        return self.last_day  

The problem is, that I don't know how the get the TradingEnvironment and I need for my algo exactly the last trading day of the month as computed by Quantopian.
May somebody help me please?

Thanks
Costantino

6 responses

You can use the get_environment() function! this is incorrect, see below for correct answer

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Unfortunately it doesn't work: date_rules.month_end().get_nth_to_last_trading_day_of_month requires an instance of TradingEnvironment and get_environment() returns a string. Therefore the following exception occurs:

Runtime exception: AttributeError: 'str' object has no attribute 'previous_trading_day'  

Any other thoughts?

If you need it in real time you can use a boolean controlled by scheduled functions, else request daily price history and you can extract the last day of the month from the series index.

############################## Before Trading ####################################

def before_trading_start(context, data):  
    context.is_end_month = False

############################## Initialization ####################################

def initialize(context):  
    context.is_end_month = False  
    context.securities = sid(8554)  
    schedule_function(func=activate_end_month,  
                      date_rule=date_rules.month_end(),  
                      time_rule=time_rules.market_open())  
    schedule_function(func=rebalance,  
                      time_rule=time_rules.market_close())

############################## Event Handler ####################################

def handle_data(context, data):  
    pass

def activate_end_month(context, data):  
    context.is_end_month = True

def rebalance(context, data):  
    if context.is_end_month:  
        log.debug("last trading day of the month")  
    else:  
        log.debug("not last trading day of the month")  

My mistake, Matthieu is right! Your best bet is to use schedule_function with the date_rules.month_end() date rule.

Okay, I actually implemented the logic in the following way:

def initialize(context):  
    log.info("Init")  
    context.benchmark = symbol('SPY')  
    context.is_month_end = False  
    schedule_function(set_month_end,  
                      date_rule=date_rules.month_end(1),  
                      time_rule=time_rules.market_close())  
    schedule_function(rebalance,  
                      date_rule=date_rules.month_end(),  
                      time_rule=time_rules.market_close())


def set_month_end(context, data):  
    context.is_month_end = True  

def rebalance(context, data):  
    log.info("context.is_month_end = %s" % context.is_month_end)  
    # Your logic here  
    context.is_month_end = False  

def before_trading_start(context, data):  
    if context.is_month_end:  
        log.info("context.is_month_end = %s"  % context.is_month_end)

def handle_data(context, data):  
    if context.is_month_end:  
        log.info("context.is_month_end = %s" % context.is_month_end)  

context.is_month_end is set to True one day before month_end then set back to False after the rebalancing.
The code above results in the following logs:

2013-01-31before_trading_start:27INFOcontext.is_month_end = True  
2013-01-31handle_data:31INFOcontext.is_month_end = True  
2013-01-31rebalance:20INFOcontext.is_month_end = True  
2013-02-28before_trading_start:27INFOcontext.is_month_end = True  
2013-02-28handle_data:31INFOcontext.is_month_end = True  
2013-02-28rebalance:20INFOcontext.is_month_end = True  
2013-03-28before_trading_start:27INFOcontext.is_month_end = True  
2013-03-28handle_data:31INFOcontext.is_month_end = True  
2013-03-28rebalance:20INFOcontext.is_month_end = True  
[...]

Thanks for sharing. I added the "tools and tips" tag so that other people can find your code in the future.

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.