Using Python from Analytica
New in Analytica 7.0
Requires the Analytica Developer edition.
Introduction
- Short overview
- Motivation (i.e., rich ecosystem, many libraries)
- Use cases
- Advantages of using python from within Analytica vs. plain python.
- Downsides: When it is better to stick with Analytica syntax (dependencies, array abstraction, MC, optimization).
Setting up a Python environment
- Very brief basics.
conda create -n MyEnv python=3.11- Configuring Python Environment or Model Environment sysvars in Analytica.
- Link to Setting up a Python environment for detailed info.
Importing Python modules and objects
The preferred way to make Python libraries available in Analytica is to place their import statements in the system variable PythonStartupCode. These lines execute when Python is loaded, so the libraries are ready for use in later Python expressions.
Note: If you edit PythonStartupCode after Python has already been loaded in the current Analytica model, you must reload the model (or close and reopen Analytica) for the modified startup code to take effect.
Python supports two main import styles:
- Module import – e.g.,
import numpy - Selective / wildcard import – e.g.,
from numpy import array, zerosorfrom numpy import *
When an import statement is the final expression in a Python block, Analytica returns its value:
| Import statement | Return value when it is the last statement | Output image |
|---|---|---|
import numpy as np, os
|
The module’s string representation e.g.,«Python <module 'numpy' from …>»«Python <module 'os' from …>»)
|
|
from numpy import array, zeros
|
A list of the imported names (alias names if provided, otherwise the original names) |
Python py:: namespace
Analytica exposes the embedded Python interpreter through the py:: namespace prefix. Any name visible at the top level of the interpreter—global variables, functions, classes, or imported modules—can be accessed through Analytica with the same spelling and case, preceded by py::.
Example: Incrementing a Python global variable counter by 2
py::counter := py::counter + 2;
Calling a Python function
Invoking a Python function from Analytica is as simple as writing it:
py::len(MyArray)
Arguments may be:
- Analytica scalars
- Analytica arrays (which get array abstracted)
- Python objects
Keyword Arguments (kwargs)
When a Python function accepts keyword arguments (**kwargs), use Analytica’s optional-parameter syntax, a colon after the parameter name, followed by the parameter value, instead of the equal sign used in Python.
py::my_func("arg1", kwarg1:1, kwarg2:"abc")
The equivalent call in native Python is:
my_func("arg1", kwarg1=1, kwarg2="abc")
Python print() function
The standard Python print() function sends its text output to the Analytica Typescript console window, just as it appears in a native Python console.
- When called from Analytica with
py::print(), the printed text will appear in the window. - When called inside a Python script executed by Analytica, any
print()statements also stream to the window.
Using Python classes
Using an existing Python class
To instantiate a Python class, call its constructor with the py:: prefix and pass any arguments exactly as you would in native Python.
py::MyClass(42, 'widgets')
Arrow Operator (->)
The arrow operator (->) lets you access the attributes and methods of a Python object, analogous to the dot operator (.) in Python:
ColNames := MyDf->columns{ attribute }Head5 := MyDf->head(5){ method }
You can chain these accesses and calls:
FirstName := MyDf->columns->tolist()
You can also assign through the arrow operator; the assignment will update the underlying Python object:
MyObj->value := 42
Using Python code in a definition
When you choose Python expr from the Definition drop-down, the node enters Python Expression mode, which passes the entire definition verbatim to the embedded Python interpreter.
Defining a UDF with a Python expr definition
When you set a Function node’s Definition to Python expr, you can write the entire body in Python. Analytica recompiles that code every time the function is evaluated, which can noticeably slow large array computations. To eliminate this overhead, place the code in a reusable Python Callable so the compiled version remains cached between calls.
Note: Inside Python expr, Analytica function parameters behave like local Python variables.
Callables
Callables let you embed full Python functions or classes directly inside Analytica, then invoke them like any other UDF.
Creating a Python Callable node
- Create a new Variable node.
- In the node’s Object window, change the Class dropdown from Variable to Callable.
- Enter your Python source in the Definition pane.
Writing Python Callable code
Use standard Python syntax to define a def function or a class inside the Definition pane of your Callable. For example:
def compound_interest(p, r, n):
return p * (1 + r) ** n
Caching compiled functions in Callables
When you evaluate a node, Analytica compiles your function and caches the resulting callable object as the node’s value. This differs from UDFs which cannot store a value, so they compile every time they run.
Parameters attribute
Callables do not have a Parameters attribute; all arguments are declared in your def or class signature.
Importing custom Python modules
Import modules exactly as you would in native Python. For example:
import myutils from mylib.finance import NPV
Ensure the module is on Python’s sys.path by appending the module's directory to the path. For additional guidance, see the official Python documentation on modules.
Dependencies
- The convenience of Analytica's dependencies.
- Drawing arrows to indicate dependence where Python doesn't track it.
- When dependencies are not tracked
Functions for evaluating Python code
Non-scalar data structures
- Distinction between Python data structures and Analytica data structures. How Python objects display in «...»
- Why to sometimes keep as python data structure w/o exploding
Converting from Python data to Analytica
- Automatic conversions (including list of types)
- PyExplode
- Basic usage. Nested usage.
- Include/exclude types
- Collections: np.array, dict, set/map, pandas data frame (documented on a separate library page), etc.
- Images & Figures, PIL.Image, matplotlib.figure.Figure
Converting from Analytica to Python data structures
Using Analytica locals from Python code
- When Analytica locals are visible to python code.
- Assignment to an Analytica local from python code.
Accessing Analytica objects from Python code
- Analytica module
- Get an Analytica object
- Evaluate a variable
- Analytica.eval(...) -- evaluate an analytica expression
- Call an Analytica function (?) -- Don't have something very direct here yet
Enable comment auto-refresher