diff --git a/docs/conf.py b/docs/conf.py index 6e52b0e34..a7147a964 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -54,9 +54,9 @@ master_doc = "index" # General information about the project. -project = u"QLib" -copyright = u"Microsoft" -author = u"Microsoft" +project = "QLib" +copyright = "Microsoft" +author = "Microsoft" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -174,7 +174,7 @@ latex_elements = { # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, "qlib.tex", u"QLib Documentation", u"Microsoft", "manual"), + (master_doc, "qlib.tex", "QLib Documentation", "Microsoft", "manual"), ] @@ -182,7 +182,7 @@ latex_documents = [ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [(master_doc, "qlib", u"QLib Documentation", [author], 1)] +man_pages = [(master_doc, "qlib", "QLib Documentation", [author], 1)] # -- Options for Texinfo output ------------------------------------------- @@ -194,7 +194,7 @@ texinfo_documents = [ ( master_doc, "QLib", - u"QLib Documentation", + "QLib Documentation", author, "QLib", "One line description of project.", diff --git a/examples/benchmarks/TRA/src/model.py b/examples/benchmarks/TRA/src/model.py index f6ee69af3..cff94388e 100644 --- a/examples/benchmarks/TRA/src/model.py +++ b/examples/benchmarks/TRA/src/model.py @@ -130,7 +130,7 @@ class TRAModel(Model): if prob is not None: P = sinkhorn(-L, epsilon=0.01) # sample assignment matrix - lamb = self.lamb * (self.rho ** self.global_step) + lamb = self.lamb * (self.rho**self.global_step) reg = prob.log().mul(P).sum(dim=-1).mean() loss = loss - lamb * reg @@ -547,7 +547,7 @@ def evaluate(pred): score = pred.score label = pred.label diff = score - label - MSE = (diff ** 2).mean() + MSE = (diff**2).mean() MAE = (diff.abs()).mean() IC = score.corr(label) return {"MSE": MSE, "MAE": MAE, "IC": IC} diff --git a/examples/orderbook_data/example.py b/examples/orderbook_data/example.py index 3daa0a1ee..f8bd84ea7 100644 --- a/examples/orderbook_data/example.py +++ b/examples/orderbook_data/example.py @@ -21,7 +21,7 @@ class TestClass(unittest.TestCase): provider_uri = "~/.qlib/qlib_data/yahoo_cn_1min" qlib.init( provider_uri=provider_uri, - mem_cache_size_limit=1024 ** 3 * 2, + mem_cache_size_limit=1024**3 * 2, mem_cache_type="sizeof", kernels=1, expression_provider={"class": "LocalExpressionProvider", "kwargs": {"time2idx": False}}, diff --git a/qlib/contrib/data/processor.py b/qlib/contrib/data/processor.py index e8ea38870..875e9b531 100644 --- a/qlib/contrib/data/processor.py +++ b/qlib/contrib/data/processor.py @@ -59,10 +59,10 @@ class ConfigSectionProcessor(Processor): # Features cols = df_focus.columns[df_focus.columns.str.contains("^KLEN|^KLOW|^KUP")] - df_focus[cols] = df_focus[cols].apply(lambda x: x ** 0.25).groupby(level="datetime").apply(_feature_norm) + df_focus[cols] = df_focus[cols].apply(lambda x: x**0.25).groupby(level="datetime").apply(_feature_norm) cols = df_focus.columns[df_focus.columns.str.contains("^KLOW2|^KUP2")] - df_focus[cols] = df_focus[cols].apply(lambda x: x ** 0.5).groupby(level="datetime").apply(_feature_norm) + df_focus[cols] = df_focus[cols].apply(lambda x: x**0.5).groupby(level="datetime").apply(_feature_norm) _cols = [ "KMID", diff --git a/qlib/contrib/model/double_ensemble.py b/qlib/contrib/model/double_ensemble.py index 9ce005507..228997ba8 100644 --- a/qlib/contrib/model/double_ensemble.py +++ b/qlib/contrib/model/double_ensemble.py @@ -160,7 +160,7 @@ class DEnsembleModel(Model, FeatureInt): h_avg = h.groupby("bins")["h_value"].mean() weights = pd.Series(np.zeros(N, dtype=float)) for i_b, b in enumerate(h_avg.index): - weights[h["bins"] == b] = 1.0 / (self.decay ** k_th * h_avg[i_b] + 0.1) + weights[h["bins"] == b] = 1.0 / (self.decay**k_th * h_avg[i_b] + 0.1) return weights def feature_selection(self, df_train, loss_values): diff --git a/qlib/contrib/model/pytorch_adarnn.py b/qlib/contrib/model/pytorch_adarnn.py index b5700def6..bda115d83 100644 --- a/qlib/contrib/model/pytorch_adarnn.py +++ b/qlib/contrib/model/pytorch_adarnn.py @@ -682,9 +682,9 @@ class MMD_loss(nn.Module): if fix_sigma: bandwidth = fix_sigma else: - bandwidth = torch.sum(L2_distance.data) / (n_samples ** 2 - n_samples) + bandwidth = torch.sum(L2_distance.data) / (n_samples**2 - n_samples) bandwidth /= kernel_mul ** (kernel_num // 2) - bandwidth_list = [bandwidth * (kernel_mul ** i) for i in range(kernel_num)] + bandwidth_list = [bandwidth * (kernel_mul**i) for i in range(kernel_num)] kernel_val = [torch.exp(-L2_distance / bandwidth_temp) for bandwidth_temp in bandwidth_list] return sum(kernel_val) diff --git a/qlib/contrib/model/pytorch_tra.py b/qlib/contrib/model/pytorch_tra.py index 81c9ba145..5c7484c32 100644 --- a/qlib/contrib/model/pytorch_tra.py +++ b/qlib/contrib/model/pytorch_tra.py @@ -742,7 +742,7 @@ def evaluate(pred): score = pred.score label = pred.label diff = score - label - MSE = (diff ** 2).mean() + MSE = (diff**2).mean() MAE = (diff.abs()).mean() IC = score.corr(label, method="spearman") return {"MSE": MSE, "MAE": MAE, "IC": IC} diff --git a/qlib/contrib/model/pytorch_utils.py b/qlib/contrib/model/pytorch_utils.py index 224809dc2..eb35c383b 100644 --- a/qlib/contrib/model/pytorch_utils.py +++ b/qlib/contrib/model/pytorch_utils.py @@ -27,11 +27,11 @@ def count_parameters(models_or_parameters, unit="m"): counts = sum(v.numel() for v in models_or_parameters) unit = unit.lower() if unit in ("kb", "k"): - counts /= 2 ** 10 + counts /= 2**10 elif unit in ("mb", "m"): - counts /= 2 ** 20 + counts /= 2**20 elif unit in ("gb", "g"): - counts /= 2 ** 30 + counts /= 2**30 elif unit is not None: raise ValueError("Unknown unit: {:}".format(unit)) return counts diff --git a/qlib/contrib/model/tcn.py b/qlib/contrib/model/tcn.py index aa61bd44a..173404b2b 100644 --- a/qlib/contrib/model/tcn.py +++ b/qlib/contrib/model/tcn.py @@ -55,7 +55,7 @@ class TemporalConvNet(nn.Module): layers = [] num_levels = len(num_channels) for i in range(num_levels): - dilation_size = 2 ** i + dilation_size = 2**i in_channels = num_inputs if i == 0 else num_channels[i - 1] out_channels = num_channels[i] layers += [ diff --git a/qlib/contrib/strategy/optimizer/enhanced_indexing.py b/qlib/contrib/strategy/optimizer/enhanced_indexing.py index 9da609005..7e42856a2 100644 --- a/qlib/contrib/strategy/optimizer/enhanced_indexing.py +++ b/qlib/contrib/strategy/optimizer/enhanced_indexing.py @@ -125,7 +125,7 @@ class EnhancedIndexingOptimizer(BaseOptimizer): # objective ret = d @ r # excess return - risk = cp.quad_form(v, cov_b) + var_u @ (d ** 2) # tracking error + risk = cp.quad_form(v, cov_b) + var_u @ (d**2) # tracking error obj = cp.Maximize(ret - self.lamb * risk) # weight bounds diff --git a/qlib/contrib/strategy/signal_strategy.py b/qlib/contrib/strategy/signal_strategy.py index b0826b1ba..9d2b8124f 100644 --- a/qlib/contrib/strategy/signal_strategy.py +++ b/qlib/contrib/strategy/signal_strategy.py @@ -482,7 +482,7 @@ class EnhancedIndexingStrategy(WeightStrategyBase): r=score, F=factor_exp, cov_b=factor_cov, - var_u=specific_risk ** 2, + var_u=specific_risk**2, w0=cur_weight, wb=bench_weight, mfh=mask_force_hold, diff --git a/qlib/model/riskmodel/poet.py b/qlib/model/riskmodel/poet.py index 840384555..8946b2ac5 100644 --- a/qlib/model/riskmodel/poet.py +++ b/qlib/model/riskmodel/poet.py @@ -63,7 +63,7 @@ class POETCovEstimator(RiskModel): lamb = rate * self.thresh SuPCA = uhat.dot(uhat.T) / n SuDiag = np.diag(np.diag(SuPCA)) - R = np.linalg.inv(SuDiag ** 0.5).dot(SuPCA).dot(np.linalg.inv(SuDiag ** 0.5)) + R = np.linalg.inv(SuDiag**0.5).dot(SuPCA).dot(np.linalg.inv(SuDiag**0.5)) if self.thresh_method == self.THRESH_HARD: M = R * (np.abs(R) > lamb) @@ -78,7 +78,7 @@ class POETCovEstimator(RiskModel): M = M1 + M2 + M3 Rthresh = M - np.diag(np.diag(M)) + np.eye(p) - SigmaU = (SuDiag ** 0.5).dot(Rthresh).dot(SuDiag ** 0.5) + SigmaU = (SuDiag**0.5).dot(Rthresh).dot(SuDiag**0.5) SigmaY = SigmaU + Lowrank return SigmaY diff --git a/qlib/model/riskmodel/shrink.py b/qlib/model/riskmodel/shrink.py index 3cb2620d1..b2594f707 100644 --- a/qlib/model/riskmodel/shrink.py +++ b/qlib/model/riskmodel/shrink.py @@ -174,7 +174,7 @@ class ShrinkCovEstimator(RiskModel): alpha = A / B where `n`, `p` are the dim of observations and variables respectively. """ - trS2 = np.sum(S ** 2) + trS2 = np.sum(S**2) tr2S = np.trace(S) ** 2 n, p = X.shape @@ -192,8 +192,8 @@ class ShrinkCovEstimator(RiskModel): """ t, n = X.shape - y = X ** 2 - phi = np.sum(y.T.dot(y) / t - S ** 2) + y = X**2 + phi = np.sum(y.T.dot(y) / t - S**2) gamma = np.linalg.norm(S - F, "fro") ** 2 @@ -213,11 +213,11 @@ class ShrinkCovEstimator(RiskModel): sqrt_var = np.sqrt(var) r_bar = (np.sum(S / np.outer(sqrt_var, sqrt_var)) - n) / (n * (n - 1)) - y = X ** 2 - phi_mat = y.T.dot(y) / t - S ** 2 + y = X**2 + phi_mat = y.T.dot(y) / t - S**2 phi = np.sum(phi_mat) - theta_mat = (X ** 3).T.dot(X) / t - var[:, None] * S + theta_mat = (X**3).T.dot(X) / t - var[:, None] * S np.fill_diagonal(theta_mat, 0) rho = np.sum(np.diag(phi_mat)) + r_bar * np.sum(np.outer(1 / sqrt_var, sqrt_var) * theta_mat) @@ -239,16 +239,16 @@ class ShrinkCovEstimator(RiskModel): cov_mkt = np.asarray(X.T.dot(X_mkt) / len(X)) var_mkt = np.asarray(X_mkt.dot(X_mkt) / len(X)) - y = X ** 2 - phi = np.sum(y.T.dot(y)) / t - np.sum(S ** 2) + y = X**2 + phi = np.sum(y.T.dot(y)) / t - np.sum(S**2) - rdiag = np.sum(y ** 2) / t - np.sum(np.diag(S) ** 2) + rdiag = np.sum(y**2) / t - np.sum(np.diag(S) ** 2) z = X * X_mkt[:, None] v1 = y.T.dot(z) / t - cov_mkt[:, None] * S roff1 = np.sum(v1 * cov_mkt[:, None].T) / var_mkt - np.sum(np.diag(v1) * cov_mkt) / var_mkt v3 = z.T.dot(z) / t - var_mkt * S roff3 = ( - np.sum(v3 * np.outer(cov_mkt, cov_mkt)) / var_mkt ** 2 - np.sum(np.diag(v3) * cov_mkt ** 2) / var_mkt ** 2 + np.sum(v3 * np.outer(cov_mkt, cov_mkt)) / var_mkt**2 - np.sum(np.diag(v3) * cov_mkt**2) / var_mkt**2 ) roff = 2 * roff1 - roff3 rho = rdiag + roff diff --git a/qlib/workflow/record_temp.py b/qlib/workflow/record_temp.py index b78e421b1..e16121ffa 100644 --- a/qlib/workflow/record_temp.py +++ b/qlib/workflow/record_temp.py @@ -321,9 +321,9 @@ class SigAnaRecord(ACRecordTemp): metrics.update( { "Long-Short Ann Return": long_short_r.mean() * self.ann_scaler, - "Long-Short Ann Sharpe": long_short_r.mean() / long_short_r.std() * self.ann_scaler ** 0.5, + "Long-Short Ann Sharpe": long_short_r.mean() / long_short_r.std() * self.ann_scaler**0.5, "Long-Avg Ann Return": long_avg_r.mean() * self.ann_scaler, - "Long-Avg Ann Sharpe": long_avg_r.mean() / long_avg_r.std() * self.ann_scaler ** 0.5, + "Long-Avg Ann Sharpe": long_avg_r.mean() / long_avg_r.std() * self.ann_scaler**0.5, } ) objects.update(