-
Notifications
You must be signed in to change notification settings - Fork 165
Expand file tree
/
Copy pathapp.py
More file actions
2702 lines (2340 loc) · 107 KB
/
app.py
File metadata and controls
2702 lines (2340 loc) · 107 KB
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 inspect
import logging
import os
import threading
from datetime import datetime, timezone, timedelta
from pathlib import Path
from typing import List, Optional, Any, Dict, Tuple, Callable, Union
from flask import Flask
from investing_algorithm_framework.app.algorithm import Algorithm
from investing_algorithm_framework.app.strategy import TradingStrategy
from investing_algorithm_framework.app.task import Task
from investing_algorithm_framework.app.web import create_flask_app
from investing_algorithm_framework.domain import DATABASE_NAME, TimeUnit, \
DATABASE_DIRECTORY_PATH, RESOURCE_DIRECTORY, ENVIRONMENT, Environment, \
SQLALCHEMY_DATABASE_URI, OperationalException, StateHandler, \
BACKTESTING_START_DATE, BACKTESTING_END_DATE, APP_MODE, MarketCredential, \
AppMode, BacktestDateRange, DATABASE_DIRECTORY_NAME, DataSource, \
BACKTESTING_INITIAL_AMOUNT, SNAPSHOT_INTERVAL, generate_algorithm_id, \
PortfolioConfiguration, SnapshotInterval, DataType, Backtest, DataError, \
PortfolioProvider, OrderExecutor, ImproperlyConfigured, TimeFrame, \
DataProvider, INDEX_DATETIME, tqdm, BacktestPermutationTest, \
LAST_SNAPSHOT_DATETIME, BACKTESTING_FLAG, DATA_DIRECTORY
from investing_algorithm_framework.infrastructure import setup_sqlalchemy, \
create_all_tables, CCXTOrderExecutor, CCXTPortfolioProvider, \
CCXTOHLCVDataProvider, clear_db, \
PandasOHLCVDataProvider
from investing_algorithm_framework.services import OrderBacktestService, \
BacktestPortfolioService, DefaultTradeOrderEvaluator
from .app_hook import AppHook
from .eventloop import EventLoopService
logger = logging.getLogger("investing_algorithm_framework")
COLOR_RESET = '\033[0m'
COLOR_GREEN = '\033[92m'
COLOR_YELLOW = '\033[93m'
class App:
"""
Class to represent the app. This class is used to initialize the
application and run your trading bot.
Attributes:
container: The dependency container for the app. This is used
to store all the services and repositories for the app.
_flask_app: The flask app instance. This is used to run the
web app.
_state_handler: The state handler for the app. This is used
to save and load the state of the app.
_name: The name of the app. This is used to identify the app
in logs and other places.
_started: A boolean value that indicates if the app has been
started or not.
_tasks (List[Task]): List of task that need to be run by the
application.
"""
def __init__(self, state_handler=None, name=None):
self._flask_app: Optional[Flask] = None
self.container = None
self._started = False
self._tasks = []
self._strategies = []
self._data_providers: List[Tuple[DataProvider, int]] = []
self._on_initialize_hooks = []
self._on_strategy_run_hooks = []
self._on_after_initialize_hooks = []
self._trade_order_evaluator = None
self._state_handler = state_handler
self._run_history = None
self._name = name
self._blotter = None
self._fx_rate_provider = None
self._base_currency = None
@property
def context(self):
from investing_algorithm_framework.domain.blotter import \
DefaultBlotter
ctx = self.container.context()
ctx._blotter = self._blotter \
if self._blotter is not None else DefaultBlotter()
ctx._fx_rate_provider = self._fx_rate_provider
ctx._base_currency = self._base_currency
return ctx
@property
def resource_directory_path(self):
"""
Returns the resource directory path from the configuration.
This directory is used to store resources such as market data,
database files, and other resources required by the app.
"""
config = self.config
resource_directory_path = config.get(RESOURCE_DIRECTORY, None)
# Check if the resource directory is set
if resource_directory_path is None:
logger.info(
"Resource directory not set, setting" +
" to current working directory"
)
resource_directory_path = os.path.join(os.getcwd(), "resources")
configuration_service = self.container.configuration_service()
configuration_service.add_value(
RESOURCE_DIRECTORY, resource_directory_path
)
return resource_directory_path
@property
def database_directory_path(self):
"""
Returns the database directory path from the configuration.
This directory is used to store database files required by the app.
"""
config = self.config
database_directory_path = config.get(DATABASE_DIRECTORY_PATH, None)
# Check if the database directory is set
if database_directory_path is None:
logger.info(
"Database directory not set, setting" +
" to current working directory"
)
resource_directory_path = self.resource_directory_path
database_directory_path = os.path.join(
resource_directory_path, "databases"
)
configuration_service = self.container.configuration_service()
configuration_service.add_value(
DATABASE_DIRECTORY_PATH, database_directory_path
)
return database_directory_path
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def started(self):
return self._started
@property
def config(self):
"""
Function to get a config instance. This allows users when
having access to the app instance also to read the
configs of the app.
"""
configuration_service = self.container.configuration_service()
return configuration_service.config
@config.setter
def config(self, config: dict):
"""
Function to set the configuration for the app.
Args:
config (dict): A dictionary containing the configuration
Returns:
None
"""
configuration_service = self.container.configuration_service()
configuration_service.initialize_from_dict(config)
def add_algorithm(self, algorithm: Algorithm) -> None:
"""
Method to add an algorithm to the app. This method should be called
before running the application.
When adding an algorithm, it will automatically register all
strategies, data sources, and tasks of the algorithm. The
algorithm itself is not registered.
Args:
algorithm (Algorithm): The algorithm to add to the app.
This should be an instance of Algorithm.
Returns:
None
"""
self.add_strategies(algorithm.strategies)
self.add_tasks(algorithm.tasks)
def add_trade_order_evaluator(self, trade_order_evaluator):
"""
Function to add a trade order evaluator to the app. This is used
to evaluate trades and orders based on OHLCV data.
Args:
trade_order_evaluator: The trade order evaluator to add to the app.
This should be an instance of TradeOrderEvaluator.
Returns:
None
"""
self._trade_order_evaluator = trade_order_evaluator
def set_config(self, key: str, value: Any) -> None:
"""
Function to add a key-value pair to the app's configuration.
Args:
key (string): The key to add to the configuration
value (any): The value to add to the configuration
Returns:
None
"""
configuration_service = self.container.configuration_service()
configuration_service.add_value(key, value)
def set_config_with_dict(self, config: dict) -> None:
"""
Function to set the configuration for the app with a dictionary.
This is useful for setting multiple configuration values at once.
Args:
config (dict): A dictionary containing the configuration
Returns:
None
"""
configuration_service = self.container.configuration_service()
configuration_service.initialize_from_dict(config)
def initialize_config(self):
"""
Function to initialize the configuration for the app. This method
should be called before running the algorithm.
Returns:
None
"""
data = {
ENVIRONMENT: self.config.get(ENVIRONMENT, Environment.PROD.value),
DATABASE_DIRECTORY_NAME: "databases",
LAST_SNAPSHOT_DATETIME: None
}
configuration_service = self.container.configuration_service()
configuration_service.initialize_from_dict(data)
config = configuration_service.get_config()
if INDEX_DATETIME not in config or config[INDEX_DATETIME] is None:
configuration_service.add_value(
INDEX_DATETIME, datetime.now(timezone.utc)
)
if Environment.TEST.equals(config[ENVIRONMENT]):
configuration_service.add_value(
DATABASE_NAME, "test-database.sqlite3"
)
elif Environment.PROD.equals(config[ENVIRONMENT]):
configuration_service.add_value(
DATABASE_NAME, "prod-database.sqlite3"
)
else:
configuration_service.add_value(
DATABASE_NAME, "dev-database.sqlite3"
)
resource_dir = config[RESOURCE_DIRECTORY]
database_dir_name = config.get(DATABASE_DIRECTORY_NAME)
configuration_service.add_value(
DATABASE_DIRECTORY_PATH,
os.path.join(resource_dir, database_dir_name)
)
config = configuration_service.get_config()
if SQLALCHEMY_DATABASE_URI not in config \
or config[SQLALCHEMY_DATABASE_URI] is None:
db_path = os.path.join(
configuration_service.config[DATABASE_DIRECTORY_PATH],
configuration_service.config[DATABASE_NAME]
)
path = "sqlite:///" + db_path.replace("\\", "/")
configuration_service.add_value(SQLALCHEMY_DATABASE_URI, path)
def initialize_backtest_config(
self,
backtest_date_range: BacktestDateRange,
initial_amount=None,
snapshot_interval: SnapshotInterval = None
):
"""
Function to initialize the configuration for the app in backtest mode.
This method should be called before running the algorithm in backtest
mode. It sets the environment to BACKTEST and initializes the
configuration accordingly.
Args:
backtest_date_range (BacktestDateRange): The date range for the
backtest. This should be an instance of BacktestDateRange.
initial_amount (float): The initial amount to start the backtest
with. This will be the amount of trading currency that the
backtest portfolio will start with.
snapshot_interval (SnapshotInterval): The snapshot interval to
use for the backtest. This is used to determine how often the
portfolio snapshot should be taken during the backtest.
Returns:
None
"""
logger.info("Initializing backtest configuration")
data = {
ENVIRONMENT: Environment.BACKTEST.value,
BACKTESTING_START_DATE: backtest_date_range.start_date,
BACKTESTING_END_DATE: backtest_date_range.end_date,
DATABASE_NAME: "backtest-database.sqlite3",
DATABASE_DIRECTORY_NAME: "backtest_databases",
DATABASE_DIRECTORY_PATH: os.path.join(
self.resource_directory_path,
"backtest_databases"
),
BACKTESTING_INITIAL_AMOUNT: initial_amount,
INDEX_DATETIME: backtest_date_range.start_date,
LAST_SNAPSHOT_DATETIME: None,
BACKTESTING_FLAG: True
}
configuration_service = self.container.configuration_service()
configuration_service.initialize_from_dict(data)
if snapshot_interval is not None:
configuration_service.add_value(
SNAPSHOT_INTERVAL,
SnapshotInterval.from_value(snapshot_interval).value
)
def initialize_storage(self, remove_database_if_exists: bool = False):
"""
Function to initialize the storage for the app. The given
resource directory will be created if it does not exist.
The database directory will also be created if it does not
exist.
"""
resource_directory_path = self.resource_directory_path
if not os.path.exists(resource_directory_path):
os.makedirs(resource_directory_path)
logger.info(
f"Resource directory created at {resource_directory_path}"
)
database_directory_path = self.database_directory_path
if not os.path.exists(database_directory_path):
os.makedirs(database_directory_path)
logger.info(
f"Database directory created at {database_directory_path}"
)
database_path = os.path.join(
database_directory_path, self.config[DATABASE_NAME]
)
if remove_database_if_exists:
if os.path.exists(database_path):
logger.info(
f"Removing existing database at {database_path}"
)
# Dispose the existing engine to release file locks
# (required on Windows where locks are mandatory)
from investing_algorithm_framework.infrastructure.database \
import Session
from sqlalchemy.orm import close_all_sessions
close_all_sessions()
bind = Session.kw.get("bind")
if bind is not None:
try:
conn = bind.connect()
conn.invalidate()
conn.close()
except Exception:
pass
bind.dispose()
import gc
gc.collect()
os.remove(database_path)
# Create the sqlalchemy database uri
path = "sqlite:///" + database_path.replace("\\", "/")
self.set_config(SQLALCHEMY_DATABASE_URI, path)
# Setup sql if needed
setup_sqlalchemy(self)
create_all_tables()
# Create the DATA_DIRECTORY if it does not exist
data_directory_dir_name = self.config[DATA_DIRECTORY]
data_directory_path = os.path.join(
resource_directory_path, data_directory_dir_name
)
if not os.path.exists(data_directory_path):
os.makedirs(data_directory_path)
logger.info(
f"Data directory created at {data_directory_path}"
)
def initialize_data_sources(
self,
data_sources: List[DataSource],
):
"""
Function to initialize the data sources for the app. This method
should be called before running the algorithm. This method
initializes all data sources so that they are ready to be used.
Args:
data_sources (List[DataSource]): The data sources to initialize.
This should be a list of DataSource instances.
Returns:
None
"""
logger.info("Initializing data sources")
if data_sources is None or len(data_sources) == 0:
return
data_provider_service = self.container.data_provider_service()
data_provider_service.reset()
for data_provider_tuple in self._data_providers:
data_provider_service.add_data_provider(
data_provider_tuple[0], priority=data_provider_tuple[1]
)
# Add the default data providers
data_provider_service.add_data_provider(CCXTOHLCVDataProvider())
# Initialize all data sources
data_provider_service.index_data_providers(data_sources)
def initialize_data_sources_backtest(
self,
data_sources: List[DataSource],
backtest_date_range: BacktestDateRange,
show_progress: bool = False,
fill_missing_data: bool = False,
):
"""
Function to initialize the data sources for the app in backtest mode.
This method should be called before running the algorithm in backtest
mode. It initializes all data sources so that they are
ready to be used.
Args:
data_sources (List[DataSource]): The data sources to initialize.
backtest_date_range (BacktestDateRange): The date range for the
backtest. This should be an instance of BacktestDateRange.
show_progress (bool): Whether to show a progress bar when
preparing the backtest data for each data provider.
fill_missing_data (bool): If True, missing time series data
entries will be filled automatically before preparing the
backtest data.
Returns:
None
"""
logger.info("Initializing data sources for backtest")
if data_sources is None or len(data_sources) == 0:
return
data_provider_service = self.container.data_provider_service()
data_provider_service.reset()
for data_provider_tuple in self._data_providers:
data_provider_service.add_data_provider(
data_provider_tuple[0], priority=data_provider_tuple[1]
)
# Add the default data providers
data_provider_service.add_data_provider(CCXTOHLCVDataProvider())
# Initialize all data sources
data_provider_service.index_backtest_data_providers(
data_sources, backtest_date_range, show_progress=show_progress
)
description = "Preparing backtest data for all data sources"
data_providers = data_provider_service.data_provider_index.get_all()
# Prepare the backtest data for each data provider
if not show_progress:
for _, data_provider in data_providers:
data_provider.prepare_backtest_data(
backtest_start_date=backtest_date_range.start_date,
backtest_end_date=backtest_date_range.end_date,
fill_missing_data=fill_missing_data,
show_progress=show_progress,
)
else:
for _, data_provider in \
tqdm(
data_providers, desc=description, colour="green"
):
data_provider.prepare_backtest_data(
backtest_start_date=backtest_date_range.start_date,
backtest_end_date=backtest_date_range.end_date,
fill_missing_data=fill_missing_data,
show_progress=show_progress,
)
def initialize_backtest_services(self):
"""
Function to initialize the backtest services for the app. This method
should be called before running the algorithm in backtest mode.
It initializes the backtest services so that they are ready to be used.
Returns:
None
"""
configuration_service = self.container.configuration_service()
self.initialize_order_executors()
self.initialize_portfolio_providers()
portfolio_conf_service = self.container \
.portfolio_configuration_service()
portfolio_snap_service = self.container \
.portfolio_snapshot_service()
market_cred_service = self.container.market_credential_service()
portfolio_provider_lookup = \
self.container.portfolio_provider_lookup()
# Override the portfolio service with the backtest portfolio service
self.container.portfolio_service.override(
BacktestPortfolioService(
configuration_service=configuration_service,
market_credential_service=market_cred_service,
position_service=self.container.position_service(),
order_service=self.container.order_service(),
portfolio_repository=self.container.portfolio_repository(),
portfolio_configuration_service=portfolio_conf_service,
portfolio_snapshot_service=portfolio_snap_service,
portfolio_provider_lookup=portfolio_provider_lookup
)
)
portfolio_conf_service = self.container. \
portfolio_configuration_service()
portfolio_snap_service = self.container. \
portfolio_snapshot_service()
configuration_service = self.container.configuration_service()
# Override the order service with the backtest order service
self.container.order_service.override(
OrderBacktestService(
trade_service=self.container.trade_service(),
order_repository=self.container.order_repository(),
position_service=self.container.position_service(),
portfolio_repository=self.container.portfolio_repository(),
portfolio_configuration_service=portfolio_conf_service,
portfolio_snapshot_service=portfolio_snap_service,
configuration_service=configuration_service,
)
)
def initialize_services(self):
"""
Method to initialize the app. This method should be called before
running the algorithm. It initializes the services and the algorithm
and sets up the database if it does not exist.
Also, it initializes all required services for the algorithm.
Returns:
None
"""
logger.info("Initializing app")
self.initialize_order_executors()
self.initialize_portfolio_providers()
# Initialize all market credentials
market_credential_service = self.container.market_credential_service()
market_credential_service.initialize()
portfolio_configuration_service = self.container \
.portfolio_configuration_service()
if portfolio_configuration_service.count() == 0:
raise OperationalException("No portfolios configured")
configuration_service = self.container.configuration_service()
config = configuration_service.get_config()
if AppMode.WEB.equals(config[APP_MODE]):
configuration_service.add_value(APP_MODE, AppMode.WEB.value)
self._initialize_web()
def run(self, number_of_iterations: int = None):
"""
Entry point to run the application. This method should be called to
start the trading bot. This method can be called in three modes:
- Without any params: In this mode, the app runs until a keyboard
interrupt is received. This mode is useful when running the app in
a loop.
- With a payload: In this mode, the app runs only once with the
payload provided. This mode is useful when running the app in a
one-off mode, such as running the app from the command line or
on a schedule. Payload is a dictionary that contains the data to
handle for the algorithm. This data should look like this:
{
"action": "RUN_STRATEGY",
}
- With a number of iterations: In this mode, the app runs for the
number of iterations provided. This mode is useful when running the
app in a loop for a fixed number of iterations.
This function first checks if there is an algorithm registered.
If not, it raises an OperationalException. Then it
initializes the algorithm with the services and the configuration.
Args:
number_of_iterations (int): The number of iterations to run the
algorithm for
Returns:
None
"""
self.initialize_config()
# Run all on_initialize hooks
for hook in self._on_initialize_hooks:
logger.info(
f"Running on_initialize hook: {hook.__class__.__name__}"
)
hook.on_run(self.context)
# Load the state if a state handler is provided
if self._state_handler is not None:
logger.info("Detected state handler, loading state")
self._state_handler.initialize()
config = self.container.configuration_service().get_config()
self._state_handler.load(config[RESOURCE_DIRECTORY])
self.initialize_storage()
logger.info("App initialization complete")
event_loop_service = None
try:
# Run all on_after_initialize hooks
for hook in self._on_after_initialize_hooks:
logger.info(
f"Running on_after_initialize "
f"hook: {hook.__class__.__name__}"
)
hook.on_run(self.context)
algorithm = self.get_algorithm()
self.initialize_data_sources(algorithm.data_sources)
self.initialize_services()
self.initialize_portfolios()
if AppMode.WEB.equals(self.config[APP_MODE]) \
and not (self._flask_app and self._flask_app.testing) \
and number_of_iterations is None:
logger.info("Running web")
flask_thread = threading.Thread(
name='Web App',
target=self._flask_app.run,
kwargs={"port": 8080}
)
flask_thread.daemon = True
flask_thread.start()
trade_order_evaluator = DefaultTradeOrderEvaluator(
trade_service=self.container.trade_service(),
order_service=self.container.order_service(),
trade_stop_loss_service=self.container
.trade_stop_loss_service(),
trade_take_profit_service=self.container
.trade_take_profit_service(),
configuration_service=self.container.configuration_service(),
blotter=self._blotter,
context=self.context
)
event_loop_service = EventLoopService(
configuration_service=self.container.configuration_service(),
portfolio_snapshot_service=self.container
.portfolio_snapshot_service(),
context=self.context,
order_service=self.container.order_service(),
portfolio_service=self.container.portfolio_service(),
data_provider_service=self.container.data_provider_service(),
trade_service=self.container.trade_service(),
)
event_loop_service.initialize(
algorithm, trade_order_evaluator=trade_order_evaluator
)
try:
event_loop_service.start(
number_of_iterations=number_of_iterations
)
except KeyboardInterrupt:
exit(0)
except Exception as e:
logger.error(e)
raise e
finally:
if event_loop_service is not None:
self._run_history = event_loop_service.history
try:
# Upload state if state handler is provided
if self._state_handler is not None:
logger.info("Detected state handler, saving state")
config = \
self.container.configuration_service().get_config()
self._state_handler.save(config[RESOURCE_DIRECTORY])
except Exception as e:
logger.error(e)
def add_portfolio_configuration(self, portfolio_configuration):
"""
Function to add a portfolio configuration to the app. The portfolio
configuration should be an instance of PortfolioConfiguration.
Args:
portfolio_configuration: Instance of PortfolioConfiguration
Returns:
None
"""
portfolio_configuration_service = self.container \
.portfolio_configuration_service()
portfolio_configuration_service.add(portfolio_configuration)
def task(
self,
function=None,
time_unit: TimeUnit = TimeUnit.MINUTE,
interval=10,
):
"""
Function to add a task to the application.
Args:
function:
time_unit:
interval:
Returns:
Union(Task, Function): the task
"""
if function:
task = Task(
decorated=function,
time_unit=time_unit,
interval=interval,
)
self._tasks.append(task)
return task
else:
def wrapper(f):
self._tasks.append(
Task(
decorated=f,
time_unit=time_unit,
interval=interval
)
)
return f
return wrapper
def add_task(self, task):
if inspect.isclass(task):
task = task()
assert isinstance(task, Task), \
OperationalException(
"Task object is not an instance of a Task"
)
self._tasks.append(task)
def add_tasks(self, tasks: List[Task]):
"""
Function to add a list of tasks to the app. The tasks should be
instances of Task.
Args:
tasks: List of Task instances
Returns:
None
"""
for task in tasks:
self.add_task(task)
def _initialize_web(self):
"""
Initialize the app for web mode by setting the configuration
parameters for web mode and overriding the services with the
web services equivalents.
Web has the following implications:
- db
- sqlite
- services
- Flask app
- Investing Algorithm Framework App
- Algorithm
"""
# Preserve the testing flag if the flask app already exists
was_testing = self._flask_app.testing \
if self._flask_app is not None else False
configuration_service = self.container.configuration_service()
self._flask_app = create_flask_app(configuration_service)
if was_testing:
self._flask_app.testing = True
def get_portfolio_configurations(self):
portfolio_configuration_service = self.container \
.portfolio_configuration_service()
return portfolio_configuration_service.get_all()
def get_market_credential(self, market: str) -> MarketCredential:
"""
Function to get a market credential from the app. This method
should be called when you want to get a market credential.
Args:
market (str): The market to get the credential for
Returns:
MarketCredential: Instance of MarketCredential
"""
market_credential_service = self.container \
.market_credential_service()
market_credential = market_credential_service.get(market)
if market_credential is None:
raise OperationalException(
f"Market credential for {market} not found"
)
return market_credential
def get_market_credentials(self) -> List[MarketCredential]:
"""
Function to get all market credentials from the app. This method
should be called when you want to get all market credentials.
Returns:
List of MarketCredential instances
"""
market_credential_service = self.container \
.market_credential_service()
return market_credential_service.get_all()
def check_data_completeness(
self,
strategies: List[TradingStrategy],
backtest_date_range: BacktestDateRange,
show_progress: bool = False
) -> Tuple[bool, Dict[str, Any]]:
"""
Function to check the data completeness for a set of strategies
over a given backtest date range. This method checks if all data
sources required by the strategies have complete data for the
specified date range.
Args:
strategies (List[TradingStrategy]): List of strategy objects
to check data completeness for.
backtest_date_range (BacktestDateRange): The date range to
check data completeness for.
show_progress (bool): Whether to show a progress bar when
checking data completeness.
Returns:
Tuple[bool, Dict[str, Any]]: A tuple containing a boolean
indicating if the data is complete and a dictionary
with information about missing data for each data source.
"""
data_sources = []
missing_data_info = {}
for strategy in strategies:
data_sources.extend(strategy.data_sources)
self.initialize_data_sources_backtest(
data_sources,
backtest_date_range,
show_progress=show_progress
)
data_provider_service = self.container.data_provider_service()
unique_data_sources = set(data_sources)
for data_source in unique_data_sources:
if DataType.OHLCV.equals(data_source.data_type):
required_start_date = backtest_date_range.start_date - \
timedelta(
minutes=TimeFrame.from_value(
data_source.time_frame
).amount_of_minutes * data_source.window_size
)
number_of_required_data_points = \
data_source.get_number_of_required_data_points(
backtest_date_range.start_date,
backtest_date_range.end_date
)
try:
data_provider = data_provider_service.get(data_source)
number_of_available_data_points = \
data_provider.get_number_of_data_points(
backtest_date_range.start_date,
backtest_date_range.end_date
)
missing_dates = \
data_provider.get_missing_data_dates(
required_start_date,
backtest_date_range.end_date
)
if len(missing_dates) > 0:
missing_data_info[data_source.identifier] = {
"data_source_id": data_source.identifier,
"completeness_percentage": (
(
number_of_available_data_points /
number_of_required_data_points
) * 100
),
"missing_data_points": len(
missing_dates
),
"missing_dates": missing_dates,
"data_source_file_path":
data_provider.get_data_source_file_path()
}
except Exception as e:
raise DataError(
f"Error getting data provider for data source "
f"{data_source.identifier} "
f"({data_source.symbol}): {str(e)}"
)
if len(missing_data_info.keys()) > 0:
return False, missing_data_info
return True, missing_data_info
def run_vector_backtests(
self,
strategies: List[TradingStrategy],
backtest_date_range: BacktestDateRange = None,
backtest_date_ranges: List[BacktestDateRange] = None,
snapshot_interval: SnapshotInterval = SnapshotInterval.DAILY,
risk_free_rate: Optional[float] = None,
skip_data_sources_initialization: bool = False,
show_progress: bool = False,
market: Optional[str] = None,
initial_amount: float = None,
trading_symbol: Optional[str] = None,
continue_on_error: bool = False,
window_filter_function: Optional[
Callable[[List[Backtest], BacktestDateRange], List[Backtest]]
] = None,
final_filter_function: Optional[
Callable[[List[Backtest]], List[Backtest]]
] = None,
backtest_storage_directory: Optional[Union[str, Path]] = None,
use_checkpoints: bool = False,
batch_size: int = 50,
checkpoint_batch_size: int = 25,
n_workers: Optional[int] = None,
dynamic_position_sizing: bool = False,
fill_missing_data: bool = True,
iterative_summary_update: bool = False,
) -> List[Backtest]:
"""
Run vectorized backtests for a set of strategies. The provided
set of strategies need to have their 'buy_signal_vectorized' and
'sell_signal_vectorized' methods implemented to support vectorized
backtesting.