id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
19,576
import fire import pandas as pd import pathlib import qlib import logging from ...data import D from ...log import get_module_logger from ...utils import get_pre_trading_date, is_tradable_date from ..evaluate import risk_analysis from ..backtest.backtest import update_account from .manager import UserManager from .util...
null
19,577
import numpy as np import pandas as pd from datetime import datetime from qlib.data.cache import H from qlib.data.data import Cal from qlib.data.ops import ElemOperator, PairOperator from qlib.utils.time import time_to_day_index H = MemCache() Cal: CalendarProviderWrapper = Wrapper() The provided code snippet includ...
Load High-Freq Calendar Date Using Memcache. !!!NOTE: Loading the calendar is quite slow. So loading calendar before start multiprocessing will make it faster. Parameters ---------- freq : str frequency of read calendar file. future : bool whether including future trading day. Returns ------- _calendar: array of date.
19,578
import numpy as np import pandas as pd from datetime import datetime from qlib.data.cache import H from qlib.data.data import Cal from qlib.data.ops import ElemOperator, PairOperator from qlib.utils.time import time_to_day_index H = MemCache() Cal: CalendarProviderWrapper = Wrapper() The provided code snippet includ...
Load High-Freq Calendar Minute Using Memcache
19,579
import matplotlib.pyplot as plt import pandas as pd The provided code snippet includes necessary dependencies for implementing the `sub_fig_generator` function. Write a Python function `def sub_fig_generator(sub_fs=(3, 3), col_n=10, row_n=1, wspace=None, hspace=None, sharex=False, sharey=False)` to solve the following...
sub_fig_generator. it will return a generator, each row contains <col_n> sub graph FIXME: Known limitation: - The last row will not be plotted automatically, please plot it outside the function Parameters ---------- sub_fs : the figure size of each subgraph in <col_n> * <row_n> subgraphs col_n : the number of subgraph ...
19,580
from functools import partial import pandas as pd import plotly.graph_objs as go import statsmodels.api as sm import matplotlib.pyplot as plt from scipy import stats from typing import Sequence from qlib.typehint import Literal from ..graph import ScatterGraph, SubplotsGraph, BarGraph, HeatmapGraph from ..utils import ...
:param pred_label: :param reverse: :param N: :return:
19,581
from functools import partial import pandas as pd import plotly.graph_objs as go import statsmodels.api as sm import matplotlib.pyplot as plt from scipy import stats from typing import Sequence from qlib.typehint import Literal from ..graph import ScatterGraph, SubplotsGraph, BarGraph, HeatmapGraph from ..utils import ...
:param pred_label: pd.DataFrame must contain one column of realized return with name `label` and one column of predicted score names `score`. :param methods: Sequence[Literal["IC", "Rank IC"]] IC series to plot. IC is sectional pearson correlation between label and score Rank IC is the spearman correlation between labe...
19,582
from functools import partial import pandas as pd import plotly.graph_objs as go import statsmodels.api as sm import matplotlib.pyplot as plt from scipy import stats from typing import Sequence from qlib.typehint import Literal from ..graph import ScatterGraph, SubplotsGraph, BarGraph, HeatmapGraph from ..utils import ...
null
19,583
from functools import partial import pandas as pd import plotly.graph_objs as go import statsmodels.api as sm import matplotlib.pyplot as plt from scipy import stats from typing import Sequence from qlib.typehint import Literal from ..graph import ScatterGraph, SubplotsGraph, BarGraph, HeatmapGraph from ..utils import ...
null
19,584
from functools import partial import pandas as pd import plotly.graph_objs as go import statsmodels.api as sm import matplotlib.pyplot as plt from scipy import stats from typing import Sequence from qlib.typehint import Literal from ..graph import ScatterGraph, SubplotsGraph, BarGraph, HeatmapGraph from ..utils import ...
r"""Model performance :param pred_label: index is **pd.MultiIndex**, index name is **[instrument, datetime]**; columns names is **[score, label]**. It is usually same as the label of model training(e.g. "Ref($close, -2)/Ref($close, -1) - 1"). .. code-block:: python instrument datetime score label SH600004 2017-12-11 -0...
19,585
import copy from typing import Iterable import pandas as pd import plotly.graph_objs as go from ..graph import BaseGraph, SubplotsGraph from ..analysis_position.parse_position import get_position_data def _get_figure_with_position( position: dict, report_normal: pd.DataFrame, label_data: pd.DataFrame, s...
Backtest buy, sell, and holding cumulative return graph Example: .. code-block:: python from qlib.data import D from qlib.contrib.evaluate import risk_analysis, backtest, long_short_backtest from qlib.contrib.strategy import TopkDropoutStrategy # backtest parameters bparas = {} bparas['limit_threshold'] = 0.095 bparas[...
19,586
import copy from typing import Iterable import pandas as pd import plotly.graph_objs as go from ..graph import ScatterGraph from ..analysis_position.parse_position import get_position_data def _get_figure_with_position( position: dict, label_data: pd.DataFrame, start_date=None, end_date=None ) -> Iterable[go.Figure...
Ranking percentage of stocks buy, sell, and holding on the trading day. Average rank-ratio(similar to **sell_df['label'].rank(ascending=False) / len(sell_df)**) of daily trading Example: .. code-block:: python from qlib.data import D from qlib.contrib.evaluate import backtest from qlib.contrib.strategy import TopkDropo...
19,587
import pandas as pd from ..graph import SubplotsGraph, BaseGraph def _report_figure(df: pd.DataFrame) -> [list, tuple]: """ :param df: :return: """ # Get data report_df = _calculate_report_data(df) # Maximum Drawdown max_start_date, max_end_date = _calculate_maximum(report_df) ex_max...
display backtest report Example: .. code-block:: python import qlib import pandas as pd from qlib.utils.time import Freq from qlib.utils import flatten_dict from qlib.backtest import backtest, executor from qlib.contrib.evaluate import risk_analysis from qlib.contrib.strategy import TopkDropoutStrategy # init qlib qlib...
19,588
from typing import Iterable import pandas as pd import plotly.graph_objs as py from ...evaluate import risk_analysis from ..graph import SubplotsGraph, ScatterGraph def _get_risk_analysis_figure(analysis_df: pd.DataFrame) -> Iterable[py.Figure]: """Get analysis graph figure :param analysis_df: :return: ...
Generate analysis graph and monthly analysis Example: .. code-block:: python import qlib import pandas as pd from qlib.utils.time import Freq from qlib.utils import flatten_dict from qlib.backtest import backtest, executor from qlib.contrib.evaluate import risk_analysis from qlib.contrib.strategy import TopkDropoutStra...
19,589
import pandas as pd from ..graph import ScatterGraph from ..utils import guess_plotly_rangebreaks def _get_score_ic(pred_label: pd.DataFrame): """ :param pred_label: :return: """ concat_data = pred_label.copy() concat_data.dropna(axis=0, how="any", inplace=True) _ic = concat_data.groupby(lev...
score IC Example: .. code-block:: python from qlib.data import D from qlib.contrib.report import analysis_position pred_df_dates = pred_df.index.get_level_values(level='datetime') features_df = D.features(D.instruments('csi500'), ['Ref($close, -2)/Ref($close, -1)-1'], pred_df_dates.min(), pred_df_dates.max()) features_...
19,590
import numpy as np import torch from torch import nn from qlib.constant import EPS from qlib.log import get_module_logger The provided code snippet includes necessary dependencies for implementing the `preds_to_weight_with_clamp` function. Write a Python function `def preds_to_weight_with_clamp(preds, clip_weight=None...
Clip the weights. Parameters ---------- clip_weight: float The clip threshold. clip_method: str The clip method. Current available: "clamp", "tanh", and "sigmoid".
19,591
import pandas as pd from typing import Tuple from qlib import get_module_logger from qlib.utils.paral import complex_parallel, DelayedDict from joblib import Parallel, delayed The provided code snippet includes necessary dependencies for implementing the `calc_long_short_prec` function. Write a Python function `def ca...
calculate the precision for long and short operation :param pred/label: index is **pd.MultiIndex**, index name is **[datetime, instruments]**; columns names is **[score]**. .. code-block:: python score datetime instrument 2020-12-01 09:30:00 SH600068 0.553634 SH600195 0.550017 SH600276 0.540321 SH600584 0.517297 SH6007...
19,592
import pandas as pd from typing import Tuple from qlib import get_module_logger from qlib.utils.paral import complex_parallel, DelayedDict from joblib import Parallel, delayed The provided code snippet includes necessary dependencies for implementing the `calc_long_short_return` function. Write a Python function `def ...
calculate long-short return Note: `label` must be raw stock returns. Parameters ---------- pred : pd.Series stock predictions label : pd.Series stock returns date_col : str datetime index name quantile : float long-short quantile Returns ---------- long_short_r : pd.Series daily long-short returns long_avg_r : pd.Serie...
19,593
import pandas as pd from typing import Tuple from qlib import get_module_logger from qlib.utils.paral import complex_parallel, DelayedDict from joblib import Parallel, delayed def pred_autocorr(pred: pd.Series, lag=1, inst_col="instrument", date_col="datetime"): """pred_autocorr. Limitation: - If the dateti...
calculate auto correlation for pred_dict Parameters ---------- pred_dict : dict A dict like {<method_name>: <prediction>} kwargs : all these arguments will be passed into pred_autocorr
19,594
import pandas as pd from typing import Tuple from qlib import get_module_logger from qlib.utils.paral import complex_parallel, DelayedDict from joblib import Parallel, delayed def calc_ic(pred: pd.Series, label: pd.Series, date_col="datetime", dropna=False) -> (pd.Series, pd.Series): """calc_ic. Parameters ...
calc_all_ic. Parameters ---------- pred_dict_all : A dict like {<method_name>: <prediction>} label: A pd.Series of label values Returns ------- {'Q2+IND_z': {'ic': <ic series like> 2016-01-04 -0.057407 ... 2020-05-28 0.183470 2020-05-29 0.171393 'ric': <rank ic series like> 2016-01-04 -0.040888 ... 2020-05-28 0.236665 ...
19,595
import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `count_parameters` function. Write a Python function `def count_parameters(models_or_parameters, unit="m")` to solve the following problem: This function is to obtain the storage size unit of a (or multiple) models. Pa...
This function is to obtain the storage size unit of a (or multiple) models. Parameters ---------- models_or_parameters : PyTorch model(s) or a list of parameters. unit : the storage size unit. Returns ------- The number of parameters of the given model(s) or parameters.
19,596
import os from torch.utils.data import Dataset, DataLoader import copy from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function from qlib.contrib.model.pytorch_utils import cou...
null
19,597
import os from torch.utils.data import Dataset, DataLoader import copy from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function from qlib.contrib.model.pytorch_utils import cou...
null
19,598
import os from torch.utils.data import Dataset, DataLoader import copy from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function from qlib.contrib.model.pytorch_utils import cou...
null
19,599
import os from torch.utils.data import Dataset, DataLoader import copy from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function from qlib.contrib.model.pytorch_utils import cou...
null
19,600
import os from torch.utils.data import Dataset, DataLoader import copy from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function from qlib.contrib.model.pytorch_utils import cou...
null
19,601
import os from torch.utils.data import Dataset, DataLoader import copy from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function from qlib.contrib.model.pytorch_utils import cou...
null
19,602
import os from torch.utils.data import Dataset, DataLoader import copy from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function from qlib.contrib.model.pytorch_utils import cou...
null
19,603
import os from torch.utils.data import Dataset, DataLoader import copy from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function from qlib.contrib.model.pytorch_utils import cou...
null
19,604
import os from torch.utils.data import Dataset, DataLoader import copy from typing import Text, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Function from qlib.contrib.model.pytorch_utils import cou...
null
19,605
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from typing import Text, Union import copy from ...utils import get_or_create_path from ...log import get_module_logger import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional a...
null
19,606
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd import copy import math from ...utils import get_or_create_path from ...log import get_module_logger import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from .....
null
19,607
import io import os import copy import math import json import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from tqdm import tqdm from qlib.constant import EPS from qlib.log import get_module_logger from ql...
null
19,608
import io import os import copy import math import json import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F try: from torch.utils.tensorboard import SummaryWriter except ImportError: SummaryWriter =...
sample-wise transport Args: all_preds (torch.Tensor): predictions from all predictors, [sample x states] label (torch.Tensor): label, [sample] choice (torch.Tensor): gumbel softmax choice, [sample x states] prob (torch.Tensor): router predicted probility, [sample x states] hist_loss (torch.Tensor): history loss matrix,...
19,609
import io import os import copy import math import json import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F try: from torch.utils.tensorboard import SummaryWriter except ImportError: SummaryWriter =...
daily transport Args: all_preds (torch.Tensor): predictions from all predictors, [sample x states] label (torch.Tensor): label, [sample] choice (torch.Tensor): gumbel softmax choice, [days x states] prob (torch.Tensor): router predicted probility, [days x states] hist_loss (torch.Tensor): history loss matrix, [days x s...
19,610
import io import os import copy import math import json import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from tqdm import tqdm from qlib.constant import EPS from qlib.log import get_module_logger from ql...
Load state dict to provided model while ignore exceptions.
19,611
import io import os import copy import math import json import numpy as np import pandas as pd import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from tqdm import tqdm from qlib.constant import EPS from qlib.log import get_module_logger from ql...
null
19,612
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from typing import Text, Union import copy import math from ...utils import get_or_create_path from ...log import get_module_logger import torch import torch.nn as nn import torch.optim as optim from ...model.ba...
null
19,613
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from scipy.stats import spearmanr, pearsonr from ..data import D from collections import OrderedDict def get_position_list_value(positions): # generate instrument list and date for whole poitions instrum...
Parameters generate daily return series from position view positions: positions generated by strategy init_asset_value : init asset value return: pd.Series of daily return , return_series[date] = daily return rate
19,614
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from scipy.stats import spearmanr, pearsonr from ..data import D from collections import OrderedDict def get_position_value(evaluate_date, position): """sum of close*amount get value of position use ...
Annualized Returns p_r = (p_end / p_start)^{(250/n)} - 1 p_r annual return p_end final value p_start init value n days of backtest
19,615
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from scipy.stats import spearmanr, pearsonr from ..data import D from collections import OrderedDict def get_annaul_return_from_return_series(r, method="ci"): """Risk Analysis from daily return series Pa...
Risk Analysis Parameters ---------- r : pandas.Series daily return series method : str interest calculation method, ci(compound interest)/si(simple interest) risk_free_rate : float risk_free_rate, default as 0.00, can set as 0.03 etc
19,616
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from scipy.stats import spearmanr, pearsonr from ..data import D from collections import OrderedDict The provided code snippet includes necessary dependencies for implementing the `get_max_drawdown_from_series`...
Risk Analysis from asset value cumprod way Parameters ---------- r : pandas.Series daily return series
19,617
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from scipy.stats import spearmanr, pearsonr from ..data import D from collections import OrderedDict def get_turnover_rate(): # in backtest pass
null
19,618
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from scipy.stats import spearmanr, pearsonr from ..data import D from collections import OrderedDict def get_annaul_return_from_return_series(r, method="ci"): """Risk Analysis from daily return series Pa...
null
19,619
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from scipy.stats import spearmanr, pearsonr from ..data import D from collections import OrderedDict def get_volatility_from_series(r): return r.std(ddof=1)
null
19,620
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from scipy.stats import spearmanr, pearsonr from ..data import D from collections import OrderedDict The provided code snippet includes necessary dependencies for implementing the `get_rank_ic` function. Write ...
Rank IC Parameters ---------- r : pandas.Series daily score series of feature b : pandas.Series daily return series
19,621
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from scipy.stats import spearmanr, pearsonr from ..data import D from collections import OrderedDict def get_normal_ic(a, b): return pearsonr(a, b)[0]
null
19,622
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd import warnings from typing import Union from ..log import get_module_logger from ..utils import get_date_range from ..utils.resam import Freq from ..strategy.base import BaseStrategy from ..backtest import get_...
analyze statistical time-series indicators of trading Parameters ---------- df : pandas.DataFrame columns: like ['pa', 'pos', 'ffr', 'deal_amount', 'value']. Necessary fields: - 'pa' is the price advantage in trade indicators - 'pos' is the positive rate in trade indicators - 'ffr' is the fulfill rate in trade indicato...
19,623
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd import warnings from typing import Union from ..log import get_module_logger from ..utils import get_date_range from ..utils.resam import Freq from ..strategy.base import BaseStrategy from ..backtest import get_...
A backtest for long-short strategy :param pred: The trading signal produced on day `T`. :param topk: The short topk securities and long topk securities. :param deal_price: The price to deal the trading. :param shift: Whether to shift prediction by one day. The trading day will be T+1 if shift==1. :param open_cost: open...
19,624
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd import warnings from typing import Union from ..log import get_module_logger from ..utils import get_date_range from ..utils.resam import Freq from ..strategy.base import BaseStrategy from ..backtest import get_...
null
19,625
import torch import numpy as np import pandas as pd import torch def data_to_tensor(data, device="cpu", raise_error=False): if isinstance(data, torch.Tensor): if device == "cpu": return data.cpu() else: return data.to(device) if isinstance(data, (pd.DataFrame, pd.Series...
null
19,626
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 class GymSpaceValidationError(Exception): def __init__(self, message: str, space: gym.Space, x: Any) -> None: ...
Strengthened version of gym.Space.contains. Giving more diagnostic information on why validation fails. Throw exception rather than returning true or false.
19,627
from __future__ import annotations import argparse import os import random import sys import warnings from pathlib import Path from typing import cast, List, Optional import numpy as np import pandas as pd import torch import yaml from qlib.backtest import Order from qlib.backtest.decision import OrderDir from qlib.con...
null
19,628
from __future__ import annotations import argparse import os import random import sys import warnings from pathlib import Path from typing import cast, List, Optional import numpy as np import pandas as pd import torch import yaml from qlib.backtest import Order from qlib.backtest.decision import OrderDir from qlib.con...
null
19,629
from __future__ import annotations import argparse import os import random import sys import warnings from pathlib import Path from typing import cast, List, Optional import numpy as np import pandas as pd import torch import yaml from qlib.backtest import Order from qlib.backtest.decision import OrderDir from qlib.con...
null
19,630
from __future__ import annotations from pathlib import Path import pandas as pd def read_order_file(order_file: Path | pd.DataFrame) -> pd.DataFrame: if isinstance(order_file, pd.DataFrame): return order_file order_file = Path(order_file) if order_file.suffix == ".pkl": order_df = pd.read...
null
19,631
import os import platform import shutil import sys import tempfile from importlib import import_module import yaml def merge_a_into_b(a: dict, b: dict) -> dict: b = b.copy() for k, v in a.items(): if isinstance(v, dict) and k in b: v.pop(DELETE_KEY, False) b[k] = merge_a_into_b(v...
null
19,632
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 qlib.rl.simulator import InitialStateType, Simulator from qlib.rl.utils import...
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 Interprets the policy actions. initial_stat...
19,633
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 qlib.rl.simulator import InitialStateType, Simulator from qlib.rl.utils import...
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 Interprets the policy actions. initial_states Ini...
19,634
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, Sequence, TypeVar, cast import torch from qlib.log import get_module_logger fr...
Make any object a (possibly dummy) context manager.
19,635
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, Sequence, TypeVar, cast import torch from qlib.log import get_module_logger fr...
Convert a list into a dict, where each item is named with its type.
19,636
from __future__ import annotations from pathlib import Path from typing import cast, List import cachetools import pandas as pd import pickle import os from qlib.backtest import Exchange, Order from qlib.backtest.decision import TradeRange, TradeRangeByTime from qlib.constant import EPS_T from .base import BaseIntraday...
null
19,637
from __future__ import annotations from pathlib import Path from typing import cast, List import cachetools import pandas as pd import pickle import os from qlib.backtest import Exchange, Order from qlib.backtest.decision import TradeRange, TradeRangeByTime from qlib.constant import EPS_T from .base import BaseIntraday...
null
19,638
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 pd from cachetools.keys import hashkey from qlib.backtest.decision import Order, OrderDir from qlib.rl.data.base import BaseIntradayBa...
null
19,639
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 pd from cachetools.keys import hashkey from qlib.backtest.decision import Order, OrderDir from qlib.rl.data.base import BaseIntradayBa...
null
19,640
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 pd from cachetools.keys import hashkey from qlib.backtest.decision import Order, OrderDir from qlib.rl.data.base import BaseIntradayBa...
null
19,641
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 pd from cachetools.keys import hashkey from qlib.backtest.decision import Order, OrderDir from qlib.rl.data.base import BaseIntradayBa...
null
19,642
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 pd from cachetools.keys import hashkey from qlib.backtest.decision import Order, OrderDir from qlib.rl.data.base import BaseIntradayBa...
Load orders, and set start time and end time for the orders.
19,643
from __future__ import annotations from pathlib import Path import qlib from qlib.constant import REG_CN from qlib.contrib.ops.high_freq import BFillNan, Cut, Date, DayCumsum, DayLast, FFillNan, IsInf, IsNull, Select REG_CN = "cn" class DayCumsum(ElemOperator): """DayCumsum Operator during start time and end time...
Initialize necessary resource to launch the workflow, including data direction, feature columns, etc.. Parameters ---------- qlib_config: Qlib configuration. Example:: { "provider_uri_day": DATA_ROOT_DIR / "qlib_1d", "provider_uri_1min": DATA_ROOT_DIR / "qlib_1min", "feature_root_dir": DATA_ROOT_DIR / "qlib_handler_sto...
19,644
from __future__ import annotations from typing import Any, cast import numpy as np import pandas as pd from qlib.backtest.decision import OrderDir from qlib.backtest.executor import BaseExecutor, NestedExecutor, SimulatorExecutor from qlib.constant import float_or_ndarray def dataframe_append(df: pd.DataFrame, other: ...
null
19,645
from __future__ import annotations from typing import Any, cast import numpy as np import pandas as pd from qlib.backtest.decision import OrderDir from qlib.backtest.executor import BaseExecutor, NestedExecutor, SimulatorExecutor from qlib.constant import float_or_ndarray class OrderDir(IntEnum): # Order direction...
null
19,646
from __future__ import annotations from typing import Any, cast import numpy as np import pandas as pd from qlib.backtest.decision import OrderDir from qlib.backtest.executor import BaseExecutor, NestedExecutor, SimulatorExecutor from qlib.constant import float_or_ndarray class BaseExecutor: """Base executor for t...
null
19,647
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 qlib.rl.interpreter import ActionInterpreter, StateInterpreter from qlib.rl.ord...
To 32-bit numeric types. Recursively.
19,648
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 qlib.rl.interpreter import ActionInterpreter, StateInterpreter from qlib.rl.ord...
null
19,649
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 qlib.rl.interpreter import ActionInterpreter, StateInterpreter from qlib.rl.ord...
null
19,650
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_ndarray from qlib.rl.data.base import BaseIntradayBacktestData from qlib.rl.da...
null
19,651
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 from tianshou.data import Batch, ReplayBuffer, to_torch from tianshou.policy ...
null
19,652
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 from tianshou.data import Batch, ReplayBuffer, to_torch from tianshou.policy ...
null
19,653
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 from tianshou.data import Batch, ReplayBuffer, to_torch from tianshou.policy ...
null
19,654
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 tianshou.data import Batch from tianshou.policy import BasePolicy from qlib...
null
19,655
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 tianshou.data import Batch from tianshou.policy import BasePolicy from qlib...
Fill missing data. Parameters ---------- original_data Original data without missing values. fill_method Method used to fill the missing data. Returns ------- The filled data.
19,656
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.env import BaseVectorEnv, DummyVectorEnv, ShmemVectorEnv, SubprocVectorEnv fro...
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.
19,657
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.env import BaseVectorEnv, DummyVectorEnv, ShmemVectorEnv, SubprocVectorEnv fro...
Check whether obs is generated by :func:`generate_nan_observation`.
19,658
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.env import BaseVectorEnv, DummyVectorEnv, ShmemVectorEnv, SubprocVectorEnv fro...
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 doing such replacement, you have two...
19,659
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 from joblib import delayed from .cache import H from ..config import C from .inst_processor import InstProcess...
register_all_wrappers
19,660
from __future__ import annotations import pandas as pd from typing import Union, List, TYPE_CHECKING from qlib.utils import init_instance_by_config def get_level_index(df: pd.DataFrame, level=Union[str, int]) -> int: """ get the level index of `df` given `level` Parameters ---------- df : pd.DataFra...
fetch data from `data` with `selector` and `level` selector are assumed to be well processed. `fetch_df_by_index` is only responsible for get the right level Parameters ---------- selector : Union[pd.Timestamp, slice, str, list] selector level : Union[int, str] the level to use the selector Returns ------- Data of the ...
19,661
from __future__ import annotations import pandas as pd from typing import Union, List, TYPE_CHECKING from qlib.utils import init_instance_by_config class DataHandler(Serializable): def __init__( self, instruments=None, start_time=None, end_time=None, dat...
null
19,662
from __future__ import annotations import pandas as pd from typing import Union, List, TYPE_CHECKING from qlib.utils import init_instance_by_config def get_level_index(df: pd.DataFrame, level=Union[str, int]) -> int: """ get the level index of `df` given `level` Parameters ---------- df : pd.DataFra...
Convert the format of df.MultiIndex according to the following rules: - If `level` is the first level of df.MultiIndex, do nothing - If `level` is the second level of df.MultiIndex, swap the level of index. NOTE: the number of levels of df.MultiIndex should be 2 Parameters ---------- df : Union[pd.DataFrame, pd.Series]...
19,663
from __future__ import annotations import pandas as pd from typing import Union, List, TYPE_CHECKING from qlib.utils import init_instance_by_config class DataHandler(Serializable): """ The steps to using a handler 1. initialized data handler (call by `init`). 2. use the data. The data handler tr...
initialize the handler part of the task **inplace** Parameters ---------- task : dict the task to be handled Returns ------- Union[DataHandler, None]: returns
19,664
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 Serializable from ...utils.paral import datetime_groupby_apply from qlib.data.inst_pro...
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. the first level value of the group index.
19,665
from __future__ import division from __future__ import print_function import numpy as np import pandas as pd from typing import Union, List, Type from scipy.stats import percentileofscore from .base import Expression, ExpressionOps, Feature, PFeature from ..log import get_module_logger from ..utils import get_callable_...
register all operator
19,666
import logging import sys import os from pathlib import Path import qlib import fire import ruamel.yaml as yaml from qlib.config import C from qlib.model.trainer import task_train from qlib.utils.data import update_config from qlib.log import get_module_logger from qlib.utils import set_log_with_config def workflow(con...
null
19,667
import atexit import logging import sys import traceback from ..log import get_module_logger from . import R from .recorder import Recorder def experiment_exception_hook(exc_type, value, tb): """ End an experiment with status to be "FAILED". This exception tries to catch those uncaught exception and end the...
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 be called. Thus, if any exception or user interruption occurs beforehand, we should handle them first. Once `R` is ended, another call of `R.end_exp` wil...
19,668
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_module_logger from pymongo import MongoClient from pymongo.database impor...
Get database in MongoDB, which means you need to declare the address and the name of a database at first. For example: Using qlib.init(): .. code-block:: python mongo_conf = { "task_url": task_url, # your MongoDB url "task_db_name": task_db_name, # database name } qlib.init(..., mongo=mongo_conf) After qlib.init(): .. ...
19,669
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_module_logger from pymongo import MongoClient from pymongo.database impor...
List all recorders which can pass the filter in an experiment. Args: experiment (str or Experiment): the name of an Experiment or an instance rec_filter_func (Callable, optional): return True to retain the given recorder. Defaults to None. Returns: dict: a dict {rid: recorder} after filtering.
19,670
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_module_logger from pymongo import MongoClient from pymongo.database impor...
Replace the handler in task with a cache handler. It will automatically cache the file and save it in cache_dir. >>> import qlib >>> qlib.auto_init() >>> import datetime >>> # it is simplified task >>> task = {"dataset": {"kwargs":{'handler': {'class': 'Alpha158', 'module_path': 'qlib.contrib.data.handler', 'kwargs': {...
19,671
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 class TaskGen(metaclass=abc.ABCMeta): """ The base class for generating different tasks Example 1: input: a specific task template and r...
Use a list of TaskGen and a list of task templates to generate different tasks. For examples: There are 3 task templates a,b,c and 2 TaskGen A,B. A will generates 2 tasks from a template and B will generates 3 tasks from a template. task_generator([a, b, c], [A, B]) will finally generate 3*2*3 = 18 tasks. Parameters --...
19,672
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 The provided code snippet includes necessary dependencies for implementing the `handler_mod` function. Write a Python function `def handler_mod(task: dict,...
Help to modify the handler end time when using RollingGen It try to handle the following case - Hander's data end_time is earlier than dataset's test_data's segments. - To handle this, handler's data's end_time is extended. If the handler's end_time is None, then it is not necessary to change it's end time. Args: task ...
19,673
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 class TimeAdjuster: """ Find appropriate date and adjust date. """ def __init__(self, future=True, end_time=None): self._future = ...
To avoid the leakage of future information, the segments should be truncated according to the test start_time NOTE: This function will change segments **inplace**
19,674
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 InvalidDocument from qlib import auto_init, get_module_logger from tqdm.cli import t...
r""" While the task pool is not empty (has WAITING tasks), use task_func to fetch and run tasks in task_pool After running this method, here are 4 situations (before_status -> after_status): STATUS_WAITING -> STATUS_DONE: use task["def"] as `task_func` param, it means that the task has not been started STATUS_WAITING -...
19,675
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 DataHandlerLP from qlib.model import Model from qlib.utils import get_date_...
null