0

I have a data frame consisting of thousands of stock quotes, ordered by symbol(tic) and Date.

    Date    tic    prccd
0   1-1-20  AAPL    4.00
1   2-1-20  AAPL    4.10
2   3-1-20  AAPL    4.12
3   1-1-20  MSFT    6.00
4   2-1-20  MSFT    6.15
5   3-1-20  MSFT    6.10

With

stocks_data['log_return'] = np.log(1 + stocks_data.groupby('tic')['prccd'].pct_change())

I aim to get the logarithmic daily return of these stocks. Does the numpy function acknowledge the groupby tic operation?

1
  • 1
    numpy dose not know the groupby., Commented Aug 16, 2020 at 16:28

1 Answer 1

2

To calculate daily log returns per tic group use:

stocks_data['log_return'] = df.groupby('tic').prccd.transform(lambda x: np.log(x) - np.log(x.shift(1)))

or equivalent formula:

stocks_data['log_return'] = df.groupby('tic').prccd.transform(lambda x: np.log(x / x.shift(1)))

result:

     Date   tic  prccd  log_return
0  1-1-20  AAPL   4.00         NaN
1  2-1-20  AAPL   4.10    0.024693
2  3-1-20  AAPL   4.12    0.004866
3  1-1-20  MSFT   6.00         NaN
4  2-1-20  MSFT   6.15    0.024693
5  3-1-20  MSFT   6.10   -0.008163
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I just did it with your formula and the results are actually the same

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.