Hello. I'd like to calculate the yield by date with Python. I'd like to know how to calculate the yield after fixing a specific date.
Assuming that there is daily stock price data from 1983 to 2010, I want to calculate the return on a specific date after fixing the end of the month, but I don't know how to implement it.
What I want to ask is, for example, to fix the price 29.29 at the end of March and then get the whole price and the yield for April. April 4th will be 29.44/29.29-1
and April 5th will be 29.71/29.29-1
, and I want to repeat this process over all months to get a return.
resample(rule = 'M').If you do last()
, the date and price of each month are obtained, but I'm asking you because I don't think this approach is right. I also looked at datetime and datarange, and the function above does not seem to fit the calculation of the return I want to implement.
import pandas as pd
# # In[2]:
s = '1983-03-30 29.4 1983-03-31 29.29 1983-04-04 29.44 1983-04-05 29.71 1983-04-06 29.44 1983-04-07 29.71 1983-04-08 29.92 1983-04-11 30.17 1983-04-12 30.38 1983-04-13 30.26 1983-04-14 30.83 1983-04-15 30.82 1983-04-18 30.67 1983-04-19 30.48 1983-04-20 30.75 1983-04-21 30.75 1983-04-22 30.7 1983-04-25 30.68 1983-04-26 30.75 1983-04-27 30.84 1983-04-28 30.71 1983-04-29 30.78 1983-05-02 30.74 1983-05-03 30.63'
d = s.split()
df = pd.DataFrame({ "date":d[::2], "wti":d[1::2]})
# # In[3]:
df.tail()
# # In[4]:
df['date_period'] = pd.to_datetime(df.date).dt.to_period('D')
df['month_period'] = pd.to_datetime(df.date).dt.to_period('M')
df.wti = df.wti.astype(float)
df.set_index('date_period', inplace=True)
# # In[5]:
df.head()
# # In[6]:
df.info()
# # In[7]:
lasts = df.resample('M').last()
lasts
# # In[8]:
lasts.drop(columns=['date', 'month_period'], inplace=True)
lasts = lasts.shift(periods=1)
lasts.index.name = 'month_period'
lasts.columns = [ 'wti_last']
# # In[9]:
lasts
# # In[10]:
lasts = lasts.reset_index()
df = df.merge(lasts)
df.drop(columns=['month_period'], inplace=True)
# # In[11]:
df.head(10)
# # In[12]:
df['Yield from the end of last month'] = df.wti/df.wti_last - 1
# # In[13]:
df
It's complicated to operate datetime, period type, etc.
Looking at the picture... I think the data is in Excel. If it were me...
For example... If you're talking about the entire month of April 1983 Use the for statement to find a key that meets the conditions in the dictionary (key date, value is price)
The conditional statement would be as follows
date = '1983-04-04'
if date[0:7]=='1983-04':
print("t")
After that, you can take the value of the key and calculate itYo
© 2024 OneMinuteCode. All rights reserved.