Using the correlation method we wrote for TimeSeries in P2, we want a function, calc_correlation , to
Question:
Using the correlation method we wrote for TimeSeries in P2, we want a function, calc_correlation, to calculate the correlation coefficient between the moving averages of any two time series.
def calc_correlation(a, b, n):
"""
Find the correlation of the moving averages of two time series
:param a: First series
:param b: Second series
:param n: Averaging period
:return: correlation coefficient (using scipy.stats.pearsonr)
"""
With calc_correlation we want to find the best-fit averaging period (i.e., the one showing the most correlation between two series). Wrote another function, find_best_correlation, to do that.
def find_best_correlation(a, b, rng = range(1, 30)):
"""
Find the highest correlated moving averages between a and b.
Uses calc_correlation to calculate correlation coefficient and
looks for max absolute value of correlations amongst
rng numbers.
:param a: First underlying series
:param b: Second underlying series
:param rng: Values for averaging periods to try (default range(1,30))
:return: Most correlated averaging period from rng
"""
Using the following time-series class, trim, wrote a backtest function:
class trim(TimeSeries):
def __init__(self, underlier, start=None, end=None):
name = 'trim(' + underlier.name + ', ' + \
str(start) + ', ' + str(end) + ')'
dates = underlier.get_dates(start=start, end=end)
data = {d:v for d,v in zip(dates, underlier.get_values(dates))}
super().__init__(name, unit=underlier.unit, data=data)
The backtest function is described below:
def back_test(a, b, split_date, rng):
"""
Backtest the best averaging period returned by find_best_correlation for a, b, rng.
:param a: First series to correlate
:param b: Second series to correlate
:param split_date: Date to split between training set and test set
:param rng: The various number of averaging days to try
:return: true if the most correlated averaging period in
the training set is the same as for the test set,
false otherwise
"""
Write the functions as described in the specification.
Additional information
p2_TimeSeries
Classes:
TimeSeries - class to hold a date/value series of data
Difference - a time series that is the difference between two other time
series
Fred - a time series that is based on a csv file downloaded from
fred.stlouis.org
dgs3mo - the 3-month treasury series from FRED
dgs10 - the 10-year treasury series from FRED
Functions:
recession_visual - plots a graphic visual showing the inverted yield curve
Dropbox link for P2_Timeseries
https://www.dropbox.com/scl/fo/esnpfktfxp7lowzysemx4/h?dl=0&rlkey=hujd4gh6lxyexqkhl0yq210xa
Income Tax Fundamentals 2013
ISBN: 9781285586618
31st Edition
Authors: Gerald E. Whittenburg, Martha Altus Buller, Steven L Gill