Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
A bug in the code
#1
Dear Python Users,

I am trying to find annual return of S&P500 given monthly prices. I have the following code below. The problem is that I receive empty (Nan) observations. Can you please point at the mistakes that I am making? I attach csv file to this post.

import pandas as pd
import numpy as np
from datetime import datetime

sp_500=pd.DataFrame(pd.read_csv("sp500_historical.csv"))
sp_500['date'] = pd.to_datetime(sp_500['date'])

logret = np.log(sp_500['Close'] / sp_500['Close'].shift(1))
date=[]
d0=sp_500.date
for i in range(0,len(logret)):
    date.append(d0[i].strftime("%Y"))
y=pd.DataFrame(logret,date,columns=['ret_annual'])
ret_annual=np.exp(y.groupby(y.index).sum())-1

ret_annual.head()

Attached Files

.csv   sp500_historical.csv (Size: 20.24 KB / Downloads: 51)
Reply


Messages In This Thread
A bug in the code - by Alberto - Feb-11-2018, 11:21 PM
RE: A bug in the code - by Larz60+ - Feb-11-2018, 11:37 PM
RE: A bug in the code - by Alberto - Feb-11-2018, 11:41 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020