-
Notifications
You must be signed in to change notification settings - Fork 238
/
Copy pathautotrader.py
2175 lines (1849 loc) · 83.1 KB
/
autotrader.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import time
import pytz
import pickle
import timeit
import logging
import importlib
import traceback
import pandas as pd
from tqdm import tqdm
from ast import literal_eval
from threading import Thread
from scipy.optimize import brute
from autotrader.comms.tg import Telegram
from autotrader.strategy import Strategy
from autotrader.autoplot import AutoPlot
from autotrader.autobot import AutoTraderBot
from autotrader.brokers.broker import Broker
from datetime import datetime, timedelta, timezone
from typing import Callable, Optional, Literal, Union
from autotrader.brokers.ccxt import Broker as CCXTBroker
from autotrader.brokers.virtual import Broker as VirtualBroker
from autotrader.utilities import (
read_yaml,
get_broker_config,
DataStream,
LocalDataStream,
TradeAnalysis,
unpickle_broker,
print_banner,
get_logger,
)
class AutoTrader:
"""A Python-Based Development Platform For Automated Trading Systems.
Methods
-------
configure(...)
Configures run settings for AutoTrader.
add_strategy(...)
Adds a strategy to the active AutoTrader instance.
backtest(...)
Configures backtest settings.
optimise(...)
Configures optimisation settings.
scan(...)
Configures scan settings.
run()
Runs AutoTrader with configured settings.
add_data(...)
Specify local data files or data streaming methods to use.
plot_settings(...)
Configures the plot settings for AutoPlot.
get_bots_deployed(instrument=None)
Returns the AutoTrader trading bots deployed in the active instance.
plot_backtest(bot=None)
Plots backtest results of a trading Bot.
plot_multibot_backtest(trade_results=None)
Plots backtest results for multiple trading bots.
multibot_backtest_analysis(bots=None)
Analyses backtest results of multiple trading bots.
print_trade_results(trade_results)
Prints trade results.
print_multibot_trade_results(trade_results=None)
Prints a multi-bot backtest results.
References
----------
Author: Kieran Mackle
Homepage: https://kieran-mackle.github.io/AutoTrader/
GitHub: https://github.com/kieran-mackle/AutoTrader
"""
def __init__(self) -> None:
"""AutoTrader initialisation. Called when creating new AutoTrader
instance.
"""
# Public attributes
self.trade_results = None
self._home_dir = None
self._verbosity = 1
self._global_config_dict = None
self._instance_str = None
self._papertrading = False
self._timestep = None
self._strategy_timestep = None
self._warmup_period = None
self._feed = None
# Communications
self._notify = 0
self._notification_provider: Literal["telegram"] = ""
self._notifier = None
self._order_summary_fp = None
# Livetrade Parameters
self._deploy_time = None
self._maintain_broker_thread = False
# Broker parameters
self._execution_method: Callable = None # Execution method
self._broker: Union[dict[str, Broker], Broker] = None # Broker instance(s)
self._brokers_dict = None # Dictionary of brokers
self._broker_name = "" # Broker name(s)
self._environment: Literal["paper", "live"] = "paper" # Trading environment
self._account_id = None # Trading account
self._base_currency = None
self._no_brokers = 0
self._multiple_brokers = False
# Strategy parameters
self._strategy_configs = {}
self._strategy_classes = {}
self._shutdown_methods = {}
self._uninitiated_strat_files = []
self._uninitiated_strat_dicts = []
self._bots_deployed: list[AutoTraderBot] = []
# Backtesting Parameters
self._backtest_mode = False
self._data_start = None
self._data_end = None
self._broker_histories = None
# Local Data Parameters
self._data_directory = None
self._data_stream_object = LocalDataStream
self._data_file = None
self._data_path_mapper = None
self._local_data = None
self._dynamic_data = False
# Virtual Broker Parameters
self._virtual_broker_config = {}
self._virtual_tradeable_instruments = {} # Instruments tradeable mapper
self._broker_refresh_freq = "1s"
# Optimisation Parameters
self._optimise_mode = False
self._opt_params = None
self._bounds = None
self._Ns = None
# Scan Parameters
self._scan_mode = False
self._scan_index = None
self._scan_watchlist = None
# Plotting
self._show_plot = False
self._max_indis_over = 3
self._max_indis_below = 2
self._fig_tools = "pan,wheel_zoom,box_zoom,undo,redo,reset,save,crosshair"
self._ohlc_height = 400
self._ohlc_width = 800
self._top_fig_height = 150
self._bottom_fig_height = 150
self._jupyter_notebook = False
self._show_cancelled = True
self._chart_timeframe = "default"
self._chart_theme = "caliber"
self._use_strat_plot_data = False
self._plot_portolio_chart = False
# Initialise logger type
self.logger: logging.Logger
def __repr__(self):
return f"AutoTrader instance"
def __str__(self):
return "AutoTrader instance"
def configure(
self,
verbosity: Optional[int] = 1,
broker: Optional[str] = None,
feed: Optional[str] = None,
home_dir: Optional[str] = None,
notify: Optional[int] = 0,
notification_provider: Optional[Literal["telegram"]] = "telegram",
execution_method: Optional[Callable] = None,
account_id: Optional[str] = None,
environment: Optional[Literal["paper", "live"]] = "paper",
show_plot: Optional[bool] = False,
jupyter_notebook: Optional[bool] = False,
global_config: Optional[dict] = None,
instance_str: Optional[str] = None,
home_currency: Optional[str] = None,
deploy_time: Optional[datetime] = None,
logger_kwargs: Optional[dict] = None,
) -> None:
"""Configures run settings for AutoTrader.
Parameters
----------
verbosity : int, optional
The verbosity of AutoTrader (0, 1, 2, 3). The default is 1. This will be
used to configure the loggers, mapping the verbosity to a logging level.
For example, verbosity = 0 is equivalent to logging.ERROR, and
verbosity = 3 is equivalent to logging.DEBUG.
broker : str, optional
The broker(s) to connect to for trade execution. Multiple exchanges
can be provided using comma separattion. The default is 'virtual'.
execution_method : Callable, optional
The execution model to call when submitting orders to the broker.
This method must accept the broker instance, the order object,
order_time and any *args, **kwargs.
feed : str, optional
The data feed to be used. This can be the same as the broker
being used, or another data source. Options include 'yahoo',
'oanda', 'ib', 'ccxt:exchange', 'local'. When data is provided
via the add_data method, the feed is automatically set to 'local'.
The default is None.
notify : int, optional
The level of notifications (0, 1, 2). The default is 0.
notification_provider : str, optional
The notifications provider to use (currently only Telegram supported).
The default is None.
home_dir : str, optional
The project home directory. The default is the current working directory.
account_id : str, optional
The brokerage account ID to be used. The default is None.
environment : str, optional
The trading environment of this instance ('paper', 'live'). The
default is 'paper'.
show_plot : bool, optional
Automatically generate trade chart. The default is False.
jupyter_notebook : bool, optional
Set to True when running in Jupyter notebook environment. The
default is False.
global_config : dict, optional
Optionally provide your global configuration directly as a
dictionary, rather than it being read in from a yaml file. The
default is None.
instance_str : str, optional
The name of the active AutoTrader instance, used to control bots
deployed when livetrading in continuous mode. When not specified,
the instance string will be of the form 'autotrader_instance_n'.
The default is None.
home_currency : str, optional
The home currency of trading accounts used (intended for FX
conversions). The default is None.
deploy_time : datetime, optional
The time to deploy the bots. If this is a future time, AutoTrader
will wait until it is reached before deploying. It will also be used
as an anchor to synchronise future bot updates. If not specified,
bots will be deployed as soon as possible, with successive updates
synchronised to the deployment time.
logger_kwargs : dict, optional
Keyword arguments to pass on to the logger function, utilities.get_logger.
Returns
-------
None
Calling this method configures the internal settings of
the active AutoTrader instance.
"""
# TODO - tidy up the signature of this method
self._verbosity = verbosity
self._feed = feed
self._broker_name = broker if broker is not None else self._broker_name
self._execution_method = execution_method
self._notify = notify
self._notification_provider = (
notification_provider
if notification_provider is not None
else self._notification_provider
)
self._home_dir = home_dir if home_dir is not None else os.getcwd()
self._account_id = account_id
self._environment = environment
self._show_plot = show_plot
self._jupyter_notebook = jupyter_notebook
self._global_config_dict = global_config
self._instance_str = instance_str
self._base_currency = home_currency
self._deploy_time = deploy_time
# Create logger kwargs
logger_kwargs = logger_kwargs if logger_kwargs is not None else {}
verbosity_map = {
0: logging.ERROR,
1: logging.WARNING,
2: logging.INFO,
3: logging.DEBUG,
}
logger_kwargs["stdout_level"] = verbosity_map.get(verbosity, logging.INFO)
# Save logger kwargs for other classes
# TODO - make verbosity control print out only, and logging separate
self._logger_kwargs = logger_kwargs
def add_strategy(
self,
config_filename: str = None,
config_dict: dict = None,
strategy: Strategy = None,
shutdown_method: str = None,
) -> None:
"""Adds a strategy to AutoTrader.
Parameters
----------
config_filename : str, optional
The prefix of the yaml strategy configuration file, located in
home_dir/config. The default is None.
config_dict : dict, optional
Alternative to config_filename, a strategy configuration
dictionary can be passed directly. The default is None.
strategy : AutoTrader Strategy, optional
The strategy class object. The default is None.
shutdown_method : str, optional
The name of the shutdown method in the strategy (if any). This
method will be called when AutoTrader is livetrading in continuous
mode, and the instance has recieved the shutdown signal. The
default is None.
Returns
-------
None
The strategy will be added to the active AutoTrader instance.
"""
# TODO - assign unique ID to different strategies to prevent instrument
# traded names conflict
if self._home_dir is None:
# Home directory has not yet been set, postpone strategy addition
if config_filename is None:
self._uninitiated_strat_dicts.append(config_dict)
else:
self._uninitiated_strat_files.append(config_filename)
if shutdown_method is not None:
raise Exception(
"Providing the shutdown method requires "
+ "the home directory to have been configured. "
+ "please either specify it, or simply call "
+ "the configure method before adding a strategy."
)
else:
# Home directory has been set, continue
if config_dict is None:
# Config YAML filepath provided
if config_filename is None:
raise Exception(
"Must provide strategy configuration either as dictionary of filename."
)
config_file_path = os.path.join(
self._home_dir, "config", config_filename
)
new_strategy = read_yaml(config_file_path + ".yaml")
else:
# Config dictionary provided directly
new_strategy = config_dict
# Construct strategy name
try:
name = new_strategy["NAME"]
except (TypeError, KeyError):
print(
"Please specify the name of your strategy via the "
+ "'NAME' key of the strategy configuration."
)
sys.exit()
# Check for other required keys
required_keys = ["CLASS", "INTERVAL"]
for key in required_keys:
if key not in new_strategy:
print(
f"Please include the '{key}' key in your strategy configuration."
)
sys.exit(0)
if name in self._strategy_configs:
print(
"Warning: duplicate strategy name deteced. Please check "
+ "the NAME field of your strategy configuration file and "
+ "make sure it is not the same as other strategies being "
+ "run from this instance."
)
print("Conflicting name:", name)
# Save to AutoTrader instance
self._strategy_configs[name] = new_strategy
self._shutdown_methods[name] = shutdown_method
# Set timestep from strategy config
try:
strat_granularity = pd.Timedelta(
new_strategy["INTERVAL"]
).to_pytimedelta()
except:
print(
f"Strategy configuration error: invalid time interval: '{new_strategy['INTERVAL']}'."
)
sys.exit(0)
if self._strategy_timestep is None:
# Timestep hasn't been set yet; set it
self._strategy_timestep = strat_granularity
else:
# Timestep has been set, overwrite only with a smaller granularity
if strat_granularity < self._strategy_timestep:
self._strategy_timestep = strat_granularity
if strategy is not None:
self._strategy_classes[strategy.__name__] = strategy
def virtual_account_config(
self,
verbosity: int = 0,
initial_balance: float = 1000,
spread: float = 0,
commission: float = 0,
spread_units: str = "price",
commission_scheme: str = "percentage",
maker_commission: float = None,
taker_commission: float = None,
leverage: int = 1,
hedging: bool = False,
margin_call_fraction: float = 0,
default_slippage_model: Callable = None,
slippage_models: dict = None,
picklefile: str = None,
exchange: str = None,
tradeable_instruments: list[str] = None,
refresh_freq: str = "1s",
home_currency: str = None,
papertrade: bool = True,
) -> None:
"""Configures the virtual broker's initial state to allow livetrading
on the virtual broker. If you wish to create multiple virtual broker
instances, call this method for each virtual account.
Parameters
----------
verbosity : int, optional
The verbosity of the broker. The default is 0.
initial_balance : float, optional
The initial balance of the account. The default is 1000.
spread : float, optional
The bid/ask spread to use in backtest (specified in units defined
by the spread_units argument). The default is 0.
spread_units : str, optional
The unit of the spread specified. Options are 'price', meaning that
the spread is quoted in price units, or 'percentage', meaning that
the spread is quoted as a percentage of the market price. The default
is 'price'.
commission : float, optional
Trading commission as percentage per trade. The default is 0.
commission_scheme : str, optional
The method with which to apply commissions to trades made. The options
are (1) 'percentage', where the percentage specified by the commission
argument is applied to the notional trade value, (2) 'fixed_per_unit',
where the monetary value specified by the commission argument is
multiplied by the number of units in the trade, and (3) 'flat', where
a flat monetary value specified by the commission argument is charged
per trade made, regardless of size. The default is 'percentage'.
maker_commission : float, optional
The commission to charge on liquidity-making orders. The default is
None, in which case the nominal commission argument will be used.
taker_commission: float, optional
The commission to charge on liquidity-taking orders. The default is
None, in which case the nominal commission argument will be used.
leverage : int, optional
Account leverage. The default is 1.
hedging : bool, optional
Allow hedging in the virtual broker (opening simultaneous
trades in oposing directions). The default is False.
margin_call_fraction : float, optional
The fraction of margin usage at which a margin call will occur.
The default is 0.
default_slippage_model : Callable, optional
The default model to use when calculating the percentage slippage
on the fill price, for a given order size. The default functon
returns zero.
slippage_models : dict, optional
A dictionary of callable slippage models, keyed by instrument.
picklefile : str, optional
The filename of the picklefile to load state from. If you do not
wish to load from state, leave this as None. The default is None.
exchange : str, optional
The name of the exchange to use for execution. This gets passed to
an instance of AutoData to update prices and use the realtime
orderbook for virtual order execution. The default is None.
tradeable_instruments : list, optional
A list containing strings of the instruments tradeable through the
exchange specified. This is used to determine which exchange orders
should be submitted to when trading across multiple exchanges. This
should account for all instruments provided in the watchlist. The
default is None.
refresh_freq : str, optional
The timeperiod to sleep for in between updates of the virtual broker
data feed when manually papertrading. The default is '1s'.
home_currency : str, optional
The home currency of the account. The default is None.
papertrade : bool, optional
A boolean to flag when the account is to be used for papertrading
(real-time trading on paper). The default is True.
"""
# TODO - allow specifying spread dictionary to have custom spreads for
# different products
# Enforce virtual broker and paper trading environment
if exchange is not None:
broker_name = exchange
else:
# TODO - catch attempt to create multiple instances with same exchange
broker_name = "virtual"
if broker_name != "virtual" and broker_name not in self._broker_name:
# Unrecognised broker
print(
f"Please specify the broker '{broker_name}' in the "
+ "configure method before configuring its virtual account."
)
sys.exit(0)
self._papertrading = False if self._backtest_mode else papertrade
# TODO - review refresh freq
self._broker_refresh_freq = refresh_freq
if tradeable_instruments is not None:
self._virtual_tradeable_instruments[broker_name] = tradeable_instruments
# Set execution feed: if backtesting, use global feed, otherwise use the exchange
# specified (eg. connect to live exchange feed for papertrading)
execution_feed = self._feed if self._backtest_mode else exchange
# Construct configuration dictionary
config = {
# Broker configuration
"verbosity": verbosity,
"initial_balance": initial_balance,
"leverage": leverage,
"spread": spread,
"spread_units": spread_units,
"commission": commission,
"commission_scheme": commission_scheme,
"maker_commission": maker_commission,
"taker_commission": taker_commission,
"hedging": hedging,
"base_currency": home_currency,
"paper_mode": self._papertrading,
"public_trade_access": False, # Not yet implemented
"margin_closeout": margin_call_fraction,
"default_slippage_model": default_slippage_model,
"slippage_models": slippage_models,
"picklefile": picklefile,
# Extra parameters
"execution_feed": execution_feed,
}
# Append
# TODO - check keys for already existing
self._virtual_broker_config[broker_name] = config
def backtest(
self,
start: str = None,
end: str = None,
start_dt: datetime = None,
end_dt: datetime = None,
warmup_period: Optional[str] = None,
localize_to_utc: Optional[bool] = False,
) -> None:
"""Configures settings for backtesting.
Parameters
----------
start : str, optional
Start date for backtesting, in format dd/mm/yyyy. The default is None.
end : str, optional
End date for backtesting, in format dd/mm/yyyy. The default is None.
start_dt : datetime, optional
Datetime object corresponding to start time. The default is None.
end_dt : datetime, optional
Datetime object corresponding to end time. The default is None.
warmup_period : str, optional
A string describing the warmup period to be used. This is
equivalent to the minimum period of time required to collect
sufficient data for the strategy. The default is '0s'.
localize_to_utc : bool, optional
If the start and end have been passed as strings, set this to True to
localize them to UTC.
Notes
------
Start and end times must be specified as the same type. For
example, both start and end arguments must be provided together,
or alternatively, start_dt and end_dt must both be provided.
"""
# Convert start and end strings to datetime objects
if start_dt is None and end_dt is None:
start_dt = datetime.strptime(start, "%d/%m/%Y")
end_dt = datetime.strptime(end, "%d/%m/%Y")
if localize_to_utc:
start_dt = pytz.utc.localize(start_dt)
end_dt = pytz.utc.localize(end_dt)
# Assign attributes
self._backtest_mode = True
self._data_start = start_dt
self._data_end = end_dt
self._warmup_period = warmup_period
# Update logging attributes
self._logger_kwargs["stdout"] = False
def optimise(
self, opt_params: list, bounds: list, Ns: int = 4, force_download: bool = False
) -> None:
"""Optimisation configuration.
Parameters
----------
opt_params : list
The parameters to be optimised, as they are named in the
strategy configuration file.
bounds : list(tuples)
The bounds on each of the parameters to be optimised, specified
as a tuple of the form (lower, upper) for each parameter. The
default is 4.
force_download : bool, optional
Force AutoTrader to download data each iteration. This is not
recommended. Instead, you should provide local download to optimise
on, using the add_data method. The default is False.
Ns : int, optional
The number of points along each dimension of the optimisation grid.
Raises
------
Exception:
When force_download is False, and local data has not been added
through the add_data method. Note that add_data should be called
prior to calling the optimise method.
Returns
-------
None:
The optimisation settings will be saved to the active AutoTrader
instance.
See Also
--------
AutoTrader.add_data()
"""
if type(bounds) == str:
full_tuple = literal_eval(bounds)
bounds = [(x[0], x[-1]) for x in full_tuple]
if type(opt_params) == str:
opt_params = opt_params.split(",")
self._optimise_mode = True
self._opt_params = opt_params
self._bounds = bounds
self._Ns = Ns
if self._local_data is None:
raise Exception(
"Local data files have not been provided. "
+ "Please do so using AutoTrader.add_data(), "
+ "or set force_download to True to proceed."
)
def add_data(
self,
data_dict: dict = None,
mapper_func: callable = None,
data_directory: str = "price_data",
stream_object: DataStream = None,
dynamic_data: bool = False,
) -> None:
"""Specify local data to run AutoTrader on.
Parameters
----------
data_dict : dict, optional
A dictionary containing the filenames of the datasets
to be used, keyed by instrument. The default is None.
mapper_func : callable, optional
A callable used to provide the absolute filepath to the data
given the instrument name (as it appears in the watchlist)
as an input argument. The default is None.
data_directory : str, optional
The name of the sub-directory containing price
data files. This directory should be located in the project
home directory (at.home_dir). The default is 'price_data'.
stream_object : LocalDataStream, optional
A custom data stream object, allowing custom data pipelines. The
default is LocalDataStream (from autotrader.utilities).
dynamic_data : bool, optional
A boolean flag to signal that the stream object provided should
be refreshed each timestep of a backtest. This can be useful when
backtesting strategies with futures contracts, which expire and
must be rolled. The default is False.
Raises
------
Exception
When multiple quote-data files are provided per instrument traded.
Returns
-------
None
Data will be assigned to the active AutoTrader instance for
later use.
Notes
------
To ensure proper directory configuration, this method should only
be called after calling autotrader.configure().
Examples
--------
An example data_dict is shown below.
>>> data_dict = {'product1': 'filename1.csv',
'product2': 'filename2.csv'}
"""
# Trading data
if data_dict is not None:
# Assign local data attribute
local_data = {}
# Populate local_data
for instrument in data_dict:
# Single timeframe data
local_data[instrument] = os.path.join(
data_directory, data_dict[instrument]
)
self._local_data = local_data
# Check mapper function
if mapper_func is not None:
self._data_path_mapper = mapper_func
# Assign data stream object
# TODO - move this earlier?
if stream_object is not None:
self._data_stream_object = stream_object
# Override other data feed attributes
self._data_directory = data_directory
self._feed = "local"
self._dynamic_data = dynamic_data
def scan(
self,
strategy_filename: Optional[str] = None,
strategy_dict: Optional[dict] = None,
scan_index: Optional[str] = None,
) -> None:
"""Configure AutoTrader scan settings.
Parameters
----------
strategy_filename : str, optional
The prefix of yaml strategy configuration file, located in
home_dir/config. The default is None.
strategy_dict : dict, optional
A strategy configuration dictionary. The default is None.
scan_index : str, optional
Forex scan index. The default is None.
Returns
-------
None
The scan settings of the active AutoTrader instance will be
configured.
"""
# If a strategy is provided here, add it
if strategy_filename is not None:
self.add_strategy(config_filename=strategy_filename)
elif strategy_dict is not None:
self.add_strategy(strategy_dict=strategy_dict)
# If scan index provided, use that. Else, use strategy watchlist
scan_index = "Strategy watchlist"
self._scan_mode = True
self._scan_index = scan_index
def run(self) -> Union[None, Broker, VirtualBroker, CCXTBroker]:
"""Performs essential checks and runs AutoTrader."""
# Create logger
self.logger = get_logger(
name="autotrader",
**self._logger_kwargs,
)
# Print Banner
if int(self._verbosity) > 0 and (
self._logger_kwargs.get("stdout", True) or self._backtest_mode
):
print_banner()
# Define home_dir if undefined
if self._home_dir is None:
self._home_dir = os.getcwd()
# Load uninitiated strategies
for strat_dict in self._uninitiated_strat_dicts:
self.add_strategy(strategy_dict=strat_dict)
for strat_config_file in self._uninitiated_strat_files:
self.add_strategy(config_filename=strat_config_file)
if self._scan_watchlist is not None:
# Scan watchlist has not overwritten strategy watchlist
self._update_strategy_watchlist()
# Check run mode
if sum([self._backtest_mode, self._scan_mode]) > 1:
self.logger.error(
"Backtest mode and scan mode are both set to True,"
+ " but only one of these can run at a time."
+ "Please check your inputs and try again."
)
sys.exit(0)
# Check self._timestep
if self._timestep is None:
# Set timestep based on strategy inferred timestep
self._timestep = self._strategy_timestep
# Remove any trailing commas in self._broker_name
self._broker_name = self._broker_name.strip().strip(",")
# Check for multiple brokers
self._no_brokers = len(self._broker_name.split(","))
self._multiple_brokers = self._no_brokers > 1
# TODO - check len(self._virtual_broker_config)
# Check self._broker_name
if self._broker_name == "":
# Broker has not been assigned
if self._backtest_mode or self._papertrading or self._scan_mode:
# Use virtual broker
self._broker_name = "virtual"
else:
# Livetrading
self.logger.error(
"Please specify the name(s) of the broker(s) "
+ "you wish to trade with."
)
sys.exit()
# Check backtesting configuration
if self._backtest_mode:
if self._notify > 0:
self.logger.warning(
"Notify set to {} ".format(self._notify)
+ "during backtest. Setting to zero to prevent notifications."
)
self._notify = 0
# Check that the backtest does not request future data
if self._data_end > datetime.now(tz=self._data_end.tzinfo):
self.logger.info(
"You have requested backtest data into the "
+ "future. The backtest end date will be adjsuted to "
+ "the current time."
)
self._data_end = datetime.now(tz=self._data_end.tzinfo)
# Check if the virtual broker has been configured
if len(self._virtual_broker_config) != self._no_brokers:
# Virtual accounts have not been configured for the brokers specified
if len(self._virtual_broker_config) == 0:
# Use default values for all virtual accounts
for exchange in self._broker_name.split(","):
self.virtual_account_config(papertrade=False, exchange=exchange)
else:
# Partially configured accounts
raise Exception(
"Please configure the virtual accounts for "
+ "each broker you plan to used.\n"
+ f" Number of brokers specifed: {self._no_brokers}\n"
+ f" Number of virtual accounts configured: {len(self._virtual_broker_config)}"
)
# Check notification settings
if self._notify > 0 and self._notification_provider is None:
self.logger.error(
"Please specify a notification provided via the " + "configure method."
)
sys.exit()
# Check bots directory exists
self._get_instance_id()
# Preliminary checks complete, continue initialisation
if self._optimise_mode:
# Run optimisation
if self._backtest_mode:
self._run_optimise()
else:
self.logger.error("Please set backtest parameters to run optimisation.")
else:
# Trading
if not self._backtest_mode and "virtual" in self._broker_name:
# Not in backtest mode, yet virtual broker is selected
if not self._papertrading and not self._scan_mode:
# Not papertrading or scanning either
self.logger.error(
"Live-trade mode requires setting the "
+ "broker. Please do so using the "
+ "AutoTrader configure method. If you "
+ "would like to use the virtual broker "
+ "for papertrading, please "
+ "configure the virtual broker account(s) "
+ "with the virtual_account_config method."
)
sys.exit()
# Load global (account) configuration
if self._global_config_dict is not None:
# Use global config dict provided
global_config = self._global_config_dict
else: