investing-algorithm-framework 1.3.1__py3-none-any.whl → 7.25.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. investing_algorithm_framework/__init__.py +195 -16
  2. investing_algorithm_framework/analysis/__init__.py +16 -0
  3. investing_algorithm_framework/analysis/backtest_data_ranges.py +202 -0
  4. investing_algorithm_framework/analysis/data.py +170 -0
  5. investing_algorithm_framework/analysis/markdown.py +91 -0
  6. investing_algorithm_framework/analysis/ranking.py +298 -0
  7. investing_algorithm_framework/app/__init__.py +31 -4
  8. investing_algorithm_framework/app/algorithm/__init__.py +7 -0
  9. investing_algorithm_framework/app/algorithm/algorithm.py +193 -0
  10. investing_algorithm_framework/app/algorithm/algorithm_factory.py +118 -0
  11. investing_algorithm_framework/app/app.py +2233 -264
  12. investing_algorithm_framework/app/app_hook.py +28 -0
  13. investing_algorithm_framework/app/context.py +1724 -0
  14. investing_algorithm_framework/app/eventloop.py +620 -0
  15. investing_algorithm_framework/app/reporting/__init__.py +27 -0
  16. investing_algorithm_framework/app/reporting/ascii.py +921 -0
  17. investing_algorithm_framework/app/reporting/backtest_report.py +349 -0
  18. investing_algorithm_framework/app/reporting/charts/__init__.py +19 -0
  19. investing_algorithm_framework/app/reporting/charts/entry_exist_signals.py +66 -0
  20. investing_algorithm_framework/app/reporting/charts/equity_curve.py +37 -0
  21. investing_algorithm_framework/app/reporting/charts/equity_curve_drawdown.py +74 -0
  22. investing_algorithm_framework/app/reporting/charts/line_chart.py +11 -0
  23. investing_algorithm_framework/app/reporting/charts/monthly_returns_heatmap.py +70 -0
  24. investing_algorithm_framework/app/reporting/charts/ohlcv_data_completeness.py +51 -0
  25. investing_algorithm_framework/app/reporting/charts/rolling_sharp_ratio.py +79 -0
  26. investing_algorithm_framework/app/reporting/charts/yearly_returns_barchart.py +55 -0
  27. investing_algorithm_framework/app/reporting/generate.py +185 -0
  28. investing_algorithm_framework/app/reporting/tables/__init__.py +11 -0
  29. investing_algorithm_framework/app/reporting/tables/key_metrics_table.py +217 -0
  30. investing_algorithm_framework/app/reporting/tables/stop_loss_table.py +0 -0
  31. investing_algorithm_framework/app/reporting/tables/time_metrics_table.py +80 -0
  32. investing_algorithm_framework/app/reporting/tables/trade_metrics_table.py +147 -0
  33. investing_algorithm_framework/app/reporting/tables/trades_table.py +75 -0
  34. investing_algorithm_framework/app/reporting/tables/utils.py +29 -0
  35. investing_algorithm_framework/app/reporting/templates/report_template.html.j2 +154 -0
  36. investing_algorithm_framework/app/stateless/action_handlers/__init__.py +6 -3
  37. investing_algorithm_framework/app/stateless/action_handlers/action_handler_strategy.py +1 -1
  38. investing_algorithm_framework/app/stateless/action_handlers/check_online_handler.py +2 -1
  39. investing_algorithm_framework/app/stateless/action_handlers/run_strategy_handler.py +14 -7
  40. investing_algorithm_framework/app/stateless/exception_handler.py +1 -1
  41. investing_algorithm_framework/app/strategy.py +873 -52
  42. investing_algorithm_framework/app/task.py +5 -3
  43. investing_algorithm_framework/app/web/__init__.py +2 -1
  44. investing_algorithm_framework/app/web/controllers/__init__.py +2 -2
  45. investing_algorithm_framework/app/web/controllers/orders.py +4 -3
  46. investing_algorithm_framework/app/web/controllers/portfolio.py +1 -1
  47. investing_algorithm_framework/app/web/controllers/positions.py +3 -3
  48. investing_algorithm_framework/app/web/create_app.py +4 -2
  49. investing_algorithm_framework/app/web/error_handler.py +1 -1
  50. investing_algorithm_framework/app/web/schemas/order.py +2 -2
  51. investing_algorithm_framework/app/web/schemas/position.py +1 -0
  52. investing_algorithm_framework/cli/__init__.py +0 -0
  53. investing_algorithm_framework/cli/cli.py +231 -0
  54. investing_algorithm_framework/cli/deploy_to_aws_lambda.py +501 -0
  55. investing_algorithm_framework/cli/deploy_to_azure_function.py +718 -0
  56. investing_algorithm_framework/cli/initialize_app.py +603 -0
  57. investing_algorithm_framework/cli/templates/.gitignore.template +178 -0
  58. investing_algorithm_framework/cli/templates/app.py.template +18 -0
  59. investing_algorithm_framework/cli/templates/app_aws_lambda_function.py.template +48 -0
  60. investing_algorithm_framework/cli/templates/app_azure_function.py.template +14 -0
  61. investing_algorithm_framework/cli/templates/app_web.py.template +18 -0
  62. investing_algorithm_framework/cli/templates/aws_lambda_dockerfile.template +22 -0
  63. investing_algorithm_framework/cli/templates/aws_lambda_dockerignore.template +92 -0
  64. investing_algorithm_framework/cli/templates/aws_lambda_readme.md.template +110 -0
  65. investing_algorithm_framework/cli/templates/aws_lambda_requirements.txt.template +2 -0
  66. investing_algorithm_framework/cli/templates/azure_function_function_app.py.template +65 -0
  67. investing_algorithm_framework/cli/templates/azure_function_host.json.template +15 -0
  68. investing_algorithm_framework/cli/templates/azure_function_local.settings.json.template +8 -0
  69. investing_algorithm_framework/cli/templates/azure_function_requirements.txt.template +3 -0
  70. investing_algorithm_framework/cli/templates/data_providers.py.template +17 -0
  71. investing_algorithm_framework/cli/templates/env.example.template +2 -0
  72. investing_algorithm_framework/cli/templates/env_azure_function.example.template +4 -0
  73. investing_algorithm_framework/cli/templates/market_data_providers.py.template +9 -0
  74. investing_algorithm_framework/cli/templates/readme.md.template +135 -0
  75. investing_algorithm_framework/cli/templates/requirements.txt.template +2 -0
  76. investing_algorithm_framework/cli/templates/run_backtest.py.template +20 -0
  77. investing_algorithm_framework/cli/templates/strategy.py.template +124 -0
  78. investing_algorithm_framework/cli/validate_backtest_checkpoints.py +197 -0
  79. investing_algorithm_framework/create_app.py +43 -9
  80. investing_algorithm_framework/dependency_container.py +121 -33
  81. investing_algorithm_framework/domain/__init__.py +109 -22
  82. investing_algorithm_framework/domain/algorithm_id.py +69 -0
  83. investing_algorithm_framework/domain/backtesting/__init__.py +25 -0
  84. investing_algorithm_framework/domain/backtesting/backtest.py +548 -0
  85. investing_algorithm_framework/domain/backtesting/backtest_date_range.py +113 -0
  86. investing_algorithm_framework/domain/backtesting/backtest_evaluation_focuss.py +241 -0
  87. investing_algorithm_framework/domain/backtesting/backtest_metrics.py +470 -0
  88. investing_algorithm_framework/domain/backtesting/backtest_permutation_test.py +275 -0
  89. investing_algorithm_framework/domain/backtesting/backtest_run.py +663 -0
  90. investing_algorithm_framework/domain/backtesting/backtest_summary_metrics.py +162 -0
  91. investing_algorithm_framework/domain/backtesting/backtest_utils.py +198 -0
  92. investing_algorithm_framework/domain/backtesting/combine_backtests.py +392 -0
  93. investing_algorithm_framework/domain/config.py +60 -138
  94. investing_algorithm_framework/domain/constants.py +23 -34
  95. investing_algorithm_framework/domain/data_provider.py +334 -0
  96. investing_algorithm_framework/domain/data_structures.py +42 -0
  97. investing_algorithm_framework/domain/decimal_parsing.py +40 -0
  98. investing_algorithm_framework/domain/exceptions.py +51 -1
  99. investing_algorithm_framework/domain/models/__init__.py +29 -14
  100. investing_algorithm_framework/domain/models/app_mode.py +34 -0
  101. investing_algorithm_framework/domain/models/base_model.py +3 -1
  102. investing_algorithm_framework/domain/models/data/__init__.py +7 -0
  103. investing_algorithm_framework/domain/models/data/data_source.py +222 -0
  104. investing_algorithm_framework/domain/models/data/data_type.py +46 -0
  105. investing_algorithm_framework/domain/models/event.py +35 -0
  106. investing_algorithm_framework/domain/models/market/__init__.py +5 -0
  107. investing_algorithm_framework/domain/models/market/market_credential.py +88 -0
  108. investing_algorithm_framework/domain/models/order/__init__.py +3 -4
  109. investing_algorithm_framework/domain/models/order/order.py +243 -86
  110. investing_algorithm_framework/domain/models/order/order_status.py +2 -2
  111. investing_algorithm_framework/domain/models/order/order_type.py +1 -3
  112. investing_algorithm_framework/domain/models/portfolio/__init__.py +7 -2
  113. investing_algorithm_framework/domain/models/portfolio/portfolio.py +134 -1
  114. investing_algorithm_framework/domain/models/portfolio/portfolio_configuration.py +37 -37
  115. investing_algorithm_framework/domain/models/portfolio/portfolio_snapshot.py +208 -0
  116. investing_algorithm_framework/domain/models/position/__init__.py +3 -2
  117. investing_algorithm_framework/domain/models/position/position.py +29 -0
  118. investing_algorithm_framework/domain/models/position/position_size.py +41 -0
  119. investing_algorithm_framework/domain/models/position/{position_cost.py → position_snapshot.py} +16 -8
  120. investing_algorithm_framework/domain/models/risk_rules/__init__.py +7 -0
  121. investing_algorithm_framework/domain/models/risk_rules/stop_loss_rule.py +51 -0
  122. investing_algorithm_framework/domain/models/risk_rules/take_profit_rule.py +55 -0
  123. investing_algorithm_framework/domain/models/snapshot_interval.py +45 -0
  124. investing_algorithm_framework/domain/models/strategy_profile.py +33 -0
  125. investing_algorithm_framework/domain/models/time_frame.py +94 -98
  126. investing_algorithm_framework/domain/models/time_interval.py +33 -0
  127. investing_algorithm_framework/domain/models/time_unit.py +111 -2
  128. investing_algorithm_framework/domain/models/tracing/__init__.py +0 -0
  129. investing_algorithm_framework/domain/models/tracing/trace.py +23 -0
  130. investing_algorithm_framework/domain/models/trade/__init__.py +11 -0
  131. investing_algorithm_framework/domain/models/trade/trade.py +389 -0
  132. investing_algorithm_framework/domain/models/trade/trade_status.py +40 -0
  133. investing_algorithm_framework/domain/models/trade/trade_stop_loss.py +332 -0
  134. investing_algorithm_framework/domain/models/trade/trade_take_profit.py +365 -0
  135. investing_algorithm_framework/domain/order_executor.py +112 -0
  136. investing_algorithm_framework/domain/portfolio_provider.py +118 -0
  137. investing_algorithm_framework/domain/services/__init__.py +11 -0
  138. investing_algorithm_framework/domain/services/market_credential_service.py +37 -0
  139. investing_algorithm_framework/domain/services/portfolios/__init__.py +5 -0
  140. investing_algorithm_framework/domain/services/portfolios/portfolio_sync_service.py +9 -0
  141. investing_algorithm_framework/domain/services/rounding_service.py +27 -0
  142. investing_algorithm_framework/domain/services/state_handler.py +38 -0
  143. investing_algorithm_framework/domain/strategy.py +1 -29
  144. investing_algorithm_framework/domain/utils/__init__.py +16 -4
  145. investing_algorithm_framework/domain/utils/csv.py +22 -0
  146. investing_algorithm_framework/domain/utils/custom_tqdm.py +22 -0
  147. investing_algorithm_framework/domain/utils/dates.py +57 -0
  148. investing_algorithm_framework/domain/utils/jupyter_notebook_detection.py +19 -0
  149. investing_algorithm_framework/domain/utils/polars.py +53 -0
  150. investing_algorithm_framework/domain/utils/random.py +29 -0
  151. investing_algorithm_framework/download_data.py +244 -0
  152. investing_algorithm_framework/infrastructure/__init__.py +39 -11
  153. investing_algorithm_framework/infrastructure/data_providers/__init__.py +36 -0
  154. investing_algorithm_framework/infrastructure/data_providers/ccxt.py +1152 -0
  155. investing_algorithm_framework/infrastructure/data_providers/csv.py +568 -0
  156. investing_algorithm_framework/infrastructure/data_providers/pandas.py +599 -0
  157. investing_algorithm_framework/infrastructure/database/__init__.py +6 -2
  158. investing_algorithm_framework/infrastructure/database/sql_alchemy.py +87 -13
  159. investing_algorithm_framework/infrastructure/models/__init__.py +13 -4
  160. investing_algorithm_framework/infrastructure/models/decimal_parser.py +14 -0
  161. investing_algorithm_framework/infrastructure/models/order/__init__.py +2 -2
  162. investing_algorithm_framework/infrastructure/models/order/order.py +73 -73
  163. investing_algorithm_framework/infrastructure/models/order/order_metadata.py +44 -0
  164. investing_algorithm_framework/infrastructure/models/order_trade_association.py +10 -0
  165. investing_algorithm_framework/infrastructure/models/portfolio/__init__.py +3 -2
  166. investing_algorithm_framework/infrastructure/models/portfolio/portfolio_snapshot.py +37 -0
  167. investing_algorithm_framework/infrastructure/models/portfolio/{portfolio.py → sql_portfolio.py} +57 -3
  168. investing_algorithm_framework/infrastructure/models/position/__init__.py +2 -2
  169. investing_algorithm_framework/infrastructure/models/position/position.py +16 -11
  170. investing_algorithm_framework/infrastructure/models/position/position_snapshot.py +23 -0
  171. investing_algorithm_framework/infrastructure/models/trades/__init__.py +9 -0
  172. investing_algorithm_framework/infrastructure/models/trades/trade.py +130 -0
  173. investing_algorithm_framework/infrastructure/models/trades/trade_stop_loss.py +59 -0
  174. investing_algorithm_framework/infrastructure/models/trades/trade_take_profit.py +55 -0
  175. investing_algorithm_framework/infrastructure/order_executors/__init__.py +21 -0
  176. investing_algorithm_framework/infrastructure/order_executors/backtest_oder_executor.py +28 -0
  177. investing_algorithm_framework/infrastructure/order_executors/ccxt_order_executor.py +200 -0
  178. investing_algorithm_framework/infrastructure/portfolio_providers/__init__.py +19 -0
  179. investing_algorithm_framework/infrastructure/portfolio_providers/ccxt_portfolio_provider.py +199 -0
  180. investing_algorithm_framework/infrastructure/repositories/__init__.py +13 -5
  181. investing_algorithm_framework/infrastructure/repositories/order_metadata_repository.py +17 -0
  182. investing_algorithm_framework/infrastructure/repositories/order_repository.py +32 -19
  183. investing_algorithm_framework/infrastructure/repositories/portfolio_repository.py +2 -2
  184. investing_algorithm_framework/infrastructure/repositories/portfolio_snapshot_repository.py +56 -0
  185. investing_algorithm_framework/infrastructure/repositories/position_repository.py +47 -4
  186. investing_algorithm_framework/infrastructure/repositories/position_snapshot_repository.py +21 -0
  187. investing_algorithm_framework/infrastructure/repositories/repository.py +85 -31
  188. investing_algorithm_framework/infrastructure/repositories/trade_repository.py +71 -0
  189. investing_algorithm_framework/infrastructure/repositories/trade_stop_loss_repository.py +29 -0
  190. investing_algorithm_framework/infrastructure/repositories/trade_take_profit_repository.py +29 -0
  191. investing_algorithm_framework/infrastructure/services/__init__.py +9 -2
  192. investing_algorithm_framework/infrastructure/services/aws/__init__.py +6 -0
  193. investing_algorithm_framework/infrastructure/services/aws/state_handler.py +193 -0
  194. investing_algorithm_framework/infrastructure/services/azure/__init__.py +5 -0
  195. investing_algorithm_framework/infrastructure/services/azure/state_handler.py +158 -0
  196. investing_algorithm_framework/infrastructure/services/backtesting/__init__.py +9 -0
  197. investing_algorithm_framework/infrastructure/services/backtesting/backtest_service.py +2596 -0
  198. investing_algorithm_framework/infrastructure/services/backtesting/event_backtest_service.py +285 -0
  199. investing_algorithm_framework/infrastructure/services/backtesting/vector_backtest_service.py +468 -0
  200. investing_algorithm_framework/services/__init__.py +127 -10
  201. investing_algorithm_framework/services/configuration_service.py +95 -0
  202. investing_algorithm_framework/services/data_providers/__init__.py +5 -0
  203. investing_algorithm_framework/services/data_providers/data_provider_service.py +1058 -0
  204. investing_algorithm_framework/services/market_credential_service.py +40 -0
  205. investing_algorithm_framework/services/metrics/__init__.py +119 -0
  206. investing_algorithm_framework/services/metrics/alpha.py +0 -0
  207. investing_algorithm_framework/services/metrics/beta.py +0 -0
  208. investing_algorithm_framework/services/metrics/cagr.py +60 -0
  209. investing_algorithm_framework/services/metrics/calmar_ratio.py +40 -0
  210. investing_algorithm_framework/services/metrics/drawdown.py +218 -0
  211. investing_algorithm_framework/services/metrics/equity_curve.py +24 -0
  212. investing_algorithm_framework/services/metrics/exposure.py +210 -0
  213. investing_algorithm_framework/services/metrics/generate.py +358 -0
  214. investing_algorithm_framework/services/metrics/mean_daily_return.py +84 -0
  215. investing_algorithm_framework/services/metrics/price_efficiency.py +57 -0
  216. investing_algorithm_framework/services/metrics/profit_factor.py +165 -0
  217. investing_algorithm_framework/services/metrics/recovery.py +113 -0
  218. investing_algorithm_framework/services/metrics/returns.py +452 -0
  219. investing_algorithm_framework/services/metrics/risk_free_rate.py +28 -0
  220. investing_algorithm_framework/services/metrics/sharpe_ratio.py +137 -0
  221. investing_algorithm_framework/services/metrics/sortino_ratio.py +74 -0
  222. investing_algorithm_framework/services/metrics/standard_deviation.py +156 -0
  223. investing_algorithm_framework/services/metrics/trades.py +473 -0
  224. investing_algorithm_framework/services/metrics/treynor_ratio.py +0 -0
  225. investing_algorithm_framework/services/metrics/ulcer.py +0 -0
  226. investing_algorithm_framework/services/metrics/value_at_risk.py +0 -0
  227. investing_algorithm_framework/services/metrics/volatility.py +118 -0
  228. investing_algorithm_framework/services/metrics/win_rate.py +177 -0
  229. investing_algorithm_framework/services/order_service/__init__.py +9 -0
  230. investing_algorithm_framework/services/order_service/order_backtest_service.py +178 -0
  231. investing_algorithm_framework/services/order_service/order_executor_lookup.py +110 -0
  232. investing_algorithm_framework/services/order_service/order_service.py +826 -0
  233. investing_algorithm_framework/services/portfolios/__init__.py +16 -0
  234. investing_algorithm_framework/services/portfolios/backtest_portfolio_service.py +54 -0
  235. investing_algorithm_framework/services/{portfolio_configuration_service.py → portfolios/portfolio_configuration_service.py} +27 -12
  236. investing_algorithm_framework/services/portfolios/portfolio_provider_lookup.py +106 -0
  237. investing_algorithm_framework/services/portfolios/portfolio_service.py +188 -0
  238. investing_algorithm_framework/services/portfolios/portfolio_snapshot_service.py +136 -0
  239. investing_algorithm_framework/services/portfolios/portfolio_sync_service.py +182 -0
  240. investing_algorithm_framework/services/positions/__init__.py +7 -0
  241. investing_algorithm_framework/services/positions/position_service.py +210 -0
  242. investing_algorithm_framework/services/positions/position_snapshot_service.py +18 -0
  243. investing_algorithm_framework/services/repository_service.py +8 -2
  244. investing_algorithm_framework/services/trade_order_evaluator/__init__.py +9 -0
  245. investing_algorithm_framework/services/trade_order_evaluator/backtest_trade_oder_evaluator.py +117 -0
  246. investing_algorithm_framework/services/trade_order_evaluator/default_trade_order_evaluator.py +51 -0
  247. investing_algorithm_framework/services/trade_order_evaluator/trade_order_evaluator.py +80 -0
  248. investing_algorithm_framework/services/trade_service/__init__.py +9 -0
  249. investing_algorithm_framework/services/trade_service/trade_service.py +1099 -0
  250. investing_algorithm_framework/services/trade_service/trade_stop_loss_service.py +39 -0
  251. investing_algorithm_framework/services/trade_service/trade_take_profit_service.py +41 -0
  252. investing_algorithm_framework-7.25.6.dist-info/METADATA +535 -0
  253. investing_algorithm_framework-7.25.6.dist-info/RECORD +268 -0
  254. {investing_algorithm_framework-1.3.1.dist-info → investing_algorithm_framework-7.25.6.dist-info}/WHEEL +1 -2
  255. investing_algorithm_framework-7.25.6.dist-info/entry_points.txt +3 -0
  256. investing_algorithm_framework/app/algorithm.py +0 -410
  257. investing_algorithm_framework/domain/models/market_data/__init__.py +0 -11
  258. investing_algorithm_framework/domain/models/market_data/asset_price.py +0 -50
  259. investing_algorithm_framework/domain/models/market_data/ohlcv.py +0 -76
  260. investing_algorithm_framework/domain/models/market_data/order_book.py +0 -63
  261. investing_algorithm_framework/domain/models/market_data/ticker.py +0 -92
  262. investing_algorithm_framework/domain/models/order/order_fee.py +0 -45
  263. investing_algorithm_framework/domain/models/trading_data_types.py +0 -47
  264. investing_algorithm_framework/domain/models/trading_time_frame.py +0 -205
  265. investing_algorithm_framework/domain/singleton.py +0 -9
  266. investing_algorithm_framework/infrastructure/models/order/order_fee.py +0 -21
  267. investing_algorithm_framework/infrastructure/models/position/position_cost.py +0 -32
  268. investing_algorithm_framework/infrastructure/repositories/order_fee_repository.py +0 -15
  269. investing_algorithm_framework/infrastructure/repositories/position_cost_repository.py +0 -16
  270. investing_algorithm_framework/infrastructure/services/market_service.py +0 -422
  271. investing_algorithm_framework/services/market_data_service.py +0 -75
  272. investing_algorithm_framework/services/order_service.py +0 -464
  273. investing_algorithm_framework/services/portfolio_service.py +0 -105
  274. investing_algorithm_framework/services/position_cost_service.py +0 -5
  275. investing_algorithm_framework/services/position_service.py +0 -50
  276. investing_algorithm_framework/services/strategy_orchestrator_service.py +0 -219
  277. investing_algorithm_framework/setup_logging.py +0 -40
  278. investing_algorithm_framework-1.3.1.dist-info/AUTHORS.md +0 -8
  279. investing_algorithm_framework-1.3.1.dist-info/METADATA +0 -172
  280. investing_algorithm_framework-1.3.1.dist-info/RECORD +0 -103
  281. investing_algorithm_framework-1.3.1.dist-info/top_level.txt +0 -1
  282. {investing_algorithm_framework-1.3.1.dist-info → investing_algorithm_framework-7.25.6.dist-info}/LICENSE +0 -0
