def rolling_regress_1(y, x, window=5): try: rolling_ys = rolling_windows(y, window) rolling_xs = rolling_windows(x, window) except Exception as e: print('debug') bet = pd.Series() # enumerate 形成带 i 的一个迭代器 for i, (rolling_x, rolling_y) in enumerate(zip(rolling_xs, rolling_ys)): tmp_index = y.index[i + window - 1] try: model = sm.OLS(rolling_y, rolling_x) result = model.fit() params = result.params b_v = params[0] # print(result.params) # print(result.summary()) except: print(i) raise b = pd.Series(index=[tmp_index], data=b_v) bet = pd.concat([bet, b]) return bet
def __init__(self, y, x=None, window=None, has_const=False, use_const=True): self.x, self.y, self.k = _clean_xy(y=y, x=x, has_const=has_const, use_const=use_const) self.window = self.n = window self.xwins = utils.rolling_windows(self.x, window=window) self.ywins = utils.rolling_windows(self.y, window=window) self.solution = _rolling_lstsq(self.xwins, self.ywins) self.has_const = has_const self.use_const = use_const
def __init__(self, y, x=None, window=None, hasconst=False, names=None): if window is None: raise ValueError('must specify `window`') OLS.__init__(self, y=y, x=x, hasconst=hasconst, names=names) self.xwins = utils.rolling_windows(self.x, window=window) self.ywins = utils.rolling_windows(self.y, window=window) # TODO: iterator? self.models = [ OLS(y=ywin, x=xwin) for ywin, xwin in zip(self.ywins, self.xwins) ]
def __init__(self, r, proxies, window, sumto=1.): self.r = r self.proxies = proxies self.window = int(window) self.sumto = sumto self.newidx = r.index[window - 1:] self.cols = proxies.columns self.n = proxies.shape[1] # TODO: constrain self._r = utils.rolling_windows(r, window=window) self._proxies = utils.rolling_windows(proxies, window=window)
def _wrap_multidx(self, stat, name=None): if name is None: name = stat[1:] outer = np.repeat(self.ridx, self.window) inner = np.ravel(utils.rolling_windows(self.index.values, window=self.window)) return Series(getattr(self, stat).flatten(), index=[outer, inner], name=name).rename_axis(['end', 'subperiod'])
def _rolling_regress(self, y, x, window=5, half_life=None, intercept=True, verbose=False, fill_na=0): fill_args = {'method': fill_na} if isinstance(fill_na, str) else {'value': fill_na} x, y = self._align(x, y) stocks = y.columns if half_life: weight = self._get_exp_weight(window, half_life) else: weight = 1 start_idx = x.loc[pd.notnull(x).values.flatten()].index[0] x, y = x.loc[start_idx:], y.loc[start_idx:,:] rolling_ys = rolling_windows(y, window) rolling_xs = rolling_windows(x, window) beta = pd.DataFrame() alpha = pd.DataFrame() sigma = pd.DataFrame() for i, (rolling_x, rolling_y) in enumerate(zip(rolling_xs, rolling_ys)): rolling_y = pd.DataFrame(rolling_y, columns=y.columns, index=y.index[i:i+window]) window_sdate, window_edate = rolling_y.index[0], rolling_y.index[-1] stks_to_regress = sorted(set(self._get_codes_listed(stocks, window_sdate)) & \ set(self._get_codes_not_delisted(stocks, window_edate))) rolling_y = rolling_y[stks_to_regress].fillna(**fill_args) try: b, a, resid = self._regress(rolling_y.values, rolling_x, intercept=True, weight=weight, verbose=True) except: print(i) raise vol = np.std(resid, axis=0) vol.index = a.index = b.columns = stks_to_regress b.index = [window_edate] vol.name = a.name = window_edate beta = pd.concat([beta, b], axis=0) alpha = pd.concat([alpha, a], axis=1) sigma = pd.concat([sigma, vol], axis=1) beta = beta.T beta = beta.reindex(y.index, axis=1).reindex(y.columns, axis=0) alpha = alpha.reindex(y.index, axis=1).reindex(y.columns, axis=0) sigma = sigma.reindex(y.index, axis=1).reindex(y.columns, axis=0) return beta, alpha, sigma
def REVSU(self): netprofit = self.totaloperatingrevenueps # 得到单季度的数据。 sig_season_va = get_signal_season_value(netprofit) cols = pd.DataFrame([i for i in sig_season_va.columns]) revsu = pd.DataFrame() rolling_cols = rolling_windows(cols, 6) for roll in rolling_cols: res = _calculate_su_simple(sig_season_va[roll]) res = pd.DataFrame(res.values, index=res.index, columns=[roll[-1]]) revsu = pd.concat([revsu, res], axis=1) revsu.dropna(how='all', axis=0, inplace=True) revsu = adjust_months(revsu) revsu = append_df(revsu) return revsu
def SUE(self): # 使用原始的财务数据 eps = self.basiceps # 得到单季度的数据。 sig_season_va = get_signal_season_value(eps) cols = pd.DataFrame([i for i in sig_season_va.columns]) sue = pd.DataFrame() rolling_cols = rolling_windows(cols, 6) for roll in rolling_cols: res = _calculate_su_simple(sig_season_va[roll]) res = pd.DataFrame(res.values, index=res.index, columns=[roll[-1]]) sue = pd.concat([sue, res], axis=1) sue.dropna(how='all', axis=0, inplace=True) sue = adjust_months(sue) sue = append_df(sue) return sue
def test__rolling_lstsq(x, y, window, out): xwins = utils.rolling_windows(x, window) ywins = utils.rolling_windows(y, window) assert np.allclose(ols._rolling_lstsq(xwins, ywins), out)