mirror of
https://github.com/wassname/catalyst.git
synced 2026-07-22 12:40:30 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
65c6322ba5 | ||
|
|
4a2d5678ad | ||
|
|
06399caa2b | ||
|
|
4c84ea8efc | ||
|
|
c85e698ee2 | ||
|
|
423e30da1e | ||
|
|
c29b1ef3c1 | ||
|
|
17f9906df4 | ||
|
|
41b5135ed4 | ||
|
|
af85ee31c9 | ||
|
|
132dffd239 | ||
|
|
887a7cc825 | ||
|
|
22249506e6 | ||
|
|
b979ffd123 | ||
|
|
0db9950347 | ||
|
|
7c4467d800 | ||
|
|
30dbeaa5fb | ||
|
|
4d6837b5d6 | ||
|
|
098a4c4fc6 | ||
|
|
f5cb6e38d6 | ||
|
|
1bd65397b6 | ||
|
|
c768b207bc | ||
|
|
e18686d5c5 | ||
|
|
b7779cf363 | ||
|
|
28819b8a32 | ||
|
|
a56d7f34c7 | ||
|
|
9f0b3303f1 | ||
|
|
9d7a35658b | ||
|
|
c58cebd1eb | ||
|
|
027cdba474 | ||
|
|
d223529100 | ||
|
|
1e02506ab4 | ||
|
|
2a97ade68e | ||
|
|
9648767e9a | ||
|
|
98449b2088 | ||
|
|
91d16aba3b | ||
|
|
9eb649371b | ||
|
|
7f2ded65bc | ||
|
|
b76b4458cb | ||
|
|
decbdbf6ea | ||
|
|
685ce25b85 | ||
|
|
1cafcc1417 | ||
|
|
0d77854782 | ||
|
|
4cb8d54d97 | ||
|
|
7b796a4276 | ||
|
|
41a4c7072f | ||
|
|
11302b3af9 | ||
|
|
5bb7eed072 | ||
|
|
dbf3b6e6b2 | ||
|
|
3e69449a6b | ||
|
|
69731b653d | ||
|
|
127d779eb1 | ||
|
|
8d86a5548f | ||
|
|
0a37cdec5b | ||
|
|
8f7d678170 | ||
|
|
1de084a08f | ||
|
|
93ca4e990d | ||
|
|
4694372496 | ||
|
|
f0606b5ea4 | ||
|
|
b0dce13672 | ||
|
|
fc9837b678 | ||
|
|
5de89549ee | ||
|
|
586d7f2954 | ||
|
|
218dc0bafd | ||
|
|
89c080fce7 | ||
|
|
4a794aa035 | ||
|
|
cb4668f093 | ||
|
|
6092471180 | ||
|
|
09068a4c37 | ||
|
|
ed406a30ff | ||
|
|
2d5d2b21ee |
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
#
|
#
|
||||||
# Dockerfile for an image with the currently checked out version of catalyst installed. To build:
|
# Dockerfile for an image with the currently checked out version of catalyst installed. To build:
|
||||||
#
|
#
|
||||||
# docker build -t quantopian/catalyst .
|
# docker build -t enigmampc/catalyst .
|
||||||
#
|
#
|
||||||
# To run the container:
|
# To run the container:
|
||||||
#
|
#
|
||||||
# docker run -v /path/to/your/notebooks:/projects -v ~/.catalyst:/root/.catalyst -p 8888:8888/tcp --name catalyst -it quantopian/catalyst
|
# docker run -v /path/to/your/notebooks:/projects -v ~/.catalyst:/root/.catalyst -p 8888:8888/tcp --name catalyst -it enigmampc/catalyst
|
||||||
#
|
#
|
||||||
# To access Jupyter when running docker locally (you may need to add NAT rules):
|
# To access Jupyter when running docker locally (you may need to add NAT rules):
|
||||||
#
|
#
|
||||||
|
|||||||
+5
-5
@@ -1,15 +1,15 @@
|
|||||||
#
|
#
|
||||||
# Dockerfile for an image with the currently checked out version of catalyst installed. To build:
|
# Dockerfile for an image with the currently checked out version of catalyst installed. To build:
|
||||||
#
|
#
|
||||||
# docker build -t quantopian/catalystdev -f Dockerfile-dev .
|
# docker build -t enigmampc/catalystdev -f Dockerfile-dev .
|
||||||
#
|
#
|
||||||
# Note: the dev build requires a quantopian/catalyst image, which you can build as follows:
|
# Note: the dev build requires a enigmampc/catalyst image, which you can build as follows:
|
||||||
#
|
#
|
||||||
# docker build -t quantopian/catalyst -f Dockerfile .
|
# docker build -t enigmampc/catalyst -f Dockerfile .
|
||||||
#
|
#
|
||||||
# To run the container:
|
# To run the container:
|
||||||
#
|
#
|
||||||
# docker run -v /path/to/your/notebooks:/projects -v ~/.catalyst:/root/.catalyst -p 8888:8888/tcp --name catalystdev -it quantopian/catalystdev
|
# docker run -v /path/to/your/notebooks:/projects -v ~/.catalyst:/root/.catalyst -p 8888:8888/tcp --name catalystdev -it enigmampc/catalystdev
|
||||||
#
|
#
|
||||||
# To access Jupyter when running docker locally (you may need to add NAT rules):
|
# To access Jupyter when running docker locally (you may need to add NAT rules):
|
||||||
#
|
#
|
||||||
@@ -25,7 +25,7 @@
|
|||||||
#
|
#
|
||||||
# docker exec -it catalystdev catalyst run -f /projects/my_algo.py --start 2015-1-1 --end 2016-1-1 /projects/result.pickle
|
# docker exec -it catalystdev catalyst run -f /projects/my_algo.py --start 2015-1-1 --end 2016-1-1 /projects/result.pickle
|
||||||
#
|
#
|
||||||
FROM quantopian/catalyst
|
FROM enigmampc/catalyst
|
||||||
|
|
||||||
WORKDIR /catalyst
|
WORKDIR /catalyst
|
||||||
|
|
||||||
|
|||||||
+9
-3
@@ -5,6 +5,7 @@
|
|||||||
|
|
||||||
|version tag|
|
|version tag|
|
||||||
|version status|
|
|version status|
|
||||||
|
|forum|
|
||||||
|discord|
|
|discord|
|
||||||
|twitter|
|
|twitter|
|
||||||
|
|
||||||
@@ -22,9 +23,11 @@ visit `enigma.co <https://www.enigma.co>`_ to learn more about Catalyst.
|
|||||||
Catalyst builds on top of the well-established
|
Catalyst builds on top of the well-established
|
||||||
`Zipline <https://github.com/quantopian/zipline>`_ project. We did our best to
|
`Zipline <https://github.com/quantopian/zipline>`_ project. We did our best to
|
||||||
minimize structural changes to the general API to maximize compatibility with
|
minimize structural changes to the general API to maximize compatibility with
|
||||||
existing trading algorithms, developer knowledge, and tutorials. Join us on
|
existing trading algorithms, developer knowledge, and tutorials. Join us on the
|
||||||
`Discord <https://discord.gg/SJK32GY>`_ where we have a *#catalyst_dev* channel
|
`Catalyst Forum <https://catalyst.enigma.co/>`_ for questions around Catalyst,
|
||||||
for questions around Catalyst, algorithmic trading and technical support.
|
algorithmic trading and technical support. We also have a
|
||||||
|
`Discord <https://discord.gg/SJK32GY>`_ group with the *#catalyst_dev* and
|
||||||
|
*#catalyst_setup* dedicated channels.
|
||||||
|
|
||||||
Overview
|
Overview
|
||||||
========
|
========
|
||||||
@@ -60,6 +63,9 @@ Go to our `Documentation Website <https://enigmampc.github.io/catalyst/>`_.
|
|||||||
|
|
||||||
.. |version status| image:: https://img.shields.io/pypi/pyversions/enigma-catalyst.svg
|
.. |version status| image:: https://img.shields.io/pypi/pyversions/enigma-catalyst.svg
|
||||||
:target: https://pypi.python.org/pypi/enigma-catalyst
|
:target: https://pypi.python.org/pypi/enigma-catalyst
|
||||||
|
|
||||||
|
.. |forum| image:: https://img.shields.io/badge/forum-join-green.svg
|
||||||
|
:target: https://catalyst.enigma.co/
|
||||||
|
|
||||||
.. |discord| image:: https://img.shields.io/badge/discord-join%20chat-green.svg
|
.. |discord| image:: https://img.shields.io/badge/discord-join%20chat-green.svg
|
||||||
:target: https://discordapp.com/invite/SJK32GY
|
:target: https://discordapp.com/invite/SJK32GY
|
||||||
|
|||||||
+17
-381
@@ -14,7 +14,6 @@ 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__
|
||||||
@@ -506,370 +505,6 @@ 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',
|
||||||
@@ -945,7 +580,7 @@ def ingest_exchange(ctx, exchange_name, data_frequency, start, end,
|
|||||||
|
|
||||||
exchange_bundle = ExchangeBundle(exchange_name)
|
exchange_bundle = ExchangeBundle(exchange_name)
|
||||||
|
|
||||||
click.echo('Ingesting exchange bundle {}...'.format(exchange_name),
|
click.echo('Trying to ingest exchange bundle {}...'.format(exchange_name),
|
||||||
sys.stdout)
|
sys.stdout)
|
||||||
exchange_bundle.ingest(
|
exchange_bundle.ingest(
|
||||||
data_frequency=data_frequency,
|
data_frequency=data_frequency,
|
||||||
@@ -1132,12 +767,18 @@ 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()
|
||||||
@@ -1152,10 +793,8 @@ def ls(ctx):
|
|||||||
)
|
)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def subscribe(ctx, dataset):
|
def subscribe(ctx, dataset):
|
||||||
if dataset is None:
|
"""Subscribe to an existing dataset.
|
||||||
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)
|
||||||
|
|
||||||
@@ -1190,11 +829,8 @@ 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):
|
||||||
if dataset is None:
|
"""Ingest a dataset (requires subscription).
|
||||||
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)
|
||||||
|
|
||||||
@@ -1207,19 +843,17 @@ def ingest(ctx, dataset, data_frequency, start, end):
|
|||||||
)
|
)
|
||||||
@click.pass_context
|
@click.pass_context
|
||||||
def clean(ctx, dataset):
|
def clean(ctx, dataset):
|
||||||
if dataset is None:
|
"""Clean/Remove local data for a given dataset.
|
||||||
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()
|
||||||
|
|
||||||
@@ -1243,6 +877,8 @@ 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 "
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ import warnings
|
|||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
|
|
||||||
from pandas.tslib import normalize_date
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
@@ -564,7 +563,7 @@ cdef class BarData:
|
|||||||
})
|
})
|
||||||
|
|
||||||
cdef bool _is_stale_for_asset(self, asset, dt, adjusted_dt, data_portal):
|
cdef bool _is_stale_for_asset(self, asset, dt, adjusted_dt, data_portal):
|
||||||
session_label = normalize_date(dt) # FIXME
|
session_label = dt.normalize_date() # FIXME
|
||||||
|
|
||||||
if not asset.is_alive_for_session(session_label):
|
if not asset.is_alive_for_session(session_label):
|
||||||
return False
|
return False
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import logbook
|
|||||||
import pytz
|
import pytz
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from contextlib2 import ExitStack
|
from contextlib2 import ExitStack
|
||||||
from pandas.tseries.tools import normalize_date
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from itertools import chain, repeat
|
from itertools import chain, repeat
|
||||||
@@ -1345,7 +1344,7 @@ class TradingAlgorithm(object):
|
|||||||
# Make sure the asset exists, and that there is a last price for it.
|
# Make sure the asset exists, and that there is a last price for it.
|
||||||
# FIXME: we should use BarData's can_trade logic here, but I haven't
|
# FIXME: we should use BarData's can_trade logic here, but I haven't
|
||||||
# yet found a good way to do that.
|
# yet found a good way to do that.
|
||||||
normalized_date = normalize_date(self.datetime)
|
normalized_date = self.datetime.normalize()
|
||||||
|
|
||||||
if normalized_date < asset.start_date:
|
if normalized_date < asset.start_date:
|
||||||
raise CannotOrderDelistedAsset(
|
raise CannotOrderDelistedAsset(
|
||||||
@@ -1392,7 +1391,7 @@ class TradingAlgorithm(object):
|
|||||||
)
|
)
|
||||||
|
|
||||||
if asset.auto_close_date:
|
if asset.auto_close_date:
|
||||||
day = normalize_date(self.get_datetime())
|
day = self.get_datetime().normalize()
|
||||||
|
|
||||||
if day > min(asset.end_date, asset.auto_close_date):
|
if day > min(asset.end_date, asset.auto_close_date):
|
||||||
# If we are after the asset's end date or auto close date, warn
|
# If we are after the asset's end date or auto close date, warn
|
||||||
@@ -2475,7 +2474,7 @@ class TradingAlgorithm(object):
|
|||||||
"""
|
"""
|
||||||
Internal implementation of `pipeline_output`.
|
Internal implementation of `pipeline_output`.
|
||||||
"""
|
"""
|
||||||
today = normalize_date(self.get_datetime())
|
today = self.get_datetime().normalize()
|
||||||
data = NO_DATA = object()
|
data = NO_DATA = object()
|
||||||
try:
|
try:
|
||||||
data = self._pipeline_cache.unwrap(today)
|
data = self._pipeline_cache.unwrap(today)
|
||||||
|
|||||||
@@ -630,23 +630,28 @@ cdef class TradingPair(Asset):
|
|||||||
and whose second element is a tuple of all the attributes that should
|
and whose second element is a tuple of all the attributes that should
|
||||||
be serialized/deserialized during pickling.
|
be serialized/deserialized during pickling.
|
||||||
"""
|
"""
|
||||||
#TODO: make sure that all fields set there
|
# added arguments for catalyst
|
||||||
return (self.__class__, (self.symbol,
|
return (self.__class__, (self.symbol,
|
||||||
self.exchange,
|
self.exchange,
|
||||||
self.start_date,
|
self.start_date,
|
||||||
self.asset_name,
|
self.asset_name,
|
||||||
self.sid,
|
self.sid,
|
||||||
self.leverage,
|
self.leverage,
|
||||||
|
self.end_daily,
|
||||||
|
self.end_minute,
|
||||||
self.end_date,
|
self.end_date,
|
||||||
|
self.exchange_symbol,
|
||||||
self.first_traded,
|
self.first_traded,
|
||||||
self.auto_close_date,
|
self.auto_close_date,
|
||||||
self.exchange_full,
|
self.exchange_full,
|
||||||
self.min_trade_size,
|
self.min_trade_size,
|
||||||
self.max_trade_size,
|
self.max_trade_size,
|
||||||
|
self.maker,
|
||||||
|
self.taker,
|
||||||
self.lot,
|
self.lot,
|
||||||
self.decimals,
|
self.decimals,
|
||||||
self.taker,
|
self.trading_state,
|
||||||
self.maker))
|
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)
|
||||||
|
|||||||
@@ -24,9 +24,7 @@ AUTO_INGEST = False
|
|||||||
|
|
||||||
AUTH_SERVER = 'https://data.enigma.co'
|
AUTH_SERVER = 'https://data.enigma.co'
|
||||||
|
|
||||||
# TODO: switch to mainnet
|
ETH_REMOTE_NODE = 'https://mainnet.infura.io'
|
||||||
ETH_REMOTE_NODE = 'https://ropsten.infura.io/'
|
|
||||||
|
|
||||||
|
|
||||||
MARKETPLACE_CONTRACT = 'https://raw.githubusercontent.com/enigmampc/' \
|
MARKETPLACE_CONTRACT = 'https://raw.githubusercontent.com/enigmampc/' \
|
||||||
'catalyst/master/catalyst/marketplace/' \
|
'catalyst/master/catalyst/marketplace/' \
|
||||||
@@ -36,11 +34,13 @@ MARKETPLACE_CONTRACT_ABI = 'https://raw.githubusercontent.com/enigmampc/' \
|
|||||||
'catalyst/master/catalyst/marketplace/' \
|
'catalyst/master/catalyst/marketplace/' \
|
||||||
'contract_marketplace_abi.json'
|
'contract_marketplace_abi.json'
|
||||||
|
|
||||||
# TODO: switch to mainnet
|
ENIGMA_CONTRACT = 'https://raw.githubusercontent.com/enigmampc/' \
|
||||||
ENIGMA_CONTRACT = 'https://raw.githubusercontent.com/enigmampc/catalyst/' \
|
'catalyst/master/catalyst/marketplace/' \
|
||||||
'master/catalyst/marketplace/' \
|
|
||||||
'contract_enigma_address.txt'
|
'contract_enigma_address.txt'
|
||||||
|
|
||||||
ENIGMA_CONTRACT_ABI = 'https://raw.githubusercontent.com/enigmampc/' \
|
ENIGMA_CONTRACT_ABI = 'https://raw.githubusercontent.com/enigmampc/' \
|
||||||
'catalyst/master/catalyst/marketplace/' \
|
'catalyst/master/catalyst/marketplace/' \
|
||||||
'contract_enigma_abi.json'
|
'contract_enigma_abi.json'
|
||||||
|
|
||||||
|
SUPPORTED_WALLETS = ['metamask', 'ledger', 'trezor', 'bitbox', 'keystore',
|
||||||
|
'key']
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ import numpy as np
|
|||||||
from numpy import float64, int64, nan
|
from numpy import float64, int64, nan
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from pandas import isnull
|
from pandas import isnull
|
||||||
from pandas.tslib import normalize_date
|
|
||||||
from six import iteritems
|
from six import iteritems
|
||||||
from six.moves import reduce
|
from six.moves import reduce
|
||||||
|
|
||||||
@@ -439,7 +438,7 @@ class DataPortal(object):
|
|||||||
(isinstance(asset, (Asset, ContinuousFuture))))
|
(isinstance(asset, (Asset, ContinuousFuture))))
|
||||||
|
|
||||||
def _get_fetcher_value(self, asset, field, dt):
|
def _get_fetcher_value(self, asset, field, dt):
|
||||||
day = normalize_date(dt)
|
day = dt.normalize()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
return \
|
return \
|
||||||
@@ -1130,7 +1129,7 @@ class DataPortal(object):
|
|||||||
if self._asset_start_dates[sid] > dt:
|
if self._asset_start_dates[sid] > dt:
|
||||||
raise NoTradeDataAvailableTooEarly(
|
raise NoTradeDataAvailableTooEarly(
|
||||||
sid=sid,
|
sid=sid,
|
||||||
dt=normalize_date(dt),
|
dt=dt.normalize(),
|
||||||
start_dt=start_date
|
start_dt=start_date
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1138,7 +1137,7 @@ class DataPortal(object):
|
|||||||
if self._asset_end_dates[sid] < dt:
|
if self._asset_end_dates[sid] < dt:
|
||||||
raise NoTradeDataAvailableTooLate(
|
raise NoTradeDataAvailableTooLate(
|
||||||
sid=sid,
|
sid=sid,
|
||||||
dt=normalize_date(dt),
|
dt=dt.normalize(),
|
||||||
end_dt=end_date
|
end_dt=end_date
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -1262,7 +1261,7 @@ class DataPortal(object):
|
|||||||
if self._extra_source_df is None:
|
if self._extra_source_df is None:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
day = normalize_date(dt)
|
day = dt.normalize()
|
||||||
|
|
||||||
if day in self._extra_source_df.index:
|
if day in self._extra_source_df.index:
|
||||||
assets = self._extra_source_df.loc[day]['sid']
|
assets = self._extra_source_df.loc[day]['sid']
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ from abc import (
|
|||||||
from numpy import concatenate
|
from numpy import concatenate
|
||||||
from lru import LRU
|
from lru import LRU
|
||||||
from pandas import isnull
|
from pandas import isnull
|
||||||
from pandas.tslib import normalize_date
|
|
||||||
from toolz import sliding_window
|
from toolz import sliding_window
|
||||||
|
|
||||||
from six import with_metaclass
|
from six import with_metaclass
|
||||||
@@ -93,8 +92,8 @@ class HistoryCompatibleUSEquityAdjustmentReader(object):
|
|||||||
The adjustments as a dict of loc -> Float64Multiply
|
The adjustments as a dict of loc -> Float64Multiply
|
||||||
"""
|
"""
|
||||||
sid = int(asset)
|
sid = int(asset)
|
||||||
start = normalize_date(dts[0])
|
start = dts[0].normalize()
|
||||||
end = normalize_date(dts[-1])
|
end = dts[-1].normalize()
|
||||||
adjs = {}
|
adjs = {}
|
||||||
if field != 'volume':
|
if field != 'volume':
|
||||||
mergers = self._adjustments_reader.get_adjustments_for_sid(
|
mergers = self._adjustments_reader.get_adjustments_for_sid(
|
||||||
|
|||||||
@@ -49,7 +49,6 @@ from pandas import (
|
|||||||
to_datetime,
|
to_datetime,
|
||||||
Timestamp,
|
Timestamp,
|
||||||
)
|
)
|
||||||
from pandas.tslib import iNaT
|
|
||||||
from six import (
|
from six import (
|
||||||
iteritems,
|
iteritems,
|
||||||
string_types,
|
string_types,
|
||||||
@@ -422,7 +421,7 @@ class BcolzDailyBarWriter(object):
|
|||||||
)
|
)
|
||||||
|
|
||||||
full_table.attrs['first_trading_day'] = (
|
full_table.attrs['first_trading_day'] = (
|
||||||
earliest_date if earliest_date is not None else iNaT
|
earliest_date if earliest_date is not None else NaT
|
||||||
)
|
)
|
||||||
|
|
||||||
full_table.attrs['first_row'] = first_row
|
full_table.attrs['first_row'] = first_row
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ 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
|
||||||
|
|||||||
@@ -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 xrange(n_portfolios):
|
for p in range(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)
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ def handle_data(context, data):
|
|||||||
context.asset,
|
context.asset,
|
||||||
fields='price',
|
fields='price',
|
||||||
bar_count=20,
|
bar_count=20,
|
||||||
frequency='2H'
|
frequency='30T'
|
||||||
)
|
)
|
||||||
last_traded = prices.index[-1]
|
last_traded = prices.index[-1]
|
||||||
log.info('last candle date: {}'.format(last_traded))
|
log.info('last candle date: {}'.format(last_traded))
|
||||||
|
|||||||
@@ -190,6 +190,9 @@ class CCXT(Exchange):
|
|||||||
if data_frequency == 'minute' and not freq.endswith('T'):
|
if data_frequency == 'minute' and not freq.endswith('T'):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
elif data_frequency == 'hourly' and not freq.endswith('D'):
|
||||||
|
continue
|
||||||
|
|
||||||
elif data_frequency == 'daily' and not freq.endswith('D'):
|
elif data_frequency == 'daily' and not freq.endswith('D'):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
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
|
||||||
@@ -12,13 +11,15 @@ 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, LastCandleTooEarlyError, \
|
NoDataAvailableOnExchange, NoValueForField, \
|
||||||
|
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, \
|
||||||
|
get_candles_number_from_minutes
|
||||||
from catalyst.exchange.utils.exchange_utils import get_exchange_symbols, \
|
from catalyst.exchange.utils.exchange_utils import get_exchange_symbols, \
|
||||||
resample_history_df, has_bundle
|
resample_history_df, has_bundle, get_candles_df
|
||||||
from logbook import Logger
|
from logbook import Logger
|
||||||
|
|
||||||
log = Logger('Exchange', level=LOG_LEVEL)
|
log = Logger('Exchange', level=LOG_LEVEL)
|
||||||
@@ -198,12 +199,8 @@ class Exchange:
|
|||||||
)
|
)
|
||||||
assets.append(asset)
|
assets.append(asset)
|
||||||
|
|
||||||
except SymbolNotFoundOnExchange:
|
except SymbolNotFoundOnExchange as e:
|
||||||
log.debug(
|
log.warn(e)
|
||||||
'skipping non-existent market {} {}'.format(
|
|
||||||
self.name, symbol
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return assets
|
return assets
|
||||||
|
|
||||||
def get_asset(self, symbol, data_frequency=None, is_exchange_symbol=False,
|
def get_asset(self, symbol, data_frequency=None, is_exchange_symbol=False,
|
||||||
@@ -256,7 +253,8 @@ 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)
|
||||||
)
|
)
|
||||||
@@ -505,49 +503,60 @@ 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)
|
||||||
|
kExtra_minutes_candles = 150
|
||||||
|
requested_bar_count = bar_count + \
|
||||||
|
get_candles_number_from_minutes(unit,
|
||||||
|
candle_size,
|
||||||
|
kExtra_minutes_candles)
|
||||||
|
|
||||||
# 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=bar_count,
|
bar_count=requested_bar_count,
|
||||||
end_dt=end_dt if not is_current else None,
|
end_dt=end_dt if not is_current else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
series = dict()
|
# candles sanity check - verify no empty candles were received:
|
||||||
for asset in candles:
|
for asset in candles:
|
||||||
if candles[asset]:
|
if not candles[asset]:
|
||||||
first_candle = candles[asset][0]
|
raise NoCandlesReceivedFromExchange(
|
||||||
asset_series = self.get_series_from_candles(
|
bar_count=requested_bar_count,
|
||||||
candles=candles[asset],
|
|
||||||
start_dt=first_candle['last_traded'],
|
|
||||||
end_dt=end_dt,
|
end_dt=end_dt,
|
||||||
data_frequency=frequency,
|
asset=asset,
|
||||||
field=field,
|
exchange=self.name)
|
||||||
)
|
|
||||||
|
|
||||||
delta_candle_size = candle_size * 60 if unit == 'H' else candle_size
|
# for avoiding unnecessary forward fill end_dt is taken back one second
|
||||||
# Checking to make sure that the dates match
|
forward_fill_till_dt = end_dt - timedelta(seconds=1)
|
||||||
delta = get_delta(delta_candle_size, data_frequency)
|
|
||||||
adj_end_dt = end_dt - delta
|
|
||||||
last_traded = asset_series.index[-1]
|
|
||||||
|
|
||||||
if last_traded < adj_end_dt:
|
series = get_candles_df(candles=candles,
|
||||||
raise LastCandleTooEarlyError(
|
field=field,
|
||||||
last_traded=last_traded,
|
freq=frequency,
|
||||||
end_dt=adj_end_dt,
|
bar_count=requested_bar_count,
|
||||||
exchange=self.name,
|
end_dt=forward_fill_till_dt)
|
||||||
)
|
|
||||||
else: # empty candle received
|
|
||||||
# because other assets are tz-aware, we need its tz to be set as well
|
|
||||||
asset_series = pd.Series([], index=pd.DatetimeIndex([], tz=pytz.utc))
|
|
||||||
|
|
||||||
|
# TODO: consider how to approach this edge case
|
||||||
series[asset] = asset_series
|
# delta_candle_size = candle_size * 60 if unit == 'H' else candle_size
|
||||||
|
# Checking to make sure that the dates match
|
||||||
|
# delta = get_delta(delta_candle_size, data_frequency)
|
||||||
|
# adj_end_dt = end_dt - delta
|
||||||
|
# last_traded = asset_series.index[-1]
|
||||||
|
# if last_traded < adj_end_dt:
|
||||||
|
# raise LastCandleTooEarlyError(
|
||||||
|
# last_traded=last_traded,
|
||||||
|
# end_dt=adj_end_dt,
|
||||||
|
# exchange=self.name,
|
||||||
|
# )
|
||||||
|
|
||||||
df = pd.DataFrame(series)
|
df = pd.DataFrame(series)
|
||||||
#df.dropna(inplace=True) # commented out due to issue 236
|
df.dropna(inplace=True)
|
||||||
|
|
||||||
return df
|
return df.tail(bar_count)
|
||||||
|
|
||||||
def get_history_window_with_bundle(self,
|
def get_history_window_with_bundle(self,
|
||||||
assets,
|
assets,
|
||||||
@@ -595,9 +604,10 @@ class Exchange:
|
|||||||
A dataframe containing the requested data.
|
A dataframe containing the requested data.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
# TODO: this function needs some work, we're currently using it just for benchmark data
|
# TODO: this function needs some work,
|
||||||
|
# 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, supported_freqs=['T', 'D']
|
||||||
)
|
)
|
||||||
adj_bar_count = candle_size * bar_count
|
adj_bar_count = candle_size * bar_count
|
||||||
try:
|
try:
|
||||||
@@ -621,7 +631,7 @@ class Exchange:
|
|||||||
start_dt = get_start_dt(end_dt, adj_bar_count, data_frequency)
|
start_dt = get_start_dt(end_dt, adj_bar_count, data_frequency)
|
||||||
trailing_dt = \
|
trailing_dt = \
|
||||||
series[asset].index[-1] + get_delta(1, data_frequency) \
|
series[asset].index[-1] + get_delta(1, data_frequency) \
|
||||||
if asset in series else start_dt
|
if asset in series else start_dt
|
||||||
|
|
||||||
# The get_history method supports multiple asset
|
# The get_history method supports multiple asset
|
||||||
# Use the original frequency to let each api optimize
|
# Use the original frequency to let each api optimize
|
||||||
|
|||||||
@@ -163,6 +163,25 @@ 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
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ 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_delta, get_start_dt, \
|
from catalyst.exchange.utils.datetime_utils import get_start_dt, \
|
||||||
get_period_label, get_month_start_end, get_year_start_end
|
get_period_label, get_month_start_end, get_year_start_end
|
||||||
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
|
save_exchange_symbols, mixin_market_params, get_catalyst_symbol
|
||||||
@@ -232,12 +232,12 @@ class ExchangeBundle:
|
|||||||
|
|
||||||
problem = '{name} ({start_dt} to {end_dt}) has empty ' \
|
problem = '{name} ({start_dt} to {end_dt}) has empty ' \
|
||||||
'periods: {dates}'.format(
|
'periods: {dates}'.format(
|
||||||
name=asset.symbol,
|
name=asset.symbol,
|
||||||
start_dt=asset.start_date.strftime(
|
start_dt=asset.start_date.strftime(
|
||||||
DATE_TIME_FORMAT),
|
DATE_TIME_FORMAT),
|
||||||
end_dt=end_dt.strftime(DATE_TIME_FORMAT),
|
end_dt=end_dt.strftime(DATE_TIME_FORMAT),
|
||||||
dates=[date.strftime(
|
dates=[date.strftime(
|
||||||
DATE_TIME_FORMAT) for date in dates])
|
DATE_TIME_FORMAT) for date in dates])
|
||||||
|
|
||||||
if empty_rows_behavior == 'warn':
|
if empty_rows_behavior == 'warn':
|
||||||
log.warn(problem)
|
log.warn(problem)
|
||||||
@@ -286,12 +286,12 @@ class ExchangeBundle:
|
|||||||
|
|
||||||
problem = '{name} ({start_dt} to {end_dt}) has {threshold} ' \
|
problem = '{name} ({start_dt} to {end_dt}) has {threshold} ' \
|
||||||
'identical close values on: {dates}'.format(
|
'identical close values on: {dates}'.format(
|
||||||
name=asset.symbol,
|
name=asset.symbol,
|
||||||
start_dt=asset.start_date.strftime(DATE_TIME_FORMAT),
|
start_dt=asset.start_date.strftime(DATE_TIME_FORMAT),
|
||||||
end_dt=end_dt.strftime(DATE_TIME_FORMAT),
|
end_dt=end_dt.strftime(DATE_TIME_FORMAT),
|
||||||
threshold=threshold,
|
threshold=threshold,
|
||||||
dates=[pd.to_datetime(date).strftime(DATE_TIME_FORMAT)
|
dates=[pd.to_datetime(date).strftime(DATE_TIME_FORMAT)
|
||||||
for date in dates])
|
for date in dates])
|
||||||
|
|
||||||
problems.append(problem)
|
problems.append(problem)
|
||||||
|
|
||||||
@@ -458,7 +458,7 @@ class ExchangeBundle:
|
|||||||
last_entry = None
|
last_entry = None
|
||||||
|
|
||||||
if start is None or \
|
if start is None or \
|
||||||
(earliest_trade is not None and earliest_trade > start):
|
(earliest_trade is not None and earliest_trade > start):
|
||||||
start = earliest_trade
|
start = earliest_trade
|
||||||
|
|
||||||
if last_entry is not None and (end is None or end > last_entry):
|
if last_entry is not None and (end is None or end > last_entry):
|
||||||
@@ -598,16 +598,41 @@ class ExchangeBundle:
|
|||||||
# we want to give an end_date far in time
|
# we want to give an end_date far in time
|
||||||
writer = self.get_writer(start_dt, end_dt, data_frequency)
|
writer = self.get_writer(start_dt, end_dt, data_frequency)
|
||||||
if show_breakdown:
|
if show_breakdown:
|
||||||
for asset in chunks:
|
if chunks:
|
||||||
|
for asset in chunks:
|
||||||
|
with maybe_show_progress(
|
||||||
|
chunks[asset],
|
||||||
|
show_progress,
|
||||||
|
label='Ingesting {frequency} price data for '
|
||||||
|
'{symbol} on {exchange}'.format(
|
||||||
|
exchange=self.exchange_name,
|
||||||
|
frequency=data_frequency,
|
||||||
|
symbol=asset.symbol
|
||||||
|
)) as it:
|
||||||
|
for chunk in it:
|
||||||
|
problems += self.ingest_ctable(
|
||||||
|
asset=chunk['asset'],
|
||||||
|
data_frequency=data_frequency,
|
||||||
|
period=chunk['period'],
|
||||||
|
writer=writer,
|
||||||
|
empty_rows_behavior='strip',
|
||||||
|
cleanup=True
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
all_chunks = list(chain.from_iterable(itervalues(chunks)))
|
||||||
|
# We sort the chunks by end date to ingest most recent data first
|
||||||
|
if all_chunks:
|
||||||
|
all_chunks.sort(
|
||||||
|
key=lambda chunk: pd.to_datetime(chunk['period'])
|
||||||
|
)
|
||||||
with maybe_show_progress(
|
with maybe_show_progress(
|
||||||
chunks[asset],
|
all_chunks,
|
||||||
show_progress,
|
show_progress,
|
||||||
label='Ingesting {frequency} price data for '
|
label='Ingesting {frequency} price data on '
|
||||||
'{symbol} on {exchange}'.format(
|
'{exchange}'.format(
|
||||||
exchange=self.exchange_name,
|
exchange=self.exchange_name,
|
||||||
frequency=data_frequency,
|
frequency=data_frequency,
|
||||||
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'],
|
||||||
@@ -617,30 +642,6 @@ class ExchangeBundle:
|
|||||||
empty_rows_behavior='strip',
|
empty_rows_behavior='strip',
|
||||||
cleanup=True
|
cleanup=True
|
||||||
)
|
)
|
||||||
else:
|
|
||||||
all_chunks = list(chain.from_iterable(itervalues(chunks)))
|
|
||||||
|
|
||||||
# We sort the chunks by end date to ingest most recent data first
|
|
||||||
all_chunks.sort(
|
|
||||||
key=lambda chunk: pd.to_datetime(chunk['period'])
|
|
||||||
)
|
|
||||||
with maybe_show_progress(
|
|
||||||
all_chunks,
|
|
||||||
show_progress,
|
|
||||||
label='Ingesting {frequency} price data on '
|
|
||||||
'{exchange}'.format(
|
|
||||||
exchange=self.exchange_name,
|
|
||||||
frequency=data_frequency,
|
|
||||||
)) as it:
|
|
||||||
for chunk in it:
|
|
||||||
problems += self.ingest_ctable(
|
|
||||||
asset=chunk['asset'],
|
|
||||||
data_frequency=data_frequency,
|
|
||||||
period=chunk['period'],
|
|
||||||
writer=writer,
|
|
||||||
empty_rows_behavior='strip',
|
|
||||||
cleanup=True
|
|
||||||
)
|
|
||||||
|
|
||||||
if show_report and len(problems) > 0:
|
if show_report and len(problems) > 0:
|
||||||
log.info('problems during ingestion:{}\n'.format(
|
log.info('problems during ingestion:{}\n'.format(
|
||||||
@@ -843,7 +844,6 @@ 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
|
||||||
-------
|
-------
|
||||||
|
|||||||
@@ -296,7 +296,7 @@ class DataPortalExchangeBacktest(DataPortalExchangeBase):
|
|||||||
bundle = self.exchange_bundles[exchange_name] # type: ExchangeBundle
|
bundle = self.exchange_bundles[exchange_name] # type: ExchangeBundle
|
||||||
|
|
||||||
freq, candle_size, unit, adj_data_frequency = get_frequency(
|
freq, candle_size, unit, adj_data_frequency = get_frequency(
|
||||||
frequency, data_frequency
|
frequency, data_frequency, supported_freqs=['T', 'D']
|
||||||
)
|
)
|
||||||
adj_bar_count = candle_size * bar_count
|
adj_bar_count = candle_size * bar_count
|
||||||
|
|
||||||
@@ -312,7 +312,7 @@ class DataPortalExchangeBacktest(DataPortalExchangeBase):
|
|||||||
algo_end_dt=self._last_available_session,
|
algo_end_dt=self._last_available_session,
|
||||||
)
|
)
|
||||||
|
|
||||||
start_dt = get_start_dt(end_dt, adj_bar_count, data_frequency)
|
start_dt = get_start_dt(end_dt, adj_bar_count, adj_data_frequency)
|
||||||
df = resample_history_df(pd.DataFrame(series), freq, field, start_dt)
|
df = resample_history_df(pd.DataFrame(series), freq, field, start_dt)
|
||||||
return df
|
return df
|
||||||
|
|
||||||
|
|||||||
@@ -322,3 +322,10 @@ 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()
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import calendar
|
import calendar
|
||||||
|
import math
|
||||||
import re
|
import re
|
||||||
from datetime import datetime, timedelta, date
|
from datetime import datetime, timedelta, date
|
||||||
|
|
||||||
@@ -248,9 +249,12 @@ def get_year_start_end(dt, first_day=None, last_day=None):
|
|||||||
return year_start, year_end
|
return year_start, year_end
|
||||||
|
|
||||||
|
|
||||||
def get_frequency(freq, data_frequency=None, supported_freqs=['D', 'T']):
|
def get_frequency(freq, data_frequency=None, supported_freqs=['D', 'H', 'T']):
|
||||||
"""
|
"""
|
||||||
Get the frequency parameters.
|
Takes an arbitrary candle size (e.g. 15T) and converts to the lowest
|
||||||
|
common denominator supported by the data bundles (e.g. 1T). The data
|
||||||
|
bundles only support 1T and 1D frequencies. If another frequency
|
||||||
|
is requested, Catalyst must request the underlying data and resample.
|
||||||
|
|
||||||
Notes
|
Notes
|
||||||
-----
|
-----
|
||||||
@@ -305,14 +309,14 @@ def get_frequency(freq, data_frequency=None, supported_freqs=['D', 'T']):
|
|||||||
data_frequency = 'minute'
|
data_frequency = 'minute'
|
||||||
|
|
||||||
elif unit.lower() == 'h':
|
elif unit.lower() == 'h':
|
||||||
|
data_frequency = 'minute'
|
||||||
|
|
||||||
if 'H' in supported_freqs:
|
if 'H' in supported_freqs:
|
||||||
unit = 'H'
|
unit = 'H'
|
||||||
alias = '{}H'.format(candle_size)
|
alias = '{}H'.format(candle_size)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
candle_size = candle_size * 60
|
candle_size = candle_size * 60
|
||||||
alias = '{}T'.format(candle_size)
|
alias = '{}T'.format(candle_size)
|
||||||
data_frequency = 'minute'
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
raise InvalidHistoryFrequencyAlias(freq=freq)
|
raise InvalidHistoryFrequencyAlias(freq=freq)
|
||||||
@@ -326,3 +330,33 @@ def from_ms_timestamp(ms):
|
|||||||
|
|
||||||
def get_epoch():
|
def get_epoch():
|
||||||
return pd.to_datetime('1970-1-1', utc=True)
|
return pd.to_datetime('1970-1-1', utc=True)
|
||||||
|
|
||||||
|
|
||||||
|
def get_candles_number_from_minutes(unit, candle_size, minutes):
|
||||||
|
"""
|
||||||
|
Get the number of bars needed for the given time interval
|
||||||
|
in minutes.
|
||||||
|
|
||||||
|
Notes
|
||||||
|
-----
|
||||||
|
Supports only "T", "D" and "H" units
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
----------
|
||||||
|
unit: str
|
||||||
|
candle_size : int
|
||||||
|
minutes: int
|
||||||
|
|
||||||
|
Returns
|
||||||
|
-------
|
||||||
|
int
|
||||||
|
|
||||||
|
"""
|
||||||
|
if unit == "T":
|
||||||
|
res = (float(minutes) / candle_size)
|
||||||
|
elif unit == "H":
|
||||||
|
res = (minutes / 60.0) / candle_size
|
||||||
|
else: # unit == "D"
|
||||||
|
res = (minutes / 1440.0) / candle_size
|
||||||
|
|
||||||
|
return int(math.ceil(res))
|
||||||
|
|||||||
@@ -734,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=None):
|
def get_candles_df(candles, field, freq, bar_count, end_dt):
|
||||||
all_series = dict()
|
all_series = dict()
|
||||||
|
|
||||||
for asset in candles:
|
for asset in candles:
|
||||||
|
|||||||
@@ -62,7 +62,6 @@ from __future__ import division
|
|||||||
import logbook
|
import logbook
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from pandas.tseries.tools import normalize_date
|
|
||||||
|
|
||||||
from catalyst.finance.performance.period import PerformancePeriod
|
from catalyst.finance.performance.period import PerformancePeriod
|
||||||
from catalyst.errors import NoFurtherDataError
|
from catalyst.errors import NoFurtherDataError
|
||||||
@@ -344,7 +343,7 @@ class PerformanceTracker(object):
|
|||||||
"""
|
"""
|
||||||
self.position_tracker.sync_last_sale_prices(dt, False, data_portal)
|
self.position_tracker.sync_last_sale_prices(dt, False, data_portal)
|
||||||
self.update_performance()
|
self.update_performance()
|
||||||
todays_date = normalize_date(dt)
|
todays_date = dt.normalize()
|
||||||
account = self.get_account(False)
|
account = self.get_account(False)
|
||||||
|
|
||||||
bench_returns = self.all_benchmark_returns.loc[todays_date:dt]
|
bench_returns = self.all_benchmark_returns.loc[todays_date:dt]
|
||||||
|
|||||||
@@ -18,7 +18,6 @@ import logbook
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from pandas.tseries.tools import normalize_date
|
|
||||||
|
|
||||||
from six import iteritems
|
from six import iteritems
|
||||||
|
|
||||||
@@ -80,7 +79,7 @@ class RiskMetricsCumulative(object):
|
|||||||
# on the first day.
|
# on the first day.
|
||||||
self.day_before_start = self.start_session - self.sessions.freq
|
self.day_before_start = self.start_session - self.sessions.freq
|
||||||
|
|
||||||
last_day = normalize_date(sim_params.end_session)
|
last_day = sim_params.end_session.normalize()
|
||||||
if last_day not in self.sessions:
|
if last_day not in self.sessions:
|
||||||
last_day = pd.tseries.index.DatetimeIndex(
|
last_day = pd.tseries.index.DatetimeIndex(
|
||||||
[last_day]
|
[last_day]
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ from functools import partial
|
|||||||
|
|
||||||
import logbook
|
import logbook
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from pandas.tslib import normalize_date
|
|
||||||
from six import string_types
|
from six import string_types
|
||||||
from sqlalchemy import create_engine
|
from sqlalchemy import create_engine
|
||||||
|
|
||||||
@@ -95,11 +94,24 @@ class TradingEnvironment(object):
|
|||||||
if not trading_calendar:
|
if not trading_calendar:
|
||||||
trading_calendar = get_calendar("NYSE")
|
trading_calendar = get_calendar("NYSE")
|
||||||
|
|
||||||
self.benchmark_returns, self.treasury_curves = load(
|
# todo: uncomment and add a well defined benchmark
|
||||||
trading_calendar.day,
|
# self.benchmark_returns, self.treasury_curves = load(
|
||||||
trading_calendar.schedule.index,
|
# trading_calendar.day,
|
||||||
self.bm_symbol,
|
# trading_calendar.schedule.index,
|
||||||
)
|
# self.bm_symbol,
|
||||||
|
# exchange=exchange,
|
||||||
|
# )
|
||||||
|
|
||||||
|
start_data = get_calendar('OPEN').first_trading_session
|
||||||
|
end_data = pd.Timestamp.utcnow()
|
||||||
|
treasure_cols = ['1month', '3month', '6month', '1year', '2year',
|
||||||
|
'3year', '5year', '7year', '10year', '20year', '30year']
|
||||||
|
self.benchmark_returns = pd.DataFrame(data=0.001,
|
||||||
|
index=pd.date_range(start_data, end_data),
|
||||||
|
columns=['close'])
|
||||||
|
self.treasury_curves = pd.DataFrame(data=0.001,
|
||||||
|
index=pd.date_range(start_data, end_data),
|
||||||
|
columns=treasure_cols)
|
||||||
|
|
||||||
self.exchange_tz = exchange_tz
|
self.exchange_tz = exchange_tz
|
||||||
|
|
||||||
@@ -151,8 +163,8 @@ class SimulationParameters(object):
|
|||||||
# chop off any minutes or hours on the given start and end dates,
|
# chop off any minutes or hours on the given start and end dates,
|
||||||
# as we only support session labels here (and we represent session
|
# as we only support session labels here (and we represent session
|
||||||
# labels as midnight UTC).
|
# labels as midnight UTC).
|
||||||
self._start_session = normalize_date(start_session)
|
self._start_session = start_session.normalize()
|
||||||
self._end_session = normalize_date(end_session)
|
self._end_session = end_session.normalize()
|
||||||
self._capital_base = capital_base
|
self._capital_base = capital_base
|
||||||
|
|
||||||
self._emission_rate = emission_rate
|
self._emission_rate = emission_rate
|
||||||
|
|||||||
@@ -14,7 +14,6 @@
|
|||||||
# limitations under the License.
|
# limitations under the License.
|
||||||
from contextlib2 import ExitStack
|
from contextlib2 import ExitStack
|
||||||
from logbook import Logger, Processor
|
from logbook import Logger, Processor
|
||||||
from pandas.tslib import normalize_date
|
|
||||||
from catalyst.protocol import BarData
|
from catalyst.protocol import BarData
|
||||||
from catalyst.utils.api_support import ZiplineAPI
|
from catalyst.utils.api_support import ZiplineAPI
|
||||||
from six import viewkeys
|
from six import viewkeys
|
||||||
@@ -229,7 +228,7 @@ class AlgorithmSimulator(object):
|
|||||||
elif action == SESSION_END:
|
elif action == SESSION_END:
|
||||||
# End of the session.
|
# End of the session.
|
||||||
if emission_rate == 'daily':
|
if emission_rate == 'daily':
|
||||||
handle_benchmark(normalize_date(dt))
|
handle_benchmark(dt).normalize()
|
||||||
execute_order_cancellation_policy()
|
execute_order_cancellation_policy()
|
||||||
|
|
||||||
yield self._get_daily_message(dt, algo, algo.perf_tracker)
|
yield self._get_daily_message(dt, algo, algo.perf_tracker)
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
0x7fAec9aaE31BE428DeAAE1be8195dF609079Fd10
|
0xf0ee6b27b759c9893ce4f094b49ad28fd15a23e4
|
||||||
File diff suppressed because one or more lines are too long
@@ -1 +1 @@
|
|||||||
0x3985f5de8fddf2e8f7705cd360b498bf35ebfbc4
|
0xa64927358a82254be92eb1f1cb01de68d1787004
|
||||||
@@ -7,6 +7,7 @@ import re
|
|||||||
import shutil
|
import shutil
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
|
import webbrowser
|
||||||
|
|
||||||
import bcolz
|
import bcolz
|
||||||
import logbook
|
import logbook
|
||||||
@@ -32,6 +33,7 @@ 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
|
||||||
@@ -67,7 +69,10 @@ class Marketplace:
|
|||||||
contract_url.info().get_content_charset()).strip())
|
contract_url.info().get_content_charset()).strip())
|
||||||
|
|
||||||
abi_url = urllib.urlopen(MARKETPLACE_CONTRACT_ABI)
|
abi_url = urllib.urlopen(MARKETPLACE_CONTRACT_ABI)
|
||||||
abi = json.load(abi_url)
|
abi_url = abi_url.read().decode(
|
||||||
|
abi_url.info().get_content_charset())
|
||||||
|
|
||||||
|
abi = json.loads(abi_url)
|
||||||
|
|
||||||
self.mkt_contract = self.web3.eth.contract(
|
self.mkt_contract = self.web3.eth.contract(
|
||||||
self.mkt_contract_address,
|
self.mkt_contract_address,
|
||||||
@@ -81,7 +86,10 @@ class Marketplace:
|
|||||||
contract_url.info().get_content_charset()).strip())
|
contract_url.info().get_content_charset()).strip())
|
||||||
|
|
||||||
abi_url = urllib.urlopen(ENIGMA_CONTRACT_ABI)
|
abi_url = urllib.urlopen(ENIGMA_CONTRACT_ABI)
|
||||||
abi = json.load(abi_url)
|
abi_url = abi_url.read().decode(
|
||||||
|
abi_url.info().get_content_charset())
|
||||||
|
|
||||||
|
abi = json.loads(abi_url)
|
||||||
|
|
||||||
self.eng_contract = self.web3.eth.contract(
|
self.eng_contract = self.web3.eth.contract(
|
||||||
self.eng_contract_address,
|
self.eng_contract_address,
|
||||||
@@ -124,9 +132,10 @@ class Marketplace:
|
|||||||
else:
|
else:
|
||||||
while True:
|
while True:
|
||||||
for i in range(0, len(self.addresses)):
|
for i in range(0, len(self.addresses)):
|
||||||
print('{}\t{}\t{}'.format(
|
print('{}\t{}\t{}\t{}'.format(
|
||||||
i,
|
i,
|
||||||
self.addresses[i]['pubAddr'],
|
self.addresses[i]['pubAddr'],
|
||||||
|
self.addresses[i]['wallet'].ljust(10),
|
||||||
self.addresses[i]['desc'])
|
self.addresses[i]['desc'])
|
||||||
)
|
)
|
||||||
address_i = int(input('Choose your address associated with '
|
address_i = int(input('Choose your address associated with '
|
||||||
@@ -141,10 +150,10 @@ class Marketplace:
|
|||||||
|
|
||||||
return address, address_i
|
return address, address_i
|
||||||
|
|
||||||
def sign_transaction(self, from_address, tx):
|
def sign_transaction(self, tx):
|
||||||
|
|
||||||
print('\nVisit https://www.myetherwallet.com/#offline-transaction and '
|
url = 'https://www.mycrypto.com/#offline-transaction'
|
||||||
'enter the following parameters:\n\n'
|
print('\nVisit {url} and 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'
|
||||||
@@ -153,7 +162,8 @@ 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(
|
||||||
_from=from_address,
|
url=url,
|
||||||
|
_from=tx['from'],
|
||||||
to=tx['to'],
|
to=tx['to'],
|
||||||
value=tx['value'],
|
value=tx['value'],
|
||||||
gas=tx['gas'],
|
gas=tx['gas'],
|
||||||
@@ -161,6 +171,8 @@ 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')
|
||||||
|
|
||||||
@@ -172,16 +184,17 @@ class Marketplace:
|
|||||||
def check_transaction(self, tx_hash):
|
def check_transaction(self, tx_hash):
|
||||||
|
|
||||||
if 'ropsten' in ETH_REMOTE_NODE:
|
if 'ropsten' in ETH_REMOTE_NODE:
|
||||||
etherscan = 'https://ropsten.etherscan.io/tx/{}'.format(
|
etherscan = 'https://ropsten.etherscan.io/tx/'
|
||||||
tx_hash)
|
elif 'rinkeby' in ETH_REMOTE_NODE:
|
||||||
|
etherscan = 'https://rinkeby.etherscan.io/tx/'
|
||||||
else:
|
else:
|
||||||
etherscan = 'https://etherscan.io/tx/{}'.format(tx_hash)
|
etherscan = 'https://etherscan.io/tx/'
|
||||||
|
etherscan = '{}{}'.format(etherscan, tx_hash)
|
||||||
|
|
||||||
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 = []
|
||||||
@@ -193,15 +206,44 @@ 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):
|
def subscribe(self, dataset=None):
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
@@ -292,13 +334,11 @@ class Marketplace:
|
|||||||
self.mkt_contract_address,
|
self.mkt_contract_address,
|
||||||
grains,
|
grains,
|
||||||
).buildTransaction(
|
).buildTransaction(
|
||||||
{'nonce': self.web3.eth.getTransactionCount(address)}
|
{'from': address,
|
||||||
|
'nonce': self.web3.eth.getTransactionCount(address)}
|
||||||
)
|
)
|
||||||
|
|
||||||
if 'ropsten' in ETH_REMOTE_NODE:
|
signed_tx = self.sign_transaction(tx)
|
||||||
tx['gas'] = min(int(tx['gas'] * 1.5), 4700000)
|
|
||||||
|
|
||||||
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))
|
||||||
@@ -333,13 +373,11 @@ class Marketplace:
|
|||||||
|
|
||||||
tx = self.mkt_contract.functions.subscribe(
|
tx = self.mkt_contract.functions.subscribe(
|
||||||
Web3.toHex(dataset),
|
Web3.toHex(dataset),
|
||||||
).buildTransaction(
|
).buildTransaction({
|
||||||
{'nonce': self.web3.eth.getTransactionCount(address)})
|
'from': address,
|
||||||
|
'nonce': self.web3.eth.getTransactionCount(address)})
|
||||||
|
|
||||||
if 'ropsten' in ETH_REMOTE_NODE:
|
signed_tx = self.sign_transaction(tx)
|
||||||
tx['gas'] = min(int(tx['gas'] * 1.5), 4700000)
|
|
||||||
|
|
||||||
signed_tx = self.sign_transaction(address, tx)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
tx_hash = '0x{}'.format(bin_hex(
|
tx_hash = '0x{}'.format(bin_hex(
|
||||||
@@ -392,17 +430,43 @@ 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')
|
||||||
merge_bundles(zsource, ztarget)
|
merge_bundles(zsource, ztarget)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
shutil.rmtree(bundle_folder, ignore_errors=True)
|
||||||
os.rename(tmp_bundle, bundle_folder)
|
os.rename(tmp_bundle, bundle_folder)
|
||||||
|
|
||||||
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()
|
||||||
|
|
||||||
@@ -440,20 +504,29 @@ class Marketplace:
|
|||||||
key = self.addresses[address_i]['key']
|
key = self.addresses[address_i]['key']
|
||||||
secret = self.addresses[address_i]['secret']
|
secret = self.addresses[address_i]['secret']
|
||||||
else:
|
else:
|
||||||
key, secret = get_key_secret(address)
|
key, secret = get_key_secret(address,
|
||||||
|
self.addresses[address_i]['wallet'])
|
||||||
|
|
||||||
headers = get_signed_headers(ds_name, key, secret)
|
headers = get_signed_headers(ds_name, key, secret)
|
||||||
log.debug('Starting download of dataset for ingestion...')
|
log.info('Starting download of dataset for ingestion...')
|
||||||
r = requests.post(
|
r = requests.post(
|
||||||
'{}/marketplace/ingest'.format(AUTH_SERVER),
|
'{}/marketplace/ingest'.format(AUTH_SERVER),
|
||||||
headers=headers,
|
headers=headers,
|
||||||
stream=True,
|
stream=True,
|
||||||
)
|
)
|
||||||
if r.status_code == 200:
|
if r.status_code == 200:
|
||||||
|
log.info('Dataset downloaded successfully. Processing dataset...')
|
||||||
target_path = get_temp_bundles_folder()
|
target_path = get_temp_bundles_folder()
|
||||||
try:
|
try:
|
||||||
decoder = MultipartDecoder.from_response(r)
|
decoder = MultipartDecoder.from_response(r)
|
||||||
|
# with maybe_show_progress(
|
||||||
|
# iter(decoder.parts),
|
||||||
|
# True,
|
||||||
|
# label='Processing files') as part:
|
||||||
|
counter = 1
|
||||||
for part in decoder.parts:
|
for part in decoder.parts:
|
||||||
|
log.info("Processing file {} of {}".format(
|
||||||
|
counter, len(decoder.parts)))
|
||||||
h = part.headers[b'Content-Disposition'].decode('utf-8')
|
h = part.headers[b'Content-Disposition'].decode('utf-8')
|
||||||
# Extracting the filename from the header
|
# Extracting the filename from the header
|
||||||
name = re.search(r'filename="(.*)"', h).group(1)
|
name = re.search(r'filename="(.*)"', h).group(1)
|
||||||
@@ -467,6 +540,7 @@ class Marketplace:
|
|||||||
f.write(part.content)
|
f.write(part.content)
|
||||||
|
|
||||||
self.process_temp_bundle(ds_name, filename)
|
self.process_temp_bundle(ds_name, filename)
|
||||||
|
counter += 1
|
||||||
|
|
||||||
except NonMultipartContentTypeException:
|
except NonMultipartContentTypeException:
|
||||||
response = r.json()
|
response = r.json()
|
||||||
@@ -498,17 +572,42 @@ class Marketplace:
|
|||||||
|
|
||||||
return df
|
return df
|
||||||
|
|
||||||
def clean(self, data_source_name, data_frequency=None):
|
def clean(self, ds_name=None, 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(data_source_name)
|
folder = get_data_source_folder(ds_name)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
folder = get_bundle_folder(data_source_name, data_frequency)
|
folder = get_bundle_folder(ds_name, data_frequency)
|
||||||
|
|
||||||
shutil.rmtree(folder)
|
shutil.rmtree(folder)
|
||||||
pass
|
|
||||||
|
|
||||||
def create_metadata(self, key, secret, ds_name, data_frequency, desc,
|
def create_metadata(self, key, secret, ds_name, data_frequency, desc,
|
||||||
has_history=True, has_live=True):
|
has_history=True, has_live=True):
|
||||||
@@ -544,7 +643,7 @@ class Marketplace:
|
|||||||
def register(self):
|
def register(self):
|
||||||
while True:
|
while True:
|
||||||
desc = input('Enter the name of the dataset to register: ')
|
desc = input('Enter the name of the dataset to register: ')
|
||||||
dataset = desc.lower()
|
dataset = desc.lower().strip()
|
||||||
provider_info = self.mkt_contract.functions.getDataProviderInfo(
|
provider_info = self.mkt_contract.functions.getDataProviderInfo(
|
||||||
Web3.toHex(dataset)
|
Web3.toHex(dataset)
|
||||||
).call()
|
).call()
|
||||||
@@ -600,7 +699,8 @@ class Marketplace:
|
|||||||
key = self.addresses[address_i]['key']
|
key = self.addresses[address_i]['key']
|
||||||
secret = self.addresses[address_i]['secret']
|
secret = self.addresses[address_i]['secret']
|
||||||
else:
|
else:
|
||||||
key, secret = get_key_secret(address)
|
key, secret = get_key_secret(address,
|
||||||
|
self.addresses[address_i]['wallet'])
|
||||||
|
|
||||||
grains = to_grains(price)
|
grains = to_grains(price)
|
||||||
|
|
||||||
@@ -609,13 +709,11 @@ class Marketplace:
|
|||||||
grains,
|
grains,
|
||||||
address,
|
address,
|
||||||
).buildTransaction(
|
).buildTransaction(
|
||||||
{'nonce': self.web3.eth.getTransactionCount(address)}
|
{'from': address,
|
||||||
|
'nonce': self.web3.eth.getTransactionCount(address)}
|
||||||
)
|
)
|
||||||
|
|
||||||
if 'ropsten' in ETH_REMOTE_NODE:
|
signed_tx = self.sign_transaction(tx)
|
||||||
tx['gas'] = min(int(tx['gas'] * 1.5), 4700000)
|
|
||||||
|
|
||||||
signed_tx = self.sign_transaction(address, tx)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
tx_hash = '0x{}'.format(
|
tx_hash = '0x{}'.format(
|
||||||
@@ -683,28 +781,34 @@ class Marketplace:
|
|||||||
key = match['key']
|
key = match['key']
|
||||||
secret = match['secret']
|
secret = match['secret']
|
||||||
else:
|
else:
|
||||||
key, secret = get_key_secret(provider_info[0])
|
key, secret = get_key_secret(provider_info[0], match['wallet'])
|
||||||
|
|
||||||
headers = get_signed_headers(dataset, key, secret)
|
|
||||||
filenames = glob.glob(os.path.join(datadir, '*.csv'))
|
filenames = glob.glob(os.path.join(datadir, '*.csv'))
|
||||||
|
|
||||||
if not filenames:
|
if not filenames:
|
||||||
raise MarketplaceNoCSVFiles(datadir=datadir)
|
raise MarketplaceNoCSVFiles(datadir=datadir)
|
||||||
|
|
||||||
files = []
|
files = []
|
||||||
for file in filenames:
|
for idx, file in enumerate(filenames):
|
||||||
|
log.info('Uploading file {} of {}: {}'.format(
|
||||||
|
idx+1, len(filenames), file))
|
||||||
|
files = []
|
||||||
files.append(('file', open(file, 'rb')))
|
files.append(('file', open(file, 'rb')))
|
||||||
|
|
||||||
r = requests.post('{}/marketplace/publish'.format(AUTH_SERVER),
|
headers = get_signed_headers(dataset, key, secret)
|
||||||
files=files,
|
r = requests.post('{}/marketplace/publish'.format(AUTH_SERVER),
|
||||||
headers=headers)
|
files=files,
|
||||||
|
headers=headers)
|
||||||
|
|
||||||
if r.status_code != 200:
|
if r.status_code != 200:
|
||||||
raise MarketplaceHTTPRequest(request='upload file',
|
raise MarketplaceHTTPRequest(request='upload file',
|
||||||
error=r.status_code)
|
error=r.status_code)
|
||||||
|
|
||||||
if 'error' in r.json():
|
if 'error' in r.json():
|
||||||
raise MarketplaceHTTPRequest(request='upload file',
|
raise MarketplaceHTTPRequest(request='upload file',
|
||||||
error=r.json()['error'])
|
error=r.json()['error'])
|
||||||
|
|
||||||
print('Dataset {} uploaded successfully.'.format(dataset))
|
log.info('File processed successfully.')
|
||||||
|
|
||||||
|
print('\nDataset {} uploaded and processed successfully.'.format(
|
||||||
|
dataset))
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import hashlib
|
import hashlib
|
||||||
import hmac
|
import hmac
|
||||||
|
import webbrowser
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
import time
|
import time
|
||||||
@@ -9,10 +10,10 @@ from catalyst.marketplace.marketplace_errors import (
|
|||||||
MarketplaceEmptySignature)
|
MarketplaceEmptySignature)
|
||||||
from catalyst.marketplace.utils.path_utils import (
|
from catalyst.marketplace.utils.path_utils import (
|
||||||
get_user_pubaddr, save_user_pubaddr)
|
get_user_pubaddr, save_user_pubaddr)
|
||||||
from catalyst.constants import AUTH_SERVER
|
from catalyst.constants import AUTH_SERVER, SUPPORTED_WALLETS
|
||||||
|
|
||||||
|
|
||||||
def get_key_secret(pubAddr, wallet='mew'):
|
def get_key_secret(pubAddr, wallet):
|
||||||
"""
|
"""
|
||||||
Obtain a new key/secret pair from authentication server
|
Obtain a new key/secret pair from authentication server
|
||||||
|
|
||||||
@@ -42,14 +43,22 @@ def get_key_secret(pubAddr, wallet='mew'):
|
|||||||
auth_type, auth_info = header.split(None, 1)
|
auth_type, auth_info = header.split(None, 1)
|
||||||
d = requests.utils.parse_dict_header(auth_info)
|
d = requests.utils.parse_dict_header(auth_info)
|
||||||
|
|
||||||
nonce = '0x{}'.format(d['nonce'])
|
nonce = 'Catalyst nonce: 0x{}'.format(d['nonce'])
|
||||||
|
|
||||||
|
if wallet in SUPPORTED_WALLETS:
|
||||||
|
url = 'https://www.mycrypto.com/signmsg.html'
|
||||||
|
|
||||||
if wallet == 'mew':
|
|
||||||
print('\nObtaining a key/secret pair to streamline all future '
|
print('\nObtaining a key/secret pair to streamline all future '
|
||||||
'requests with the authentication server.\n'
|
'requests with the authentication server.\n'
|
||||||
'Visit https://www.myetherwallet.com/signmsg.html and sign the '
|
'Visit {url} and sign the '
|
||||||
'following message:\n{}'.format(nonce))
|
'following message (copy the entire line, without the '
|
||||||
signature = input('Copy and Paste the "sig" field from '
|
'line break at the end):\n\n{nonce}'.format(
|
||||||
|
url=url,
|
||||||
|
nonce=nonce))
|
||||||
|
|
||||||
|
webbrowser.open_new(url)
|
||||||
|
|
||||||
|
signature = input('\nCopy and Paste the "sig" field from '
|
||||||
'the signature here (without the double quotes, '
|
'the signature here (without the double quotes, '
|
||||||
'only the HEX value):\n')
|
'only the HEX value):\n')
|
||||||
else:
|
else:
|
||||||
@@ -83,7 +92,8 @@ def get_key_secret(pubAddr, wallet='mew'):
|
|||||||
addresses = get_user_pubaddr()
|
addresses = get_user_pubaddr()
|
||||||
|
|
||||||
match = next((l for l in addresses if
|
match = next((l for l in addresses if
|
||||||
l['pubAddr'] == pubAddr), None)
|
l['pubAddr'].lower() == pubAddr.lower()), None)
|
||||||
|
|
||||||
match['key'] = response.json()['key']
|
match['key'] = response.json()['key']
|
||||||
match['secret'] = response.json()['secret']
|
match['secret'] = response.json()['secret']
|
||||||
|
|
||||||
@@ -113,7 +123,7 @@ def get_signed_headers(ds_name, key, secret):
|
|||||||
-------
|
-------
|
||||||
|
|
||||||
"""
|
"""
|
||||||
nonce = str(int(time.time()))
|
nonce = str(int(time.time() * 1000))
|
||||||
|
|
||||||
signature = hmac.new(
|
signature = hmac.new(
|
||||||
secret.encode('utf-8'),
|
secret.encode('utf-8'),
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
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):
|
||||||
@@ -27,10 +31,64 @@ 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))
|
||||||
os.rename(ztarget.rootdir, bak_dir)
|
shutil.move(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)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import os
|
|||||||
import json
|
import json
|
||||||
import tarfile
|
import tarfile
|
||||||
|
|
||||||
|
from catalyst.constants import SUPPORTED_WALLETS
|
||||||
from catalyst.utils.deprecate import deprecated
|
from catalyst.utils.deprecate import deprecated
|
||||||
from catalyst.utils.paths import data_root, ensure_directory
|
from catalyst.utils.paths import data_root, ensure_directory
|
||||||
from catalyst.marketplace.marketplace_errors import MarketplaceJSONError
|
from catalyst.marketplace.marketplace_errors import MarketplaceJSONError
|
||||||
@@ -131,17 +132,63 @@ def get_user_pubaddr(environ=None):
|
|||||||
try:
|
try:
|
||||||
d = data[0]['pubAddr']
|
d = data[0]['pubAddr']
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return [data, ]
|
data = [data, ]
|
||||||
|
|
||||||
|
changed = False
|
||||||
|
|
||||||
|
for idx, d in enumerate(data):
|
||||||
|
try:
|
||||||
|
if d['wallet'] not in SUPPORTED_WALLETS:
|
||||||
|
data[idx]['wallet'] = _choose_wallet(
|
||||||
|
d['pubAddr'], False)
|
||||||
|
changed = True
|
||||||
|
except KeyError:
|
||||||
|
data[idx]['wallet'] = _choose_wallet(
|
||||||
|
d['pubAddr'], True)
|
||||||
|
changed = True
|
||||||
|
|
||||||
|
if changed:
|
||||||
|
save_user_pubaddr(data)
|
||||||
|
|
||||||
return data
|
return data
|
||||||
|
|
||||||
else:
|
else:
|
||||||
data = []
|
data = []
|
||||||
data.append(dict(pubAddr='', desc=''))
|
data.append(dict(pubAddr='', desc='', wallet=''))
|
||||||
with open(filename, 'w') as f:
|
with open(filename, 'w') as f:
|
||||||
json.dump(data, f, sort_keys=False, indent=2,
|
json.dump(data, f, sort_keys=False, indent=2,
|
||||||
separators=(',', ':'))
|
separators=(',', ':'))
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def _choose_wallet(pubAddr, missing):
|
||||||
|
while True:
|
||||||
|
if missing:
|
||||||
|
print('\nYou need to specify a wallet for address '
|
||||||
|
'{}.'.format(pubAddr))
|
||||||
|
else:
|
||||||
|
print('\nThe wallet specified for address {} is not '
|
||||||
|
'supported.'.format(pubAddr))
|
||||||
|
|
||||||
|
print('Please choose among the following options:')
|
||||||
|
for idx, wallet in enumerate(SUPPORTED_WALLETS):
|
||||||
|
print('{}\t{}'.format(idx, wallet))
|
||||||
|
|
||||||
|
lw = len(SUPPORTED_WALLETS)-1
|
||||||
|
w = input('Choose a number between 0 and {}: '.format(
|
||||||
|
lw))
|
||||||
|
try:
|
||||||
|
w = int(w)
|
||||||
|
except ValueError:
|
||||||
|
print('Enter a number between 0 and {}'.format(lw))
|
||||||
|
else:
|
||||||
|
if w not in range(0, lw+1):
|
||||||
|
print('Enter a number between 0 and '
|
||||||
|
'{}'.format(lw))
|
||||||
|
else:
|
||||||
|
return SUPPORTED_WALLETS[w]
|
||||||
|
|
||||||
|
|
||||||
def save_user_pubaddr(data, environ=None):
|
def save_user_pubaddr(data, environ=None):
|
||||||
"""
|
"""
|
||||||
Saves the user's public addresses and their related metadata in
|
Saves the user's public addresses and their related metadata in
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import pytz
|
||||||
|
from datetime import datetime
|
||||||
|
from catalyst.api import symbol
|
||||||
|
from catalyst.utils.run_algo import run_algorithm
|
||||||
|
|
||||||
|
coin = 'btc'
|
||||||
|
base_currency = 'usd'
|
||||||
|
n_candles = 5
|
||||||
|
|
||||||
|
|
||||||
|
def initialize(context):
|
||||||
|
context.symbol = symbol('%s_%s' % (coin, base_currency))
|
||||||
|
|
||||||
|
|
||||||
|
def handle_data_polo_partial_candles(context, data):
|
||||||
|
history = data.history(symbol('btc_usdt'), ['volume'],
|
||||||
|
bar_count=10,
|
||||||
|
frequency='4H')
|
||||||
|
print('\nnow: %s\n%s' % (data.current_dt, history))
|
||||||
|
if not hasattr(context, 'i'):
|
||||||
|
context.i = 0
|
||||||
|
context.i += 1
|
||||||
|
if context.i > 5:
|
||||||
|
raise Exception('stop')
|
||||||
|
|
||||||
|
|
||||||
|
live = False
|
||||||
|
|
||||||
|
if live:
|
||||||
|
run_algorithm(initialize=lambda ctx: True,
|
||||||
|
handle_data=handle_data_polo_partial_candles,
|
||||||
|
exchange_name='poloniex',
|
||||||
|
base_currency='usdt',
|
||||||
|
algo_namespace='ns',
|
||||||
|
live=True,
|
||||||
|
data_frequency='minute',
|
||||||
|
capital_base=3000)
|
||||||
|
else:
|
||||||
|
run_algorithm(initialize=lambda ctx: True,
|
||||||
|
handle_data=handle_data_polo_partial_candles,
|
||||||
|
exchange_name='poloniex',
|
||||||
|
base_currency='usdt',
|
||||||
|
algo_namespace='ns',
|
||||||
|
live=False,
|
||||||
|
data_frequency='minute',
|
||||||
|
capital_base=3000,
|
||||||
|
start=datetime(2018, 2, 2, 0, 0, 0, 0, pytz.utc),
|
||||||
|
end=datetime(2018, 2, 20, 0, 0, 0, 0, pytz.utc)
|
||||||
|
)
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import pytz
|
||||||
|
from datetime import datetime
|
||||||
|
from catalyst.api import symbol
|
||||||
|
from catalyst.utils.run_algo import run_algorithm
|
||||||
|
|
||||||
|
coin = 'btc'
|
||||||
|
base_currency = 'usd'
|
||||||
|
|
||||||
|
|
||||||
|
def initialize(context):
|
||||||
|
context.symbol = symbol('%s_%s' % (coin, base_currency))
|
||||||
|
|
||||||
|
|
||||||
|
def handle_data_polo_partial_candles(context, data):
|
||||||
|
history = data.history(symbol('btc_usdt'), ['volume'],
|
||||||
|
bar_count=10,
|
||||||
|
frequency='1D')
|
||||||
|
print('\nnow: %s\n%s' % (data.current_dt, history))
|
||||||
|
if not hasattr(context, 'i'):
|
||||||
|
context.i = 0
|
||||||
|
context.i += 1
|
||||||
|
if context.i > 5:
|
||||||
|
raise Exception('stop')
|
||||||
|
|
||||||
|
|
||||||
|
run_algorithm(initialize=lambda ctx: True,
|
||||||
|
handle_data=handle_data_polo_partial_candles,
|
||||||
|
exchange_name='poloniex',
|
||||||
|
base_currency='usdt',
|
||||||
|
algo_namespace='ns',
|
||||||
|
live=False,
|
||||||
|
data_frequency='minute',
|
||||||
|
capital_base=3000,
|
||||||
|
start=datetime(2018, 2, 2, 0, 0, 0, 0, pytz.utc),
|
||||||
|
end=datetime(2018, 2, 20, 0, 0, 0, 0, pytz.utc))
|
||||||
@@ -640,12 +640,9 @@ class TradingCalendar(with_metaclass(ABCMeta)):
|
|||||||
"""
|
"""
|
||||||
sched = self.schedule
|
sched = self.schedule
|
||||||
|
|
||||||
# `market_open` and `market_close` should be timezone aware, but pandas
|
|
||||||
# 0.16.1 does not appear to support this:
|
|
||||||
# http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#datetime-with-tz # noqa
|
|
||||||
return (
|
return (
|
||||||
sched.at[session_label, 'market_open'].tz_localize('UTC'),
|
sched.at[session_label, 'market_open'],
|
||||||
sched.at[session_label, 'market_close'].tz_localize('UTC'),
|
sched.at[session_label, 'market_close'],
|
||||||
)
|
)
|
||||||
|
|
||||||
def session_open(self, session_label):
|
def session_open(self, session_label):
|
||||||
|
|||||||
@@ -117,9 +117,9 @@ def create_dividend(sid, payment, declared_date, ex_date, pay_date):
|
|||||||
'net_amount': payment,
|
'net_amount': payment,
|
||||||
'payment_sid': None,
|
'payment_sid': None,
|
||||||
'ratio': None,
|
'ratio': None,
|
||||||
'declared_date': pd.tslib.normalize_date(declared_date),
|
'declared_date': pd.tslib.declared_date.normalize(),
|
||||||
'ex_date': pd.tslib.normalize_date(ex_date),
|
'ex_date': pd.tslib.ex_date.normalize(),
|
||||||
'pay_date': pd.tslib.normalize_date(pay_date),
|
'pay_date': pd.tslib.pay_date.normalize(),
|
||||||
'type': DATASOURCE_TYPE.DIVIDEND,
|
'type': DATASOURCE_TYPE.DIVIDEND,
|
||||||
'source_id': 'MockDividendSource'
|
'source_id': 'MockDividendSource'
|
||||||
})
|
})
|
||||||
@@ -134,9 +134,9 @@ def create_stock_dividend(sid, payment_sid, ratio, declared_date,
|
|||||||
'ratio': ratio,
|
'ratio': ratio,
|
||||||
'net_amount': None,
|
'net_amount': None,
|
||||||
'gross_amount': None,
|
'gross_amount': None,
|
||||||
'dt': pd.tslib.normalize_date(declared_date),
|
'dt': pd.tslib.declared_date.normalize(),
|
||||||
'ex_date': pd.tslib.normalize_date(ex_date),
|
'ex_date': pd.tslib.ex_date.normalize(),
|
||||||
'pay_date': pd.tslib.normalize_date(pay_date),
|
'pay_date': pd.tslib.pay_date.normalize(),
|
||||||
'type': DATASOURCE_TYPE.DIVIDEND,
|
'type': DATASOURCE_TYPE.DIVIDEND,
|
||||||
'source_id': 'MockDividendSource'
|
'source_id': 'MockDividendSource'
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ 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, \
|
||||||
@@ -23,7 +24,7 @@ try:
|
|||||||
from pygments.formatters import TerminalFormatter
|
from pygments.formatters import TerminalFormatter
|
||||||
|
|
||||||
PYGMENTS = True
|
PYGMENTS = True
|
||||||
except:
|
except ImportError:
|
||||||
PYGMENTS = False
|
PYGMENTS = False
|
||||||
from toolz import valfilter, concatv
|
from toolz import valfilter, concatv
|
||||||
from functools import partial
|
from functools import partial
|
||||||
@@ -151,6 +152,7 @@ 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:
|
||||||
@@ -261,6 +263,15 @@ 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.start.normalize() or \
|
||||||
|
end != pd.tslib.end.normalize():
|
||||||
|
# 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,
|
||||||
|
|||||||
@@ -1,103 +0,0 @@
|
|||||||
#!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)
|
|
||||||
+15
-1
@@ -143,7 +143,7 @@ with the following steps:
|
|||||||
|
|
||||||
.. code-block:: bash
|
.. code-block:: bash
|
||||||
|
|
||||||
conda create --name catalyst python=2.7 scipy zlib
|
conda create --name catalyst python=3.6 scipy zlib
|
||||||
|
|
||||||
3. Activate the environment:
|
3. Activate the environment:
|
||||||
|
|
||||||
@@ -314,6 +314,16 @@ Troubleshooting ``pip`` Install
|
|||||||
|
|
||||||
$ sudo apt-get install python-dev
|
$ sudo apt-get install python-dev
|
||||||
|
|
||||||
|
----
|
||||||
|
|
||||||
|
**Issue**:
|
||||||
|
Missing TA_Lib
|
||||||
|
|
||||||
|
**Solution**:
|
||||||
|
Follow `these instructions
|
||||||
|
<https://mrjbq7.github.io/ta-lib/install.html>`_ to install the TA_Lib Python wrapper
|
||||||
|
(and if needed, its underlying C library as well).
|
||||||
|
|
||||||
.. _pipenv:
|
.. _pipenv:
|
||||||
|
|
||||||
Installing with ``pipenv``
|
Installing with ``pipenv``
|
||||||
@@ -552,6 +562,10 @@ If after following the instructions above, and going through the
|
|||||||
*Troubleshooting* sections, you still experience problems installing Catalyst,
|
*Troubleshooting* sections, you still experience problems installing Catalyst,
|
||||||
you can seek additional help through the following channels:
|
you can seek additional help through the following channels:
|
||||||
|
|
||||||
|
- Join our `Catalyst Forum <https://catalyst.enigma.co/>`_, and browse a variety
|
||||||
|
of topics and conversations around common issues that others face when using
|
||||||
|
Catalyst, and how to resolve them. And join the conversation!
|
||||||
|
|
||||||
- Join our `Discord community <https://discord.gg/SJK32GY>`_, and head over
|
- Join our `Discord community <https://discord.gg/SJK32GY>`_, and head over
|
||||||
the #catalyst_dev channel where many other users (as well as the project
|
the #catalyst_dev channel where many other users (as well as the project
|
||||||
developers) hang out, and can assist you with your particular issue. The
|
developers) hang out, and can assist you with your particular issue. The
|
||||||
|
|||||||
@@ -2,6 +2,94 @@
|
|||||||
Release Notes
|
Release Notes
|
||||||
=============
|
=============
|
||||||
|
|
||||||
|
Version 0.5.8
|
||||||
|
^^^^^^^^^^^^^
|
||||||
|
**Release Date**: 2018-03-29
|
||||||
|
|
||||||
|
Bug Fixes
|
||||||
|
~~~~~~~~~
|
||||||
|
- Fix proper release of Data Marketplace on mainnet.
|
||||||
|
|
||||||
|
|
||||||
|
Version 0.5.7
|
||||||
|
^^^^^^^^^^^^^
|
||||||
|
**Release Date**: 2018-03-29
|
||||||
|
|
||||||
|
Build
|
||||||
|
~~~~~
|
||||||
|
- Data Marketplace deployed on mainnet.
|
||||||
|
- Added progress indicators for publishing data, and made the data publishing
|
||||||
|
synchronous to provide feedback to the publisher.
|
||||||
|
|
||||||
|
Bug Fixes
|
||||||
|
~~~~~~~~~
|
||||||
|
- Added arguments to the ``reduce`` function in tha Asset class :issue:`214`,
|
||||||
|
:issue:`287`
|
||||||
|
|
||||||
|
Version 0.5.6
|
||||||
|
^^^^^^^^^^^^^
|
||||||
|
**Release Date**: 2018-03-22
|
||||||
|
|
||||||
|
Build
|
||||||
|
~~~~~
|
||||||
|
- Data Marketplace: ensures compatibility across wallets, now fully supporting
|
||||||
|
``ledger``, ``trezor``, ``keystore``, ``private key``. Partial support for
|
||||||
|
``metamask`` (includes sign_msg, but not sign_tx). Current support for
|
||||||
|
``Digital Bitbox`` is unknown, but believed to be supported.
|
||||||
|
- Data Marketplace: Switched online provider from MyEtherWallet to MyCrypto.
|
||||||
|
- Data Marketplace: Added progress indicator for data ingestion.
|
||||||
|
|
||||||
|
Bug Fixes
|
||||||
|
~~~~~~~~~
|
||||||
|
- Changed benchmark to be constant, so it doesn't ingest data at all. Temporary
|
||||||
|
fix for :issue:`271`, :issue:`285`
|
||||||
|
|
||||||
|
Version 0.5.5
|
||||||
|
^^^^^^^^^^^^^
|
||||||
|
**Release Date**: 2018-03-19
|
||||||
|
|
||||||
|
Bug Fixes
|
||||||
|
~~~~~~~~~
|
||||||
|
- Fixed an issue with the data history in daily frequency :issue:`274`
|
||||||
|
- Fix hourly frequency issues :issue:`227` and :issue:`114`
|
||||||
|
|
||||||
|
Version 0.5.4
|
||||||
|
^^^^^^^^^^^^^
|
||||||
|
**Release Date**: 2018-03-14
|
||||||
|
|
||||||
|
Build
|
||||||
|
~~~~~
|
||||||
|
- Switched Data Marketplace from Ropstein testnet to Rinkeby testnet after
|
||||||
|
incorporating changes resulting from the marketplace contract audit
|
||||||
|
- Several usability improvements of the Data Marketplace that make the
|
||||||
|
`--dataset` parameter optional. If it is not included in the command line,
|
||||||
|
will list available datasets, and let you choose interactively.
|
||||||
|
|
||||||
|
Bug Fixes
|
||||||
|
~~~~~~~~~
|
||||||
|
- Fix Binance requirement of symbol to be included in the cancelled order
|
||||||
|
:issue:`204`
|
||||||
|
- Fix `notenoughcasherror` when an open order is filled minutes later
|
||||||
|
:issue:`237`
|
||||||
|
- Properly handle of empty candles received from exchanges :issue:`236`
|
||||||
|
- Added a function to reduce open orders amount from calculated target/amount
|
||||||
|
for target orders :issue:`243`
|
||||||
|
- Fix missing file in live trading mode on date change :issue:`252`,
|
||||||
|
:issue:`253`
|
||||||
|
- Upgraded Data Marketplace to Web3==4.0.0b11, which was breaking some
|
||||||
|
functionality from prior version 4.0.0b7 :issue:`257`
|
||||||
|
- Always request more data to avoid empty bars and always give the exact bar
|
||||||
|
number :issue:`260`
|
||||||
|
|
||||||
|
Documentation
|
||||||
|
~~~~~~~~~~~~~
|
||||||
|
- PyCharm documentation :issue:`195`
|
||||||
|
- Added TA-Lib troubleshooting instructions
|
||||||
|
- Added instructions on how to create a Conda environment for Python 3.6, and
|
||||||
|
updated Visual C++ instructions for Windows and Python 3
|
||||||
|
- Linking example algorithms in the documentation to their sources
|
||||||
|
|
||||||
|
|
||||||
Version 0.5.3
|
Version 0.5.3
|
||||||
^^^^^^^^^^^^^
|
^^^^^^^^^^^^^
|
||||||
**Release Date**: 2018-02-09
|
**Release Date**: 2018-02-09
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ channels:
|
|||||||
dependencies:
|
dependencies:
|
||||||
- certifi=2016.2.28=py27_0
|
- certifi=2016.2.28=py27_0
|
||||||
- mkl=2017.0.3
|
- mkl=2017.0.3
|
||||||
- matplotlib=2.1.2=py36_0
|
|
||||||
- numpy=1.13.1=py27_0
|
- numpy=1.13.1=py27_0
|
||||||
- openssl=1.0.2l
|
- openssl=1.0.2l
|
||||||
- pip=9.0.1=py27_1
|
- pip=9.0.1=py27_1
|
||||||
@@ -40,7 +39,7 @@ dependencies:
|
|||||||
- lru-dict==1.1.6
|
- lru-dict==1.1.6
|
||||||
- mako==1.0.7
|
- mako==1.0.7
|
||||||
- markupsafe==1.0
|
- markupsafe==1.0
|
||||||
- matplotlib==2.1.0
|
- matplotlib==2.1.2
|
||||||
- multipledispatch==0.4.9
|
- multipledispatch==0.4.9
|
||||||
- networkx==2.0
|
- networkx==2.0
|
||||||
- numexpr==2.6.4
|
- numexpr==2.6.4
|
||||||
|
|||||||
@@ -165,7 +165,7 @@ def _filter_requirements(lines_iter, filter_names=None,
|
|||||||
|
|
||||||
REQ_UPPER_BOUNDS = {
|
REQ_UPPER_BOUNDS = {
|
||||||
'bcolz': '<1',
|
'bcolz': '<1',
|
||||||
'pandas': '<0.20',
|
'pandas': '>=0.22',
|
||||||
'empyrical': '<0.2.2',
|
'empyrical': '<0.2.2',
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ 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 exchange.utils.datetime_utils import get_start_dt
|
from catalyst.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
|
||||||
@@ -42,7 +42,7 @@ class TestExchangeBundle:
|
|||||||
|
|
||||||
def test_ingest_minute(self):
|
def test_ingest_minute(self):
|
||||||
data_frequency = 'minute'
|
data_frequency = 'minute'
|
||||||
exchange_name = 'poloniex'
|
exchange_name = 'binance'
|
||||||
|
|
||||||
exchange = get_exchange(exchange_name)
|
exchange = get_exchange(exchange_name)
|
||||||
exchange_bundle = ExchangeBundle(exchange)
|
exchange_bundle = ExchangeBundle(exchange)
|
||||||
@@ -50,8 +50,8 @@ class TestExchangeBundle:
|
|||||||
exchange.get_asset('eth_btc')
|
exchange.get_asset('eth_btc')
|
||||||
]
|
]
|
||||||
|
|
||||||
start = pd.to_datetime('2016-03-01', utc=True)
|
start = pd.to_datetime('2018-03-01', utc=True)
|
||||||
end = pd.to_datetime('2017-11-1', utc=True)
|
end = pd.to_datetime('2018-03-8', utc=True)
|
||||||
|
|
||||||
log.info('ingesting exchange bundle {}'.format(exchange_name))
|
log.info('ingesting exchange bundle {}'.format(exchange_name))
|
||||||
exchange_bundle.ingest(
|
exchange_bundle.ingest(
|
||||||
@@ -101,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 = 'bitfinex'
|
exchange_name = 'binance'
|
||||||
data_frequency = 'minute'
|
data_frequency = 'minute'
|
||||||
|
|
||||||
exchange = get_exchange(exchange_name)
|
exchange = get_exchange(exchange_name)
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ import datetime
|
|||||||
from math import sqrt
|
from math import sqrt
|
||||||
|
|
||||||
from nose_parameterized import parameterized
|
from nose_parameterized import parameterized
|
||||||
from pandas.tslib import normalize_date
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
import pytz
|
import pytz
|
||||||
@@ -1108,8 +1107,8 @@ class OrdersStopTestCase(WithSimParams,
|
|||||||
)),
|
)),
|
||||||
)
|
)
|
||||||
days = pd.date_range(
|
days = pd.date_range(
|
||||||
start=normalize_date(self.minutes[0]),
|
start=self.minutes[0].normalize(),
|
||||||
end=normalize_date(self.minutes[-1])
|
end=self.minutes[-1].normalize()
|
||||||
)
|
)
|
||||||
with tmp_bcolz_equity_minute_bar_reader(
|
with tmp_bcolz_equity_minute_bar_reader(
|
||||||
self.trading_calendar, days, assets) as reader:
|
self.trading_calendar, days, assets) as reader:
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
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):
|
||||||
@@ -16,12 +15,12 @@ class TestMarketplace(WithLogger, ZiplineTestCase):
|
|||||||
|
|
||||||
def test_subscribe(self):
|
def test_subscribe(self):
|
||||||
marketplace = Marketplace()
|
marketplace = Marketplace()
|
||||||
marketplace.subscribe('marketcap2222')
|
marketplace.subscribe('marketcap')
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def test_ingest(self):
|
def test_ingest(self):
|
||||||
marketplace = Marketplace()
|
marketplace = Marketplace()
|
||||||
ds_def = marketplace.ingest('github')
|
ds_def = marketplace.ingest('marketcap')
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def test_publish(self):
|
def test_publish(self):
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ from pandas import (
|
|||||||
Series,
|
Series,
|
||||||
Timestamp,
|
Timestamp,
|
||||||
)
|
)
|
||||||
from pandas.tseries.tools import normalize_date
|
|
||||||
from six import iteritems, itervalues
|
from six import iteritems, itervalues
|
||||||
|
|
||||||
from catalyst.algorithm import TradingAlgorithm
|
from catalyst.algorithm import TradingAlgorithm
|
||||||
@@ -530,7 +529,7 @@ class PipelineAlgorithmTestCase(WithBcolzEquityDailyBarReaderFromCSVs,
|
|||||||
attach_pipeline(pipeline, 'test')
|
attach_pipeline(pipeline, 'test')
|
||||||
|
|
||||||
def handle_data(context, data):
|
def handle_data(context, data):
|
||||||
today = normalize_date(get_datetime())
|
today = get_datetime().normalize()
|
||||||
results = pipeline_output('test')
|
results = pipeline_output('test')
|
||||||
expect_over_300 = {
|
expect_over_300 = {
|
||||||
AAPL: today < self.AAPL_split_date,
|
AAPL: today < self.AAPL_split_date,
|
||||||
|
|||||||
@@ -395,7 +395,6 @@ def handle_data(context, data):
|
|||||||
|
|
||||||
algocode = """
|
algocode = """
|
||||||
from pandas import Timestamp
|
from pandas import Timestamp
|
||||||
from pandas.tseries.tools import normalize_date
|
|
||||||
from catalyst.api import fetch_csv, record, sid, get_datetime
|
from catalyst.api import fetch_csv, record, sid, get_datetime
|
||||||
|
|
||||||
def initialize(context):
|
def initialize(context):
|
||||||
@@ -411,7 +410,7 @@ def initialize(context):
|
|||||||
context.bar_count = 0
|
context.bar_count = 0
|
||||||
|
|
||||||
def handle_data(context, data):
|
def handle_data(context, data):
|
||||||
expected = context.expected_sids[normalize_date(get_datetime())]
|
expected = context.expected_sids[get_datetime().normalize()]
|
||||||
actual = data.fetcher_assets
|
actual = data.fetcher_assets
|
||||||
for stk in expected:
|
for stk in expected:
|
||||||
if stk not in actual:
|
if stk not in actual:
|
||||||
|
|||||||
Reference in New Issue
Block a user