Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Track values

Example of track_val(context, var) to log current, average, high and low for a particular value.

Use, output and code:

    track_val(context, prices_list[stock][-1])

    ''' Out:  
    2015-04-01 track_val:49 INFO now 187.59  avg 226.49  lo 187.59  hi 284.09  
    2015-05-01 track_val:49 INFO now 225.96  avg 226.44  lo 187.59  hi 284.09  
    2015-06-01 track_val:49 INFO now 249.28  avg 228.20  lo 187.59  hi 284.09  
    2015-07-01 track_val:49 INFO now 269.14  avg 231.12  lo 187.59  hi 284.09  
    '''

def  track_val (c, var):  
    ''' Log current, average, high and low for a particular value.  
        Incoming 'c' for brevity is context  
    '''  
    if 'val' not in c:  
        c.val = {  
            'hi' : var,  
            'lo' : var,  
            'avg': [0, 0],  
        }  
    avg, num     = c.val['avg']  
    avg_new      = ((avg * num) + var) / (num + 1)  
    c.val['avg'] = [avg_new, num + 1]  
    if var > c.val['hi']: c.val['hi'] = var  
    if var < c.val['lo']: c.val['lo'] = var  
    log.info('now {}  avg {}  lo {}  hi {} '.format(  
        '%.2f' % var, '%.2f' % avg_new, '%.2f' % c.val['lo'], '%.2f' % c.val['hi']))  

See 'Source Code' tab for working examples.

1 response

Adding some logging control.

    track_values(context, <THE VARIABLE TO BE TRACKED> )

def track_values(c, var):  
    ''' Log current, average, high and low for a particular variable.  
        Incoming 'c' for brevity is context  
    '''  
    log_level = 1  #  0   Off  
                   #  1   Each new minimum or maximum  
                   #  2   Everything always  
    if 'val' not in c:  
        c.val = {  
            'hi' : var,  
            'lo' : var,  
            'avg': [0, 0],  
        }  
    avg, num     = c.val['avg']  
    avg_new      = ((avg * num) + var) / (num + 1)  
    c.val['avg'] = [avg_new, num + 1]  
    new_str = ''  
    if   var > c.val['hi']:  
        c.val['hi'] = var  
        new_str = 'new max'  
    elif var < c.val['lo']:  
        c.val['lo'] = var  
        new_str = 'new min'  
    if (log_level == 1 and new_str) or log_level == 2:  
        log.info('now {}  avg {}  lo {}  hi {}  {}'.format(  
        '%.2f' % var, '%.2f' % avg_new, '%.2f' % c.val['lo'], '%.2f' % c.val['hi'], new_str))