desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
':arg slo: A :class:`curator.snapshotlist.SnapshotList` object
:arg retry_interval: Number of seconds to delay betwen retries. Default:
120 (seconds)
:arg retry_count: Number of attempts to make. Default: 3'
| def __init__(self, slo, retry_interval=120, retry_count=3):
| verify_snapshot_list(slo)
self.client = slo.client
self.retry_interval = retry_interval
self.retry_count = retry_count
self.snapshot_list = slo
self.repository = slo.repository
self.loggit = logging.getLogger('curator.actions.delete_snapshots')
|
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| logger.info('DRY-RUN MODE. No changes will be made.')
mykwargs = {'repository': self.repository, 'retry_interval': self.retry_interval, 'retry_count': self.retry_count}
for snap in self.snapshot_list.snapshots:
logger.info('DRY-RUN: delete_snapshot: {0} with argumen... |
'Delete snapshots in `slo`
Retry up to `retry_count` times, pausing `retry_interval`
seconds between retries.'
| def do_action(self):
| self.snapshot_list.empty_list_check()
self.loggit.info('Deleting selected snapshots')
if (not safe_to_snap(self.client, repository=self.repository, retry_interval=self.retry_interval, retry_count=self.retry_count)):
raise FailedExecution('Unable to delete snapshot(s) because a ... |
':arg ilo: A :class:`curator.indexlist.IndexList` object
:arg request_body: The body to send to
:py:meth:`elasticsearch.Elasticsearch.reindex`, which must be complete and
usable, as Curator will do no vetting of the request_body. If it
fails to function, Curator will return an exception.
:arg refresh: Whether to refres... | def __init__(self, ilo, request_body, refresh=True, requests_per_second=(-1), slices=1, timeout=60, wait_for_active_shards=1, wait_for_completion=True, max_wait=(-1), wait_interval=9, remote_url_prefix=None, remote_ssl_no_validate=None, remote_certificate=None, remote_client_cert=None, remote_client_key=None, remote_aw... | self.loggit = logging.getLogger('curator.actions.reindex')
verify_index_list(ilo)
if (not isinstance(request_body, dict)):
raise ConfigurationError('"request_body" is not of type dictionary')
self.body = request_body
self.loggit.debug('REQUEST_BODY = {0}'.format(request_... |
'Show what will run'
| def show_run_args(self, source, dest):
| return 'request body: {0} with arguments: refresh={1} requests_per_second={2} slices={3} timeout={4} wait_for_active_shards={5} wait_for_completion={6}'.format(self._get_request_body(source, dest), self.refresh, self.requests_per_second, self.slices, self.timeout, self.wait_for_active_... |
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| self.loggit.info('DRY-RUN MODE. No changes will be made.')
for (source, dest) in self.sources():
self.loggit.info('DRY-RUN: REINDEX: {0}'.format(self.show_run_args(source, dest)))
|
'Execute :py:meth:`elasticsearch.Elasticsearch.reindex` operation with the
provided request_body and arguments.'
| def do_action(self):
| try:
for (source, dest) in self.sources():
self.loggit.info('Commencing reindex operation')
self.loggit.debug('REINDEX: {0}'.format(self.show_run_args(source, dest)))
response = self.client.reindex(**self._get_reindex_args(source, dest))
self.loggit.d... |
':arg ilo: A :class:`curator.indexlist.IndexList` object
:arg repository: The Elasticsearch snapshot repository to use
:arg name: What to name the snapshot.
:arg wait_for_completion: Wait (or not) for the operation
to complete before returning. (default: `True`)
:type wait_for_completion: bool
:arg wait_interval: How ... | def __init__(self, ilo, repository=None, name=None, ignore_unavailable=False, include_global_state=True, partial=False, wait_for_completion=True, wait_interval=9, max_wait=(-1), skip_repo_fs_check=False):
| verify_index_list(ilo)
ilo.empty_list_check()
if (not repository_exists(ilo.client, repository=repository)):
raise ActionError('Cannot snapshot indices to missing repository: {0}'.format(repository))
if (not name):
raise MissingArgument('No value for "name" ... |
'Get the state of the snapshot'
| def get_state(self):
| try:
self.state = self.client.snapshot.get(repository=self.repository, snapshot=self.name)['snapshots'][0]['state']
return self.state
except IndexError:
raise CuratorException('Snapshot "{0}" not found in repository "{1}"'.format(self.name, self.repository))
|
'Log the state of the snapshot'
| def report_state(self):
| self.get_state()
if (self.state == 'SUCCESS'):
self.loggit.info('Snapshot {0} successfully completed.'.format(self.name))
else:
self.loggit.warn('Snapshot {0} completed with state: {0}'.format(self.state))
|
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| self.loggit.info('DRY-RUN MODE. No changes will be made.')
self.loggit.info('DRY-RUN: snapshot: {0} in repository {1} with arguments: {2}'.format(self.name, self.repository, self.body))
|
'Snapshot indices in `index_list.indices`, with options passed.'
| def do_action(self):
| if (not self.skip_repo_fs_check):
test_repo_fs(self.client, self.repository)
if snapshot_running(self.client):
raise SnapshotInProgress('Snapshot already in progress.')
try:
self.loggit.info('Creating snapshot "{0}" from indices: {1}'.format(self.name, self.in... |
':arg slo: A :class:`curator.snapshotlist.SnapshotList` object
:arg name: Name of the snapshot to restore. If no name is provided, it
will restore the most recent snapshot by age.
:type name: str
:arg indices: A list of indices to restore. If no indices are provided,
it will restore all indices in the snapshot.
:type... | def __init__(self, slo, name=None, indices=None, include_aliases=False, ignore_unavailable=False, include_global_state=False, partial=False, rename_pattern=None, rename_replacement=None, extra_settings={}, wait_for_completion=True, wait_interval=9, max_wait=(-1), skip_repo_fs_check=False):
| self.loggit = logging.getLogger('curator.actions.snapshot')
verify_snapshot_list(slo)
most_recent = slo.most_recent()
self.loggit.debug('"most_recent" snapshot: {0}'.format(most_recent))
self.name = (name if name else most_recent)
if ((slo.snapshot_info[self.name]['state'] == 'PARTIAL') an... |
'Log the state of the restore
This should only be done if ``wait_for_completion`` is `True`, and only
after completing the restore.'
| def report_state(self):
| all_indices = get_indices(self.client)
found_count = 0
missing = []
for index in self.expected_output:
if (index in all_indices):
found_count += 1
self.loggit.info('Found restored index {0}'.format(index))
else:
missing.append(index)
if (f... |
'Log what the output would be, but take no action.'
| def do_dry_run(self):
| logger.info('DRY-RUN MODE. No changes will be made.')
logger.info('DRY-RUN: restore: Repository: {0} Snapshot name: {1} Arguments: {2}'.format(self.repository, self.name, {'wait_for_completion': self.wfc, 'body': self.body}))
for index in self.indices:
i... |
'Restore indices with options passed.'
| def do_action(self):
| if (not self.skip_repo_fs_check):
test_repo_fs(self.client, self.repository)
if snapshot_running(self.client):
raise SnapshotInProgress('Cannot restore while a snapshot is in progress.')
try:
self.loggit.info('Restoring indices "{0}" from snapshot: ... |
'Plots useful statistics for the trading strategy using various backends
Parameters
trading_model : TradingModel
defining trading strategy
engine : str
\'pyfolio\' - use PyFolio as a backend
\'finmarketpy\' - use finmarketpy as a backend
index: DataFrame
define strategy by a time series'
| def run_strategy_returns_stats(self, trading_model, index=None, engine='finmarketpy'):
| if (index is None):
pnl = trading_model.strategy_pnl()
else:
pnl = index
tz = Timezone()
calculations = Calculations()
if (engine == 'pyfolio'):
try:
pnl = tz.localise_index_as_UTC(pnl)
except:
pass
try:
matplotlib.rcdefault... |
'run_excel_trade_report - Creates an Excel spreadsheet with model returns and latest trades
Parameters
trading_model : TradingModel
defining trading strategy (can be a list)'
| def run_excel_trade_report(self, trading_model, excel_file='model.xlsx'):
| trading_model_list = trading_model
if (not isinstance(trading_model_list, list)):
trading_model_list = [trading_model]
writer = pandas.ExcelWriter(excel_file, engine='xlsxwriter')
for tm in trading_model_list:
strategy_name = tm.FINAL_STRATEGY
returns = tm.strategy_group_benchmar... |
'Calculates P&L table which can be used for debugging purposes,
The table is populated with asset, signal and further dataframes provided by the user, can be used to check signalling methodology.
It does not apply parameters such as transaction costs, vol adjusment and so on.
Parameters
asset_a_df : DataFrame
Asset pri... | def calculate_diagnostic_trading_PnL(self, asset_a_df, signal_df, further_df=[], further_df_labels=[]):
| calculations = Calculations()
asset_rets_df = calculations.calculate_returns(asset_a_df)
strategy_rets = calculations.calculate_signal_returns(signal_df, asset_rets_df)
reset_points = (signal_df - signal_df.shift(1)).abs()
asset_a_df_entry = asset_a_df.copy(deep=True)
asset_a_df_entry[(reset_poi... |
'Calculates P&L of a trading strategy and statistics to be retrieved later
Calculates the P&L for each asset/signal combination and also for the finally strategy applying appropriate
weighting in the portfolio, depending on predefined parameters, for example:
static weighting for each asset
static weighting for each as... | def calculate_trading_PnL(self, br, asset_a_df, signal_df, contract_value_df=None):
| calculations = Calculations()
risk_engine = RiskEngine()
signal_df = signal_df.shift(br.signal_delay)
(asset_df, signal_df) = calculations.join_left_fill_right(asset_a_df, signal_df)
if (contract_value_df is not None):
(asset_df, contract_value_df) = asset_df.align(contract_value_df, join='l... |
'Calculates time series for the total longs, short, net and absolute exposure on an aggregated portfolio basis.
Parameters
portfolio_signal : DataFrame
Signals for each asset in the portfolio after all weighting, portfolio & signal level volatility adjustments
Returns
DataFrame (list)'
| def calculate_exposures(self, portfolio_signal):
| portfolio_total_longs = pandas.DataFrame(portfolio_signal[(portfolio_signal > 0)].sum(axis=1))
portfolio_total_shorts = pandas.DataFrame(portfolio_signal[(portfolio_signal < 0)].sum(axis=1))
portfolio_total_longs.columns = ['Total Longs']
portfolio_total_shorts.columns = ['Total Shorts']
portf... |
'Calculates P&L of a trading strategy and statistics to be retrieved later
Parameters
br : BacktestRequest
Parameters for the backtest specifying start date, finish data, transaction costs etc.
_pnl : pandas.DataFrame
Contains the daily P&L for the portfolio
method : String
\'mean\' - assumes equal weighting for each s... | def create_portfolio_weights(self, br, _pnl, method='mean'):
| if (method == 'mean'):
weights_vector = numpy.ones(len(_pnl.columns))
elif ((method == 'weighted') or 'weighted-sum'):
weights_vector = numpy.array([float(br.portfolio_combination_weights[col]) for col in _pnl.columns])
weights_matrix = numpy.repeat(weights_vector[numpy.newaxis, :], len(_pnl... |
'Gets P&L returns of all the individual sub_components of the model (before any portfolio level leverage is applied)
Returns
pandas.Dataframe'
| def pnl(self):
| return self._pnl
|
'Gets number of trades for each signal in the backtest (before
Returns
pandas.Dataframe'
| def trade_no(self):
| if (self._trade_no is None):
calculations = Calculations()
self._trade_no = calculations.calculate_trade_no(self._signal)
return self._trade_no
|
'Gets P&L of each individual trade per signal
Returns
pandas.Dataframe'
| def pnl_trades(self):
| if (self._pnl_trades is None):
calculations = Calculations()
self._pnl_trades = calculations.calculate_individual_trade_gains(self._signal, self._pnl)
return self._pnl_trades
|
'Gets P&L return statistics in a string format
Returns
str'
| def pnl_desc(self):
| return self._ret_stats_signals.summary()
|
'Gets P&L return statistics of individual strategies as class to be queried
Returns
TimeSeriesDesc'
| def pnl_ret_stats(self):
| return self._pnl_ret_stats
|
'Gets P&L as a cumulative time series of individual assets
Returns
pandas.DataFrame'
| def pnl_cum(self):
| return self._pnl_cum
|
'Gets P&L returns of all the individual subcomponents of the model (after portfolio level leverage is applied)
Returns
pandas.Dataframe'
| def components_pnl(self):
| return self._components_pnl
|
'Gets P&L of each individual trade per signal
Returns
pandas.Dataframe'
| def components_pnl_trades(self):
| if (self._components_pnl_trades is None):
calculations = Calculations()
self._components_pnl_trades = calculations.calculate_individual_trade_gains(self._signal, self._components_pnl)
return self._components_pnl_trades
|
'Gets P&L return statistics of individual strategies as class to be queried
Returns
TimeSeriesDesc'
| def components_pnl_ret_stats(self):
| return self._components_pnl_ret_stats
|
'Gets P&L as a cumulative time series of individual assets (after portfolio level leverage adjustments)
Returns
pandas.DataFrame'
| def components_pnl_cum(self):
| return self._components_pnl_cum
|
'Gets P&L as a cumulative time series of portfolio
Returns
pandas.DataFrame'
| def portfolio_cum(self):
| return self._portfolio_cum
|
'Gets portfolio returns in raw form (ie. not indexed into cumulative form)
Returns
pandas.DataFrame'
| def portfolio_pnl(self):
| return self._portfolio
|
'Gets P&L return statistics of portfolio as string
Returns
pandas.DataFrame'
| def portfolio_pnl_desc(self):
| return self._portfolio_ret_stats.summary()
|
'Gets P&L return statistics of portfolio as class to be queried
Returns
RetStats'
| def portfolio_pnl_ret_stats(self):
| return self._portfolio_ret_stats
|
'Gets leverage for each asset historically
Returns
pandas.DataFrame'
| def individual_leverage(self):
| return self._individual_leverage
|
'Gets the leverage for the portfolio
Returns
pandas.DataFrame'
| def portfolio_leverage(self):
| return self._portfolio_leverage
|
'Gets number of trades for each signal in the backtest (after both signal and portfolio level vol adjustment)
Returns
pandas.Dataframe'
| def portfolio_trade_no(self):
| if (self._portfolio_trade_no is None):
calculations = Calculations()
self._portfolio_trade_no = calculations.calculate_trade_no(self._portfolio_signal)
return self._portfolio_trade_no
|
'Gets the signals (with individual leverage & portfolio leverage) for each asset, which
equates to what we would trade in practice
Returns
DataFrame'
| def portfolio_signal(self):
| return self._portfolio_signal
|
'Gets the total long exposure in the portfolio
Returns
DataFrame'
| def portfolio_total_longs(self):
| return self._portfolio_total_longs
|
'Gets the total short exposure in the portfolio
Returns
DataFrame'
| def portfolio_total_shorts(self):
| return self._portfolio_total_shorts
|
'Gets the total net exposure of the portfolio
Returns
DataFrame'
| def portfolio_net_exposure(self):
| return self._portfolio_net_exposure
|
'Gets the total absolute exposure of the portfolio
Returns
DataFrame'
| def portfolio_total_exposure(self):
| return self._portfolio_total_exposure
|
'Gets the total long exposure in the portfolio scaled by notional
Returns
DataFrame'
| def portfolio_total_longs_notional(self):
| return self._portfolio_total_longs_notional
|
'Gets the total short exposure in the portfolio scaled by notional
Returns
DataFrame'
| def portfolio_total_shorts_notional(self):
| return self._portfolio_total_shorts_notional
|
'Gets the total net exposure of the portfolio scaled by notional
Returns
DataFrame'
| def portfolio_net_exposure_notional(self):
| return self._portfolio_net_exposure_notional
|
'Gets the total absolute exposure of the portfolio scaled by notional
Returns
DataFrame'
| def portfolio_total_exposure_notional(self):
| return self._portfolio_total_exposure_notional
|
'Gets the trades (with individual leverage & portfolio leverage) for each asset, which
we\'d need to execute
Returns
DataFrame'
| def portfolio_trade(self):
| return self._portfolio_trade
|
'Gets the signals (with individual leverage & portfolio leverage) for each asset, which
equates to what we would have a positions in practice, scaled by a notional amount we have already specified
Returns
DataFrame'
| def portfolio_signal_notional(self):
| return self._portfolio_signal_notional
|
'Gets the trades (with individual leverage & portfolio leverage) for each asset, which
we\'d need to execute, scaled by a notional amount we have already specified
Returns
DataFrame'
| def portfolio_trade_notional(self):
| return self._portfolio_signal_trade_notional
|
'Gets the signals (with individual leverage & portfolio leverage) for each asset, which
equates to what we would have a positions in practice, scaled by a notional amount and into contract sizes (eg. for futures)
which we need to specify in another dataframe
Returns
DataFrame'
| def portfolio_signal_contracts(self):
| return self._portfolio_signal_contracts
|
'Gets the trades (with individual leverage & portfolio leverage) for each asset, which
we\'d need to execute, scaled by a notional amount we have already specified and into contract sizes (eg. for futures)
which we need to specify in another dataframe
Returns
DataFrame'
| def portfolio_trade_contracts(self):
| return self._portfolio_signal_trade_contracts
|
'Gets signal for each asset (with individual leverage, but excluding portfolio leverage constraints) for each asset
Returns
pandas.DataFrame'
| def signal(self):
| return self._signal
|
'Fills parameters for the backtest, such as start-end dates, transaction costs etc. To
be implemented by subclass.'
| @abc.abstractmethod
def load_parameters(self):
| return
|
'Loads time series for the assets to be traded and also for data for generating signals.'
| @abc.abstractmethod
def load_assets(self):
| return
|
'Constructs signal from pre-loaded time series
Parameters
spot_df : pandas.DataFrame
Market time series for generating signals
spot_df2 : pandas.DataFrame
Market time series for generated signals (can be of different frequency)
tech_params : TechParams
Parameters for generating signals'
| @abc.abstractmethod
def construct_signal(self, spot_df, spot_df2, tech_params):
| return
|
'Constructs the returns for all the strategies which have been specified.
It gets backtesting parameters from fill_backtest_request (although these can be overwritten
and then market data from fill_assets
Parameters
br : BacktestRequest
Parameters which define the backtest (for example start date, end date, transaction... | def construct_strategy(self, br=None):
| calculations = Calculations()
if hasattr(self, 'br'):
br = self.br
elif (br is None):
br = self.load_parameters()
market_data = self.load_assets()
asset_df = market_data[0]
spot_df = market_data[1]
spot_df2 = market_data[2]
basket_dict = market_data[3]
contract_value_... |
'Combines the signal with asset returns to find the returns of an individual strategy
Parameters
br : BacktestRequest
Parameters for backtest such as start and finish dates
spot_df : pandas.DataFrame
Market time series for generating signals
spot_df2 : pandas.DataFrame
Secondary Market time series for generated signals... | def construct_individual_strategy(self, br, spot_df, spot_df2, asset_df, tech_params, key, contract_value_df=None):
| backtest = Backtest()
signal_df = self.construct_signal(spot_df, spot_df2, tech_params, br)
backtest.calculate_trading_PnL(br, asset_df, signal_df, contract_value_df)
pnl_cum = backtest.pnl_cum()
if br.write_csv:
pnl_cum.to_csv(((self.DUMP_CSV + key) + '.csv'))
portfolio_cum = backtest.p... |
'Compares the trading strategy we are backtesting against a benchmark
Parameters
br : BacktestRequest
Parameters for backtest such as start and finish dates
strategy_df : pandas.DataFrame
Strategy time series
benchmark_df : pandas.DataFrame
Benchmark time series'
| def compare_strategy_vs_benchmark(self, br, strategy_df, benchmark_df):
| if br.include_benchmark:
ret_stats = RetStats()
risk_engine = RiskEngine()
filter = Filter()
calculations = Calculations()
benchmark_df.columns = [(x + ' be') for x in benchmark_df.columns]
(strategy_df, benchmark_df) = strategy_df.align(benchmark_df, join='left', ... |
'Flattens list, particularly useful for combining baskets
Parameters
list_of_lists : str (list)
List to be flattened
Returns'
| def _flatten_list(self, list_of_lists):
| result = []
for i in list_of_lists:
if isinstance(i, str):
result.append(i)
else:
result.extend(self._flatten_list(i))
return result
|
'Reduces the frequency of a time series to every business day so it can be plotted more easily
Parameters
data_frame: pandas.DataFrame
Strategy time series
Returns
pandas.DataFrame'
| def _reduce_plot(self, data_frame):
| try:
data_frame = data_frame.resample('B')
data_frame = data_frame.fillna(method='pad')
return data_frame
except:
return data_frame
|
'Adjusts an index of prices for a vol target
Parameters
br : BacktestRequest
Parameters for the backtest specifying start date, finish data, transaction costs etc.
asset_a_df : pandas.DataFrame
Asset prices to be traded
Returns
pandas.Dataframe containing vol adjusted index'
| def calculate_vol_adjusted_index_from_prices(self, prices_df, br):
| calculations = Calculations()
(returns_df, leverage_df) = self.calculate_vol_adjusted_returns(prices_df, br, returns=False)
return calculations.create_mult_index(returns_df)
|
'Adjusts returns for a vol target
Parameters
br : BacktestRequest
Parameters for the backtest specifying start date, finish data, transaction costs etc.
returns_a_df : pandas.DataFrame
Asset returns to be traded
Returns
pandas.DataFrame'
| def calculate_vol_adjusted_returns(self, returns_df, br, returns=True):
| calculations = Calculations()
if (not returns):
returns_df = calculations.calculate_returns(returns_df)
leverage_df = self.calculate_leverage_factor(returns_df, br.portfolio_vol_target, br.portfolio_vol_max_leverage, br.portfolio_vol_periods, br.portfolio_vol_obs_in_year, br.portfolio_vol_rebalance_... |
'Calculates the time series of leverage for a specified vol target
Parameters
returns_df : DataFrame
Asset returns
vol_target : float
vol target for assets
vol_max_leverage : float
maximum leverage allowed
vol_periods : int
number of periods to calculate volatility
vol_obs_in_year : int
number of observations in the ye... | def calculate_leverage_factor(self, returns_df, vol_target, vol_max_leverage, vol_periods=60, vol_obs_in_year=252, vol_rebalance_freq='BM', resample_freq=None, resample_type='mean', returns=True, period_shift=0):
| calculations = Calculations()
filter = Filter()
if (resample_freq is not None):
return
if (not returns):
returns_df = calculations.calculate_returns(returns_df)
roll_vol_df = calculations.rolling_volatility(returns_df, periods=vol_periods, obs_in_year=vol_obs_in_year).shift(period_sh... |
'Calculate the leverage adjustment that needs to be made in the portfolio such that either the net exposure or
the absolute exposure fits within predefined limits
Parameters
portfolio_net_exposure : DataFrame
Net exposure of the whole portfolio
portfolio_total_exposure : DataFrame
Absolute exposure of the whole portfol... | def calculate_position_clip_adjustment(self, portfolio_net_exposure, portfolio_total_exposure, br):
| position_clip_adjustment = None
if (br.max_net_exposure is not None):
portfolio_net_exposure = portfolio_net_exposure.shift(br.position_clip_period_shift)
position_clip_adjustment = pandas.DataFrame(data=numpy.ones(len(portfolio_net_exposure.index)), index=portfolio_net_exposure.index, columns=[... |
'Adjusted time series which exhibit strong seasonality. If time series do not exhibit any seasonality will return
NaN values.
Parameters
data_frame : DataFrame
Data to be seasonally adjusted
window : int
Number of points to use in our rolling window (eg. for monthly data 60 = 5 year * 12 months)
likely_period
What is t... | def adjust_rolling_seasonality(self, data_frame, window=None, likely_period=None):
| data_frame = data_frame.copy()
for c in data_frame.columns:
data_frame[c] = data_frame[c].rolling(center=False, window=window, min_periods=window).apply((lambda x: self._remove_seasonality(x, likely_period=likely_period)))
return data_frame
|
'Private function to check that the X and y in fitting are the same
than in sampling.'
| def _check_X_y(self, X, y):
| (X_hash, y_hash) = hash_X_y(X, y)
if ((self.X_hash_ != X_hash) or (self.y_hash_ != y_hash)):
raise RuntimeError('X and y need to be same array earlier fitted.')
|
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def sample(self, X, y):
| (X, y) = check_X_y(X, y)
check_is_fitted(self, 'ratio_')
self._check_X_y(X, y)
return self._sample(X, y)
|
'Fit the statistics and resample the data directly.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing ... | def fit_sample(self, X, y):
| return self.fit(X, y).sample(X, y)
|
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | @abstractmethod
def _sample(self, X, y):
| pass
|
'Prevent logger from being pickled.'
| def __getstate__(self):
| object_dictionary = self.__dict__.copy()
del object_dictionary['logger']
return object_dictionary
|
'Re-open the logger.'
| def __setstate__(self, dict):
| logger = logging.getLogger(__name__)
self.__dict__.update(dict)
self.logger = logger
|
'Find the classes statistics before to perform sampling.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
self : object,
Return self.'
| def fit(self, X, y):
| (X, y) = check_X_y(X, y)
y = check_target_type(y)
(self.X_hash_, self.y_hash_) = hash_X_y(X, y)
self.ratio_ = check_ratio(self.ratio, y, self._sampling_type)
return self
|
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| random_state = check_random_state(self.random_state)
target_stats = Counter(y)
X_resampled = X.copy()
y_resampled = y.copy()
for (class_sample, num_samples) in self.ratio_.items():
index_samples = random_state.randint(low=0, high=target_stats[class_sample], size=num_samples)
X_resamp... |
'Estimate if a set of sample are in danger or noise.
Parameters
samples : ndarray, shape (n_samples, n_features)
The samples to check if either they are in danger or not.
target_class : int or str,
The target corresponding class being over-sampled.
y : ndarray, shape (n_samples, )
The true label in order to check the n... | def _in_danger_noise(self, samples, target_class, y, kind='danger'):
| x = self.nn_m_.kneighbors(samples, return_distance=False)[:, 1:]
nn_label = (y[x] != target_class).astype(int)
n_maj = np.sum(nn_label, axis=1)
if (kind == 'danger'):
return np.bitwise_and((n_maj >= ((self.nn_m_.n_neighbors - 1) / 2)), (n_maj < (self.nn_m_.n_neighbors - 1)))
elif (kind == 'n... |
'A support function that returns artificial samples constructed along
the line connecting nearest neighbours.
Parameters
X : ndarray, shape (n_samples, n_features)
Points from which the points will be created.
y_type : str or int
The minority target value, just so the function can return the
target values for the synth... | def _make_samples(self, X, y_type, nn_data, nn_num, n_samples, step_size=1.0):
| random_state = check_random_state(self.random_state)
X_new = np.zeros((n_samples, X.shape[1]))
samples = random_state.randint(low=0, high=len(nn_num.flatten()), size=n_samples)
steps = (step_size * random_state.uniform(size=n_samples))
rows = np.floor_divide(samples, nn_num.shape[1])
cols = np.m... |
'Create the necessary objects for SMOTE.'
| def _validate_estimator(self):
| deprecate_parameter(self, '0.2', 'k', 'k_neighbors')
deprecate_parameter(self, '0.2', 'm', 'm_neighbors')
if (self.kind not in SMOTE_KIND):
raise ValueError('Unknown kind for SMOTE algorithm. Choices are {}. Got {} instead.'.format(SMOTE_KIND, self.kind))
self.nn_k_... |
'Resample the dataset using the regular SMOTE implementation.
Use the regular SMOTE algorithm proposed in [1]_.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndar... | def _sample_regular(self, X, y):
| X_resampled = X.copy()
y_resampled = y.copy()
for (class_sample, n_samples) in self.ratio_.items():
if (n_samples == 0):
continue
X_class = X[(y == class_sample)]
self.nn_k_.fit(X_class)
nns = self.nn_k_.kneighbors(X_class, return_distance=False)[:, 1:]
(X... |
'Resample the dataset using the borderline SMOTE implementation.
Use the borderline SMOTE algorithm proposed in [2]_. Two methods can be
used: (i) borderline-1 or (ii) borderline-2. A nearest-neighbours
algorithm is used to determine the samples forming the boundaries and
will create samples next to those features depe... | def _sample_borderline(self, X, y):
| X_resampled = X.copy()
y_resampled = y.copy()
for (class_sample, n_samples) in self.ratio_.items():
if (n_samples == 0):
continue
X_class = X[(y == class_sample)]
self.nn_m_.fit(X)
danger_index = self._in_danger_noise(X_class, class_sample, y, kind='danger')
... |
'Resample the dataset using the SVM SMOTE implementation.
Use the SVM SMOTE algorithm proposed in [3]_. A SVM classifier detect
support vectors to get a notion of the boundary.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Cor... | def _sample_svm(self, X, y):
| random_state = check_random_state(self.random_state)
X_resampled = X.copy()
y_resampled = y.copy()
for (class_sample, n_samples) in self.ratio_.items():
if (n_samples == 0):
continue
X_class = X[(y == class_sample)]
self.svm_estimator_.fit(X, y)
support_index ... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
if (self.kind == 'regular'):
return self._sample_regular(X, y)
elif ((self.kind == 'borderline1') or (self.kind == 'borderline2')):
return self._sample_borderline(X, y)
elif (self.kind == 'svm'):
return self._sample_svm(X, y)
|
'Create the necessary objects for ADASYN'
| def _validate_estimator(self):
| deprecate_parameter(self, '0.2', 'k', 'n_neighbors')
self.nn_ = check_neighbors_object('n_neighbors', self.n_neighbors, additional_neighbor=1)
self.nn_.set_params(**{'n_jobs': self.n_jobs})
|
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
random_state = check_random_state(self.random_state)
X_resampled = X.copy()
y_resampled = y.copy()
for (class_sample, n_samples) in self.ratio_.items():
if (n_samples == 0):
continue
X_class = X[(y == class_sample)]
self.nn_.fit(X)
... |
'Private function to validate SMOTE and ENN objects'
| def _validate_estimator(self):
| if ((self.k is not None) or (self.m is not None) or (self.out_step is not None) or (self.kind_smote is not None) or (self.n_jobs is not None)):
warnings.warn('Parameters initialization will be replaced in version 0.4. Use a SMOTE object instead.', DeprecationWarning)
... |
'Find the classes statistics before to perform sampling.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
self : object,
Return self.'
| def fit(self, X, y):
| (X, y) = check_X_y(X, y)
y = check_target_type(y)
self.ratio_ = self.ratio
(self.X_hash_, self.y_hash_) = hash_X_y(X, y)
return self
|
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
(X_res, y_res) = self.smote_.fit_sample(X, y)
return self.tomek_.fit_sample(X_res, y_res)
|
'Private function to validate SMOTE and ENN objects'
| def _validate_estimator(self):
| if ((self.k is not None) or (self.m is not None) or (self.out_step is not None) or (self.kind_smote is not None) or (self.n_jobs is not None)):
if (self.k is None):
self.k = 5
if (self.m is None):
self.m = 10
if (self.out_step is None):
self.out_step = 0.5... |
'Find the classes statistics before to perform sampling.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
self : object,
Return self.'
| def fit(self, X, y):
| (X, y) = check_X_y(X, y)
y = check_target_type(y)
self.ratio_ = self.ratio
(self.X_hash_, self.y_hash_) = hash_X_y(X, y)
return self
|
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_samples_new, n_features)
The array containing the resampled data.
y_resampl... | def _sample(self, X, y):
| self._validate_estimator()
(X_res, y_res) = self.smote_.fit_sample(X, y)
return self.enn_.fit_sample(X_res, y_res)
|
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_subset, n_samples_new, n_features)
The array containing the resampled data.... | def _sample(self, X, y):
| random_state = check_random_state(self.random_state)
X_resampled = []
y_resampled = []
if self.return_indices:
idx_under = []
for _ in range(self.n_subsets):
rus = RandomUnderSampler(ratio=self.ratio_, return_indices=True, random_state=random_state.randint(MAX_INT), replacement=self.... |
'Find the classes statistics before to perform sampling.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
self : object,
Return self.'
| def fit(self, X, y):
| super(BalanceCascade, self).fit(X, y)
self.ratio_ = check_ratio(self.ratio, y, 'under-sampling')
return self
|
'Private function to create the classifier'
| def _validate_estimator(self):
| if (self.classifier is not None):
warnings.warn('`classifier` will be replaced in version 0.4. Use a `estimator` instead.', DeprecationWarning)
self.estimator = self.classifier
if ((self.estimator is not None) and isinstance(self.estimator, ClassifierMixin) and hasa... |
'Resample the dataset.
Parameters
X : ndarray, shape (n_samples, n_features)
Matrix containing the data which have to be sampled.
y : ndarray, shape (n_samples, )
Corresponding label for each sample in X.
Returns
X_resampled : ndarray, shape (n_subset, n_samples_new, n_features)
The array containing the resampled data.... | def _sample(self, X, y):
| self._validate_estimator()
random_state = check_random_state(self.random_state)
samples_mask = np.ones(y.shape, dtype=bool)
X_resampled = []
y_resampled = []
idx_under = []
n_subsets = 0
b_subset_search = True
while b_subset_search:
target_stats = Counter(y[samples_mask])
... |
'Fit the model
Fit all the transforms/samplers one after the other and
transform/sample the data, then fit the transformed/sampled
data using the final estimator.
Parameters
X : iterable
Training data. Must fulfill input requirements of first step of the
pipeline.
y : iterable, default=None
Training targets. Must fulfi... | def fit(self, X, y=None, **fit_params):
| (Xt, yt, fit_params) = self._fit(X, y, **fit_params)
if (self._final_estimator is not None):
self._final_estimator.fit(Xt, yt, **fit_params)
return self
|
'Fit the model and transform with the final estimator
Fits all the transformers/samplers one after the other and
transform/sample the data, then uses fit_transform on
transformed data with the final estimator.
Parameters
X : iterable
Training data. Must fulfill input requirements of first step of the
pipeline.
y : iter... | def fit_transform(self, X, y=None, **fit_params):
| last_step = self._final_estimator
(Xt, yt, fit_params) = self._fit(X, y, **fit_params)
if (last_step is None):
return Xt
elif hasattr(last_step, 'fit_transform'):
return last_step.fit_transform(Xt, yt, **fit_params)
else:
return last_step.fit(Xt, yt, **fit_params).transform(X... |
'Fit the model and sample with the final estimator
Fits all the transformers/samplers one after the other and
transform/sample the data, then uses fit_sample on transformed
data with the final estimator.
Parameters
X : iterable
Training data. Must fulfill input requirements of first step of the
pipeline.
y : iterable, ... | @if_delegate_has_method(delegate='_final_estimator')
def fit_sample(self, X, y=None, **fit_params):
| last_step = self._final_estimator
(Xt, yt, fit_params) = self._fit(X, y, **fit_params)
if (last_step is None):
return Xt
elif hasattr(last_step, 'fit_sample'):
return last_step.fit_sample(Xt, yt, **fit_params)
|
'Sample the data with the final estimator
Applies transformers/samplers to the data, and the sample
method of the final estimator. Valid only if the final
estimator implements sample.
Parameters
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.'
| @if_delegate_has_method(delegate='_final_estimator')
def sample(self, X, y):
| Xt = X
for (name, transform) in self.steps[:(-1)]:
if (transform is None):
continue
if hasattr(transform, 'fit_sample'):
(Xt, y) = transform.fit_sample(Xt, y)
else:
Xt = transform.transform(Xt)
return self.steps[(-1)][(-1)].fit_sample(Xt, y)
|
'Apply transformers/samplers to the data, and predict with the final
estimator
Parameters
X : iterable
Data to predict on. Must fulfill input requirements of first step
of the pipeline.
Returns
y_pred : array-like'
| @if_delegate_has_method(delegate='_final_estimator')
def predict(self, X):
| Xt = X
for (_, transform) in self.steps[:(-1)]:
if (transform is None):
continue
if hasattr(transform, 'fit_sample'):
pass
else:
Xt = transform.transform(Xt)
return self.steps[(-1)][(-1)].predict(Xt)
|
'Applies fit_predict of last step in pipeline after transforms.
Applies fit_transforms of a pipeline to the data, followed by the
fit_predict method of the final estimator in the pipeline. Valid
only if the final estimator implements fit_predict.
Parameters
X : iterable
Training data. Must fulfill input requirements of... | @if_delegate_has_method(delegate='_final_estimator')
def fit_predict(self, X, y=None, **fit_params):
| (Xt, yt, fit_params) = self._fit(X, y, **fit_params)
return self.steps[(-1)][(-1)].fit_predict(Xt, yt, **fit_params)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.