Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

# st: calculate gains and losses from stock prices

 From Nadine R To statalist@hsphsun2.harvard.edu Subject st: calculate gains and losses from stock prices Date Tue, 5 Jul 2011 21:58:55 +0200

```Hello statalisters!

I have a timeseries of share prices and many people buying (purchase
P) and selling (sell S) shares. I want to calculate the accrued gains
and losses if someone who bought the share earlier sells it after a
while. My data looks like this (stata version 11.0):

shares    price               gain_loss
1                                                            1
1
2                             P                             1
10          1.2                0
3                                                            1
1.4                =10*(1.4-1.2)
4                             P                             1
20          1.6
=20*(1.6-1.6)+10*(1.6-1.2)
5                                                            1
1.5
=20*(1.5-1.6)+10*(1.5-1.2)
6                             S                             1
25          1.3
=10*(1.3-1.2)+15*(1.3-1.6)
7                                                            1
1.5                =5*(1.5-1.6)
8                            S                              1
15          1.4                =5*(1.4-1.6)
9                                                            1
1.6
10                                                          1
1.8
11                                                          1
1.6
12                          P                              1
10            1.7               =10*(1.7-1.7)
13                                                          1
1.5               =10*(1.5-1.7)
14                          S                              1
5             1.3               =5*(1.3-1.7)
1                                                            2

What I have written in the collum gain_loss is what Stata should
calculate: once a share is bought, following purchases accumulate and
gains/losses are calculated. If some shares are sold this happens by
the FIFO-method (shares first bought are first sold). It is only
possible to sell shares which were bought before (see day 8, where 15
shares are sold but only for 5 the gains/losses are calculated). On
day 8 there are zero shares in the portfolio and on day 12 all starts
from the beginning. If the first transaction a sell it should be
ignored as no shares were bought before. This happens for a timeseries
of person 1 and then for person 2 and so on... How can I let Stata
calculate theses gains and losses? With a kind of loop?