def r_squared(returns, benchmark): """ measures the straight line fit of the equity curve """ # slope, intercept, r_val, p_val, std_err = _linregress( _, _, r_val, _, _ = _linregress( _utils._prepare_returns(returns), _utils._prepare_benchmark(benchmark, returns.index)) return r_val**2
def polynomial_fit(x, y, n): """ Returns a polynomial fit for y given x of order n with an R-squared score of the fit Parameters ----------- x : numpy array x data for polynomial fit. y : numpy array y data for polynomial fit. n : int order of the polynomial fit. Returns ---------- polynomial_coefficients : numpy polynomial List of polynomial coefficients R2 : float Polynomical fit coeffcient of determination """ try: x = np.array(x) except: pass try: y = np.array(y) except: pass assert isinstance(x, np.ndarray), 'x must be of type np.ndarray' assert isinstance(y, np.ndarray), 'y must be of type np.ndarray' assert isinstance(n, int), 'n must be of type int' # Get coeffcients of polynomial of order n polynomial_coefficients = np.poly1d(np.polyfit(x, y, n)) # Calculate the coeffcient of determination slope, intercept, r_value, p_value, std_err = _linregress(y, polynomial_coefficients(x)) R2 = r_value**2 return polynomial_coefficients, R2