deephaven / deephaven-docs-community

Source code for Community docs on the deephaven.io website.
Apache License 2.0
0 stars 5 forks source link

Object oriented vs table oriented table guide #161

Open margaretkennedy opened 5 months ago

margaretkennedy commented 5 months ago

Let me give you an example to help you think about usage. Your example code above is an object-oriented approach. DH is inherently a table-oriented approach. As such, you want to think in terms of tables instead of classes. Here is some example code that is fully table oriented.

import random
from deephaven import time_table, updateby as uby

# Set up a price feed

last_price = {"A" : 100.0, "B": 200.0}

def price_generator(sym: str) -> float:
    p = last_price[sym]
    p += (random.random()-0.5)
    # p = lognormvariate(p, 0.0)
    last_price["sym"] = p
    return p

prices = time_table("PT00:00:00.1") \
    .update([
        "Sym = ii%2==0 ? `A` : `B`", 
        "Price = price_generator(Sym)",
    ])

# Set up a trade feed

trades = time_table("PT00:00:01") \
    .update([
        "Sym = ii%2==0 ? `A` : `B`", 
        "Size = randomInt(-1000, 1000)",
        "Direction = Size > 0 ? `LONG` : `SHORT`",
        ]) \
    .aj(prices, ["Sym", "Timestamp"], ["Price"])

# Compute portfolio views -- these could also be feeds

portfolio_hist = trades.update_by([uby.cum_sum("Size")], "Sym")

portfolio = portfolio_hist.drop_columns("Direction").last_by("Sym")

# Do some trade analysis

analysis = trades \
    .aj(
        prices.update_view(["FutureTimestamp=Timestamp", "Timestamp=Timestamp-'PT00:01:00'"]), 
        ["Sym", "Timestamp"], ["FuturePrice=Price"] \
        ) \
    .update_view("PriceChange = FuturePrice-Price") 

Note that here, key concepts are represented as tables instead of classes. For example:

When generating a trading system with simulated or real trading, you need to think through the relationships of tables. Which are the key inputs. Of those key inputs, which will be simulated by replaying raw data (e.g. prices)? Which will be simulated otherwise (e.g. trades)? A few years ago, I had an intern create these articles which may be helpful in you thinking through this. Any code examples are way out of date, but the concepts should be there. https://medium.com/@deephavendatalabs/automated-trading-with-deephaven-part-1-7eaacf44be2f https://medium.com/@deephavendatalabs/automated-trading-with-deephaven-part-2-ad2a944eef10