Compare commits

..
32 changed files with 1136 additions and 1197 deletions
+380 -16
View File
@@ -14,6 +14,7 @@ from catalyst.exchange.exchange_bundle import ExchangeBundle
from catalyst.exchange.utils.exchange_utils import delete_algo_folder from catalyst.exchange.utils.exchange_utils import delete_algo_folder
from catalyst.utils.cli import Date, Timestamp from catalyst.utils.cli import Date, Timestamp
from catalyst.utils.run_algo import _run, load_extensions from catalyst.utils.run_algo import _run, load_extensions
from catalyst.utils.run_server import run_server
try: try:
__IPYTHON__ __IPYTHON__
@@ -505,6 +506,370 @@ def live(ctx,
return perf return perf
@main.command(name='serve')
@click.option(
'-f',
'--algofile',
default=None,
type=click.File('r'),
help='The file that contains the algorithm to run.',
)
@click.option(
'-t',
'--algotext',
help='The algorithm script to run.',
)
@click.option(
'-D',
'--define',
multiple=True,
help="Define a name to be bound in the namespace before executing"
" the algotext. For example '-Dname=value'. The value may be"
" any python expression. These are evaluated in order so they"
" may refer to previously defined names.",
)
@click.option(
'--data-frequency',
type=click.Choice({'daily', 'minute'}),
default='daily',
show_default=True,
help='The data frequency of the simulation.',
)
@click.option(
'--capital-base',
type=float,
show_default=True,
help='The starting capital for the simulation.',
)
@click.option(
'-b',
'--bundle',
default='poloniex',
metavar='BUNDLE-NAME',
show_default=True,
help='The data bundle to use for the simulation.',
)
@click.option(
'--bundle-timestamp',
type=Timestamp(),
default=pd.Timestamp.utcnow(),
show_default=False,
help='The date to lookup data on or before.\n'
'[default: <current-time>]'
)
@click.option(
'-s',
'--start',
type=Date(tz='utc', as_timestamp=True),
help='The start date of the simulation.',
)
@click.option(
'-e',
'--end',
type=Date(tz='utc', as_timestamp=True),
help='The end date of the simulation.',
)
@click.option(
'-o',
'--output',
default='-',
metavar='FILENAME',
show_default=True,
help="The location to write the perf data. If this is '-' the perf"
" will be written to stdout.",
)
@click.option(
'--print-algo/--no-print-algo',
is_flag=True,
default=False,
help='Print the algorithm to stdout.',
)
@ipython_only(click.option(
'--local-namespace/--no-local-namespace',
is_flag=True,
default=None,
help='Should the algorithm methods be resolved in the local namespace.'
))
@click.option(
'-x',
'--exchange-name',
help='The name of the targeted exchange.',
)
@click.option(
'-n',
'--algo-namespace',
help='A label assigned to the algorithm for data storage purposes.'
)
@click.option(
'-c',
'--base-currency',
help='The base currency used to calculate statistics '
'(e.g. usd, btc, eth).',
)
@click.pass_context
def run(ctx,
algofile,
algotext,
define,
data_frequency,
capital_base,
bundle,
bundle_timestamp,
start,
end,
output,
print_algo,
local_namespace,
exchange_name,
algo_namespace,
base_currency):
"""Run a backtest for the given algorithm on the server.
"""
if (algotext is not None) == (algofile is not None):
ctx.fail(
"must specify exactly one of '-f' / '--algofile' or"
" '-t' / '--algotext'",
)
# check that the start and end dates are passed correctly
if start is None and end is None:
# check both at the same time to avoid the case where a user
# does not pass either of these and then passes the first only
# to be told they need to pass the second argument also
ctx.fail(
"must specify dates with '-s' / '--start' and '-e' / '--end'"
" in backtest mode",
)
if start is None:
ctx.fail("must specify a start date with '-s' / '--start'"
" in backtest mode")
if end is None:
ctx.fail("must specify an end date with '-e' / '--end'"
" in backtest mode")
if exchange_name is None:
ctx.fail("must specify an exchange name '-x'")
if base_currency is None:
ctx.fail("must specify a base currency with '-c' in backtest mode")
if capital_base is None:
ctx.fail("must specify a capital base with '--capital-base'")
click.echo('Running in backtesting mode.', sys.stdout)
perf = run_server(
initialize=None,
handle_data=None,
before_trading_start=None,
analyze=None,
algofile=algofile,
algotext=algotext,
defines=define,
data_frequency=data_frequency,
capital_base=capital_base,
data=None,
bundle=bundle,
bundle_timestamp=bundle_timestamp,
start=start,
end=end,
output=output,
print_algo=print_algo,
local_namespace=local_namespace,
environ=os.environ,
live=False,
exchange=exchange_name,
algo_namespace=algo_namespace,
base_currency=base_currency,
analyze_live=None,
live_graph=False,
simulate_orders=True,
auth_aliases=None,
stats_output=None,
)
if output == '-':
click.echo(str(perf), sys.stdout)
elif output != os.devnull: # make the catalyst magic not write any data
perf.to_pickle(output)
return perf
@main.command(name='serve-live')
@click.option(
'-f',
'--algofile',
default=None,
type=click.File('r'),
help='The file that contains the algorithm to run.',
)
@click.option(
'--capital-base',
type=float,
show_default=True,
help='The amount of capital (in base_currency) allocated to trading.',
)
@click.option(
'-t',
'--algotext',
help='The algorithm script to run.',
)
@click.option(
'-D',
'--define',
multiple=True,
help="Define a name to be bound in the namespace before executing"
" the algotext. For example '-Dname=value'. The value may be"
" any python expression. These are evaluated in order so they"
" may refer to previously defined names.",
)
@click.option(
'-o',
'--output',
default='-',
metavar='FILENAME',
show_default=True,
help="The location to write the perf data. If this is '-' the perf will"
" be written to stdout.",
)
@click.option(
'--print-algo/--no-print-algo',
is_flag=True,
default=False,
help='Print the algorithm to stdout.',
)
@ipython_only(click.option(
'--local-namespace/--no-local-namespace',
is_flag=True,
default=None,
help='Should the algorithm methods be resolved in the local namespace.'
))
@click.option(
'-x',
'--exchange-name',
help='The name of the targeted exchange.',
)
@click.option(
'-n',
'--algo-namespace',
help='A label assigned to the algorithm for data storage purposes.'
)
@click.option(
'-c',
'--base-currency',
help='The base currency used to calculate statistics '
'(e.g. usd, btc, eth).',
)
@click.option(
'-e',
'--end',
type=Date(tz='utc', as_timestamp=True),
help='An optional end date at which to stop the execution.',
)
@click.option(
'--live-graph/--no-live-graph',
is_flag=True,
default=False,
help='Display live graph.',
)
@click.option(
'--simulate-orders/--no-simulate-orders',
is_flag=True,
default=True,
help='Simulating orders enable the paper trading mode. No orders will be '
'sent to the exchange unless set to false.',
)
@click.option(
'--auth-aliases',
default=None,
help='Authentication file aliases for the specified exchanges. By default,'
'each exchange uses the "auth.json" file in the exchange folder. '
'Specifying an "auth2" alias would use "auth2.json". It should be '
'specified like this: "[exchange_name],[alias],..." For example, '
'"binance,auth2" or "binance,auth2,bittrex,auth2".',
)
@click.pass_context
def serve_live(ctx,
algofile,
capital_base,
algotext,
define,
output,
print_algo,
local_namespace,
exchange_name,
algo_namespace,
base_currency,
end,
live_graph,
auth_aliases,
simulate_orders):
"""Trade live with the given algorithm on the server.
"""
if (algotext is not None) == (algofile is not None):
ctx.fail(
"must specify exactly one of '-f' / '--algofile' or"
" '-t' / '--algotext'",
)
if exchange_name is None:
ctx.fail("must specify an exchange name '-x'")
if algo_namespace is None:
ctx.fail("must specify an algorithm name '-n' in live execution mode")
if base_currency is None:
ctx.fail("must specify a base currency '-c' in live execution mode")
if capital_base is None:
ctx.fail("must specify a capital base with '--capital-base'")
if simulate_orders:
click.echo('Running in paper trading mode.', sys.stdout)
else:
click.echo('Running in live trading mode.', sys.stdout)
perf = run_server(
initialize=None,
handle_data=None,
before_trading_start=None,
analyze=None,
algofile=algofile,
algotext=algotext,
defines=define,
data_frequency=None,
capital_base=capital_base,
data=None,
bundle=None,
bundle_timestamp=None,
start=None,
end=end,
output=output,
print_algo=print_algo,
local_namespace=local_namespace,
environ=os.environ,
live=True,
exchange=exchange_name,
algo_namespace=algo_namespace,
base_currency=base_currency,
live_graph=live_graph,
analyze_live=None,
simulate_orders=simulate_orders,
auth_aliases=auth_aliases,
stats_output=None,
)
if output == '-':
click.echo(str(perf), sys.stdout)
elif output != os.devnull: # make the catalyst magic not write any data
perf.to_pickle(output)
return perf
@main.command(name='ingest-exchange') @main.command(name='ingest-exchange')
@click.option( @click.option(
'-x', '-x',
@@ -767,18 +1132,12 @@ def bundles():
@main.group() @main.group()
@click.pass_context @click.pass_context
def marketplace(ctx): def marketplace(ctx):
"""Access the Enigma Data Marketplace to:\n
- Register and Publish new datasets (seller-side)\n
- Subscribe and Ingest premium datasets (buyer-side)\n
"""
pass pass
@marketplace.command() @marketplace.command()
@click.pass_context @click.pass_context
def ls(ctx): def ls(ctx):
"""List all available datasets.
"""
click.echo('Listing of available data sources on the marketplace:', click.echo('Listing of available data sources on the marketplace:',
sys.stdout) sys.stdout)
marketplace = Marketplace() marketplace = Marketplace()
@@ -793,8 +1152,10 @@ def ls(ctx):
) )
@click.pass_context @click.pass_context
def subscribe(ctx, dataset): def subscribe(ctx, dataset):
"""Subscribe to an exisiting dataset. if dataset is None:
""" ctx.fail("must specify a dataset to subscribe to with '--dataset'\n"
"List available dataset on the marketplace with "
"'catalyst marketplace ls'")
marketplace = Marketplace() marketplace = Marketplace()
marketplace.subscribe(dataset) marketplace.subscribe(dataset)
@@ -829,8 +1190,11 @@ def subscribe(ctx, dataset):
) )
@click.pass_context @click.pass_context
def ingest(ctx, dataset, data_frequency, start, end): def ingest(ctx, dataset, data_frequency, start, end):
"""Ingest a dataset (requires subscription). if dataset is None:
""" ctx.fail("must specify a dataset to clean with '--dataset'\n"
"List available dataset on the marketplace with "
"'catalyst marketplace ls'")
click.echo('Ingesting data: {}'.format(dataset), sys.stdout)
marketplace = Marketplace() marketplace = Marketplace()
marketplace.ingest(dataset, data_frequency, start, end) marketplace.ingest(dataset, data_frequency, start, end)
@@ -843,17 +1207,19 @@ def ingest(ctx, dataset, data_frequency, start, end):
) )
@click.pass_context @click.pass_context
def clean(ctx, dataset): def clean(ctx, dataset):
"""Clean/Remove local data for a given dataset. if dataset is None:
""" ctx.fail("must specify a dataset to ingest with '--dataset'\n"
"List available dataset on the marketplace with "
"'catalyst marketplace ls'")
click.echo('Cleaning data source: {}'.format(dataset), sys.stdout)
marketplace = Marketplace() marketplace = Marketplace()
marketplace.clean(dataset) marketplace.clean(dataset)
click.echo('Done', sys.stdout)
@marketplace.command() @marketplace.command()
@click.pass_context @click.pass_context
def register(ctx): def register(ctx):
"""Register a new dataset.
"""
marketplace = Marketplace() marketplace = Marketplace()
marketplace.register() marketplace.register()
@@ -877,8 +1243,6 @@ def register(ctx):
) )
@click.pass_context @click.pass_context
def publish(ctx, dataset, datadir, watch): def publish(ctx, dataset, datadir, watch):
"""Publish data for a registered dataset.
"""
marketplace = Marketplace() marketplace = Marketplace()
if dataset is None: if dataset is None:
ctx.fail("must specify a dataset to publish data for " ctx.fail("must specify a dataset to publish data for "
+10 -59
View File
@@ -433,7 +433,7 @@ cdef class TradingPair(Asset):
'taker', 'taker',
'trading_state', 'trading_state',
'data_source', 'data_source',
'decimals', 'decimals'
}) })
def __init__(self, def __init__(self,
object symbol, object symbol,
@@ -455,7 +455,7 @@ cdef class TradingPair(Asset):
float taker=0.0025, float taker=0.0025,
float lot=0, float lot=0,
int decimals = 8, int decimals = 8,
int trading_state=1, int trading_state=0,
object data_source='catalyst'): object data_source='catalyst'):
""" """
Replicates the Asset constructor with some built-in conventions Replicates the Asset constructor with some built-in conventions
@@ -600,51 +600,14 @@ cdef class TradingPair(Asset):
cpdef to_dict(self): cpdef to_dict(self):
""" """
Convert to a python dict. Convert to a python dict.
Repeat constructor params:
object symbol,
object exchange,
object start_date=None,
object asset_name=None,
int sid=0,
float leverage=1.0,
object end_daily=None,
object end_minute=None,
object end_date=None,
object exchange_symbol=None,
object first_traded=None,
object auto_close_date=None,
object exchange_full=None,
float min_trade_size=0.0001,
float max_trade_size=1000000,
float maker=0.0015,
float taker=0.0025,
float lot=0,
int decimals = 8,
int trading_state=1,
object data_source='catalyst',
""" """
trading_pair_dict = dict( #TODO: missing fields
symbol=self.symbol, super_dict = super(TradingPair, self).to_dict()
exchange=self.exchange, super_dict['end_daily'] = self.end_daily
start_date=self.start_date, super_dict['end_minute'] = self.end_minute
asset_name=self.asset_name, super_dict['leverage'] = self.leverage
leverage=self.leverage, super_dict['min_trade_size'] = self.min_trade_size
end_daily=self.end_daily, return super_dict
end_minute=self.end_minute,
end_date=self.end_date,
exchange_symbol=self.exchange_symbol,
exchange_full=self.exchange_full,
min_trade_size=self.min_trade_size,
max_trade_size=self.max_trade_size,
maker=self.maker,
taker=self.taker,
lot=self.lot,
decimals=self.decimals,
trading_state=self.trading_state,
data_source=self.data_source,
)
return trading_pair_dict
def is_exchange_open(self, dt_minute): def is_exchange_open(self, dt_minute):
""" """
@@ -660,16 +623,6 @@ cdef class TradingPair(Asset):
#TODO: make more dymanic to catch holds #TODO: make more dymanic to catch holds
return True return True
def set_end_date(self, dt, data_frequency):
if data_frequency == 'minute':
self.end_minute = dt
else:
self.end_daily = dt
def set_start_date(self, dt):
self.start_date = dt
cpdef __reduce__(self): cpdef __reduce__(self):
""" """
Function used by pickle to determine how to serialize/deserialize this Function used by pickle to determine how to serialize/deserialize this
@@ -693,9 +646,7 @@ cdef class TradingPair(Asset):
self.lot, self.lot,
self.decimals, self.decimals,
self.taker, self.taker,
self.maker, self.maker))
self.trading_state,
self.data_source))
def make_asset_array(int size, Asset asset): def make_asset_array(int size, Asset asset):
cdef np.ndarray out = np.empty([size], dtype=object) cdef np.ndarray out = np.empty([size], dtype=object)
+1 -4
View File
@@ -11,10 +11,7 @@ LOG_LEVEL = int(os.environ.get('CATALYST_LOG_LEVEL', logbook.INFO))
SYMBOLS_URL = 'https://s3.amazonaws.com/enigmaco/catalyst-exchanges/' \ SYMBOLS_URL = 'https://s3.amazonaws.com/enigmaco/catalyst-exchanges/' \
'{exchange}/symbols.json' '{exchange}/symbols.json'
EXCHANGE_CONFIG_URL = 'https://s3.amazonaws.com/enigmaco/ohlcv/' \
'{exchange}/config.json'
BUNDLE_URL = 'https://s3.amazonaws.com/enigmaco/ohlcv/' \
'{exchange}/{data_frequency}/{name}.tar.gz'
DATE_TIME_FORMAT = '%Y-%m-%d %H:%M' DATE_TIME_FORMAT = '%Y-%m-%d %H:%M'
DATE_FORMAT = '%Y-%m-%d' DATE_FORMAT = '%Y-%m-%d'
+1
View File
@@ -7,6 +7,7 @@ from catalyst.api import (
order_target_percent, order_target_percent,
symbol, symbol,
record, record,
get_open_orders,
) )
from catalyst.exchange.utils.stats_utils import get_pretty_stats from catalyst.exchange.utils.stats_utils import get_pretty_stats
from catalyst.utils.run_algo import run_algorithm from catalyst.utils.run_algo import run_algorithm
+7 -7
View File
@@ -33,12 +33,12 @@ def initialize(context):
# parameters or values you're going to use. # parameters or values you're going to use.
# In our example, we're looking at Neo in Ether. # In our example, we're looking at Neo in Ether.
context.market = symbol('eth_btc') context.market = symbol('bnb_eth')
context.base_price = None context.base_price = None
context.current_day = None context.current_day = None
context.RSI_OVERSOLD = 55 context.RSI_OVERSOLD = 60
context.RSI_OVERBOUGHT = 60 context.RSI_OVERBOUGHT = 70
context.CANDLE_SIZE = '15T' context.CANDLE_SIZE = '15T'
context.start_time = time.time() context.start_time = time.time()
@@ -248,14 +248,14 @@ if __name__ == '__main__':
if live: if live:
run_algorithm( run_algorithm(
capital_base=0.03, capital_base=0.1,
initialize=initialize, initialize=initialize,
handle_data=handle_data, handle_data=handle_data,
analyze=analyze, analyze=analyze,
exchange_name='poloniex', exchange_name='binance',
live=True, live=True,
algo_namespace=NAMESPACE, algo_namespace=NAMESPACE,
base_currency='btc', base_currency='eth',
live_graph=False, live_graph=False,
simulate_orders=False, simulate_orders=False,
stats_output=None, stats_output=None,
@@ -274,7 +274,7 @@ if __name__ == '__main__':
# -x bitfinex -s 2017-10-1 -e 2017-11-10 -c usdt -n mean-reversion \ # -x bitfinex -s 2017-10-1 -e 2017-11-10 -c usdt -n mean-reversion \
# --data-frequency minute --capital-base 10000 # --data-frequency minute --capital-base 10000
run_algorithm( run_algorithm(
capital_base=0.1, capital_base=0.035,
data_frequency='minute', data_frequency='minute',
initialize=initialize, initialize=initialize,
handle_data=handle_data, handle_data=handle_data,
+1 -1
View File
@@ -66,7 +66,7 @@ def handle_data(context, data):
# Define portfolio optimization parameters # Define portfolio optimization parameters
n_portfolios = 50000 n_portfolios = 50000
results_array = np.zeros((3 + context.nassets, n_portfolios)) results_array = np.zeros((3 + context.nassets, n_portfolios))
for p in range(n_portfolios): for p in xrange(n_portfolios):
weights = np.random.random(context.nassets) weights = np.random.random(context.nassets)
weights /= np.sum(weights) weights /= np.sum(weights)
w = np.asmatrix(weights) w = np.asmatrix(weights)
+273 -185
View File
@@ -1,33 +1,34 @@
import json
import os
import re import re
from collections import defaultdict from collections import defaultdict
import ccxt import ccxt
import pandas as pd import pandas as pd
import six import six
from catalyst.assets._assets import TradingPair from ccxt import InvalidOrder, NetworkError, \
from redo import retry ExchangeError
from logbook import Logger
from six import string_types
from catalyst.algorithm import MarketOrder from catalyst.algorithm import MarketOrder
from catalyst.assets._assets import TradingPair
from catalyst.constants import LOG_LEVEL from catalyst.constants import LOG_LEVEL
from catalyst.exchange.exchange import Exchange from catalyst.exchange.exchange import Exchange
from catalyst.exchange.exchange_bundle import ExchangeBundle from catalyst.exchange.exchange_bundle import ExchangeBundle
from catalyst.exchange.exchange_errors import InvalidHistoryFrequencyError, \ from catalyst.exchange.exchange_errors import InvalidHistoryFrequencyError, \
ExchangeSymbolsNotFound, ExchangeRequestError, InvalidOrderStyle, \ ExchangeSymbolsNotFound, ExchangeRequestError, InvalidOrderStyle, \
UnsupportedHistoryFrequencyError, \
ExchangeNotFoundError, CreateOrderError, InvalidHistoryTimeframeError, \ ExchangeNotFoundError, CreateOrderError, InvalidHistoryTimeframeError, \
MarketsNotFoundError, InvalidMarketError UnsupportedHistoryFrequencyError
from catalyst.exchange.exchange_execution import ExchangeLimitOrder from catalyst.exchange.exchange_execution import ExchangeLimitOrder
from catalyst.exchange.utils.ccxt_utils import get_exchange_config from catalyst.exchange.utils.exchange_utils import mixin_market_params, \
get_exchange_folder, get_catalyst_symbol, \
get_exchange_auth
from catalyst.exchange.utils.datetime_utils import from_ms_timestamp, \ from catalyst.exchange.utils.datetime_utils import from_ms_timestamp, \
get_epoch, \ get_epoch, \
get_periods_range get_periods_range
from catalyst.exchange.utils.exchange_utils import get_catalyst_symbol
from catalyst.finance.order import Order, ORDER_STATUS from catalyst.finance.order import Order, ORDER_STATUS
from catalyst.finance.transaction import Transaction from catalyst.finance.transaction import Transaction
from ccxt import InvalidOrder, NetworkError, \
ExchangeError
from logbook import Logger
from six import string_types
log = Logger('CCXT', level=LOG_LEVEL) log = Logger('CCXT', level=LOG_LEVEL)
@@ -43,7 +44,7 @@ SUPPORTED_EXCHANGES = dict(
class CCXT(Exchange): class CCXT(Exchange):
def __init__(self, exchange_name, key, def __init__(self, exchange_name, key,
secret, password, base_currency, config=None): secret, password, base_currency):
log.debug( log.debug(
'finding {} in CCXT exchanges:\n{}'.format( 'finding {} in CCXT exchanges:\n{}'.format(
exchange_name, ccxt.exchanges exchange_name, ccxt.exchanges
@@ -63,8 +64,6 @@ class CCXT(Exchange):
'password': password, 'password': password,
}) })
self.api.enableRateLimit = True self.api.enableRateLimit = True
self.has = self.api.has
self.fees = self.api.fees
except Exception: except Exception:
raise ExchangeNotFoundError(exchange_name=exchange_name) raise ExchangeNotFoundError(exchange_name=exchange_name)
@@ -72,7 +71,6 @@ class CCXT(Exchange):
self._symbol_maps = [None, None] self._symbol_maps = [None, None]
self.name = exchange_name self.name = exchange_name
self.assets = []
self.base_currency = base_currency self.base_currency = base_currency
self.transactions = defaultdict(list) self.transactions = defaultdict(list)
@@ -84,123 +82,97 @@ class CCXT(Exchange):
self._common_symbols = dict() self._common_symbols = dict()
self.bundle = ExchangeBundle(self.name) self.bundle = ExchangeBundle(self.name)
self.markets = None
self._is_init = False self._is_init = False
self._config = config
def init(self): def init(self):
if self._is_init: if self._is_init:
return return
if self._config is None: exchange_folder = get_exchange_folder(self.name)
self._config = get_exchange_config(self.name) filename = os.path.join(exchange_folder, 'cctx_markets.json')
log.debug(
'got exchange config {}:\n{}'.format( if os.path.exists(filename):
self.name, self._config timestamp = os.path.getmtime(filename)
dt = pd.to_datetime(timestamp, unit='s', utc=True)
if dt >= pd.Timestamp.utcnow().floor('1D'):
with open(filename) as f:
self.markets = json.load(f)
log.debug('loaded markets for {}'.format(self.name))
if self.markets is None:
try:
markets_symbols = self.api.load_markets()
log.debug(
'fetching {} markets:\n{}'.format(
self.name, markets_symbols
)
) )
)
self.markets = self.api.fetch_markets()
with open(filename, 'w+') as f:
json.dump(self.markets, f, indent=4)
except (ExchangeError, NetworkError) as e:
log.warn(
'unable to fetch markets {}: {}'.format(
self.name, e
)
)
raise ExchangeRequestError(error=e)
self.load_assets() self.load_assets()
self._is_init = True self._is_init = True
def load_assets(self): @staticmethod
if self._config is None: def find_exchanges(features=None, is_authenticated=False):
raise ValueError('Exchange config not available.') ccxt_features = []
if features is not None:
for feature in features:
if not feature.endswith('Bundle'):
ccxt_features.append(feature)
self.assets = [] exchange_names = []
for asset_dict in self._config['assets']: for exchange_name in ccxt.exchanges:
asset = TradingPair(**asset_dict) if is_authenticated:
self.assets.append(asset) exchange_auth = get_exchange_auth(exchange_name)
def _fetch_markets(self): has_auth = (exchange_auth['key'] != ''
markets_symbols = self.api.load_markets() and exchange_auth['secret'] != '')
log.debug(
'fetching {} markets:\n{}'.format(
self.name, markets_symbols
)
)
try:
markets = self.api.fetch_markets()
except NetworkError as e: if not has_auth:
raise ExchangeRequestError(error=e) continue
if not markets: log.debug('loading exchange: {}'.format(exchange_name))
raise MarketsNotFoundError( exchange = getattr(ccxt, exchange_name)()
exchange=self.name,
)
for market in markets: if ccxt_features is None:
if 'id' not in market: has_feature = True
raise InvalidMarketError(
exchange=self.name,
market=market,
)
return markets
def create_exchange_config(self): else:
config = dict( try:
name=self.name, has_feature = all(
features=[feature for feature in self.has if self.has[feature]] [exchange.has[feature] for feature in ccxt_features]
) )
markets = retry(
action=self._fetch_markets,
attempts=5,
sleeptime=5,
retry_exceptions=(ExchangeRequestError,),
cleanup=lambda: log.warn(
'fetching markets again for {}'.format(self.name)
),
)
config['assets'] = [] except Exception:
for market in markets: has_feature = False
asset = self.create_trading_pair(market=market)
config['assets'].append(asset)
return config if has_feature:
try:
log.info('initializing {}'.format(exchange_name))
exchange_names.append(exchange_name)
def create_trading_pair(self, market, start_dt=None, end_dt=None, except Exception as e:
leverage=1, end_daily=None, end_minute=None): log.warn(
""" 'unable to initialize exchange {}: {}'.format(
Creating a TradingPair from market and asset data. exchange_name, e
)
)
Parameters return exchange_names
----------
market: dict[str, Object]
start_dt
end_dt
leverage
end_daily
end_minute
Returns
-------
"""
params = dict(
exchange=self.name,
data_source='catalyst',
exchange_symbol=market['id'],
symbol=get_catalyst_symbol(market),
start_date=start_dt,
end_date=end_dt,
leverage=leverage,
asset_name=market['symbol'],
end_daily=end_daily,
end_minute=end_minute,
)
self.apply_conditional_market_params(params, market)
return TradingPair(**params)
def load_assets(self):
if self._config is None or 'error' in self._config:
raise ValueError('Exchange config not available.')
self.assets = []
for asset_dict in self._config['assets']:
asset = TradingPair(**asset_dict)
self.assets.append(asset)
def account(self): def account(self):
return None return None
@@ -232,11 +204,32 @@ class CCXT(Exchange):
return frequencies return frequencies
def get_market(self, symbol):
"""
The CCXT market.
Parameters
----------
symbol:
The CCXT symbol.
Returns
-------
dict[str, Object]
"""
s = self.get_symbol(symbol)
market = next(
(market for market in self.markets if market['symbol'] == s),
None,
)
return market
def substitute_currency_code(self, currency, source='catalyst'): def substitute_currency_code(self, currency, source='catalyst'):
if source == 'catalyst': if source == 'catalyst':
currency = currency.upper() currency = currency.upper()
key = self.api.common_currency_code(currency).lower() key = self.api.common_currency_code(currency)
self._common_symbols[key] = currency.lower() self._common_symbols[key] = currency.lower()
return key return key
@@ -264,7 +257,13 @@ class CCXT(Exchange):
if source == 'ccxt': if source == 'ccxt':
if isinstance(asset_or_symbol, string_types): if isinstance(asset_or_symbol, string_types):
parts = asset_or_symbol.split('/') parts = asset_or_symbol.split('/')
return '{}_{}'.format(parts[0].lower(), parts[1].lower()) base_currency = self.substitute_currency_code(
parts[0], source
)
quote_currency = self.substitute_currency_code(
parts[1], source
)
return '{}_{}'.format(base_currency, quote_currency)
else: else:
return asset_or_symbol.symbol return asset_or_symbol.symbol
@@ -275,7 +274,13 @@ class CCXT(Exchange):
) else asset_or_symbol.symbol ) else asset_or_symbol.symbol
parts = symbol.split('_') parts = symbol.split('_')
return '{}/{}'.format(parts[0].upper(), parts[1].upper()) base_currency = self.substitute_currency_code(
parts[0], source
)
quote_currency = self.substitute_currency_code(
parts[1], source
)
return '{}/{}'.format(base_currency, quote_currency)
@staticmethod @staticmethod
def map_frequency(value, source='ccxt', raise_error=True): def map_frequency(value, source='ccxt', raise_error=True):
@@ -401,7 +406,7 @@ class CCXT(Exchange):
) )
def get_candles(self, freq, assets, bar_count=1, start_dt=None, def get_candles(self, freq, assets, bar_count=1, start_dt=None,
end_dt=None, floor_dates=True): end_dt=None):
is_single = (isinstance(assets, TradingPair)) is_single = (isinstance(assets, TradingPair))
if is_single: if is_single:
assets = [assets] assets = [assets]
@@ -448,20 +453,16 @@ class CCXT(Exchange):
candles[asset] = [] candles[asset] = []
for ohlcv in ohlcvs: for ohlcv in ohlcvs:
dt = pd.to_datetime(ohlcv[0], unit='ms', utc=True) candles[asset].append(dict(
if floor_dates: last_traded=pd.to_datetime(
dt = dt.floor('1T') ohlcv[0], unit='ms', utc=True
),
candles[asset].append( open=ohlcv[1],
dict( high=ohlcv[2],
last_traded=dt, low=ohlcv[3],
open=ohlcv[1], close=ohlcv[4],
high=ohlcv[2], volume=ohlcv[5]
low=ohlcv[3], ))
close=ohlcv[4],
volume=ohlcv[5],
)
)
candles[asset] = sorted( candles[asset] = sorted(
candles[asset], key=lambda c: c['last_traded'] candles[asset], key=lambda c: c['last_traded']
) )
@@ -479,53 +480,144 @@ class CCXT(Exchange):
except ExchangeSymbolsNotFound: except ExchangeSymbolsNotFound:
return None return None
def apply_conditional_market_params(self, params, market): def get_asset_defs(self, market):
""" """
Applies a CCXT market dict to parameters of TradingPair init. The local and Catalyst definitions of the specified market.
Parameters Parameters
---------- ----------
params: dict[Object] market: dict[str, Object]
market: dict[Object] The CCXT market dicts.
Returns
-------
dict[str, Object]
The asset definition.
"""
asset_defs = []
for is_local in (False, True):
asset_def = self.get_asset_def(market, is_local)
asset_defs.append((asset_def, is_local))
return asset_defs
def get_asset_def(self, market, is_local=False):
"""
The asset definition (in symbols.json files) corresponding
to the the specified market.
Parameters
----------
market: dict[str, Object]
The CCXT market dict.
is_local
Whether to search in local or Catalyst asset definitions.
Returns
-------
dict[str, Object]
The asset definition.
"""
exchange_symbol = market['id']
symbol_map = self._fetch_symbol_map(is_local)
if symbol_map is not None:
assets_lower = {k.lower(): v for k, v in symbol_map.items()}
key = exchange_symbol.lower()
asset = assets_lower[key] if key in assets_lower else None
if asset is not None:
return asset
else:
return None
else:
return None
def create_trading_pair(self, market, asset_def=None, is_local=False):
"""
Creating a TradingPair from market and asset data.
Parameters
----------
market: dict[str, Object]
asset_def: dict[str, Object]
is_local: bool
Returns Returns
------- -------
""" """
# TODO: make this more externalized / configurable data_source = 'local' if is_local else 'catalyst'
# Consider representing in some type of JSON structure params = dict(
if 'active' in market: exchange=self.name,
params['trading_state'] = 1 if market['active'] else 0 data_source=data_source,
exchange_symbol=market['id'],
)
mixin_market_params(self.name, params, market)
if asset_def is not None:
params['symbol'] = asset_def['symbol']
params['start_date'] = asset_def['start_date'] \
if 'start_date' in asset_def else None
params['end_date'] = asset_def['end_date'] \
if 'end_date' in asset_def else None
params['leverage'] = asset_def['leverage'] \
if 'leverage' in asset_def else 1.0
params['asset_name'] = asset_def['asset_name'] \
if 'asset_name' in asset_def else None
params['end_daily'] = asset_def['end_daily'] \
if 'end_daily' in asset_def \
and asset_def['end_daily'] != 'N/A' else None
params['end_minute'] = asset_def['end_minute'] \
if 'end_minute' in asset_def \
and asset_def['end_minute'] != 'N/A' else None
else: else:
params['trading_state'] = 1 params['symbol'] = get_catalyst_symbol(market)
# TODO: add as an optional column
params['leverage'] = 1.0
if 'lot' in market: return TradingPair(**params)
params['min_trade_size'] = market['lot']
params['lot'] = market['lot']
if self.name == 'bitfinex': def load_assets(self):
params['maker'] = 0.001 log.debug('loading assets for {}'.format(self.name))
params['taker'] = 0.002 self.assets = []
elif 'maker' in market and 'taker' in market \ for market in self.markets:
and market['maker'] is not None \ if 'id' not in market:
and market['taker'] is not None: log.warn('invalid market: {}'.format(market))
params['maker'] = market['maker'] continue
params['taker'] = market['taker']
else: asset_defs = self.get_asset_defs(market)
# TODO: default commission, make configurable
params['maker'] = 0.0015
params['taker'] = 0.0025
info = market['info'] if 'info' in market else None asset = None
if info: for asset_def in asset_defs:
if 'minimum_order_size' in info: if asset_def[0] is not None or not asset_defs[1]:
params['min_trade_size'] = float(info['minimum_order_size']) try:
asset = self.create_trading_pair(
market=market,
asset_def=asset_def[0],
is_local=asset_def[1]
)
self.assets.append(asset)
if 'lot' not in params: except TypeError as e:
params['lot'] = params['min_trade_size'] log.warn('unable to add asset: {}'.format(e))
if asset is None:
asset = self.create_trading_pair(market=market)
self.assets.append(asset)
def get_balances(self): def get_balances(self):
try: try:
@@ -663,14 +755,18 @@ class CCXT(Exchange):
side = 'buy' if amount > 0 else 'sell' side = 'buy' if amount > 0 else 'sell'
if hasattr(self.api, 'amount_to_lots'): if hasattr(self.api, 'amount_to_lots'):
adj_amount = self.api.amount_to_lots( # TODO: is this right?
symbol=symbol, if self.api.markets is None:
amount=abs(amount), self.api.load_markets()
)
if adj_amount != abs(amount): # https://github.com/ccxt/ccxt/issues/1483
log.info( adj_amount = round(abs(amount), asset.decimals)
'adjusted order amount {} to {} based on lot size'.format( market = self.api.markets[symbol]
abs(amount), adj_amount, if 'lots' in market and market['lots'] > amount:
raise CreateOrderError(
exchange=self.name,
e='order amount lower than the smallest lot: {}'.format(
amount
) )
) )
@@ -898,7 +994,7 @@ class CCXT(Exchange):
symbol = self.get_symbol(asset_or_symbol) \ symbol = self.get_symbol(asset_or_symbol) \
if asset_or_symbol is not None else None if asset_or_symbol is not None else None
self.api.cancel_order(id=order_id, self.api.cancel_order(id=order_id,
symbol=symbol, params=params) symbol=symbol, params= params)
except (ExchangeError, NetworkError) as e: except (ExchangeError, NetworkError) as e:
log.warn( log.warn(
@@ -1016,27 +1112,19 @@ class CCXT(Exchange):
return result return result
def get_trades(self, asset, my_trades=True, start_dt=None, limit=100): def get_trades(self, asset, my_trades=True, start_dt=None, limit=100):
if not my_trades:
raise NotImplemented(
'get_trades only supports "my trades"'
)
# TODO: is it possible to sort this? Limit is useless otherwise. # TODO: is it possible to sort this? Limit is useless otherwise.
ccxt_symbol = self.get_symbol(asset) ccxt_symbol = self.get_symbol(asset)
if start_dt:
delta = start_dt - get_epoch()
since = int(delta.total_seconds()) * 1000
else:
since = None
try: try:
if my_trades: trades = self.api.fetch_my_trades(
trades = self.api.fetch_my_trades( symbol=ccxt_symbol,
symbol=ccxt_symbol, since=start_dt,
since=since, limit=limit,
limit=limit, )
)
else:
trades = self.api.fetch_trades(
symbol=ccxt_symbol,
since=since,
limit=limit,
)
except (ExchangeError, NetworkError) as e: except (ExchangeError, NetworkError) as e:
log.warn( log.warn(
'unable to fetch trades {} / {}: {}'.format( 'unable to fetch trades {} / {}: {}'.format(
+65 -54
View File
@@ -1,26 +1,25 @@
import abc import abc
import pytz
from abc import ABCMeta, abstractmethod, abstractproperty from abc import ABCMeta, abstractmethod, abstractproperty
from datetime import timedelta from datetime import timedelta
from time import sleep from time import sleep
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from logbook import Logger
from catalyst.constants import LOG_LEVEL from catalyst.constants import LOG_LEVEL
from catalyst.data.data_portal import BASE_FIELDS from catalyst.data.data_portal import BASE_FIELDS
from catalyst.exchange.exchange_bundle import ExchangeBundle from catalyst.exchange.exchange_bundle import ExchangeBundle
from catalyst.exchange.exchange_errors import MismatchingBaseCurrencies, \ from catalyst.exchange.exchange_errors import MismatchingBaseCurrencies, \
SymbolNotFoundOnExchange, \ SymbolNotFoundOnExchange, \
PricingDataNotLoadedError, \ PricingDataNotLoadedError, \
NoDataAvailableOnExchange, NoValueForField, \ NoDataAvailableOnExchange, NoValueForField, LastCandleTooEarlyError, \
NoCandlesReceivedFromExchange, \
TickerNotFoundError, NotEnoughCashError TickerNotFoundError, NotEnoughCashError
from catalyst.exchange.utils.datetime_utils import get_delta, \ from catalyst.exchange.utils.datetime_utils import get_delta, \
get_periods_range, \ get_periods_range, \
get_periods, get_start_dt, get_frequency get_periods, get_start_dt, get_frequency
from catalyst.exchange.utils.exchange_utils import \ from catalyst.exchange.utils.exchange_utils import get_exchange_symbols, \
resample_history_df, has_bundle resample_history_df, has_bundle
from logbook import Logger
log = Logger('Exchange', level=LOG_LEVEL) log = Logger('Exchange', level=LOG_LEVEL)
@@ -257,10 +256,9 @@ class Exchange:
elif data_frequency is not None: elif data_frequency is not None:
applies = ( applies = (
( (
data_frequency == 'minute' and a.end_minute is not None data_frequency == 'minute' and a.end_minute is not None)
) or ( or (
data_frequency == 'daily' and a.end_daily is not None data_frequency == 'daily' and a.end_daily is not None)
)
) )
else: else:
@@ -293,6 +291,16 @@ class Exchange:
log.debug('found asset: {}'.format(asset)) log.debug('found asset: {}'.format(asset))
return asset return asset
def fetch_symbol_map(self, is_local=False):
index = 1 if is_local else 0
if self._symbol_maps[index] is not None:
return self._symbol_maps[index]
else:
symbol_map = get_exchange_symbols(self.name, is_local)
self._symbol_maps[index] = symbol_map
return symbol_map
@abstractmethod @abstractmethod
def init(self): def init(self):
""" """
@@ -304,13 +312,24 @@ class Exchange:
""" """
@abstractmethod @abstractmethod
def create_exchange_config(self): def load_assets(self, is_local=False):
""" """
Fetch the exchange market data and generate a config object Populate the 'assets' attribute with a dictionary of Assets.
Returns The key of the resulting dictionary is the exchange specific
------- currency pair symbol. The universal symbol is contained in the
'symbol' attribute of each asset.
Notes
-----
The sid of each asset is calculated based on a numeric hash of the
universal symbol. This simple approach avoids maintaining a mapping
of sids.
This method can be omerridden if an exchange offers equivalent data
via its api.
""" """
pass
def get_spot_value(self, assets, field, dt=None, data_frequency='minute'): def get_spot_value(self, assets, field, dt=None, data_frequency='minute'):
""" """
@@ -486,52 +505,49 @@ class Exchange:
freq, candle_size, unit, data_frequency = get_frequency( freq, candle_size, unit, data_frequency = get_frequency(
frequency, data_frequency, supported_freqs=['T', 'D', 'H'] frequency, data_frequency, supported_freqs=['T', 'D', 'H']
) )
# we want to avoid receiving empty candles
# so we request more than needed
# TODO: consider defining a const per asset
# and/or some retry mechanism (in each iteration request more data)
requested_bar_count = bar_count + 30
# The get_history method supports multiple asset # The get_history method supports multiple asset
candles = self.get_candles( candles = self.get_candles(
freq=freq, freq=freq,
assets=assets, assets=assets,
bar_count=requested_bar_count, bar_count=bar_count,
end_dt=end_dt if not is_current else None, end_dt=end_dt if not is_current else None,
) )
# candles sanity check - verify no empty candles were received: series = dict()
for asset in candles: for asset in candles:
if not candles[asset]: if candles[asset]:
raise NoCandlesReceivedFromExchange( first_candle = candles[asset][0]
bar_count=requested_bar_count, asset_series = self.get_series_from_candles(
candles=candles[asset],
start_dt=first_candle['last_traded'],
end_dt=end_dt, end_dt=end_dt,
asset=asset, data_frequency=frequency,
exchange=self.name) field=field,
)
series = get_candles_df(candles=candles, delta_candle_size = candle_size * 60 if unit == 'H' else candle_size
field=field, # Checking to make sure that the dates match
freq=frequency, delta = get_delta(delta_candle_size, data_frequency)
bar_count=requested_bar_count, adj_end_dt = end_dt - delta
end_dt=end_dt) last_traded = asset_series.index[-1]
# TODO: consider how to approach this edge case if last_traded < adj_end_dt:
# delta_candle_size = candle_size * 60 if unit == 'H' else candle_size raise LastCandleTooEarlyError(
# Checking to make sure that the dates match last_traded=last_traded,
# delta = get_delta(delta_candle_size, data_frequency) end_dt=adj_end_dt,
# adj_end_dt = end_dt - delta exchange=self.name,
# last_traded = asset_series.index[-1] )
# if last_traded < adj_end_dt: else: # empty candle received
# raise LastCandleTooEarlyError( # because other assets are tz-aware, we need its tz to be set as well
# last_traded=last_traded, asset_series = pd.Series([], index=pd.DatetimeIndex([], tz=pytz.utc))
# end_dt=adj_end_dt,
# exchange=self.name,
# ) series[asset] = asset_series
df = pd.DataFrame(series) df = pd.DataFrame(series)
df.dropna(inplace=True) #df.dropna(inplace=True) # commented out due to issue 236
return df.tail(bar_count) return df
def get_history_window_with_bundle(self, def get_history_window_with_bundle(self,
assets, assets,
@@ -579,8 +595,7 @@ class Exchange:
A dataframe containing the requested data. A dataframe containing the requested data.
""" """
# TODO: this function needs some work, # TODO: this function needs some work, we're currently using it just for benchmark data
# we're currently using it just for benchmark data
freq, candle_size, unit, data_frequency = get_frequency( freq, candle_size, unit, data_frequency = get_frequency(
frequency, data_frequency frequency, data_frequency
) )
@@ -647,20 +662,16 @@ class Exchange:
return df return df
def _check_low_balance(self, currency, balances, amount, open_orders=None): def _check_low_balance(self, currency, balances, amount):
free = balances[currency]['free'] if currency in balances else 0.0 free = balances[currency]['free'] if currency in balances else 0.0
if open_orders:
# TODO: make sure that this works
free += sum([order.amount for order in open_orders])
if free < amount: if free < amount:
return free, True return free, True
else: else:
return free, False return free, False
def sync_positions(self, positions, open_orders=None, cash=None, def sync_positions(self, positions, cash=None,
check_balances=False): check_balances=False):
""" """
Update the portfolio cash and position balances based on the Update the portfolio cash and position balances based on the
@@ -690,7 +701,7 @@ class Exchange:
balances=balances, balances=balances,
amount=cash, amount=cash,
) )
if is_lower and not open_orders: if is_lower:
raise NotEnoughCashError( raise NotEnoughCashError(
currency=self.base_currency, currency=self.base_currency,
exchange=self.name, exchange=self.name,
+2 -23
View File
@@ -18,11 +18,9 @@ from datetime import timedelta
from os import listdir from os import listdir
from os.path import isfile, join, exists from os.path import isfile, join, exists
import catalyst.protocol as zp
import logbook import logbook
import pandas as pd import pandas as pd
from redo import retry
import catalyst.protocol as zp
from catalyst.algorithm import TradingAlgorithm from catalyst.algorithm import TradingAlgorithm
from catalyst.constants import LOG_LEVEL from catalyst.constants import LOG_LEVEL
from catalyst.exchange.exchange_blotter import ExchangeBlotter from catalyst.exchange.exchange_blotter import ExchangeBlotter
@@ -52,6 +50,7 @@ from catalyst.utils.api_support import api_method
from catalyst.utils.input_validation import error_keywords, ensure_upper_case from catalyst.utils.input_validation import error_keywords, ensure_upper_case
from catalyst.utils.math_utils import round_nearest from catalyst.utils.math_utils import round_nearest
from catalyst.utils.preprocess import preprocess from catalyst.utils.preprocess import preprocess
from redo import retry
log = logbook.Logger('exchange_algorithm', level=LOG_LEVEL) log = logbook.Logger('exchange_algorithm', level=LOG_LEVEL)
@@ -164,25 +163,6 @@ class ExchangeTradingAlgorithmBase(TradingAlgorithm):
style) style)
return amount, style return amount, style
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: target
"""
if asset in self.blotter.open_orders:
for open_order in self.blotter.open_orders[asset]:
current_amount = open_order.amount
target -= current_amount
target = super(ExchangeTradingAlgorithmBase, self). \
_calculate_order_target_amount(asset, target)
return target
def round_order(self, amount, asset): def round_order(self, amount, asset):
""" """
We need fractions with cryptocurrencies We need fractions with cryptocurrencies
@@ -671,7 +651,6 @@ class ExchangeTradingAlgorithmLive(ExchangeTradingAlgorithmBase):
required_cash = self.portfolio.cash if not orders else None required_cash = self.portfolio.cash if not orders else None
cash, positions_value = exchange.sync_positions( cash, positions_value = exchange.sync_positions(
positions=exchange_positions, positions=exchange_positions,
open_orders=orders,
check_balances=check_balances, check_balances=check_balances,
cash=required_cash, cash=required_cash,
) )
+48 -47
View File
@@ -1,4 +1,3 @@
import copy
import os import os
import shutil import shutil
from datetime import timedelta from datetime import timedelta
@@ -9,12 +8,8 @@ from operator import is_not
import numpy as np import numpy as np
import pandas as pd import pandas as pd
import pytz import pytz
from catalyst.assets._assets import TradingPair
from logbook import Logger
from pytz import UTC
from six import itervalues
from catalyst import get_calendar from catalyst import get_calendar
from catalyst.assets._assets import TradingPair
from catalyst.constants import DATE_TIME_FORMAT, AUTO_INGEST from catalyst.constants import DATE_TIME_FORMAT, AUTO_INGEST
from catalyst.constants import LOG_LEVEL from catalyst.constants import LOG_LEVEL
from catalyst.data.minute_bars import BcolzMinuteOverlappingData, \ from catalyst.data.minute_bars import BcolzMinuteOverlappingData, \
@@ -27,12 +22,15 @@ from catalyst.exchange.exchange_errors import EmptyValuesInBundleError, \
PricingDataNotLoadedError, DataCorruptionError, PricingDataValueError PricingDataNotLoadedError, DataCorruptionError, PricingDataValueError
from catalyst.exchange.utils.bundle_utils import range_in_bundle, \ from catalyst.exchange.utils.bundle_utils import range_in_bundle, \
get_bcolz_chunk, get_df_from_arrays, get_assets get_bcolz_chunk, get_df_from_arrays, get_assets
from catalyst.exchange.utils.datetime_utils import get_start_dt, \ from catalyst.exchange.utils.datetime_utils import get_delta, get_start_dt, \
get_period_label, get_month_start_end, get_year_start_end, get_period, \ get_period_label, get_month_start_end, get_year_start_end
timestr_to_dt from catalyst.exchange.utils.exchange_utils import get_exchange_folder, \
from catalyst.exchange.utils.exchange_utils import get_exchange_folder save_exchange_symbols, mixin_market_params, get_catalyst_symbol
from catalyst.utils.cli import maybe_show_progress from catalyst.utils.cli import maybe_show_progress
from catalyst.utils.paths import ensure_directory from catalyst.utils.paths import ensure_directory
from logbook import Logger
from pytz import UTC
from six import itervalues
log = Logger('exchange_bundle', level=LOG_LEVEL) log = Logger('exchange_bundle', level=LOG_LEVEL)
@@ -514,8 +512,8 @@ class ExchangeBundle:
continue continue
dates = pd.date_range( dates = pd.date_range(
start=get_period(adj_start, data_frequency), start=get_period_label(adj_start, data_frequency),
end=get_period(adj_end, data_frequency), end=get_period_label(adj_end, data_frequency),
freq='MS' if data_frequency == 'minute' else 'AS', freq='MS' if data_frequency == 'minute' else 'AS',
tz=UTC tz=UTC
) )
@@ -554,9 +552,7 @@ class ExchangeBundle:
# We sort the chunks by end date to ingest most recent data first # We sort the chunks by end date to ingest most recent data first
chunks[asset].sort( chunks[asset].sort(
key=lambda chunk: timestr_to_dt( key=lambda chunk: pd.to_datetime(chunk['period'])
chunk['period'], data_frequency
)
) )
return chunks return chunks
@@ -611,8 +607,7 @@ class ExchangeBundle:
exchange=self.exchange_name, exchange=self.exchange_name,
frequency=data_frequency, frequency=data_frequency,
symbol=asset.symbol symbol=asset.symbol
) )) as it:
) as it:
for chunk in it: for chunk in it:
problems += self.ingest_ctable( problems += self.ingest_ctable(
asset=chunk['asset'], asset=chunk['asset'],
@@ -627,9 +622,7 @@ class ExchangeBundle:
# We sort the chunks by end date to ingest most recent data first # We sort the chunks by end date to ingest most recent data first
all_chunks.sort( all_chunks.sort(
key=lambda chunk: timestr_to_dt( key=lambda chunk: pd.to_datetime(chunk['period'])
chunk['period'], data_frequency
)
) )
with maybe_show_progress( with maybe_show_progress(
all_chunks, all_chunks,
@@ -638,8 +631,7 @@ class ExchangeBundle:
'{exchange}'.format( '{exchange}'.format(
exchange=self.exchange_name, exchange=self.exchange_name,
frequency=data_frequency, frequency=data_frequency,
) )) as it:
) as it:
for chunk in it: for chunk in it:
problems += self.ingest_ctable( problems += self.ingest_ctable(
asset=chunk['asset'], asset=chunk['asset'],
@@ -708,36 +700,42 @@ class ExchangeBundle:
for symbol in symbols: for symbol in symbols:
start_dt = df.index.get_level_values(1).min() start_dt = df.index.get_level_values(1).min()
end_dt = df.index.get_level_values(1).max() end_dt = df.index.get_level_values(1).max()
end_dt_key = 'end_{}'.format(data_frequency)
try: market = self.exchange.get_market(symbol)
asset = self.exchange.get_asset(symbol, is_local=True) if market is None:
except: raise ValueError('symbol not available in the exchange.')
asset = copy.deepcopy(self.exchange.get_asset(symbol))
if asset.data_source == 'local': params = dict(
asset.start_date = asset.start_date \ exchange=self.exchange.name,
if asset.start_date < start_dt else start_dt data_source='local',
exchange_symbol=market['id'],
)
mixin_market_params(self.exchange_name, params, market)
if data_frequency == 'daily': asset_def = self.exchange.get_asset_def(market, True)
asset.end_date = asset.end_daily = asset.end_daily \ if asset_def is not None:
if asset.end_daily > end_dt else end_dt params['symbol'] = asset_def['symbol']
else: params['start_date'] = asset_def['start_date'] \
asset.end_date = asset.end_minute = asset.end_minute \ if asset_def['start_date'] < start_dt else start_dt
if asset.end_minute > end_dt else end_dt
params['end_date'] = asset_def[end_dt_key] \
if asset_def[end_dt_key] > end_dt else end_dt
params['end_daily'] = end_dt \
if data_frequency == 'daily' else asset_def['end_daily']
params['end_minute'] = end_dt \
if data_frequency == 'minute' else asset_def['end_minute']
else: else:
asset.data_source = 'local' params['symbol'] = get_catalyst_symbol(market)
asset.start_date = start_dt
asset.end_dt = end_dt
if data_frequency == 'daily': params['end_daily'] = end_dt \
asset.end_daily = end_dt if data_frequency == 'daily' else 'N/A'
asset.end_minute = None params['end_minute'] = end_dt \
if data_frequency == 'minute' else 'N/A'
else:
asset.end_daily = None
asset.end_minute = end_dt
if min_start_dt is None or start_dt < min_start_dt: if min_start_dt is None or start_dt < min_start_dt:
min_start_dt = start_dt min_start_dt = start_dt
@@ -745,9 +743,11 @@ class ExchangeBundle:
if max_end_dt is None or end_dt > max_end_dt: if max_end_dt is None or end_dt > max_end_dt:
max_end_dt = end_dt max_end_dt = end_dt
assets[symbol] = asset asset = TradingPair(**params)
assets[market['id']] = asset
save_exchange_symbols(self.exchange_name, assets, True)
# TODO: update config.json
writer = self.get_writer( writer = self.get_writer(
start_dt=min_start_dt.replace(hour=00, minute=00), start_dt=min_start_dt.replace(hour=00, minute=00),
end_dt=max_end_dt.replace(hour=23, minute=59), end_dt=max_end_dt.replace(hour=23, minute=59),
@@ -843,6 +843,7 @@ class ExchangeBundle:
field: str field: str
data_frequency: str data_frequency: str
algo_end_dt: pd.Timestamp algo_end_dt: pd.Timestamp
force_auto_ingest:
Returns Returns
------- -------
-21
View File
@@ -322,24 +322,3 @@ class BalanceTooLowError(ZiplineError):
'add positions to hold a free amount greater than {amount}, or clean ' 'add positions to hold a free amount greater than {amount}, or clean '
'the state of this algo and restart.' 'the state of this algo and restart.'
).strip() ).strip()
class NoCandlesReceivedFromExchange(ZiplineError):
msg = (
'Although requesting {bar_count} candles until {end_dt} of asset {asset}, '
'an empty list of candles was received for {exchange}.'
).strip()
class MarketsNotFoundError(ZiplineError):
msg = (
'Exchange {exchange} contains no valid market so it is unusable in '
'Catalyst.'
).strip()
class InvalidMarketError(ZiplineError):
msg = (
'Exchange {exchange} contains at least one incorrectly structured '
'market: {market}, so it is unusable in Catalyst.'
).strip()
+5 -7
View File
@@ -5,7 +5,6 @@ from datetime import datetime
import numpy as np import numpy as np
import pandas as pd import pandas as pd
from catalyst.constants import BUNDLE_URL
from catalyst.data.bundles.core import download_without_progress from catalyst.data.bundles.core import download_without_progress
from catalyst.exchange.utils.exchange_utils import get_exchange_bundles_folder from catalyst.exchange.utils.exchange_utils import get_exchange_bundles_folder
import os import os
@@ -49,11 +48,10 @@ def get_bcolz_chunk(exchange_name, symbol, data_frequency, period):
path = os.path.join(root, name) path = os.path.join(root, name)
if not os.path.isdir(path): if not os.path.isdir(path):
url = BUNDLE_URL.format( url = 'https://s3.amazonaws.com/enigmaco/catalyst-bundles/' \
'exchange-{exchange}/{name}.tar.gz'.format(
exchange=exchange_name, exchange=exchange_name,
data_frequency=data_frequency, name=name)
name=name,
)
bytes = download_without_progress(url) bytes = download_without_progress(url)
with tarfile.open('r', fileobj=bytes) as tar: with tarfile.open('r', fileobj=bytes) as tar:
@@ -77,14 +75,14 @@ def get_df_from_arrays(arrays, periods):
""" """
ohlcv = dict() ohlcv = dict()
for index, field in enumerate(['open', 'high', 'low', 'close', 'volume']): for index, field in enumerate(
['open', 'high', 'low', 'close', 'volume']):
ohlcv[field] = arrays[index].flatten() ohlcv[field] = arrays[index].flatten()
df = pd.DataFrame( df = pd.DataFrame(
data=ohlcv, data=ohlcv,
index=periods index=periods
) )
df.index.name = 'last_traded'
return df return df
-307
View File
@@ -1,307 +0,0 @@
import json
import os
import pandas as pd
from six.moves.urllib import request
from catalyst.assets._assets import TradingPair
from ccxt import NetworkError
from catalyst.constants import LOG_LEVEL, EXCHANGE_CONFIG_URL
from catalyst.exchange.exchange_errors import MarketsNotFoundError, \
InvalidMarketError
from catalyst.exchange.utils.exchange_utils import get_catalyst_symbol, \
get_exchange_folder, get_exchange_auth
from catalyst.exchange.utils.serialization_utils import ExchangeJSONDecoder, \
ExchangeJSONEncoder
from logbook import Logger
from redo import retry
from ccxt.base.exchange import Exchange
from catalyst.utils.paths import last_modified_time, data_root, \
ensure_directory
import ccxt
log = Logger('ccxt_utils', level=LOG_LEVEL)
def scan_exchange_configs(features=None, history=None, is_authenticated=False,
path=None):
"""
Finding exchanges from their config files
Parameters
----------
features
is_authenticated
Returns
-------
"""
for exchange_name in ccxt.exchanges:
config = get_exchange_config(exchange_name, path)
if not config or 'error' in config:
log.info(
'skipping invalid exchange {}'.format(exchange_name)
)
# Check if the exchange has an auth.json file
if is_authenticated:
exchange_auth = get_exchange_auth(exchange_name)
has_auth = (exchange_auth['key'] != ''
and exchange_auth['secret'] != '')
if not has_auth:
continue
if features is None:
has_features = True
else:
try:
supported_features = [
feature for feature in features if
feature in config['features']
]
has_features = len(supported_features) > 0
except Exception:
has_features = False
# TODO: filter by history
if has_features:
yield config
def get_exchange_config(exchange_name, path=None, environ=None,
expiry='1H'):
"""
The de-serialized content of the exchange's config.json.
Parameters
----------
exchange_name: str
The exchange name
filename: str
The target file
environ:
Returns
-------
config: dict[srt, Object]
The config dictionary.
"""
try:
if path is None:
root = data_root(environ)
path = os.path.join(root, 'exchanges')
folder = os.path.join(path, exchange_name)
ensure_directory(folder)
filename = os.path.join(folder, 'config.json')
url = EXCHANGE_CONFIG_URL.format(exchange=exchange_name)
if os.path.isfile(filename):
# If the file exists, only update periodically to avoid
# unnecessary calls
now = pd.Timestamp.utcnow()
limit = pd.Timedelta(expiry)
if pd.Timedelta(now - last_modified_time(filename)) > limit:
try:
request.urlretrieve(url=url, filename=filename)
except Exception as e:
log.warn(
'unable to update config {} => {}: {}'.format(
url, filename, e
)
)
else:
request.urlretrieve(url=url, filename=filename)
with open(filename) as data_file:
data = json.load(data_file, cls=ExchangeJSONDecoder)
return data
except Exception as e:
log.warn(
'unable to download {} config: {}'.format(
exchange_name, e
)
)
return dict(error=e)
def save_exchange_config(config, filename=None, environ=None):
"""
Save assets into an exchange_config file.
Parameters
----------
exchange_name: str
config
environ
Returns
-------
"""
if filename is None:
name = 'config.json'
exchange_folder = get_exchange_folder(config['id'], environ)
filename = os.path.join(exchange_folder, name)
with open(filename, 'w+') as handle:
json.dump(config, handle, indent=4, cls=ExchangeJSONEncoder)
def fetch_markets(ccxt_exchange):
"""
Fetches CCXT market objects.
Parameters
----------
ccxt_exchange: Exchange
Returns
-------
"""
markets_symbols = ccxt_exchange.load_markets()
log.debug(
'fetching {} markets:\n{}'.format(
ccxt_exchange.name, markets_symbols
)
)
markets = ccxt_exchange.fetch_markets()
if not markets:
raise MarketsNotFoundError(
exchange=ccxt_exchange.name,
)
for market in markets:
if 'id' not in market:
raise InvalidMarketError(
exchange=ccxt_exchange.name,
market=market,
)
return markets
def create_exchange_config(ccxt_exchange):
"""
Creates an exchange config structure.
Parameters
----------
ccxt_exchange: Exchange
Returns
-------
"""
exchange_name = ccxt_exchange.__class__.__name__
config = dict(
id=exchange_name,
name=ccxt_exchange.name,
features=[
feature for feature in ccxt_exchange.has if
ccxt_exchange.has[feature]
]
)
markets = retry(
action=fetch_markets,
attempts=5,
sleeptime=5,
retry_exceptions=(NetworkError,),
cleanup=lambda: log.warn(
'fetching markets again for {}'.format(exchange_name)
),
args=(ccxt_exchange,)
)
config['assets'] = []
for market in markets:
asset = create_trading_pair(exchange_name, market)
config['assets'].append(asset)
return config
def create_trading_pair(exchange_name, market, start_dt=None, end_dt=None,
leverage=1, end_daily=None, end_minute=None):
"""
Creating a TradingPair from market and asset data.
Parameters
----------
market: dict[str, Object]
start_dt
end_dt
leverage
end_daily
end_minute
Returns
-------
"""
params = dict(
exchange=exchange_name,
data_source='catalyst',
exchange_symbol=market['id'],
symbol=get_catalyst_symbol(market),
start_date=start_dt,
end_date=end_dt,
leverage=leverage,
asset_name=market['symbol'],
end_daily=end_daily,
end_minute=end_minute,
)
apply_conditional_market_params(exchange_name, params, market)
return TradingPair(**params)
def apply_conditional_market_params(exchange_name, params, market):
"""
Applies a CCXT market dict to parameters of TradingPair init.
Parameters
----------
params: dict[Object]
market: dict[Object]
Returns
-------
"""
# TODO: make this more externalized / configurable
# Consider representing in some type of JSON structure
if 'active' in market:
params['trading_state'] = 1 if market['active'] else 0
else:
params['trading_state'] = 1
if 'lot' in market:
params['min_trade_size'] = market['lot']
params['lot'] = market['lot']
if exchange_name == 'bitfinex':
params['maker'] = 0.001
params['taker'] = 0.002
elif 'maker' in market and 'taker' in market \
and market['maker'] is not None \
and market['taker'] is not None:
params['maker'] = market['maker']
params['taker'] = market['taker']
else:
# TODO: default commission, make configurable
params['maker'] = 0.0015
params['taker'] = 0.0025
info = market['info'] if 'info' in market else None
if info:
if 'minimum_order_size' in info:
params['min_trade_size'] = float(info['minimum_order_size'])
if 'lot' not in params:
params['lot'] = params['min_trade_size']
-26
View File
@@ -164,12 +164,6 @@ def get_start_dt(end_dt, bar_count, data_frequency, include_first=True):
return start_dt return start_dt
def timestr_to_dt(timestr, data_frequency):
dt_format = '%Y' if data_frequency == 'daily' else '%Y%m'
dt = pd.to_datetime(timestr, format=dt_format, utc=True)
return dt
def get_period_label(dt, data_frequency): def get_period_label(dt, data_frequency):
""" """
The period label for the specified date and frequency. The period label for the specified date and frequency.
@@ -183,26 +177,6 @@ def get_period_label(dt, data_frequency):
------- -------
str str
"""
if data_frequency == 'minute':
return '{}{:02d}'.format(dt.year, dt.month)
else:
return '{}'.format(dt.year)
def get_period(dt, data_frequency):
"""
The period label for the specified date and frequency.
Parameters
----------
dt: datetime
data_frequency: str
Returns
-------
str
""" """
if data_frequency == 'minute': if data_frequency == 'minute':
return '{}-{:02d}'.format(dt.year, dt.month) return '{}-{:02d}'.format(dt.year, dt.month)
+106 -76
View File
@@ -1,19 +1,19 @@
import hashlib import hashlib
import os
import shutil
import json import json
import pandas as pd import os
import pickle import pickle
from catalyst.assets._assets import TradingPair import shutil
from datetime import date, datetime from datetime import date, datetime
import pandas as pd
from catalyst.assets._assets import TradingPair
from six import string_types from six import string_types
from six.moves.urllib import request from six.moves.urllib import request
from catalyst.constants import EXCHANGE_CONFIG_URL from catalyst.constants import DATE_FORMAT, SYMBOLS_URL
from catalyst.exchange.exchange_errors import ExchangeSymbolsNotFound
from catalyst.exchange.utils.serialization_utils import ExchangeJSONEncoder, \ from catalyst.exchange.utils.serialization_utils import ExchangeJSONEncoder, \
ExchangeJSONDecoder, ConfigJSONEncoder ExchangeJSONDecoder
from catalyst.utils.deprecate import deprecated
from catalyst.utils.paths import data_root, ensure_directory, \ from catalyst.utils.paths import data_root, ensure_directory, \
last_modified_time last_modified_time
@@ -69,7 +69,7 @@ def is_blacklist(exchange_name, environ=None):
return os.path.exists(filename) return os.path.exists(filename)
def get_exchange_config_filename(exchange_name, environ=None): def get_exchange_symbols_filename(exchange_name, is_local=False, environ=None):
""" """
The absolute path of the exchange's symbol.json file. The absolute path of the exchange's symbol.json file.
@@ -83,12 +83,12 @@ def get_exchange_config_filename(exchange_name, environ=None):
str str
""" """
name = 'config.json' name = 'symbols.json' if not is_local else 'symbols_local.json'
exchange_folder = get_exchange_folder(exchange_name, environ) exchange_folder = get_exchange_folder(exchange_name, environ)
return os.path.join(exchange_folder, name) return os.path.join(exchange_folder, name)
def download_exchange_config(exchange_name, filename, environ=None): def download_exchange_symbols(exchange_name, environ=None):
""" """
Downloads the exchange's symbols.json from the repository. Downloads the exchange's symbols.json from the repository.
@@ -102,14 +102,15 @@ def download_exchange_config(exchange_name, filename, environ=None):
str str
""" """
url = EXCHANGE_CONFIG_URL.format(exchange=exchange_name) filename = get_exchange_symbols_filename(exchange_name)
request.urlretrieve(url=url, filename=filename) url = SYMBOLS_URL.format(exchange=exchange_name)
response = request.urlretrieve(url=url, filename=filename)
return response
@deprecated def get_exchange_symbols(exchange_name, is_local=False, environ=None):
def get_exchange_config(exchange_name, filename=None, environ=None):
""" """
The de-serialized content of the exchange's config.json. The de-serialized content of the exchange's symbols.json.
Parameters Parameters
---------- ----------
@@ -122,48 +123,55 @@ def get_exchange_config(exchange_name, filename=None, environ=None):
Object Object
""" """
if filename is None: filename = get_exchange_symbols_filename(exchange_name, is_local)
filename = get_exchange_config_filename(exchange_name)
if not is_local and (not os.path.isfile(filename) or pd.Timedelta(
pd.Timestamp('now', tz='UTC') - last_modified_time(
filename)).days > 1):
try:
download_exchange_symbols(exchange_name, environ)
except Exception:
pass
if os.path.isfile(filename): if os.path.isfile(filename):
now = pd.Timestamp.utcnow() with open(filename) as data_file:
limit = pd.Timedelta('2H') try:
if pd.Timedelta(now - last_modified_time(filename)) > limit: data = json.load(data_file, cls=ExchangeJSONDecoder)
download_exchange_config(exchange_name, filename, environ) return data
except ValueError:
return dict()
else: else:
download_exchange_config(exchange_name, filename, environ) raise ExchangeSymbolsNotFound(
exchange=exchange_name,
with open(filename) as data_file: filename=filename
try: )
data = json.load(data_file, cls=ExchangeJSONDecoder)
return data
except ValueError:
return dict()
def save_exchange_config(exchange_name, config, filename=None, environ=None): def save_exchange_symbols(exchange_name, assets, is_local=False, environ=None):
""" """
Save assets into an exchange_config file. Save assets into an exchange_symbols file.
Parameters Parameters
---------- ----------
exchange_name: str exchange_name: str
config assets: list[dict[str, object]]
is_local: bool
environ environ
Returns Returns
------- -------
""" """
if filename is None: asset_dicts = dict()
name = 'config.json' for symbol in assets:
exchange_folder = get_exchange_folder(exchange_name, environ) asset_dicts[symbol] = assets[symbol].to_dict()
filename = os.path.join(exchange_folder, name)
with open(filename, 'w+') as handle: filename = get_exchange_symbols_filename(
json.dump(config, handle, indent=4, cls=ConfigJSONEncoder) exchange_name, is_local, environ
)
with open(filename, 'wt') as handle:
json.dump(asset_dicts, handle, indent=4, default=symbols_serial)
def get_symbols_string(assets): def get_symbols_string(assets):
@@ -504,6 +512,25 @@ def has_bundle(exchange_name, data_frequency, environ=None):
return os.path.isdir(folder) return os.path.isdir(folder)
def symbols_serial(obj):
"""
JSON serializer for objects not serializable by default json code
Parameters
----------
obj: Object
Returns
-------
str
"""
if isinstance(obj, (datetime, date)):
return obj.floor('1D').strftime(DATE_FORMAT)
raise TypeError("Type %s not serializable" % type(obj))
def perf_serial(obj): def perf_serial(obj):
""" """
JSON serializer for objects not serializable by default json code JSON serializer for objects not serializable by default json code
@@ -593,12 +620,46 @@ def resample_history_df(df, freq, field, start_dt=None):
return resampled_df return resampled_df
def from_ms_timestamp(ms): def mixin_market_params(exchange_name, params, market):
return pd.to_datetime(ms, unit='ms', utc=True) """
Applies a CCXT market dict to parameters of TradingPair init.
Parameters
----------
params: dict[Object]
market: dict[Object]
def get_epoch(): Returns
return pd.to_datetime('1970-1-1', utc=True) -------
"""
# TODO: make this more externalized / configurable
if 'lot' in market:
params['min_trade_size'] = market['lot']
params['lot'] = market['lot']
if exchange_name == 'bitfinex':
params['maker'] = 0.001
params['taker'] = 0.002
elif 'maker' in market and 'taker' in market and \
market['maker'] is not None and market['taker'] is not None:
params['maker'] = market['maker']
params['taker'] = market['taker']
else:
# TODO: default commission, make configurable
params['maker'] = 0.0015
params['taker'] = 0.0025
info = market['info'] if 'info' in market else None
if info:
if 'minimum_order_size' in info:
params['min_trade_size'] = float(info['minimum_order_size'])
if 'lot' not in params:
params['lot'] = params['min_trade_size']
def group_assets_by_exchange(assets): def group_assets_by_exchange(assets):
@@ -673,7 +734,7 @@ def transform_candles_to_df(candles):
return pd.DataFrame(candles).set_index('last_traded') return pd.DataFrame(candles).set_index('last_traded')
def get_candles_df(candles, field, freq, bar_count, end_dt): def get_candles_df(candles, field, freq, bar_count, end_dt=None):
all_series = dict() all_series = dict()
for asset in candles: for asset in candles:
@@ -687,37 +748,6 @@ def get_candles_df(candles, field, freq, bar_count, end_dt):
all_series[asset] = pd.Series(asset_df[field]) all_series[asset] = pd.Series(asset_df[field])
df = pd.DataFrame(all_series) df = pd.DataFrame(all_series)
df.dropna(inplace=True) df.dropna(inplace=True)
return df return df
def get_trades_df(trades):
df = pd.DataFrame(trades)
df.index = pd.to_datetime(df.pop('datetime'))
df.index = df.index.tz_localize('UTC')
return df
def candles_from_trades(trades_df, freq):
"""
Calculate OHLCV from candles.
Parameters
----------
trades_df
freq
Returns
-------
"""
df = trades_df['price'].resample(freq).ohlc() # type: pd.DataFrame
df['volume'] = trades_df['amount'].resample(freq).sum()
df.dropna(axis=0, how='all', inplace=True)
df.sort_index(inplace=True, ascending=False)
return df
+23 -33
View File
@@ -4,9 +4,8 @@ from catalyst.constants import LOG_LEVEL
from catalyst.exchange.ccxt.ccxt_exchange import CCXT from catalyst.exchange.ccxt.ccxt_exchange import CCXT
from catalyst.exchange.exchange import Exchange from catalyst.exchange.exchange import Exchange
from catalyst.exchange.exchange_errors import ExchangeAuthEmpty from catalyst.exchange.exchange_errors import ExchangeAuthEmpty
from catalyst.exchange.utils.ccxt_utils import scan_exchange_configs
from catalyst.exchange.utils.exchange_utils import get_exchange_auth, \ from catalyst.exchange.utils.exchange_utils import get_exchange_auth, \
get_exchange_folder get_exchange_folder, is_blacklist
from logbook import Logger from logbook import Logger
log = Logger('factory', level=LOG_LEVEL) log = Logger('factory', level=LOG_LEVEL)
@@ -14,12 +13,9 @@ exchange_cache = dict()
def get_exchange(exchange_name, base_currency=None, must_authenticate=False, def get_exchange(exchange_name, base_currency=None, must_authenticate=False,
skip_init=False, auth_alias=None, config=None): skip_init=False, auth_alias=None):
key = (exchange_name, base_currency) key = (exchange_name, base_currency)
if key in exchange_cache: if key in exchange_cache:
if not skip_init:
exchange_cache[key].init()
return exchange_cache[key] return exchange_cache[key]
exchange_auth = get_exchange_auth(exchange_name, alias=auth_alias) exchange_auth = get_exchange_auth(exchange_name, alias=auth_alias)
@@ -40,7 +36,6 @@ def get_exchange(exchange_name, base_currency=None, must_authenticate=False,
password=exchange_auth['password'] if 'password' password=exchange_auth['password'] if 'password'
in exchange_auth.keys() else '', in exchange_auth.keys() else '',
base_currency=base_currency, base_currency=base_currency,
config=config,
) )
exchange_cache[key] = exchange exchange_cache[key] = exchange
@@ -58,8 +53,8 @@ def get_exchanges(exchange_names):
return exchanges return exchanges
def find_exchanges(features=None, history=None, skip_blacklist=True, path=None, def find_exchanges(features=None, skip_blacklist=True, is_authenticated=False,
is_authenticated=False, base_currency=None): base_currency=None):
""" """
Find exchanges filtered by a list of feature. Find exchanges filtered by a list of feature.
@@ -77,33 +72,28 @@ def find_exchanges(features=None, history=None, skip_blacklist=True, path=None,
list[Exchange] list[Exchange]
""" """
exchange_names = CCXT.find_exchanges(features, is_authenticated)
return list( exchanges = []
scan_exchanges( for exchange_name in exchange_names:
features, if skip_blacklist and is_blacklist(exchange_name):
history,
skip_blacklist,
path,
is_authenticated,
base_currency
)
)
def scan_exchanges(features=None, history=None, skip_blacklist=True, path=None,
is_authenticated=False, base_currency=None):
for config in scan_exchange_configs(
features=features,
history=history,
is_authenticated=is_authenticated,
path=path,
):
if skip_blacklist and (config is None or 'error' in config):
continue continue
yield get_exchange( exchange = get_exchange(
exchange_name=config['id'], exchange_name=exchange_name,
skip_init=True, skip_init=True,
base_currency=base_currency, base_currency=base_currency,
config=config,
) )
if features is not None:
if 'dailyBundle' in features \
and not exchange.has_bundle('daily'):
continue
elif 'minuteBundle' in features \
and not exchange.has_bundle('minute'):
continue
exchanges.append(exchange)
return exchanges
+1 -34
View File
@@ -3,48 +3,15 @@ import re
from json import JSONEncoder from json import JSONEncoder
import pandas as pd import pandas as pd
from catalyst.constants import DATE_TIME_FORMAT
from six import string_types from six import string_types
from datetime import date, datetime
from catalyst.constants import DATE_TIME_FORMAT, DATE_FORMAT
from catalyst.assets._assets import TradingPair
class ConfigJSONEncoder(json.JSONEncoder):
def default(self, obj):
"""
JSON serializer for objects not serializable by default json code
Parameters
----------
obj: Object
Returns
-------
str
"""
if isinstance(obj, (datetime, date)):
return obj.floor('1D').strftime(DATE_FORMAT)
elif isinstance(obj, TradingPair):
return obj.to_dict()
class ExchangeJSONEncoder(json.JSONEncoder): class ExchangeJSONEncoder(json.JSONEncoder):
def default(self, obj): def default(self, obj):
if isinstance(obj, pd.Timestamp): if isinstance(obj, pd.Timestamp):
return obj.strftime(DATE_TIME_FORMAT) return obj.strftime(DATE_TIME_FORMAT)
elif isinstance(obj, TradingPair):
asset = obj.to_dict()
asset['maker'] = round(asset['maker'], asset['decimals'])
asset['taker'] = round(asset['taker'], asset['decimals'])
asset['lot'] = round(asset['lot'], 4)
asset['min_trade_size'] = round(asset['min_trade_size'], 4)
asset['max_trade_size'] = round(asset['max_trade_size'], 4)
return asset
# Let the base class default method raise the TypeError # Let the base class default method raise the TypeError
return JSONEncoder.default(self, obj) return JSONEncoder.default(self, obj)
+20 -109
View File
@@ -7,7 +7,6 @@ import re
import shutil import shutil
import sys import sys
import time import time
import webbrowser
import bcolz import bcolz
import logbook import logbook
@@ -33,7 +32,6 @@ from catalyst.marketplace.utils.eth_utils import bin_hex, from_grains, \
from catalyst.marketplace.utils.path_utils import get_bundle_folder, \ from catalyst.marketplace.utils.path_utils import get_bundle_folder, \
get_data_source_folder, get_marketplace_folder, \ get_data_source_folder, get_marketplace_folder, \
get_user_pubaddr, get_temp_bundles_folder, extract_bundle get_user_pubaddr, get_temp_bundles_folder, extract_bundle
from catalyst.utils.paths import ensure_directory
if sys.version_info.major < 3: if sys.version_info.major < 3:
import urllib import urllib
@@ -143,10 +141,10 @@ class Marketplace:
return address, address_i return address, address_i
def sign_transaction(self, tx): def sign_transaction(self, from_address, tx):
url = 'https://www.myetherwallet.com/#offline-transaction' print('\nVisit https://www.myetherwallet.com/#offline-transaction and '
print('\nVisit {url} and enter the following parameters:\n\n' 'enter the following parameters:\n\n'
'From Address:\t\t{_from}\n' 'From Address:\t\t{_from}\n'
'\n\tClick the "Generate Information" button\n\n' '\n\tClick the "Generate Information" button\n\n'
'To Address:\t\t{to}\n' 'To Address:\t\t{to}\n'
@@ -155,8 +153,7 @@ class Marketplace:
'Gas Price:\t\t[Accept the default value]\n' 'Gas Price:\t\t[Accept the default value]\n'
'Nonce:\t\t\t{nonce}\n' 'Nonce:\t\t\t{nonce}\n'
'Data:\t\t\t{data}\n'.format( 'Data:\t\t\t{data}\n'.format(
url=url, _from=from_address,
_from=tx['from'],
to=tx['to'], to=tx['to'],
value=tx['value'], value=tx['value'],
gas=tx['gas'], gas=tx['gas'],
@@ -164,8 +161,6 @@ class Marketplace:
data=tx['data'], ) data=tx['data'], )
) )
webbrowser.open_new(url)
signed_tx = input('Copy and Paste the "Signed Transaction" ' signed_tx = input('Copy and Paste the "Signed Transaction" '
'field here:\n') 'field here:\n')
@@ -185,7 +180,8 @@ class Marketplace:
print('\nYou can check the outcome of your transaction here:\n' print('\nYou can check the outcome of your transaction here:\n'
'{}\n\n'.format(etherscan)) '{}\n\n'.format(etherscan))
def _list(self): def list(self):
data_sources = self.mkt_contract.functions.getAllProviders().call() data_sources = self.mkt_contract.functions.getAllProviders().call()
data = [] data = []
@@ -197,44 +193,15 @@ class Marketplace:
dataset=self.to_text(data_source) dataset=self.to_text(data_source)
) )
) )
return pd.DataFrame(data)
def list(self):
df = self._list()
df = pd.DataFrame(data)
set_print_settings() set_print_settings()
if df.empty: if df.empty:
print('There are no datasets available yet.') print('There are no datasets available yet.')
else: else:
print(df) print(df)
def subscribe(self, dataset=None): def subscribe(self, dataset):
if dataset is None:
df_sets = self._list()
if df_sets.empty:
print('There are no datasets available yet.')
return
set_print_settings()
while True:
print(df_sets)
dataset_num = input('Choose the dataset you want to '
'subscribe to [0..{}]: '.format(
df_sets.size - 1))
try:
dataset_num = int(dataset_num)
except ValueError:
print('Enter a number between 0 and {}'.format(
df_sets.size - 1))
else:
if dataset_num not in range(0, df_sets.size):
print('Enter a number between 0 and {}'.format(
df_sets.size - 1))
else:
dataset = df_sets.iloc[dataset_num]['dataset']
break
dataset = dataset.lower() dataset = dataset.lower()
@@ -325,14 +292,13 @@ class Marketplace:
self.mkt_contract_address, self.mkt_contract_address,
grains, grains,
).buildTransaction( ).buildTransaction(
{'from': address, {'nonce': self.web3.eth.getTransactionCount(address)}
'nonce': self.web3.eth.getTransactionCount(address)}
) )
if 'ropsten' in ETH_REMOTE_NODE: if 'ropsten' in ETH_REMOTE_NODE:
tx['gas'] = min(int(tx['gas'] * 1.5), 4700000) tx['gas'] = min(int(tx['gas'] * 1.5), 4700000)
signed_tx = self.sign_transaction(tx) signed_tx = self.sign_transaction(address, tx)
try: try:
tx_hash = '0x{}'.format( tx_hash = '0x{}'.format(
bin_hex(self.web3.eth.sendRawTransaction(signed_tx)) bin_hex(self.web3.eth.sendRawTransaction(signed_tx))
@@ -367,14 +333,13 @@ class Marketplace:
tx = self.mkt_contract.functions.subscribe( tx = self.mkt_contract.functions.subscribe(
Web3.toHex(dataset), Web3.toHex(dataset),
).buildTransaction({ ).buildTransaction(
'from': address, {'nonce': self.web3.eth.getTransactionCount(address)})
'nonce': self.web3.eth.getTransactionCount(address)})
if 'ropsten' in ETH_REMOTE_NODE: if 'ropsten' in ETH_REMOTE_NODE:
tx['gas'] = min(int(tx['gas'] * 1.5), 4700000) tx['gas'] = min(int(tx['gas'] * 1.5), 4700000)
signed_tx = self.sign_transaction(tx) signed_tx = self.sign_transaction(address, tx)
try: try:
tx_hash = '0x{}'.format(bin_hex( tx_hash = '0x{}'.format(bin_hex(
@@ -427,7 +392,6 @@ class Marketplace:
""" """
tmp_bundle = extract_bundle(path) tmp_bundle = extract_bundle(path)
bundle_folder = get_data_source_folder(ds_name) bundle_folder = get_data_source_folder(ds_name)
ensure_directory(bundle_folder)
if os.listdir(bundle_folder): if os.listdir(bundle_folder):
zsource = bcolz.ctable(rootdir=tmp_bundle, mode='r') zsource = bcolz.ctable(rootdir=tmp_bundle, mode='r')
ztarget = bcolz.ctable(rootdir=bundle_folder, mode='r') ztarget = bcolz.ctable(rootdir=bundle_folder, mode='r')
@@ -438,33 +402,7 @@ class Marketplace:
pass pass
def ingest(self, ds_name=None, start=None, end=None, force_download=False): def ingest(self, ds_name, start=None, end=None, force_download=False):
if ds_name is None:
df_sets = self._list()
if df_sets.empty:
print('There are no datasets available yet.')
return
set_print_settings()
while True:
print(df_sets)
dataset_num = input('Choose the dataset you want to '
'ingest [0..{}]: '.format(
df_sets.size - 1))
try:
dataset_num = int(dataset_num)
except ValueError:
print('Enter a number between 0 and {}'.format(
df_sets.size - 1))
else:
if dataset_num not in range(0, df_sets.size):
print('Enter a number between 0 and {}'.format(
df_sets.size - 1))
else:
ds_name = df_sets.iloc[dataset_num]['dataset']
break
# ds_name = ds_name.lower() # ds_name = ds_name.lower()
@@ -560,40 +498,14 @@ class Marketplace:
return df return df
def clean(self, ds_name=None, data_frequency=None): def clean(self, data_source_name, data_frequency=None):
data_source_name = data_source_name.lower()
if ds_name is None:
mktplace_root = get_marketplace_folder()
folders = [os.path.basename(f.rstrip('/'))
for f in glob.glob('{}/*/'.format(mktplace_root))
if 'temp_bundles' not in f]
while True:
for idx, f in enumerate(folders):
print('{}\t{}'.format(idx, f))
dataset_num = input('Choose the dataset you want to '
'clean [0..{}]: '.format(
len(folders) - 1))
try:
dataset_num = int(dataset_num)
except ValueError:
print('Enter a number between 0 and {}'.format(
len(folders) - 1))
else:
if dataset_num not in range(0, len(folders)):
print('Enter a number between 0 and {}'.format(
len(folders) - 1))
else:
ds_name = folders[dataset_num]
break
ds_name = ds_name.lower()
if data_frequency is None: if data_frequency is None:
folder = get_data_source_folder(ds_name) folder = get_data_source_folder(data_source_name)
else: else:
folder = get_bundle_folder(ds_name, data_frequency) folder = get_bundle_folder(data_source_name, data_frequency)
shutil.rmtree(folder) shutil.rmtree(folder)
pass pass
@@ -697,14 +609,13 @@ class Marketplace:
grains, grains,
address, address,
).buildTransaction( ).buildTransaction(
{'from': address, {'nonce': self.web3.eth.getTransactionCount(address)}
'nonce': self.web3.eth.getTransactionCount(address)}
) )
if 'ropsten' in ETH_REMOTE_NODE: if 'ropsten' in ETH_REMOTE_NODE:
tx['gas'] = min(int(tx['gas'] * 1.5), 4700000) tx['gas'] = min(int(tx['gas'] * 1.5), 4700000)
signed_tx = self.sign_transaction(tx) signed_tx = self.sign_transaction(address, tx)
try: try:
tx_hash = '0x{}'.format( tx_hash = '0x{}'.format(
+1 -59
View File
@@ -1,12 +1,8 @@
import os import os
import random
import re
import shutil import shutil
import bcolz import bcolz
import numpy as np
import pandas as pd import pandas as pd
from six import string_types
def merge_bundles(zsource, ztarget): def merge_bundles(zsource, ztarget):
@@ -31,64 +27,10 @@ def merge_bundles(zsource, ztarget):
df.drop_duplicates(inplace=True) df.drop_duplicates(inplace=True)
df.set_index(['date', 'symbol'], drop=False, inplace=True) df.set_index(['date', 'symbol'], drop=False, inplace=True)
sanitize_df(df)
dirname = os.path.basename(ztarget.rootdir) dirname = os.path.basename(ztarget.rootdir)
bak_dir = ztarget.rootdir.replace(dirname, '.{}'.format(dirname)) bak_dir = ztarget.rootdir.replace(dirname, '.{}'.format(dirname))
shutil.move(ztarget.rootdir, bak_dir) os.rename(ztarget.rootdir, bak_dir)
z = bcolz.ctable.fromdataframe(df=df, rootdir=ztarget.rootdir) z = bcolz.ctable.fromdataframe(df=df, rootdir=ztarget.rootdir)
shutil.rmtree(bak_dir) shutil.rmtree(bak_dir)
return z return z
def sanitize_df(df):
# Using a sampling method to identify dates for efficiency with
# large datasets
if len(df) > 100:
indexes = random.sample(range(0, len(df) - 1), 100)
elif len(df) > 1:
indexes = range(0, len(df) - 1)
else:
indexes = [0, ]
for column in df.columns:
is_date = False
for index in indexes:
value = df[column].iloc[index]
if not isinstance(value, string_types):
continue
# TODO: assuming that the date is at least daily
exp = re.compile(r'^\d{4}-\d{2}-\d{2}.*$')
matches = exp.findall(value)
if matches:
is_date = True
break
if is_date:
df[column] = pd.to_datetime(df[column])
else:
try:
ser = safely_reduce_dtype(df[column])
df[column] = ser
except Exception:
pass
return df
def safely_reduce_dtype(ser): # pandas.Series or numpy.array
orig_dtype = "".join(
[x for x in ser.dtype.name if x.isalpha()]) # float/int
mx = 1
for val in ser.values:
new_itemsize = np.min_scalar_type(val).itemsize
if mx < new_itemsize:
mx = new_itemsize
if orig_dtype == 'int':
mx = max(mx, 4)
new_dtype = orig_dtype + str(mx * 8)
return ser.astype(new_dtype)
+14 -16
View File
@@ -1,8 +1,7 @@
from catalyst.api import symbol from catalyst.api import symbol
from catalyst.utils.run_algo import run_algorithm from catalyst.utils.run_algo import run_algorithm
coins = ['dash', 'btc', 'dash', 'etc', 'eth', 'ltc', 'nxt', 'rep', 'str', coins = ['dash', 'btc', 'dash', 'etc', 'eth', 'ltc', 'nxt', 'rep', 'str', 'xmr', 'xrp', 'zec']
'xmr', 'xrp', 'zec']
symbols = None symbols = None
@@ -14,21 +13,20 @@ def _handle_data(context, data):
global symbols global symbols
if symbols is None: symbols = [symbol(c + '_usdt') for c in coins] if symbols is None: symbols = [symbol(c + '_usdt') for c in coins]
print('getting history for: %s' % [s.symbol for s in symbols]) print'getting history for: %s' % [s.symbol for s in symbols]
history = data.history(symbols, history = data.history(symbols,
['close', 'volume'], ['close', 'volume'],
bar_count=1, # EXCEPTION, Change to 2 bar_count=1, # EXCEPTION, Change to 2
frequency='5T') frequency='5T')
# print 'history: %s' % history.shape #print 'history: %s' % history.shape
run_algorithm(initialize=initialize, run_algorithm(initialize=initialize,
handle_data=_handle_data, handle_data=_handle_data,
analyze=lambda _, results: True, analyze=lambda _, results: True,
exchange_name='poloniex', exchange_name='poloniex',
base_currency='usdt', base_currency='usdt',
algo_namespace='issue-236', algo_namespace='issue-236',
live=True, live=True,
data_frequency='minute', data_frequency='minute',
capital_base=3000, capital_base=3000,
simulate_orders=True) simulate_orders=True)
+1 -12
View File
@@ -10,7 +10,6 @@ import click
import pandas as pd import pandas as pd
from six import string_types from six import string_types
import catalyst
from catalyst.data.bundles import load from catalyst.data.bundles import load
from catalyst.data.data_portal import DataPortal from catalyst.data.data_portal import DataPortal
from catalyst.exchange.exchange_pricing_loader import ExchangePricingLoader, \ from catalyst.exchange.exchange_pricing_loader import ExchangePricingLoader, \
@@ -24,7 +23,7 @@ try:
from pygments.formatters import TerminalFormatter from pygments.formatters import TerminalFormatter
PYGMENTS = True PYGMENTS = True
except ImportError: except:
PYGMENTS = False PYGMENTS = False
from toolz import valfilter, concatv from toolz import valfilter, concatv
from functools import partial from functools import partial
@@ -152,7 +151,6 @@ def _run(handle_data,
'We encourage you to report any issue on GitHub: ' 'We encourage you to report any issue on GitHub: '
'https://github.com/enigmampc/catalyst/issues' 'https://github.com/enigmampc/catalyst/issues'
) )
log.info('Catalyst version {}'.format(catalyst.__version__))
sleep(3) sleep(3)
if live: if live:
@@ -263,15 +261,6 @@ def _run(handle_data,
# We still need to support bundles for other misc data, but we # We still need to support bundles for other misc data, but we
# can handle this later. # can handle this later.
if start != pd.tslib.normalize_date(start) or \
end != pd.tslib.normalize_date(end):
# todo: add to Sim_Params the option to start & end at specific times
log.warn(
"Catalyst currently starts and ends on the start and "
"end of the dates specified, respectively. We hope to "
"Modify this and support specific times in a future release."
)
data = DataPortalExchangeBacktest( data = DataPortalExchangeBacktest(
exchange_names=[exchange_name for exchange_name in exchanges], exchange_names=[exchange_name for exchange_name in exchanges],
asset_finder=None, asset_finder=None,
+103
View File
@@ -0,0 +1,103 @@
#!flask/bin/python
import base64
import requests
import pandas as pd
import json
def convert_date(date):
"""
when transferring dates by json,
converts it to str
:param date:
:return: str(date)
"""
if isinstance(date, pd.Timestamp):
return date.__str__()
def run_server(
initialize,
handle_data,
before_trading_start,
analyze,
algofile,
algotext,
defines,
data_frequency,
capital_base,
data,
bundle,
bundle_timestamp,
start,
end,
output,
print_algo,
local_namespace,
environ,
live,
exchange,
algo_namespace,
base_currency,
live_graph,
analyze_live,
simulate_orders,
auth_aliases,
stats_output,
):
# address to send
url = 'http://sandbox.enigma.co/api/catalyst/serve'
# url = 'http://127.0.0.1:5000/api/catalyst/serve'
# argument preparation - encode the file for transfer
if algotext:
algotext = base64.b64encode(algotext)
else:
algotext = base64.b64encode(bytes(algofile.read(), 'utf-8')).decode('utf-8')
algofile = None
json_file = {'arguments': {
'initialize': initialize,
'handle_data': handle_data,
'before_trading_start': before_trading_start,
'analyze': analyze,
'algotext': algotext,
'defines': defines,
'data_frequency': data_frequency,
'capital_base': capital_base,
'data': data,
'bundle': bundle,
'bundle_timestamp': bundle_timestamp,
'start': start,
'end': end,
'local_namespace': local_namespace,
'environ': None,
'analyze_live': analyze_live,
'stats_output': stats_output,
'algofile': algofile,
'output': output,
'print_algo': print_algo,
'live': live,
'exchange': exchange,
'algo_namespace': algo_namespace,
'base_currency': base_currency,
'live_graph': live_graph,
'simulate_orders': simulate_orders,
'auth_aliases': auth_aliases,
}}
response = requests.post(url,
json=json.dumps(
json_file,
default=convert_date
)
)
if response.status_code == 500:
raise Exception("issues with cloud connections, "
"unable to run catalyst on the cloud")
received_data = response.json()
cloud_log_tail = base64.b64decode(received_data["log"])
print(cloud_log_tail)
+1 -1
View File
@@ -22,7 +22,7 @@ dependencies:
- bcolz==0.12.1 - bcolz==0.12.1
- bottleneck==1.2.1 - bottleneck==1.2.1
- chardet==3.0.4 - chardet==3.0.4
- ccxt==1.11.22 - ccxt==1.10.1094
# The Enigma Data Marketplace requires Python3 because it depends on # The Enigma Data Marketplace requires Python3 because it depends on
# web3, which requires Python3, as building its dependencies breaks in Python2 # web3, which requires Python3, as building its dependencies breaks in Python2
# - web3==4.0.0b7 # - web3==4.0.0b7
+1 -1
View File
@@ -31,7 +31,7 @@ dependencies:
- botocore==1.8.41 - botocore==1.8.41
- bottleneck==1.2.1 - bottleneck==1.2.1
- cchardet==2.1.1 - cchardet==2.1.1
- ccxt==1.11.22 - ccxt==1.10.1102
- chardet==3.0.4 - chardet==3.0.4
- click==6.7 - click==6.7
- contextlib2==0.5.5 - contextlib2==0.5.5
+1 -1
View File
@@ -81,7 +81,7 @@ empyrical==0.2.1
tables==3.3.0 tables==3.3.0
#Catalyst dependencies #Catalyst dependencies
ccxt==1.11.22 ccxt==1.10.1094
boto3==1.4.8 boto3==1.4.8
redo==1.6 redo==1.6
web3==4.0.0b11; python_version > '3.4' web3==4.0.0b11; python_version > '3.4'
+17 -35
View File
@@ -11,11 +11,10 @@ from catalyst.exchange.exchange_bundle import ExchangeBundle, \
BUNDLE_NAME_TEMPLATE BUNDLE_NAME_TEMPLATE
from catalyst.exchange.utils.bundle_utils import get_bcolz_chunk, \ from catalyst.exchange.utils.bundle_utils import get_bcolz_chunk, \
get_df_from_arrays get_df_from_arrays
from catalyst.exchange.utils.datetime_utils import get_start_dt from exchange.utils.datetime_utils import get_start_dt
from catalyst.exchange.utils.exchange_utils import get_exchange_folder from catalyst.exchange.utils.exchange_utils import get_exchange_folder
from catalyst.exchange.utils.factory import get_exchange from catalyst.exchange.utils.factory import get_exchange
from catalyst.exchange.utils.stats_utils import df_to_string, \ from catalyst.exchange.utils.stats_utils import df_to_string
set_print_settings
from catalyst.utils.paths import ensure_directory from catalyst.utils.paths import ensure_directory
log = getLogger('test_exchange_bundle') log = getLogger('test_exchange_bundle')
@@ -43,16 +42,16 @@ class TestExchangeBundle:
def test_ingest_minute(self): def test_ingest_minute(self):
data_frequency = 'minute' data_frequency = 'minute'
exchange_name = 'binance' exchange_name = 'poloniex'
exchange = get_exchange(exchange_name) exchange = get_exchange(exchange_name)
exchange_bundle = ExchangeBundle(exchange_name) exchange_bundle = ExchangeBundle(exchange)
assets = [ assets = [
exchange.get_asset('bch_eth') exchange.get_asset('eth_btc')
] ]
start = pd.to_datetime('2018-03-01', utc=True) start = pd.to_datetime('2016-03-01', utc=True)
end = pd.to_datetime('2018-03-8', utc=True) end = pd.to_datetime('2017-11-1', utc=True)
log.info('ingesting exchange bundle {}'.format(exchange_name)) log.info('ingesting exchange bundle {}'.format(exchange_name))
exchange_bundle.ingest( exchange_bundle.ingest(
@@ -62,8 +61,7 @@ class TestExchangeBundle:
exclude_symbols=None, exclude_symbols=None,
start=start, start=start,
end=end, end=end,
show_progress=False, show_progress=True
show_breakdown=False
) )
reader = exchange_bundle.get_reader(data_frequency) reader = exchange_bundle.get_reader(data_frequency)
@@ -74,15 +72,9 @@ class TestExchangeBundle:
start_dt=start, start_dt=start,
end_dt=end end_dt=end
) )
periods = exchange_bundle.get_calendar_periods_range( print('found {} rows for {} ingestion\n{}'.format(
start, end, data_frequency len(arrays[0]), asset.symbol, arrays[0])
) )
dx = get_df_from_arrays(arrays[0], periods)
set_print_settings()
print('found {} rows for last ingestion:\n{}\n{}'.format(
len(dx), dx.head(10), dx.tail(10)
))
pass pass
def test_ingest_minute_all(self): def test_ingest_minute_all(self):
@@ -109,7 +101,7 @@ class TestExchangeBundle:
# data_frequency = 'daily' # data_frequency = 'daily'
# include_symbols = 'neo_btc,bch_btc,eth_btc' # include_symbols = 'neo_btc,bch_btc,eth_btc'
exchange_name = 'binance' exchange_name = 'bitfinex'
data_frequency = 'minute' data_frequency = 'minute'
exchange = get_exchange(exchange_name) exchange = get_exchange(exchange_name)
@@ -230,14 +222,9 @@ class TestExchangeBundle:
start_dt=start, start_dt=start,
end_dt=end end_dt=end
) )
periods = exchange_bundle.get_calendar_periods_range( print('found {} rows for {} ingestion\n{}'.format(
start, end, data_frequency len(arrays[0]), asset.symbol, arrays[0])
) )
dx = get_df_from_arrays(arrays, periods)
print('found {} rows for last ingestion'.format(
len(dx)
))
pass pass
def test_daily_data_to_minute_table(self): def test_daily_data_to_minute_table(self):
@@ -303,22 +290,17 @@ class TestExchangeBundle:
for asset in assets: for asset in assets:
sid = asset.sid sid = asset.sid
arrays = reader.load_raw_arrays( daily_values = reader.load_raw_arrays(
fields=['open', 'high', 'low', 'close', 'volume'], fields=['open', 'high', 'low', 'close', 'volume'],
start_dt=start, start_dt=start,
end_dt=end, end_dt=end,
sids=[sid], sids=[sid],
) )
periods = exchange_bundle.get_calendar_periods_range(
start, end, data_frequency
)
dx = get_df_from_arrays(arrays, periods)
print('found {} rows for last ingestion'.format( print('found {} rows for last ingestion'.format(
len(dx) len(daily_values[0]))
)) )
pass pass
def test_minute_bundle(self): def test_minute_bundle(self):
# exchange_name = 'poloniex' # exchange_name = 'poloniex'
+4 -37
View File
@@ -5,8 +5,7 @@ from catalyst.exchange.utils.stats_utils import set_print_settings
from .base import BaseExchangeTestCase from .base import BaseExchangeTestCase
from catalyst.exchange.ccxt.ccxt_exchange import CCXT from catalyst.exchange.ccxt.ccxt_exchange import CCXT
from catalyst.exchange.exchange_execution import ExchangeLimitOrder from catalyst.exchange.exchange_execution import ExchangeLimitOrder
from catalyst.exchange.utils.exchange_utils import get_exchange_auth, \ from catalyst.exchange.utils.exchange_utils import get_exchange_auth
get_trades_df, candles_from_trades
from catalyst.finance.order import Order from catalyst.finance.order import Order
log = Logger('test_ccxt') log = Logger('test_ccxt')
@@ -15,13 +14,12 @@ log = Logger('test_ccxt')
class TestCCXT(BaseExchangeTestCase): class TestCCXT(BaseExchangeTestCase):
@classmethod @classmethod
def setup(self): def setup(self):
exchange_name = 'binance' exchange_name = 'bittrex'
auth = get_exchange_auth(exchange_name) auth = get_exchange_auth(exchange_name)
self.exchange = CCXT( self.exchange = CCXT(
exchange_name=exchange_name, exchange_name=exchange_name,
key=auth['key'], key=auth['key'],
secret=auth['secret'], secret=auth['secret'],
password=None,
base_currency='usdt', base_currency='usdt',
) )
self.exchange.init() self.exchange.init()
@@ -60,9 +58,9 @@ class TestCCXT(BaseExchangeTestCase):
log.info('retrieving candles') log.info('retrieving candles')
candles = self.exchange.get_candles( candles = self.exchange.get_candles(
freq='1T', freq='1T',
assets=[self.exchange.get_asset('eng_eth')], assets=[self.exchange.get_asset('eth_btc')],
bar_count=200, bar_count=200,
start_dt=pd.to_datetime('2017-09-01', utc=True), # start_dt=pd.to_datetime('2017-09-01', utc=True),
) )
for asset in candles: for asset in candles:
@@ -92,37 +90,6 @@ class TestCCXT(BaseExchangeTestCase):
assert trades assert trades
pass pass
def test_validate_volume(self):
asset = self.exchange.get_asset('eng_eth')
candles = self.exchange.get_candles(
freq='1T',
assets=[asset],
bar_count=10,
)
df = pd.DataFrame(candles[asset])
df.set_index('last_traded', drop=True, inplace=True)
df.drop_duplicates()
df.sort_index(inplace=True, ascending=False)
assert candles
start_dt = df.index[-1]
trades = self.exchange.get_trades(
asset, start_dt=start_dt, my_trades=False
)
assert trades
trades_df = get_trades_df(trades)
df2 = candles_from_trades(trades_df, '1T')
set_print_settings()
log.info(
'comparing candles / resampled trades:\n{}\n{}'.format(
df, df2
)
)
pass
def test_get_executed_order(self): def test_get_executed_order(self):
log.info('retrieving executed order') log.info('retrieving executed order')
asset = self.exchange.get_asset('eng_eth') asset = self.exchange.get_asset('eng_eth')
-8
View File
@@ -1,8 +0,0 @@
from catalyst.exchange.utils.factory import get_exchange
class TestConfig:
def test_create_config(self):
exchange = get_exchange('binance', skip_init=True)
config = exchange.create_exchange_config()
pass
+1 -1
View File
@@ -9,7 +9,7 @@ from catalyst.exchange.exchange_data_portal import (
) )
from catalyst.exchange.utils.exchange_utils import get_common_assets from catalyst.exchange.utils.exchange_utils import get_common_assets
from catalyst.exchange.utils.factory import get_exchanges from catalyst.exchange.utils.factory import get_exchanges
from .test_utils import rnd_history_date_days, rnd_bar_count from test_utils import rnd_history_date_days, rnd_bar_count
log = Logger('test_bitfinex') log = Logger('test_bitfinex')
@@ -197,7 +197,6 @@ class TestSuiteBundle:
# population=exchange_population, # population=exchange_population,
# features=[bundle], # features=[bundle],
# ) # Type: list[Exchange] # ) # Type: list[Exchange]
# TODO: currently focusing on Binance, try other exchanges
exchanges = [get_exchange('poloniex', skip_init=True)] exchanges = [get_exchange('poloniex', skip_init=True)]
data_portal = TestSuiteBundle.get_data_portal(exchanges) data_portal = TestSuiteBundle.get_data_portal(exchanges)
@@ -205,20 +204,17 @@ class TestSuiteBundle:
exchange.init() exchange.init()
frequencies = exchange.get_candle_frequencies(data_frequency) frequencies = exchange.get_candle_frequencies(data_frequency)
# freq = random.sample(frequencies, 1)[0] freq = random.sample(frequencies, 1)[0]
freq = '5T'
rnd = random.SystemRandom() rnd = random.SystemRandom()
# field = rnd.choice(['open', 'high', 'low', 'close', 'volume']) # field = rnd.choice(['open', 'high', 'low', 'close', 'volume'])
field = rnd.choice(['close']) field = rnd.choice(['volume'])
# bar_count = random.randint(3, 6) bar_count = random.randint(3, 6)
bar_count = 5
# assets = select_random_assets( assets = select_random_assets(
# exchange.assets, asset_population exchange.assets, asset_population
# ) )
assets = [exchange.get_asset('bch_eth')] end_dt = None
end_dt = pd.to_datetime('2018-03-01', utc=True)
for asset in assets: for asset in assets:
attribute = 'end_{}'.format(data_frequency) attribute = 'end_{}'.format(data_frequency)
asset_end_dt = getattr(asset, attribute) asset_end_dt = getattr(asset, attribute)
@@ -5,28 +5,63 @@ from logging import Logger, WARNING
from time import sleep from time import sleep
import pandas as pd import pandas as pd
from catalyst.assets._assets import TradingPair
from logbook import TestHandler from logbook import TestHandler
from catalyst.assets._assets import TradingPair from catalyst.exchange.exchange_errors import ExchangeRequestError
from catalyst.exchange.exchange_execution import ExchangeLimitOrder from catalyst.exchange.exchange_execution import ExchangeLimitOrder
from catalyst.exchange.utils.exchange_utils import get_exchange_folder from catalyst.exchange.utils.exchange_utils import get_exchange_folder
from catalyst.exchange.utils.factory import get_exchanges, get_exchange
from catalyst.exchange.utils.test_utils import select_random_exchanges, \ from catalyst.exchange.utils.test_utils import select_random_exchanges, \
select_random_assets handle_exchange_error, select_random_assets
from catalyst.testing import ZiplineTestCase from catalyst.testing import ZiplineTestCase
from catalyst.testing.fixtures import WithLogger from catalyst.testing.fixtures import WithLogger
from catalyst.exchange.utils.factory import get_exchanges, get_exchange
log = Logger('TestSuiteExchange') log = Logger('TestSuiteExchange')
class TestSuiteExchange(WithLogger, ZiplineTestCase): class TestSuiteExchange(WithLogger, ZiplineTestCase):
def _test_markets_exchange(self, exchange, attempts=0):
assets = None
try:
exchange.init()
# Verify that the assets and markets are populated
if not exchange.markets:
raise ValueError(
'no markets found'
)
if not exchange.assets:
raise ValueError(
'no assets derived from markets'
)
assets = exchange.assets
except ExchangeRequestError as e:
sleep(5)
if attempts > 5:
handle_exchange_error(exchange, e)
else:
print(
're-trying an exchange request {} {}'.format(
exchange.name, attempts
)
)
self._test_markets_exchange(exchange, attempts + 1)
except Exception as e:
handle_exchange_error(exchange, e)
return assets
def test_markets(self): def test_markets(self):
population = 3 population = 3
results = dict() results = dict()
exchanges = select_random_exchanges(population) # Type: list[Exchange] exchanges = select_random_exchanges(population) # Type: list[Exchange]
for exchange in exchanges: for exchange in exchanges:
exchange.init()
assets = self._test_markets_exchange(exchange) assets = self._test_markets_exchange(exchange)
if assets is not None: if assets is not None:
+3 -2
View File
@@ -1,5 +1,6 @@
from catalyst.marketplace.marketplace import Marketplace from catalyst.marketplace.marketplace import Marketplace
from catalyst.testing.fixtures import WithLogger, ZiplineTestCase from catalyst.testing.fixtures import WithLogger, ZiplineTestCase
import pandas as pd
class TestMarketplace(WithLogger, ZiplineTestCase): class TestMarketplace(WithLogger, ZiplineTestCase):
@@ -15,12 +16,12 @@ class TestMarketplace(WithLogger, ZiplineTestCase):
def test_subscribe(self): def test_subscribe(self):
marketplace = Marketplace() marketplace = Marketplace()
marketplace.subscribe('marketcap') marketplace.subscribe('marketcap2222')
pass pass
def test_ingest(self): def test_ingest(self):
marketplace = Marketplace() marketplace = Marketplace()
ds_def = marketplace.ingest('marketcap') ds_def = marketplace.ingest('github')
pass pass
def test_publish(self): def test_publish(self):