code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def train(
simulator_fn: Callable[[InitialStateType], Simulator],
state_interpreter: StateInterpreter,
action_interpreter: ActionInterpreter,
initial_states: Sequence[InitialStateType],
policy: BasePolicy,
reward: Reward,
vessel_kwargs: Dict[str, Any],
trainer_kwargs: Dict[str, Any],
) -... | Train a policy with the parallelism provided by RL framework.
Experimental API. Parameters might change shortly.
Parameters
----------
simulator_fn
Callable receiving initial seed, returning a simulator.
state_interpreter
Interprets the state of simulators.
action_interpreter
... | train | python | microsoft/qlib | qlib/rl/trainer/api.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/api.py | MIT |
def backtest(
simulator_fn: Callable[[InitialStateType], Simulator],
state_interpreter: StateInterpreter,
action_interpreter: ActionInterpreter,
initial_states: Sequence[InitialStateType],
policy: BasePolicy,
logger: LogWriter | List[LogWriter],
reward: Reward | None = None,
finite_env_t... | Backtest with the parallelism provided by RL framework.
Experimental API. Parameters might change shortly.
Parameters
----------
simulator_fn
Callable receiving initial seed, returning a simulator.
state_interpreter
Interprets the state of simulators.
action_interpreter
... | backtest | python | microsoft/qlib | qlib/rl/trainer/api.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/api.py | MIT |
def on_train_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None:
"""Called when the training ends.
To access all outputs produced during training, cache the data in either trainer and vessel,
and post-process them in this hook.
""" | Called when the training ends.
To access all outputs produced during training, cache the data in either trainer and vessel,
and post-process them in this hook.
| on_train_end | python | microsoft/qlib | qlib/rl/trainer/callbacks.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/callbacks.py | MIT |
def on_iter_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None:
"""Called upon every end of iteration.
This is called **after** the bump of ``current_iter``,
when the previous iteration is considered complete.
""" | Called upon every end of iteration.
This is called **after** the bump of ``current_iter``,
when the previous iteration is considered complete.
| on_iter_end | python | microsoft/qlib | qlib/rl/trainer/callbacks.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/callbacks.py | MIT |
def initialize(self):
"""Initialize the whole training process.
The states here should be synchronized with state_dict.
"""
self.should_stop = False
self.current_iter = 0
self.current_episode = 0
self.current_stage = "train" | Initialize the whole training process.
The states here should be synchronized with state_dict.
| initialize | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def state_dict(self) -> dict:
"""Putting every states of current training into a dict, at best effort.
It doesn't try to handle all the possible kinds of states in the middle of one training collect.
For most cases at the end of each iteration, things should be usually correct.
Note th... | Putting every states of current training into a dict, at best effort.
It doesn't try to handle all the possible kinds of states in the middle of one training collect.
For most cases at the end of each iteration, things should be usually correct.
Note that it's also intended behavior that repla... | state_dict | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def load_state_dict(self, state_dict: dict) -> None:
"""Load all states into current trainer."""
self.vessel.load_state_dict(state_dict["vessel"])
for name, callback in self.named_callbacks().items():
callback.load_state_dict(state_dict["callbacks"][name])
for name, logger in... | Load all states into current trainer. | load_state_dict | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def fit(self, vessel: TrainingVesselBase, ckpt_path: Path | None = None) -> None:
"""Train the RL policy upon the defined simulator.
Parameters
----------
vessel
A bundle of all elements used in training.
ckpt_path
Load a pre-trained / paused training che... | Train the RL policy upon the defined simulator.
Parameters
----------
vessel
A bundle of all elements used in training.
ckpt_path
Load a pre-trained / paused training checkpoint.
| fit | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def test(self, vessel: TrainingVesselBase) -> None:
"""Test the RL policy against the simulator.
The simulator will be fed with data generated in ``test_seed_iterator``.
Parameters
----------
vessel
A bundle of all related elements.
"""
self.vessel =... | Test the RL policy against the simulator.
The simulator will be fed with data generated in ``test_seed_iterator``.
Parameters
----------
vessel
A bundle of all related elements.
| test | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def venv_from_iterator(self, iterator: Iterable[InitialStateType]) -> FiniteVectorEnv:
"""Create a vectorized environment from iterator and the training vessel."""
def env_factory():
# FIXME: state_interpreter and action_interpreter are stateful (having a weakref of env),
# and ... | Create a vectorized environment from iterator and the training vessel. | venv_from_iterator | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def _wrap_context(obj):
"""Make any object a (possibly dummy) context manager."""
if isinstance(obj, AbstractContextManager):
# obj has __enter__ and __exit__
with obj as ctx:
yield ctx
else:
yield obj | Make any object a (possibly dummy) context manager. | _wrap_context | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def _named_collection(seq: Sequence[T]) -> Dict[str, T]:
"""Convert a list into a dict, where each item is named with its type."""
res = {}
retry_cnt: collections.Counter = collections.Counter()
for item in seq:
typename = type(item).__name__.lower()
key = typename if retry_cnt[typename]... | Convert a list into a dict, where each item is named with its type. | _named_collection | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def train(self, vector_env: FiniteVectorEnv) -> Dict[str, Any]:
"""Create a collector and collects ``episode_per_iter`` episodes.
Update the policy on the collected replay buffer.
"""
self.policy.train()
with vector_env.collector_guard():
collector = Collector(
... | Create a collector and collects ``episode_per_iter`` episodes.
Update the policy on the collected replay buffer.
| train | python | microsoft/qlib | qlib/rl/trainer/vessel.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/vessel.py | MIT |
def reset(self, **kwargs: Any) -> ObsType:
"""
Try to get a state from state queue, and init the simulator with this state.
If the queue is exhausted, generate an invalid (nan) observation.
"""
try:
if self.seed_iterator is None:
raise RuntimeError("Y... |
Try to get a state from state queue, and init the simulator with this state.
If the queue is exhausted, generate an invalid (nan) observation.
| reset | python | microsoft/qlib | qlib/rl/utils/env_wrapper.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/env_wrapper.py | MIT |
def step(self, policy_action: PolicyActType, **kwargs: Any) -> Tuple[ObsType, float, bool, InfoDict]:
"""Environment step.
See the code along with comments to get a sequence of things happening here.
"""
if self.seed_iterator is None:
raise RuntimeError("State queue is alre... | Environment step.
See the code along with comments to get a sequence of things happening here.
| step | python | microsoft/qlib | qlib/rl/utils/env_wrapper.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/env_wrapper.py | MIT |
def generate_nan_observation(obs_space: gym.Space) -> Any:
"""The NaN observation that indicates the environment receives no seed.
We assume that obs is complex and there must be something like float.
Otherwise this logic doesn't work.
"""
sample = obs_space.sample()
sample = fill_invalid(samp... | The NaN observation that indicates the environment receives no seed.
We assume that obs is complex and there must be something like float.
Otherwise this logic doesn't work.
| generate_nan_observation | python | microsoft/qlib | qlib/rl/utils/finite_env.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/finite_env.py | MIT |
def collector_guard(self) -> Generator[FiniteVectorEnv, None, None]:
"""Guard the collector. Recommended to guard every collect.
This guard is for two purposes.
1. Catch and ignore the StopIteration exception, which is the stopping signal
thrown by FiniteEnv to let tianshou know tha... | Guard the collector. Recommended to guard every collect.
This guard is for two purposes.
1. Catch and ignore the StopIteration exception, which is the stopping signal
thrown by FiniteEnv to let tianshou know that ``collector.collect()`` should exit.
2. Notify the loggers that the co... | collector_guard | python | microsoft/qlib | qlib/rl/utils/finite_env.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/finite_env.py | MIT |
def vectorize_env(
env_factory: Callable[..., gym.Env],
env_type: FiniteEnvType,
concurrency: int,
logger: LogWriter | List[LogWriter],
) -> FiniteVectorEnv:
"""Helper function to create a vector env. Can be used to replace usual VectorEnv.
For example, once you wrote: ::
DummyVectorEn... | Helper function to create a vector env. Can be used to replace usual VectorEnv.
For example, once you wrote: ::
DummyVectorEnv([lambda: gym.make(task) for _ in range(env_num)])
Now you can replace it with: ::
finite_env_factory(lambda: gym.make(task), "dummy", env_num, my_logger)
By doi... | vectorize_env | python | microsoft/qlib | qlib/rl/utils/finite_env.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/finite_env.py | MIT |
def add_string(self, name: str, string: str, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None:
"""Add a string with name into logged contents."""
if loglevel < self._min_loglevel:
return
if not isinstance(string, str):
raise TypeError(f"{string} is not a string.")
... | Add a string with name into logged contents. | add_string | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def add_scalar(self, name: str, scalar: Any, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None:
"""Add a scalar with name into logged contents.
Scalar will be converted into a float.
"""
if loglevel < self._min_loglevel:
return
if hasattr(scalar, "item"):
... | Add a scalar with name into logged contents.
Scalar will be converted into a float.
| add_scalar | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def add_array(
self,
name: str,
array: np.ndarray | pd.DataFrame | pd.Series,
loglevel: int | LogLevel = LogLevel.PERIODIC,
) -> None:
"""Add an array with name into logging."""
if loglevel < self._min_loglevel:
return
if not isinstance(array, (np... | Add an array with name into logging. | add_array | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def add_any(self, name: str, obj: Any, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None:
"""Log something with any type.
As it's an "any" object, the only LogWriter accepting it is pickle.
Therefore, pickle must be able to serialize it.
"""
if loglevel < self._min_loglevel:... | Log something with any type.
As it's an "any" object, the only LogWriter accepting it is pickle.
Therefore, pickle must be able to serialize it.
| add_any | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def clear(self):
"""Clear all the metrics for a fresh start.
To make the logger instance reusable.
"""
self.episode_count = self.step_count = 0
self.active_env_ids = set() | Clear all the metrics for a fresh start.
To make the logger instance reusable.
| clear | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def state_dict(self) -> dict:
"""Save the states of the logger to a dict."""
return {
"episode_count": self.episode_count,
"step_count": self.step_count,
"global_step": self.global_step,
"global_episode": self.global_episode,
"active_env_ids": ... | Save the states of the logger to a dict. | state_dict | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def load_state_dict(self, state_dict: dict) -> None:
"""Load the states of current logger from a dict."""
self.episode_count = state_dict["episode_count"]
self.step_count = state_dict["step_count"]
self.global_step = state_dict["global_step"]
self.global_episode = state_dict["glo... | Load the states of current logger from a dict. | load_state_dict | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def aggregation(array: Sequence[Any], name: str | None = None) -> Any:
"""Aggregation function from step-wise to episode-wise.
If it's a sequence of float, take the mean.
Otherwise, take the first element.
If a name is specified and,
- if it's ``reward``, the reduction will be... | Aggregation function from step-wise to episode-wise.
If it's a sequence of float, take the mean.
Otherwise, take the first element.
If a name is specified and,
- if it's ``reward``, the reduction will be sum.
| aggregation | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def log_episode(self, length: int, rewards: List[float], contents: List[Dict[str, Any]]) -> None:
"""This is triggered at the end of each trajectory.
Parameters
----------
length
Length of this trajectory.
rewards
A list of rewards at each step of this ep... | This is triggered at the end of each trajectory.
Parameters
----------
length
Length of this trajectory.
rewards
A list of rewards at each step of this episode.
contents
Logged contents for every step.
| log_episode | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def log_step(self, reward: float, contents: Dict[str, Any]) -> None:
"""This is triggered at each step.
Parameters
----------
reward
Reward for this step.
contents
Logged contents for this step.
""" | This is triggered at each step.
Parameters
----------
reward
Reward for this step.
contents
Logged contents for this step.
| log_step | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def on_env_step(self, env_id: int, obs: ObsType, rew: float, done: bool, info: InfoDict) -> None:
"""Callback for finite env, on each step."""
# Update counter
self.global_step += 1
self.step_count += 1
self.active_env_ids.add(env_id)
self.episode_lengths[env_id] += 1
... | Callback for finite env, on each step. | on_env_step | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def episode_metrics(self) -> dict[str, float]:
"""Retrieve the numeric metrics of the latest episode."""
if self._latest_metrics is None:
raise ValueError("No episode metrics available yet.")
return self._latest_metrics | Retrieve the numeric metrics of the latest episode. | episode_metrics | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def __init__(
self,
outer_trade_decision: BaseTradeDecision = None,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
trade_exchange: Exchange = None,
) -> None:
"""
Parameters
----------
outer_trade_decision :... |
Parameters
----------
outer_trade_decision : BaseTradeDecision, optional
the trade decision of outer strategy which this strategy relies, and it will be traded in
[start_time, end_time], by default None
- If the strategy is used to split trade decision, it w... | __init__ | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def reset(
self,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
outer_trade_decision: BaseTradeDecision = None,
**kwargs,
) -> None:
"""
- reset `level_infra`, used to reset trade calendar, .etc
- reset `common_infr... |
- reset `level_infra`, used to reset trade calendar, .etc
- reset `common_infra`, used to reset `trade_account`, `trade_exchange`, .etc
- reset `outer_trade_decision`, used to make split decision
**NOTE**:
split this function into `reset` and `_reset` will make following cases ... | reset | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def _reset(
self,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
outer_trade_decision: BaseTradeDecision = None,
):
"""
Please refer to the docs of `reset`
"""
if level_infra is not None:
self.reset_leve... |
Please refer to the docs of `reset`
| _reset | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def generate_trade_decision(
self,
execute_result: list = None,
) -> Union[BaseTradeDecision, Generator[Any, Any, BaseTradeDecision]]:
"""Generate trade decision in each trading bar
Parameters
----------
execute_result : List[object], optional
the execute... | Generate trade decision in each trading bar
Parameters
----------
execute_result : List[object], optional
the executed result for trade decision, by default None
- When call the generate_trade_decision firstly, `execute_result` could be None
| generate_trade_decision | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def update_trade_decision(
trade_decision: BaseTradeDecision,
trade_calendar: TradeCalendarManager,
) -> Optional[BaseTradeDecision]:
"""
update trade decision in each step of inner execution, this method enable all order
Parameters
----------
trade_decision ... |
update trade decision in each step of inner execution, this method enable all order
Parameters
----------
trade_decision : BaseTradeDecision
the trade decision that will be updated
trade_calendar : TradeCalendarManager
The calendar of the **inner strateg... | update_trade_decision | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def alter_outer_trade_decision(self, outer_trade_decision: BaseTradeDecision) -> BaseTradeDecision:
"""
A method for updating the outer_trade_decision.
The outer strategy may change its decision during updating.
Parameters
----------
outer_trade_decision : BaseTradeDecis... |
A method for updating the outer_trade_decision.
The outer strategy may change its decision during updating.
Parameters
----------
outer_trade_decision : BaseTradeDecision
the decision updated by the outer strategy
Returns
-------
BaseTra... | alter_outer_trade_decision | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def post_upper_level_exe_step(self) -> None:
"""
A hook for doing sth after the upper level executor finished its execution (for example, finalize
the metrics collection).
""" |
A hook for doing sth after the upper level executor finished its execution (for example, finalize
the metrics collection).
| post_upper_level_exe_step | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def post_exe_step(self, execute_result: Optional[list]) -> None:
"""
A hook for doing sth after the corresponding executor finished its execution.
Parameters
----------
execute_result :
the execution result
""" |
A hook for doing sth after the corresponding executor finished its execution.
Parameters
----------
execute_result :
the execution result
| post_exe_step | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def __init__(
self,
policy,
outer_trade_decision: BaseTradeDecision = None,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
**kwargs,
) -> None:
"""
Parameters
----------
policy :
RL polic... |
Parameters
----------
policy :
RL policy for generate action
| __init__ | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def __init__(
self,
policy,
state_interpreter: dict | StateInterpreter,
action_interpreter: dict | ActionInterpreter,
outer_trade_decision: BaseTradeDecision = None,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
**kwar... |
Parameters
----------
state_interpreter : Union[dict, StateInterpreter]
interpreter that interprets the qlib execute result into rl env state
action_interpreter : Union[dict, ActionInterpreter]
interpreter that interprets the rl agent action into qlib order list
... | __init__ | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def download(self, url: str, target_path: [Path, str]):
"""
Download a file from the specified url.
Parameters
----------
url: str
The url of the data.
target_path: str
The location where the data is saved, including the file name.
"""
... |
Download a file from the specified url.
Parameters
----------
url: str
The url of the data.
target_path: str
The location where the data is saved, including the file name.
| download | python | microsoft/qlib | qlib/tests/data.py | https://github.com/microsoft/qlib/blob/master/qlib/tests/data.py | MIT |
def download_data(self, file_name: str, target_dir: [Path, str], delete_old: bool = True):
"""
Download the specified file to the target folder.
Parameters
----------
target_dir: str
data save directory
file_name: str
dataset name, needs to endwit... |
Download the specified file to the target folder.
Parameters
----------
target_dir: str
data save directory
file_name: str
dataset name, needs to endwith .zip, value from [rl_data.zip, csv_data_cn.zip, ...]
may contain folder names, for examp... | download_data | python | microsoft/qlib | qlib/tests/data.py | https://github.com/microsoft/qlib/blob/master/qlib/tests/data.py | MIT |
def qlib_data(
self,
name="qlib_data",
target_dir="~/.qlib/qlib_data/cn_data",
version=None,
interval="1d",
region="cn",
delete_old=True,
exists_skip=False,
):
"""download cn qlib data from remote
Parameters
----------
... | download cn qlib data from remote
Parameters
----------
target_dir: str
data save directory
name: str
dataset name, value from [qlib_data, qlib_data_simple], by default qlib_data
version: str
data version, value from [v1, ...], by default None... | qlib_data | python | microsoft/qlib | qlib/tests/data.py | https://github.com/microsoft/qlib/blob/master/qlib/tests/data.py | MIT |
def robust_zscore(x: pd.Series, zscore=False):
"""Robust ZScore Normalization
Use robust statistics for Z-Score normalization:
mean(x) = median(x)
std(x) = MAD(x) * 1.4826
Reference:
https://en.wikipedia.org/wiki/Median_absolute_deviation.
"""
x = x - x.median()
mad = x... | Robust ZScore Normalization
Use robust statistics for Z-Score normalization:
mean(x) = median(x)
std(x) = MAD(x) * 1.4826
Reference:
https://en.wikipedia.org/wiki/Median_absolute_deviation.
| robust_zscore | python | microsoft/qlib | qlib/utils/data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/data.py | MIT |
def deepcopy_basic_type(obj: object) -> object:
"""
deepcopy an object without copy the complicated objects.
This is useful when you want to generate Qlib tasks and share the handler
NOTE:
- This function can't handle recursive objects!!!!!
Parameters
----------
obj : object
... |
deepcopy an object without copy the complicated objects.
This is useful when you want to generate Qlib tasks and share the handler
NOTE:
- This function can't handle recursive objects!!!!!
Parameters
----------
obj : object
the object to be copied
Returns
-------
... | deepcopy_basic_type | python | microsoft/qlib | qlib/utils/data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/data.py | MIT |
def update_config(base_config: dict, ext_config: Union[dict, List[dict]]):
"""
supporting adding base config based on the ext_config
>>> bc = {"a": "xixi"}
>>> ec = {"b": "haha"}
>>> new_bc = update_config(bc, ec)
>>> print(new_bc)
{'a': 'xixi', 'b': 'haha'}
>>> print(bc) # base config... |
supporting adding base config based on the ext_config
>>> bc = {"a": "xixi"}
>>> ec = {"b": "haha"}
>>> new_bc = update_config(bc, ec)
>>> print(new_bc)
{'a': 'xixi', 'b': 'haha'}
>>> print(bc) # base config should not be changed
{'a': 'xixi'}
>>> print(update_config(bc, {"b": S_D... | update_config | python | microsoft/qlib | qlib/utils/data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/data.py | MIT |
def guess_horizon(label: List):
"""
Try to guess the horizon by parsing label
"""
expr = DatasetProvider.parse_fields(label)[0]
lft_etd, rght_etd = expr.get_extended_window_size()
return rght_etd |
Try to guess the horizon by parsing label
| guess_horizon | python | microsoft/qlib | qlib/utils/data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/data.py | MIT |
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 True, create and return a directory;... | 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 True, create and return a directory; otherwise c&r a file.
| get_or_create_path | python | microsoft/qlib | qlib/utils/file.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/file.py | MIT |
def save_multiple_parts_file(filename, format="gztar"):
"""Save multiple parts file
Implementation process:
1. get the absolute path to 'filename'
2. create a 'filename' directory
3. user does something with file_path('filename/')
4. remove 'filename' directory
5. make_a... | Save multiple parts file
Implementation process:
1. get the absolute path to 'filename'
2. create a 'filename' directory
3. user does something with file_path('filename/')
4. remove 'filename' directory
5. make_archive 'filename' directory, and rename 'archive file' to filen... | save_multiple_parts_file | python | microsoft/qlib | qlib/utils/file.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/file.py | MIT |
def unpack_archive_with_buffer(buffer, format="gztar"):
"""Unpack archive with archive buffer
After the call is finished, the archive file and directory will be deleted.
Implementation process:
1. create 'tempfile' in '~/tmp/' and directory
2. 'buffer' write to 'tempfile'
3. unpack ... | Unpack archive with archive buffer
After the call is finished, the archive file and directory will be deleted.
Implementation process:
1. create 'tempfile' in '~/tmp/' and directory
2. 'buffer' write to 'tempfile'
3. unpack archive file('tempfile')
4. user does something with fi... | unpack_archive_with_buffer | python | microsoft/qlib | qlib/utils/file.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/file.py | MIT |
def get_io_object(file: Union[IO, str, Path], *args, **kwargs) -> IO:
"""
providing a easy interface to get an IO object
Parameters
----------
file : Union[IO, str, Path]
a object representing the file
Returns
-------
IO:
a IO-like object
Raises
------
NotI... |
providing a easy interface to get an IO object
Parameters
----------
file : Union[IO, str, Path]
a object representing the file
Returns
-------
IO:
a IO-like object
Raises
------
NotImplementedError:
| get_io_object | python | microsoft/qlib | qlib/utils/file.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/file.py | MIT |
def concat(data_list: Union[SingleData], axis=0) -> MultiData:
"""concat all SingleData by index.
TODO: now just for SingleData.
Parameters
----------
data_list : List[SingleData]
the list of all SingleData to concat.
Returns
-------
MultiData
the MultiData with ndim ==... | concat all SingleData by index.
TODO: now just for SingleData.
Parameters
----------
data_list : List[SingleData]
the list of all SingleData to concat.
Returns
-------
MultiData
the MultiData with ndim == 2
| concat | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def sum_by_index(data_list: Union[SingleData], new_index: list, fill_value=0) -> SingleData:
"""concat all SingleData by new index.
Parameters
----------
data_list : List[SingleData]
the list of all SingleData to sum.
new_index : list
the new_index of new SingleData.
fill_value ... | concat all SingleData by new index.
Parameters
----------
data_list : List[SingleData]
the list of all SingleData to sum.
new_index : list
the new_index of new SingleData.
fill_value : float
fill the missing values or replace np.nan.
Returns
-------
SingleData
... | sum_by_index | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def _convert_type(self, item):
"""
After user creates indices with Type A, user may query data with other types with the same info.
This method try to make type conversion and make query sane rather than raising KeyError strictly
Parameters
----------
item :
... |
After user creates indices with Type A, user may query data with other types with the same info.
This method try to make type conversion and make query sane rather than raising KeyError strictly
Parameters
----------
item :
The item to query index
| _convert_type | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def index(self, item) -> int:
"""
Given the index value, get the integer index
Parameters
----------
item :
The item to query
Returns
-------
int:
The index of the item
Raises
------
KeyError:
... |
Given the index value, get the integer index
Parameters
----------
item :
The item to query
Returns
-------
int:
The index of the item
Raises
------
KeyError:
If the query item does not exist
| index | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def sort(self) -> Tuple["Index", np.ndarray]:
"""
sort the index
Returns
-------
Tuple["Index", np.ndarray]:
the sorted Index and the changed index
"""
sorted_idx = np.argsort(self.idx_list)
idx = Index(self.idx_list[sorted_idx])
idx._... |
sort the index
Returns
-------
Tuple["Index", np.ndarray]:
the sorted Index and the changed index
| sort | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def proc_idx_l(indices: List[Union[List, pd.Index, Index]], data_shape: Tuple = None) -> List[Index]:
"""process the indices from user and output a list of `Index`"""
res = []
for i, idx in enumerate(indices):
res.append(Index(data_shape[i] if len(idx) == 0 else idx))
return ... | process the indices from user and output a list of `Index` | proc_idx_l | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def _slc_convert(self, index: Index, indexing: slice) -> slice:
"""
convert value-based indexing to integer-based indexing.
Parameters
----------
index : Index
index data.
indexing : slice
value based indexing data with slice type for indexing.
... |
convert value-based indexing to integer-based indexing.
Parameters
----------
index : Index
index data.
indexing : slice
value based indexing data with slice type for indexing.
Returns
-------
slice:
the integer based... | _slc_convert | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def __getitem__(self, indexing):
"""
Parameters
----------
indexing :
query for data
Raises
------
KeyError:
If the non-slice index is queried but does not exist, `KeyError` is raised.
"""
# 1) convert slices to int loc
... |
Parameters
----------
indexing :
query for data
Raises
------
KeyError:
If the non-slice index is queried but does not exist, `KeyError` is raised.
| __getitem__ | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def index_data_ops_creator(*args, **kwargs):
"""
meta class for auto generating operations for index data.
"""
for method_name in ["__add__", "__sub__", "__rsub__", "__mul__", "__truediv__", "__eq__", "__gt__", "__lt__"]:
args[2][method_name] = BinaryOps(method_name=method_name)
return type(... |
meta class for auto generating operations for index data.
| index_data_ops_creator | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def abs(self):
"""get the abs of data except np.nan."""
tmp_data = np.absolute(self.data)
return self.__class__(tmp_data, *self.indices) | get the abs of data except np.nan. | abs | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def __init__(
self, data: Union[int, float, np.number, list, dict, pd.Series] = [], index: Union[List, pd.Index, Index] = []
):
"""A data structure of index and numpy data.
It's used to replace pd.Series due to high-speed.
Parameters
----------
data : Union[int, floa... | A data structure of index and numpy data.
It's used to replace pd.Series due to high-speed.
Parameters
----------
data : Union[int, float, np.number, list, dict, pd.Series]
the input data
index : Union[list, pd.Index]
the index of data.
empty ... | __init__ | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def reindex(self, index: Index, fill_value=np.nan) -> SingleData:
"""reindex data and fill the missing value with np.nan.
Parameters
----------
new_index : list
new index
fill_value:
what value to fill if index is missing
Returns
-------
... | reindex data and fill the missing value with np.nan.
Parameters
----------
new_index : list
new index
fill_value:
what value to fill if index is missing
Returns
-------
SingleData
reindex data
| reindex | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def __init__(
self,
data: Union[int, float, np.number, list] = [],
index: Union[List, pd.Index, Index] = [],
columns: Union[List, pd.Index, Index] = [],
):
"""A data structure of index and numpy data.
It's used to replace pd.DataFrame due to high-speed.
Param... | A data structure of index and numpy data.
It's used to replace pd.DataFrame due to high-speed.
Parameters
----------
data : Union[list, np.ndarray]
the dim of data must be 2.
index : Union[List, pd.Index, Index]
the index of data.
columns: Union[L... | __init__ | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def get_module_by_module_path(module_path: Union[str, ModuleType]):
"""Load module path
:param module_path:
:return:
:raises: ModuleNotFoundError
"""
if module_path is None:
raise ModuleNotFoundError("None is passed in as parameters as module_path")
if isinstance(module_path, Modul... | Load module path
:param module_path:
:return:
:raises: ModuleNotFoundError
| get_module_by_module_path | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
def split_module_path(module_path: str) -> Tuple[str, str]:
"""
Parameters
----------
module_path : str
e.g. "a.b.c.ClassName"
Returns
-------
Tuple[str, str]
e.g. ("a.b.c", "ClassName")
"""
*m_path, cls = module_path.split(".")
m_path = ".".join(m_path)
ret... |
Parameters
----------
module_path : str
e.g. "a.b.c.ClassName"
Returns
-------
Tuple[str, str]
e.g. ("a.b.c", "ClassName")
| split_module_path | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
def get_callable_kwargs(config: InstConf, default_module: Union[str, ModuleType] = None) -> (type, dict):
"""
extract class/func and kwargs from config info
Parameters
----------
config : [dict, str]
similar to config
please refer to the doc of init_instance_by_config
default_m... |
extract class/func and kwargs from config info
Parameters
----------
config : [dict, str]
similar to config
please refer to the doc of init_instance_by_config
default_module : Python module or str
It should be a python module to load the class type
This function wi... | get_callable_kwargs | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
def init_instance_by_config(
config: InstConf,
default_module=None,
accept_types: Union[type, Tuple[type]] = (),
try_kwargs: Dict = {},
**kwargs,
) -> Any:
"""
get initialized instance with config
Parameters
----------
config : InstConf
default_module : Python module
... |
get initialized instance with config
Parameters
----------
config : InstConf
default_module : Python module
Optional. It should be a python module.
NOTE: the "module_path" will be override by `module` arguments
This function will load class from the config['module_path'] ... | init_instance_by_config | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
def class_casting(obj: object, cls: type):
"""
Python doesn't provide the downcasting mechanism.
We use the trick here to downcast the class
Parameters
----------
obj : object
the object to be cast
cls : type
the target class type
"""
orig_cls = obj.__class__
obj... |
Python doesn't provide the downcasting mechanism.
We use the trick here to downcast the class
Parameters
----------
obj : object
the object to be cast
cls : type
the target class type
| class_casting | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
def find_all_classes(module_path: Union[str, ModuleType], cls: type) -> List[type]:
"""
Find all the classes recursively that inherit from `cls` in a given module.
- `cls` itself is also included
>>> from qlib.data.dataset.handler import DataHandler
>>> find_all_classes("qlib.contrib.data.h... |
Find all the classes recursively that inherit from `cls` in a given module.
- `cls` itself is also included
>>> from qlib.data.dataset.handler import DataHandler
>>> find_all_classes("qlib.contrib.data.handler", DataHandler)
[<class 'qlib.contrib.data.handler.Alpha158'>, <class 'qlib.c... | find_all_classes | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
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 :
DataFrame for processing
apply_fu... | datetime_groupby_apply
This function will apply the `apply_func` on the datetime level index.
Parameters
----------
df :
DataFrame for processing
apply_func : Union[Callable, Text]
apply_func for processing the data
if a string is given, then it is treated as naive pandas fu... | datetime_groupby_apply | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
def _replace_and_get_dt(complex_iter):
"""_replace_and_get_dt.
FIXME: this function may cause infinite loop when the complex data-structure contains loop-reference
Parameters
----------
complex_iter :
complex_iter
"""
if isinstance(complex_iter, DelayedTask):
dt = complex_i... | _replace_and_get_dt.
FIXME: this function may cause infinite loop when the complex data-structure contains loop-reference
Parameters
----------
complex_iter :
complex_iter
| _replace_and_get_dt | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
def _recover_dt(complex_iter):
"""_recover_dt.
replace all the DelayedTask in the `complex_iter` with its `.res` value
FIXME: this function may cause infinite loop when the complex data-structure contains loop-reference
Parameters
----------
complex_iter :
complex_iter
"""
if ... | _recover_dt.
replace all the DelayedTask in the `complex_iter` with its `.res` value
FIXME: this function may cause infinite loop when the complex data-structure contains loop-reference
Parameters
----------
complex_iter :
complex_iter
| _recover_dt | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
def complex_parallel(paral: Parallel, complex_iter):
"""complex_parallel.
Find all the delayed function created by delayed in complex_iter, run them parallelly and then replace it with the result
>>> from qlib.utils.paral import complex_parallel
>>> from joblib import Parallel, delayed
>>> complex_... | complex_parallel.
Find all the delayed function created by delayed in complex_iter, run them parallelly and then replace it with the result
>>> from qlib.utils.paral import complex_parallel
>>> from joblib import Parallel, delayed
>>> complex_iter = {"a": delayed(sum)([1,2,3]), "b": [1, 2, delayed(sum)... | complex_parallel | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
def __init__(self, func: Callable, qlib_config: QlibConfig = None):
"""
Parameters
----------
func : Callable
the function to be wrapped
qlib_config : QlibConfig
Qlib config for initialization in subprocess
Returns
-------
Callabl... |
Parameters
----------
func : Callable
the function to be wrapped
qlib_config : QlibConfig
Qlib config for initialization in subprocess
Returns
-------
Callable
| __init__ | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
def _func_mod(self, *args, **kwargs):
"""Modify the initial function by adding Qlib initialization"""
if self.qlib_config is not None:
C.register_from_C(self.qlib_config)
return self.func(*args, **kwargs) | Modify the initial function by adding Qlib initialization | _func_mod | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
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 the calendar in each day.
P... |
Resample the calendar with frequency freq_raw into the calendar with frequency freq_sam
Assumption:
- Fix length (240) of the calendar in each day.
Parameters
----------
calendar_raw : np.ndarray
The calendar with frequency freq_raw
freq_raw : str
Frequency of the raw ... | resam_calendar | python | microsoft/qlib | qlib/utils/resam.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/resam.py | MIT |
def get_higher_eq_freq_feature(instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1):
"""get the feature with higher or equal frequency than `freq`.
Returns
-------
pd.DataFrame
the feature with higher or equal frequency
"""
from ..data.data import D # pylint: ... | get the feature with higher or equal frequency than `freq`.
Returns
-------
pd.DataFrame
the feature with higher or equal frequency
| get_higher_eq_freq_feature | python | microsoft/qlib | qlib/utils/resam.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/resam.py | MIT |
def resam_ts_data(
ts_feature: Union[pd.DataFrame, pd.Series],
start_time: Union[str, pd.Timestamp] = None,
end_time: Union[str, pd.Timestamp] = None,
method: Union[str, Callable] = "last",
method_kwargs: dict = {},
):
"""
Resample value from time-series data
- If `feature` has Mult... |
Resample value from time-series data
- If `feature` has MultiIndex[instrument, datetime], apply the `method` to each instruemnt data with datetime in [start_time, end_time]
Example:
.. code-block::
print(feature)
$close ... | resam_ts_data | python | microsoft/qlib | qlib/utils/resam.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/resam.py | MIT |
def _ts_data_valid(ts_feature, last=False):
"""get the first/last not nan value of pd.Series|DataFrame with single level index"""
if isinstance(ts_feature, pd.DataFrame):
return ts_feature.apply(lambda column: get_valid_value(column, last=last))
elif isinstance(ts_feature, pd.Series):
return... | get the first/last not nan value of pd.Series|DataFrame with single level index | _ts_data_valid | python | microsoft/qlib | qlib/utils/resam.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/resam.py | MIT |
def _get_attr_list(self, attr_type: str) -> list:
"""
What attribute will not be in specific list
Parameters
----------
attr_type : str
"include" or "exclude"
Returns
-------
list:
"""
if hasattr(self, f"_{attr_type}"):
... |
What attribute will not be in specific list
Parameters
----------
attr_type : str
"include" or "exclude"
Returns
-------
list:
| _get_attr_list | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
def config(self, recursive=False, **kwargs):
"""
configure the serializable object
Parameters
----------
kwargs may include following keys
dump_all : bool
will the object dump all object
exclude : list
What attribute will ... |
configure the serializable object
Parameters
----------
kwargs may include following keys
dump_all : bool
will the object dump all object
exclude : list
What attribute will not be dumped
include : list
... | config | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
def to_pickle(self, path: Union[Path, str], **kwargs):
"""
Dump self to a pickle file.
path (Union[Path, str]): the path to dump
kwargs may include following keys
dump_all : bool
will the object dump all object
exclude : list
Wha... |
Dump self to a pickle file.
path (Union[Path, str]): the path to dump
kwargs may include following keys
dump_all : bool
will the object dump all object
exclude : list
What attribute will not be dumped
include : list
... | to_pickle | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
def load(cls, filepath):
"""
Load the serializable class from a filepath.
Args:
filepath (str): the path of file
Raises:
TypeError: the pickled file must be `type(cls)`
Returns:
`type(cls)`: the instance of `type(cls)`
"""
wi... |
Load the serializable class from a filepath.
Args:
filepath (str): the path of file
Raises:
TypeError: the pickled file must be `type(cls)`
Returns:
`type(cls)`: the instance of `type(cls)`
| load | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
def get_backend(cls):
"""
Return the real backend of a Serializable class. The pickle_backend value can be "pickle" or "dill".
Returns:
module: pickle or dill module based on pickle_backend
"""
# NOTE: pickle interface like backend; such as dill
if cls.pickle... |
Return the real backend of a Serializable class. The pickle_backend value can be "pickle" or "dill".
Returns:
module: pickle or dill module based on pickle_backend
| get_backend | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
def general_dump(obj, path: Union[Path, str]):
"""
A general dumping method for object
Parameters
----------
obj : object
the object to be dumped
path : Union[Path, str]
the target path the data will be dumped
"""
path = Path(path)... |
A general dumping method for object
Parameters
----------
obj : object
the object to be dumped
path : Union[Path, str]
the target path the data will be dumped
| general_dump | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
def get_min_cal(shift: int = 0, region: str = REG_CN) -> List[time]:
"""
get the minute level calendar in day period
Parameters
----------
shift : int
the shift direction would be like pandas shift.
series.shift(1) will replace the value at `i`-th with the one at `i-1`-th
region... |
get the minute level calendar in day period
Parameters
----------
shift : int
the shift direction would be like pandas shift.
series.shift(1) will replace the value at `i`-th with the one at `i-1`-th
region: str
Region, for example, "cn", "us"
Returns
-------
L... | get_min_cal | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
def is_single_value(start_time, end_time, freq, region: str = REG_CN):
"""Is there only one piece of data for stock market.
Parameters
----------
start_time : Union[pd.Timestamp, str]
closed start time for data.
end_time : Union[pd.Timestamp, str]
closed end time for data.
freq ... | Is there only one piece of data for stock market.
Parameters
----------
start_time : Union[pd.Timestamp, str]
closed start time for data.
end_time : Union[pd.Timestamp, str]
closed end time for data.
freq :
region: str
Region, for example, "cn", "us"
Returns
----... | is_single_value | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
def parse(freq: str) -> Tuple[int, str]:
"""
Parse freq into a unified format
Parameters
----------
freq : str
Raw freq, supported freq should match the re '^([0-9]*)(month|mon|week|w|day|d|minute|min)$'
Returns
-------
freq: Tuple[int, str]
... |
Parse freq into a unified format
Parameters
----------
freq : str
Raw freq, supported freq should match the re '^([0-9]*)(month|mon|week|w|day|d|minute|min)$'
Returns
-------
freq: Tuple[int, str]
Unified freq, including freq count and u... | parse | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
def get_min_delta(left_frq: str, right_freq: str):
"""Calculate freq delta
Parameters
----------
left_frq: str
right_freq: str
Returns
-------
"""
minutes_map = {
Freq.NORM_FREQ_MINUTE: 1,
Freq.NORM_FREQ_DAY: 60 * 24,
... | Calculate freq delta
Parameters
----------
left_frq: str
right_freq: str
Returns
-------
| get_min_delta | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
def get_recent_freq(base_freq: Union[str, "Freq"], freq_list: List[Union[str, "Freq"]]) -> Optional["Freq"]:
"""Get the closest freq to base_freq from freq_list
Parameters
----------
base_freq
freq_list
Returns
-------
if the recent frequency is found
... | Get the closest freq to base_freq from freq_list
Parameters
----------
base_freq
freq_list
Returns
-------
if the recent frequency is found
Freq
else:
None
| get_recent_freq | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
def get_day_min_idx_range(start: str, end: str, freq: str, region: str) -> Tuple[int, int]:
"""
get the min-bar index in a day for a time range (both left and right is closed) given a fixed frequency
Parameters
----------
start : str
e.g. "9:30"
end : str
e.g. "14:30"
freq : ... |
get the min-bar index in a day for a time range (both left and right is closed) given a fixed frequency
Parameters
----------
start : str
e.g. "9:30"
end : str
e.g. "14:30"
freq : str
"1min"
Returns
-------
Tuple[int, int]:
The index of start and end... | get_day_min_idx_range | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
def cal_sam_minute(x: pd.Timestamp, sam_minutes: int, region: str = REG_CN) -> pd.Timestamp:
"""
align the minute-level data to a down sampled calendar
e.g. align 10:38 to 10:35 in 5 minute-level(10:30 in 10 minute-level)
Parameters
----------
x : pd.Timestamp
datetime to be aligned
... |
align the minute-level data to a down sampled calendar
e.g. align 10:38 to 10:35 in 5 minute-level(10:30 in 10 minute-level)
Parameters
----------
x : pd.Timestamp
datetime to be aligned
sam_minutes : int
align to `sam_minutes` minute-level calendar
region: str
Reg... | cal_sam_minute | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
def epsilon_change(date_time: pd.Timestamp, direction: str = "backward") -> pd.Timestamp:
"""
change the time by infinitely small quantity.
Parameters
----------
date_time : pd.Timestamp
the original time
direction : str
the direction the time are going to
- "backward" ... |
change the time by infinitely small quantity.
Parameters
----------
date_time : pd.Timestamp
the original time
direction : str
the direction the time are going to
- "backward" for going to history
- "forward" for going to the future
Returns
-------
pd.... | epsilon_change | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
def get_period_list(first: int, last: int, quarterly: bool) -> List[int]:
"""
This method will be used in PIT database.
It return all the possible values between `first` and `end` (first and end is included)
Parameters
----------
quarterly : bool
will it return quarterly index or yearl... |
This method will be used in PIT database.
It return all the possible values between `first` and `end` (first and end is included)
Parameters
----------
quarterly : bool
will it return quarterly index or yearly index.
Returns
-------
List[int]
the possible index betwee... | get_period_list | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
def read_period_data(
index_path,
data_path,
period,
cur_date_int: int,
quarterly,
last_period_index: int = None,
):
"""
At `cur_date`(e.g. 20190102), read the information at `period`(e.g. 201803).
Only the updating info before cur_date or at cur_date will be used.
Parameters
... |
At `cur_date`(e.g. 20190102), read the information at `period`(e.g. 201803).
Only the updating info before cur_date or at cur_date will be used.
Parameters
----------
period: int
date period represented by interger, e.g. 201901 corresponds to the first quarter in 2019
cur_date_int: int... | read_period_data | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
def np_ffill(arr: np.array):
"""
forward fill a 1D numpy array
Parameters
----------
arr : np.array
Input numpy 1D array
"""
mask = np.isnan(arr.astype(float)) # np.isnan only works on np.float
# get fill index
idx = np.where(~mask, np.arange(mask.shape[0]), 0)
np.maxim... |
forward fill a 1D numpy array
Parameters
----------
arr : np.array
Input numpy 1D array
| np_ffill | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
def lower_bound(data, val, level=0):
"""multi fields list lower bound.
for single field list use `bisect.bisect_left` instead
"""
left = 0
right = len(data)
while left < right:
mid = (left + right) // 2
if val <= data[mid][level]:
right = mid
else:
... | multi fields list lower bound.
for single field list use `bisect.bisect_left` instead
| lower_bound | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
def upper_bound(data, val, level=0):
"""multi fields list upper bound.
for single field list use `bisect.bisect_right` instead
"""
left = 0
right = len(data)
while left < right:
mid = (left + right) // 2
if val >= data[mid][level]:
left = mid + 1
else:
... | multi fields list upper bound.
for single field list use `bisect.bisect_right` instead
| upper_bound | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
def compare_dict_value(src_data: dict, dst_data: dict):
"""Compare dict value
:param src_data:
:param dst_data:
:return:
"""
class DateEncoder(json.JSONEncoder):
# FIXME: This class can only be accurate to the day. If it is a minute,
# there may be a bug
def default(sel... | Compare dict value
:param src_data:
:param dst_data:
:return:
| compare_dict_value | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.