@@ -1,66 +1,68 @@
1
- from datetime import datetime
2
- from investing_algorithm_framework.domain.models.base_model import BaseModel
1
+ from dateutil.parser import parse
2
+
3
3
  from investing_algorithm_framework.domain.exceptions import \
4
4
  ImproperlyConfigured
5
+ from investing_algorithm_framework.domain.models.base_model import BaseModel
5
6
 
6
7
 
7
8
  class PortfolioConfiguration(BaseModel):
9
+ """
10
+ This class represents a portfolio configuration. It is used to
11
+ configure the portfolio that the user wants to create.
12
+
13
+ Attributes:
14
+ - market: The market where the portfolio will be created
15
+ - trading_symbol: The trading symbol of the portfolio
16
+ - track_from: The date from which the portfolio will be tracked
17
+ - identifier: The identifier of the portfolio
18
+ - initial_balance: The initial balance of the portfolio
19
+
20
+ For backtesting, a portfolio configuration is used to create a
21
+ portfolio that will be used to simulate the trading of the algorithm. if
22
+ the user does not provide an initial balance, the portfolio will be created
23
+ with a balance of according to the initial balanace of
24
+ the PortfolioConfiguration class.
25
+ """
8
26
 
9
27
  def __init__(
10
28
  self,
11
29
  market,
12
30
  trading_symbol,
13
- api_key,
14
- secret_key,
15
31
  track_from=None,
16
32
  identifier=None,
17
- max_unallocated=-1,
33
+ initial_balance=None,
18
34
  ):
