Alpaca's brokerage ledger needs a chronological cash-balance view for each account. Write a PostgreSQL query that uses a CTE to aggregate settled cash movements by account and date, then uses a correlated subquery and window function to calculate running balances.
daily_net_change, treating NULL amounts as zero.running_cash_balance in date order for each account.account_id and movement_date.| Column | Type | Description |
|---|---|---|
| account_idPK | VARCHAR(20) | Alpaca brokerage account identifier |
| initial_cash_balance | NUMERIC(12,2) | Cash balance before the reporting period |
| Column | Type | Description |
|---|---|---|
| movement_idPK | INT | Unique cash movement identifier |
| account_id | VARCHAR(20) | Account associated with the movement |
| movement_date | DATE | Settlement date of the movement |
| amount | NUMERIC(12,2) | Signed cash movement amount |
| status | VARCHAR(20) | Processing status of the movement |