(c) 2016 - present. Enplus Advisors, Inc.
This module uses:
import datetime as dt
import numpy as np
import pandas as pd
pd.set_option('precision', 2)
sp5_df = pd.read_csv(
'sp500.csv', usecols=['date', 'adj_close'],
parse_dates=['date'])
Exercise:
Create a pandas
Timestamp for January 1st, 1993 16:00 (don't worry about timezone).
pd.Timestamp('1993-01-01 16:00') # __
Timestamp('1993-01-01 16:00:00')
Exercise:
Generate a an Index of:
Hint: You can view the help for a function by running help(function_name)
, e.g. help(pd.Timestamp)
. Try looking at the help for pd.date_range
.
pd.date_range(start='2010-01-01', periods=5, freq='D') # __
DatetimeIndex(['2010-01-01', '2010-01-02', '2010-01-03', '2010-01-04', '2010-01-05'], dtype='datetime64[ns]', freq='D')
pd.date_range(start='2010-01-01', end='2010-01-15', freq='B') # __
DatetimeIndex(['2010-01-01', '2010-01-04', '2010-01-05', '2010-01-06', '2010-01-07', '2010-01-08', '2010-01-11', '2010-01-12', '2010-01-13', '2010-01-14', '2010-01-15'], dtype='datetime64[ns]', freq='B')
Exercise:
Create a Series named sp5
from the adj_close
column sp5_df
, using date
as the
index. Make sure you call sort_index()
to make sure the index is sorted.
Hint: The first two parameters of pd.Series
are data
and index
. When both data
and index
are Series
, the index
of data
is aligned against the values in Series
. You can always force positional alignment by converting a Series
to an PandasArray
(pd.Series.array
)
sp5 = pd.Series( # __
sp5_df.adj_close.array, index=sp5_df.date,
name='adj_close').sort_index()
Exercise:
Write 2 different ways to select January 3, 1995 from the sp5
series.
There are more than 2 ways to do this, but you only need 2!
d1a = sp5['19950103'] # __
d1b = sp5['1995-01-03'] # __
d1c = sp5[dt.datetime(1995, 1, 3)] # __
Exercise:
Select from sp5
all observations for:
mar_95 = sp5['1995-03'] # __
y_95 = sp5['1995'] # __
Exercise
For sp5
:
Calculate the day-over-day percent change in the values and to the variable sp5_rtn
.
Hint: Use shift
sp5_rtn = sp5 / sp5.shift(1) - 1 # __
# alternative solution
# sp5.pct_change()
Exercise
Resample the data from daily to monthly to calculate average 1-day returns.
rtn_mnth = sp5_rtn.resample('M').mean() # __