Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Generate a report at the end of backtest

Example of a way to log some information just at the end of a run in the IDE.

This log_info function being used can be replaced with any logging. Here's the general idea in this case at the end of the run:

2018-07-23 12:59 log_info:189 INFO Rows: 200  Columns: 4  
                     min       mean        max  
        alpha        1.0      100.5      200.0  
       sector        101     213.36        311  
          pnl      -6179      60.97       8280  
pnl_per_alpha       -875      -2.32        827

    ....

2018-07-23 12:59 log_info:205 INFO _ _ _   pnl_per_alpha   _ _ _  
    ... pnl_per_alpha highs  
                      alpha  sector   pnl  pnl_per_alpha  
Equity(8461 [CHK])      1.0     309   827            827  
Equity(40430 [GM])      2.0     102   758            379  
Equity(39840 [TSLA])    4.0     102  1352            338  
Equity(161 [AEP])       5.0     207  1166            233  
Equity(216 [HES])       7.0     309  1357            193  
Equity(24778 [SRE])     6.0     207  1130            188  
Equity(23709 [NFLX])   20.0     102  3420            171  
Equity(2127 [DE])      12.0     310  1836            153  
    ... pnl_per_alpha lows  
                      alpha  sector   pnl  pnl_per_alpha  
Equity(24124 [WYNN])   26.0     102 -3509           -134  
Equity(20940 [UPS])    22.0     310 -2963           -134  
Equity(34525 [MELI])   28.0     102 -4070           -145  
Equity(51231 [ROKU])   24.0     308 -3778           -157  
Equity(34440 [CXO])    11.0     309 -2208           -200  
Equity(49610 [SQ])     29.0     311 -6179           -213  
Equity(25006 [JPM])    10.0     ...  

The heart of it:

def initialize(context):  
    context.last_day = get_environment('end').date()  
    context.report_mode = 'strict'  # strict for minute 390, anything else for minute 389 (faster)

    if context.report_mode == 'strict':  
        for i in range(1, 391):   # 391 to include 390  
            schedule_function(report, date_rules.every_day(), time_rules.market_open(minutes=i))  
    else:  
        # This is more efficient, not requiring the check for which minute in report(),  
        #   just that market_close is minute 389 instead of 390. But this will also catch half days?  
        # For most uses, this is probably ok.  
        schedule_function(report, date_rules.every_day(), time_rules.market_close())

def report(context, data):  
    ''' Logging at the end of the run '''

    # Check for last day.  
    if get_datetime().date() != get_environment('end').date():  
        return

    ... etc ...