r"""Add a variable to the given dataframe. This is the core function for adding a variable to a dataframe. The default variable functions are already defined locally in ``alphapy.transforms``; however, you may want to define your own variable functions. If so, then the ``vfuncs`` pa
(f, v, vfuncs=None)
| 358 | # |
| 359 | |
| 360 | def vexec(f, v, vfuncs=None): |
| 361 | r"""Add a variable to the given dataframe. |
| 362 | |
| 363 | This is the core function for adding a variable to a dataframe. |
| 364 | The default variable functions are already defined locally |
| 365 | in ``alphapy.transforms``; however, you may want to define your |
| 366 | own variable functions. If so, then the ``vfuncs`` parameter |
| 367 | will contain the list of modules and functions to be imported |
| 368 | and applied by the ``vexec`` function. |
| 369 | |
| 370 | To write your own variable function, your function must have |
| 371 | a pandas *DataFrame* as an input parameter and must return |
| 372 | a pandas *DataFrame* with the new variable(s). |
| 373 | |
| 374 | Parameters |
| 375 | ---------- |
| 376 | f : pandas.DataFrame |
| 377 | Dataframe to contain the new variable. |
| 378 | v : str |
| 379 | Variable to add to the dataframe. |
| 380 | vfuncs : dict, optional |
| 381 | Dictionary of external modules and functions. |
| 382 | |
| 383 | Returns |
| 384 | ------- |
| 385 | f : pandas.DataFrame |
| 386 | Dataframe with the new variable. |
| 387 | |
| 388 | Other Parameters |
| 389 | ---------------- |
| 390 | Variable.variables : dict |
| 391 | Global dictionary of variables |
| 392 | |
| 393 | """ |
| 394 | vxlag, root, plist, lag = vparse(v) |
| 395 | logger.debug("vexec : %s", v) |
| 396 | logger.debug("vxlag : %s", vxlag) |
| 397 | logger.debug("root : %s", root) |
| 398 | logger.debug("plist : %s", plist) |
| 399 | logger.debug("lag : %s", lag) |
| 400 | if vxlag not in f.columns: |
| 401 | if root in Variable.variables: |
| 402 | logger.debug("Found variable %s: ", root) |
| 403 | vroot = Variable.variables[root] |
| 404 | expr = vroot.expr |
| 405 | expr_new = vsub(vxlag, expr) |
| 406 | estr = "%s" % expr_new |
| 407 | logger.debug("Expression: %s", estr) |
| 408 | # pandas eval |
| 409 | f[vxlag] = f.eval(estr) |
| 410 | else: |
| 411 | logger.debug("Did not find variable: %s", root) |
| 412 | # Must be a function call |
| 413 | func_name = root |
| 414 | # Convert the parameter list and prepend the data frame |
| 415 | newlist = [] |
| 416 | for p in plist: |
| 417 | try: |