Evaluation of math formula in Python (with custom variable names and subscripts)
Question: I need to evaluate a bunch of math formulas (string format) for a time series
for example:

    
    
    " y = 0.5 * gdp[t] + 0.2 * ln( sp500[t-2] ) "
    

The math formula has two elements I need to take care of:

  * Custom variable names (e.g. `gdp`) that refer to a time series / array
  * Variable subscripts to denote indices such as `t-1` or `t-2` for a time series

Does anyone have an relatively robust/efficient way to evaluate this formula
to a number for a given input (i.e. such as t = 5). Ideally a fast approach
but that is a luxury item.


Answer: I'm not sure how you want to use `gdp` and `sp500`, but this is an example
with `eval` to get you started:

    
    
    import math
    
    s = "0.5 * gdp[t] + 0.2 * ln( sp500[t-2] ) "
    gdp = [0,1,2,3,4,5]
    sp500 = [0,1,2,3,4,5]
    t = 5
    ln = lambda x: math.log(x)
    
    y = eval(s)
    print y # prints 2.71972245773
    

