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 record(self, *args, **kwargs): """Track and record values each day. Parameters ---------- \*\*kwargs The names and values to record. Notes ----- These values will appear in the performance packets and the performance dataframe passed to `...
Track and record values each day. Parameters ---------- \*\*kwargs The names and values to record. Notes ----- These values will appear in the performance packets and the performance dataframe passed to ``analyze`` and returned from :func:`~c...
record
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def set_benchmark(self, benchmark): """Set the benchmark asset. Parameters ---------- benchmark : Asset The asset to set as the new benchmark. Notes ----- Any dividends payed out for that new benchmark asset will be automatically reinvested. ...
Set the benchmark asset. Parameters ---------- benchmark : Asset The asset to set as the new benchmark. Notes ----- Any dividends payed out for that new benchmark asset will be automatically reinvested.
set_benchmark
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def symbol(self, symbol_str): """Lookup an Equity by its ticker symbol. Parameters ---------- symbol_str : str The ticker symbol for the equity to lookup. Returns ------- equity : Equity The equity that held the ticker symbol on the curre...
Lookup an Equity by its ticker symbol. Parameters ---------- symbol_str : str The ticker symbol for the equity to lookup. Returns ------- equity : Equity The equity that held the ticker symbol on the current symbol lookup date. ...
symbol
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def continuous_future(self, root_symbol_str, offset=0, roll='volume', adjustment='mul'): """Create a specifier for a continuous contract. Parameters ---------- root_symbol_str : str ...
Create a specifier for a continuous contract. Parameters ---------- root_symbol_str : str The root symbol for the future chain. offset : int, optional The distance from the primary contract. Default is 0. roll_style : str, optional How rolls...
continuous_future
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def on_dt_changed(self, dt): """ Callback triggered by the simulation loop whenever the current dt changes. Any logic that should happen exactly once at the start of each datetime group should happen here. """ self.datetime = dt self.perf_tracker.set_date...
Callback triggered by the simulation loop whenever the current dt changes. Any logic that should happen exactly once at the start of each datetime group should happen here.
on_dt_changed
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def set_slippage(self, us_equities=None, us_futures=None): """Set the slippage models for the simulation. Parameters ---------- us_equities : EquitySlippageModel The slippage model to use for trading US equities. us_futures : FutureSlippageModel The slipp...
Set the slippage models for the simulation. Parameters ---------- us_equities : EquitySlippageModel The slippage model to use for trading US equities. us_futures : FutureSlippageModel The slippage model to use for trading US futures. See Also ---...
set_slippage
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def set_commission(self, us_equities=None, us_futures=None): """Sets the commission models for the simulation. Parameters ---------- us_equities : EquityCommissionModel The commission model to use for trading US equities. us_futures : FutureCommissionModel ...
Sets the commission models for the simulation. Parameters ---------- us_equities : EquityCommissionModel The commission model to use for trading US equities. us_futures : FutureCommissionModel The commission model to use for trading US futures. See Also ...
set_commission
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def set_cancel_policy(self, cancel_policy): """Sets the order cancellation policy for the simulation. Parameters ---------- cancel_policy : CancelPolicy The cancellation policy to use. See Also -------- :class:`catalyst.api.EODCancel` :class:...
Sets the order cancellation policy for the simulation. Parameters ---------- cancel_policy : CancelPolicy The cancellation policy to use. See Also -------- :class:`catalyst.api.EODCancel` :class:`catalyst.api.NeverCancel`
set_cancel_policy
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def set_symbol_lookup_date(self, dt): """Set the date for which symbols will be resolved to their assets Parameters ---------- dt : datetime The new symbol lookup date. """ try: self._symbol_lookup_date = pd.Timestamp(dt, tz='UTC') except ...
Set the date for which symbols will be resolved to their assets Parameters ---------- dt : datetime The new symbol lookup date.
set_symbol_lookup_date
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def batch_market_order(self, share_counts): """Place a batch market order for multiple assets. Parameters ---------- share_counts : pd.Series[Asset -> int] Map from TradingPair to the number to order for that TradingPair. Returns ------- order_ids : ...
Place a batch market order for multiple assets. Parameters ---------- share_counts : pd.Series[Asset -> int] Map from TradingPair to the number to order for that TradingPair. Returns ------- order_ids : pd.Index[str] Index of ids for newly-create...
batch_market_order
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def get_open_orders(self, asset=None): """Retrieve all of the current open orders. Parameters ---------- asset : Asset, optional If passed and not None, return only the open orders for the given asset instead of all open orders. Returns ------- ...
Retrieve all of the current open orders. Parameters ---------- asset : Asset, optional If passed and not None, return only the open orders for the given asset instead of all open orders. Returns ------- open_orders : dict[list[Order]] or list[Ord...
get_open_orders
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def set_asset_restrictions(self, restrictions, on_error='fail'): """Set a restriction on which assets can be ordered. Parameters ---------- restricted_list : Restrictions An object providing information about restricted assets. See Also -------- cata...
Set a restriction on which assets can be ordered. Parameters ---------- restricted_list : Restrictions An object providing information about restricted assets. See Also -------- catalyst.finance.asset_restrictions.Restrictions
set_asset_restrictions
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def attach_pipeline(self, pipeline, name, chunks=None): """Register a pipeline to be computed at the start of each day. Parameters ---------- pipeline : Pipeline The pipeline to have computed. name : str The name of the pipeline. chunks : int or i...
Register a pipeline to be computed at the start of each day. Parameters ---------- pipeline : Pipeline The pipeline to have computed. name : str The name of the pipeline. chunks : int or iterator, optional The number of days to compute pipelin...
attach_pipeline
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def pipeline_output(self, name): """Get the results of the pipeline that was attached with the name: ``name``. Parameters ---------- name : str Name of the pipeline for which results are requested. Returns ------- results : pd.DataFrame ...
Get the results of the pipeline that was attached with the name: ``name``. Parameters ---------- name : str Name of the pipeline for which results are requested. Returns ------- results : pd.DataFrame DataFrame containing the results of t...
pipeline_output
python
scrtlabs/catalyst
catalyst/algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/algorithm.py
Apache-2.0
def live(ctx, algofile, capital_base, algotext, define, output, print_algo, local_namespace, exchange_name, algo_namespace, quote_currency, start, end, live_graph, auth_aliases, simulat...
Trade live with the given algorithm.
live
python
scrtlabs/catalyst
catalyst/__main__.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/__main__.py
Apache-2.0
def remote_run(ctx, algofile, algotext, define, data_frequency, capital_base, bundle, bundle_timestamp, start, end, mail, print_algo, local_...
Run a backtest for the given algorithm on the cloud.
remote_run
python
scrtlabs/catalyst
catalyst/__main__.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/__main__.py
Apache-2.0
def remote_status(ctx, algo_id, data_output, log_output): """ Get the status of a running algorithm on the cloud """ if algo_id is None: ctx.fail("must specify an id of your running algorithm with '--id'") status_response = get_remote_status( algo_id=algo_id ) if isinstance(...
Get the status of a running algorithm on the cloud
remote_status
python
scrtlabs/catalyst
catalyst/__main__.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/__main__.py
Apache-2.0
def ingest_exchange(ctx, exchange_name, data_frequency, start, end, include_symbols, exclude_symbols, csv, show_progress, verbose, validate): """ Ingest data for the given exchange. """ if exchange_name is None: ctx.fail("must specify an exchange name '-x...
Ingest data for the given exchange.
ingest_exchange
python
scrtlabs/catalyst
catalyst/__main__.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/__main__.py
Apache-2.0
def clean_exchange(ctx, exchange_name, data_frequency): """Clean up bundles from 'ingest-exchange'. """ if exchange_name is None: ctx.fail("must specify an exchange name '-x'") exchange_bundle = ExchangeBundle(exchange_name) click.echo('Cleaning exchange bundle {}...'.format(exchange_name...
Clean up bundles from 'ingest-exchange'.
clean_exchange
python
scrtlabs/catalyst
catalyst/__main__.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/__main__.py
Apache-2.0
def _reset_caches(self): """ Reset our asset caches. You probably shouldn't call this method. """ # This method exists as a workaround for the in-place mutating behavior # of `TradingAlgorithm._write_and_map_id_index_to_sids`. No one else # should be calling thi...
Reset our asset caches. You probably shouldn't call this method.
_reset_caches
python
scrtlabs/catalyst
catalyst/assets/assets.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/assets.py
Apache-2.0
def reload_symbol_maps(self): """Clear the in memory symbol lookup maps. This will make any changes to the underlying db available to the symbol maps. """ # clear the lazyval caches, the next access will requery try: del type(self).symbol_ownership_map[self] ...
Clear the in memory symbol lookup maps. This will make any changes to the underlying db available to the symbol maps.
reload_symbol_maps
python
scrtlabs/catalyst
catalyst/assets/assets.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/assets.py
Apache-2.0
def lookup_symbol(self, symbol, as_of_date, fuzzy=False): """Lookup an equity by symbol. Parameters ---------- symbol : str The ticker symbol to resolve. as_of_date : datetime or None Look up the last owner of this symbol as of this datetime. ...
Lookup an equity by symbol. Parameters ---------- symbol : str The ticker symbol to resolve. as_of_date : datetime or None Look up the last owner of this symbol as of this datetime. If ``as_of_date`` is None, then this can only resolve the equity ...
lookup_symbol
python
scrtlabs/catalyst
catalyst/assets/assets.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/assets.py
Apache-2.0
def lookup_symbols(self, symbols, as_of_date, fuzzy=False): """ Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, as_of, fuzzy) for s in symbols] but potentially faster because repeated lookups are memoized. Parameters ---------...
Lookup a list of equities by symbol. Equivalent to:: [finder.lookup_symbol(s, as_of, fuzzy) for s in symbols] but potentially faster because repeated lookups are memoized. Parameters ---------- symbols : sequence[str] Sequence of ticker symbol...
lookup_symbols
python
scrtlabs/catalyst
catalyst/assets/assets.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/assets.py
Apache-2.0
def _symbol_lookups(self): """ An iterable of symbol lookup functions to use with ``lookup_generic`` Attempts equities lookup, then futures. """ return ( self.lookup_symbol, # lookup_future_symbol method does not use as_of date, since # symbol...
An iterable of symbol lookup functions to use with ``lookup_generic`` Attempts equities lookup, then futures.
_symbol_lookups
python
scrtlabs/catalyst
catalyst/assets/assets.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/assets.py
Apache-2.0
def lookup_generic(self, asset_convertible_or_iterable, as_of_date): """ Convert a AssetConvertible or iterable of AssetConvertibles into a list of Asset objects. This method exists primarily as a convenience for implementing user-fa...
Convert a AssetConvertible or iterable of AssetConvertibles into a list of Asset objects. This method exists primarily as a convenience for implementing user-facing APIs that can handle multiple kinds of input. It should not be used for internal code where we already know the ...
lookup_generic
python
scrtlabs/catalyst
catalyst/assets/assets.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/assets.py
Apache-2.0
def map_identifier_index_to_sids(self, index, as_of_date): """ This method is for use in sanitizing a user's DataFrame or Panel inputs. Takes the given index of identifiers, checks their types, builds assets if necessary, and returns a list of the sids that correspond to the ...
This method is for use in sanitizing a user's DataFrame or Panel inputs. Takes the given index of identifiers, checks their types, builds assets if necessary, and returns a list of the sids that correspond to the input index. Parameters ---------- index...
map_identifier_index_to_sids
python
scrtlabs/catalyst
catalyst/assets/assets.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/assets.py
Apache-2.0
def _compute_asset_lifetimes(self): """ Compute and cache a recarry of asset lifetimes. """ equities_cols = self.equities.c buf = np.array( tuple( sa.select(( equities_cols.sid, equities_cols.start_date, ...
Compute and cache a recarry of asset lifetimes.
_compute_asset_lifetimes
python
scrtlabs/catalyst
catalyst/assets/assets.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/assets.py
Apache-2.0
def lifetimes(self, dates, include_start_date): """ Compute a DataFrame representing asset lifetimes for the specified date range. Parameters ---------- dates : pd.DatetimeIndex The dates for which to compute lifetimes. include_start_date : bool ...
Compute a DataFrame representing asset lifetimes for the specified date range. Parameters ---------- dates : pd.DatetimeIndex The dates for which to compute lifetimes. include_start_date : bool Whether or not to count the asset as alive on its st...
lifetimes
python
scrtlabs/catalyst
catalyst/assets/assets.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/assets.py
Apache-2.0
def _generate_output_dataframe(data_subset, defaults): """ Generates an output dataframe from the given subset of user-provided data, the given column names, and the given default values. Parameters ---------- data_subset : DataFrame A DataFrame, usually from an AssetData object, ...
Generates an output dataframe from the given subset of user-provided data, the given column names, and the given default values. Parameters ---------- data_subset : DataFrame A DataFrame, usually from an AssetData object, that contains the user's input metadata for the asset type b...
_generate_output_dataframe
python
scrtlabs/catalyst
catalyst/assets/asset_writer.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/asset_writer.py
Apache-2.0
def _split_symbol_mappings(df): """Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. Returns ------- asset_info : pd.DataFrame The asset info with one row per asset. ...
Split out the symbol: sid mappings from the raw data. Parameters ---------- df : pd.DataFrame The dataframe with multiple rows for each symbol: sid pair. Returns ------- asset_info : pd.DataFrame The asset info with one row per asset. symbol_mappings : pd.DataFrame ...
_split_symbol_mappings
python
scrtlabs/catalyst
catalyst/assets/asset_writer.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/asset_writer.py
Apache-2.0
def write(self, equities=None, futures=None, exchanges=None, root_symbols=None, equity_supplementary_mappings=None, chunk_size=DEFAULT_CHUNK_SIZE): """Write asset metadata to a sqlite database. Parameters ------...
Write asset metadata to a sqlite database. Parameters ---------- equities : pd.DataFrame, optional The equity metadata. The columns for this dataframe are: symbol : str The ticker symbol for this equity. asset_name : str ...
write
python
scrtlabs/catalyst
catalyst/assets/asset_writer.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/asset_writer.py
Apache-2.0
def make_rotating_equity_info(num_assets, first_start, frequency, periods_between_starts, asset_lifetime): """ Create a DataFrame representing lifetimes of assets that are constantly rotat...
Create a DataFrame representing lifetimes of assets that are constantly rotating in and out of existence. Parameters ---------- num_assets : int How many assets to create. first_start : pd.Timestamp The start date for the first asset. frequency : str or pd.tseries.offsets.O...
make_rotating_equity_info
python
scrtlabs/catalyst
catalyst/assets/synthetic.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/synthetic.py
Apache-2.0
def make_simple_equity_info(sids, start_date, end_date, symbols=None): """ Create a DataFrame representing assets that exist for the full duration between `start_date` and `end_date`. Parameters ---------- sids ...
Create a DataFrame representing assets that exist for the full duration between `start_date` and `end_date`. Parameters ---------- sids : array-like of int start_date : pd.Timestamp, optional end_date : pd.Timestamp, optional symbols : list, optional Symbols to use for the asse...
make_simple_equity_info
python
scrtlabs/catalyst
catalyst/assets/synthetic.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/synthetic.py
Apache-2.0
def make_future_info(first_sid, root_symbols, years, notice_date_func, expiration_date_func, start_date_func, month_codes=None): """ Create a DataFrame representing futures for `root_sym...
Create a DataFrame representing futures for `root_symbols` during `year`. Generates a contract per triple of (symbol, year, month) supplied to `root_symbols`, `years`, and `month_codes`. Parameters ---------- first_sid : int The first sid to use for assigning sids to the created contr...
make_future_info
python
scrtlabs/catalyst
catalyst/assets/synthetic.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/synthetic.py
Apache-2.0
def make_commodity_future_info(first_sid, root_symbols, years, month_codes=None): """ Make futures testing data that simulates the notice/expiration date behavior of physical commodities like oil. Parameters ...
Make futures testing data that simulates the notice/expiration date behavior of physical commodities like oil. Parameters ---------- first_sid : int root_symbols : list[str] years : list[int] month_codes : dict[str -> int] Expiration dates are on the 20th of the month prior to the...
make_commodity_future_info
python
scrtlabs/catalyst
catalyst/assets/synthetic.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/assets/synthetic.py
Apache-2.0
def get_currency_pairs(self): ''' Retrieves and returns all currency pairs from the exchange ''' url = self._api_path + 'command=returnTicker' try: response = requests.get(url) except Exception as e: log.error('Failed to retrieve list of currency ...
Retrieves and returns all currency pairs from the exchange
get_currency_pairs
python
scrtlabs/catalyst
catalyst/curate/poloniex.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/curate/poloniex.py
Apache-2.0
def _retrieve_tradeID_date(self, row): ''' Helper function that reads tradeID and date fields from CSV readline ''' tId = int(row.split(',')[0]) d = pd.to_datetime(row.split(',')[1], infer_datetime_format=True).value // 10 ** 9 return tId, d
Helper function that reads tradeID and date fields from CSV readline
_retrieve_tradeID_date
python
scrtlabs/catalyst
catalyst/curate/poloniex.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/curate/poloniex.py
Apache-2.0
def generate_ohlcv(self, df): ''' Generates OHLCV dataframe from a dataframe containing all TradeHistory by resampling with 1-minute period ''' df.set_index('date', inplace=True) # Index by date vol = df['total'].to_frame('volume') # set Vol aside ...
Generates OHLCV dataframe from a dataframe containing all TradeHistory by resampling with 1-minute period
generate_ohlcv
python
scrtlabs/catalyst
catalyst/curate/poloniex.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/curate/poloniex.py
Apache-2.0
def write_ohlcv_file(self, currencyPair): ''' Generates OHLCV data file with 1minute bars from TradeHistory on disk ''' csv_trades = CSV_OUT_FOLDER + 'crypto_trades-' + currencyPair + '.csv' csv_1min = CSV_OUT_FOLDER + 'crypto_1min-' + currencyPair + '.csv' if(os.path.get...
Generates OHLCV data file with 1minute bars from TradeHistory on disk
write_ohlcv_file
python
scrtlabs/catalyst
catalyst/curate/poloniex.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/curate/poloniex.py
Apache-2.0
def onemin_to_dataframe(self, currencyPair, start, end): ''' Returns a data frame for a given currencyPair from data on disk ''' csv_fn = CSV_OUT_FOLDER + 'crypto_1min-' + currencyPair + '.csv' df = pd.read_csv(csv_fn, names=['date', 'open'...
Returns a data frame for a given currencyPair from data on disk
onemin_to_dataframe
python
scrtlabs/catalyst
catalyst/curate/poloniex.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/curate/poloniex.py
Apache-2.0
def generate_symbols_json(self, filename=None): ''' Generates a symbols.json file with corresponding start_date for each currencyPair ''' symbol_map = {} if(filename is None): filename = get_exchange_symbols_filename('poloniex') with open(filename, '...
Generates a symbols.json file with corresponding start_date for each currencyPair
generate_symbols_json
python
scrtlabs/catalyst
catalyst/curate/poloniex.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/curate/poloniex.py
Apache-2.0
def get_last_traded_dt(self, asset, dt): """ Get the latest minute on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : catalyst.asset.Asset The asset for which to get th...
Get the latest minute on or before ``dt`` in which ``asset`` traded. If there are no trades on or before ``dt``, returns ``pd.NaT``. Parameters ---------- asset : catalyst.asset.Asset The asset for which to get the last traded minute. dt : pd.Timestamp ...
get_last_traded_dt
python
scrtlabs/catalyst
catalyst/data/continuous_future_reader.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/continuous_future_reader.py
Apache-2.0
def get_adjustments(self, assets, field, dt, perspective_dt): """ Returns a list of adjustments between the dt and perspective_dt for the given field and list of assets Parameters ---------- assets : list of type Asset, or Asset The asset, or assets whose adj...
Returns a list of adjustments between the dt and perspective_dt for the given field and list of assets Parameters ---------- assets : list of type Asset, or Asset The asset, or assets whose adjustments are desired. field : {'open', 'high', 'low', 'close', 'v...
get_adjustments
python
scrtlabs/catalyst
catalyst/data/data_portal.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/data_portal.py
Apache-2.0
def get_history_window(self, assets, end_dt, bar_count, frequency, field, data_frequency, ffill=True): """ Public A...
Public API method that returns a dataframe containing the requested history window. Data is fully adjusted. Parameters ---------- assets : list of catalyst.data.Asset objects The assets whose data is desired. bar_count: int The number of bars d...
get_history_window
python
scrtlabs/catalyst
catalyst/data/data_portal.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/data_portal.py
Apache-2.0
def get_data_filepath(name, environ=None): """ Returns a handle to data file. Creates containing directory, if needed. """ dr = data_root(environ) if not os.path.exists(dr): os.makedirs(dr) return os.path.join(dr, name)
Returns a handle to data file. Creates containing directory, if needed.
get_data_filepath
python
scrtlabs/catalyst
catalyst/data/loader.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/loader.py
Apache-2.0
def has_data_for_dates(series_or_df, first_date, last_date): """ Does `series_or_df` have data on or before first_date and on or after last_date? """ dts = series_or_df.index if not isinstance(dts, pd.DatetimeIndex): raise TypeError("Expected a DatetimeIndex, but got %s." % type(dts)) ...
Does `series_or_df` have data on or before first_date and on or after last_date?
has_data_for_dates
python
scrtlabs/catalyst
catalyst/data/loader.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/loader.py
Apache-2.0
def load_market_data(trading_day=None, trading_days=None, bm_symbol='SPY', environ=None): """ Load benchmark returns and treasury yield curves for the given calendar and benchmark symbol. Benchmarks are downloaded as a Series from Google Finance. Treasury curves are US Treasur...
Load benchmark returns and treasury yield curves for the given calendar and benchmark symbol. Benchmarks are downloaded as a Series from Google Finance. Treasury curves are US Treasury Bond rates and are downloaded from 'www.federalreserve.gov' by default. For Canadian exchanges, a loader for Ca...
load_market_data
python
scrtlabs/catalyst
catalyst/data/loader.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/loader.py
Apache-2.0
def ensure_benchmark_data(symbol, first_date, last_date, now, trading_day, environ=None): """ Ensure we have benchmark data for `symbol` from `first_date` to `last_date` Parameters ---------- symbol : str The symbol for the benchmark to load. first_date : pd.Ti...
Ensure we have benchmark data for `symbol` from `first_date` to `last_date` Parameters ---------- symbol : str The symbol for the benchmark to load. first_date : pd.Timestamp First required date for the cache. last_date : pd.Timestamp Last required date for the cache. ...
ensure_benchmark_data
python
scrtlabs/catalyst
catalyst/data/loader.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/loader.py
Apache-2.0
def ensure_treasury_data(symbol, first_date, last_date, now, environ=None): """ Ensure we have treasury data from treasury module associated with `symbol`. Parameters ---------- symbol : str Benchmark symbol for which we're loading associated treasury curves. first_date : pd.Timesta...
Ensure we have treasury data from treasury module associated with `symbol`. Parameters ---------- symbol : str Benchmark symbol for which we're loading associated treasury curves. first_date : pd.Timestamp First date required to be in the cache. last_date : pd.Timestamp ...
ensure_treasury_data
python
scrtlabs/catalyst
catalyst/data/loader.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/loader.py
Apache-2.0
def _load_raw_yahoo_data(indexes=None, stocks=None, start=None, end=None): """Load closing prices from yahoo finance. :Optional: indexes : dict (Default: {'SPX': '^SPY'}) Financial indexes to load. stocks : list (Default: ['AAPL', 'GE', 'IBM', 'MSFT', ...
Load closing prices from yahoo finance. :Optional: indexes : dict (Default: {'SPX': '^SPY'}) Financial indexes to load. stocks : list (Default: ['AAPL', 'GE', 'IBM', 'MSFT', 'XOM', 'AA', 'JNJ', 'PEP', 'KO']) Stock closing prices to load. ...
_load_raw_yahoo_data
python
scrtlabs/catalyst
catalyst/data/loader.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/loader.py
Apache-2.0
def load_from_yahoo(indexes=None, stocks=None, start=None, end=None, adjusted=True): """ Loads price data from Yahoo into a dataframe for each of the indicated assets. By default, 'price' is taken from Yahoo's 'Adjusted Close',...
Loads price data from Yahoo into a dataframe for each of the indicated assets. By default, 'price' is taken from Yahoo's 'Adjusted Close', which removes the impact of splits and dividends. If the argument 'adjusted' is False, then the non-adjusted 'close' field is used instead. :param indexes: Fi...
load_from_yahoo
python
scrtlabs/catalyst
catalyst/data/loader.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/loader.py
Apache-2.0
def load_bars_from_yahoo(indexes=None, stocks=None, start=None, end=None, adjusted=True): """ Loads data from Yahoo into a panel with the following column names for each indicated security: - open ...
Loads data from Yahoo into a panel with the following column names for each indicated security: - open - high - low - close - volume - price Note that 'price' is Yahoo's 'Adjusted Close', which removes the impact of splits and dividends. If the argument...
load_bars_from_yahoo
python
scrtlabs/catalyst
catalyst/data/loader.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/loader.py
Apache-2.0
def convert_cols(cols, scale_factor, sid, invalid_data_behavior): """Adapt OHLCV columns into uint64 columns. Parameters ---------- cols : dict A dict mapping each column name (open, high, low, close, volume) to a float column to convert to uint64. scale_factor : int Factor ...
Adapt OHLCV columns into uint64 columns. Parameters ---------- cols : dict A dict mapping each column name (open, high, low, close, volume) to a float column to convert to uint64. scale_factor : int Factor to use to scale float values before converting to uint64. sid : int ...
convert_cols
python
scrtlabs/catalyst
catalyst/data/minute_bars.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/minute_bars.py
Apache-2.0
def write(self, rootdir): """ Write the metadata to a JSON file in the rootdir. Values contained in the metadata are: version : int The value of FORMAT_VERSION of this class. ohlc_ratio : int The default ratio by which to multiply the pricing data to ...
Write the metadata to a JSON file in the rootdir. Values contained in the metadata are: version : int The value of FORMAT_VERSION of this class. ohlc_ratio : int The default ratio by which to multiply the pricing data to convert the floats from floa...
write
python
scrtlabs/catalyst
catalyst/data/minute_bars.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/minute_bars.py
Apache-2.0
def minute_frame_to_session_frame(minute_frame, calendar): """ Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `d...
Resample a DataFrame with minute data into the frame expected by a BcolzDailyBarWriter. Parameters ---------- minute_frame : pd.DataFrame A DataFrame with the columns `open`, `high`, `low`, `close`, `volume`, and `dt` (minute dts) calendar : catalyst.utils.calendars.trading_cal...
minute_frame_to_session_frame
python
scrtlabs/catalyst
catalyst/data/resample.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/resample.py
Apache-2.0
def parse_treasury_csv_column(column): """ Parse a treasury CSV column into a more human-readable format. Columns start with 'RIFLGFC', followed by Y or M (year or month), followed by a two-digit number signifying number of years/months, followed by _N.B. We only care about the middle two entries, ...
Parse a treasury CSV column into a more human-readable format. Columns start with 'RIFLGFC', followed by Y or M (year or month), followed by a two-digit number signifying number of years/months, followed by _N.B. We only care about the middle two entries, which we turn into a string like 3month or...
parse_treasury_csv_column
python
scrtlabs/catalyst
catalyst/data/treasuries.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/treasuries.py
Apache-2.0
def earliest_possible_date(): """ The earliest date for which we can load data from this module. """ # The US Treasury actually has data going back further than this, but it's # pretty rare to find pricing data going back that far, and there's no # reason to make people download benchmarks back ...
The earliest date for which we can load data from this module.
earliest_possible_date
python
scrtlabs/catalyst
catalyst/data/treasuries.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/treasuries.py
Apache-2.0
def get_daily_10yr_treasury_data(): """Download daily 10 year treasury rates from the Federal Reserve and return a pandas.Series.""" url = "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15" \ "&series=bcb44e57fb57efbe90002369321bfb3f&lastObs=&from=&to=" \ "&filetype=csv&la...
Download daily 10 year treasury rates from the Federal Reserve and return a pandas.Series.
get_daily_10yr_treasury_data
python
scrtlabs/catalyst
catalyst/data/treasuries.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/treasuries.py
Apache-2.0
def _format_url(instrument_type, instrument_ids, start_date, end_date, earliest_allowed_date): """ Format a URL for loading data from Bank of Canada. """ return ( "http://www.bankofcanada.ca/stats/results/csv" "?lP=lookup_{i...
Format a URL for loading data from Bank of Canada.
_format_url
python
scrtlabs/catalyst
catalyst/data/treasuries_can.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/treasuries_can.py
Apache-2.0
def load_frame(url, skiprows): """ Load a DataFrame of data from a Bank of Canada site. """ return pd.read_csv( url, skiprows=skiprows, skipinitialspace=True, na_values=["Bank holiday", "Not available"], parse_dates=["Date"], index_col="Date", ).dropna...
Load a DataFrame of data from a Bank of Canada site.
load_frame
python
scrtlabs/catalyst
catalyst/data/treasuries_can.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/treasuries_can.py
Apache-2.0
def check_known_inconsistencies(bill_data, bond_data): """ There are a couple quirks in the data provided by Bank of Canada. Check that no new quirks have been introduced in the latest download. """ inconsistent_dates = bill_data.index.sym_diff(bond_data.index) known_inconsistencies = [ ...
There are a couple quirks in the data provided by Bank of Canada. Check that no new quirks have been introduced in the latest download.
check_known_inconsistencies
python
scrtlabs/catalyst
catalyst/data/treasuries_can.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/treasuries_can.py
Apache-2.0
def winsorise_uint64(df, invalid_data_behavior, column, *columns): """Drops any record where a value would not fit into a uint64. Parameters ---------- df : pd.DataFrame The dataframe to winsorise. invalid_data_behavior : {'warn', 'raise', 'ignore'} What to do when data is outside t...
Drops any record where a value would not fit into a uint64. Parameters ---------- df : pd.DataFrame The dataframe to winsorise. invalid_data_behavior : {'warn', 'raise', 'ignore'} What to do when data is outside the bounds of a uint64. *columns : iterable[str] The names of t...
winsorise_uint64
python
scrtlabs/catalyst
catalyst/data/us_equity_pricing.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/us_equity_pricing.py
Apache-2.0
def write(self, data, assets=None, show_progress=False, invalid_data_behavior='warn'): """ Parameters ---------- data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]] The data chunks to write. Each chunk should b...
Parameters ---------- data : iterable[tuple[int, pandas.DataFrame or bcolz.ctable]] The data chunks to write. Each chunk should be a tuple of sid and the data for that asset. assets : set[int], optional The assets that should be in ``data``. If this i...
write
python
scrtlabs/catalyst
catalyst/data/us_equity_pricing.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/us_equity_pricing.py
Apache-2.0
def write_csvs(self, asset_map, show_progress=False, invalid_data_behavior='warn'): """Read CSVs as DataFrames from our asset map. Parameters ---------- asset_map : dict[int -> str] A mapping from asset id to file path...
Read CSVs as DataFrames from our asset map. Parameters ---------- asset_map : dict[int -> str] A mapping from asset id to file path with the CSV data for that asset show_progress : bool Whether or not to show a progress bar while writing. inva...
write_csvs
python
scrtlabs/catalyst
catalyst/data/us_equity_pricing.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/us_equity_pricing.py
Apache-2.0
def get_last_traded_dt(self, asset, dt): """ Parameters ---------- asset : catalyst.asset.Asset The asset identifier. dt : datetime64-like Midnight of the day for which data is requested. Returns ------- pd.Timestamp : The last kno...
Parameters ---------- asset : catalyst.asset.Asset The asset identifier. dt : datetime64-like Midnight of the day for which data is requested. Returns ------- pd.Timestamp : The last know dt for the asset and dt; Na...
get_last_traded_dt
python
scrtlabs/catalyst
catalyst/data/us_equity_pricing.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/us_equity_pricing.py
Apache-2.0
def write(self, splits=None, mergers=None, dividends=None, stock_dividends=None): """ Writes data to a SQLite file to be read by SQLiteAdjustmentReader. Parameters ---------- splits : pandas.DataFrame, optional ...
Writes data to a SQLite file to be read by SQLiteAdjustmentReader. Parameters ---------- splits : pandas.DataFrame, optional Dataframe containing split data. The format of this dataframe is: effective_date : int The date, represented as secon...
write
python
scrtlabs/catalyst
catalyst/data/us_equity_pricing.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/us_equity_pricing.py
Apache-2.0
def _make_bundle_core(): """Create a family of data bundle functions that read from the same bundle mapping. Returns ------- bundles : mappingproxy The mapping of bundles to bundle payloads. register_bundle : Bundle A bundle instance to add to the ``bundles`` mapping. regist...
Create a family of data bundle functions that read from the same bundle mapping. Returns ------- bundles : mappingproxy The mapping of bundles to bundle payloads. register_bundle : Bundle A bundle instance to add to the ``bundles`` mapping. register : callable The functi...
_make_bundle_core
python
scrtlabs/catalyst
catalyst/data/bundles/core.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/bundles/core.py
Apache-2.0
def register(name, f, calendar_name='OPEN', start_session=None, end_session=None, minutes_per_day=1440, create_writers=True): """Register a data bundle ingest function. Parameters ---------- ...
Register a data bundle ingest function. Parameters ---------- name : str The name of the bundle. f : callable The ingest function. This function will be passed: environ : mapping The environment this is being run with. ...
register
python
scrtlabs/catalyst
catalyst/data/bundles/core.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/bundles/core.py
Apache-2.0
def unregister(name): """Unregister a bundle. Parameters ---------- name : str The name of the bundle to unregister. Raises ------ UnknownBundle Raised when no bundle has been registered with the given name. See Also ----...
Unregister a bundle. Parameters ---------- name : str The name of the bundle to unregister. Raises ------ UnknownBundle Raised when no bundle has been registered with the given name. See Also -------- catalyst.data.bundle...
unregister
python
scrtlabs/catalyst
catalyst/data/bundles/core.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/bundles/core.py
Apache-2.0
def most_recent_data(bundle_name, timestamp, environ=None): """Get the path to the most recent data after ``date``for the given bundle. Parameters ---------- bundle_name : str The name of the bundle to lookup. timestamp : datetime The timestamp to...
Get the path to the most recent data after ``date``for the given bundle. Parameters ---------- bundle_name : str The name of the bundle to lookup. timestamp : datetime The timestamp to begin searching on or before. environ : dict, optional ...
most_recent_data
python
scrtlabs/catalyst
catalyst/data/bundles/core.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/bundles/core.py
Apache-2.0
def clean(name, before=None, after=None, keep_last=None, environ=os.environ): """Clean up data that was created with ``ingest`` or ``$ python -m catalyst ingest`` Parameters ---------- name : str The name of the...
Clean up data that was created with ``ingest`` or ``$ python -m catalyst ingest`` Parameters ---------- name : str The name of the bundle to remove data for. before : datetime, optional Remove data ingested before this date. This argument is m...
clean
python
scrtlabs/catalyst
catalyst/data/bundles/core.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/bundles/core.py
Apache-2.0
def _format_metadata_url(self, api_key, page_number): """Build the query RL for the quandl WIKI metadata. """ query_params = [ ('per_page', '100'), ('sort_by', 'id'), ('page', str(page_number)), ('database_code', 'WIKI'), ] if api_k...
Build the query RL for the quandl WIKI metadata.
_format_metadata_url
python
scrtlabs/catalyst
catalyst/data/bundles/quandl.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/bundles/quandl.py
Apache-2.0
def _format_wiki_url(self, api_key, symbol, start_date, end_date, data_frequency): """ Build a query URL for a quandl WIKI dataset. """ query_params = [ ...
Build a query URL for a quandl WIKI dataset.
_format_wiki_url
python
scrtlabs/catalyst
catalyst/data/bundles/quandl.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/bundles/quandl.py
Apache-2.0
def yahoo_equities(symbols, start=None, end=None): """Create a data bundle ingest function from a set of symbols loaded from yahoo. Parameters ---------- symbols : iterable[str] The ticker symbols to load data for. start : datetime, optional The start date to query for. By defau...
Create a data bundle ingest function from a set of symbols loaded from yahoo. Parameters ---------- symbols : iterable[str] The ticker symbols to load data for. start : datetime, optional The start date to query for. By default this pulls the full history for the calendar. ...
yahoo_equities
python
scrtlabs/catalyst
catalyst/data/bundles/yahoo.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/data/bundles/yahoo.py
Apache-2.0
def place_orders(context, amount, buying_price, selling_price, action): """ This method will always place two orders of the same amount to keep the currency position the same as it moves between the two exchanges. :param context: TradingAlgorithm :param amount: float The trading pair amount...
This method will always place two orders of the same amount to keep the currency position the same as it moves between the two exchanges. :param context: TradingAlgorithm :param amount: float The trading pair amount to trade on both exchanges. :param buying_price: float The current...
place_orders
python
scrtlabs/catalyst
catalyst/examples/arbitrage_with_interface.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/examples/arbitrage_with_interface.py
Apache-2.0
def run_example(example_name, environ): """ Run an example module from catalyst.examples. """ mod = EXAMPLE_MODULES[example_name] register_calendar("YAHOO", get_calendar("NYSE"), force=True) return run_algorithm( initialize=getattr(mod, 'initialize', None), handle_data=getattr(...
Run an example module from catalyst.examples.
run_example
python
scrtlabs/catalyst
catalyst/examples/__init__.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/examples/__init__.py
Apache-2.0
def get_symbol(self, asset): """ The exchange specific symbol of the specified market. Parameters ---------- asset: TradingPair Returns ------- str """ symbol = None for a in self.assets: if not symbol and a.symbol =...
The exchange specific symbol of the specified market. Parameters ---------- asset: TradingPair Returns ------- str
get_symbol
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def get_symbols(self, assets): """ Get a list of symbols corresponding to each given asset. Parameters ---------- assets: list[TradingPair] Returns ------- list[str] """ symbols = [] for asset in assets: symbols.appen...
Get a list of symbols corresponding to each given asset. Parameters ---------- assets: list[TradingPair] Returns ------- list[str]
get_symbols
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def get_assets(self, symbols=None, data_frequency=None, is_exchange_symbol=False, is_local=None, quote_currency=None): """ The list of markets for the specified symbols. Parameters ---------- symbols: list[str] data_frequency: str ...
The list of markets for the specified symbols. Parameters ---------- symbols: list[str] data_frequency: str is_exchange_symbol: bool is_local: bool Returns ------- list[TradingPair] A list of asset objects. Notes ...
get_assets
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def get_asset(self, symbol, data_frequency=None, is_exchange_symbol=False, is_local=None): """ The market for the specified symbol. Parameters ---------- symbol: str The Catalyst or exchange symbol. data_frequency: str Check for...
The market for the specified symbol. Parameters ---------- symbol: str The Catalyst or exchange symbol. data_frequency: str Check for asset corresponding to the specified data_frequency. The same asset might exist in the Catalyst repository ...
get_asset
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def init(self): """ Load the asset list from the network. Returns ------- """
Load the asset list from the network. Returns -------
init
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def get_spot_value(self, assets, field, dt=None, data_frequency='minute'): """ Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset, ContinuousFuture, or iterable of...
Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset, ContinuousFuture, or iterable of same. The asset or assets whose data is desired. field : {'open',...
get_spot_value
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def get_series_from_candles(self, candles, start_dt, end_dt, data_frequency, field, previous_value=None): """ Get a series of field data for the specified candles. Parameters ---------- candles: list[dict[str, float]] start_dt: datetime ...
Get a series of field data for the specified candles. Parameters ---------- candles: list[dict[str, float]] start_dt: datetime end_dt: datetime data_frequency: str field: str previous_value: float Returns ------- Series ...
get_series_from_candles
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def get_history_window(self, assets, end_dt, bar_count, frequency, field, data_frequency=None, is_current=False): """ ...
Public API method that returns a dataframe containing the requested history window. Data is fully adjusted. Parameters ---------- assets : list[TradingPair] The assets whose data is desired. end_dt: datetime The date of the last bar ba...
get_history_window
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def get_history_window_with_bundle(self, assets, end_dt, bar_count, frequency, field, ...
Public API method that returns a dataframe containing the requested history window. Data is fully adjusted. Parameters ---------- assets : list[TradingPair] The assets whose data is desired. end_dt: datetime The date of the last bar. b...
get_history_window_with_bundle
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def _check_low_balance(self, currency, balances, amount): """ In order to avoid spending money that the user doesn't own, we are comparing to the balance on the account. For positions, we want to avoid double updates, since, exchanges update positions when the order is opened as ...
In order to avoid spending money that the user doesn't own, we are comparing to the balance on the account. For positions, we want to avoid double updates, since, exchanges update positions when the order is opened as used, catalyst wants to take them into consideration, therefo...
_check_low_balance
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def sync_positions(self, positions, cash=None, check_balances=False): """ Update the portfolio cash and position balances based on the latest ticker prices. Parameters ---------- positions: The positions to synchronize. check_b...
Update the portfolio cash and position balances based on the latest ticker prices. Parameters ---------- positions: The positions to synchronize. check_balances: Check balances amounts against the exchange.
sync_positions
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def get_order(self, order_id, symbol_or_asset=None, return_price=False, params={}): """Lookup an order based on the order id returned from one of the order functions. Parameters ---------- order_id : str The unique identifier for the order. ...
Lookup an order based on the order id returned from one of the order functions. Parameters ---------- order_id : str The unique identifier for the order. symbol_or_asset: str|TradingPair The catalyst symbol, some exchanges need this return_price: ...
get_order
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def process_order(self, order): """ Similar to get_order but looks only for executed orders. Parameters ---------- order: Order Returns ------- float Avg execution price """
Similar to get_order but looks only for executed orders. Parameters ---------- order: Order Returns ------- float Avg execution price
process_order
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def cancel_order(self, order_param, symbol_or_asset=None, params={}): """Cancel an open order. Parameters ---------- order_param : str or Order The order_id or order object to cancel. symbol_or_asset: str|TradingPair The catalyst symb...
Cancel an open order. Parameters ---------- order_param : str or Order The order_id or order object to cancel. symbol_or_asset: str|TradingPair The catalyst symbol, some exchanges need this params:
cancel_order
python
scrtlabs/catalyst
catalyst/exchange/exchange.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange.py
Apache-2.0
def set_commission(self, maker=None, taker=None): """Sets the maker and taker fees of the commission model for the simulation. Parameters ---------- maker : float The taker fee - taking from the order book. taker : float The maker fee - adding to the orde...
Sets the maker and taker fees of the commission model for the simulation. Parameters ---------- maker : float The taker fee - taking from the order book. taker : float The maker fee - adding to the order book.
set_commission
python
scrtlabs/catalyst
catalyst/exchange/exchange_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange_algorithm.py
Apache-2.0
def set_slippage(self, slippage=None): """Set the slippage of the fixed slippage model used by the simulation. Parameters ---------- slippage : float The slippage to be set. """ key = list(self.blotter.slippage_models.keys())[0] if slippage is not Non...
Set the slippage of the fixed slippage model used by the simulation. Parameters ---------- slippage : float The slippage to be set.
set_slippage
python
scrtlabs/catalyst
catalyst/exchange/exchange_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange_algorithm.py
Apache-2.0
def _calculate_order_target_amount(self, asset, target): """ removes order amounts so we won't run into issues when two orders are placed one after the other. it then proceeds to removing positions amount at TradingAlgorithm :param asset: :param target: :return: t...
removes order amounts so we won't run into issues when two orders are placed one after the other. it then proceeds to removing positions amount at TradingAlgorithm :param asset: :param target: :return: target
_calculate_order_target_amount
python
scrtlabs/catalyst
catalyst/exchange/exchange_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange_algorithm.py
Apache-2.0
def symbol(self, symbol_str, exchange_name=None): """Lookup a Trading pair by its ticker symbol. Catalyst defines its own set of "universal" symbols to reference trading pairs across exchanges. This is required because exchanges are not adhering to a universal symbolism. For example, Bit...
Lookup a Trading pair by its ticker symbol. Catalyst defines its own set of "universal" symbols to reference trading pairs across exchanges. This is required because exchanges are not adhering to a universal symbolism. For example, Bitfinex uses the BTC symbol for Bitcon while Kraken use...
symbol
python
scrtlabs/catalyst
catalyst/exchange/exchange_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange_algorithm.py
Apache-2.0
def prepare_period_stats(self, start_dt, end_dt): """ Creates a dictionary representing the state of the tracker. Parameters ---------- start_dt: datetime end_dt: datetime Notes ----- I rewrote this in an attempt to better control the stats. ...
Creates a dictionary representing the state of the tracker. Parameters ---------- start_dt: datetime end_dt: datetime Notes ----- I rewrote this in an attempt to better control the stats. I don't want things to happen magically through complex l...
prepare_period_stats
python
scrtlabs/catalyst
catalyst/exchange/exchange_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange_algorithm.py
Apache-2.0
def get_frame_stats(self): """ preparing the stats before analyze :return: stats: pd.Dataframe """ # add the last day stats which is not saved in the directory current_stats = pd.DataFrame(self.frame_stats) current_stats.set_index('period_close', drop=False, inpla...
preparing the stats before analyze :return: stats: pd.Dataframe
get_frame_stats
python
scrtlabs/catalyst
catalyst/exchange/exchange_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange_algorithm.py
Apache-2.0
def interrupt_algorithm(self): """ when algorithm comes to an end this function is called. extracts the stats and calls analyze. after finishing, it exits the run. Parameters ---------- Returns ------- """ self.is_running = False ...
when algorithm comes to an end this function is called. extracts the stats and calls analyze. after finishing, it exits the run. Parameters ---------- Returns -------
interrupt_algorithm
python
scrtlabs/catalyst
catalyst/exchange/exchange_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange_algorithm.py
Apache-2.0
def _init_trading_client(self): """ This replaces Ziplines `_create_generator` method. The main difference is that we are restoring performance tracker objects if available. This allows us to stop/start algos without loosing their state. """ self.state = get_algo_object(...
This replaces Ziplines `_create_generator` method. The main difference is that we are restoring performance tracker objects if available. This allows us to stop/start algos without loosing their state.
_init_trading_client
python
scrtlabs/catalyst
catalyst/exchange/exchange_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange_algorithm.py
Apache-2.0
def synchronize_portfolio(self): """ Synchronizes the portfolio tracked by the algorithm to refresh its current value. This includes updating the last_sale_price of all tracked positions, returning the available cash, and raising error if the data goes out of sync. ...
Synchronizes the portfolio tracked by the algorithm to refresh its current value. This includes updating the last_sale_price of all tracked positions, returning the available cash, and raising error if the data goes out of sync. Returns ------- float ...
synchronize_portfolio
python
scrtlabs/catalyst
catalyst/exchange/exchange_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange_algorithm.py
Apache-2.0
def add_custom_signals_stats(self, period_stats): """ Save custom signals stats. Parameters ---------- period_stats Returns ------- """ log.debug('adding custom signals stats: {}'.format(self.recorded_vars)) df = pd.DataFrame( ...
Save custom signals stats. Parameters ---------- period_stats Returns -------
add_custom_signals_stats
python
scrtlabs/catalyst
catalyst/exchange/exchange_algorithm.py
https://github.com/scrtlabs/catalyst/blob/master/catalyst/exchange/exchange_algorithm.py
Apache-2.0