GitHub user ElonSabag created a discussion: A DataFusion window fixture for 
preserving both candles in a scan

Here’s a four-row DataFusion example for a scan that needs both the latest 
candle and the one before it. I ran it with the Python package for DataFusion 
55.0.0. The dates, symbols, and prices are fictional.

```python
from datafusion import SessionContext

ctx = SessionContext()
query = """
WITH bars(symbol, session, close, avg20) AS (
  VALUES ('DEMO1', '2025-01-02', 103, 100),
         ('DEMO1', '2025-01-03',  98, 100),
         ('DEMO2', '2025-01-02',  95, 100),
         ('DEMO2', '2025-01-03',  94, 100)
),
paired AS (
  SELECT *,
    LAG(close >= avg20) OVER (PARTITION BY symbol ORDER BY session) AS 
prev_above
  FROM bars
)
SELECT symbol FROM paired
WHERE session = '2025-01-03' AND close < avg20 AND prev_above
"""

def symbols(sql):
    return [row["symbol"] for batch in ctx.sql(sql).collect() for row in 
batch.to_pylist()]

early_filter = query.replace("FROM bars\n)", "FROM bars WHERE close < avg20\n)")
assert symbols(query) == ["DEMO1"]
assert symbols(early_filter) == []
print("Pair first:", symbols(query))
print("Filter below-average rows first:", symbols(early_filter))
```

The first query returns DEMO1. DEMO2 was already below its average. Moving 
`close < avg20` into the input of the window drops DEMO1's earlier candle, 
because that candle was above. The window then has no previous row for that 
symbol and the second query returns nothing. Pair the rows before filtering the 
crossing condition. [DataFusion window 
functions](https://datafusion.apache.org/user-guide/sql/window_functions.html)

I’m on the eStockes team. The free [Smart Scan 
demo](https://estockes.com/scan?utm_source=github&utm_medium=community&utm_campaign=datafusion_keep_previous_candle)
 has a fictional EXMPA result. Could you open it and tell me which row you’d 
lose if you kept only candles below their average? I’d like to know whether the 
comparison table makes that dependency clear.


GitHub link: https://github.com/apache/datafusion/discussions/27697

----
This is an automatically sent email for [email protected].
To unsubscribe, please send an email to: 
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to