DaveL DaveL - 4 months ago 39
Python Question

Calculate stock returns in pandas DataFrame

I would like to calculate the annual performance (as change in market value) of these two firms whose data is stored in the dataframe below.

df = pd.DataFrame({'tic' : ['AAPL', 'AAPL', 'AAPL', 'GOOGL','GOOGL','GOOGL'],
'mktvalue' : [20,25,30,50,55,60],
'fyear' : [2014,2015,2016,2014,2015,2016]})


I have have seen a similar with solution a lambda function, but until now I couldn't adapt it to my data. I had a solution like this in mind to calculate the performance based on the year:

df['performance'] = df.fyear.apply(lambda x: (df.mktvalue[(df['fyear'] == 2014)]) /
(df.mktvalue[(df['fyear'] == 2013)]) if x == 2014
else (df.mktvalue[(df['fyear'] == 2013)]) /
(df.mktvalue[(df['fyear'] == 2013)])


One of my major problems was that in the implementation when calling

(df.mktvalue[(df['fyear'] == 2013)])


I received all of the market values of 2013 instead of only the corresponding one to this firm.

I would appreciate any help!

Answer

is that what you want?

In [129]: df['performance'] = df.groupby('tic').mktvalue.pct_change().fillna(0)

In [130]: df
Out[130]:
   fyear  mktvalue    tic  performance
0   2014        20   AAPL     0.000000
1   2015        25   AAPL     0.250000
2   2016        30   AAPL     0.200000
3   2014        50  GOOGL     0.000000
4   2015        55  GOOGL     0.100000
5   2016        60  GOOGL     0.090909