instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Add docstrings to improve code quality
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. class Reweighter: def __init__(self, *args, **kwargs): raise NotImplementedError() def reweight(self, data: object) -> object: raise NotImplementedError(f"This type of input is not supported")
--- +++ @@ -4,7 +4,24 @@ class Reweighter: def __init__(self, *args, **kwargs): + """ + To initialize the Reweighter, users should provide specific methods to let reweighter do the reweighting (such as sample-wise, rule-based). + """ raise NotImplementedError() def reweight(s...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/dataset/weight.py
Generate docstrings for this script
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from abc import abstractmethod import pandas as pd class BaseIntradayBacktestData: @abstractmethod def __repr__(self) -> str: raise NotImplementedError @abstractmethod def __len__(se...
--- +++ @@ -8,6 +8,12 @@ class BaseIntradayBacktestData: + """ + Raw market data that is often used in backtesting (thus called BacktestData). + + Base class for all types of backtest data. Currently, each type of simulator has its corresponding backtest + data type. + """ @abstractmethod ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/data/base.py
Include argument descriptions in docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import logging import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error from typing import Dict, Text, Any from ...contrib.eva.alpha import calc_ic from ...workflow.record_temp import RecordTemp from ...workflow.re...
--- +++ @@ -17,6 +17,10 @@ class MultiSegRecord(RecordTemp): + """ + This is the multiple segments signal record class that generates the signal prediction. + This class inherits the ``RecordTemp`` class. + """ def __init__(self, model, dataset, recorder=None): super().__init__(recorder=...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/workflow/record_temp.py
Generate descriptive docstrings automatically
import numpy as np from qlib.model.riskmodel import RiskModel class POETCovEstimator(RiskModel): THRESH_SOFT = "soft" THRESH_HARD = "hard" THRESH_SCAD = "scad" def __init__(self, num_factors: int = 0, thresh: float = 1.0, thresh_method: str = "soft", **kwargs): super().__init__(**kwargs) ...
--- +++ @@ -4,12 +4,29 @@ class POETCovEstimator(RiskModel): + """Principal Orthogonal Complement Thresholding Estimator (POET) + + Reference: + [1] Fan, J., Liao, Y., & Mincheva, M. (2013). Large covariance estimation by thresholding principal orthogonal complements. + Journal of the Royal ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/riskmodel/poet.py
Document helper functions with docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import inspect import numpy as np import pandas as pd from typing import Union from qlib.model.base import BaseModel class RiskModel(BaseModel): MASK_NAN = "mask" FILL_NAN = "fill" IGNORE_NAN = "ignore" def __init__(self, nan...
--- +++ @@ -10,12 +10,22 @@ class RiskModel(BaseModel): + """Risk Model + + A risk model is used to estimate the covariance matrix of stock returns. + """ MASK_NAN = "mask" FILL_NAN = "fill" IGNORE_NAN = "ignore" def __init__(self, nan_option: str = "ignore", assume_centered: bool =...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/riskmodel/base.py
Add docstrings to improve code quality
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from qlib.model.ens.ensemble import Ensemble, RollingEnsemble from typing import Callable from joblib import Parallel, delayed class Group: def __init__(self, group_func=None, ens: Ensemble = None): self._group_func = group_func ...
--- +++ @@ -1,6 +1,16 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Group can group a set of objects based on `group_func` and change them to a dict. +After group, we provide a method to reduce them. + +For example: + +group: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: ob...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/ens/group.py
Add docstrings including usage examples
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import struct from pathlib import Path from typing import Iterable, Union, Dict, Mapping, Tuple, List import numpy as np import pandas as pd from qlib.utils.time import Freq from qlib.utils.resam import resam_calendar from qlib.config import C ...
--- +++ @@ -19,6 +19,10 @@ class FileStorageMixin: + """FileStorageMixin, applicable to FileXXXStorage + Subclasses need to have provider_uri, freq, storage_name, file_name attributes + + """ # NOTE: provider_uri priority: # 1. self._provider_uri : if provider_uri is provided. @@ -59,6 +63,12...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/storage/file_storage.py
Create docstrings for API functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # coding=utf-8 from abc import abstractmethod import warnings from typing import Callable, Union, Tuple, List, Iterator, Optional import pandas as pd from qlib.typehint import Literal from ...log import get_module_logger, TimeInspector from ......
--- +++ @@ -23,8 +23,26 @@ class DataHandlerABC(Serializable): + """ + Interface for data handler. + + This class does not assume the internal data structure of the data handler. + It only defines the interface for external users (uses DataFrame as the internal data structure). + + In the future, the...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/dataset/handler.py
Generate documentation strings for clarity
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pandas as pd from abc import abstractmethod class FeatureInt: @abstractmethod def get_feature_importance(self) -> pd.Series: class LightGBMFInt(FeatureInt): def __init__(self): self.model = None def get_fe...
--- +++ @@ -1,25 +1,45 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Interfaces to interpret models +""" import pandas as pd from abc import abstractmethod class FeatureInt: + """Feature (Int)erpreter""" @abstractmethod def get_feature_importance(self) ->...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/interpret/base.py
Add inline docstrings for readability
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import re from typing import Iterable, overload, Tuple, List, Text, Union, Dict import numpy as np import pandas as pd from qlib.log import get_module_logger # calendar value type CalVT = str # instrument value InstVT = List[Tuple[CalVT, CalVT...
--- +++ @@ -82,6 +82,9 @@ class CalendarStorage(BaseStorage): + """ + The behavior of CalendarStorage's methods and List's methods of the same name remain consistent + """ def __init__(self, freq: str, future: bool, **kwargs): self.freq = freq @@ -90,6 +93,13 @@ @property def dat...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/storage/storage.py
Generate missing documentation strings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc from typing import Text, Union from ..utils.serial import Serializable from ..data.dataset import Dataset from ..data.dataset.weight import Reweighter class BaseModel(Serializable, metaclass=abc.ABCMeta): @abc.abstractmethod ...
--- +++ @@ -8,26 +8,103 @@ class BaseModel(Serializable, metaclass=abc.ABCMeta): + """Modeling things""" @abc.abstractmethod def predict(self, *args, **kwargs) -> object: + """Make predictions after modeling things""" def __call__(self, *args, **kwargs) -> object: + """leverage P...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/base.py
Write docstrings for backend logic
import numpy as np from typing import Union from qlib.model.riskmodel import RiskModel class ShrinkCovEstimator(RiskModel): SHR_LW = "lw" SHR_OAS = "oas" TGT_CONST_VAR = "const_var" TGT_CONST_CORR = "const_corr" TGT_SINGLE_FACTOR = "single_factor" def __init__(self, alpha: Union[str, float...
--- +++ @@ -5,6 +5,44 @@ class ShrinkCovEstimator(RiskModel): + """Shrinkage Covariance Estimator + + This estimator will shrink the sample covariance matrix towards + an identify matrix: + S_hat = (1 - alpha) * S + alpha * F + where `alpha` is the shrink parameter and `F` is the shrinking target...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/riskmodel/shrink.py
Help me write clear docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from qlib.data.dataset import Dataset from ...utils import init_instance_by_config class MetaTask: PROC_MODE_FULL = "full" PROC_MODE_TEST = "test" PROC_MODE_TRANSFER = "transfer" def __init__(self, task: dict, meta_info: objec...
--- +++ @@ -6,12 +6,39 @@ class MetaTask: + """ + A single meta-task, a meta-dataset contains a list of them. + It serves as a component as in MetaDatasetDS + + The data processing is different + + - the processed input may be different between training and testing + + - When training, the X, ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/meta/task.py
Add docstrings following best practices
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # pylint: skip-file # flake8: noqa import os import yaml import json import copy import logging import importlib import subprocess import pandas as pd import numpy as np from abc import abstractmethod from ...log import get_module_logger, Time...
--- +++ @@ -58,14 +58,26 @@ @abstractmethod def objective(self, params): + """ + Implement this method to give an optimization factor using parameters in space. + :return: {'loss': a factor for optimization, float type, + 'status': the status of this evaluation step, STA...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/contrib/tuner/tuner.py
Add documentation for all methods
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc from typing import Union, Text, Optional import numpy as np import pandas as pd from qlib.utils.data import robust_zscore, zscore from ...constant import EPS from .utils import fetch_df_by_index from ...utils.serial import Serializabl...
--- +++ @@ -16,6 +16,16 @@ def get_group_columns(df: pd.DataFrame, group: Union[Text, None]): + """ + get a group of columns from multi-index columns DataFrame + + Parameters + ---------- + df : pd.DataFrame + with multi of columns. + group : str + the name of the feature group, i.e....
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/dataset/processor.py
Document this code for team use
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import socket from typing import Callable, List, Optional from tqdm.auto import tqdm from qlib.config import C from qlib.data.dataset import Dataset from qlib.data.dataset.weight import Reweighter from qlib.log import get_module_logger from ql...
--- +++ @@ -1,6 +1,15 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +The Trainer will train a list of tasks and return a list of model recorders. +There are two steps in each Trainer including ``train`` (make model recorder) and ``end_train`` (modify model recorder). + +This is a c...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/trainer.py
Annotate my code with docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np from typing import Union from sklearn.decomposition import PCA, FactorAnalysis from qlib.model.riskmodel import RiskModel class StructuredCovEstimator(RiskModel): FACTOR_MODEL_PCA = "pca" FACTOR_MODEL_FA = "fa" ...
--- +++ @@ -9,12 +9,46 @@ class StructuredCovEstimator(RiskModel): + """Structured Covariance Estimator + + This estimator assumes observations can be predicted by multiple factors + X = B @ F.T + U + where `X` contains observations (row) of multiple variables (column), + `F` contains factor expo...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/riskmodel/structured.py
Add docstrings with type hints explained
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc from typing import List from .dataset import MetaTaskDataset class MetaModel(metaclass=abc.ABCMeta): @abc.abstractmethod def fit(self, *args, **kwargs): @abc.abstractmethod def inference(self, *args, **kwargs) -> o...
--- +++ @@ -8,24 +8,63 @@ class MetaModel(metaclass=abc.ABCMeta): + """ + The meta-model guiding the model learning. + + The word `Guiding` can be categorized into two types based on the stage of model learning + - The definition of learning tasks: Please refer to docs of `MetaTaskModel` + - Control...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/meta/model.py
Include argument descriptions in docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from typing import Union import pandas as pd from qlib.utils import FLATTEN_TUPLE, flatten_dict from qlib.log import get_module_logger class Ensemble: def __call__(self, ensemble_dict: dict, *args, **kwargs): raise NotImplementedE...
--- +++ @@ -1,6 +1,9 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Ensemble module can merge the objects in an Ensemble. For example, if there are many submodels predictions, we may need to merge them into an ensemble prediction. +""" from typing import Union import pandas as ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/model/ens/ensemble.py
Improve my code by adding docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division from __future__ import print_function import re import abc import copy import queue import bisect import numpy as np import pandas as pd from typing import List, Union, Optional # For supporting multiprocessing ...
--- +++ @@ -41,6 +41,10 @@ class ProviderBackendMixin: + """ + This helper class tries to make the provider based on storage backend more convenient + It is not necessary to inherent this class if that provider don't rely on the backend storage + """ def get_default_backend(self): backen...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/data.py
Generate helpful docstrings for debugging
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import logging from typing import Optional, Text, Dict, Any import re from logging import config as logging_config from time import time from contextlib import contextmanager from .config import C class MetaLogger(type): def __new__(mcs, ...
--- +++ @@ -22,6 +22,9 @@ class QlibLogger(metaclass=MetaLogger): + """ + Customized logger for Qlib. + """ def __init__(self, module_name): self.module_name = module_name @@ -54,6 +57,15 @@ logger.setLevel(level) def __call__(self, module_name, level: Optional[int] = Non...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/log.py
Add detailed docstrings explaining each function
from ...utils.serial import Serializable from typing import Callable, Union, List, Tuple, Dict, Text, Optional from ...utils import init_instance_by_config, np_ffill, time_to_slc_point from ...log import get_module_logger from .handler import DataHandler, DataHandlerLP from copy import copy, deepcopy from inspect impor...
--- +++ @@ -13,20 +13,73 @@ class Dataset(Serializable): + """ + Preparing data for model training and inferencing. + """ def __init__(self, **kwargs): + """ + init is designed to finish following steps: + + - init the sub instance and the state of the dataset(info to prepare th...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/dataset/__init__.py
Fill in missing docstrings in my code
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import division, print_function import json import socketio import qlib from ..log import get_module_logger class Client: def __init__(self, host, port): super(Client, self).__init__() self.sio = socket...
--- +++ @@ -14,6 +14,10 @@ class Client: + """A client class + + Provide the connection tool functions for ClientProvider. + """ def __init__(self, host, port): super(Client, self).__init__() @@ -29,21 +33,40 @@ self.sio.on("disconnect", lambda: self.logger.debug("Disconnect from se...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/data/client.py
Add missing documentation to my Python functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import List, Tuple, cast import torch import torch.nn as nn from tianshou.data import Batch from qlib.typehint import Literal from .interpreter import FullHistoryObs __all__ = ["Recurrent"] cl...
--- +++ @@ -17,6 +17,15 @@ class Recurrent(nn.Module): + """The network architecture proposed in `OPD <https://seqml.github.io/opd/opd_aaai21_supplement.pdf>`_. + + At every time step the input of policy network is divided into two parts, + the public variables and the private variables. which are handled ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/order_execution/network.py
Add clean documentation to messy code
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import collections import copy from contextlib import AbstractContextManager, contextmanager from datetime import datetime from pathlib import Path from typing import Any, Dict, Iterable, List, OrderedDict, Seq...
--- +++ @@ -28,6 +28,45 @@ class Trainer: + """ + Utility to train a policy on a particular task. + + Different from traditional DL trainer, the iteration of this trainer is "collect", + rather than "epoch", or "mini-batch". + In each collect, :class:`Collector` collects a number of policy-env intera...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/trainer/trainer.py
Help me add docstrings to my project
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import weakref from typing import Any, Callable, cast, Dict, Generic, Iterable, Iterator, Optional, Tuple import gym from gym import Space from qlib.rl.aux_info import AuxiliaryInfoCollector from qlib.rl.inte...
--- +++ @@ -24,6 +24,7 @@ class InfoDict(TypedDict): + """The type of dict that is used in the 4th return value of ``env.step()``.""" aux_info: dict """Any information depends on auxiliary info collector.""" @@ -32,6 +33,12 @@ class EnvWrapperStatus(TypedDict): + """ + This is the status da...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/utils/env_wrapper.py
Add professional docstrings to my codebase
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # TODO: this utils covers too much utilities, please seperat it into sub modules from __future__ import division from __future__ import print_function import os import re import copy import json import redis import bisect import struct import d...
--- +++ @@ -41,6 +41,7 @@ #################### Server #################### def get_redis_connection(): + """get redis connection instance.""" return redis.StrictRedis( host=C.redis_host, port=C.redis_port, @@ -68,6 +69,20 @@ def get_period_list(first: int, last: int, quarterly: bool) ->...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/__init__.py
Create docstrings for reusable components
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import Generator, List, Optional import pandas as pd from qlib.backtest import collect_data_loop, get_strategy_executor from qlib.backtest.decision import BaseTradeDecision, Order, TradeRangeByTim...
--- +++ @@ -17,6 +17,21 @@ class SingleAssetOrderExecution(Simulator[Order, SAOEState, float]): + """Single-asset order execution (SAOE) simulator which is implemented based on Qlib backtest tools. + + Parameters + ---------- + order + The seed to start an SAOE simulator is an order. + executo...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/order_execution/simulator_qlib.py
Add docstrings for internal functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import cast import numpy as np from qlib.backtest.decision import OrderDir from qlib.rl.order_execution.state import SAOEMetrics, SAOEState from qlib.rl.reward import Reward __all__ = ["PAPenalty...
--- +++ @@ -15,6 +15,16 @@ class PAPenaltyReward(Reward[SAOEState]): + """Encourage higher PAs, but penalize stacking all the amounts within a very short time. + Formally, for each time step, the reward is :math:`(PA_t * vol_t / target - vol_t^2 * penalty)`. + + Parameters + ---------- + penalty + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/order_execution/reward.py
Help me add docstrings to my project
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import Any, Generator, Optional, TYPE_CHECKING, Union if TYPE_CHECKING: from qlib.backtest.exchange import Exchange from qlib.backtest.position import...
--- +++ @@ -21,6 +21,7 @@ class BaseStrategy: + """Base strategy for trading""" def __init__( self, @@ -29,6 +30,31 @@ common_infra: CommonInfrastructure = None, trade_exchange: Exchange = None, ) -> None: + """ + Parameters + ---------- + outer_t...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/strategy/base.py
Add docstrings for better understanding
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import copy import os import shutil import time from datetime import datetime from pathlib import Path from typing import Any, List, TYPE_CHECKING import numpy as np import pandas as pd import torch from qli...
--- +++ @@ -1,6 +1,9 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +"""Callbacks to insert customized recipes during the training. +Mimicks the hooks of Keras / PyTorch-Lightning, but tailored for the context of RL. +""" from __future__ import annotations @@ -27,33 +30,65 @@ cl...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/trainer/callbacks.py
Add docstrings to existing functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, Generic, Optional, Tuple, TypeVar from qlib.typehint import final if TYPE_CHECKING: from .utils.env_wrapper import EnvWrapper SimulatorState = TypeVar("Simula...
--- +++ @@ -14,6 +14,11 @@ class Reward(Generic[SimulatorState]): + """ + Reward calculation component that takes a single argument: state of simulator. Returns a real number: reward. + + Subclass should implement ``reward(simulator_state)`` to implement their own reward calculation recipe. + """ ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/reward.py
Add docstrings to meet PEP guidelines
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import atexit import logging import sys import traceback from ..log import get_module_logger from . import R from .recorder import Recorder logger = get_module_logger("workflow", logging.INFO) # function to handle the experiment when unusual ...
--- +++ @@ -15,15 +15,33 @@ # function to handle the experiment when unusual program ending occurs def experiment_exit_handler(): + """ + Method for handling the experiment when any unusual program ending occurs. + The `atexit` handler should be put in the last, since, as long as the program ends, it will b...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/utils.py
Add docstrings explaining edge cases
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pickle import dill from pathlib import Path from typing import Union from ..config import C class Serializable: pickle_backend = "pickle" # another optional value is "dill" which can pickle more things of python. default_dump_a...
--- +++ @@ -9,6 +9,20 @@ class Serializable: + """ + Serializable will change the behaviors of pickle. + + The rule to tell if a attribute will be kept or dropped when dumping. + The rule with higher priorities is on the top + - in the config attribute list -> always dropped + - in...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/serial.py
Write docstrings for data processing functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # NOTE: This file contains many hardcoded / ad-hoc rules. # Refactoring it will be one of the future tasks. from __future__ import annotations import logging from collections import defaultdict from enum import IntEnum from pathlib import Path...
--- +++ @@ -1,6 +1,16 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +"""Distributed logger for RL. + +:class:`LogCollector` runs in every environment workers. It collects log info from simulator states, +and add them (as a dict) to auxiliary info returned for each step. + +:class:`LogWr...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/utils/log.py
Add docstrings including usage examples
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import Any, Generic, TypeVar import gym import numpy as np from gym import spaces from qlib.typehint import final from .simulator import ActType, StateType ObsType = TypeVar("ObsType") PolicyActT...
--- +++ @@ -17,9 +17,23 @@ class Interpreter: + """Interpreter is a media between states produced by simulators and states needed by RL policies. + Interpreters are two-way: + + 1. From simulator state to policy state (aka observation), see :class:`StateInterpreter`. + 2. From policy action to action ac...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/interpreter.py
Generate docstrings for each module
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import Any, Callable, Dict, List, Sequence, cast from tianshou.policy import BasePolicy from qlib.rl.interpreter import ActionInterpreter, StateInterpreter from qlib.rl.reward import Reward from q...
--- +++ @@ -26,6 +26,29 @@ vessel_kwargs: Dict[str, Any], trainer_kwargs: Dict[str, Any], ) -> None: + """Train a policy with the parallelism provided by RL framework. + + Experimental API. Parameters might change shortly. + + Parameters + ---------- + simulator_fn + Callable receiving i...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/trainer/api.py
Add docstrings to improve code quality
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import Dict, Tuple, Union, Callable, List import bisect import numpy as np import pandas as pd def concat(data_list: Union[SingleData], axis=0) -> MultiData: if axis == 0: raise NotIm...
--- +++ @@ -1,5 +1,13 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Motivation of index_data +- Pandas has a lot of user-friendly interfaces. However, integrating too much features in a single tool bring too much overhead and makes it much slower than numpy. + Some users just wan...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/index_data.py
Add docstrings for better understanding
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import math from typing import Any, List, Optional, cast import numpy as np import pandas as pd from gym import spaces from qlib.constant import EPS from qlib.rl.data.base import ProcessedDataProvider from ql...
--- +++ @@ -28,6 +28,7 @@ def canonicalize(value: int | float | np.ndarray | pd.DataFrame | dict) -> np.ndarray | dict: + """To 32-bit numeric types. Recursively.""" if isinstance(value, pd.DataFrame): return value.to_numpy() if isinstance(value, (float, np.floating)) or (isinstance(value, np....
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/order_execution/interpreter.py
Write docstrings for backend logic
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import contextlib import importlib import os from pathlib import Path import pkgutil import re import sys from types import ModuleType from typing import Any, Dict, List, Tuple, Union from urllib.parse import urlparse from qlib.typehint import I...
--- +++ @@ -1,5 +1,11 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +All module related class, e.g. : +- importing a module, class +- walkiing a module +- operations on class or module... +""" import contextlib import importlib @@ -17,6 +23,12 @@ def get_module_by_module_path...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/mod.py
Write proper docstrings for these functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import shutil import tempfile import contextlib from typing import Optional, Text, IO, Union from pathlib import Path from qlib.log import get_module_logger log = get_module_logger("utils.file") def get_or_create_path(path: Optional...
--- +++ @@ -14,6 +14,14 @@ def get_or_create_path(path: Optional[Text] = None, return_dir: bool = False): + """Create or get a file or directory given the path and return_dir. + + Parameters + ---------- + path: a string indicates the path or None indicates creating a temporary path. + return_dir: if...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/file.py
Document all endpoints with docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # Base exception class class QlibException(Exception): pass class RecorderInitializationError(QlibException): class LoadObjectError(QlibException): class ExpAlreadyExistError(Exception):
--- +++ @@ -8,9 +8,12 @@ class RecorderInitializationError(QlibException): + """Error type for re-initialization when starting an experiment""" class LoadObjectError(QlibException): + """Error type for Recorder when can not load object""" -class ExpAlreadyExistError(Exception):+class ExpAlreadyExistE...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/exceptions.py
Generate NumPy-style docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import io import pickle from typing import Any, BinaryIO, Set, Tuple # Whitelist of safe classes that are allowed to be unpickled # These are common data types used in qlib that should be safe to deserialize SAFE_PICKLE_CLASSES: Set[Tuple[str, s...
--- +++ @@ -1,5 +1,11 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Secure pickle utilities to prevent arbitrary code execution through deserialization. + +This module provides a secure alternative to pickle.load() and pickle.loads() +that restricts deserialization to a whitelist of...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/pickle_utils.py
Document helper functions with docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from pathlib import Path from typing import Any, Dict, Generator, Iterable, Optional, OrderedDict, Tuple, cast import gym import numpy as np import torch import torch.nn as nn from gym.spaces import Discrete f...
--- +++ @@ -23,6 +23,10 @@ class NonLearnablePolicy(BasePolicy): + """Tianshou's BasePolicy with empty ``learn`` and ``process_fn``. + + This could be moved outside in future. + """ def __init__(self, obs_space: gym.Space, action_space: gym.Space) -> None: super().__init__() @@ -40,6 +44,10...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/order_execution/policy.py
Add minimal docstrings for each function
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import collections from types import GeneratorType from typing import Any, Callable, cast, Dict, Generator, List, Optional, Tuple, Union import warnings import numpy as np import pandas as pd import torch from...
--- +++ @@ -52,10 +52,35 @@ original_data: np.ndarray, fill_method: Callable = np.nanmedian, ) -> np.ndarray: + """Fill missing data. + + Parameters + ---------- + original_data + Original data without missing values. + fill_method + Method used to fill the missing data. + + Re...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/order_execution/strategy.py
Can you add docstrings to this Python file?
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import threading from functools import partial from threading import Thread from typing import Callable, Text, Union import joblib from joblib import Parallel, delayed from joblib._parallel_backends import MultiprocessingBackend import pandas as...
--- +++ @@ -33,6 +33,27 @@ def datetime_groupby_apply( df, apply_func: Union[Callable, Text], axis=0, level="datetime", resample_rule="ME", n_jobs=-1 ): + """datetime_groupby_apply + This function will apply the `apply_func` on the datetime level index. + + Parameters + ---------- + df : + D...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/paral.py
Write docstrings for algorithm functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from copy import deepcopy from typing import List, Union import numpy as np import pandas as pd from qlib.data.data import DatasetProvider def robust_zscore(x: pd.Series, zscore=False): x = x - x.median() mad = x.abs().median() x ...
--- +++ @@ -1,5 +1,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +This module covers some utility functions that operate on data or basic object +""" from copy import deepcopy from typing import List, Union @@ -11,6 +14,15 @@ def robust_zscore(x: pd.Series, zscore=False): +...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/data.py
Create docstrings for API functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import copy import warnings from contextlib import contextmanager from typing import Any, Callable, Dict, Generator, List, Optional, Set, Tuple, Type, Union, cast import gym import numpy as np from tianshou.e...
--- +++ @@ -1,6 +1,10 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +This is to support finite env in vector env. +See https://github.com/thu-ml/tianshou/issues/322 for details. +""" from __future__ import annotations @@ -66,6 +70,11 @@ def generate_nan_observation(obs_spa...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/utils/finite_env.py
Add docstrings for utility scripts
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import os from pathlib import Path from typing import List, cast import cachetools import pandas as pd from qlib.backtest import Exchange, Order from qlib.backtest.decision import TradeRange, TradeRangeByTime ...
--- +++ @@ -29,6 +29,7 @@ class IntradayBacktestData(BaseIntradayBacktestData): + """Backtest data for Qlib simulator""" def __init__( self, @@ -84,6 +85,7 @@ class DataframeIntradayBacktestData(BaseIntradayBacktestData): + """Backtest data from dataframe""" def __init__(self, df: p...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/data/native.py
Add docstrings explaining edge cases
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc import time import datetime import importlib from pathlib import Path from typing import Type, Iterable from concurrent.futures import ProcessPoolExecutor import pandas as pd from tqdm import tqdm from loguru import logger from jobli...
--- +++ @@ -41,6 +41,29 @@ check_data_length: int = None, limit_nums: int = None, ): + """ + + Parameters + ---------- + save_dir: str + instrument save dir + max_workers: int + workers, default 1; Concurrent number, default is 1; when colle...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/base.py
Add standardized docstrings across the file
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import weakref from typing import TYPE_CHECKING, Any, Callable, ContextManager, Dict, Generic, Iterable, Sequence, TypeVar, cast import numpy as np from tianshou.data import Collector, VectorReplayBuffer from ...
--- +++ @@ -32,6 +32,12 @@ class TrainingVesselBase(Generic[InitialStateType, StateType, ActType, ObsType, PolicyActType]): + """A ship that contains simulator, interpreter, and policy, will be sent to trainer. + This class controls algorithm-related parts of training, while trainer is responsible for runtime...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/trainer/vessel.py
Generate missing documentation strings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import Any, cast, List, Optional import numpy as np import pandas as pd from pathlib import Path from qlib.backtest.decision import Order, OrderDir from qlib.constant import EPS, EPS_T, float_or_n...
--- +++ @@ -22,6 +22,35 @@ class SingleAssetOrderExecutionSimple(Simulator[Order, SAOEState, float]): + """Single-asset order execution (SAOE) simulator. + + As there's no "calendar" in the simple simulator, ticks are used to trade. + A tick is a record (a line) in the pickle-styled data file. + Each ti...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/order_execution/simulator_simple.py
Generate docstrings with parameter types
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar from .seed import InitialStateType if TYPE_CHECKING: from .utils.env_wrapper import EnvWrapper StateType = TypeVar("StateType") """StateT...
--- +++ @@ -19,6 +19,35 @@ class Simulator(Generic[InitialStateType, StateType, ActType]): + """ + Simulator that resets with ``__init__``, and transits with ``step(action)``. + + To make the data-flow clear, we make the following restrictions to Simulator: + + 1. The only way to modify the inner status...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/simulator.py
Write beginner-friendly docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import pickle import tempfile from pathlib import Path from qlib.config import C from qlib.utils.pickle_utils import restricted_pickle_load class ObjManager: def save_obj(self, obj: object, name: str): raise NotImplemented...
--- +++ @@ -11,25 +11,87 @@ class ObjManager: def save_obj(self, obj: object, name: str): + """ + save obj as name + + Parameters + ---------- + obj : object + object to be saved + name : str + name of the object + """ raise NotImple...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/objm.py
Add detailed documentation for each class
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import sys import copy import fire import numpy as np import pandas as pd import baostock as bs from tqdm import tqdm from pathlib import Path from loguru import logger from typing import Iterable, List import qlib from qlib.data import D CUR_...
--- +++ @@ -36,6 +36,29 @@ check_data_length: int = None, limit_nums: int = None, ): + """ + + Parameters + ---------- + save_dir: str + stock save dir + max_workers: int + workers, default 4 + max_collector_count: int + de...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/baostock_5min/collector.py
Help me add docstrings to my project
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from __future__ import annotations import typing from typing import NamedTuple, Optional import numpy as np import pandas as pd from qlib.backtest import Order from qlib.typehint import TypedDict if typing.TYPE_CHECKING: from qlib.rl.data....
--- +++ @@ -16,6 +16,14 @@ class SAOEMetrics(TypedDict): + """Metrics for SAOE accumulated for a "period". + It could be accumulated for a day, or a period of time (e.g., 30min), or calculated separately for every minute. + + Warnings + -------- + The type hints are for single elements. In lots of ti...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/order_execution/state.py
Add verbose docstrings with examples
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import bisect from datetime import datetime, time, date, timedelta from typing import List, Optional, Tuple, Union import functools import re import pandas as pd from qlib.config import C from qlib.constant import REG_CN, REG_TW, REG_US CN_TIM...
--- +++ @@ -1,5 +1,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Time related utils are compiled in this script +""" import bisect from datetime import datetime, time, date, timedelta @@ -27,6 +30,22 @@ @functools.lru_cache(maxsize=240) def get_min_cal(shift: int = 0, regio...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/time.py
Add docstrings to clarify complex logic
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # TODO: merge with qlib/backtest/high_performance_ds.py from __future__ import annotations from functools import lru_cache from pathlib import Path from typing import List, Sequence, cast import cachetools import numpy as np import pandas as ...
--- +++ @@ -1,6 +1,19 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +"""This module contains utilities to read financial data from pickle-styled files. + +This is the format used in `OPD paper <https://seqml.github.io/opd/>`__. NOT the standard data format in qlib. + +The data here are ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/rl/data/pickle_styled.py
Help me document legacy Python code
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from typing import Dict, List, Union from qlib.typehint import Literal import mlflow from mlflow.entities import ViewType from mlflow.exceptions import MlflowException from .recorder import Recorder, MLflowRecorder from ..log import get_module_lo...
--- +++ @@ -1,212 +1,379 @@-# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -from typing import Dict, List, Union -from qlib.typehint import Literal -import mlflow -from mlflow.entities import ViewType -from mlflow.exceptions import MlflowException -from .recorder import Recorder, MLflowReco...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/exp.py
Document all public functions with docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from urllib.parse import urlparse import mlflow from filelock import FileLock from mlflow.exceptions import MlflowException, RESOURCE_ALREADY_EXISTS, ErrorCode from mlflow.entities import ViewType import os from typing import Optional, Text from ...
--- +++ @@ -20,6 +20,16 @@ class ExpManager: + """ + This is the `ExpManager` class for managing experiments. The API is designed similar to mlflow. + (The link: https://mlflow.org/docs/latest/python_api/mlflow.html) + + The `ExpManager` is expected to be a singleton (btw, we can have multiple `Experime...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/expm.py
Generate docstrings for each module
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from contextlib import contextmanager from typing import Text, Optional, Any, Dict from .expm import ExpManager from .exp import Experiment from .recorder import Recorder from ..utils import Wrapper from ..utils.exceptions import RecorderInitiali...
--- +++ @@ -1,5 +1,18 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Motivation of this design (instead of using mlflow directly): +- Better design than mlflow native design + - we have record object with a lot of methods(more intuitive), instead of use run_id everytime in mlflow ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/__init__.py
Turn comments into proper docstrings
import numpy as np import pandas as pd from functools import partial from typing import Union, Callable from . import lazy_sort_index from .time import Freq, cal_sam_minute from ..config import C def resam_calendar( calendar_raw: np.ndarray, freq_raw: Union[str, Freq], freq_sam: Union[str, Freq], region: str = ...
--- +++ @@ -12,6 +12,26 @@ def resam_calendar( calendar_raw: np.ndarray, freq_raw: Union[str, Freq], freq_sam: Union[str, Freq], region: str = None ) -> np.ndarray: + """ + Resample the calendar with frequency freq_raw into the calendar with frequency freq_sam + Assumption: + - Fix length (240) of...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/utils/resam.py
Document functions with clear intent
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from typing import List, Union from qlib.log import get_module_logger from qlib.utils.exceptions import LoadObjectError from qlib.workflow.online.update import PredUpdater from qlib.workflow.recorder import Recorder from qlib.workflow.task.util...
--- +++ @@ -1,6 +1,11 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +OnlineTool is a module to set and unset a series of `online` models. +The `online` models are some decisive models in some time points, which can be changed with the change of time. +This allows us to use efficien...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/online/utils.py
Can you add docstrings to this Python file?
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc import sys import copy import time import datetime import importlib from abc import ABC import multiprocessing from pathlib import Path from typing import Iterable import fire import requests import numpy as np import pandas as pd fro...
--- +++ @@ -60,6 +60,29 @@ check_data_length: int = None, limit_nums: int = None, ): + """ + + Parameters + ---------- + save_dir: str + stock save dir + max_workers: int + workers, default 4 + max_collector_count: int + de...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/yahoo/collector.py
Create docstrings for reusable components
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import logging from typing import Callable, List, Union import pandas as pd from qlib import get_module_logger from qlib.data.data import D from qlib.log import set_global_logger_level from qlib.model.ens.ensemble import AverageEnsemble from ql...
--- +++ @@ -1,6 +1,88 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +OnlineManager can manage a set of `Online Strategy <#Online Strategy>`_ and run them dynamically. + +With the change of time, the decisive models will be also changed. In this module, we call those contributing mo...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/online/manager.py
Add documentation for all methods
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import re import copy import importlib import time import bisect import pickle import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from loguru import logger ...
--- +++ @@ -54,6 +54,17 @@ def get_calendar_list(bench_code="CSI300") -> List[pd.Timestamp]: + """get SH/SZ history calendar list + + Parameters + ---------- + bench_code: str + value from ["CSI300", "CSI500", "ALL", "US_ALL"] + + Returns + ------- + history calendar list + """ ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/utils.py
Document functions with detailed explanations
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from abc import ABCMeta, abstractmethod from typing import Optional import pandas as pd from qlib import get_module_logger from qlib.data import D from qlib.data.dataset import Dataset, DatasetH, TSDatasetH from qlib.data.dataset.handler import ...
--- +++ @@ -1,5 +1,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Updater is a module to update artifacts such as predictions when the stock data is updating. +""" from abc import ABCMeta, abstractmethod from typing import Optional @@ -16,6 +19,9 @@ class RMDLoader: + ""...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/online/update.py
Write docstrings for utility functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from typing import List, Union from qlib.log import get_module_logger from qlib.model.ens.group import RollingGroup from qlib.utils import transform_end_date from qlib.workflow.online.utils import OnlineTool, OnlineToolR from qlib.workflow.recor...
--- +++ @@ -1,6 +1,9 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +OnlineStrategy module is an element of online serving. +""" from typing import List, Union from qlib.log import get_module_logger @@ -14,29 +17,82 @@ class OnlineStrategy: + """ + OnlineStrategy is wo...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/online/strategy.py
Add docstrings with type hints explained
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc from functools import partial import sys from pathlib import Path from concurrent.futures import ThreadPoolExecutor from typing import List from io import StringIO import fire import requests import pandas as pd from tqdm import tqdm ...
--- +++ @@ -56,13 +56,42 @@ @property @abc.abstractmethod def bench_start_date(self) -> pd.Timestamp: + """ + Returns + ------- + index start date + """ raise NotImplementedError("rewrite bench_start_date") @abc.abstractmethod def get_changes(sel...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/us_index/collector.py
Improve documentation using docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import sys from typing import Optional import mlflow import shutil import pickle import tempfile import subprocess import platform from pathlib import Path from datetime import datetime from qlib.utils.serial import Serializable from q...
--- +++ @@ -1,322 +1,493 @@-# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -import os -import sys -from typing import Optional -import mlflow -import shutil -import pickle -import tempfile -import subprocess -import platform -from pathlib import Path -from datetime import datetime - -from q...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/recorder.py
Document functions with clear intent
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import logging import warnings import pandas as pd import numpy as np from tqdm import trange from pprint import pprint from typing import Union, List, Optional, Dict from qlib.utils.exceptions import LoadObjectError from ..contrib.evaluate im...
--- +++ @@ -26,6 +26,10 @@ class RecordTemp: + """ + This is the Records Template class that enables user to generate experiment results such as IC and + backtest in a certain format. + """ artifact_path = None depend_cls = None # the dependant class of the record; the record will depend on...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/record_temp.py
Add well-formatted docstrings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc import copy import pandas as pd from typing import Dict, List, Union, Callable from qlib.utils import transform_end_date from .utils import TimeAdjuster def task_generator(tasks, generators) -> list: if isinstance(tasks, dict):...
--- +++ @@ -1,5 +1,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +TaskGenerator module can generate many tasks based on TaskGen and some task templates. +""" import abc import copy @@ -11,6 +14,26 @@ def task_generator(tasks, generators) -> list: + """ + Use a list of...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/task/gen.py
Add docstrings to meet PEP guidelines
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import concurrent import pickle import time from contextlib import contextmanager from typing import Callable, List import fire import pymongo from bson.binary import Binary from bson.objectid import ObjectId from pymongo.errors import InvalidD...
--- +++ @@ -1,6 +1,17 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +TaskManager can fetch unused tasks automatically and manage the lifecycle of a set of tasks with error handling. +These features can run tasks concurrently and ensure every task will be used only once. +Task Manag...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/task/manage.py
Write docstrings for backend logic
import os from typing import Optional import fire import pandas as pd from loguru import logger from tqdm import tqdm import qlib from qlib.data import D class DataHealthChecker: def __init__( self, csv_path=None, qlib_dir=None, freq="day", large_step_threshold_price=0.5...
--- +++ @@ -11,6 +11,12 @@ class DataHealthChecker: + """Checks a dataset for data completeness and correctness. The data will be converted to a pd.DataFrame and checked for the following problems: + - any of the columns ["open", "high", "low", "close", "volume"] are missing + - any data is missing + - ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/check_data_health.py
Add docstrings to clarify complex logic
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from collections import defaultdict from qlib.log import TimeInspector from typing import Callable, Dict, Iterable, List from qlib.log import get_module_logger from qlib.utils.serial import Serializable from qlib.utils.exceptions import LoadObje...
--- +++ @@ -1,6 +1,9 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Collector module can collect objects from everywhere and process them such as merging, grouping, averaging and so on. +""" from collections import defaultdict from qlib.log import TimeInspector @@ -14,19 +17,53...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/task/collect.py
Write docstrings describing functionality
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from pathlib import Path from concurrent.futures import ProcessPoolExecutor import qlib from qlib.data import D import fire import datacompy import pandas as pd from tqdm import tqdm from loguru import logger class CheckBin: NOT_IN_FEATUR...
--- +++ @@ -31,6 +31,27 @@ file_suffix: str = ".csv", max_workers: int = 16, ): + """ + + Parameters + ---------- + qlib_dir : str + qlib dir + csv_path : str + origin csv path + check_fields : str, optional + check fields,...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/check_dump_bin.py
Expand my code with proper documentation strings
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc import sys import datetime import json from abc import ABC from pathlib import Path import fire import requests import pandas as pd from loguru import logger from dateutil.tz import tzlocal from qlib.constant import REG_CN as REGION_C...
--- +++ @@ -36,6 +36,29 @@ check_data_length: int = None, limit_nums: int = None, ): + """ + + Parameters + ---------- + save_dir: str + fund save dir + max_workers: int + workers, default 4 + max_collector_count: int + def...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/fund/collector.py
Create docstrings for each class method
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc import importlib from pathlib import Path from typing import Union, Iterable, List import fire import numpy as np import pandas as pd # pip install baostock import baostock as bs from loguru import logger class CollectorFutureCalen...
--- +++ @@ -19,6 +19,17 @@ calendar_format = "%Y-%m-%d" def __init__(self, qlib_dir: Union[str, Path], start_date: str = None, end_date: str = None): + """ + + Parameters + ---------- + qlib_dir: + qlib data directory + start_date + start date + ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/future_calendar_collector.py
Create documentation strings for testing functions
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import shutil import struct from pathlib import Path from typing import Iterable from functools import partial from concurrent.futures import ProcessPoolExecutor import fire import pandas as pd from tqdm import tqdm from loguru import logger fro...
--- +++ @@ -1,5 +1,10 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +TODO: +- A more well-designed PIT database is required. + - separated insert, delete, update, query operations are required. +""" import shutil import struct @@ -61,6 +66,31 @@ include_fields: str = "...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/dump_pit.py
Create docstrings for each class method
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import bisect from copy import deepcopy import pandas as pd from qlib.data import D from qlib.utils import hash_args from qlib.utils.mod import init_instance_by_config from qlib.workflow import R from qlib.config import C from qlib.log import get...
--- +++ @@ -1,5 +1,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +""" +Some tools for task management. +""" import bisect from copy import deepcopy @@ -17,6 +20,33 @@ def get_mongodb() -> Database: + """ + Get database in MongoDB, which means you need to declare the addres...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/qlib/workflow/task/utils.py
Create structured documentation for my script
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc import shutil import traceback from pathlib import Path from typing import Iterable, List, Union from functools import partial from concurrent.futures import ThreadPoolExecutor, as_completed, ProcessPoolExecutor import fire import num...
--- +++ @@ -18,6 +18,21 @@ def read_as_df(file_path: Union[str, Path], **kwargs) -> pd.DataFrame: + """ + Read a csv or parquet file into a pandas DataFrame. + + Parameters + ---------- + file_path : Union[str, Path] + Path to the data file. + **kwargs : + Additional keyword argument...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/dump_bin.py
Annotate my code with docstrings
import sys import abc from pathlib import Path from typing import List import pandas as pd from tqdm import tqdm from loguru import logger CUR_DIR = Path(__file__).resolve().parent sys.path.append(str(CUR_DIR.parent)) from data_collector.utils import get_trading_date_by_shift class IndexBase: DEFAULT_END_DATE...
--- +++ @@ -34,6 +34,21 @@ request_retry: int = 5, retry_sleep: int = 3, ): + """ + + Parameters + ---------- + index_name: str + index name + qlib_dir: str + qlib directory, by default Path(__file__).resolve().parent.joinpath("qlib_data") +...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/index.py
Add docstrings including usage examples
import abc import sys import datetime from abc import ABC from pathlib import Path import fire import pandas as pd from loguru import logger from dateutil.tz import tzlocal CUR_DIR = Path(__file__).resolve().parent sys.path.append(str(CUR_DIR.parent.parent)) from data_collector.base import BaseCollector, BaseNormaliz...
--- +++ @@ -23,6 +23,12 @@ def get_cg_crypto_symbols(qlib_data_path: [str, Path] = None) -> list: + """get crypto symbols in coingecko + + Returns + ------- + crypto symbols in given exchanges list of coingecko + """ global _CG_CRYPTO_SYMBOLS # pylint: disable=W0603 @deco_retry @@ -6...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/crypto/collector.py
Write docstrings including parameters and return values
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import re import abc import sys from io import BytesIO from typing import List, Iterable from pathlib import Path import fire import requests import pandas as pd import baostock as bs from tqdm import tqdm from loguru import logger CUR_DIR = Pa...
--- +++ @@ -49,6 +49,12 @@ class CSIIndex(IndexBase): @property def calendar_list(self) -> List[pd.Timestamp]: + """get history trading date + + Returns + ------- + calendar list + """ _calendar = getattr(self, "_calendar_list", None) if not _calendar: ...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/cn_index/collector.py
Document this code for team use
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. from functools import partial import sys from pathlib import Path import datetime import fire import pandas as pd from tqdm import tqdm from loguru import logger CUR_DIR = Path(__file__).resolve().parent sys.path.append(str(CUR_DIR.parent.parent...
--- +++ @@ -42,9 +42,41 @@ @property def bench_start_date(self) -> pd.Timestamp: + """ + The ibovespa index started on 2 January 1968 (wiki), however, + no suitable data source that keeps track of ibovespa's history + stocks composition has been found. Except from the repo indicat...
https://raw.githubusercontent.com/microsoft/qlib/HEAD/scripts/data_collector/br_index/collector.py
Write docstrings including parameters and return values
import argparse import getpass import os import sys from copy import deepcopy from typing import List, Optional, Union from .constants import DEFAULT_FORMAT_OPTIONS, SEPARATOR_CREDENTIALS from ..sessions import VALID_SESSION_NAME_PATTERN class KeyValueArg: def __init__(self, key: str, value: Optional[str], sep:...
--- +++ @@ -10,6 +10,7 @@ class KeyValueArg: + """Base key-value pair parsed from CLI.""" def __init__(self, key: str, value: Optional[str], sep: str, orig: str): self.key = key @@ -38,12 +39,19 @@ class Escaped(str): + """Represents an escaped character.""" def __repr__(self): ...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/cli/argtypes.py
Add docstrings to existing functions
import inspect import os import platform import sys import httpie.__main__ from contextlib import suppress from subprocess import Popen, DEVNULL from typing import Dict, List from httpie.compat import is_frozen, is_windows ProcessContext = Dict[str, str] def _start_process(cmd: List[str], **kwargs) -> Popen: p...
--- +++ @@ -1,3 +1,9 @@+""" +This module provides an interface to spawn a detached task to be +run with httpie.internal.daemon_runner on a separate process. It is +based on DVC's daemon system. +https://github.com/iterative/dvc/blob/main/dvc/daemon.py +""" import inspect import os @@ -47,6 +53,13 @@ def _spawn_...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/internal/daemons.py
Add standardized docstrings across the file
import argparse import http.client import json import sys from contextlib import contextmanager from time import monotonic from typing import Any, Dict, Callable, Iterable from urllib.parse import urlparse, urlunparse import requests # noinspection PyPackageRequirements import urllib3 from urllib3.util import SKIP_HEA...
--- +++ @@ -213,6 +213,8 @@ request: requests.Request, prepared_request: requests.PreparedRequest ) -> None: + """Apply various transformations on top of the `prepared_requests`'s + headers to change the request prepreation behavior.""" # Remove 'Content-Length' when it is misplaced by requests. ...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/client.py
Document functions with detailed explanations
import dataclasses import shlex import subprocess import sys import tempfile import venv from argparse import ArgumentParser, FileType from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from typing import (IO, Dict, Generator, Iterable, List, Optional, ...
--- +++ @@ -1,3 +1,38 @@+""" +Run the HTTPie benchmark suite with multiple environments. + +This script is configured in a way that, it will create +two (or more) isolated environments and compare the *last +commit* of this repository with it's master. + +> If you didn't commit yet, it won't be showing results. + +You ...
https://raw.githubusercontent.com/httpie/cli/HEAD/extras/profiling/run.py
Help me add docstrings to my project
import argparse import textwrap import typing from dataclasses import dataclass, field from enum import Enum, auto from typing import Any, Optional, Dict, List, Tuple, Type, TypeVar from httpie.cli.argparser import HTTPieArgumentParser from httpie.cli.utils import Manual, LazyChoices class Qualifiers(Enum): OPTI...
--- +++ @@ -100,6 +100,7 @@ configuration: Dict[str, Any] def post_init(self): + """Run a bunch of post-init hooks.""" # If there is a short help, then create the longer version from it. short_help = self.configuration.get('short_help') if ( @@ -239,9 +240,10 @@ def pars...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/cli/options.py
Write docstrings for utility functions
import argparse import os import platform import sys import socket from typing import List, Optional, Union, Callable import requests from pygments import __version__ as pygments_version from requests import __version__ as requests_version from . import __version__ as httpie_version from .cli.constants import OUT_REQ...
--- +++ @@ -147,6 +147,15 @@ args: List[Union[str, bytes]] = sys.argv, env: Environment = Environment() ) -> ExitStatus: + """ + The main function. + + Pre-process args, handle some special types of invocations, + and run the main program with error handling. + + Return exit status code. + + ...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/core.py
Add return value explanations in docstrings
import argparse import sys import os import warnings from contextlib import contextmanager from pathlib import Path from typing import Iterator, IO, Optional, TYPE_CHECKING from enum import Enum try: import curses except ImportError: curses = None # Compiled w/o curses from .compat import is_windows, cached...
--- +++ @@ -44,6 +44,15 @@ class Environment: + """ + Information about the execution context + (standard streams, config directory, etc). + + By default, it represents the actual environment. + All of the attributes can be overwritten though, which + is used by the test suite to simulate various ...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/context.py
Add well-formatted docstrings
from __future__ import annotations import os import shlex import subprocess import sys import threading from contextlib import ExitStack, contextmanager from dataclasses import dataclass, field from functools import cached_property, partial from http.server import HTTPServer, SimpleHTTPRequestHandler from tempfile im...
--- +++ @@ -1,3 +1,35 @@+""" +This file is the declaration of benchmarks for HTTPie. It +is also used to run them with the current environment. + +Each instance of BaseRunner class will be an individual +benchmark. And if run without any arguments, this file +will execute every benchmark instance and report the +timing...
https://raw.githubusercontent.com/httpie/cli/HEAD/extras/profiling/benchmarks.py
Add docstrings including usage examples
from typing import Any, Type, List, Dict, TYPE_CHECKING if TYPE_CHECKING: from httpie.sessions import Session OLD_HEADER_STORE_WARNING = '''\ Outdated layout detected for the current session. Please consider updating it, in order to use the latest features regarding the header layout. For fixing the current ses...
--- +++ @@ -24,6 +24,8 @@ def pre_process(session: 'Session', headers: Any) -> List[Dict[str, Any]]: + """Serialize the headers into a unified form and issue a warning if + the session file is using the old layout.""" is_old_style = isinstance(headers, dict) if is_old_style: @@ -49,6 +51,8 @@ ...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/legacy/v3_2_0_session_header_format.py
Provide clean and structured docstrings
from typing import TYPE_CHECKING, Optional from ...encoding import UTF8 from ...plugins import FormatterPlugin if TYPE_CHECKING: from xml.dom.minidom import Document XML_DECLARATION_OPEN = '<?xml' XML_DECLARATION_CLOSE = '?>' def parse_xml(data: str) -> 'Document': from defusedxml.minidom import parseStri...
--- +++ @@ -12,6 +12,7 @@ def parse_xml(data: str) -> 'Document': + """Parse given XML `data` string into an appropriate :class:`~xml.dom.minidom.Document` object.""" from defusedxml.minidom import parseString return parseString(data) @@ -29,6 +30,7 @@ declaration: Optional[str] = None...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/output/formatters/xml.py
Write proper docstrings for these functions
import sys from ssl import SSLContext from typing import Any, Optional, Iterable from httpie.cookies import HTTPieCookiePolicy from http import cookiejar # noqa # Request does not carry the original policy attached to the # cookie jar, so until it is resolved we change the global cookie # policy. <https://github.co...
--- +++ @@ -23,6 +23,15 @@ # Can be removed once we drop Python <3.8 support. # Taken from `django.utils.functional.cached_property`. class cached_property: + """ + Decorator that converts a method with a single self argument into a + property cached on the instance. + + A cach...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/compat.py
Document functions with detailed explanations
import json import os import re import sys from copy import deepcopy from datetime import datetime from pathlib import Path from subprocess import check_output from time import sleep from typing import Any, Dict, Optional, Set import requests FullNames = Set[str] GitHubLogins = Set[str] Person = Dict[str, str] People...
--- +++ @@ -1,3 +1,8 @@+""" +Generate the contributors database. + +FIXME: replace `requests` calls with the HTTPie API, when available. +""" import json import os import re @@ -33,6 +38,7 @@ class FinishedForNow(Exception): + """Raised when remaining GitHub rate limit is zero.""" def main(previous_relea...
https://raw.githubusercontent.com/httpie/cli/HEAD/docs/contributors/fetch.py
Fully document this Python code with docstrings
import mimetypes import os import re from mailbox import Message from time import monotonic from typing import IO, Optional, Tuple from urllib.parse import urlsplit import requests from .models import HTTPResponse, OutputOptions from .output.streams import RawStream from .context import Environment PARTIAL_CONTENT ...
--- +++ @@ -1,3 +1,7 @@+""" +Download mode implementation. + +""" import mimetypes import os import re @@ -21,6 +25,17 @@ def parse_content_range(content_range: str, resumed_from: int) -> int: + """ + Parse and validate Content-Range header. + + <https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html> ...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/downloads.py
Replace inline comments with docstrings
import argparse import errno import os import re import sys from argparse import RawDescriptionHelpFormatter from textwrap import dedent from urllib.parse import urlsplit from requests.utils import get_netrc_auth from .argtypes import ( AuthCredentials, SSLCredentials, KeyValueArgType, PARSED_DEFAULT_FORMAT_O...
--- +++ @@ -30,6 +30,14 @@ class HTTPieHelpFormatter(RawDescriptionHelpFormatter): + """A nicer help formatter. + + Help for arguments can be indented and contain new lines. + It will be de-dented and arguments in the help + will be separated by a blank line for better readability. + + + """ d...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/cli/argparser.py
Add minimal docstrings for each function
import json import os from pathlib import Path from typing import Any, Dict, Union from . import __version__ from .compat import is_windows from .encoding import UTF8 ENV_XDG_CONFIG_HOME = 'XDG_CONFIG_HOME' ENV_HTTPIE_CONFIG_DIR = 'HTTPIE_CONFIG_DIR' DEFAULT_CONFIG_DIRNAME = 'httpie' DEFAULT_RELATIVE_XDG_CONFIG_HOME...
--- +++ @@ -18,6 +18,19 @@ def get_default_config_dir() -> Path: + """ + Return the path to the httpie configuration directory. + + This directory isn't guaranteed to exist, and nor are any of its + ancestors (only the legacy ~/.httpie, if returned, is guaranteed to exist). + + XDG Base Directory Spe...
https://raw.githubusercontent.com/httpie/cli/HEAD/httpie/config.py