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.