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 return_task(self, task, status=STATUS_WAITING):
"""
Return a task to status. Always using in error handling.
Args:
task ([type]): [description]
status (str, optional): STATUS_WAITING, STATUS_RUNNING, STATUS_DONE, STATUS_PART_DONE. Defaults to STATUS_WAITING.
... |
Return a task to status. Always using in error handling.
Args:
task ([type]): [description]
status (str, optional): STATUS_WAITING, STATUS_RUNNING, STATUS_DONE, STATUS_PART_DONE. Defaults to STATUS_WAITING.
| return_task | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def remove(self, query={}):
"""
Remove the task using query
Parameters
----------
query: dict
the dict of query
"""
query = query.copy()
query = self._decode_query(query)
self.task_pool.delete_many(query) |
Remove the task using query
Parameters
----------
query: dict
the dict of query
| remove | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def task_stat(self, query={}) -> dict:
"""
Count the tasks in every status.
Args:
query (dict, optional): the query dict. Defaults to {}.
Returns:
dict
"""
query = query.copy()
query = self._decode_query(query)
tasks = self.query(... |
Count the tasks in every status.
Args:
query (dict, optional): the query dict. Defaults to {}.
Returns:
dict
| task_stat | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def reset_waiting(self, query={}):
"""
Reset all running task into waiting status. Can be used when some running task exit unexpected.
Args:
query (dict, optional): the query dict. Defaults to {}.
"""
query = query.copy()
# default query
if "status" n... |
Reset all running task into waiting status. Can be used when some running task exit unexpected.
Args:
query (dict, optional): the query dict. Defaults to {}.
| reset_waiting | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def prioritize(self, task, priority: int):
"""
Set priority for task
Parameters
----------
task : dict
The task query from the database
priority : int
the target priority
"""
update_dict = {"$set": {"priority": priority}}
s... |
Set priority for task
Parameters
----------
task : dict
The task query from the database
priority : int
the target priority
| prioritize | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def wait(self, query={}):
"""
When multiprocessing, the main progress may fetch nothing from TaskManager because there are still some running tasks.
So main progress should wait until all tasks are trained well by other progress or machines.
Args:
query (dict, optional): the... |
When multiprocessing, the main progress may fetch nothing from TaskManager because there are still some running tasks.
So main progress should wait until all tasks are trained well by other progress or machines.
Args:
query (dict, optional): the query dict. Defaults to {}.
| wait | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def get_mongodb() -> Database:
"""
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... |
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... | get_mongodb | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def list_recorders(experiment, rec_filter_func=None):
"""
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... |
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} aft... | list_recorders | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def get(self, idx: int):
"""
Get datetime by index.
Parameters
----------
idx : int
index of the calendar
"""
if idx is None or idx >= len(self.cals):
return None
return self.cals[idx] |
Get datetime by index.
Parameters
----------
idx : int
index of the calendar
| get | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def align_idx(self, time_point, tp_type="start") -> int:
"""
Align the index of time_point in the calendar.
Parameters
----------
time_point
tp_type : str
Returns
-------
index : int
"""
if time_point is None:
# `None`... |
Align the index of time_point in the calendar.
Parameters
----------
time_point
tp_type : str
Returns
-------
index : int
| align_idx | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def align_time(self, time_point, tp_type="start") -> pd.Timestamp:
"""
Align time_point to trade date of calendar
Args:
time_point
Time point
tp_type : str
time point type (`"start"`, `"end"`)
Returns:
pd.Timestamp
... |
Align time_point to trade date of calendar
Args:
time_point
Time point
tp_type : str
time point type (`"start"`, `"end"`)
Returns:
pd.Timestamp
| align_time | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def align_seg(self, segment: Union[dict, tuple]) -> Union[dict, tuple]:
"""
Align the given date to the trade date
for example:
.. code-block:: python
input: {'train': ('2008-01-01', '2014-12-31'), 'valid': ('2015-01-01', '2016-12-31'), 'test': ('2017-01-01', '2020... |
Align the given date to the trade date
for example:
.. code-block:: python
input: {'train': ('2008-01-01', '2014-12-31'), 'valid': ('2015-01-01', '2016-12-31'), 'test': ('2017-01-01', '2020-08-01')}
output: {'train': (Timestamp('2008-01-02 00:00:00'), Tim... | align_seg | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def truncate(self, segment: tuple, test_start, days: int) -> tuple:
"""
Truncate the segment based on the test_start date
Parameters
----------
segment : tuple
time segment
test_start
days : int
The trading days to be truncated
... |
Truncate the segment based on the test_start date
Parameters
----------
segment : tuple
time segment
test_start
days : int
The trading days to be truncated
the data in this segment may need 'days' data
`days` are based on ... | truncate | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def shift(self, seg: tuple, step: int, rtype=SHIFT_SD) -> tuple:
"""
Shift the datetime of segment
If there are None (which indicates unbounded index) in the segment, this method will return None.
Parameters
----------
seg :
datetime segment
step : i... |
Shift the datetime of segment
If there are None (which indicates unbounded index) in the segment, this method will return None.
Parameters
----------
seg :
datetime segment
step : int
rolling step
rtype : str
rolling type ("s... | shift | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def replace_task_handler_with_cache(task: dict, cache_dir: Union[str, Path] = ".") -> dict:
"""
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 ta... |
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.cont... | replace_task_handler_with_cache | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def __init__(
self,
qlib_dir: str,
csv_path: str,
check_fields: str = None,
freq: str = "day",
symbol_field_name: str = "symbol",
date_field_name: str = "date",
file_suffix: str = ".csv",
max_workers: int = 16,
):
"""
Parameter... |
Parameters
----------
qlib_dir : str
qlib dir
csv_path : str
origin csv path
check_fields : str, optional
check fields, by default None, check qlib_dir/features/<first_dir>/*.<freq>.bin
freq : str, optional
freq, value fro... | __init__ | python | microsoft/qlib | scripts/check_dump_bin.py | https://github.com/microsoft/qlib/blob/master/scripts/check_dump_bin.py | MIT |
def check(self):
"""Check whether the bin file after ``dump_bin.py`` is executed is consistent with the original csv file data"""
logger.info("start check......")
error_list = []
not_in_features = []
compare_false = []
with tqdm(total=len(self.csv_files)) as p_bar:
... | Check whether the bin file after ``dump_bin.py`` is executed is consistent with the original csv file data | check | python | microsoft/qlib | scripts/check_dump_bin.py | https://github.com/microsoft/qlib/blob/master/scripts/check_dump_bin.py | MIT |
def _dump_pit(
self,
file_path: str,
interval: str = "quarterly",
overwrite: bool = False,
):
"""
dump data as the following format:
`/path/to/<field>.data`
[date, period, value, _next]
[date, period, value, _next]
... |
dump data as the following format:
`/path/to/<field>.data`
[date, period, value, _next]
[date, period, value, _next]
[...]
`/path/to/<field>.index`
[first_year, index, index, ...]
`<field.data>` contains the data a... | _dump_pit | python | microsoft/qlib | scripts/dump_pit.py | https://github.com/microsoft/qlib/blob/master/scripts/dump_pit.py | MIT |
def get_data(
self, symbol: str, interval: str, start_datetime: pd.Timestamp, end_datetime: pd.Timestamp
) -> pd.DataFrame:
"""get data with symbol
Parameters
----------
symbol: str
interval: str
value from [1min, 1d]
start_datetime: pd.Timestamp
... | get data with symbol
Parameters
----------
symbol: str
interval: str
value from [1min, 1d]
start_datetime: pd.Timestamp
end_datetime: pd.Timestamp
Returns
---------
pd.DataFrame, "symbol" and "date"in pd.columns
| get_data | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def save_instrument(self, symbol, df: pd.DataFrame):
"""save instrument data to file
Parameters
----------
symbol: str
instrument code
df : pd.DataFrame
df.columns must contain "symbol" and "datetime"
"""
if df is None or df.empty:
... | save instrument data to file
Parameters
----------
symbol: str
instrument code
df : pd.DataFrame
df.columns must contain "symbol" and "datetime"
| save_instrument | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def __init__(self, date_field_name: str = "date", symbol_field_name: str = "symbol", **kwargs):
"""
Parameters
----------
date_field_name: str
date field name, default is date
symbol_field_name: str
symbol field name, default is symbol
"""
... |
Parameters
----------
date_field_name: str
date field name, default is date
symbol_field_name: str
symbol field name, default is symbol
| __init__ | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def __init__(
self,
source_dir: [str, Path],
target_dir: [str, Path],
normalize_class: Type[BaseNormalize],
max_workers: int = 16,
date_field_name: str = "date",
symbol_field_name: str = "symbol",
**kwargs,
):
"""
Parameters
--... |
Parameters
----------
source_dir: str or Path
The directory where the raw data collected from the Internet is saved
target_dir: str or Path
Directory for normalize data
normalize_class: Type[YahooNormalize]
normalize class
max_workers... | __init__ | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def __init__(self, source_dir=None, normalize_dir=None, max_workers=1, interval="1d"):
"""
Parameters
----------
source_dir: str
The directory where the raw data collected from the Internet is saved, default "Path(__file__).parent/source"
normalize_dir: str
... |
Parameters
----------
source_dir: str
The directory where the raw data collected from the Internet is saved, default "Path(__file__).parent/source"
normalize_dir: str
Directory for normalize data, default "Path(__file__).parent/normalize"
max_workers: in... | __init__ | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def normalize_data(self, date_field_name: str = "date", symbol_field_name: str = "symbol", **kwargs):
"""normalize data
Parameters
----------
date_field_name: str
date field name, default date
symbol_field_name: str
symbol field name, default symbol
... | normalize data
Parameters
----------
date_field_name: str
date field name, default date
symbol_field_name: str
symbol field name, default symbol
Examples
---------
$ python collector.py normalize_data --source_dir ~/.qlib/instrument_d... | normalize_data | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def __init__(self, qlib_dir: Union[str, Path], start_date: str = None, end_date: str = None):
"""
Parameters
----------
qlib_dir:
qlib data directory
start_date
start date
end_date
end date
"""
self.qlib_dir = Path(qlib... |
Parameters
----------
qlib_dir:
qlib data directory
start_date
start date
end_date
end date
| __init__ | python | microsoft/qlib | scripts/data_collector/future_calendar_collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/future_calendar_collector.py | MIT |
def run(qlib_dir: Union[str, Path], region: str = "cn", start_date: str = None, end_date: str = None):
"""Collect future calendar(day)
Parameters
----------
qlib_dir:
qlib data directory
region:
cn/CN or us/US
start_date
start date
end_date
end date
Exam... | 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... | run | python | microsoft/qlib | scripts/data_collector/future_calendar_collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/future_calendar_collector.py | MIT |
def __init__(
self,
index_name: str,
qlib_dir: [str, Path] = None,
freq: str = "day",
request_retry: int = 5,
retry_sleep: int = 3,
):
"""
Parameters
----------
index_name: str
index name
qlib_dir: str
q... |
Parameters
----------
index_name: str
index name
qlib_dir: str
qlib directory, by default Path(__file__).resolve().parent.joinpath("qlib_data")
freq: str
freq, value from ["day", "1min"]
request_retry: int
request retry, b... | __init__ | python | microsoft/qlib | scripts/data_collector/index.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/index.py | MIT |
def save_new_companies(self):
"""save new companies
Examples
-------
$ python collector.py save_new_companies --index_name CSI300 --qlib_dir ~/.qlib/qlib_data/cn_data
"""
df = self.get_new_companies()
if df is None or df.empty:
raise ValueError(f"... | save new companies
Examples
-------
$ python collector.py save_new_companies --index_name CSI300 --qlib_dir ~/.qlib/qlib_data/cn_data
| save_new_companies | python | microsoft/qlib | scripts/data_collector/index.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/index.py | MIT |
def get_changes_with_history_companies(self, history_companies: pd.DataFrame) -> pd.DataFrame:
"""get changes with history companies
Parameters
----------
history_companies : pd.DataFrame
symbol date
SH600000 2020-11-11
dtypes:
... | get changes with history companies
Parameters
----------
history_companies : pd.DataFrame
symbol date
SH600000 2020-11-11
dtypes:
symbol: str
date: pd.Timestamp
Return
--------
pd.DataFram... | get_changes_with_history_companies | python | microsoft/qlib | scripts/data_collector/index.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/index.py | MIT |
def parse_instruments(self):
"""parse instruments, eg: csi300.txt
Examples
-------
$ python collector.py parse_instruments --index_name CSI300 --qlib_dir ~/.qlib/qlib_data/cn_data
"""
logger.info(f"start parse {self.index_name.lower()} companies.....")
instru... | parse instruments, eg: csi300.txt
Examples
-------
$ python collector.py parse_instruments --index_name CSI300 --qlib_dir ~/.qlib/qlib_data/cn_data
| parse_instruments | python | microsoft/qlib | scripts/data_collector/index.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/index.py | MIT |
def get_calendar_list(bench_code="CSI300") -> List[pd.Timestamp]:
"""get SH/SZ history calendar list
Parameters
----------
bench_code: str
value from ["CSI300", "CSI500", "ALL", "US_ALL"]
Returns
-------
history calendar list
"""
logger.info(f"get calendar list: {bench... | get SH/SZ history calendar list
Parameters
----------
bench_code: str
value from ["CSI300", "CSI500", "ALL", "US_ALL"]
Returns
-------
history calendar list
| get_calendar_list | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_calendar_list_by_ratio(
source_dir: [str, Path],
date_field_name: str = "date",
threshold: float = 0.5,
minimum_count: int = 10,
max_workers: int = 16,
) -> list:
"""get calendar list by selecting the date when few funds trade in this day
Parameters
----------
source_dir: st... | 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 t... | get_calendar_list_by_ratio | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_hs_stock_symbols() -> list:
"""get SH/SZ stock symbols
Returns
-------
stock symbols
"""
global _HS_SYMBOLS # pylint: disable=W0603
def _get_symbol():
"""
Get the stock pool from a web page and process it into the format required by yahooquery.
Format o... | get SH/SZ stock symbols
Returns
-------
stock symbols
| get_hs_stock_symbols | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def _get_symbol():
"""
Get the stock pool from a web page and process it into the format required by yahooquery.
Format of data retrieved from the web page: 600519, 000001
The data format required by yahooquery: 600519.ss, 000001.sz
Returns
-------
set: Retur... |
Get the stock pool from a web page and process it into the format required by yahooquery.
Format of data retrieved from the web page: 600519, 000001
The data format required by yahooquery: 600519.ss, 000001.sz
Returns
-------
set: Returns the set of symbol codes.
... | _get_symbol | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_us_stock_symbols(qlib_data_path: [str, Path] = None) -> list:
"""get US stock symbols
Returns
-------
stock symbols
"""
global _US_SYMBOLS # pylint: disable=W0603
@deco_retry
def _get_eastmoney():
url = "http://4.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=10000&f... | get US stock symbols
Returns
-------
stock symbols
| get_us_stock_symbols | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_in_stock_symbols(qlib_data_path: [str, Path] = None) -> list:
"""get IN stock symbols
Returns
-------
stock symbols
"""
global _IN_SYMBOLS # pylint: disable=W0603
@deco_retry
def _get_nifty():
url = f"https://www1.nseindia.com/content/equities/EQUITY_L.csv"
... | get IN stock symbols
Returns
-------
stock symbols
| get_in_stock_symbols | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_br_stock_symbols(qlib_data_path: [str, Path] = None) -> list:
"""get Brazil(B3) stock symbols
Returns
-------
B3 stock symbols
"""
global _BR_SYMBOLS # pylint: disable=W0603
@deco_retry
def _get_ibovespa():
_symbols = []
url = "https://www.fundamentus.com.b... | get Brazil(B3) stock symbols
Returns
-------
B3 stock symbols
| get_br_stock_symbols | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def symbol_suffix_to_prefix(symbol: str, capital: bool = True) -> str:
"""symbol suffix to prefix
Parameters
----------
symbol: str
symbol
capital : bool
by default True
Returns
-------
"""
code, exchange = symbol.split(".")
if exchange.lower() in ["sh", "ss"]:
... | symbol suffix to prefix
Parameters
----------
symbol: str
symbol
capital : bool
by default True
Returns
-------
| symbol_suffix_to_prefix | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def symbol_prefix_to_sufix(symbol: str, capital: bool = True) -> str:
"""symbol prefix to sufix
Parameters
----------
symbol: str
symbol
capital : bool
by default True
Returns
-------
"""
res = f"{symbol[:-2]}.{symbol[-2:]}"
return res.upper() if capital else re... | symbol prefix to sufix
Parameters
----------
symbol: str
symbol
capital : bool
by default True
Returns
-------
| symbol_prefix_to_sufix | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_trading_date_by_shift(trading_list: list, trading_date: pd.Timestamp, shift: int = 1):
"""get trading date by shift
Parameters
----------
trading_list: list
trading calendar list
shift : int
shift, default is 1
trading_date : pd.Timestamp
trading date
Return... | 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
-------
| get_trading_date_by_shift | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def generate_minutes_calendar_from_daily(
calendars: Iterable,
freq: str = "1min",
am_range: Tuple[str, str] = ("09:30:00", "11:29:00"),
pm_range: Tuple[str, str] = ("13:00:00", "14:59:00"),
) -> pd.Index:
"""generate minutes calendar
Parameters
----------
calendars: Iterable
da... | generate minutes calendar
Parameters
----------
calendars: Iterable
daily calendar
freq: str
by default 1min
am_range: Tuple[str, str]
AM Time Range, by default China-Stock: ("09:30:00", "11:29:00")
pm_range: Tuple[str, str]
PM Time Range, by default China-Stock:... | generate_minutes_calendar_from_daily | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_instruments(
qlib_dir: str,
index_name: str,
method: str = "parse_instruments",
freq: str = "day",
request_retry: int = 5,
retry_sleep: int = 3,
market_index: str = "cn_index",
):
"""
Parameters
----------
qlib_dir: str
qlib data dir, default "Path(__file__).... |
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",... | get_instruments | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_1d_data(
_date_field_name: str,
_symbol_field_name: str,
symbol: str,
start: str,
end: str,
_1d_data_all: pd.DataFrame,
) -> pd.DataFrame:
"""get 1d data
Returns
------
data_1d: pd.DataFrame
data_1d.columns = [_date_field_name, _symbol_field_name, "paused... | get 1d data
Returns
------
data_1d: pd.DataFrame
data_1d.columns = [_date_field_name, _symbol_field_name, "paused", "volume", "factor", "close"]
| get_1d_data | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def calc_adjusted_price(
df: pd.DataFrame,
_1d_data_all: pd.DataFrame,
_date_field_name: str,
_symbol_field_name: str,
frequence: str,
consistent_1d: bool = True,
calc_paused: bool = True,
) -> pd.DataFrame:
"""calc adjusted price
This method does 4 things.
1. Adds the `paused` f... | 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 * facto... | calc_adjusted_price | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def calc_paused_num(df: pd.DataFrame, _date_field_name, _symbol_field_name):
"""calc paused num
This method adds the paused_num field
- The `paused_num` is the number of consecutive days of trading suspension.
"""
_symbol = df.iloc[0][_symbol_field_name]
df = df.copy()
df["_tmp_date"] = ... | calc paused num
This method adds the paused_num field
- The `paused_num` is the number of consecutive days of trading suspension.
| calc_paused_num | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def __init__(
self, qlib_data_1d_dir: [str, Path], date_field_name: str = "date", symbol_field_name: str = "symbol", **kwargs
):
"""
Parameters
----------
qlib_data_1d_dir: str, Path
the qlib data to be updated for yahoo, usually from: Normalised to 5min using lo... |
Parameters
----------
qlib_data_1d_dir: str, Path
the qlib data to be updated for yahoo, usually from: Normalised to 5min using local 1d data
date_field_name: str
date field name, default is date
symbol_field_name: str
symbol field name, defa... | __init__ | python | microsoft/qlib | scripts/data_collector/baostock_5min/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/baostock_5min/collector.py | MIT |
def __init__(self, source_dir=None, normalize_dir=None, max_workers=1, interval="5min", region="HS300"):
"""
Changed the default value of: scripts.data_collector.base.BaseRun.
"""
super().__init__(source_dir, normalize_dir, max_workers, interval)
self.region = region |
Changed the default value of: scripts.data_collector.base.BaseRun.
| __init__ | python | microsoft/qlib | scripts/data_collector/baostock_5min/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/baostock_5min/collector.py | MIT |
def download_data(
self,
max_collector_count=2,
delay=0.5,
start=None,
end=None,
check_data_length=None,
limit_nums=None,
):
"""download data from Baostock
Notes
-----
check_data_length, example:
hs300 5min,... | download data from Baostock
Notes
-----
check_data_length, example:
hs300 5min, a week: 4 * 60 * 5
Examples
---------
# get hs300 5min data
$ python collector.py download_data --source_dir ~/.qlib/stock_data/source/hs300_5min_original... | download_data | python | microsoft/qlib | scripts/data_collector/baostock_5min/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/baostock_5min/collector.py | MIT |
def normalize_data(
self,
date_field_name: str = "date",
symbol_field_name: str = "symbol",
end_date: str = None,
qlib_data_1d_dir: str = None,
):
"""normalize data
Attention
---------
qlib_data_1d_dir cannot be None, normalize 5min needs to u... | normalize data
Attention
---------
qlib_data_1d_dir cannot be None, normalize 5min needs to use 1d data;
qlib_data_1d can be obtained like this:
$ python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --interval 1d --region cn --version v3
... | normalize_data | python | microsoft/qlib | scripts/data_collector/baostock_5min/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/baostock_5min/collector.py | MIT |
def get_current_4_month_period(self, current_month: int):
"""
This function is used to calculated what is the current
four month period for the current month. For example,
If the current month is August 8, its four month period
is 2Q.
OBS: In english Q is used to represe... |
This function is used to calculated what is the current
four month period for the current month. For example,
If the current month is August 8, its four month period
is 2Q.
OBS: In english Q is used to represent *quarter*
which means a three month period. However, in
... | get_current_4_month_period | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def get_four_month_period(self):
"""
The ibovespa index is updated every four months.
Therefore, we will represent each time period as 2003_1Q
which means 2003 first four mount period (Jan, Feb, Mar, Apr)
"""
four_months_period = ["1Q", "2Q", "3Q"]
init_year = 200... |
The ibovespa index is updated every four months.
Therefore, we will represent each time period as 2003_1Q
which means 2003 first four mount period (Jan, Feb, Mar, Apr)
| get_four_month_period | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def format_datetime(self, inst_df: pd.DataFrame) -> pd.DataFrame:
"""formatting the datetime in an instrument
Parameters
----------
inst_df: pd.DataFrame
inst_df.columns = [self.SYMBOL_FIELD_NAME, self.START_DATE_FIELD, self.END_DATE_FIELD]
Returns
-------
... | formatting the datetime in an instrument
Parameters
----------
inst_df: pd.DataFrame
inst_df.columns = [self.SYMBOL_FIELD_NAME, self.START_DATE_FIELD, self.END_DATE_FIELD]
Returns
-------
inst_df: pd.DataFrame
| format_datetime | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def format_quarter(self, cell: str):
"""
Parameters
----------
cell: str
It must be on the format 2003_1Q --> years_4_month_periods
Returns
----------
date: str
Returns date in format 2003-03-01
"""
cell_split = cell.split(... |
Parameters
----------
cell: str
It must be on the format 2003_1Q --> years_4_month_periods
Returns
----------
date: str
Returns date in format 2003-03-01
| format_quarter | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def get_changes(self):
"""
Access the index historic composition and compare it quarter
by quarter and year by year in order to generate a file that
keeps track of which stocks have been removed and which have
been added.
The Dataframe used as reference will provided the... |
Access the index historic composition and compare it quarter
by quarter and year by year in order to generate a file that
keeps track of which stocks have been removed and which have
been added.
The Dataframe used as reference will provided the index
composition for eac... | get_changes | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def get_new_companies(self):
"""
Get latest index composition.
The repo indicated on README has implemented a script
to get the latest index composition from B3 website using
selenium. Therefore, this method will download the file
containing such composition
Para... |
Get latest index composition.
The repo indicated on README has implemented a script
to get the latest index composition from B3 website using
selenium. Therefore, this method will download the file
containing such composition
Parameters
----------
self: ... | get_new_companies | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def calendar_list(self) -> List[pd.Timestamp]:
"""get history trading date
Returns
-------
calendar list
"""
_calendar = getattr(self, "_calendar_list", None)
if not _calendar:
_calendar = get_calendar_list(bench_code=self.index_name.upper())
... | get history trading date
Returns
-------
calendar list
| calendar_list | python | microsoft/qlib | scripts/data_collector/cn_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/cn_index/collector.py | MIT |
def format_datetime(self, inst_df: pd.DataFrame) -> pd.DataFrame:
"""formatting the datetime in an instrument
Parameters
----------
inst_df: pd.DataFrame
inst_df.columns = [self.SYMBOL_FIELD_NAME, self.START_DATE_FIELD, self.END_DATE_FIELD]
Returns
-------
... | formatting the datetime in an instrument
Parameters
----------
inst_df: pd.DataFrame
inst_df.columns = [self.SYMBOL_FIELD_NAME, self.START_DATE_FIELD, self.END_DATE_FIELD]
Returns
-------
| format_datetime | python | microsoft/qlib | scripts/data_collector/cn_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/cn_index/collector.py | MIT |
def get_changes(self) -> pd.DataFrame:
"""get companies changes
Returns
-------
pd.DataFrame:
symbol date type
SH600000 2019-11-11 add
SH600000 2020-11-10 remove
dtypes:
symbol: str
... | get companies changes
Returns
-------
pd.DataFrame:
symbol date type
SH600000 2019-11-11 add
SH600000 2020-11-10 remove
dtypes:
symbol: str
date: pd.Timestamp
type... | get_changes | python | microsoft/qlib | scripts/data_collector/cn_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/cn_index/collector.py | MIT |
def normalize_symbol(symbol: str) -> str:
"""
Parameters
----------
symbol: str
symbol
Returns
-------
symbol
"""
symbol = f"{int(symbol):06}"
return f"SH{symbol}" if symbol.startswith("60") or symbol.startswith("688") els... |
Parameters
----------
symbol: str
symbol
Returns
-------
symbol
| normalize_symbol | python | microsoft/qlib | scripts/data_collector/cn_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/cn_index/collector.py | MIT |
def get_new_companies(self) -> pd.DataFrame:
"""
Returns
-------
pd.DataFrame:
symbol start_date end_date
SH600000 2000-01-01 2099-12-31
dtypes:
symbol: str
start_date: pd.Timestamp
... |
Returns
-------
pd.DataFrame:
symbol start_date end_date
SH600000 2000-01-01 2099-12-31
dtypes:
symbol: str
start_date: pd.Timestamp
end_date: pd.Timestamp
| get_new_companies | python | microsoft/qlib | scripts/data_collector/cn_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/cn_index/collector.py | MIT |
def get_history_companies(self) -> pd.DataFrame:
"""
Returns
-------
pd.DataFrame:
symbol date type
SH600000 2019-11-11 add
SH600000 2020-11-10 remove
dtypes:
symbol: str
... |
Returns
-------
pd.DataFrame:
symbol date type
SH600000 2019-11-11 add
SH600000 2020-11-10 remove
dtypes:
symbol: str
date: pd.Timestamp
type: str, value from ["... | get_history_companies | python | microsoft/qlib | scripts/data_collector/cn_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/cn_index/collector.py | MIT |
def get_new_companies(self) -> pd.DataFrame:
"""
Returns
-------
pd.DataFrame:
symbol start_date end_date
SH600000 2000-01-01 2099-12-31
dtypes:
symbol: str
start_date: pd.Timestamp
... |
Returns
-------
pd.DataFrame:
symbol start_date end_date
SH600000 2000-01-01 2099-12-31
dtypes:
symbol: str
start_date: pd.Timestamp
end_date: pd.Timestamp
| get_new_companies | python | microsoft/qlib | scripts/data_collector/cn_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/cn_index/collector.py | MIT |
def fill_1min_using_1d(
data_1min_dir: [str, Path],
qlib_data_1d_dir: [str, Path],
max_workers: int = 16,
date_field_name: str = "date",
symbol_field_name: str = "symbol",
):
"""Use 1d data to fill in the missing symbols relative to 1min
Parameters
----------
data_1min_dir: str
... | 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: in... | fill_1min_using_1d | python | microsoft/qlib | scripts/data_collector/contrib/fill_cn_1min_data/fill_cn_1min_data.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/contrib/fill_cn_1min_data/fill_cn_1min_data.py | MIT |
def future_calendar_collector(qlib_dir: [str, Path], freq: str = "day"):
"""get future calendar
Parameters
----------
qlib_dir: str or Path
qlib data directory
freq: str
value from ["day", "1min"], by default day
"""
qlib_dir = Path(qlib_dir).expanduser().resolve()
if no... | get future calendar
Parameters
----------
qlib_dir: str or Path
qlib data directory
freq: str
value from ["day", "1min"], by default day
| future_calendar_collector | python | microsoft/qlib | scripts/data_collector/contrib/future_trading_date_collector/future_trading_date_collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/contrib/future_trading_date_collector/future_trading_date_collector.py | MIT |
def get_cg_crypto_symbols(qlib_data_path: [str, Path] = None) -> list:
"""get crypto symbols in coingecko
Returns
-------
crypto symbols in given exchanges list of coingecko
"""
global _CG_CRYPTO_SYMBOLS # pylint: disable=W0603
@deco_retry
def _get_coingecko():
try:
... | get crypto symbols in coingecko
Returns
-------
crypto symbols in given exchanges list of coingecko
| get_cg_crypto_symbols | python | microsoft/qlib | scripts/data_collector/crypto/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/crypto/collector.py | MIT |
def __init__(self, source_dir=None, normalize_dir=None, max_workers=4, interval="1d", region=REGION_CN):
"""
Parameters
----------
source_dir: str
The directory where the raw data collected from the Internet is saved, default "Path(__file__).parent/source"
normalize_... |
Parameters
----------
source_dir: str
The directory where the raw data collected from the Internet is saved, default "Path(__file__).parent/source"
normalize_dir: str
Directory for normalize data, default "Path(__file__).parent/normalize"
max_workers: in... | __init__ | python | microsoft/qlib | scripts/data_collector/fund/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/fund/collector.py | MIT |
def format_datetime(self, inst_df: pd.DataFrame) -> pd.DataFrame:
"""formatting the datetime in an instrument
Parameters
----------
inst_df: pd.DataFrame
inst_df.columns = [self.SYMBOL_FIELD_NAME, self.START_DATE_FIELD, self.END_DATE_FIELD]
Returns
-------
... | formatting the datetime in an instrument
Parameters
----------
inst_df: pd.DataFrame
inst_df.columns = [self.SYMBOL_FIELD_NAME, self.START_DATE_FIELD, self.END_DATE_FIELD]
Returns
-------
| format_datetime | python | microsoft/qlib | scripts/data_collector/us_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/us_index/collector.py | MIT |
def calendar_list(self) -> List[pd.Timestamp]:
"""get history trading date
Returns
-------
calendar list
"""
_calendar_list = getattr(self, "_calendar_list", None)
if _calendar_list is None:
_calendar_list = list(filter(lambda x: x >= self.bench_s... | get history trading date
Returns
-------
calendar list
| calendar_list | python | microsoft/qlib | scripts/data_collector/us_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/us_index/collector.py | MIT |
def _get_first_close(self, df: pd.DataFrame) -> float:
"""get first close value
Notes
-----
For incremental updates(append) to Yahoo 1D data, user need to use a close that is not 0 on the first trading day of the existing data
"""
df = df.loc[df["close"].first_valid_... | get first close value
Notes
-----
For incremental updates(append) to Yahoo 1D data, user need to use a close that is not 0 on the first trading day of the existing data
| _get_first_close | python | microsoft/qlib | scripts/data_collector/yahoo/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/yahoo/collector.py | MIT |
def _manual_adj_data(self, df: pd.DataFrame) -> pd.DataFrame:
"""manual adjust data: All fields (except change) are standardized according to the close of the first day"""
if df.empty:
return df
df = df.copy()
df.sort_values(self._date_field_name, inplace=True)
df = d... | manual adjust data: All fields (except change) are standardized according to the close of the first day | _manual_adj_data | python | microsoft/qlib | scripts/data_collector/yahoo/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/yahoo/collector.py | MIT |
def __init__(
self, old_qlib_data_dir: [str, Path], date_field_name: str = "date", symbol_field_name: str = "symbol", **kwargs
):
"""
Parameters
----------
old_qlib_data_dir: str, Path
the qlib data to be updated for yahoo, usually from: https://github.com/micros... |
Parameters
----------
old_qlib_data_dir: str, Path
the qlib data to be updated for yahoo, usually from: https://github.com/microsoft/qlib/tree/main/scripts#download-cn-data
date_field_name: str
date field name, default is date
symbol_field_name: str
... | __init__ | python | microsoft/qlib | scripts/data_collector/yahoo/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/yahoo/collector.py | MIT |
def __init__(
self, qlib_data_1d_dir: [str, Path], date_field_name: str = "date", symbol_field_name: str = "symbol", **kwargs
):
"""
Parameters
----------
qlib_data_1d_dir: str, Path
the qlib data to be updated for yahoo, usually from: Normalised to 1min using lo... |
Parameters
----------
qlib_data_1d_dir: str, Path
the qlib data to be updated for yahoo, usually from: Normalised to 1min using local 1d data
date_field_name: str
date field name, default is date
symbol_field_name: str
symbol field name, defa... | __init__ | python | microsoft/qlib | scripts/data_collector/yahoo/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/yahoo/collector.py | MIT |
def __init__(self, source_dir=None, normalize_dir=None, max_workers=1, interval="1d", region=REGION_CN):
"""
Parameters
----------
source_dir: str
The directory where the raw data collected from the Internet is saved, default "Path(__file__).parent/source"
normalize_... |
Parameters
----------
source_dir: str
The directory where the raw data collected from the Internet is saved, default "Path(__file__).parent/source"
normalize_dir: str
Directory for normalize data, default "Path(__file__).parent/normalize"
max_workers: in... | __init__ | python | microsoft/qlib | scripts/data_collector/yahoo/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/yahoo/collector.py | MIT |
def normalize_data(
self,
date_field_name: str = "date",
symbol_field_name: str = "symbol",
end_date: str = None,
qlib_data_1d_dir: str = None,
):
"""normalize data
Parameters
----------
date_field_name: str
date field name, defaul... | normalize data
Parameters
----------
date_field_name: str
date field name, default date
symbol_field_name: str
symbol field name, default symbol
end_date: str
if not None, normalize the last date saved (including end_date); if None, it will ig... | normalize_data | python | microsoft/qlib | scripts/data_collector/yahoo/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/yahoo/collector.py | MIT |
def normalize_data_1d_extend(
self, old_qlib_data_dir, date_field_name: str = "date", symbol_field_name: str = "symbol"
):
"""normalize data extend; extending yahoo qlib data(from: https://github.com/microsoft/qlib/tree/main/scripts#download-cn-data)
Notes
-----
Steps to... | normalize data extend; extending yahoo qlib data(from: https://github.com/microsoft/qlib/tree/main/scripts#download-cn-data)
Notes
-----
Steps to extend yahoo qlib data:
1. download qlib data: https://github.com/microsoft/qlib/tree/main/scripts#download-cn-data; save to <di... | normalize_data_1d_extend | python | microsoft/qlib | scripts/data_collector/yahoo/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/yahoo/collector.py | MIT |
def update_data_to_bin(
self,
qlib_data_1d_dir: str,
end_date: str = None,
check_data_length: int = None,
delay: float = 1,
exists_skip: bool = False,
):
"""update yahoo data to bin
Parameters
----------
qlib_data_1d_dir: str
... | update yahoo data to bin
Parameters
----------
qlib_data_1d_dir: str
the qlib data to be updated for yahoo, usually from: https://github.com/microsoft/qlib/tree/main/scripts#download-cn-data
end_date: str
end datetime, default ``pd.Timestamp(trading_date + pd.Ti... | update_data_to_bin | python | microsoft/qlib | scripts/data_collector/yahoo/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/yahoo/collector.py | MIT |
def train(uri_path: str = None):
"""train model
Returns
-------
pred_score: pandas.DataFrame
predict scores
performance: dict
model performance
"""
# model initialization
model = init_instance_by_config(CSI300_GBDT_TASK["model"])
dataset = init_insta... | train model
Returns
-------
pred_score: pandas.DataFrame
predict scores
performance: dict
model performance
| train | python | microsoft/qlib | tests/test_all_pipeline.py | https://github.com/microsoft/qlib/blob/master/tests/test_all_pipeline.py | MIT |
def fake_experiment():
"""A fake experiment workflow to test uri
Returns
-------
pass_or_not_for_default_uri: bool
pass_or_not_for_current_uri: bool
temporary_exp_dir: str
"""
# start exp
default_uri = R.get_uri()
current_uri = "file:./temp-test-exp-mag"
with R.... | A fake experiment workflow to test uri
Returns
-------
pass_or_not_for_default_uri: bool
pass_or_not_for_current_uri: bool
temporary_exp_dir: str
| fake_experiment | python | microsoft/qlib | tests/test_all_pipeline.py | https://github.com/microsoft/qlib/blob/master/tests/test_all_pipeline.py | MIT |
def backtest_analysis(pred, rid, uri_path: str = None):
"""backtest and analysis
Parameters
----------
rid : str
the id of the recorder to be used in this function
uri_path: str
mlflow uri path
Returns
-------
analysis : pandas.DataFrame
the analysis result
... | backtest and analysis
Parameters
----------
rid : str
the id of the recorder to be used in this function
uri_path: str
mlflow uri path
Returns
-------
analysis : pandas.DataFrame
the analysis result
| backtest_analysis | python | microsoft/qlib | tests/test_all_pipeline.py | https://github.com/microsoft/qlib/blob/master/tests/test_all_pipeline.py | MIT |
def test_TSDataSampler2(self):
"""
Extra test TSDataSampler to prevent incorrect filling of nan for the values at the front
"""
datetime_list = ["2000-01-31", "2000-02-29", "2000-03-31", "2000-04-30", "2000-05-31"]
instruments = ["000001", "000002", "000003", "000004", "000005"]
... |
Extra test TSDataSampler to prevent incorrect filling of nan for the values at the front
| test_TSDataSampler2 | python | microsoft/qlib | tests/data_mid_layer_tests/test_dataset.py | https://github.com/microsoft/qlib/blob/master/tests/data_mid_layer_tests/test_dataset.py | MIT |
def test_creating_client(self):
"""
Please refer to qlib/workflow/expm.py:MLflowExpManager._client
we don't cache _client (this is helpful to reduce maintainance work when MLflowExpManager's uri is chagned)
This implementation is based on the assumption creating a client is fast
... |
Please refer to qlib/workflow/expm.py:MLflowExpManager._client
we don't cache _client (this is helpful to reduce maintainance work when MLflowExpManager's uri is chagned)
This implementation is based on the assumption creating a client is fast
| test_creating_client | python | microsoft/qlib | tests/dependency_tests/test_mlflow.py | https://github.com/microsoft/qlib/blob/master/tests/dependency_tests/test_mlflow.py | MIT |
def test_multi_proc(self):
"""
For testing if it will raise error
"""
iter_n = 2
pool = Pool(iter_n)
res = []
for _ in range(iter_n):
res.append(pool.apply_async(get_features, (self.FIELDS,), {}))
for r in res:
print(r.get())
... |
For testing if it will raise error
| test_multi_proc | python | microsoft/qlib | tests/misc/test_get_multi_proc.py | https://github.com/microsoft/qlib/blob/master/tests/misc/test_get_multi_proc.py | MIT |
def cal_sam_minute(x: pd.Timestamp, sam_minutes: int, region: str):
"""
Sample raw calendar into calendar with sam_minutes freq, shift represents the shift minute the market time
- open time of stock market is [9:30 - shift*pd.Timedelta(minutes=1)]
- mid close time of stock market is [11:29 - sh... |
Sample raw calendar into calendar with sam_minutes freq, shift represents the shift minute the market time
- open time of stock market is [9:30 - shift*pd.Timedelta(minutes=1)]
- mid close time of stock market is [11:29 - shift*pd.Timedelta(minutes=1)]
- mid open time of stock market is [13... | cal_sam_minute | python | microsoft/qlib | tests/misc/test_utils.py | https://github.com/microsoft/qlib/blob/master/tests/misc/test_utils.py | MIT |
def test_update_pred(self):
"""
This test is for testing if it will raise error if the `to_date` is out of the boundary.
"""
task = copy.deepcopy(CSI300_GBDT_TASK)
task["record"] = ["qlib.workflow.record_temp.SignalRecord"]
exp_name = "online_srv_test"
cal = D.... |
This test is for testing if it will raise error if the `to_date` is out of the boundary.
| test_update_pred | python | microsoft/qlib | tests/rolling_tests/test_update_pred.py | https://github.com/microsoft/qlib/blob/master/tests/rolling_tests/test_update_pred.py | MIT |
def test_instrument_storage(self):
"""
The meaning of instrument, such as CSI500:
CSI500 composition changes:
date add remove
2005-01-01 SH600000
2005-01-01 SH600001
2005-01-01 SH600002
... |
The meaning of instrument, such as CSI500:
CSI500 composition changes:
date add remove
2005-01-01 SH600000
2005-01-01 SH600001
2005-01-01 SH600002
2005-02-01 SH600003 SH600000... | test_instrument_storage | python | microsoft/qlib | tests/storage_tests/test_storage.py | https://github.com/microsoft/qlib/blob/master/tests/storage_tests/test_storage.py | MIT |
def test_feature_storage(self):
"""
Calendar:
pd.date_range(start="2005-01-01", stop="2005-03-01", freq="1D")
Instrument:
{
"SH600000": [(2005-01-01, 2005-01-31), (2005-02-15, 2005-03-01)],
"SH600001": [(2005-01-01, 2005-03-01)],
... |
Calendar:
pd.date_range(start="2005-01-01", stop="2005-03-01", freq="1D")
Instrument:
{
"SH600000": [(2005-01-01, 2005-01-31), (2005-02-15, 2005-03-01)],
"SH600001": [(2005-01-01, 2005-03-01)],
"SH600002": [(2005-01-01, 2005-02-14... | test_feature_storage | python | microsoft/qlib | tests/storage_tests/test_storage.py | https://github.com/microsoft/qlib/blob/master/tests/storage_tests/test_storage.py | MIT |
def convert_realtime(
self,
voice_id: str,
*,
text: typing.Iterator[str],
model_id: typing.Optional[str] = OMIT,
output_format: typing.Optional[OutputFormat] = "mp3_44100_128",
voice_settings: typing.Optional[VoiceSettings] = OMIT,
request_options: typing.... |
Converts text into speech using a voice of your choice and returns audio.
Parameters:
- voice_id: str. Voice ID to be used, you can use https://api.elevenlabs.io/v1/voices to list all the available voices.
- text: typing.Iterator[str]. The text that will get converted into spe... | convert_realtime | python | elevenlabs/elevenlabs-python | src/elevenlabs/realtime_tts.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/realtime_tts.py | MIT |
def construct_event(self, rawBody: str, sig_header: str, secret: str) -> Dict:
"""
Constructs a webhook event object from a payload and signature.
Verifies the webhook signature to ensure the event came from ElevenLabs.
Args:
rawBody: The webhook request body. Must be the ra... |
Constructs a webhook event object from a payload and signature.
Verifies the webhook signature to ensure the event came from ElevenLabs.
Args:
rawBody: The webhook request body. Must be the raw body, not a JSON object
sig_header: The signature header from the request
... | construct_event | python | elevenlabs/elevenlabs-python | src/elevenlabs/webhooks.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/webhooks.py | MIT |
def convert(
self,
*,
audio: core.File,
file_format: typing.Optional[AudioIsolationConvertRequestFileFormat] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.Iterator[bytes]:
"""
Removes background noise from audio.
Paramet... |
Removes background noise from audio.
Parameters
----------
audio : core.File
See core.File for more documentation
file_format : typing.Optional[AudioIsolationConvertRequestFileFormat]
The format of input audio. Options are 'pcm_s16le_16' or 'other' For ... | convert | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_isolation/client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_isolation/client.py | MIT |
def stream(
self,
*,
audio: core.File,
file_format: typing.Optional[AudioIsolationStreamRequestFileFormat] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.Iterator[bytes]:
"""
Removes background noise from audio.
Parameter... |
Removes background noise from audio.
Parameters
----------
audio : core.File
See core.File for more documentation
file_format : typing.Optional[AudioIsolationStreamRequestFileFormat]
The format of input audio. Options are 'pcm_s16le_16' or 'other' For `... | stream | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_isolation/client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_isolation/client.py | MIT |
async def convert(
self,
*,
audio: core.File,
file_format: typing.Optional[AudioIsolationConvertRequestFileFormat] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.AsyncIterator[bytes]:
"""
Removes background noise from audio.
... |
Removes background noise from audio.
Parameters
----------
audio : core.File
See core.File for more documentation
file_format : typing.Optional[AudioIsolationConvertRequestFileFormat]
The format of input audio. Options are 'pcm_s16le_16' or 'other' For ... | convert | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_isolation/client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_isolation/client.py | MIT |
async def stream(
self,
*,
audio: core.File,
file_format: typing.Optional[AudioIsolationStreamRequestFileFormat] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.AsyncIterator[bytes]:
"""
Removes background noise from audio.
... |
Removes background noise from audio.
Parameters
----------
audio : core.File
See core.File for more documentation
file_format : typing.Optional[AudioIsolationStreamRequestFileFormat]
The format of input audio. Options are 'pcm_s16le_16' or 'other' For `... | stream | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_isolation/client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_isolation/client.py | MIT |
def convert(
self,
*,
audio: core.File,
file_format: typing.Optional[AudioIsolationConvertRequestFileFormat] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.Iterator[HttpResponse[typing.Iterator[bytes]]]:
"""
Removes background noi... |
Removes background noise from audio.
Parameters
----------
audio : core.File
See core.File for more documentation
file_format : typing.Optional[AudioIsolationConvertRequestFileFormat]
The format of input audio. Options are 'pcm_s16le_16' or 'other' For ... | convert | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_isolation/raw_client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_isolation/raw_client.py | MIT |
def stream(
self,
*,
audio: core.File,
file_format: typing.Optional[AudioIsolationStreamRequestFileFormat] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.Iterator[HttpResponse[typing.Iterator[bytes]]]:
"""
Removes background noise... |
Removes background noise from audio.
Parameters
----------
audio : core.File
See core.File for more documentation
file_format : typing.Optional[AudioIsolationStreamRequestFileFormat]
The format of input audio. Options are 'pcm_s16le_16' or 'other' For `... | stream | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_isolation/raw_client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_isolation/raw_client.py | MIT |
async def convert(
self,
*,
audio: core.File,
file_format: typing.Optional[AudioIsolationConvertRequestFileFormat] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[bytes]]]:
"""
R... |
Removes background noise from audio.
Parameters
----------
audio : core.File
See core.File for more documentation
file_format : typing.Optional[AudioIsolationConvertRequestFileFormat]
The format of input audio. Options are 'pcm_s16le_16' or 'other' For ... | convert | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_isolation/raw_client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_isolation/raw_client.py | MIT |
async def stream(
self,
*,
audio: core.File,
file_format: typing.Optional[AudioIsolationStreamRequestFileFormat] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[bytes]]]:
"""
Rem... |
Removes background noise from audio.
Parameters
----------
audio : core.File
See core.File for more documentation
file_format : typing.Optional[AudioIsolationStreamRequestFileFormat]
The format of input audio. Options are 'pcm_s16le_16' or 'other' For `... | stream | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_isolation/raw_client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_isolation/raw_client.py | MIT |
def create(
self,
*,
name: str,
image: typing.Optional[str] = OMIT,
author: typing.Optional[str] = OMIT,
title: typing.Optional[str] = OMIT,
small: typing.Optional[bool] = OMIT,
text_color: typing.Optional[str] = OMIT,
background_color: typing.Opti... |
Creates Audio Native enabled project, optionally starts conversion and returns project ID and embeddable HTML snippet.
Parameters
----------
name : str
Project name.
image : typing.Optional[str]
(Deprecated) Image URL used in the player. If not provided... | create | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_native/client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_native/client.py | MIT |
def get_settings(
self, project_id: str, *, request_options: typing.Optional[RequestOptions] = None
) -> GetAudioNativeProjectSettingsResponseModel:
"""
Get player settings for the specific project.
Parameters
----------
project_id : str
The ID of the Stu... |
Get player settings for the specific project.
Parameters
----------
project_id : str
The ID of the Studio project.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
GetAudioNativeP... | get_settings | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_native/client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_native/client.py | MIT |
def update(
self,
project_id: str,
*,
file: typing.Optional[core.File] = OMIT,
auto_convert: typing.Optional[bool] = OMIT,
auto_publish: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> AudioNativeEditContentResponseM... |
Updates content for the specific AudioNative Project.
Parameters
----------
project_id : str
The ID of the project to be used. You can use the [List projects](/docs/api-reference/studio/get-projects) endpoint to list all the available projects.
file : typing.Option... | update | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_native/client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_native/client.py | MIT |
async def create(
self,
*,
name: str,
image: typing.Optional[str] = OMIT,
author: typing.Optional[str] = OMIT,
title: typing.Optional[str] = OMIT,
small: typing.Optional[bool] = OMIT,
text_color: typing.Optional[str] = OMIT,
background_color: typin... |
Creates Audio Native enabled project, optionally starts conversion and returns project ID and embeddable HTML snippet.
Parameters
----------
name : str
Project name.
image : typing.Optional[str]
(Deprecated) Image URL used in the player. If not provided... | create | python | elevenlabs/elevenlabs-python | src/elevenlabs/audio_native/client.py | https://github.com/elevenlabs/elevenlabs-python/blob/master/src/elevenlabs/audio_native/client.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.