I need to get the % change in price of a stock for the dates when the company have dividend exdates.
I have these two tables:
Table 1: Get the prices
select *
from prices_table
where ticker = 'AAPL-US'
order by date desc
Table 2: Get the dividends
select *
from dividends
where ticker = 'AAPL-US'
order by exdate desc
The dates in the prices table are daily (trading dates) while the dividends table only have rows for dates with dividend exdates.
prices table
| Date | Ticker | Prices |
|---|---|---|
| 20240312 | AAPL-US | 172.75 |
| 20240311 | AAPL-US | 170.73 |
| 20240309 | AAPL-US | 169 |
dividends table
| Exdate | Ticker |
|---|---|
| 20240209 | AAPL-US |
| 20231110 | AAPL-US |
| 20230811 | AAPL-US |
I tried the below script using lag() however, the issue is instead of getting the price for the previous trading day before the dividend exdate, it gets the price for the previous exdate:
select
a.ticker
, a.date
, price as current_price
, lag(price, 1) over(order by date asc) as previous_price
, round(((price - (lag(price, 1) over(order by date asc))) /
(lag(price, 1) over(order by date asc)) * 100),2) as pct_chg
from price a
join dividends b on a.ticker = b.ticker
and (a.date = b.exdate)
where a.ticker = 'AAPL-US'
order by a.date desc`
data i am expecting:
| ticker | date | current price | previous_price | pct_chg |
|---|---|---|---|---|
| AAPL-US | 20240209 | 188.85 | 188.32 | 0.28 |
May you please help me with what should I tweak with my script?