19
35
  self._market = market
20
- self._api_key = api_key
21
- self._secret_key = secret_key
36
+
37
+ if self._market is not None:
38
+ self._market = self._market.upper()
39
+
22
40
  self._track_from = None
23
41
  self._trading_symbol = trading_symbol.upper()
24
42
  self._identifier = identifier
25
- self._max_unallocated = max_unallocated
43
+ self._initial_balance = initial_balance
26
44
 
27
45
  if self.identifier is None:
28
- self._identifier = market.lower()
46
+ self._identifier = market.upper()
47
+ else:
48
+ self._identifier = identifier.upper()
29
49
 
30
50
  if track_from:
31
- self._track_from = datetime.strptime(track_from, "%d/%m/%Y")
51
+ self._track_from = parse(track_from)
32
52
 
33
53
  if self.trading_symbol is None:
34
54
  raise ImproperlyConfigured(
35
55
  "Portfolio configuration requires a trading symbol"
36
56
  )
37
57
 
38
- if self.api_key is None:
39
- raise ImproperlyConfigured(
40
- "Portfolio configuration requires an api key"
41
- )
42
-
43
- if self.secret_key is None:
44
- raise ImproperlyConfigured(
45
- "Portfolio configuration requires a secret key"
46
- )
47
-
48
58
  @property
