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 _calculate_execution_cash_flow(txn): """ Calculates the cash flow from executing the given transaction """ if isinstance(txn.asset, Future): return 0.0 # When running on live mode and the commission is reduced from the # quote, means that the commission w...
Calculates the cash flow from executing the given transaction
_calculate_execution_cash_flow
python
scrtlabs/catalyst
catalyst/finance/performance/period.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/performance/period.py
Apache-2.0
def to_dict(self, dt=None): """ Creates a dictionary representing the state of this performance period. See header comments for a detailed description. Kwargs: dt (datetime): If present, only return transactions for the dt. """ rval = self.__core_dict() ...
Creates a dictionary representing the state of this performance period. See header comments for a detailed description. Kwargs: dt (datetime): If present, only return transactions for the dt.
to_dict
python
scrtlabs/catalyst
catalyst/finance/performance/period.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/performance/period.py
Apache-2.0
def as_portfolio(self): """ The purpose of this method is to provide a portfolio object to algorithms running inside the same trading client. The data needed is captured raw in a PerformancePeriod, and in this method we rename some fields for usability and remove extraneo...
The purpose of this method is to provide a portfolio object to algorithms running inside the same trading client. The data needed is captured raw in a PerformancePeriod, and in this method we rename some fields for usability and remove extraneous fields.
as_portfolio
python
scrtlabs/catalyst
catalyst/finance/performance/period.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/performance/period.py
Apache-2.0
def handle_splits(self, splits): """ Processes a list of splits by modifying any positions as needed. Parameters ---------- splits: list A list of splits. Each split is a tuple of (asset, ratio). Returns ------- int: The leftover cash from f...
Processes a list of splits by modifying any positions as needed. Parameters ---------- splits: list A list of splits. Each split is a tuple of (asset, ratio). Returns ------- int: The leftover cash from fractional sahres after modifying each ...
handle_splits
python
scrtlabs/catalyst
catalyst/finance/performance/position_tracker.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/performance/position_tracker.py
Apache-2.0
def earn_dividends(self, dividends, stock_dividends): """ Given a list of dividends whose ex_dates are all the next trading day, calculate and store the cash and/or stock payments to be paid on each dividend's pay date. Parameters ---------- dividends: iterable o...
Given a list of dividends whose ex_dates are all the next trading day, calculate and store the cash and/or stock payments to be paid on each dividend's pay date. Parameters ---------- dividends: iterable of (asset, amount, pay_date) namedtuples stock_dividends:...
earn_dividends
python
scrtlabs/catalyst
catalyst/finance/performance/position_tracker.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/performance/position_tracker.py
Apache-2.0
def to_dict(self, emission_type=None): """ Creates a dictionary representing the state of this tracker. Returns a dict object of the form described in header comments. """ # Default to the emission rate of this tracker if no type is provided if emission_type is None: ...
Creates a dictionary representing the state of this tracker. Returns a dict object of the form described in header comments.
to_dict
python
scrtlabs/catalyst
catalyst/finance/performance/tracker.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/performance/tracker.py
Apache-2.0
def check_upcoming_dividends(self, next_session, adjustment_reader): """ Check if we currently own any stocks with dividends whose ex_date is the next trading day. Track how much we should be payed on those dividends' pay dates. Then check if we are owed cash/stock for any divi...
Check if we currently own any stocks with dividends whose ex_date is the next trading day. Track how much we should be payed on those dividends' pay dates. Then check if we are owed cash/stock for any dividends whose pay date is the next trading day. Apply all such benefits, ...
check_upcoming_dividends
python
scrtlabs/catalyst
catalyst/finance/performance/tracker.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/performance/tracker.py
Apache-2.0
def handle_minute_close(self, dt, data_portal): """ Handles the close of the given minute in minute emission. Parameters __________ dt : Timestamp The minute that is ending Returns _______ A minute perf packet. """ self.positi...
Handles the close of the given minute in minute emission. Parameters __________ dt : Timestamp The minute that is ending Returns _______ A minute perf packet.
handle_minute_close
python
scrtlabs/catalyst
catalyst/finance/performance/tracker.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/performance/tracker.py
Apache-2.0
def handle_market_close(self, dt, data_portal): """ Handles the close of the given day, in both minute and daily emission. In daily emission, also updates performance, benchmark and risk metrics as it would in handle_minute_close if it were minute emission. Parameters __...
Handles the close of the given day, in both minute and daily emission. In daily emission, also updates performance, benchmark and risk metrics as it would in handle_minute_close if it were minute emission. Parameters __________ dt : Timestamp The minute that...
handle_market_close
python
scrtlabs/catalyst
catalyst/finance/performance/tracker.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/performance/tracker.py
Apache-2.0
def to_dict(self): """ Creates a dictionary representing the state of the risk report. Returns a dict object of the form: """ dt = self.latest_dt dt_loc = self.latest_dt_loc period_label = dt.strftime("%Y-%m") rval = { 'trading_days': self.num_...
Creates a dictionary representing the state of the risk report. Returns a dict object of the form:
to_dict
python
scrtlabs/catalyst
catalyst/finance/risk/cumulative.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/risk/cumulative.py
Apache-2.0
def __init__(self, algorithm_returns, sim_params, trading_calendar, treasury_curves, benchmark_returns, algorithm_leverages=None): """ algorithm_returns needs to be a list of daily_return objects sorted in date ascending order account needs to be a list...
algorithm_returns needs to be a list of daily_return objects sorted in date ascending order account needs to be a list of account objects sorted in date ascending order
__init__
python
scrtlabs/catalyst
catalyst/finance/risk/report.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/risk/report.py
Apache-2.0
def to_dict(self): """ RiskMetrics are calculated for rolling windows in four lengths:: - 1_month - 3_month - 6_month - 12_month The return value of this function is a dictionary keyed by the above list of durations. The value of each entr...
RiskMetrics are calculated for rolling windows in four lengths:: - 1_month - 3_month - 6_month - 12_month The return value of this function is a dictionary keyed by the above list of durations. The value of each entry is a list of RiskMetric ...
to_dict
python
scrtlabs/catalyst
catalyst/finance/risk/report.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/risk/report.py
Apache-2.0
def choose_treasury(select_treasury, treasury_curves, start_session, end_session, trading_calendar, compound=True): """ Find the latest known interest rate for a given duration within a date range. If we find one but it's more than a trading day ago from the date we're looking f...
Find the latest known interest rate for a given duration within a date range. If we find one but it's more than a trading day ago from the date we're looking for, then we log a warning
choose_treasury
python
scrtlabs/catalyst
catalyst/finance/risk/risk.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/finance/risk/risk.py
Apache-2.0
def _normalize_array(data, missing_value): """ Coerce buffer data for an AdjustedArray into a standard scalar representation, returning the coerced array and a dict of argument to pass to np.view to use when providing a user-facing view of the underlying data. - float* data is coerced to float64 wi...
Coerce buffer data for an AdjustedArray into a standard scalar representation, returning the coerced array and a dict of argument to pass to np.view to use when providing a user-facing view of the underlying data. - float* data is coerced to float64 with viewtype float64. - int32, int64, and uint3...
_normalize_array
python
scrtlabs/catalyst
catalyst/lib/adjusted_array.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/lib/adjusted_array.py
Apache-2.0
def ensure_ndarray(ndarray_or_adjusted_array): """ Return the input as a numpy ndarray. This is a no-op if the input is already an ndarray. If the input is an adjusted_array, this extracts a read-only view of its internal data buffer. Parameters ---------- ndarray_or_adjusted_array : nump...
Return the input as a numpy ndarray. This is a no-op if the input is already an ndarray. If the input is an adjusted_array, this extracts a read-only view of its internal data buffer. Parameters ---------- ndarray_or_adjusted_array : numpy.ndarray | catalyst.data.adjusted_array Returns ...
ensure_ndarray
python
scrtlabs/catalyst
catalyst/lib/adjusted_array.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/lib/adjusted_array.py
Apache-2.0
def process_temp_bundle(self, ds_name, path): """ Merge the temp bundle into the main bundle for the specified data source. Parameters ---------- ds_name path Returns ------- """ tmp_bundle = extract_bundle(path) bundle_f...
Merge the temp bundle into the main bundle for the specified data source. Parameters ---------- ds_name path Returns -------
process_temp_bundle
python
scrtlabs/catalyst
catalyst/marketplace/marketplace.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/marketplace/marketplace.py
Apache-2.0
def get_key_secret(pubAddr, wallet): """ Obtain a new key/secret pair from authentication server Parameters ---------- pubAddr: str dataset: str Returns ------- key: str secret: str """ session = requests.Session() response = session.get('{}/marketplace/getkeysecre...
Obtain a new key/secret pair from authentication server Parameters ---------- pubAddr: str dataset: str Returns ------- key: str secret: str
get_key_secret
python
scrtlabs/catalyst
catalyst/marketplace/utils/auth_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/marketplace/utils/auth_utils.py
Apache-2.0
def get_signed_headers(ds_name, key, secret): """ Return a new request header including the key / secret signature Parameters ---------- ds_name key secret Returns ------- """ nonce = str(int(time.time() * 1000)) signature = hmac.new( secret.encode('utf-8'), ...
Return a new request header including the key / secret signature Parameters ---------- ds_name key secret Returns -------
get_signed_headers
python
scrtlabs/catalyst
catalyst/marketplace/utils/auth_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/marketplace/utils/auth_utils.py
Apache-2.0
def get_marketplace_folder(environ=None): """ The root path of the marketplace folder. Parameters ---------- environ: Returns ------- str """ if not environ: environ = os.environ root = data_root(environ) marketplace_folder = os.path.join(root, 'marketplace') ...
The root path of the marketplace folder. Parameters ---------- environ: Returns ------- str
get_marketplace_folder
python
scrtlabs/catalyst
catalyst/marketplace/utils/path_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/marketplace/utils/path_utils.py
Apache-2.0
def get_data_source_folder(data_source_name, environ=None): """ The root path of an data_source folder. Parameters ---------- data_source_name: str environ: Returns ------- str """ if not environ: environ = os.environ root = data_root(environ) data_source_...
The root path of an data_source folder. Parameters ---------- data_source_name: str environ: Returns ------- str
get_data_source_folder
python
scrtlabs/catalyst
catalyst/marketplace/utils/path_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/marketplace/utils/path_utils.py
Apache-2.0
def get_temp_bundles_folder(environ=None): """ The temp folder for bundle downloads by algo name. Parameters ---------- ds_name: str environ: Returns ------- str """ root = data_root(environ) folder = os.path.join(root, 'marketplace', 'temp_bundles') ensure_directo...
The temp folder for bundle downloads by algo name. Parameters ---------- ds_name: str environ: Returns ------- str
get_temp_bundles_folder
python
scrtlabs/catalyst
catalyst/marketplace/utils/path_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/marketplace/utils/path_utils.py
Apache-2.0
def extract_bundle(tar_filename): """ Extract a bcolz bundle. Parameters ---------- ds_name Returns ------- str """ target_path = tar_filename.replace('.tar.gz', '') with tarfile.open(tar_filename, 'r') as tar: tar.extractall(target_path) return target_path
Extract a bcolz bundle. Parameters ---------- ds_name Returns ------- str
extract_bundle
python
scrtlabs/catalyst
catalyst/marketplace/utils/path_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/marketplace/utils/path_utils.py
Apache-2.0
def get_user_pubaddr(environ=None): """ The de-serialized content of the user's addresses.json file. Parameters ---------- environ: Returns ------- Object """ marketplace_folder = get_marketplace_folder(environ) filename = os.path.join(marketplace_folder, 'addresses.json')...
The de-serialized content of the user's addresses.json file. Parameters ---------- environ: Returns ------- Object
get_user_pubaddr
python
scrtlabs/catalyst
catalyst/marketplace/utils/path_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/marketplace/utils/path_utils.py
Apache-2.0
def save_user_pubaddr(data, environ=None): """ Saves the user's public addresses and their related metadata in the corresponding addresses.json file. Parameters ---------- data: dict Returns ------- True """ marketplace_folder = get_marketplace_folder(environ) filename...
Saves the user's public addresses and their related metadata in the corresponding addresses.json file. Parameters ---------- data: dict Returns ------- True
save_user_pubaddr
python
scrtlabs/catalyst
catalyst/marketplace/utils/path_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/marketplace/utils/path_utils.py
Apache-2.0
def _adjust_returns(returns, adjustment_factor): """ Returns the returns series adjusted by adjustment_factor. Optimizes for the case of adjustment_factor being 0 by returning returns itself, not a copy! Parameters ---------- returns : pd.Series or np.ndarray adjustment_factor : pd.Series o...
Returns the returns series adjusted by adjustment_factor. Optimizes for the case of adjustment_factor being 0 by returning returns itself, not a copy! Parameters ---------- returns : pd.Series or np.ndarray adjustment_factor : pd.Series or np.ndarray or float or int Returns ------- ...
_adjust_returns
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def annualization_factor(period, annualization): """ Return annualization factor from period entered or if a custom value is passed in. Parameters ---------- period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annua...
Return annualization factor from period entered or if a custom value is passed in. Parameters ---------- period : str, optional Defines the periodicity of the 'returns' data for purposes of annualizing. Value ignored if `annualization` parameter is specified. Defaults are: ...
annualization_factor
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def cum_returns(returns, starting_value=0): """ Compute cumulative returns from simple returns. Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy as a percentage, noncumulative. - Time series with decimal returns. - Example: 2015-0...
Compute cumulative returns from simple returns. Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy as a percentage, noncumulative. - Time series with decimal returns. - Example: 2015-07-16 -0.012143 2015-07-17 0.04535...
cum_returns
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def cum_returns_final(returns, starting_value=0): """ Compute total returns from simple returns. Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy as a percentage, noncumulative. - Time series with decimal returns. - Example: 2015-...
Compute total returns from simple returns. Parameters ---------- returns : pd.Series or np.ndarray Returns of the strategy as a percentage, noncumulative. - Time series with decimal returns. - Example: 2015-07-16 -0.012143 2015-07-17 0.045350 ...
cum_returns_final
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def array_wrap(arg_name, _not_specified=object()): """ Decorator for functions working on array_likes that ensures the type of output matches that of the input, delegating to the input's __array_wrap__. Parameters ---------- arg_name : str The name of the array_like arg to the wrapped ...
Decorator for functions working on array_likes that ensures the type of output matches that of the input, delegating to the input's __array_wrap__. Parameters ---------- arg_name : str The name of the array_like arg to the wrapped function. Should be the first positional parameter...
array_wrap
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def nancumsum(a, axis=None, dtype=None): """ Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros. Handles a subset of the edge cases handled by the n...
Return the cumulative sum of array elements over a given axis treating Not a Numbers (NaNs) as zero. The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros. Handles a subset of the edge cases handled by the nancumsum added in numpy 1.12.0. Paramet...
nancumsum
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def aggregate_returns(returns, convert_to): """ Aggregates returns by week, month, or year. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. convert_to : str Can be 'wee...
Aggregates returns by week, month, or year. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. convert_to : str Can be 'weekly', 'monthly', or 'yearly'. Returns ----...
aggregate_returns
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def max_drawdown(returns): """ Determines the maximum drawdown of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. Returns ------- float ...
Determines the maximum drawdown of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. Returns ------- float Maximum drawdown. Note ...
max_drawdown
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def annual_return(returns, period=DAILY, annualization=None): """Determines the mean annual growth rate of returns. Parameters ---------- returns : pd.Series or np.ndarray Periodic returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. ...
Determines the mean annual growth rate of returns. Parameters ---------- returns : pd.Series or np.ndarray Periodic returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. period : str, optional Defines the periodicity of the 'retu...
annual_return
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def annual_volatility(returns, period=DAILY, alpha=2.0, annualization=None): """ Determines the annual volatility of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Periodic returns of the strategy, noncumulative. - See full explanation in :...
Determines the annual volatility of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Periodic returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. period : str, optional Defines the periodicity of the 're...
annual_volatility
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def calmar_ratio(returns, period=DAILY, annualization=None): """ Determines the Calmar ratio, or drawdown ratio, of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum...
Determines the Calmar ratio, or drawdown ratio, of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. period : str, optional Defines the periodicit...
calmar_ratio
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def omega_ratio(returns, risk_free=0.0, required_return=0.0, annualization=APPROX_BDAYS_PER_YEAR): """Determines the Omega ratio of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in...
Determines the Omega ratio of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. risk_free : int, float Constant risk-free return throughout the period ...
omega_ratio
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def sharpe_ratio(returns, risk_free=0, period=DAILY, annualization=None): """ Determines the Sharpe ratio of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_return...
Determines the Sharpe ratio of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. risk_free : int, float Constant risk-free return throughout the p...
sharpe_ratio
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def sortino_ratio(returns, required_return=0, period=DAILY, annualization=None, _downside_risk=None): """ Determines the Sortino ratio of a strategy. Parameters ---------- returns : pd.Series or np.ndarray or pd.DataFrame Daily returns of the strategy, noncumulative. ...
Determines the Sortino ratio of a strategy. Parameters ---------- returns : pd.Series or np.ndarray or pd.DataFrame Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. required_return: float / series minimum acceptab...
sortino_ratio
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def downside_risk(returns, required_return=0, period=DAILY, annualization=None): """ Determines the downside deviation below a threshold Parameters ---------- returns : pd.Series or np.ndarray or pd.DataFrame Daily returns of the strategy, noncumulative. - See full...
Determines the downside deviation below a threshold Parameters ---------- returns : pd.Series or np.ndarray or pd.DataFrame Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. required_return: float / series minimum ...
downside_risk
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def information_ratio(returns, factor_returns): """ Determines the Information ratio of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_return...
Determines the Information ratio of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns: float / series Benchmark return to compare r...
information_ratio
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def _aligned_series(*many_series): """ Return a new list of series containing the data in the input series, but with their indices aligned. NaNs will be filled in for missing values. Parameters ---------- many_series : list[pd.Series] Returns ------- aligned_series : list[pd.Series...
Return a new list of series containing the data in the input series, but with their indices aligned. NaNs will be filled in for missing values. Parameters ---------- many_series : list[pd.Series] Returns ------- aligned_series : list[pd.Series] A new list of series containing...
_aligned_series
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def alpha_beta(returns, factor_returns, risk_free=0.0, period=DAILY, annualization=None): """Calculates annualized alpha and beta. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum...
Calculates annualized alpha and beta. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series Daily noncumulative returns of the factor to which beta is ...
alpha_beta
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def alpha_beta_aligned(returns, factor_returns, risk_free=0.0, period=DAILY, annualization=None): """Calculates annualized alpha and beta. If they are pd.Series, expects returns and factor_returns have already been aligned on their labels. If np.ndarray, these arguments should have ...
Calculates annualized alpha and beta. If they are pd.Series, expects returns and factor_returns have already been aligned on their labels. If np.ndarray, these arguments should have the same shape. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, ...
alpha_beta_aligned
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def alpha(returns, factor_returns, risk_free=0.0, period=DAILY, annualization=None, _beta=None): """Calculates annualized alpha. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_return...
Calculates annualized alpha. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series Daily noncumulative returns of the factor to which beta is co...
alpha
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def alpha_aligned(returns, factor_returns, risk_free=0.0, period=DAILY, annualization=None, _beta=None): """Calculates annualized alpha. If they are pd.Series, expects returns and factor_returns have already been aligned on their labels. If np.ndarray, these arguments should have the...
Calculates annualized alpha. If they are pd.Series, expects returns and factor_returns have already been aligned on their labels. If np.ndarray, these arguments should have the same shape. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumula...
alpha_aligned
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def beta(returns, factor_returns, risk_free=0.0): """Calculates beta. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series Daily noncumulative retur...
Calculates beta. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. factor_returns : pd.Series Daily noncumulative returns of the factor to which beta is computed. Usua...
beta
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def beta_aligned(returns, factor_returns, risk_free=0.0): """Calculates beta. If they are pd.Series, expects returns and factor_returns have already been aligned on their labels. If np.ndarray, these arguments should have the same shape. Parameters ---------- returns : pd.Series or np.nda...
Calculates beta. If they are pd.Series, expects returns and factor_returns have already been aligned on their labels. If np.ndarray, these arguments should have the same shape. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. ...
beta_aligned
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def stability_of_timeseries(returns): """Determines R-squared of a linear fit to the cumulative log returns. Computes an ordinary least squares linear fit, and returns R-squared. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. ...
Determines R-squared of a linear fit to the cumulative log returns. Computes an ordinary least squares linear fit, and returns R-squared. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical...
stability_of_timeseries
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def tail_ratio(returns): """Determines the ratio between the right (95%) and left tail (5%). For example, a ratio of 0.25 means that losses are four times as bad as profits. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. -...
Determines the ratio between the right (95%) and left tail (5%). For example, a ratio of 0.25 means that losses are four times as bad as profits. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`...
tail_ratio
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def cagr(returns, period=DAILY, annualization=None): """ Compute compound annual growth rate. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. period : str, optio...
Compute compound annual growth rate. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. period : str, optional Defines the periodicity of the 'returns' data fo...
cagr
python
scrtlabs/catalyst
catalyst/patches/stats.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/patches/stats.py
Apache-2.0
def restrict_to_dtype(dtype, message_template): """ A factory for decorators that restrict Term methods to only be callable on Terms with a specific dtype. This is conceptually similar to catalyst.utils.input_validation.expect_dtypes, but provides more flexibility for providing error messages t...
A factory for decorators that restrict Term methods to only be callable on Terms with a specific dtype. This is conceptually similar to catalyst.utils.input_validation.expect_dtypes, but provides more flexibility for providing error messages that are specifically targeting Term methods. P...
restrict_to_dtype
python
scrtlabs/catalyst
catalyst/pipeline/api_utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/api_utils.py
Apache-2.0
def run_pipeline(self, pipeline, start_date, end_date): """ Compute a pipeline. The algorithm implemented here can be broken down into the following stages: 0. Build a dependency graph of all terms in `pipeline`. Topologically sort the graph to determine an order in...
Compute a pipeline. The algorithm implemented here can be broken down into the following stages: 0. Build a dependency graph of all terms in `pipeline`. Topologically sort the graph to determine an order in which we can compute the terms. 1. Ask our Ass...
run_pipeline
python
scrtlabs/catalyst
catalyst/pipeline/engine.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/engine.py
Apache-2.0
def _compute_root_mask(self, start_date, end_date, extra_rows): """ Compute a lifetimes matrix from our AssetFinder, then drop columns that didn't exist at all during the query dates. Parameters ---------- start_date : pd.Timestamp Base start date for the mat...
Compute a lifetimes matrix from our AssetFinder, then drop columns that didn't exist at all during the query dates. Parameters ---------- start_date : pd.Timestamp Base start date for the matrix. end_date : pd.Timestamp End date for the matrix. ...
_compute_root_mask
python
scrtlabs/catalyst
catalyst/pipeline/engine.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/engine.py
Apache-2.0
def compute_chunk(self, graph, dates, assets, initial_workspace): """ Compute the Pipeline terms in the graph for the requested start and end dates. Parameters ---------- graph : catalyst.pipeline.graph.TermGraph dates : pd.DatetimeIndex Row labels fo...
Compute the Pipeline terms in the graph for the requested start and end dates. Parameters ---------- graph : catalyst.pipeline.graph.TermGraph dates : pd.DatetimeIndex Row labels for our root mask. assets : pd.Int64Index Column labels for...
compute_chunk
python
scrtlabs/catalyst
catalyst/pipeline/engine.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/engine.py
Apache-2.0
def execution_order(self, refcounts): """ Return a topologically-sorted iterator over the terms in ``self`` which need to be computed. """ return iter(topological_sort( self.graph.subgraph( {term for term, refcount in refcounts.items() if refcount > 0}...
Return a topologically-sorted iterator over the terms in ``self`` which need to be computed.
execution_order
python
scrtlabs/catalyst
catalyst/pipeline/graph.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/graph.py
Apache-2.0
def _decref_depencies_recursive(self, term, refcounts, garbage): """ Decrement terms recursively. Notes ----- This should only be used to build the initial workspace, after that we should use: :meth:`~catalyst.pipeline.graph.TermGraph.decref_dependencies` ...
Decrement terms recursively. Notes ----- This should only be used to build the initial workspace, after that we should use: :meth:`~catalyst.pipeline.graph.TermGraph.decref_dependencies`
_decref_depencies_recursive
python
scrtlabs/catalyst
catalyst/pipeline/graph.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/graph.py
Apache-2.0
def decref_dependencies(self, term, refcounts): """ Decrement in-edges for ``term`` after computation. Parameters ---------- term : catalyst.pipeline.Term The term whose parents should be decref'ed. refcounts : dict[Term -> int] Dictionary of refc...
Decrement in-edges for ``term`` after computation. Parameters ---------- term : catalyst.pipeline.Term The term whose parents should be decref'ed. refcounts : dict[Term -> int] Dictionary of refcounts. Return ------ garbage : set...
decref_dependencies
python
scrtlabs/catalyst
catalyst/pipeline/graph.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/graph.py
Apache-2.0
def offset(self): """ For all pairs (term, input) such that `input` is an input to `term`, compute a mapping:: (term, input) -> offset(term, input) where ``offset(term, input)`` is the number of rows that ``term`` should truncate off the raw array produced for ``inp...
For all pairs (term, input) such that `input` is an input to `term`, compute a mapping:: (term, input) -> offset(term, input) where ``offset(term, input)`` is the number of rows that ``term`` should truncate off the raw array produced for ``input`` before using it....
offset
python
scrtlabs/catalyst
catalyst/pipeline/graph.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/graph.py
Apache-2.0
def extra_rows(self): """ A dict mapping `term` -> `# of extra rows to load/compute of `term`. Notes ---- This value depends on the other terms in the graph that require `term` **as an input**. This is not to be confused with `term.dependencies`, which describes...
A dict mapping `term` -> `# of extra rows to load/compute of `term`. Notes ---- This value depends on the other terms in the graph that require `term` **as an input**. This is not to be confused with `term.dependencies`, which describes how many additional rows of `ter...
extra_rows
python
scrtlabs/catalyst
catalyst/pipeline/graph.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/graph.py
Apache-2.0
def make_aliased_type(cls, other_base): """ Factory for making Aliased{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that names another {t}. Parameters ---------- term : {t} {{name}} """ ...
Factory for making Aliased{Filter,Factor,Classifier}.
make_aliased_type
python
scrtlabs/catalyst
catalyst/pipeline/mixins.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/mixins.py
Apache-2.0
def make_downsampled_type(cls, other_base): """ Factory for making Downsampled{Filter,Factor,Classifier}. """ docstring = dedent( """ A {t} that defers to another {t} at lower-than-daily frequency. Parameters ---------- term : ...
Factory for making Downsampled{Filter,Factor,Classifier}.
make_downsampled_type
python
scrtlabs/catalyst
catalyst/pipeline/mixins.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/mixins.py
Apache-2.0
def add(self, term, name, overwrite=False): """ Add a column. The results of computing `term` will show up as a column in the DataFrame produced by running this pipeline. Parameters ---------- column : catalyst.pipeline.Term A Filter, Factor, or Clas...
Add a column. The results of computing `term` will show up as a column in the DataFrame produced by running this pipeline. Parameters ---------- column : catalyst.pipeline.Term A Filter, Factor, or Classifier to add to the pipeline. name : str ...
add
python
scrtlabs/catalyst
catalyst/pipeline/pipeline.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/pipeline.py
Apache-2.0
def set_screen(self, screen, overwrite=False): """ Set a screen on this Pipeline. Parameters ---------- filter : catalyst.pipeline.Filter The filter to apply as a screen. overwrite : bool Whether to overwrite any existing screen. If overwrite is ...
Set a screen on this Pipeline. Parameters ---------- filter : catalyst.pipeline.Filter The filter to apply as a screen. overwrite : bool Whether to overwrite any existing screen. If overwrite is False and self.screen is not None, we raise an...
set_screen
python
scrtlabs/catalyst
catalyst/pipeline/pipeline.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/pipeline.py
Apache-2.0
def to_execution_plan(self, screen_name, default_screen, all_dates, start_date, end_date): """ Compile into an ExecutionPlan. Parameters ---------- s...
Compile into an ExecutionPlan. Parameters ---------- screen_name : str Name to supply for self.screen. default_screen : catalyst.pipeline.term.Term Term to use as a screen if self.screen is None. all_dates : pd.DatetimeIndex A calenda...
to_execution_plan
python
scrtlabs/catalyst
catalyst/pipeline/pipeline.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/pipeline.py
Apache-2.0
def to_simple_graph(self, screen_name, default_screen): """ Compile into a simple TermGraph with no extra row metadata. Parameters ---------- screen_name : str Name to supply for self.screen. default_screen : catalyst.pipeline.term.Term Term to us...
Compile into a simple TermGraph with no extra row metadata. Parameters ---------- screen_name : str Name to supply for self.screen. default_screen : catalyst.pipeline.term.Term Term to use as a screen if self.screen is None.
to_simple_graph
python
scrtlabs/catalyst
catalyst/pipeline/pipeline.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/pipeline.py
Apache-2.0
def _init(self, domain, dtype, missing_value, window_safe, ndim, params): """ Parameters ---------- domain : object Unused placeholder. dtype : np.dtype Dtype of this term's output. params : tuple[(str, hashable)] Tuple of key/value pai...
Parameters ---------- domain : object Unused placeholder. dtype : np.dtype Dtype of this term's output. params : tuple[(str, hashable)] Tuple of key/value pairs of additional parameters.
_init
python
scrtlabs/catalyst
catalyst/pipeline/term.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/term.py
Apache-2.0
def _downsampled_type(self, *args, **kwargs): """ The expression type to return from self.downsample(). """ raise NotImplementedError( "downsampling is not yet implemented " "for instances of %s." % type(self).__name__ )
The expression type to return from self.downsample().
_downsampled_type
python
scrtlabs/catalyst
catalyst/pipeline/term.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/term.py
Apache-2.0
def _aliased_type(self, *args, **kwargs): """ The expression type to return from self.alias(). """ raise NotImplementedError( "alias is not yet implemented " "for instances of %s." % type(self).__name__ )
The expression type to return from self.alias().
_aliased_type
python
scrtlabs/catalyst
catalyst/pipeline/term.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/term.py
Apache-2.0
def _render(g, out, format_, include_asset_exists=False): """ Draw `g` as a graph to `out`, in format `format`. Parameters ---------- g : catalyst.pipeline.graph.TermGraph Graph to render. out : file-like object format_ : str {'png', 'svg'} Output format. include_asset_e...
Draw `g` as a graph to `out`, in format `format`. Parameters ---------- g : catalyst.pipeline.graph.TermGraph Graph to render. out : file-like object format_ : str {'png', 'svg'} Output format. include_asset_exists : bool Whether to filter out `AssetExists()` nodes....
_render
python
scrtlabs/catalyst
catalyst/pipeline/visualize.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/visualize.py
Apache-2.0
def engine_from_files(daily_bar_path, adjustments_path, asset_db_path, calendar, warmup_assets=False): """ Construct a SimplePipelineEngine from local filesystem resources. Parameters ---------- daily_bar_path :...
Construct a SimplePipelineEngine from local filesystem resources. Parameters ---------- daily_bar_path : str Path to pass to `BcolzDailyBarReader`. adjustments_path : str Path to pass to SQLiteAdjustmentReader. asset_db_path : str Path to pass to `AssetFinder`. cale...
engine_from_files
python
scrtlabs/catalyst
catalyst/pipeline/__init__.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/__init__.py
Apache-2.0
def to_workspace_value(self, result, assets): """ Called with the result of a pipeline. This needs to return an object which can be put into the workspace to continue doing computations. This is the inverse of :func:`~catalyst.pipeline.term.Term.postprocess`. """ ...
Called with the result of a pipeline. This needs to return an object which can be put into the workspace to continue doing computations. This is the inverse of :func:`~catalyst.pipeline.term.Term.postprocess`.
to_workspace_value
python
scrtlabs/catalyst
catalyst/pipeline/classifiers/classifier.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/classifiers/classifier.py
Apache-2.0
def demean(self, mask=NotSpecified, groupby=NotSpecified): """ Construct a Factor that computes ``self`` and subtracts the mean from row of the result. If ``mask`` is supplied, ignore values where ``mask`` returns False when computing row means, and output NaN anywhere the mask ...
Construct a Factor that computes ``self`` and subtracts the mean from row of the result. If ``mask`` is supplied, ignore values where ``mask`` returns False when computing row means, and output NaN anywhere the mask is False. If ``groupby`` is supplied, compute by partitioning...
demean
python
scrtlabs/catalyst
catalyst/pipeline/factors/factor.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/factor.py
Apache-2.0
def zscore(self, mask=NotSpecified, groupby=NotSpecified): """ Construct a Factor that Z-Scores each day's results. The Z-Score of a row is defined as:: (row - row.mean()) / row.stddev() If ``mask`` is supplied, ignore values where ``mask`` returns False when compu...
Construct a Factor that Z-Scores each day's results. The Z-Score of a row is defined as:: (row - row.mean()) / row.stddev() If ``mask`` is supplied, ignore values where ``mask`` returns False when computing row means and standard deviations, and output NaN anywher...
zscore
python
scrtlabs/catalyst
catalyst/pipeline/factors/factor.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/factor.py
Apache-2.0
def rank(self, method='ordinal', ascending=True, mask=NotSpecified, groupby=NotSpecified): """ Construct a new Factor representing the sorted rank of each column within each row. Parameters ---------- method : str, {'or...
Construct a new Factor representing the sorted rank of each column within each row. Parameters ---------- method : str, {'ordinal', 'min', 'max', 'dense', 'average'} The method used to assign ranks to tied elements. See `scipy.stats.rankdata` for a full ...
rank
python
scrtlabs/catalyst
catalyst/pipeline/factors/factor.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/factor.py
Apache-2.0
def pearsonr(self, target, correlation_length, mask=NotSpecified): """ Construct a new Factor that computes rolling pearson correlation coefficients between `target` and the columns of `self`. This method can only be called on factors which are deemed safe for use as inputs to o...
Construct a new Factor that computes rolling pearson correlation coefficients between `target` and the columns of `self`. This method can only be called on factors which are deemed safe for use as inputs to other factors. This includes `Returns` and any factors created from `Fa...
pearsonr
python
scrtlabs/catalyst
catalyst/pipeline/factors/factor.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/factor.py
Apache-2.0
def spearmanr(self, target, correlation_length, mask=NotSpecified): """ Construct a new Factor that computes rolling spearman rank correlation coefficients between `target` and the columns of `self`. This method can only be called on factors which are deemed safe for use as inpu...
Construct a new Factor that computes rolling spearman rank correlation coefficients between `target` and the columns of `self`. This method can only be called on factors which are deemed safe for use as inputs to other factors. This includes `Returns` and any factors created fr...
spearmanr
python
scrtlabs/catalyst
catalyst/pipeline/factors/factor.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/factor.py
Apache-2.0
def linear_regression(self, target, regression_length, mask=NotSpecified): """ Construct a new Factor that performs an ordinary least-squares regression predicting the columns of `self` from `target`. This method can only be called on factors which are deemed safe for use as inp...
Construct a new Factor that performs an ordinary least-squares regression predicting the columns of `self` from `target`. This method can only be called on factors which are deemed safe for use as inputs to other factors. This includes `Returns` and any factors created from `Fa...
linear_regression
python
scrtlabs/catalyst
catalyst/pipeline/factors/factor.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/factor.py
Apache-2.0
def percentile_between(self, min_percentile, max_percentile, mask=NotSpecified): """ Construct a new Filter representing entries from the output of this Factor that fall within the percentile range defined by min_pe...
Construct a new Filter representing entries from the output of this Factor that fall within the percentile range defined by min_percentile and max_percentile. Parameters ---------- min_percentile : float [0.0, 100.0] Return True for assets falling above this...
percentile_between
python
scrtlabs/catalyst
catalyst/pipeline/factors/factor.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/factor.py
Apache-2.0
def isnull(self): """ A Filter producing True for values where this Factor has missing data. Equivalent to self.isnan() when ``self.dtype`` is float64. Otherwise equivalent to ``self.eq(self.missing_value)``. Returns ------- filter : catalyst.pipeline.filters.Fi...
A Filter producing True for values where this Factor has missing data. Equivalent to self.isnan() when ``self.dtype`` is float64. Otherwise equivalent to ``self.eq(self.missing_value)``. Returns ------- filter : catalyst.pipeline.filters.Filter
isnull
python
scrtlabs/catalyst
catalyst/pipeline/factors/factor.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/factor.py
Apache-2.0
def from_span(cls, inputs, window_length, span, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of `span`. Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the behavior equivalent to passing `span` to pandas.ewma. Examples -----...
Convenience constructor for passing `decay_rate` in terms of `span`. Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the behavior equivalent to passing `span` to pandas.ewma. Examples -------- .. code-block:: python # Equivalent to: ...
from_span
python
scrtlabs/catalyst
catalyst/pipeline/factors/crypto/technical.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/crypto/technical.py
Apache-2.0
def from_halflife(cls, inputs, window_length, halflife, **kwargs): """ Convenience constructor for passing ``decay_rate`` in terms of half life. Forwards ``decay_rate`` as ``exp(log(.5) / halflife)``. This provides the behavior equivalent to passing `halflife` to pandas.ewma. ...
Convenience constructor for passing ``decay_rate`` in terms of half life. Forwards ``decay_rate`` as ``exp(log(.5) / halflife)``. This provides the behavior equivalent to passing `halflife` to pandas.ewma. Examples -------- .. code-block:: python ...
from_halflife
python
scrtlabs/catalyst
catalyst/pipeline/factors/crypto/technical.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/crypto/technical.py
Apache-2.0
def from_center_of_mass(cls, inputs, window_length, center_of_mass, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of center of mass. Forwards `decay...
Convenience constructor for passing `decay_rate` in terms of center of mass. Forwards `decay_rate` as `1 - (1 / 1 + center_of_mass)`. This provides behavior equivalent to passing `center_of_mass` to pandas.ewma. Examples -------- .. code-block:: python ...
from_center_of_mass
python
scrtlabs/catalyst
catalyst/pipeline/factors/crypto/technical.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/crypto/technical.py
Apache-2.0
def from_span(cls, inputs, window_length, span, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of `span`. Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the behavior equivalent to passing `span` to pandas.ewma. Examples -----...
Convenience constructor for passing `decay_rate` in terms of `span`. Forwards `decay_rate` as `1 - (2.0 / (1 + span))`. This provides the behavior equivalent to passing `span` to pandas.ewma. Examples -------- .. code-block:: python # Equivalent to: ...
from_span
python
scrtlabs/catalyst
catalyst/pipeline/factors/equity/technical.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/equity/technical.py
Apache-2.0
def from_halflife(cls, inputs, window_length, halflife, **kwargs): """ Convenience constructor for passing ``decay_rate`` in terms of half life. Forwards ``decay_rate`` as ``exp(log(.5) / halflife)``. This provides the behavior equivalent to passing `halflife` to pandas.ewma. ...
Convenience constructor for passing ``decay_rate`` in terms of half life. Forwards ``decay_rate`` as ``exp(log(.5) / halflife)``. This provides the behavior equivalent to passing `halflife` to pandas.ewma. Examples -------- .. code-block:: python ...
from_halflife
python
scrtlabs/catalyst
catalyst/pipeline/factors/equity/technical.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/equity/technical.py
Apache-2.0
def from_center_of_mass(cls, inputs, window_length, center_of_mass, **kwargs): """ Convenience constructor for passing `decay_rate` in terms of center of mass. Forwards `decay...
Convenience constructor for passing `decay_rate` in terms of center of mass. Forwards `decay_rate` as `1 - (1 / 1 + center_of_mass)`. This provides behavior equivalent to passing `center_of_mass` to pandas.ewma. Examples -------- .. code-block:: python ...
from_center_of_mass
python
scrtlabs/catalyst
catalyst/pipeline/factors/equity/technical.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/factors/equity/technical.py
Apache-2.0
def get_last_data_per_qtr(self, assets_with_data, columns, dates): """ Determine the last piece of information we know for each column on each date in the index for each sid and quarter. Parameters ---------- assets_with_data : pd.Index Index of all assets th...
Determine the last piece of information we know for each column on each date in the index for each sid and quarter. Parameters ---------- assets_with_data : pd.Index Index of all assets that appear in the raw data given to the loader. columns : i...
get_last_data_per_qtr
python
scrtlabs/catalyst
catalyst/pipeline/loaders/earnings_estimates.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/earnings_estimates.py
Apache-2.0
def from_files(cls, pricing_path, adjustments_path): """ Create a loader from a bcolz equity pricing dir and a SQLite adjustments path. Parameters ---------- pricing_path : str Path to a bcolz directory written by a BcolzDailyBarWriter. adjusments_pat...
Create a loader from a bcolz equity pricing dir and a SQLite adjustments path. Parameters ---------- pricing_path : str Path to a bcolz directory written by a BcolzDailyBarWriter. adjusments_path : str Path to an adjusments db written by a SQLite...
from_files
python
scrtlabs/catalyst
catalyst/pipeline/loaders/equity_pricing_loader.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/equity_pricing_loader.py
Apache-2.0
def make_bar_data(asset_info, calendar): """ For a given asset/date/column combination, we generate a corresponding raw value using the following formula for OHLCV columns: data(asset, date, column) = (100,000 * asset_id) + (10,000 * column_num) ...
For a given asset/date/column combination, we generate a corresponding raw value using the following formula for OHLCV columns: data(asset, date, column) = (100,000 * asset_id) + (10,000 * column_num) + (date - Jan 1 2000).days # ~6000 for 2015...
make_bar_data
python
scrtlabs/catalyst
catalyst/pipeline/loaders/synthetic.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/synthetic.py
Apache-2.0
def expected_bar_values_2d(dates, asset_info, colname): """ Return an 2D array containing cls.expected_value(asset_id, date, colname) for each date/asset pair in the inputs. Values before/after an assets lifetime are filled with 0 for volume and NaN for price columns. """ if colname == 'vol...
Return an 2D array containing cls.expected_value(asset_id, date, colname) for each date/asset pair in the inputs. Values before/after an assets lifetime are filled with 0 for volume and NaN for price columns.
expected_bar_values_2d
python
scrtlabs/catalyst
catalyst/pipeline/loaders/synthetic.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/synthetic.py
Apache-2.0
def next_event_indexer(all_dates, all_sids, event_dates, event_timestamps, event_sids): """ Construct an index array that, when applied to an array of values, produces a 2D array containing the values associated with...
Construct an index array that, when applied to an array of values, produces a 2D array containing the values associated with the next event for each sid at each moment in time. Locations where no next event was known will be filled with -1. Parameters ---------- all_dates : ndarray[dateti...
next_event_indexer
python
scrtlabs/catalyst
catalyst/pipeline/loaders/utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/utils.py
Apache-2.0
def previous_event_indexer(all_dates, all_sids, event_dates, event_timestamps, event_sids): """ Construct an index array that, when applied to an array of values, produces a 2D array containing the va...
Construct an index array that, when applied to an array of values, produces a 2D array containing the values associated with the previous event for each sid at each moment in time. Locations where no previous event was known will be filled with -1. Parameters ---------- all_dates : ndarra...
previous_event_indexer
python
scrtlabs/catalyst
catalyst/pipeline/loaders/utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/utils.py
Apache-2.0
def normalize_data_query_time(dt, time, tz): """Apply the correct time and timezone to a date. Parameters ---------- dt : pd.Timestamp The original datetime that represents the date. time : datetime.time The time of day to use as the cutoff point for new data. Data points th...
Apply the correct time and timezone to a date. Parameters ---------- dt : pd.Timestamp The original datetime that represents the date. time : datetime.time The time of day to use as the cutoff point for new data. Data points that you learn about after this time will become avail...
normalize_data_query_time
python
scrtlabs/catalyst
catalyst/pipeline/loaders/utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/utils.py
Apache-2.0
def normalize_data_query_bounds(lower, upper, time, tz): """Adjust the first and last dates in the requested datetime index based on the provided query time and tz. lower : pd.Timestamp The lower date requested. upper : pd.Timestamp The upper date requested. time : datetime.time ...
Adjust the first and last dates in the requested datetime index based on the provided query time and tz. lower : pd.Timestamp The lower date requested. upper : pd.Timestamp The upper date requested. time : datetime.time The time of day to use as the cutoff point for new data. Da...
normalize_data_query_bounds
python
scrtlabs/catalyst
catalyst/pipeline/loaders/utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/utils.py
Apache-2.0
def normalize_timestamp_to_query_time(df, time, tz, inplace=False, ts_field='timestamp'): """Update the timestamp field of a dataframe to normalize dates around ...
Update the timestamp field of a dataframe to normalize dates around some data query time/timezone. Parameters ---------- df : pd.DataFrame The dataframe to update. This needs a column named ``ts_field``. time : datetime.time The time of day to use as the cutoff point for new data. D...
normalize_timestamp_to_query_time
python
scrtlabs/catalyst
catalyst/pipeline/loaders/utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/utils.py
Apache-2.0
def check_data_query_args(data_query_time, data_query_tz): """Checks the data_query_time and data_query_tz arguments for loaders and raises a standard exception if one is None and the other is not. Parameters ---------- data_query_time : datetime.time or None data_query_tz : tzinfo or None ...
Checks the data_query_time and data_query_tz arguments for loaders and raises a standard exception if one is None and the other is not. Parameters ---------- data_query_time : datetime.time or None data_query_tz : tzinfo or None Raises ------ ValueError Raised when only one of ...
check_data_query_args
python
scrtlabs/catalyst
catalyst/pipeline/loaders/utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/utils.py
Apache-2.0
def last_in_date_group(df, dates, assets, reindex=True, have_sids=True, extra_groupers=None): """ Determine the last piece of information known on each date in the date index for each group. In...
Determine the last piece of information known on each date in the date index for each group. Input df MUST be sorted such that the correct last item is chosen from each group. Parameters ---------- df : pd.DataFrame The DataFrame containing the data to be grouped. Must be sorted so tha...
last_in_date_group
python
scrtlabs/catalyst
catalyst/pipeline/loaders/utils.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/pipeline/loaders/utils.py
Apache-2.0
def new_dataset(expr, deltas, missing_values): """ Creates or returns a dataset from a pair of blaze expressions. Parameters ---------- expr : Expr The blaze expression representing the first known values. deltas : Expr The blaze expression representing the deltas to the data. ...
Creates or returns a dataset from a pair of blaze expressions. Parameters ---------- expr : Expr The blaze expression representing the first known values. deltas : Expr The blaze expression representing the deltas to the data. missing_values : frozenset((name, value) pairs ...
new_dataset
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 from_blaze(expr, deltas='auto', checkpoints='auto', loader=None, resources=None, odo_kwargs=None, missing_values=None, no_deltas_rule='warn', no_checkpoints_rule='warn', apply_delta...
Create a Pipeline API object from a blaze expression. Parameters ---------- expr : Expr The blaze expression to use. deltas : Expr, 'auto' or None, optional The expression to use for the point in time adjustments. If the string 'auto' is passed, a deltas expr will be looked up ...
from_blaze
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 overwrite_novel_deltas(baseline, deltas, dates): """overwrite any deltas into the baseline set that would have changed our most recently known value. Parameters ---------- baseline : pd.DataFrame The first known values. deltas : pd.DataFrame Overwrites to the baseline data. ...
overwrite any deltas into the baseline set that would have changed our most recently known value. Parameters ---------- baseline : pd.DataFrame The first known values. deltas : pd.DataFrame Overwrites to the baseline data. dates : pd.DatetimeIndex The dates requested by ...
overwrite_novel_deltas
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 overwrite_from_dates(asof, dense_dates, sparse_dates, asset_idx, value): """Construct an Overwrite with the correct start and end date based on the asof date of the delta, the dense_dates, and the dense_dates. Parameters ---------- asof : datetime The asof date of the delta. den...
Construct an Overwrite with the correct start and end date based on the asof date of the delta, the dense_dates, and the dense_dates. Parameters ---------- asof : datetime The asof date of the delta. dense_dates : pd.DatetimeIndex The dates requested by the loader. sparse_da...
overwrite_from_dates
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