deephaven / deephaven-docs-community

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

Question: example of ATR (average true range) #315

Closed margaretkennedy closed 1 month ago

margaretkennedy commented 1 month ago

Does Deephaven have a built-in ATR? No, but you can accomplish with code like:

from deephaven import time_table, agg, updateby
from deephaven.calendar import calendar

cal = nyse_cal = calendar("USNYSE_EXAMPLE")

trades = (
    time_table("PT00:00:01", "2024-09-01T00:00 ET")
    .update([
        "Date = formatDate(Timestamp, 'ET')", 
        "Sym = ii%2 == 0 ? `COS` : `SIN`", 
        "Price = ii%2 == 0 ? cos(0.000001*ii) : sin(0.0000001*ii)",
        ])
    .where("cal.isBusinessDay(Date)")
    )

# See https://www.investopedia.com/terms/a/atr.asp

data = (
    trades.agg_by([
        agg.first("Open=Price"),
        agg.last("Close=Price"),
        agg.max_("High=Price"),
        agg.min_("Low=Price")
    ], by=["Date", "Sym"])
)

data = (
    data
    .update("PriorBusDay = cal.plusBusinessDays(Date, -1)")
    .natural_join(data, on=["PriorBusDay=Date", "Sym"], joins="ClosePrior=Close")
    .where("!isNull(ClosePrior)")
    .update("TR = max(High-Low, abs(High-ClosePrior), abs(Low-ClosePrior))")
    .update_by([updateby.rolling_avg_tick("ATR=TR", rev_ticks=14)], by=["Sym"])
)