49
59
  def market(self):
50
60
 
51
- if hasattr(self._market, "lower"):
52
- return self._market.lower()
61
+ if hasattr(self._market, "upper"):
62
+ return self._market.upper()
53
63
 
54
64
  return self._market
55
65
 
56
- @property
57
- def secret_key(self):
58
- return self._secret_key
59
-
60
- @property
61
- def api_key(self):
62
- return self._api_key
63
-
64
66
  @property
65
67
  def track_from(self):
66
68
  return self._track_from
@@ -74,20 +76,18 @@ class PortfolioConfiguration(BaseModel):
74
76
  return self._trading_symbol
75
77
 
76
78
  @property
77
- def max_unallocated(self):
78
- return self._max_unallocated
79
+ def initial_balance(self):
80
+ return self._initial_balance
79
81
 
80
82
  @property
81
- def has_unallocated_limit(self):
82
- return self.max_unallocated != -1
83
+ def has_initial_balance(self):
84
+ return self._initial_balance is not None
83
85
 
84
86
  def __repr__(self):
85
87
  return self.repr(
86
88
  market=self.market,
87
89
  trading_symbol=self.trading_symbol,
88
- api_key=self.api_key,
89
- secret_key=self.secret_key,
90
90
  identifier=self.identifier,
91
91
  track_from=self.track_from,
92
- max_unallocated=self.max_unallocated,
92
+ initial_balance=self.initial_balance
93
93
  )
@@ -0,0 +1,208 @@
1
+ from datetime import timezone
2
+
3
+ from dateutil import parser
4
+
5
+ from investing_algorithm_framework.domain.models.base_model import BaseModel
6
+
7
+
8
+ class PortfolioSnapshot(BaseModel):
9
+
10
+ def __init__(
11
+ self,
12
+ portfolio_id=None,
13
+ trading_symbol=None,
14
+ pending_value=None,
15
+ unallocated=None,
16
+ net_size=None,
17
+ total_net_gain=None,
18
+ total_revenue=None,
19
+ total_cost=None,
20
+ total_value=None,
21
+ cash_flow=None,
22
+ created_at=None,
23
+ position_snapshots=None,
24
+ metadata=None,
25
+ ):
26
+ self.portfolio_id = portfolio_id
27
+ self.trading_symbol = trading_symbol
28
+ self.pending_value = pending_value
29
+ self.unallocated = unallocated
30
+ self.total_net_gain = total_net_gain
31
+ self.total_revenue = total_revenue
32
+ self.total_value = total_value if total_value is not None else 0.0
33
+ self.net_size = net_size
34
+ self.total_cost = total_cost
35
+ self.cash_flow = cash_flow
36
+ self.metadata = metadata if metadata is not None else {}
37
+
38
+ if created_at is not None and isinstance(created_at, str):
39
+ self.created_at = parser.parse(created_at)
40
+ else:
41
+ self.created_at = created_at
42
+
43
+ # Make sure that created_at is a timezone aware datetime object
44
+ self.created_at = self.created_at.replace(tzinfo=timezone.utc)
45
+
46
+ if position_snapshots is None:
47
+ position_snapshots = []
48
+
49
+ self.position_snapshots = position_snapshots
50
+
51
+ def get_portfolio_id(self):
52
+ return self.portfolio_id
53
+
54
+ def set_portfolio_id(self, portfolio_id):
55
+ self.portfolio_id = portfolio_id
56
+
57
+ def get_trading_symbol(self):
58
+ return self.trading_symbol
59
+
60
+ def set_trading_symbol(self, trading_symbol):
61
+ self.trading_symbol = trading_symbol.upper()
62
+
63
+ def get_pending_value(self):
64
+ return self.pending_value
65
+
66
+ def set_pending_value(self, pending_value):
67
+ self.pending_value = pending_value
68
+
69
+ def get_unallocated(self):
70
+ return self.unallocated
71
+
72
+ def set_unallocated(self, unallocated):
73
+ self.unallocated = unallocated
74
+
75
+ def get_total_net_gain(self):
76
+ return self.total_net_gain
77
+
78
+ def set_total_net_gain(self, total_net_gain):
79
+ self.total_net_gain = total_net_gain
80
+
81
+ def get_total_revenue(self):
82
+ return self.total_revenue
83
+
84
+ def set_total_revenue(self, total_revenue):
85
+ self.total_revenue = total_revenue
86
+
87
+ def get_total_value(self):
88
+ return self.total_value
89
+
90
+ def set_total_value(self, total_value):
91
+ self.total_value = total_value
92
+
93
+ def get_total_cost(self):
94
+ return self.total_cost
95
+
96
+ def set_total_cost(self, total_cost):
97
+ self.total_cost = total_cost
98
+
99
+ def get_cash_flow(self):
100
+ return self.cash_flow
101
+
102
+ def set_cash_flow(self, cash_flow):
103
+ self.cash_flow = cash_flow
104
+
105
+ def get_created_at(self):
106
+ return self.created_at
107
+
108
+ def set_created_at(self, created_at):
109
+ self.created_at = created_at
110
+
111
+ def get_portfolio_snapshot_id(self):
112
+ return self.portfolio_snapshot_id
113
+
114
+ def set_position_snapshots(self, position_snapshots):
115
+ self.position_snapshots = position_snapshots
116
+
117
+ def get_position_snapshots(self):
118
+ return self.position_snapshots
119
+
120
+ def set_portfolio_snapshot_id(self, portfolio_snapshot_id):
121
+ self.portfolio_snapshot_id = portfolio_snapshot_id
122
+
123
+ def __repr__(self):
124
+ return self.repr(
125
+ portfolio_id=self.portfolio_id,
126
+ created_at=self.created_at.strftime("%Y-%m-%d %H:%M:%S"),
127
+ trading_symbol=self.trading_symbol,
128
+ net_size=self.net_size,
129
+ unallocated=self.unallocated,
130
+ pending_value=self.pending_value,
131
+ total_net_gain=self.total_net_gain,
132
+ total_revenue=self.total_revenue,
133
+ total_cost=self.total_cost,
134
+ cash_flow=self.cash_flow,
135
+ metadata=self.metadata,
136
+ )
137
+
138
+ def to_dict(self, datetime_format=None):
139
+ """
140
+ Convert the portfolio snapshot object to a dictionary
141
+
142
+ Args:
143
+ datetime_format (str): The format to use for the datetime fields.
144
+ If None, the datetime fields will be returned as is.
145
+ Defaults to None.
146
+
147
+ Returns:
148
+ dict: A dictionary representation of the portfolio snapshot object.
149
+ """
150
+ def ensure_iso(value):
151
+ if hasattr(value, "isoformat"):
152
+ if value.tzinfo is None:
153
+ value = value.replace(tzinfo=timezone.utc)
154
+ return value.isoformat()
155
+ return value
156
+
157
+ created_at = ensure_iso(self.created_at) if self.created_at else None
158
+
159
+ return {
160
+ "metadata": self.metadata if self.metadata else {},
161
+ "portfolio_id": self.portfolio_id if self.portfolio_id else "",
162
+ "trading_symbol": self.trading_symbol
163
+ if self.trading_symbol else "",
164
+ "pending_value": self.pending_value if self.pending_value else 0.0,
165
+ "unallocated": self.unallocated if self.unallocated else 0.0,
166
+ "total_net_gain": self.total_net_gain
167
+ if self.total_net_gain else 0.0,
168
+ "total_revenue": self.total_revenue if self.total_revenue else 0.0,
169
+ "total_cost": self.total_cost if self.total_cost else 0.0,
170
+ "cash_flow": self.cash_flow if self.cash_flow else 0.0,
171
+ "net_size": self.net_size if self.net_size else 0.0,
172
+ "created_at": created_at if created_at else "",
173
+ "total_value": self.total_value if self.total_value else 0.0,
174
+ }
175
+
176
+ @staticmethod
177
+ def from_dict(data):
178
+ """
179
+ Create a PortfolioSnapshot object from a dictionary.
180
+
181
+ Args:
182
+ data (dict): A dictionary containing the portfolio snapshot data.
183
+
184
+ Returns:
185
+ PortfolioSnapshot: An instance of PortfolioSnapshot.
186
+ """
187
+ created_at_str = data.get("created_at")
188
+ created_at = parser.parse(created_at_str)
189
+
190
+ # Ensure created_at is timezone aware
191
+ created_at = created_at.replace(tzinfo=timezone.utc)
192
+
193
+ return PortfolioSnapshot(
194
+ net_size=data.get("net_size", 0.0),
195
+ created_at=created_at,
196
+ total_value=data.get("total_value", 0.0),
197
+ trading_symbol=data.get(
198
+ "trading_symbol", None
199
+ ),
200
+ portfolio_id=data.get("portfolio_id", None),
201
+ pending_value=data.get("pending_value", 0.0),
202
+ unallocated=data.get("unallocated", 0.0),
203
+ total_net_gain=data.get("total_net_gain", 0.0),
204
+ total_revenue=data.get("total_revenue", 0.0),
205
+ total_cost=data.get("total_cost", 0.0),
206
+ cash_flow=data.get("cash_flow", 0.0),
207
+ metadata=data.get("metadata", {})
208
+ )
@@ -1,4 +1,5 @@
1
1
  from .position import Position
