I'm gonna get straight to the problem:

Image dividend reinvestment as this scenario:

  • You buy 10 shares of AAPL on 2018-01-01 for $10

  • -- AAPL pays $1 / per share dividend on 2018-02-01 -> you get $10 CASH

    • This CASH is automatically reinvested into shares: 1 AAPL share costs $20 on 2018-02-01 -> shares_per_dividend = $1 (dividend amount) / 20 (AAPL price_per_share) = 0.05 -> you get + 0.5 shares calculated as: 10 (cash from dividends) * 0.05 (shares_per_dividend)
    • Now you have 10 (initial shares) + 0.5 (new shares) = 10.5 shares
  • -- AAPL pays $1 / per share dividend on 2018-03-01 (month after first dividend) -> now you get $10.5 cash as you have 10.5 shares of AAPL

    • For the sake of simplicity AAPL again costs $20 on 2018-03-01 so you automatically buy 10.5 * shares_per_dividend (0.05) = 0.525 new shares -> now you have 10.5 + 0.525 = 11.025 shares

This could go on and on... The point is, after every paid dividend I want to add "CASH-BOUGHT" shares to initial shares, and then on next dividend date I want to multiply shares_per_dividend by current amount of owned shares (eg. 10.5 mentioned above)

Hope I expressed myself right :)

I would write query similar to this using window function, but it does not take current shares in account.

SELECT shares + shares * SUM(shares_per_dividend) OVER(PARTITION BY stock_symbol ORDER BY dividend_date ASC) as current_shares
FROM some_table;

shares_per_dividend is NULL if no dividend was paid on that day.

example of calculations: example of correct calculations

the final result should look like this: enter image description here

  • 10 + 10x0.05 is 10x(1+0.05) and 10.5 + 10.5x0.05 is 10.5x(1+0.05) with is then also 10x(1+0.05)x(1+0.05) since your 10.5 came as result of computation of previous step, and then all later steps are derived in the same way... so 10x(1.05)^3, 10x(1.05)^4, etc. – Patrick Mevzek Mar 25 '19 at 17:14
  • Patrik Mevzek - thanks for suggestion but shares_per_dividend could be any other value each time dividend is paid. It depends on closing price of that company on that very day. – Martin Galovic Mar 26 '19 at 9:44
  • You will get more / better answers if you post your CREATE TABLE statement and some input data so people can experiment with your problem easier. – filiprem Mar 26 '19 at 9:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.