id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
19,676
import logging from typing import Optional, Text, Dict, Any import re from logging import config as logging_config from time import time from contextlib import contextmanager from .config import C The provided code snippet includes necessary dependencies for implementing the `set_log_with_config` function. Write a Pyt...
set log with config :param log_config: :return:
19,677
import logging from typing import Optional, Text, Dict, Any import re from logging import config as logging_config from time import time from contextlib import contextmanager from .config import C def set_global_logger_level(level: int, return_orig_handler_level: bool = False): """set qlib.xxx logger handlers level...
set qlib.xxx logger handlers level to use contextmanager Parameters ---------- level: int logger level Examples --------- .. code-block:: python import qlib import logging from qlib.log import get_module_logger, set_global_logger_level_cm qlib.init() tmp_logger_01 = get_module_logger("tmp_logger_01", level=logging.INFO...
19,678
import socket from typing import Callable, List, Optional from tqdm.auto import tqdm from qlib.config import C from qlib.data.dataset import Dataset from qlib.data.dataset.weight import Reweighter from qlib.log import get_module_logger from qlib.model.base import Model from qlib.utils import ( auto_filter_kwargs, ...
Begin task training to start a recorder and save the task config. Args: task_config (dict): the config of a task experiment_name (str): the name of experiment recorder_name (str): the given name will be the recorder name. None for using rid. Returns: Recorder: the model recorder
19,679
import socket from typing import Callable, List, Optional from tqdm.auto import tqdm from qlib.config import C from qlib.data.dataset import Dataset from qlib.data.dataset.weight import Reweighter from qlib.log import get_module_logger from qlib.model.base import Model from qlib.utils import ( auto_filter_kwargs, ...
Finish task training with real model fitting and saving. Args: rec (Recorder): the recorder will be resumed experiment_name (str): the name of experiment Returns: Recorder: the model recorder
19,680
import bisect from datetime import datetime, time, date, timedelta from typing import List, Optional, Tuple, Union import functools import re import pandas as pd from qlib.config import C from qlib.constant import REG_CN, REG_TW, REG_US REG_CN = "cn" REG_US = "us" REG_TW = "tw" The provided code snippet includes nece...
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 ------- bool True means one piece of data to obtain.
19,681
import bisect from datetime import datetime, time, date, timedelta from typing import List, Optional, Tuple, Union import functools import re import pandas as pd from qlib.config import C from qlib.constant import REG_CN, REG_TW, REG_US CN_TIME = [ datetime.strptime("9:30", "%H:%M"), datetime.strptime("11:30", ...
null
19,682
import bisect from datetime import datetime, time, date, timedelta from typing import List, Optional, Tuple, Union import functools import re import pandas as pd from qlib.config import C from qlib.constant import REG_CN, REG_TW, REG_US def get_min_cal(shift: int = 0, region: str = REG_CN) -> List[time]: """ ge...
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 in the calendar. Both left and right are **closed**
19,683
import bisect from datetime import datetime, time, date, timedelta from typing import List, Optional, Tuple, Union import functools import re import pandas as pd from qlib.config import C from qlib.constant import REG_CN, REG_TW, REG_US The provided code snippet includes necessary dependencies for implementing the `ep...
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.Timestamp: the shifted time
19,684
from __future__ import annotations from typing import Dict, Tuple, Union, Callable, List import bisect import numpy as np import pandas as pd class SingleData(IndexData): def __init__( self, data: Union[int, float, np.number, list, dict, pd.Series] = [], index: Union[List, pd.Index, Index] = [] ): ...
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
19,685
from __future__ import annotations from typing import Dict, Tuple, Union, Callable, List import bisect import numpy as np import pandas as pd class SingleData(IndexData): def __init__( self, data: Union[int, float, np.number, list, dict, pd.Series] = [], index: Union[List, pd.Index, Index] = [] ): ...
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 the SingleData with new_index and values after sum.
19,686
from __future__ import annotations from typing import Dict, Tuple, Union, Callable, List import bisect import numpy as np import pandas as pd class BinaryOps: def __init__(self, method_name): self.method_name = method_name def __get__(self, obj, *args): # bind object self.obj = obj ...
meta class for auto generating operations for index data.
19,687
import contextlib import importlib import os from pathlib import Path import pickle import pkgutil import re import sys from types import ModuleType from typing import Any, Dict, List, Tuple, Union from urllib.parse import urlparse from qlib.typehint import InstConf The provided code snippet includes necessary depende...
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
19,688
import contextlib import importlib import os from pathlib import Path import pickle import pkgutil import re import sys from types import ModuleType from typing import Any, Dict, List, Tuple, Union from urllib.parse import urlparse from qlib.typehint import InstConf The provided code snippet includes necessary depende...
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.contrib.data.handler.Alpha158vwap'>...
19,689
import os import shutil import tempfile import contextlib from typing import Optional, Text, IO, Union from pathlib import Path from qlib.log import get_module_logger The provided code snippet includes necessary dependencies for implementing the `get_or_create_path` function. Write a Python function `def get_or_create...
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.
19,690
import os import shutil import tempfile import contextlib from typing import Optional, Text, IO, Union from pathlib import Path from qlib.log import get_module_logger The provided code snippet includes necessary dependencies for implementing the `save_multiple_parts_file` function. Write a Python function `def save_mu...
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 filename :param filename: result model path :param...
19,691
import os import shutil import tempfile import contextlib from typing import Optional, Text, IO, Union from pathlib import Path from qlib.log import get_module_logger log = get_module_logger("utils.file") The provided code snippet includes necessary dependencies for implementing the `unpack_archive_with_buffer` functi...
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 file_path('tempfile/') 5. remove 'tempfile'...
19,692
import os import shutil import tempfile import contextlib from typing import Optional, Text, IO, Union from pathlib import Path from qlib.log import get_module_logger def get_tmp_file_with_buffer(buffer): temp_dir = os.path.expanduser("~/tmp") if not os.path.exists(temp_dir): os.makedirs(temp_dir) ...
null
19,693
import os import shutil import tempfile import contextlib from typing import Optional, Text, IO, Union from pathlib import Path from qlib.log import get_module_logger The provided code snippet includes necessary dependencies for implementing the `get_io_object` function. Write a Python function `def get_io_object(file...
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:
19,694
from copy import deepcopy from typing import List, Union import pandas as pd import numpy as np The provided code snippet includes necessary dependencies for implementing the `robust_zscore` function. Write a Python function `def robust_zscore(x: pd.Series, zscore=False)` to solve the following problem: Robust ZScore ...
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.
19,695
from copy import deepcopy from typing import List, Union import pandas as pd import numpy as np def zscore(x: Union[pd.Series, pd.DataFrame]): return (x - x.mean()).div(x.std())
null
19,696
from copy import deepcopy from typing import List, Union import pandas as pd import numpy as np The provided code snippet includes necessary dependencies for implementing the `deepcopy_basic_type` function. Write a Python function `def deepcopy_basic_type(obj: object) -> object` to solve the following problem: deepcop...
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 ------- object: The copied object
19,697
from functools import partial from threading import Thread from typing import Callable, Text, Union from joblib import Parallel, delayed from joblib._parallel_backends import MultiprocessingBackend import pandas as pd from queue import Queue import concurrent from qlib.config import C, QlibConfig class ParallelExt(Para...
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 function axis : which axis is the datetime leve...
19,698
import numpy as np import pandas as pd from functools import partial from typing import Union, Callable from . import lazy_sort_index from .time import Freq, cal_sam_minute from ..config import C class Freq: NORM_FREQ_MONTH = "month" NORM_FREQ_WEEK = "week" NORM_FREQ_DAY = "day" NORM_FREQ_MINUTE = "min...
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 calendar freq_sam : str Sample frequency region: st...
19,699
import numpy as np import pandas as pd from functools import partial from typing import Union, Callable from . import lazy_sort_index from .time import Freq, cal_sam_minute from ..config import C class Freq: NORM_FREQ_MONTH = "month" NORM_FREQ_WEEK = "week" NORM_FREQ_DAY = "day" NORM_FREQ_MINUTE = "min...
get the feature with higher or equal frequency than `freq`. Returns ------- pd.DataFrame the feature with higher or equal frequency
19,700
import numpy as np import pandas as pd from functools import partial from typing import Union, Callable from . import lazy_sort_index from .time import Freq, cal_sam_minute from ..config import C def get_level_index(df: pd.DataFrame, level=Union[str, int]) -> int: """ get the level index of `df` given `level`...
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 $volume instrument datetime SH600000 2010-01-04 86.778313 16162960.0 2010-01-05 87.433578 28117442.0...
19,701
import numpy as np import pandas as pd from functools import partial from typing import Union, Callable from . import lazy_sort_index from .time import Freq, cal_sam_minute from ..config import C def get_valid_value(series, last=True): """get the first/last not nan value of pd.Series with single level index Par...
get the first/last not nan value of pd.Series|DataFrame with single level index
19,702
import os import numpy as np import pandas as pd from pathlib import Path DATA_PATH = Path(os.path.join("data", "pickle", "backtest")) OUTPUT_PATH = Path(os.path.join("data", "orders")) np.random.seed(1234) np.random.shuffle(stocks) def generate_order(stock: str, start_idx: int, end_idx: int) -> bool: dataset = pd...
null
19,703
import qlib import optuna from qlib.constant import REG_CN from qlib.utils import init_instance_by_config from qlib.tests.data import GetData from qlib.tests.config import get_dataset_config, CSI300_MARKET, DATASET_ALPHA360_CLASS def objective(trial): task = { "model": { "class": "LGBModel", ...
null
19,704
import qlib import optuna from qlib.constant import REG_CN from qlib.utils import init_instance_by_config from qlib.tests.config import CSI300_DATASET_CONFIG from qlib.tests.data import GetData def objective(trial): task = { "model": { "class": "LGBModel", "module_path": "qlib.contr...
null
19,705
import os import sys import fire import time import glob import yaml import shutil import signal import inspect import tempfile import functools import statistics import subprocess from datetime import datetime from pathlib import Path from operator import xor from pprint import pprint import qlib from qlib.workflow im...
null
19,706
import os import sys import fire import time import glob import yaml import shutil import signal import inspect import tempfile import functools import statistics import subprocess from datetime import datetime from pathlib import Path from operator import xor from pprint import pprint import qlib from qlib.workflow im...
null
19,707
import os import sys import fire import time import glob import yaml import shutil import signal import inspect import tempfile import functools import statistics import subprocess from datetime import datetime from pathlib import Path from operator import xor from pprint import pprint import qlib from qlib.workflow im...
null
19,708
import os import sys import fire import time import glob import yaml import shutil import signal import inspect import tempfile import functools import statistics import subprocess from datetime import datetime from pathlib import Path from operator import xor from pprint import pprint import qlib from qlib.workflow im...
null
19,709
import os import sys import fire import time import glob import yaml import shutil import signal import inspect import tempfile import functools import statistics import subprocess from datetime import datetime from pathlib import Path from operator import xor from pprint import pprint import qlib from qlib.workflow im...
null
19,710
import os import sys import fire import time import glob import yaml import shutil import signal import inspect import tempfile import functools import statistics import subprocess from datetime import datetime from pathlib import Path from operator import xor from pprint import pprint import qlib from qlib.workflow im...
null
19,711
import os import sys import fire import time import glob import yaml import shutil import signal import inspect import tempfile import functools import statistics import subprocess from datetime import datetime from pathlib import Path from operator import xor from pprint import pprint import qlib from qlib.workflow im...
null
19,712
import os import sys import fire import time import glob import yaml import shutil import signal import inspect import tempfile import functools import statistics import subprocess from datetime import datetime from pathlib import Path from operator import xor from pprint import pprint import qlib from qlib.workflow im...
null
19,713
import os import sys import fire import time import glob import yaml import shutil import signal import inspect import tempfile import functools import statistics import subprocess from datetime import datetime from pathlib import Path from operator import xor from pprint import pprint import qlib from qlib.workflow im...
null
19,714
from pathlib import Path from typing import Union import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import data_formatters.base import expt_settings.configs import libs.hyperparam_opt import libs.tft_model import libs.utils as utils import os import datetime as dte from qlib.model.base import Mod...
Prepare data to fit the TFT model. Args: df: Original DataFrame. fillna: Whether to fill the data with the mean values. Returns: Transformed DataFrame.
19,715
from pathlib import Path from typing import Union import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import data_formatters.base import expt_settings.configs import libs.hyperparam_opt import libs.tft_model import libs.utils as utils import os import datetime as dte from qlib.model.base import Mod...
null
19,716
from pathlib import Path from typing import Union import numpy as np import pandas as pd import tensorflow.compat.v1 as tf import data_formatters.base import expt_settings.configs import libs.hyperparam_opt import libs.tft_model import libs.utils as utils import os import datetime as dte from qlib.model.base import Mod...
null
19,717
import os import pathlib import numpy as np import tensorflow as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file The provided code snippet includes necessary dependencies for implementing the `get_single_col_by_input_type` function. Write a Python function `def get_single_col...
Returns name of single column. Args: input_type: Input type of column to extract column_definition: Column definition list for experiment
19,718
import os import pathlib import numpy as np import tensorflow as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file The provided code snippet includes necessary dependencies for implementing the `extract_cols_from_data_type` function. Write a Python function `def extract_cols_fr...
Extracts the names of columns that correspond to a define data_type. Args: data_type: DataType of columns to extract. column_definition: Column definition to use. excluded_input_types: Set of input types to exclude Returns: List of names for columns with data type specified.
19,719
import os import pathlib import numpy as np import tensorflow as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file The provided code snippet includes necessary dependencies for implementing the `tensorflow_quantile_loss` function. Write a Python function `def tensorflow_quantil...
Computes quantile loss for tensorflow. Standard quantile loss as defined in the "Training Procedure" section of the main TFT paper Args: y: Targets y_pred: Predictions quantile: Quantile to use for loss calculations (between 0 & 1) Returns: Tensor for quantile loss.
19,720
import os import pathlib import numpy as np import tensorflow as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file The provided code snippet includes necessary dependencies for implementing the `numpy_normalised_quantile_loss` function. Write a Python function `def numpy_normal...
Computes normalised quantile loss for numpy arrays. Uses the q-Risk metric as defined in the "Training Procedure" section of the main TFT paper. Args: y: Targets y_pred: Predictions quantile: Quantile to use for loss calculations (between 0 & 1) Returns: Float for normalised quantile loss.
19,721
import os import pathlib import numpy as np import tensorflow as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file The provided code snippet includes necessary dependencies for implementing the `create_folder_if_not_exist` function. Write a Python function `def create_folder_if...
Creates folder if it doesn't exist. Args: directory: Folder path to create.
19,722
import os import pathlib import numpy as np import tensorflow as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file The provided code snippet includes necessary dependencies for implementing the `get_default_tensorflow_config` function. Write a Python function `def get_default_t...
Creates tensorflow config for graphs to run on CPU or GPU. Specifies whether to run graph on gpu or cpu and which GPU ID to use for multi GPU machines. Args: tf_device: 'cpu' or 'gpu' gpu_id: GPU ID to use if relevant Returns: Tensorflow config.
19,723
import os import pathlib import numpy as np import tensorflow as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file The provided code snippet includes necessary dependencies for implementing the `save` function. Write a Python function `def save(tf_session, model_folder, cp_name...
Saves Tensorflow graph to checkpoint. Saves all trainiable variables under a given variable scope to checkpoint. Args: tf_session: Session containing graph model_folder: Folder to save models cp_name: Name of Tensorflow checkpoint scope: Variable scope containing variables to save
19,724
import os import pathlib import numpy as np import tensorflow as tf from tensorflow.python.tools.inspect_checkpoint import print_tensors_in_checkpoint_file def print_weights_in_checkpoint(model_folder, cp_name): """Prints all weights in Tensorflow checkpoint. Args: model_folder: Folder containing checkpoi...
Loads Tensorflow graph from checkpoint. Args: tf_session: Session to load graph into model_folder: Folder containing serialised model cp_name: Name of Tensorflow checkpoint scope: Variable scope to use. verbose: Whether to print additional debugging information.
19,725
from __future__ import absolute_import from __future__ import division from __future__ import print_function import gc import json import os import shutil import data_formatters.base import libs.utils as utils import numpy as np import pandas as pd import tensorflow as tf Dense = tf.keras.layers.Dense The provided cod...
Applies simple feed-forward network to an input. Args: inputs: MLP inputs hidden_size: Hidden state size output_size: Output size of MLP output_activation: Activation function to apply on output hidden_activation: Activation function to apply on input use_time_distributed: Whether to apply across time Returns: Tensor f...
19,726
from __future__ import absolute_import from __future__ import division from __future__ import print_function import gc import json import os import shutil import data_formatters.base import libs.utils as utils import numpy as np import pandas as pd import tensorflow as tf Dense = tf.keras.layers.Dense Activation = tf.k...
Applies the gated residual network (GRN) as defined in paper. Args: x: Network inputs hidden_layer_size: Internal state size output_size: Size of output layer dropout_rate: Dropout rate if dropout is applied use_time_distributed: Whether to apply network across time dimension additional_context: Additional context vect...
19,727
from __future__ import absolute_import from __future__ import division from __future__ import print_function import gc import json import os import shutil import data_formatters.base import libs.utils as utils import numpy as np import pandas as pd import tensorflow as tf K = tf.keras.backend The provided code snippet...
Returns causal mask to apply for self-attention layer. Args: self_attn_inputs: Inputs to self attention layer to determine mask shape
19,728
import os import copy import math import json import collections import numpy as np import pandas as pd import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from tqdm import tqdm from qlib.utils import get_or_create_path from qlib.log import get_module_logger from qlib.model.ba...
null
19,729
import os import copy import math import json import collections import numpy as np import pandas as pd import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from tqdm import tqdm from qlib.utils import get_or_create_path from qlib.log import get_module_logger from qlib.model.ba...
null
19,730
import os import copy import math import json import collections import numpy as np import pandas as pd import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from tqdm import tqdm from qlib.utils import get_or_create_path from qlib.log import get_module_logger from qlib.model.ba...
null
19,731
import copy import torch import numpy as np import pandas as pd from qlib.data.dataset import DatasetH device = "cuda" if torch.cuda.is_available() else "cpu" def _to_tensor(x): if not isinstance(x, torch.Tensor): return torch.tensor(x, dtype=torch.float, device=device) return x
null
19,732
import copy import torch import numpy as np import pandas as pd from qlib.data.dataset import DatasetH The provided code snippet includes necessary dependencies for implementing the `_create_ts_slices` function. Write a Python function `def _create_ts_slices(index, seq_len)` to solve the following problem: create time...
create time series slices from pandas index Args: index (pd.MultiIndex): pandas multiindex with <instrument, datetime> order seq_len (int): sequence length
19,733
import copy import torch import numpy as np import pandas as pd from qlib.data.dataset import DatasetH The provided code snippet includes necessary dependencies for implementing the `_get_date_parse_fn` function. Write a Python function `def _get_date_parse_fn(target)` to solve the following problem: get date parse fu...
get date parse function This method is used to parse date arguments as target type. Example: get_date_parse_fn('20120101')('2017-01-01') => '20170101' get_date_parse_fn(20120101)('2017-01-01') => 20170101
19,734
import os import numpy as np import pandas as pd from qlib.data import D from qlib.model.riskmodel import StructuredCovEstimator def prepare_data(riskdata_root="./riskdata", T=240, start_time="2016-01-01"): universe = D.features(D.instruments("csi300"), ["$close"], start_time=start_time).swaplevel().sort_index() ...
null
19,735
from datetime import date, datetime as dt import os from pathlib import Path import random import shutil import time import traceback from arctic import Arctic, chunkstore import arctic from arctic import Arctic, CHUNK_STORE from arctic.chunkstore.chunkstore import CHUNK_SIZE import fire from joblib import Parallel, de...
null
19,736
from datetime import date, datetime as dt import os from pathlib import Path import random import shutil import time import traceback from arctic import Arctic, chunkstore import arctic from arctic import Arctic, CHUNK_STORE from arctic.chunkstore.chunkstore import CHUNK_SIZE import fire from joblib import Parallel, de...
null
19,737
import pickle import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set(color_codes=True) plt.rcParams["font.sans-serif"] = "SimHei" plt.rcParams["axes.unicode_minus"] = False from tqdm.auto import tqdm plt.figure(figsize=(40, 20)) sns.heatmap(data_sim) plt.figure(figsize=(40,...
null
19,738
import abc import importlib from pathlib import Path from typing import Union, Iterable, List import fire import numpy as np import pandas as pd import baostock as bs from loguru import logger The provided code snippet includes necessary dependencies for implementing the `run` function. Write a Python function `def ru...
Collect future calendar(day) Parameters ---------- qlib_dir: qlib data directory region: cn/CN or us/US start_date start date end_date end date Examples ------- # get cn future calendar $ python future_calendar_collector.py --qlib_data_1d_dir <user data dir> --region cn
19,739
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
get SH/SZ history calendar list Parameters ---------- bench_code: str value from ["CSI300", "CSI500", "ALL", "US_ALL"] Returns ------- history calendar list
19,740
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
get calendar list by selecting the date when few funds trade in this day Parameters ---------- source_dir: str or Path The directory where the raw data collected from the Internet is saved date_field_name: str date field name, default is date threshold: float threshold to exclude some days when few funds trade in this ...
19,741
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
get SH/SZ stock symbols Returns ------- stock symbols
19,742
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
get US stock symbols Returns ------- stock symbols
19,743
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
get IN stock symbols Returns ------- stock symbols
19,744
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
get Brazil(B3) stock symbols Returns ------- B3 stock symbols
19,745
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
get en fund symbols Returns ------- fund symbols in China
19,746
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
symbol suffix to prefix Parameters ---------- symbol: str symbol capital : bool by default True Returns -------
19,747
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
symbol prefix to sufix Parameters ---------- symbol: str symbol capital : bool by default True Returns -------
19,748
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
get trading date by shift Parameters ---------- trading_list: list trading calendar list shift : int shift, default is 1 trading_date : pd.Timestamp trading date Returns -------
19,749
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
Parameters ---------- qlib_dir: str qlib data dir, default "Path(__file__).parent/qlib_data" index_name: str index name, value from ["csi100", "csi300"] method: str method, value from ["parse_instruments", "save_new_companies"] freq: str freq, value from ["day", "1min"] request_retry: int request retry, by default 5 re...
19,750
import re import copy import importlib import time import bisect import pickle import random import requests import functools from pathlib import Path from typing import Iterable, Tuple, List import numpy as np import pandas as pd from lxml import etree from loguru import logger from yahooquery import Ticker from tqdm ...
calc adjusted price This method does 4 things. 1. Adds the `paused` field. - The added paused field comes from the paused field of the 1d data. 2. Aligns the time of the 1d data. 3. The data is reweighted. - The reweighting method: - volume / factor - open * factor - high * factor - low * factor - close * factor 4. Cal...
19,751
import sys from pathlib import Path from concurrent.futures import ThreadPoolExecutor import fire import qlib import pandas as pd from tqdm import tqdm from qlib.data import D from loguru import logger from data_collector.utils import generate_minutes_calendar_from_daily def get_date_range(data_1min_dir: Path, max_work...
Use 1d data to fill in the missing symbols relative to 1min Parameters ---------- data_1min_dir: str 1min data dir qlib_data_1d_dir: str 1d qlib data(bin data) dir, from: https://qlib.readthedocs.io/en/latest/component/data.html#converting-csv-format-into-qlib-format max_workers: int ThreadPoolExecutor(max_workers), by...
19,752
import sys from typing import List from pathlib import Path import fire import numpy as np import pandas as pd from loguru import logger import baostock as bs from data_collector.utils import generate_minutes_calendar_from_daily def read_calendar_from_qlib(qlib_dir: Path) -> pd.DataFrame: calendar_path = qlib_dir.j...
get future calendar Parameters ---------- qlib_dir: str or Path qlib data directory freq: str value from ["day", "1min"], by default day
19,753
import abc import sys import datetime from abc import ABC from pathlib import Path import fire import pandas as pd from loguru import logger from dateutil.tz import tzlocal from data_collector.base import BaseCollector, BaseNormalize, BaseRun from data_collector.utils import deco_retry from pycoingecko import CoinGecko...
get crypto symbols in coingecko Returns ------- crypto symbols in given exchanges list of coingecko
19,754
import re import abc import sys from io import BytesIO from typing import List, Iterable from pathlib import Path import fire import requests import pandas as pd import baostock as bs from tqdm import tqdm from loguru import logger from data_collector.index import IndexBase from data_collector.utils import get_calendar...
null
19,755
import mysql.connector def print_user(user): config = { "host": "127.0.0.1", "port": "3306", "database": "hello_mysql", "user": "root", "password": "root1234" } # config = { # "host": "bpw0hq9h09e7mqicjhtl-mysql.services.clever-cloud.com", # "port":...
null
19,756
from hatchway import QueryOrBody, api_view from api import schemas from api.decorators import scope_required from api.models import Application def add_app( request, client_name: QueryOrBody[str], redirect_uris: QueryOrBody[str], scopes: QueryOrBody[None | str] = None, website: QueryOrBody[None | s...
null
19,757
from hatchway import QueryOrBody, api_view from api import schemas from api.decorators import scope_required from api.models import Application def verify_credentials( request, ) -> schemas.Application: return schemas.Application.from_application_no_keys(request.token.application)
null
19,758
from django.core.files import File from django.shortcuts import get_object_or_404 from hatchway import ApiError, QueryOrBody, api_view from activities.models import PostAttachment, PostAttachmentStates from api import schemas from core.files import blurhash_image, resize_image from ..decorators import scope_required d...
null
19,759
from django.core.files import File from django.shortcuts import get_object_or_404 from hatchway import ApiError, QueryOrBody, api_view from activities.models import PostAttachment, PostAttachmentStates from api import schemas from core.files import blurhash_image, resize_image from ..decorators import scope_required d...
null
19,760
from django.core.files import File from django.shortcuts import get_object_or_404 from hatchway import ApiError, QueryOrBody, api_view from activities.models import PostAttachment, PostAttachmentStates from api import schemas from core.files import blurhash_image, resize_image from ..decorators import scope_required d...
null
19,761
from hatchway import api_view from activities.models import Emoji from api.schemas import CustomEmoji class CustomEmoji(Schema): def from_emoji(cls, emoji: activities_models.Emoji) -> "CustomEmoji": def emojis(request) -> list[CustomEmoji]: return [ CustomEmoji.from_emoji(e) for e in Emoji.objects.us...
null
19,762
from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, api_view from activities.models import PostInteraction, TimelineEvent from activities.services import TimelineService from api import schemas from api.decorators import scope_required from api.pagination...
null
19,763
from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, api_view from activities.models import PostInteraction, TimelineEvent from activities.services import TimelineService from api import schemas from api.decorators import scope_required from api.pagination...
null
19,764
from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, api_view from activities.models import PostInteraction, TimelineEvent from activities.services import TimelineService from api import schemas from api.decorators import scope_required from api.pagination...
null
19,765
from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import api_view from activities.models import Hashtag from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from users.models...
null
19,766
from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import api_view from activities.models import Hashtag from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from users.models...
null
19,767
from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import api_view from activities.models import Hashtag from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from users.models...
null
19,768
from django.http import HttpRequest from hatchway import api_view from activities.models import Post from activities.services import TimelineService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult class PaginatingAp...
null
19,769
from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import api_view from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from users.models.identity import Identity from users.s...
null
19,770
from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import api_view from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from users.models.identity import Identity from users.s...
null
19,771
from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import api_view from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from users.models.identity import Identity from users.s...
null
19,772
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService fr...
null
19,773
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService fr...
null
19,774
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService fr...
null
19,775
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService fr...
Returns people you follow that also follow given account IDs