-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrun.py
249 lines (205 loc) · 6.79 KB
/
run.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import json
import logging
import warnings
from argparse import ArgumentParser
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler
from sys import argv
from blankly import Alpaca, Binance, PaperTrade, Screener, ScreenerState
from quantipy.logger import QuantiPyLogger
from quantipy.strategies import AdvancedHarmonicOscillators, Oversold
STRATEGIES = {
"AdvancedHarmonicOscillators": AdvancedHarmonicOscillators,
"Oversold": Oversold,
}
EXCHANGES = {"Binance": Binance, "PaperTrade": PaperTrade, "Alpaca": Alpaca}
def setupLogger() -> None:
loggers = [logging.getLogger()]
loggers.extend(
logging.getLogger(name) for name in logging.root.manager.loggerDict
)
fslog = TimedRotatingFileHandler(
"strategy.log", when="midnight", backupCount=30
)
fslog.suffix = "%Y%m%d"
for logger in loggers:
logger.propagate = False
console = logging.StreamHandler()
formatter = QuantiPyLogger()
console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
logger.addHandler(console)
fslog.setFormatter(formatter)
logger.addHandler(fslog)
logger.setLevel(logging.DEBUG)
def main() -> None: # noqa: C901
setupLogger()
parser = ArgumentParser(
description="""
CLI tool to start the trading bot.
By default all trades are paper unless --live is passed in.
Specify the strategy and symbols to begin trading.
"""
)
parser.add_argument(
"strategy",
type=STRATEGIES.get,
help="The name of the strategy to use",
)
parser.add_argument(
"exchange",
type=EXCHANGES.get,
help="The name of the exchange to use",
)
parser.add_argument(
"-ls",
action="store_true",
default=False,
help="Print all available strategies and exchanges, then exit",
)
parser.add_argument(
"--backtest",
action="store_true",
default=False,
help="Backtest the strategy",
)
parser.add_argument(
"-r",
"--resolution",
default="30m",
help="Time domain resolution",
)
parser.add_argument(
"-p",
"--portfolio",
type=str,
help="The name of the portfoloio to use (see keys.json)",
)
parser.add_argument(
"--to", type=str, default="1y", help='Timeframe to backtest: e.g "1y"'
)
parser.add_argument(
"--live",
action="store_true",
default=False,
help="Run the strategy in live mode",
)
parser.add_argument(
"-sym",
"--symbol",
action="append",
dest="symbols",
required=True,
help="One or more symbols to process",
)
parser.add_argument(
"--as-screener",
action="store_true",
default=False,
help='Use the strategy in "Screener" mode',
)
parser.add_argument("-l", "--log-level", type=str, default="INFO")
parser.add_argument(
"-as",
"--all-symbols",
action="store_true",
default=False,
help="Use all symbols traded in a given exchange (Not recommended)",
)
parser.add_argument(
"--top",
type=int,
default=10,
help="When using symbol lists, use top X symbols",
)
parser.add_argument(
"--dump-audit",
action="store_true",
default=False,
help="Dump the strategy audit log for analysis",
)
if len(argv) > 1 and argv[1] == "-ls":
print("Available strategies:")
for st in sorted(STRATEGIES.keys()):
print("" * 4, st, end="")
print("" * 8, STRATEGIES[st].__doc__)
print("\nAvailable exchanges:")
for ex in sorted(EXCHANGES.keys()):
print("" * 4, ex)
exit()
args = parser.parse_args()
loggers = [logging.getLogger()]
loggers.extend(
logging.getLogger(name) for name in logging.root.manager.loggerDict
)
for logger in loggers:
logger.setLevel(args.log_level)
logger = logging.getLogger()
exchange = args.exchange(portfolio_name=args.portfolio)
initial = {}
if args.exchange == Binance:
initial["USDT"] = 1000
else:
initial["USD"] = 1000
if not args.live:
exchange = PaperTrade(exchange, initial_account_values=initial)
strategy = args.strategy(exchange)
if len(args.symbols) == 1 and args.symbols[0] in ["NASDAQ100"]:
# Select the top 10 of these lists
_list = args.symbols[0]
with open("symbols.json") as fp:
data = json.load(fp)
if _list in data:
args.symbols = data[_list][: args.top]
if args.backtest:
with open("backtest.json") as fp:
data = json.load(fp)
settings = data.get("settings", {})
benchmark = settings.get("benchmark_symbol")
if benchmark and benchmark not in args.symbols:
logging.info(
"Benchmark symbol %s not in symbols, adding it now",
benchmark,
)
args.symbols.append(benchmark)
# We need this in the backtest data but don't
# necessarily want to actually *trade* it
strategy.blacklist.append(benchmark)
for symbol in args.symbols:
logger.info("Tracking symbol: %s", symbol)
strategy.add_price_event(
strategy.tick,
symbol=symbol,
resolution=args.resolution,
init=strategy.init,
)
if args.backtest:
with warnings.catch_warnings():
warnings.simplefilter("ignore")
res = strategy.backtest(to=args.to, initial_values=initial)
with open(f"{args.strategy.__name__}_results.json", "w") as fp:
json.dump(res.to_dict(), fp, indent=4)
logger.info("Wrote backtest results to `%s`", fp.name)
if args.dump_audit and strategy._audit_log != {}:
with open(f"{strategy.__class__.__name__}_audit.json", "w") as fp:
json.dump(strategy._audit_log, fp, indent=4)
exit()
if args.as_screener:
def init(state: ScreenerState) -> None:
state.resolution = args.resolution
def formatter(results: dict, state: ScreenerState) -> None:
outupt = datetime.now().strftime("%c") + ":\n"
for symbol in results:
if results[symbol]["buy"]:
outupt += "[%s] %s\n" % (symbol, results[symbol]["buy"])
print(outupt)
Screener(
exchange,
strategy.screener,
symbols=args.symbols,
init=init,
formatter=formatter,
)
strategy.start()
if __name__ == "__main__":
main()