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 adjustments_from_deltas_no_sids(dense_dates, sparse_dates, column_idx, column_name, asset_idx, deltas): """Collect all the adjustmen...
Collect all the adjustments that occur in a dataset that does not have a sid column. Parameters ---------- dense_dates : pd.DatetimeIndex The dates requested by the loader. sparse_dates : pd.DatetimeIndex The dates that were in the raw data. column_idx : int The index of...
adjustments_from_deltas_no_sids
python
scrtlabs/catalyst
catalyst/pipeline/loaders/blaze/core.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/blaze/core.py
Apache-2.0
def adjustments_from_deltas_with_sids(dense_dates, sparse_dates, column_idx, column_name, asset_idx, deltas): """Collect all t...
Collect all the adjustments that occur in a dataset that has a sid column. Parameters ---------- dense_dates : pd.DatetimeIndex The dates requested by the loader. sparse_dates : pd.DatetimeIndex The dates that were in the raw data. column_idx : int The index of the colum...
adjustments_from_deltas_with_sids
python
scrtlabs/catalyst
catalyst/pipeline/loaders/blaze/core.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/blaze/core.py
Apache-2.0
def load_raw_data(assets, dates, data_query_time, data_query_tz, expr, odo_kwargs, checkpoints=None): """ Given an expression representing data to load, perform normalization and forward-filling and r...
Given an expression representing data to load, perform normalization and forward-filling and return the data, materialized. Only accepts data with a `sid` field. Parameters ---------- assets : pd.int64index the assets to load data for. dates : pd.datetimeindex the simulatio...
load_raw_data
python
scrtlabs/catalyst
catalyst/pipeline/loaders/blaze/utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/blaze/utils.py
Apache-2.0
def _initialize_precalculated_series(self, asset, trading_calendar, trading_days, data_portal): """ Internal method that pre-calculates the benchmark return series for use in the simulation. Parameters ---------- asset: Asset to ...
Internal method that pre-calculates the benchmark return series for use in the simulation. Parameters ---------- asset: Asset to use trading_calendar: TradingCalendar trading_days: pd.DateTimeIndex data_portal: DataPortal Notes -----...
_initialize_precalculated_series
python
scrtlabs/catalyst
catalyst/sources/benchmark_source.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/sources/benchmark_source.py
Apache-2.0
def subtest(iterator, *_names): """ Construct a subtest in a unittest. Consider using ``catalyst.testing.parameter_space`` when subtests are constructed over a single input or over the cross-product of multiple inputs. ``subtest`` works by decorating a function as a subtest. The decorated ...
Construct a subtest in a unittest. Consider using ``catalyst.testing.parameter_space`` when subtests are constructed over a single input or over the cross-product of multiple inputs. ``subtest`` works by decorating a function as a subtest. The decorated function will be run by iterating over ...
subtest
python
scrtlabs/catalyst
catalyst/testing/core.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/testing/core.py
Apache-2.0
def parameter_space(__fail_fast=False, **params): """ Wrapper around subtest that allows passing keywords mapping names to iterables of values. The decorated test function will be called with the cross-product of all possible inputs Examples -------- >>> from unittest import TestCase ...
Wrapper around subtest that allows passing keywords mapping names to iterables of values. The decorated test function will be called with the cross-product of all possible inputs Examples -------- >>> from unittest import TestCase >>> class SomeTestCase(TestCase): ... @paramet...
parameter_space
python
scrtlabs/catalyst
catalyst/testing/core.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/testing/core.py
Apache-2.0
def make_asset_finder(cls): """Returns a new AssetFinder Returns ------- asset_finder : catalyst.assets.AssetFinder """ return cls.enter_class_context(tmp_asset_finder( url=cls.make_asset_finder_db_url(), equities=cls.make_equity_info(), ...
Returns a new AssetFinder Returns ------- asset_finder : catalyst.assets.AssetFinder
make_asset_finder
python
scrtlabs/catalyst
catalyst/testing/fixtures.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/testing/fixtures.py
Apache-2.0
def invert_unique(d, check=True): """ Invert a dictionary with unique values into a dictionary with (k, v) pairs flipped. """ if check: assert len(set(d.values())) == len(d), "Values were not unique!" return {v: k for k, v in iteritems(d)}
Invert a dictionary with unique values into a dictionary with (k, v) pairs flipped.
invert_unique
python
scrtlabs/catalyst
catalyst/utils/control_flow.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/control_flow.py
Apache-2.0
def deprecated(msg=None, stacklevel=2): """ Used to mark a function as deprecated. Parameters ---------- msg : str The message to display in the deprecation warning. stacklevel : int How far up the stack the warning needs to go, before showing the relevant calling lines....
Used to mark a function as deprecated. Parameters ---------- msg : str The message to display in the deprecation warning. stacklevel : int How far up the stack the warning needs to go, before showing the relevant calling lines. Examples -------- @deprecated(msg=...
deprecated
python
scrtlabs/catalyst
catalyst/utils/deprecate.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/deprecate.py
Apache-2.0
def ensure_dtype(func, argname, arg): """ Argument preprocessor that converts the input into a numpy dtype. Examples -------- >>> import numpy as np >>> from catalyst.utils.preprocess import preprocess >>> @preprocess(dtype=ensure_dtype) ... def foo(dtype): ... return dtype ...
Argument preprocessor that converts the input into a numpy dtype. Examples -------- >>> import numpy as np >>> from catalyst.utils.preprocess import preprocess >>> @preprocess(dtype=ensure_dtype) ... def foo(dtype): ... return dtype ... >>> foo(float) dtype('float64') ...
ensure_dtype
python
scrtlabs/catalyst
catalyst/utils/input_validation.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/input_validation.py
Apache-2.0
def ensure_timezone(func, argname, arg): """Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from catalyst.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc') <UTC> """ ...
Argument preprocessor that converts the input into a tzinfo object. Examples -------- >>> from catalyst.utils.preprocess import preprocess >>> @preprocess(tz=ensure_timezone) ... def foo(tz): ... return tz >>> foo('utc') <UTC>
ensure_timezone
python
scrtlabs/catalyst
catalyst/utils/input_validation.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/input_validation.py
Apache-2.0
def ensure_timestamp(func, argname, arg): """Argument preprocessor that converts the input into a pandas Timestamp object. Examples -------- >>> from catalyst.utils.preprocess import preprocess >>> @preprocess(ts=ensure_timestamp) ... def foo(ts): ... return ts >>> foo('2014-01-...
Argument preprocessor that converts the input into a pandas Timestamp object. Examples -------- >>> from catalyst.utils.preprocess import preprocess >>> @preprocess(ts=ensure_timestamp) ... def foo(ts): ... return ts >>> foo('2014-01-01') Timestamp('2014-01-01 00:00:00')
ensure_timestamp
python
scrtlabs/catalyst
catalyst/utils/input_validation.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/input_validation.py
Apache-2.0
def compose_types(a, *cs): """Compose multiple classes together. Parameters ---------- *mcls : tuple[type] The classes that you would like to compose Returns ------- cls : type A type that subclasses all of the types in ``mcls``. Notes ----- A common use case f...
Compose multiple classes together. Parameters ---------- *mcls : tuple[type] The classes that you would like to compose Returns ------- cls : type A type that subclasses all of the types in ``mcls``. Notes ----- A common use case for this is to build composed metac...
compose_types
python
scrtlabs/catalyst
catalyst/utils/metautils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/metautils.py
Apache-2.0
def catalyst_root(environ=None): """ Get the root directory for all catalyst-managed files. For testing purposes, this accepts a dictionary to interpret as the os environment. Parameters ---------- environ : dict, optional A dict to interpret as the os environment. Returns ...
Get the root directory for all catalyst-managed files. For testing purposes, this accepts a dictionary to interpret as the os environment. Parameters ---------- environ : dict, optional A dict to interpret as the os environment. Returns ------- root : string Path ...
catalyst_root
python
scrtlabs/catalyst
catalyst/utils/paths.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/paths.py
Apache-2.0
def handle_response(response, mode): """ handles the response given by the server according to it's status code :param response: the format returned from a request :param mode: Backtest/ status :return: DataFrame/ str """ if response.status_code == 500: raise Exception("issues with ...
handles the response given by the server according to it's status code :param response: the format returned from a request :param mode: Backtest/ status :return: DataFrame/ str
handle_response
python
scrtlabs/catalyst
catalyst/utils/remote.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/remote.py
Apache-2.0
def prepare_args(file, text): """ send the algo as a base64 decoded text object :param file: File :param text: str :return: None, text: str """ if text: text = base64.b64encode(text) else: text = base64.b64encode(bytes(file.read(), 'utf-8')).decode('utf-8') file...
send the algo as a base64 decoded text object :param file: File :param text: str :return: None, text: str
prepare_args
python
scrtlabs/catalyst
catalyst/utils/remote_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/remote_utils.py
Apache-2.0
def is_valid_uuid(uuid_to_test, version=4): """ Check if uuid_to_test is a valid UUID. Parameters ---------- uuid_to_test : str version : {1, 2, 3, 4} Returns ------- `True` if uuid_to_test is a valid UUID, otherwise `False`. Examples -------- >>> is_valid_uuid('c9bf9e...
Check if uuid_to_test is a valid UUID. Parameters ---------- uuid_to_test : str version : {1, 2, 3, 4} Returns ------- `True` if uuid_to_test is a valid UUID, otherwise `False`. Examples -------- >>> is_valid_uuid('c9bf9e57-1685-4c89-bafb-ff5af830be8a') True >>> i...
is_valid_uuid
python
scrtlabs/catalyst
catalyst/utils/remote_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/remote_utils.py
Apache-2.0
def _run(handle_data, initialize, before_trading_start, analyze, algofile, algotext, defines, data_frequency, capital_base, data, bundle, bundle_timestamp, start, end, output, print_alg...
Run a backtest for the given algorithm. This is shared between the cli and :func:`catalyst.run_algo`.
_run
python
scrtlabs/catalyst
catalyst/utils/run_algo.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/run_algo.py
Apache-2.0
def load_extensions(default, extensions, strict, environ, reload=False): """Load all of the given extensions. This should be called by run_algo or the cli. Parameters ---------- default : bool Load the default exension (~/.catalyst/extension.py)? extension : iterable[str] The pa...
Load all of the given extensions. This should be called by run_algo or the cli. Parameters ---------- default : bool Load the default exension (~/.catalyst/extension.py)? extension : iterable[str] The paths to the extensions to load. If the path ends in ``.py`` it is treated...
load_extensions
python
scrtlabs/catalyst
catalyst/utils/run_algo.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/run_algo.py
Apache-2.0
def dumps_with_persistent_ids(obj, protocol=None): """ Performs a pickle dumps on the given object, substituting all references to a TradingEnvironment or AssetFinder with tokenized representations. All arguments are passed to pickle.Pickler and are described therein. """ file = BytesIO() p...
Performs a pickle dumps on the given object, substituting all references to a TradingEnvironment or AssetFinder with tokenized representations. All arguments are passed to pickle.Pickler and are described therein.
dumps_with_persistent_ids
python
scrtlabs/catalyst
catalyst/utils/serialization_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/serialization_utils.py
Apache-2.0
def loads_with_persistent_ids(str, env): """ Performs a pickle loads on the given string, substituting the given TradingEnvironment in to any tokenized representations of a TradingEnvironment or AssetFinder. Parameters ---------- str : String The string representation of the object ...
Performs a pickle loads on the given string, substituting the given TradingEnvironment in to any tokenized representations of a TradingEnvironment or AssetFinder. Parameters ---------- str : String The string representation of the object to be unpickled. env : TradingEnvironment ...
loads_with_persistent_ids
python
scrtlabs/catalyst
catalyst/utils/serialization_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/serialization_utils.py
Apache-2.0
def create_test_catalyst(**config): """ :param config: A configuration object that is a dict with: - sid - an integer, which will be used as the asset ID. - order_count - the number of orders the test algo will place, defaults to 100 - order_amount - the number ...
:param config: A configuration object that is a dict with: - sid - an integer, which will be used as the asset ID. - order_count - the number of orders the test algo will place, defaults to 100 - order_amount - the number of shares per order, defaults to 100 ...
create_test_catalyst
python
scrtlabs/catalyst
catalyst/utils/simfactory.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/simfactory.py
Apache-2.0
def get_calendar(self, name): """ Retrieves an instance of a TradingCalendar whose name is given. Parameters ---------- name : str The name of the TradingCalendar to be retrieved. Returns ------- calendar : catalyst.utils.calendars.TradingCal...
Retrieves an instance of a TradingCalendar whose name is given. Parameters ---------- name : str The name of the TradingCalendar to be retrieved. Returns ------- calendar : catalyst.utils.calendars.TradingCalendar The desired calendar. ...
get_calendar
python
scrtlabs/catalyst
catalyst/utils/calendars/calendar_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/calendar_utils.py
Apache-2.0
def has_calendar(self, name): """ Do we have (or have the ability to make) a calendar with ``name``? """ return ( name in self._calendars or name in self._calendar_factories or name in self._aliases )
Do we have (or have the ability to make) a calendar with ``name``?
has_calendar
python
scrtlabs/catalyst
catalyst/utils/calendars/calendar_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/calendar_utils.py
Apache-2.0
def register_calendar(self, name, calendar, force=False): """ Registers a calendar for retrieval by the get_calendar method. Parameters ---------- name: str The key with which to register this calendar. calendar: TradingCalendar The calendar to be...
Registers a calendar for retrieval by the get_calendar method. Parameters ---------- name: str The key with which to register this calendar. calendar: TradingCalendar The calendar to be registered for retrieval. force : bool, optional ...
register_calendar
python
scrtlabs/catalyst
catalyst/utils/calendars/calendar_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/calendar_utils.py
Apache-2.0
def register_calendar_type(self, name, calendar_type, force=False): """ Registers a calendar by type. This is useful for registering a new calendar to be lazily instantiated at some future point in time. Parameters ---------- name: str The key with w...
Registers a calendar by type. This is useful for registering a new calendar to be lazily instantiated at some future point in time. Parameters ---------- name: str The key with which to register this calendar. calendar_type: type The typ...
register_calendar_type
python
scrtlabs/catalyst
catalyst/utils/calendars/calendar_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/calendar_utils.py
Apache-2.0
def register_calendar_alias(self, alias, real_name, force=False): """ Register an alias for a calendar. This is useful when multiple exchanges should share a calendar, or when there are multiple ways to refer to the same exchange. After calling ``register_alias('alias', 'real_n...
Register an alias for a calendar. This is useful when multiple exchanges should share a calendar, or when there are multiple ways to refer to the same exchange. After calling ``register_alias('alias', 'real_name')``, subsequent calls to ``get_calendar('alias')`` will return th...
register_calendar_alias
python
scrtlabs/catalyst
catalyst/utils/calendars/calendar_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/calendar_utils.py
Apache-2.0
def resolve_alias(self, name): """ Resolve a calendar alias for retrieval. Parameters ---------- name : str The name of the requested calendar. Returns ------- canonical_name : str The real name of the calendar to create/return. ...
Resolve a calendar alias for retrieval. Parameters ---------- name : str The name of the requested calendar. Returns ------- canonical_name : str The real name of the calendar to create/return.
resolve_alias
python
scrtlabs/catalyst
catalyst/utils/calendars/calendar_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/calendar_utils.py
Apache-2.0
def deregister_calendar(self, name): """ If a calendar is registered with the given name, it is de-registered. Parameters ---------- cal_name : str The name of the calendar to be deregistered. """ self._calendars.pop(name, None) self._calendar...
If a calendar is registered with the given name, it is de-registered. Parameters ---------- cal_name : str The name of the calendar to be deregistered.
deregister_calendar
python
scrtlabs/catalyst
catalyst/utils/calendars/calendar_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/calendar_utils.py
Apache-2.0
def next_open(self, dt): """ Given a dt, returns the next open. If the given dt happens to be a session open, the next session's open will be returned. Parameters ---------- dt: pd.Timestamp The dt for which to get the next open. Returns ...
Given a dt, returns the next open. If the given dt happens to be a session open, the next session's open will be returned. Parameters ---------- dt: pd.Timestamp The dt for which to get the next open. Returns ------- pd.Timestamp ...
next_open
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def next_close(self, dt): """ Given a dt, returns the next close. Parameters ---------- dt: pd.Timestamp The dt for which to get the next close. Returns ------- pd.Timestamp The UTC timestamp of the next close. """ ...
Given a dt, returns the next close. Parameters ---------- dt: pd.Timestamp The dt for which to get the next close. Returns ------- pd.Timestamp The UTC timestamp of the next close.
next_close
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def previous_open(self, dt): """ Given a dt, returns the previous open. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous open. Returns ------- pd.Timestamp The UTC imestamp of the previous open. ...
Given a dt, returns the previous open. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous open. Returns ------- pd.Timestamp The UTC imestamp of the previous open.
previous_open
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def previous_close(self, dt): """ Given a dt, returns the previous close. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous close. Returns ------- pd.Timestamp The UTC timestamp of the previous close. ...
Given a dt, returns the previous close. Parameters ---------- dt: pd.Timestamp The dt for which to get the previous close. Returns ------- pd.Timestamp The UTC timestamp of the previous close.
previous_close
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def next_session_label(self, session_label): """ Given a session label, returns the label of the next session. Parameters ---------- session_label: pd.Timestamp A session whose next session is desired. Returns ------- pd.Timestamp ...
Given a session label, returns the label of the next session. Parameters ---------- session_label: pd.Timestamp A session whose next session is desired. Returns ------- pd.Timestamp The next session label (midnight UTC). Notes ...
next_session_label
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def previous_session_label(self, session_label): """ Given a session label, returns the label of the previous session. Parameters ---------- session_label: pd.Timestamp A session whose previous session is desired. Returns ------- pd.Timestamp...
Given a session label, returns the label of the previous session. Parameters ---------- session_label: pd.Timestamp A session whose previous session is desired. Returns ------- pd.Timestamp The previous session label (midnight UTC). ...
previous_session_label
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def minutes_for_session(self, session_label): """ Given a session label, return the minutes for that session. Parameters ---------- session_label: pd.Timestamp (midnight UTC) A session label whose session's minutes are desired. Returns ------- ...
Given a session label, return the minutes for that session. Parameters ---------- session_label: pd.Timestamp (midnight UTC) A session label whose session's minutes are desired. Returns ------- pd.DateTimeIndex All the minutes for the gi...
minutes_for_session
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def sessions_in_range(self, start_session_label, end_session_label): """ Given start and end session labels, return all the sessions in that range, inclusive. Parameters ---------- start_session_label: pd.Timestamp (midnight UTC) The label representing the fi...
Given start and end session labels, return all the sessions in that range, inclusive. Parameters ---------- start_session_label: pd.Timestamp (midnight UTC) The label representing the first session of the desired range. end_session_label: pd.Timestamp (midn...
sessions_in_range
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def sessions_window(self, session_label, count): """ Given a session label and a window size, returns a list of sessions of size `count` + 1, that either starts with the given session (if `count` is positive) or ends with the given session (if `count` is negative). Param...
Given a session label and a window size, returns a list of sessions of size `count` + 1, that either starts with the given session (if `count` is positive) or ends with the given session (if `count` is negative). Parameters ---------- session_label: pd.Timestamp...
sessions_window
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def session_distance(self, start_session_label, end_session_label): """ Given a start and end session label, returns the distance between them. For example, for three consecutive sessions Mon., Tues., and Wed, `session_distance(Mon, Wed)` would return 2. Parameters ----...
Given a start and end session label, returns the distance between them. For example, for three consecutive sessions Mon., Tues., and Wed, `session_distance(Mon, Wed)` would return 2. Parameters ---------- start_session_label: pd.Timestamp The label of the s...
session_distance
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def minutes_in_range(self, start_minute, end_minute): """ Given start and end minutes, return all the calendar minutes in that range, inclusive. Given minutes don't need to be calendar minutes. Parameters ---------- start_minute: pd.Timestamp The min...
Given start and end minutes, return all the calendar minutes in that range, inclusive. Given minutes don't need to be calendar minutes. Parameters ---------- start_minute: pd.Timestamp The minute representing the start of the desired range. end_min...
minutes_in_range
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def minutes_for_sessions_in_range(self, start_session_label, end_session_label): """ Returns all the minutes for all the sessions from the given start session label to the given end session label, inclusive. Parameters ---------- sta...
Returns all the minutes for all the sessions from the given start session label to the given end session label, inclusive. Parameters ---------- start_session_label: pd.Timestamp The label of the first session in the range. end_session_label: pd.Timestamp ...
minutes_for_sessions_in_range
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def open_and_close_for_session(self, session_label): """ Returns a tuple of timestamps of the open and close of the session represented by the given label. Parameters ---------- session_label: pd.Timestamp The session whose open and close are desired. ...
Returns a tuple of timestamps of the open and close of the session represented by the given label. Parameters ---------- session_label: pd.Timestamp The session whose open and close are desired. Returns ------- (Timestamp, Timestamp) ...
open_and_close_for_session
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def _all_minutes_with_interval(self, interval): """ Returns a DatetimeIndex representing all the minutes in this calendar. """ opens_in_ns = \ self._opens.values.astype('datetime64[ns]') closes_in_ns = \ self._closes.values.astype('datetime64[ns]') ...
Returns a DatetimeIndex representing all the minutes in this calendar.
_all_minutes_with_interval
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def minute_to_session_label(self, dt, direction="next"): """ Given a minute, get the label of its containing session. Parameters ---------- dt : pd.Timestamp or nanosecond offset The dt for which to get the containing session. direction: str "nex...
Given a minute, get the label of its containing session. Parameters ---------- dt : pd.Timestamp or nanosecond offset The dt for which to get the containing session. direction: str "next" (default) means that if the given dt is not part of a ...
minute_to_session_label
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def minute_index_to_session_labels(self, index): """ Given a sorted DatetimeIndex of market minutes, return a DatetimeIndex of the corresponding session labels. Parameters ---------- index: pd.DatetimeIndex or pd.Series The ordered list of market minutes we w...
Given a sorted DatetimeIndex of market minutes, return a DatetimeIndex of the corresponding session labels. Parameters ---------- index: pd.DatetimeIndex or pd.Series The ordered list of market minutes we want session labels for. Returns ------- ...
minute_index_to_session_labels
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def _special_dates(self, calendars, ad_hoc_dates, start_date, end_date): """ Union an iterable of pairs of the form (time, calendar) and an iterable of pairs of the form (time, [dates]) (This is shared logic for computing special opens and special closes.) """ _dates = D...
Union an iterable of pairs of the form (time, calendar) and an iterable of pairs of the form (time, [dates]) (This is shared logic for computing special opens and special closes.)
_special_dates
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def days_at_time(days, t, tz, day_offset=0): """ Create an index of days at time ``t``, interpreted in timezone ``tz``. The returned index is localized to UTC. Parameters ---------- days : DatetimeIndex An index of dates (represented as midnight). t : datetime.time The time...
Create an index of days at time ``t``, interpreted in timezone ``tz``. The returned index is localized to UTC. Parameters ---------- days : DatetimeIndex An index of dates (represented as midnight). t : datetime.time The time to apply as an offset to each day in ``days``. ...
days_at_time
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def _overwrite_special_dates(midnight_utcs, opens_or_closes, special_opens_or_closes): """ Overwrite dates in open_or_closes with corresponding dates in special_opens_or_closes, using midnight_utcs for alignment. """ # Short circuit when noth...
Overwrite dates in open_or_closes with corresponding dates in special_opens_or_closes, using midnight_utcs for alignment.
_overwrite_special_dates
python
scrtlabs/catalyst
catalyst/utils/calendars/trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/utils/calendars/trading_calendar.py
Apache-2.0
def test_algo_record_allow_mock(self): """ Test that values from "MagicMock"ed methods can be passed to record. Relevant for our basic/validation and methods like history, which will end up returning a MagicMock instead of a DataFrame. """ test_algo = TradingAlgorithm( ...
Test that values from "MagicMock"ed methods can be passed to record. Relevant for our basic/validation and methods like history, which will end up returning a MagicMock instead of a DataFrame.
test_algo_record_allow_mock
python
scrtlabs/catalyst
tests/test_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_algorithm.py
Apache-2.0
def _test_order_methods(self): """ Only test that order methods can be called without error. Correct filling of orders is tested in catalyst. """ test_algo = TradingAlgorithm( script=call_all_order_methods, sim_params=self.sim_params, env=self....
Only test that order methods can be called without error. Correct filling of orders is tested in catalyst.
_test_order_methods
python
scrtlabs/catalyst
tests/test_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_algorithm.py
Apache-2.0
def _test_order_in_init(self): """ Test that calling order in initialize will raise an error. """ with self.assertRaises(OrderDuringInitialize): test_algo = TradingAlgorithm( script=call_order_in_init, sim_params=self.sim_params, ...
Test that calling order in initialize will raise an error.
_test_order_in_init
python
scrtlabs/catalyst
tests/test_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_algorithm.py
Apache-2.0
def _test_portfolio_in_init(self): """ Test that accessing portfolio in init doesn't break. """ test_algo = TradingAlgorithm( script=access_portfolio_in_init, sim_params=self.sim_params, env=self.env, ) test_algo.run(self.data_portal)
Test that accessing portfolio in init doesn't break.
_test_portfolio_in_init
python
scrtlabs/catalyst
tests/test_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_algorithm.py
Apache-2.0
def _test_account_in_init(self): """ Test that accessing account in init doesn't break. """ test_algo = TradingAlgorithm( script=access_account_in_init, sim_params=self.sim_params, env=self.env, ) test_algo.run(self.data_portal)
Test that accessing account in init doesn't break.
_test_account_in_init
python
scrtlabs/catalyst
tests/test_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_algorithm.py
Apache-2.0
def _test_zero_trading_days(self, name, algocode): """ Test that when we run a simulation with no trading days (e.g. beginning and ending the same weekend), we don't crash on calculating the benchmark """ sim_params = factory.create_simulation_parameters( star...
Test that when we run a simulation with no trading days (e.g. beginning and ending the same weekend), we don't crash on calculating the benchmark
_test_zero_trading_days
python
scrtlabs/catalyst
tests/test_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_algorithm.py
Apache-2.0
def test_can_trade_delisted(self): """ Test that can_trade returns False for an asset on or after its auto close date. """ auto_closing_asset = self.asset_finder.retrieve_asset(7) # Our asset's auto close date is 2016-01-20, which means that as of the # market op...
Test that can_trade returns False for an asset on or after its auto close date.
test_can_trade_delisted
python
scrtlabs/catalyst
tests/test_bar_data.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_bar_data.py
Apache-2.0
def _test_set_portfolio(self): """ Are we protected against overwriting an algo's portfolio? """ algo = SetPortfolioAlgorithm(self.sid, sim_params=self.sim_params, env=self.env) with self.assertRaises(Attr...
Are we protected against overwriting an algo's portfolio?
_test_set_portfolio
python
scrtlabs/catalyst
tests/test_exception_handling.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_exception_handling.py
Apache-2.0
def create_txn(asset, dt, price, amount): """ Create a fake transaction to be filled and processed prior to the execution of a given trade event. """ if not isinstance(asset, Asset): raise ValueError("pass an asset to create_txn") mock_order = Order(dt, asset, amount, id=None) retur...
Create a fake transaction to be filled and processed prior to the execution of a given trade event.
create_txn
python
scrtlabs/catalyst
tests/test_perf_tracking.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_perf_tracking.py
Apache-2.0
def calculate_results(sim_params, env, data_portal, splits=None, txns=None, commissions=None): """ Run the given events through a stripped down version of the loop in AlgorithmSimulator.transform. ...
Run the given events through a stripped down version of the loop in AlgorithmSimulator.transform. IMPORTANT NOTE FOR TEST WRITERS/READERS: This loop has some wonky logic for the order of event processing for datasource types. This exists mostly to accommodate legacy tests that were making as...
calculate_results
python
scrtlabs/catalyst
tests/test_perf_tracking.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_perf_tracking.py
Apache-2.0
def _test_long_short_positions(self): """ start with $1000 buy 100 stock1 shares at $10 sell short 100 stock2 shares at $10 stock1 then goes down to $9 stock2 goes to $11 """ self.create_environment_stuff() trades_1 = factory.create_trade_history(...
start with $1000 buy 100 stock1 shares at $10 sell short 100 stock2 shares at $10 stock1 then goes down to $9 stock2 goes to $11
_test_long_short_positions
python
scrtlabs/catalyst
tests/test_perf_tracking.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_perf_tracking.py
Apache-2.0
def _test_levered_long_position(self): """ start with $1,000, then buy 1000 shares at $10. price goes to $11 """ # post some trades in the market self.create_environment_stuff() trades = factory.create_trade_history( self.asset1, ...
start with $1,000, then buy 1000 shares at $10. price goes to $11
_test_levered_long_position
python
scrtlabs/catalyst
tests/test_perf_tracking.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_perf_tracking.py
Apache-2.0
def _test_long_position(self): """ verify that the performance period calculates properly for a single buy transaction """ self.create_environment_stuff() # post some trades in the market trades = factory.create_trade_history( self.asset1, ...
verify that the performance period calculates properly for a single buy transaction
_test_long_position
python
scrtlabs/catalyst
tests/test_perf_tracking.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_perf_tracking.py
Apache-2.0
def _test_short_position(self): """verify that the performance period calculates properly for a \ single short-sale transaction""" self.create_environment_stuff(num_days=6) trades = factory.create_trade_history( self.asset1, [10, 10, 10, 11, 10, 9], [100, 100...
verify that the performance period calculates properly for a single short-sale transaction
_test_short_position
python
scrtlabs/catalyst
tests/test_perf_tracking.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_perf_tracking.py
Apache-2.0
def _test_covering_short(self): """verify performance where short is bought and covered, and shares \ trade after cover""" self.create_environment_stuff(num_days=10) trades = factory.create_trade_history( self.asset1, [10, 10, 10, 11, 9, 8, 7, 8, 9, 10], [100...
verify performance where short is bought and covered, and shares trade after cover
_test_covering_short
python
scrtlabs/catalyst
tests/test_perf_tracking.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_perf_tracking.py
Apache-2.0
def test_empty_positions(self): """ make sure all the empty position stats return a numeric 0 Originally this bug was due to np.dot([], []) returning np.bool_(False) """ sim_params = factory.create_simulation_parameters(num_days=4) pt = perf.PositionTracker(sim_...
make sure all the empty position stats return a numeric 0 Originally this bug was due to np.dot([], []) returning np.bool_(False)
test_empty_positions
python
scrtlabs/catalyst
tests/test_perf_tracking.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_perf_tracking.py
Apache-2.0
def test_security_list_restrictions(self): """ Test single- and multi-asset queries on restrictions defined by catalyst.utils.security_list.SecurityList """ # A mock SecurityList object filled with fake data class SecurityList(object): def __init__(self, asse...
Test single- and multi-asset queries on restrictions defined by catalyst.utils.security_list.SecurityList
test_security_list_restrictions
python
scrtlabs/catalyst
tests/test_restrictions.py
https://github.com/scrtlabs/catalyst/blob/master/tests/test_restrictions.py
Apache-2.0
def test_new_years(self): """ Check whether the TradingCalendar contains certain dates. """ # January 2012 # Su Mo Tu We Th Fr Sa # 1 2 3 4 5 6 7 # 8 9 10 11 12 13 14 # 15 16 17 18 19 20 21 # 22 23 24 25 26 27 28 # 29 30 31 ...
Check whether the TradingCalendar contains certain dates.
test_new_years
python
scrtlabs/catalyst
tests/calendars/test_nyse_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/tests/calendars/test_nyse_calendar.py
Apache-2.0
def test_early_close_independence_day_thursday(self): """ Until 2013, the market closed early the Friday after an Independence Day on Thursday. Since then, the early close is on Wednesday. """ # July 2002 # Su Mo Tu We Th Fr Sa # 1 2 3 4 5 6...
Until 2013, the market closed early the Friday after an Independence Day on Thursday. Since then, the early close is on Wednesday.
test_early_close_independence_day_thursday
python
scrtlabs/catalyst
tests/calendars/test_nyse_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/tests/calendars/test_nyse_calendar.py
Apache-2.0
def test_start_end(self): """ Check TradingCalendar with defined start/end dates. """ start = pd.Timestamp('2010-1-3', tz='UTC') end = pd.Timestamp('2010-1-10', tz='UTC') calendar = NYSEExchangeCalendar(start=start, end=end) expected_first = pd.Timestamp('2010-1-4...
Check TradingCalendar with defined start/end dates.
test_start_end
python
scrtlabs/catalyst
tests/calendars/test_nyse_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/tests/calendars/test_nyse_calendar.py
Apache-2.0
def load_answer_key(filename): """ Load a CSV from tests/resources/calendars/{filename}.csv """ fullpath = join( dirname(abspath(__file__)), '../resources', 'calendars', filename + '.csv', ) return read_csv( ful...
Load a CSV from tests/resources/calendars/{filename}.csv
load_answer_key
python
scrtlabs/catalyst
tests/calendars/test_trading_calendar.py
https://github.com/scrtlabs/catalyst/blob/master/tests/calendars/test_trading_calendar.py
Apache-2.0
def create_orders_dict(self, asset, last_order): """ create an orders dict which mocks the .orders object :param asset: TradingPair :param last_order: bool, adds another order to the dict. mocks the functionality of the fetchOrder methods :return: dict...
create an orders dict which mocks the .orders object :param asset: TradingPair :param last_order: bool, adds another order to the dict. mocks the functionality of the fetchOrder methods :return: dict(Order)
create_orders_dict
python
scrtlabs/catalyst
tests/exchange/test_ccxt.py
https://github.com/scrtlabs/catalyst/blob/master/tests/exchange/test_ccxt.py
Apache-2.0
def create_trades_dict(self, symbol): """ :param symbol: only for the side effect :return: list(dict) """ trades = list() trades.append( {'info': {'globalTradeID': 369156767, 'tradeID': '8415970', 'rate': '0.0025', 'amount': '0.78', 'tota...
:param symbol: only for the side effect :return: list(dict)
create_trades_dict
python
scrtlabs/catalyst
tests/exchange/test_ccxt.py
https://github.com/scrtlabs/catalyst/blob/master/tests/exchange/test_ccxt.py
Apache-2.0
def mod_last_order(self): """ adds the last order into .orders :return: """ self.last_order = True asset = [pair for pair in self.exchange.assets if pair.symbol == 'eth_usdt'][0] orders_dict = self.create_orders_dict(asset, self.last_order) ...
adds the last order into .orders :return:
mod_last_order
python
scrtlabs/catalyst
tests/exchange/test_ccxt.py
https://github.com/scrtlabs/catalyst/blob/master/tests/exchange/test_ccxt.py
Apache-2.0
def compare_orders(self, observed, expected): """ compares orders arguments to make sure that they are equal :param observed: Order :param expected: Order :return: bool """ return observed.id == expected.id and \ observed.amount == expected.amount and ...
compares orders arguments to make sure that they are equal :param observed: Order :param expected: Order :return: bool
compare_orders
python
scrtlabs/catalyst
tests/exchange/test_ccxt.py
https://github.com/scrtlabs/catalyst/blob/master/tests/exchange/test_ccxt.py
Apache-2.0
def test_create_order_timeout_order(self): """ create_order method tests the handling of a RequestTimeout exception and locating the order, if was created, using the fetchOrders method :return: """ asset = [pair for pair in self.exchange.assets if ...
create_order method tests the handling of a RequestTimeout exception and locating the order, if was created, using the fetchOrders method :return:
test_create_order_timeout_order
python
scrtlabs/catalyst
tests/exchange/test_ccxt.py
https://github.com/scrtlabs/catalyst/blob/master/tests/exchange/test_ccxt.py
Apache-2.0
def test_create_order_timeout_open(self): """ create_order method tests the handling of a RequestTimeout exception and locating the order, if was created, using the fetchOpenOrders method :return: """ asset = [pair for pair in self.exchange.assets if ...
create_order method tests the handling of a RequestTimeout exception and locating the order, if was created, using the fetchOpenOrders method :return:
test_create_order_timeout_open
python
scrtlabs/catalyst
tests/exchange/test_ccxt.py
https://github.com/scrtlabs/catalyst/blob/master/tests/exchange/test_ccxt.py
Apache-2.0
def test_create_order_timeout_closed(self): """ create_order method tests the handling of a RequestTimeout exception and locating the order, if was created, using the fetchClosedOrders method :return: """ asset = [pair for pair in self.exchange.assets if ...
create_order method tests the handling of a RequestTimeout exception and locating the order, if was created, using the fetchClosedOrders method :return:
test_create_order_timeout_closed
python
scrtlabs/catalyst
tests/exchange/test_ccxt.py
https://github.com/scrtlabs/catalyst/blob/master/tests/exchange/test_ccxt.py
Apache-2.0
def test_create_order_timeout_trade(self): """ create_order method tests the handling of a RequestTimeout exception and locating the order, if was created, using the fetchTrades method. checks as well, the case that the order was not created at all, and makes sure an exce...
create_order method tests the handling of a RequestTimeout exception and locating the order, if was created, using the fetchTrades method. checks as well, the case that the order was not created at all, and makes sure an exception is raised in order to retry the creation...
test_create_order_timeout_trade
python
scrtlabs/catalyst
tests/exchange/test_ccxt.py
https://github.com/scrtlabs/catalyst/blob/master/tests/exchange/test_ccxt.py
Apache-2.0
def test_process_order_timeout(self): """ in case of a requestTimeout make sure that the process_order method returns an exception so the retry method can request the trades again. :return: """ asset = [pair for pair in self.exchange.assets if pair.symbol...
in case of a requestTimeout make sure that the process_order method returns an exception so the retry method can request the trades again. :return:
test_process_order_timeout
python
scrtlabs/catalyst
tests/exchange/test_ccxt.py
https://github.com/scrtlabs/catalyst/blob/master/tests/exchange/test_ccxt.py
Apache-2.0
def compare_bundle_with_exchange(self, exchange, assets, end_dt, bar_count, freq, data_frequency, data_portal, field): """ Creates DataFrames from the bundle and exchange for the specified data set. Parameters ---------- exchange: Exc...
Creates DataFrames from the bundle and exchange for the specified data set. Parameters ---------- exchange: Exchange assets end_dt bar_count freq data_frequency data_portal Returns -------
compare_bundle_with_exchange
python
scrtlabs/catalyst
tests/exchange/test_suites/test_suite_bundle.py
https://github.com/scrtlabs/catalyst/blob/master/tests/exchange/test_suites/test_suite_bundle.py
Apache-2.0
def run_graph(self, graph, initial_workspace, mask=None): """ Compute the given TermGraph, seeding the workspace of our engine with `initial_workspace`. Parameters ---------- graph : catalyst.pipeline.graph.TermGraph Graph to run. initial_workspace : ...
Compute the given TermGraph, seeding the workspace of our engine with `initial_workspace`. Parameters ---------- graph : catalyst.pipeline.graph.TermGraph Graph to run. initial_workspace : dict Initial workspace to forward to SimplePipelineEngine...
run_graph
python
scrtlabs/catalyst
tests/pipeline/base.py
https://github.com/scrtlabs/catalyst/blob/master/tests/pipeline/base.py
Apache-2.0
def _utc_localize_index_level_0(df): """``tz_localize`` the first level of a multiindexed dataframe to utc. Mutates df in place. """ idx = df.index df.index = pd.MultiIndex.from_product( (idx.levels[0].tz_localize('utc'), idx.levels[1]), names=idx.names, ) return df
``tz_localize`` the first level of a multiindexed dataframe to utc. Mutates df in place.
_utc_localize_index_level_0
python
scrtlabs/catalyst
tests/pipeline/test_blaze.py
https://github.com/scrtlabs/catalyst/blob/master/tests/pipeline/test_blaze.py
Apache-2.0
def _test_checkpoints(self, checkpoints, ffilled_values=None): """Simple checkpoints test that accepts a checkpoints dataframe and the expected value for 2014-01-03. The underlying data has value -1.0 on 2014-01-01 and 1.0 on 2014-01-04. Parameters ---------- checkpoint...
Simple checkpoints test that accepts a checkpoints dataframe and the expected value for 2014-01-03. The underlying data has value -1.0 on 2014-01-01 and 1.0 on 2014-01-04. Parameters ---------- checkpoints : pd.DataFrame The checkpoints data. ffilled_value :...
_test_checkpoints
python
scrtlabs/catalyst
tests/pipeline/test_blaze.py
https://github.com/scrtlabs/catalyst/blob/master/tests/pipeline/test_blaze.py
Apache-2.0
def retrieve_timesteps( scheduler, num_inference_steps: Optional[int] = None, device: Optional[Union[str, torch.device]] = None, timesteps: Optional[List[int]] = None, sigmas: Optional[List[float]] = None, **kwargs, ): r""" Calls the scheduler's `set_timesteps` method and retrieves times...
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`. Args: scheduler (`SchedulerMixin`): The scheduler to get timesteps from. num_inference_ste...
retrieve_timesteps
python
bytedance/InfiniteYou
pipelines/pipeline_flux_infusenet.py
https://github.com/bytedance/InfiniteYou/blob/master/pipelines/pipeline_flux_infusenet.py
Apache-2.0
def __call__( self, prompt: Union[str, List[str]] = None, prompt_2: Optional[Union[str, List[str]]] = None, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 28, timesteps: List[int] = None, guidance_scale: float = 3.5, ...
Function invoked when calling the pipeline for generation. Args: prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead. prompt_2 (`str` or `List[st...
__call__
python
bytedance/InfiniteYou
pipelines/pipeline_flux_infusenet.py
https://github.com/bytedance/InfiniteYou/blob/master/pipelines/pipeline_flux_infusenet.py
Apache-2.0
def seed_everything(seed, deterministic=False): """Set random seed. Args: seed (int): Seed to be used. deterministic (bool): Whether to set the deterministic option for CUDNN backend, i.e., set `torch.backends.cudnn.deterministic` to True and `torch.backends.cudnn.benchm...
Set random seed. Args: seed (int): Seed to be used. deterministic (bool): Whether to set the deterministic option for CUDNN backend, i.e., set `torch.backends.cudnn.deterministic` to True and `torch.backends.cudnn.benchmark` to False. Default: False.
seed_everything
python
bytedance/InfiniteYou
pipelines/pipeline_infu_flux.py
https://github.com/bytedance/InfiniteYou/blob/master/pipelines/pipeline_infu_flux.py
Apache-2.0
def forward(self, x, latents): """ Args: x (torch.Tensor): image features shape (b, n1, D) latent (torch.Tensor): latent features shape (b, n2, D) """ x = self.norm1(x) latents = self.norm2(latents) b, l, _ ...
Args: x (torch.Tensor): image features shape (b, n1, D) latent (torch.Tensor): latent features shape (b, n2, D)
forward
python
bytedance/InfiniteYou
pipelines/resampler.py
https://github.com/bytedance/InfiniteYou/blob/master/pipelines/resampler.py
Apache-2.0
def get_mock_processor_inputs(array_library, num_tokens=30000): """ logits: (4, 30,000 ) dtype=float input_ids shape: (4, 2048) dtype=int """ if array_library.startswith("torch"): device = array_library.split("_")[1] if "_" in array_library else "cpu" logits = torch.rand((4, num_tok...
logits: (4, 30,000 ) dtype=float input_ids shape: (4, 2048) dtype=int
get_mock_processor_inputs
python
dottxt-ai/outlines
benchmarks/bench_processors.py
https://github.com/dottxt-ai/outlines/blob/master/benchmarks/bench_processors.py
Apache-2.0
def one_cycle(objective: str, task_list, next_task_id: int): """One BabyAGI cycle. It consists in executing the highest-priority task, creating some new tasks given the result, and re-priotizing the tasks. Parameters ---------- objective The overall objective of the session. task_l...
One BabyAGI cycle. It consists in executing the highest-priority task, creating some new tasks given the result, and re-priotizing the tasks. Parameters ---------- objective The overall objective of the session. task_list The current list of tasks to perform. task_id_counte...
one_cycle
python
dottxt-ai/outlines
examples/babyagi.py
https://github.com/dottxt-ai/outlines/blob/master/examples/babyagi.py
Apache-2.0
def call_thunk(self): """Call a vectorized thunk. Thunks have no arguments and can thus be called directly. """ if self.is_coroutine_fn: loop = asyncio.new_event_loop() try: outputs = loop.run_until_complete(self.func()) finally: ...
Call a vectorized thunk. Thunks have no arguments and can thus be called directly.
call_thunk
python
dottxt-ai/outlines
outlines/base.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/base.py
Apache-2.0
def call_no_signature(self, *args, **kwargs): """Call functions and coroutines when no signature is specified. When no signature is specified we assume that all of the function's inputs and outputs are scalars (core dimension of zero). We first broadcast the input arrays, then iterative...
Call functions and coroutines when no signature is specified. When no signature is specified we assume that all of the function's inputs and outputs are scalars (core dimension of zero). We first broadcast the input arrays, then iteratively apply the function over the elements of the br...
call_no_signature
python
dottxt-ai/outlines
outlines/base.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/base.py
Apache-2.0
def call_with_signature(self, *args, **kwargs): """Call functions and coroutines when a signature is specified.""" input_core_dims, output_core_dims = self._in_and_out_core_dimensions # Make sure that the numbers of arguments passed is compatible with # the signature. num_args =...
Call functions and coroutines when a signature is specified.
call_with_signature
python
dottxt-ai/outlines
outlines/base.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/base.py
Apache-2.0
def vectorize_call(self, broadcast_shape, args, kwargs): """Run the function in a for loop. A possible extension would be to parallelize the calls. Parameters ---------- broadcast_shape The brodcast shape of the input arrays. args The function's ...
Run the function in a for loop. A possible extension would be to parallelize the calls. Parameters ---------- broadcast_shape The brodcast shape of the input arrays. args The function's broadcasted arguments. kwargs The function's bro...
vectorize_call
python
dottxt-ai/outlines
outlines/base.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/base.py
Apache-2.0
def vectorize_call_coroutine(self, broadcast_shape, args, kwargs): """Run coroutines concurrently. Creates as many tasks as needed and executes them in a new event loop. Parameters ---------- broadcast_shape The brodcast shape of the input arrays. ar...
Run coroutines concurrently. Creates as many tasks as needed and executes them in a new event loop. Parameters ---------- broadcast_shape The brodcast shape of the input arrays. args The function's broadcasted arguments. kwargs ...
vectorize_call_coroutine
python
dottxt-ai/outlines
outlines/base.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/base.py
Apache-2.0
def _update_arrays_type(arrays, results): """Update the dtype of arrays. String arrays contain strings of fixed length. Here they are initialized with the type of the first results, so that if the next results contain longer strings they will be truncated when added to the output arrays. Here we up...
Update the dtype of arrays. String arrays contain strings of fixed length. Here they are initialized with the type of the first results, so that if the next results contain longer strings they will be truncated when added to the output arrays. Here we update the type if the current results contain long...
_update_arrays_type
python
dottxt-ai/outlines
outlines/base.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/base.py
Apache-2.0
def get_cache(): """Get the context object that contains previously-computed return values. The cache is used to avoid unnecessary computations and API calls, which can be long and expensive for large models. The cache directory defaults to `HOMEDIR/.cache/outlines`, but this choice can be overrid...
Get the context object that contains previously-computed return values. The cache is used to avoid unnecessary computations and API calls, which can be long and expensive for large models. The cache directory defaults to `HOMEDIR/.cache/outlines`, but this choice can be overridden by the user by setti...
get_cache
python
dottxt-ai/outlines
outlines/caching.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/caching.py
Apache-2.0
def cache(expire: Optional[float] = None, typed=False, ignore=()): """Caching decorator for memoizing function calls. The cache key is created based on the values returned by the key_function callable if provided or based on the arguments of the decorated function directly otherwise This is based on `...
Caching decorator for memoizing function calls. The cache key is created based on the values returned by the key_function callable if provided or based on the arguments of the decorated function directly otherwise This is based on `diskcache`'s `memoize`. Parameters ---------- expire ...
cache
python
dottxt-ai/outlines
outlines/caching.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/caching.py
Apache-2.0
def disable_cache(): """Disable the cache for this session. Generative models output different results each time they are called when sampling. This can be a desirable property for some workflows, in which case one can call `outlines.call.disable` to disable the cache for the session. This functio...
Disable the cache for this session. Generative models output different results each time they are called when sampling. This can be a desirable property for some workflows, in which case one can call `outlines.call.disable` to disable the cache for the session. This function does not delete the cache,...
disable_cache
python
dottxt-ai/outlines
outlines/caching.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/caching.py
Apache-2.0
def init_generator(self): """Load the model and initialize the generator.""" model = models.transformers(self.model_name) self.generator = generate.json(model, self.schema)
Load the model and initialize the generator.
init_generator
python
dottxt-ai/outlines
outlines/function.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/function.py
Apache-2.0
def __call__(self, *args, **kwargs): """Call the function. .. warning:: This currently does not support batching. Parameters ---------- args Values to pass to the prompt template as positional arguments. kwargs Values to pass to the p...
Call the function. .. warning:: This currently does not support batching. Parameters ---------- args Values to pass to the prompt template as positional arguments. kwargs Values to pass to the prompt template as keyword arguments.
__call__
python
dottxt-ai/outlines
outlines/function.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/function.py
Apache-2.0
def download_from_github(short_path: str): """Download the file in which the function is stored on GitHub.""" GITHUB_BASE_URL = "https://raw.githubusercontent.com" BRANCH = "main" path = short_path.split("/") if len(path) < 3: raise ValueError( "Please provide a valid path in th...
Download the file in which the function is stored on GitHub.
download_from_github
python
dottxt-ai/outlines
outlines/function.py
https://github.com/dottxt-ai/outlines/blob/master/outlines/function.py
Apache-2.0