I have a MySQL table (version 8.0.26) with stock prices and want to calculate the log price change for future analysis. Here's my table and data.
CREATE TABLE `prices` (
`ticker` varchar(7) NOT NULL,
`date` datetime NOT NULL,
`price` double DEFAULT NULL,
PRIMARY KEY (`ticker`,`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
INSERT INTO `sandbox`.`prices` (`ticker`, `date`, `price`) VALUES ('A', '2021-01-01', '10');
INSERT INTO `sandbox`.`prices` (`ticker`, `date`, `price`) VALUES ('A', '2021-01-02', '10.1');
INSERT INTO `sandbox`.`prices` (`ticker`, `date`, `price`) VALUES ('A', '2021-01-03', '11');
INSERT INTO `sandbox`.`prices` (`ticker`, `date`, `price`) VALUES ('B', '2021-01-01', '50');
INSERT INTO `sandbox`.`prices` (`ticker`, `date`, `price`) VALUES ('B', '2021-01-02', '51.5');
INSERT INTO `sandbox`.`prices` (`ticker`, `date`, `price`) VALUES ('B', '2021-01-03', '49');
I can write this query but the column isn't saved.
SELECT *, LN(price / lag(price, 1) OVER (PARTITION BY ticker)) AS ln_open_return FROM sandbox.prices;
I put together this code from these answers but I'm still getting a "1064 syntax error: 'WITH' is not valid at this position. Expecting an expression."
ALTER TABLE sandbox.prices
ADD COLUMN ln_change DOUBLE AS (
WITH temp AS (
SELECT
*,
LAG(price, 1) OVER(PARTITION BY ticker ORDER BY date) AS prior
FROM sandbox.prices
)
SELECT
*,
COALESCE(LN(price / prior)) AS ln_change
FROM temp) PERSISTED;