2
- from .position_cost import PositionCost
2
+ from .position_snapshot import PositionSnapshot
3
+ from .position_size import PositionSize
3
4
 
4
- __all__ = ["Position", "PositionCost"]
5
+ __all__ = ["Position", "PositionSnapshot", "PositionSize"]
@@ -2,15 +2,20 @@ from investing_algorithm_framework.domain.models.base_model import BaseModel
2
2
 
3
3
 
4
4
  class Position(BaseModel):
5
+ """
6
+ This class represents a position in a portfolio.
7
+ """
5
8
 
6
9
  def __init__(
7
10
  self,
8
11
  symbol=None,
9
12
  amount=0,
13
+ cost=0,
10
14
  portfolio_id=None
11
15
  ):
12
16
  self.symbol = symbol
13
17
  self.amount = amount
18
+ self.cost = cost
14
19
  self.portfolio_id = portfolio_id
15
20
 
16
21
  def get_symbol(self):
@@ -22,6 +27,12 @@ class Position(BaseModel):
22
27
  def get_amount(self):
23
28
  return self.amount
24
29
 
30
+ def get_cost(self):
31
+ return self.cost
32
+
33
+ def set_cost(self, cost):
34
+ self.cost = cost
35
+
25
36
  def set_amount(self, amount):
