Write Python in Deephaven
Using Deephaven from within Python is very easy. Let’s dive in.
First Python Query
After creating and connecting to a Python console session, you can run your first query.
def total_dollars(a,b):
return a*b
t = db.t("LearnDeephaven", "StockTrades") \
.where("inRange(Date, `2017-08-22`,`2017-08-24`)") \
.view("Date", "Timestamp", "Sym", "Price=Last", "Size", "Dollars=Price*Size") \
.update("TotalDollars=(double)total_dollars.call(Price,Size)", "SqrtDollars=sqrt(TotalDollars)")
Deephaven’s Query Language reads like English, so you can probably guess what the query does, even if you have never used Deephaven before.
- "def" is the Python keyword to define a function.
- The StockTrades table is loaded from the LearnDeephaven namespace.
- Dates between 2017-08-22 and 2017-08-24 are selected.
- A table is created containing only the Date, Timestamp, Sym, and Size columns from the prior table. Additionally, the Last column is added and renamed to Price. Finally, a new column, Dollars, is added, which is the product of Price and Size.
- A new table is created with two new columns: TotalDollars and SqrtDollars. TotalDollars is computed by applying the total_dollars Python function, and SqrtDollars is computed by applying the built-in sqrt function.
Tip
If you have a real-time table, simply switch db.t
for db.i
in order to access the dynamic table.
If you're new to Python, note that \ indicates a line continuation in Python and is necessary for the console to interpret your query correctly. Standard Python indentation is four whitespaces (preferred over tabs).
Deephaven Modules
Deephaven's Python module is extensive and provides functionality to create tables, save tables, plot, work with Pandas, etc. These modules can be made available by importing them in your query, and you can refer to the PyDocs to see all the Deephaven Python modules.
In this example, the emptyTable
and merge
functions are imported from the deephaven.TableTools
module. emptyTable
is used to create two tables with 5 rows. merge
is then used to stack tables t1 and t2 into a 10-row table containing the contents of both input tables.
from deephaven.TableTools import emptyTable, merge
t1 = emptyTable(5).update("X=i")
t2 = emptyTable(5).update("X=i*i")
t3 = merge(t1, t2)
For more details see Deephaven's Python API documentation and Deephaven's Java documentation.