26
37
  self.amount = amount
27
38
 
@@ -31,9 +42,27 @@ class Position(BaseModel):
31
42
  def set_portfolio_id(self, portfolio_id):
32
43
  self.portfolio_id = portfolio_id
33
44
 
45
+ def to_dict(self):
46
+ return {
47
+ "symbol": self.symbol,
48
+ "amount": self.amount,
49
+ "cost": self.cost,
50
+ "portfolio_id": self.portfolio_id,
51
+ }
52
+
53
+ @staticmethod
54
+ def from_dict(data: dict):
55
+ return Position(
56
+ symbol=data.get("symbol"),
57
+ amount=data.get("amount", 0),
58
+ cost=data.get("cost", 0),
59
+ portfolio_id=data.get("portfolio_id"),
60
+ )
61
+
34
62
  def __repr__(self):
35
63
  return self.repr(
36
64
  symbol=self.symbol,
37
65
  amount=self.amount,
66
+ cost=self.cost,
38
67
  portfolio_id=self.portfolio_id,
39
68
  )
@@ -0,0 +1,41 @@
1
+ from typing import Optional
2
+ from investing_algorithm_framework.domain.exceptions import \
3
+ OperationalException
4
+
5
+
6
+ class PositionSize:
7
+ """
8
+ Defines how much capital to allocate to a specific symbol.
9
+ """
10
+
11
+ def __init__(
12
+ self,
13
+ symbol: str,
14
+ percentage_of_portfolio: Optional[float] = None,
15
+ fixed_amount: Optional[float] = None
16
+ ):
17
+ self.symbol = symbol
18
+ self.percentage_of_portfolio = percentage_of_portfolio
19
+ self.fixed_amount = fixed_amount
20
+
21
+ def get_size(self, portfolio, asset_price) -> float:
22
+ """
23
+ Calculate size in currency/units.
24
+ """
25
+ if self.fixed_amount is not None:
26
+ return self.fixed_amount
27
+ elif self.percentage_of_portfolio is not None:
28
+ total_value = portfolio.get_unallocated() + portfolio.allocated
29
+ return total_value * (self.percentage_of_portfolio / 100)
30
+ else:
31
+ raise OperationalException(
32
+ "A position size object must have either a fixed amount or a "
33
+ "percentage of the portfolio defined."
34
+ )
35
+
36
+ def __repr__(self) -> str:
37
+ return (
38
+ f"PositionSize(symbol={self.symbol}, "
39
+ f"percentage_of_portfolio={self.percentage_of_portfolio}, "
40
+ f"fixed_amount={self.fixed_amount})"
41
+ )
@@ -1,17 +1,19 @@
1
1
  from investing_algorithm_framework.domain.models.base_model import BaseModel
2
2
 
3
3
 
4
- class PositionCost(BaseModel):
4
+ class PositionSnapshot(BaseModel):
5
5
 
6
6
  def __init__(
7
7
  self,
8
8
  symbol=None,
9
9
  amount=0,
10
- position_id=None
10
+ cost=0,
11
+ portfolio_snapshot_id=None
11
12
  ):
12
13
  self.symbol = symbol
13
14
  self.amount = amount
14
- self.position_id = position_id
15
+ self.cost = cost
16
+ self.portfolio_snapshot_id = portfolio_snapshot_id
15
17
 
16
18
  def get_symbol(self):
17
19
  return self.symbol
@@ -22,18 +24,24 @@ class PositionCost(BaseModel):
22
24
  def get_amount(self):
23
25
  return self.amount
24
26
 
27
+ def get_cost(self):
28
+ return self.cost
29
+
30
+ def set_cost(self, cost):
31
+ self.cost = cost
32
+
25
33
  def set_amount(self, amount):
26
34
  self.amount = amount
27
35
 
28
- def get_position_id(self):
29
- return self.position_id
36
+ def get_portfolio_snapshot_id(self):
37
+ return self.portfolio_snapshot_id
30
38
 
31
- def set_position_id(self, position_id):
32
- self.position_id = position_id
39
+ def set_portfolio_snapshot_id(self, portfolio_snapshot_id):
40
+ self.portfolio_snapshot_id = portfolio_snapshot_id
33
41
 
34
42
  def __repr__(self):
35
43
  return self.repr(
36
44
  symbol=self.symbol,
37
45
  amount=self.amount,
38
- position_id=self.position_id,
46
+ portfolio_snapshot_id=self.portfolio_snapshot_id,
39
47
  )
@@ -0,0 +1,7 @@
1
+ from .stop_loss_rule import StopLossRule
2
+ from .take_profit_rule import TakeProfitRule
3
+
4
+ __all__ = [
5
+ "StopLossRule",
6
+ "TakeProfitRule",
7
+ ]
@@ -0,0 +1,51 @@
1
+ class StopLossRule:
2
+ """
3
+ A rule that defines when to trigger a stop loss based
4
+ on a specified threshold such as a percentage drop in price or
5
+ a fixed amount.
6
+
7
+ if trade_risk_type is fixed, the stop loss price is calculated as follows:
8
+ You buy an asset at $100.
9
+ You set a 5% stop loss, meaning you will sell if
10
+ the price drops to $95.
11
+ If the price rises to $120, the stop loss is not triggered.
12
+ But if the price keeps falling to $95, the stop loss triggers,
13
+ and you exit with a $5 loss.
14
+
15
+ if trade_risk_type is trailing, the stop loss price is
16
+ calculated as follows:
17
+ You buy an asset at $100.
18
+ You set a 5% trailing stop loss, meaning you will sell if
19
+ the price drops 5% from its peak at $96
20
+ If the price rises to $120, the stop loss adjusts
21
+ to $114 (5% below $120).
22
+ If the price falls to $114, the position is
23
+ closed, securing a $14 profit.
24
+ But if the price keeps rising to $150, the stop
25
+ loss moves up to $142.50.
26
+ If the price drops from $150 to $142.50, the stop
27
+ loss triggers, and you exit with a $42.50 profit.
28
+
29
+ Attributes:
30
+ - percentage_threshold (float): The percentage drop in price
31
+ that triggers the stop loss.
32
+ - trailing (bool): Indicates whether the stop loss is trailing
33
+ or fixed.
34
+ - sell_percentage (float): The percentage of the position to sell
35
+ when the stop loss is triggered.
36
+ - symbol (str): The symbol of the asset the stop loss rule
37
+ applies to. Symbol is defined as the target symbol
38
+ (the asset being traded) combined with the trading symbol
39
+ (the asset used to trade the target symbol), e.g., 'BTC-EUR'.
40
+ """
41
+ def __init__(
42
+ self,
43
+ percentage_threshold: float,
44
+ sell_percentage: float,
45
+ symbol: str,
46
+ trailing: bool = False,
47
+ ):
48
+ self.percentage_threshold = percentage_threshold
49
+ self.trailing = trailing
50
+ self.sell_percentage = sell_percentage
51
+ self.symbol = symbol
@@ -0,0 +1,55 @@
1
+ class TakeProfitRule:
2
+ """
3
+ A rule that defines when to trigger a take profit based
4
+ on a specified threshold such as a percentage gain in price or
5
+ a fixed amount.
6
+
7
+ if trailing is set to true, the take profit price is
8
+ calculated as follows:
9
+ You buy an asset at $100.
10
+ You set a 5% take profit, meaning you will sell if the price
11
+ rises to $105.
12
+ If the price rises to $120, the take profit triggers,
13
+ and you exit with a $20 profit.
14
+ But if the price keeps falling below $105, the take profit is not
15
+ triggered.
16
+
17
+ if trailing is set to true, the take profit price is
18
+ calculated as follows:
19
+ You buy an asset at $100.
20
+ You set a 5% trailing take profit, the moment the price rises
21
+ 5% the initial take profit mark will be set. This means you
22
+ will set the take_profit_price initially at none and
23
+ only if the price hits $105, you will set the
24
+ take_profit_price to $105.
25
+ if the price drops below $105, the take profit is triggered.
26
+ If the price rises to $120, the take profit adjusts to
27
+ $114 (5% below $120).
28
+ If the price falls to $114, the position is closed,
29
+ securing a $14 profit.
30
+ But if the price keeps rising to $150, the take profit
31
+ moves up to $142.50.
32
+
33
+
34
+ Attributes:
35
+ - percentage_threshold (float): The percentage gain in price
36
+ that triggers the stop loss.
37
+ - trailing (bool): Indicates whether the take profit is trailing
38
+ or fixed.
39
+ - sell_percentage (float): The percentage of the position to sell
40
+ when the take profit is triggered.
41
+ - symbol (str): The symbol of the asset the take profit rule
42
+ applies to. Symbol is defined as only the target symbol.
43
+ So for example, 'BTC' in 'BTC-EUR' or 'META' in 'META-USD'.
44
+ """
45
+ def __init__(
46
+ self,
47
+ percentage_threshold: float,
48
+ sell_percentage: float,
49
+ symbol: str,
50
+ trailing: bool = False,
51
+ ):
52
+ self.percentage_threshold = percentage_threshold
53
+ self.trailing = trailing
54
+ self.sell_percentage = sell_percentage
55
+ self.symbol = symbol
@@ -0,0 +1,45 @@
1
+ from enum import Enum
2
+
3
+
4
+ class SnapshotInterval(Enum):
5
+ STRATEGY_ITERATION = "STRATEGY_ITERATION"
6
+ DAILY = "DAILY"
7
+
8
+ @staticmethod
9
+ def from_string(value: str):
10
+
11
+ if isinstance(value, str):
12
+
13
+ for entry in SnapshotInterval:
14
+
15
+ if value.upper() == entry.value:
16
+ return entry
17
+
18
+ raise ValueError(
19
+ f"Could not convert {value} to SnapshotInterval"
20
+ )
21
+ return None
22
+
23
+ @staticmethod
24
+ def from_value(value):
25
+
26
+ if isinstance(value, str):
27
+ return SnapshotInterval.from_string(value)
28
+
29
+ if isinstance(value, SnapshotInterval):
30
+
31
+ for entry in SnapshotInterval:
32
+
33
+ if value == entry:
34
+ return entry
35
+
36
+ raise ValueError(
37
+ f"Could not convert {value} to SnapshotInterval"
38
+ )
39
+
40
+ def equals(self, other):
41
+
42
+ if isinstance(other, Enum):
43
+ return self.value == other.value
44
+ else:
45
+ return SnapshotInterval.from_string(other) == self
@@ -0,0 +1,33 @@
1
+ from dataclasses import dataclass
2
+
3
+ from .time_unit import TimeUnit
4
+
5
+
6
+ @dataclass(frozen=True)
7
+ class StrategyProfile:
8
+ """
9
+ StrategyProfile class that represents the profile of a trading strategy.
10
+ """
11
+ strategy_id: str = None
12
+ interval: int = None
13
+ time_unit: TimeUnit = None
14
+ trading_time_frame: str = None
15
+ trading_time_frame_start_date: str = None
16
+ backtest_start_date_data: str = None
17
+ backtest_data_index_date: str = None
18
+ symbols: list = None
19
+ market: str = None
20
+ trading_data_type: str = None
21
+ trading_data_types: list = None
22
+ data_sources: list = None
23
+
24
+ def get_runs_per_day(self):
25
+
26
+ if self.time_unit is None:
27
+ return 0
28
+ elif TimeUnit.SECOND.equals(self.time_unit):
29
+ return 86400 / self.interval
30
+ elif TimeUnit.MINUTE.equals(self.time_unit):
31
+ return 1440 / self.interval
32
+ else:
33
+ return 24 / self.interval