investing-algorithm-framework 1.5__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 (276) hide show
  1. investing_algorithm_framework/__init__.py +192 -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 +29 -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 +2220 -379
  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/time_metrics_table.py +80 -0
  31. investing_algorithm_framework/app/reporting/tables/trade_metrics_table.py +147 -0
  32. investing_algorithm_framework/app/reporting/tables/trades_table.py +75 -0
  33. investing_algorithm_framework/app/reporting/tables/utils.py +29 -0
  34. investing_algorithm_framework/app/reporting/templates/report_template.html.j2 +154 -0
  35. investing_algorithm_framework/app/stateless/action_handlers/__init__.py +6 -3
  36. investing_algorithm_framework/app/stateless/action_handlers/action_handler_strategy.py +1 -1
  37. investing_algorithm_framework/app/stateless/action_handlers/check_online_handler.py +2 -1
  38. investing_algorithm_framework/app/stateless/action_handlers/run_strategy_handler.py +14 -7
  39. investing_algorithm_framework/app/strategy.py +867 -60
  40. investing_algorithm_framework/app/task.py +5 -3
  41. investing_algorithm_framework/app/web/__init__.py +2 -1
  42. investing_algorithm_framework/app/web/controllers/__init__.py +2 -2
  43. investing_algorithm_framework/app/web/controllers/orders.py +3 -2
  44. investing_algorithm_framework/app/web/controllers/positions.py +2 -2
  45. investing_algorithm_framework/app/web/create_app.py +4 -2
  46. investing_algorithm_framework/app/web/schemas/position.py +1 -0
  47. investing_algorithm_framework/cli/__init__.py +0 -0
  48. investing_algorithm_framework/cli/cli.py +231 -0
  49. investing_algorithm_framework/cli/deploy_to_aws_lambda.py +501 -0
  50. investing_algorithm_framework/cli/deploy_to_azure_function.py +718 -0
  51. investing_algorithm_framework/cli/initialize_app.py +603 -0
  52. investing_algorithm_framework/cli/templates/.gitignore.template +178 -0
  53. investing_algorithm_framework/cli/templates/app.py.template +18 -0
  54. investing_algorithm_framework/cli/templates/app_aws_lambda_function.py.template +48 -0
  55. investing_algorithm_framework/cli/templates/app_azure_function.py.template +14 -0
  56. investing_algorithm_framework/cli/templates/app_web.py.template +18 -0
  57. investing_algorithm_framework/cli/templates/aws_lambda_dockerfile.template +22 -0
  58. investing_algorithm_framework/cli/templates/aws_lambda_dockerignore.template +92 -0
  59. investing_algorithm_framework/cli/templates/aws_lambda_readme.md.template +110 -0
  60. investing_algorithm_framework/cli/templates/aws_lambda_requirements.txt.template +2 -0
  61. investing_algorithm_framework/cli/templates/azure_function_function_app.py.template +65 -0
  62. investing_algorithm_framework/cli/templates/azure_function_host.json.template +15 -0
  63. investing_algorithm_framework/cli/templates/azure_function_local.settings.json.template +8 -0
  64. investing_algorithm_framework/cli/templates/azure_function_requirements.txt.template +3 -0
  65. investing_algorithm_framework/cli/templates/data_providers.py.template +17 -0
  66. investing_algorithm_framework/cli/templates/env.example.template +2 -0
  67. investing_algorithm_framework/cli/templates/env_azure_function.example.template +4 -0
  68. investing_algorithm_framework/cli/templates/market_data_providers.py.template +9 -0
  69. investing_algorithm_framework/cli/templates/readme.md.template +135 -0
  70. investing_algorithm_framework/cli/templates/requirements.txt.template +2 -0
  71. investing_algorithm_framework/cli/templates/run_backtest.py.template +20 -0
  72. investing_algorithm_framework/cli/templates/strategy.py.template +124 -0
  73. investing_algorithm_framework/cli/validate_backtest_checkpoints.py +197 -0
  74. investing_algorithm_framework/create_app.py +40 -7
  75. investing_algorithm_framework/dependency_container.py +100 -47
  76. investing_algorithm_framework/domain/__init__.py +97 -30
  77. investing_algorithm_framework/domain/algorithm_id.py +69 -0
  78. investing_algorithm_framework/domain/backtesting/__init__.py +25 -0
  79. investing_algorithm_framework/domain/backtesting/backtest.py +548 -0
  80. investing_algorithm_framework/domain/backtesting/backtest_date_range.py +113 -0
  81. investing_algorithm_framework/domain/backtesting/backtest_evaluation_focuss.py +241 -0
  82. investing_algorithm_framework/domain/backtesting/backtest_metrics.py +470 -0
  83. investing_algorithm_framework/domain/backtesting/backtest_permutation_test.py +275 -0
  84. investing_algorithm_framework/domain/backtesting/backtest_run.py +663 -0
  85. investing_algorithm_framework/domain/backtesting/backtest_summary_metrics.py +162 -0
  86. investing_algorithm_framework/domain/backtesting/backtest_utils.py +198 -0
  87. investing_algorithm_framework/domain/backtesting/combine_backtests.py +392 -0
  88. investing_algorithm_framework/domain/config.py +59 -136
  89. investing_algorithm_framework/domain/constants.py +18 -37
  90. investing_algorithm_framework/domain/data_provider.py +334 -0
  91. investing_algorithm_framework/domain/data_structures.py +42 -0
  92. investing_algorithm_framework/domain/exceptions.py +51 -1
  93. investing_algorithm_framework/domain/models/__init__.py +26 -19
  94. investing_algorithm_framework/domain/models/app_mode.py +34 -0
  95. investing_algorithm_framework/domain/models/data/__init__.py +7 -0
  96. investing_algorithm_framework/domain/models/data/data_source.py +222 -0
  97. investing_algorithm_framework/domain/models/data/data_type.py +46 -0
  98. investing_algorithm_framework/domain/models/event.py +35 -0
  99. investing_algorithm_framework/domain/models/market/__init__.py +5 -0
  100. investing_algorithm_framework/domain/models/market/market_credential.py +88 -0
  101. investing_algorithm_framework/domain/models/order/__init__.py +3 -4
  102. investing_algorithm_framework/domain/models/order/order.py +198 -65
  103. investing_algorithm_framework/domain/models/order/order_status.py +2 -2
  104. investing_algorithm_framework/domain/models/order/order_type.py +1 -3
  105. investing_algorithm_framework/domain/models/portfolio/__init__.py +6 -2
  106. investing_algorithm_framework/domain/models/portfolio/portfolio.py +98 -3
  107. investing_algorithm_framework/domain/models/portfolio/portfolio_configuration.py +37 -43
  108. investing_algorithm_framework/domain/models/portfolio/portfolio_snapshot.py +108 -11
  109. investing_algorithm_framework/domain/models/position/__init__.py +2 -1
  110. investing_algorithm_framework/domain/models/position/position.py +20 -0
  111. investing_algorithm_framework/domain/models/position/position_size.py +41 -0
  112. investing_algorithm_framework/domain/models/position/position_snapshot.py +0 -2
  113. investing_algorithm_framework/domain/models/risk_rules/__init__.py +7 -0
  114. investing_algorithm_framework/domain/models/risk_rules/stop_loss_rule.py +51 -0
  115. investing_algorithm_framework/domain/models/risk_rules/take_profit_rule.py +55 -0
  116. investing_algorithm_framework/domain/models/snapshot_interval.py +45 -0
  117. investing_algorithm_framework/domain/models/strategy_profile.py +19 -141
  118. investing_algorithm_framework/domain/models/time_frame.py +94 -98
  119. investing_algorithm_framework/domain/models/time_interval.py +33 -0
  120. investing_algorithm_framework/domain/models/time_unit.py +66 -2
  121. investing_algorithm_framework/domain/models/tracing/__init__.py +0 -0
  122. investing_algorithm_framework/domain/models/tracing/trace.py +23 -0
  123. investing_algorithm_framework/domain/models/trade/__init__.py +11 -0
  124. investing_algorithm_framework/domain/models/trade/trade.py +389 -0
  125. investing_algorithm_framework/domain/models/trade/trade_status.py +40 -0
  126. investing_algorithm_framework/domain/models/trade/trade_stop_loss.py +332 -0
  127. investing_algorithm_framework/domain/models/trade/trade_take_profit.py +365 -0
  128. investing_algorithm_framework/domain/order_executor.py +112 -0
  129. investing_algorithm_framework/domain/portfolio_provider.py +118 -0
  130. investing_algorithm_framework/domain/services/__init__.py +11 -0
  131. investing_algorithm_framework/domain/services/market_credential_service.py +37 -0
  132. investing_algorithm_framework/domain/services/portfolios/__init__.py +5 -0
  133. investing_algorithm_framework/domain/services/portfolios/portfolio_sync_service.py +9 -0
  134. investing_algorithm_framework/domain/services/rounding_service.py +27 -0
  135. investing_algorithm_framework/domain/services/state_handler.py +38 -0
  136. investing_algorithm_framework/domain/strategy.py +1 -29
  137. investing_algorithm_framework/domain/utils/__init__.py +15 -5
  138. investing_algorithm_framework/domain/utils/csv.py +22 -0
  139. investing_algorithm_framework/domain/utils/custom_tqdm.py +22 -0
  140. investing_algorithm_framework/domain/utils/dates.py +57 -0
  141. investing_algorithm_framework/domain/utils/jupyter_notebook_detection.py +19 -0
  142. investing_algorithm_framework/domain/utils/polars.py +53 -0
  143. investing_algorithm_framework/domain/utils/random.py +29 -0
  144. investing_algorithm_framework/download_data.py +244 -0
  145. investing_algorithm_framework/infrastructure/__init__.py +37 -11
  146. investing_algorithm_framework/infrastructure/data_providers/__init__.py +36 -0
  147. investing_algorithm_framework/infrastructure/data_providers/ccxt.py +1152 -0
  148. investing_algorithm_framework/infrastructure/data_providers/csv.py +568 -0
  149. investing_algorithm_framework/infrastructure/data_providers/pandas.py +599 -0
  150. investing_algorithm_framework/infrastructure/database/__init__.py +6 -2
  151. investing_algorithm_framework/infrastructure/database/sql_alchemy.py +86 -12
  152. investing_algorithm_framework/infrastructure/models/__init__.py +7 -3
  153. investing_algorithm_framework/infrastructure/models/order/__init__.py +2 -2
  154. investing_algorithm_framework/infrastructure/models/order/order.py +53 -53
  155. investing_algorithm_framework/infrastructure/models/order/order_metadata.py +44 -0
  156. investing_algorithm_framework/infrastructure/models/order_trade_association.py +10 -0
  157. investing_algorithm_framework/infrastructure/models/portfolio/__init__.py +1 -1
  158. investing_algorithm_framework/infrastructure/models/portfolio/portfolio_snapshot.py +8 -2
  159. investing_algorithm_framework/infrastructure/models/portfolio/{portfolio.py → sql_portfolio.py} +17 -6
  160. investing_algorithm_framework/infrastructure/models/position/position_snapshot.py +3 -1
  161. investing_algorithm_framework/infrastructure/models/trades/__init__.py +9 -0
  162. investing_algorithm_framework/infrastructure/models/trades/trade.py +130 -0
  163. investing_algorithm_framework/infrastructure/models/trades/trade_stop_loss.py +59 -0
  164. investing_algorithm_framework/infrastructure/models/trades/trade_take_profit.py +55 -0
  165. investing_algorithm_framework/infrastructure/order_executors/__init__.py +21 -0
  166. investing_algorithm_framework/infrastructure/order_executors/backtest_oder_executor.py +28 -0
  167. investing_algorithm_framework/infrastructure/order_executors/ccxt_order_executor.py +200 -0
  168. investing_algorithm_framework/infrastructure/portfolio_providers/__init__.py +19 -0
  169. investing_algorithm_framework/infrastructure/portfolio_providers/ccxt_portfolio_provider.py +199 -0
  170. investing_algorithm_framework/infrastructure/repositories/__init__.py +10 -4
  171. investing_algorithm_framework/infrastructure/repositories/order_metadata_repository.py +17 -0
  172. investing_algorithm_framework/infrastructure/repositories/order_repository.py +16 -5
  173. investing_algorithm_framework/infrastructure/repositories/portfolio_repository.py +2 -2
  174. investing_algorithm_framework/infrastructure/repositories/position_repository.py +11 -0
  175. investing_algorithm_framework/infrastructure/repositories/repository.py +84 -30
  176. investing_algorithm_framework/infrastructure/repositories/trade_repository.py +71 -0
  177. investing_algorithm_framework/infrastructure/repositories/trade_stop_loss_repository.py +29 -0
  178. investing_algorithm_framework/infrastructure/repositories/trade_take_profit_repository.py +29 -0
  179. investing_algorithm_framework/infrastructure/services/__init__.py +9 -4
  180. investing_algorithm_framework/infrastructure/services/aws/__init__.py +6 -0
  181. investing_algorithm_framework/infrastructure/services/aws/state_handler.py +193 -0
  182. investing_algorithm_framework/infrastructure/services/azure/__init__.py +5 -0
  183. investing_algorithm_framework/infrastructure/services/azure/state_handler.py +158 -0
  184. investing_algorithm_framework/infrastructure/services/backtesting/__init__.py +9 -0
  185. investing_algorithm_framework/infrastructure/services/backtesting/backtest_service.py +2596 -0
  186. investing_algorithm_framework/infrastructure/services/backtesting/event_backtest_service.py +285 -0
  187. investing_algorithm_framework/infrastructure/services/backtesting/vector_backtest_service.py +468 -0
  188. investing_algorithm_framework/services/__init__.py +123 -15
  189. investing_algorithm_framework/services/configuration_service.py +77 -11
  190. investing_algorithm_framework/services/data_providers/__init__.py +5 -0
  191. investing_algorithm_framework/services/data_providers/data_provider_service.py +1058 -0
  192. investing_algorithm_framework/services/market_credential_service.py +40 -0
  193. investing_algorithm_framework/services/metrics/__init__.py +119 -0
  194. investing_algorithm_framework/services/metrics/alpha.py +0 -0
  195. investing_algorithm_framework/services/metrics/beta.py +0 -0
  196. investing_algorithm_framework/services/metrics/cagr.py +60 -0
  197. investing_algorithm_framework/services/metrics/calmar_ratio.py +40 -0
  198. investing_algorithm_framework/services/metrics/drawdown.py +218 -0
  199. investing_algorithm_framework/services/metrics/equity_curve.py +24 -0
  200. investing_algorithm_framework/services/metrics/exposure.py +210 -0
  201. investing_algorithm_framework/services/metrics/generate.py +358 -0
  202. investing_algorithm_framework/services/metrics/mean_daily_return.py +84 -0
  203. investing_algorithm_framework/services/metrics/price_efficiency.py +57 -0
  204. investing_algorithm_framework/services/metrics/profit_factor.py +165 -0
  205. investing_algorithm_framework/services/metrics/recovery.py +113 -0
  206. investing_algorithm_framework/services/metrics/returns.py +452 -0
  207. investing_algorithm_framework/services/metrics/risk_free_rate.py +28 -0
  208. investing_algorithm_framework/services/metrics/sharpe_ratio.py +137 -0
  209. investing_algorithm_framework/services/metrics/sortino_ratio.py +74 -0
  210. investing_algorithm_framework/services/metrics/standard_deviation.py +156 -0
  211. investing_algorithm_framework/services/metrics/trades.py +473 -0
  212. investing_algorithm_framework/services/metrics/treynor_ratio.py +0 -0
  213. investing_algorithm_framework/services/metrics/ulcer.py +0 -0
  214. investing_algorithm_framework/services/metrics/value_at_risk.py +0 -0
  215. investing_algorithm_framework/services/metrics/volatility.py +118 -0
  216. investing_algorithm_framework/services/metrics/win_rate.py +177 -0
  217. investing_algorithm_framework/services/order_service/__init__.py +9 -0
  218. investing_algorithm_framework/services/order_service/order_backtest_service.py +178 -0
  219. investing_algorithm_framework/services/order_service/order_executor_lookup.py +110 -0
  220. investing_algorithm_framework/services/order_service/order_service.py +826 -0
  221. investing_algorithm_framework/services/portfolios/__init__.py +16 -0
  222. investing_algorithm_framework/services/portfolios/backtest_portfolio_service.py +54 -0
  223. investing_algorithm_framework/services/{portfolio_configuration_service.py → portfolios/portfolio_configuration_service.py} +27 -12
  224. investing_algorithm_framework/services/portfolios/portfolio_provider_lookup.py +106 -0
  225. investing_algorithm_framework/services/portfolios/portfolio_service.py +188 -0
  226. investing_algorithm_framework/services/portfolios/portfolio_snapshot_service.py +136 -0
  227. investing_algorithm_framework/services/portfolios/portfolio_sync_service.py +182 -0
  228. investing_algorithm_framework/services/positions/__init__.py +7 -0
  229. investing_algorithm_framework/services/positions/position_service.py +210 -0
  230. investing_algorithm_framework/services/repository_service.py +8 -2
  231. investing_algorithm_framework/services/trade_order_evaluator/__init__.py +9 -0
  232. investing_algorithm_framework/services/trade_order_evaluator/backtest_trade_oder_evaluator.py +117 -0
  233. investing_algorithm_framework/services/trade_order_evaluator/default_trade_order_evaluator.py +51 -0
  234. investing_algorithm_framework/services/trade_order_evaluator/trade_order_evaluator.py +80 -0
  235. investing_algorithm_framework/services/trade_service/__init__.py +9 -0
  236. investing_algorithm_framework/services/trade_service/trade_service.py +1099 -0
  237. investing_algorithm_framework/services/trade_service/trade_stop_loss_service.py +39 -0
  238. investing_algorithm_framework/services/trade_service/trade_take_profit_service.py +41 -0
  239. investing_algorithm_framework-7.25.6.dist-info/METADATA +535 -0
  240. investing_algorithm_framework-7.25.6.dist-info/RECORD +268 -0
  241. {investing_algorithm_framework-1.5.dist-info → investing_algorithm_framework-7.25.6.dist-info}/WHEEL +1 -2
  242. investing_algorithm_framework-7.25.6.dist-info/entry_points.txt +3 -0
  243. investing_algorithm_framework/app/algorithm.py +0 -630
  244. investing_algorithm_framework/domain/models/backtest_profile.py +0 -414
  245. investing_algorithm_framework/domain/models/market_data/__init__.py +0 -11
  246. investing_algorithm_framework/domain/models/market_data/asset_price.py +0 -50
  247. investing_algorithm_framework/domain/models/market_data/ohlcv.py +0 -105
  248. investing_algorithm_framework/domain/models/market_data/order_book.py +0 -63
  249. investing_algorithm_framework/domain/models/market_data/ticker.py +0 -92
  250. investing_algorithm_framework/domain/models/order/order_fee.py +0 -45
  251. investing_algorithm_framework/domain/models/trade.py +0 -78
  252. investing_algorithm_framework/domain/models/trading_data_types.py +0 -47
  253. investing_algorithm_framework/domain/models/trading_time_frame.py +0 -223
  254. investing_algorithm_framework/domain/singleton.py +0 -9
  255. investing_algorithm_framework/domain/utils/backtesting.py +0 -82
  256. investing_algorithm_framework/infrastructure/models/order/order_fee.py +0 -21
  257. investing_algorithm_framework/infrastructure/repositories/order_fee_repository.py +0 -15
  258. investing_algorithm_framework/infrastructure/services/market_backtest_service.py +0 -360
  259. investing_algorithm_framework/infrastructure/services/market_service.py +0 -410
  260. investing_algorithm_framework/infrastructure/services/performance_service.py +0 -192
  261. investing_algorithm_framework/services/backtest_service.py +0 -268
  262. investing_algorithm_framework/services/market_data_service.py +0 -77
  263. investing_algorithm_framework/services/order_backtest_service.py +0 -122
  264. investing_algorithm_framework/services/order_service.py +0 -752
  265. investing_algorithm_framework/services/portfolio_service.py +0 -164
  266. investing_algorithm_framework/services/portfolio_snapshot_service.py +0 -68
  267. investing_algorithm_framework/services/position_cost_service.py +0 -5
  268. investing_algorithm_framework/services/position_service.py +0 -63
  269. investing_algorithm_framework/services/strategy_orchestrator_service.py +0 -225
  270. investing_algorithm_framework-1.5.dist-info/AUTHORS.md +0 -8
  271. investing_algorithm_framework-1.5.dist-info/METADATA +0 -230
  272. investing_algorithm_framework-1.5.dist-info/RECORD +0 -119
  273. investing_algorithm_framework-1.5.dist-info/top_level.txt +0 -1
  274. /investing_algorithm_framework/{infrastructure/services/performance_backtest_service.py → app/reporting/tables/stop_loss_table.py} +0 -0
  275. /investing_algorithm_framework/services/{position_snapshot_service.py → positions/position_snapshot_service.py} +0 -0
  276. {investing_algorithm_framework-1.5.dist-info → investing_algorithm_framework-7.25.6.dist-info}/LICENSE +0 -0
@@ -1,68 +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,
18
- backtest=False
33
+ initial_balance=None,
19
34
  ):
20
35
  self._market = market
21
- self._api_key = api_key
22
- self._secret_key = secret_key
36
+
37
+ if self._market is not None:
38
+ self._market = self._market.upper()
39
+
23
40
  self._track_from = None
24
41
  self._trading_symbol = trading_symbol.upper()
25
42
  self._identifier = identifier
26
- self._max_unallocated = max_unallocated
27
- self._backtest = backtest
43
+ self._initial_balance = initial_balance
28
44
 
29
45
  if self.identifier is None:
30
- self._identifier = market.lower()
46
+ self._identifier = market.upper()
47
+ else:
48
+ self._identifier = identifier.upper()
31
49
 
32
50
  if track_from:
33
- self._track_from = datetime.strptime(track_from, "%d/%m/%Y")
51
+ self._track_from = parse(track_from)
34
52
 
35
53
  if self.trading_symbol is None:
36
54
  raise ImproperlyConfigured(
37
55
  "Portfolio configuration requires a trading symbol"
38
56
  )
39
57
 
40
- if self.api_key is None and not self._backtest:
41
- raise ImproperlyConfigured(
42
- "Portfolio configuration requires an api key"
43
- )
44
-
45
- if self.secret_key is None and not self._backtest:
46
- raise ImproperlyConfigured(
47
- "Portfolio configuration requires a secret key"
48
- )
49
-
50
58
  @property
51
59
  def market(self):
52
60
 
53
- if hasattr(self._market, "lower"):
54
- return self._market.lower()
61
+ if hasattr(self._market, "upper"):
62
+ return self._market.upper()
55
63
 
56
64
  return self._market
57
65
 
58
- @property
59
- def secret_key(self):
60
- return self._secret_key
61
-
62
- @property
63
- def api_key(self):
64
- return self._api_key
65
-
66
66
  @property
67
67
  def track_from(self):
68
68
  return self._track_from
@@ -76,24 +76,18 @@ class PortfolioConfiguration(BaseModel):
76
76
  return self._trading_symbol
77
77
 
78
78
  @property
79
- def max_unallocated(self):
80
- return self._max_unallocated
81
-
82
- @property
83
- def has_unallocated_limit(self):
84
- return self.max_unallocated != -1
79
+ def initial_balance(self):
80
+ return self._initial_balance
85
81
 
86
82
  @property
87
- def backtest(self):
88
- return self._backtest
83
+ def has_initial_balance(self):
84
+ return self._initial_balance is not None
89
85
 
90
86
  def __repr__(self):
91
87
  return self.repr(
92
88
  market=self.market,
93
89
  trading_symbol=self.trading_symbol,
94
- api_key=self.api_key,
95
- secret_key=self.secret_key,
96
90
  identifier=self.identifier,
97
91
  track_from=self.track_from,
98
- max_unallocated=self.max_unallocated,
92
+ initial_balance=self.initial_balance
99
93
  )
@@ -1,3 +1,7 @@
1
+ from datetime import timezone
2
+
3
+ from dateutil import parser
4
+
1
5
  from investing_algorithm_framework.domain.models.base_model import BaseModel
2
6
 
3
7
 
@@ -5,16 +9,19 @@ class PortfolioSnapshot(BaseModel):
5
9
 
6
10
  def __init__(
7
11
  self,
8
- portfolio_id,
9
- trading_symbol,
10
- pending_value,
11
- unallocated,
12
- total_net_gain,
13
- total_revenue,
14
- total_cost,
15
- cash_flow,
16
- created_at,
17
- position_snapshots=None
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,
18
25
  ):
19
26
  self.portfolio_id = portfolio_id
20
27
  self.trading_symbol = trading_symbol
@@ -22,9 +29,19 @@ class PortfolioSnapshot(BaseModel):
22
29
  self.unallocated = unallocated
23
30
  self.total_net_gain = total_net_gain
24
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
25
34
  self.total_cost = total_cost
26
35
  self.cash_flow = cash_flow
27
- self.created_at = created_at
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)
28
45
 
29
46
  if position_snapshots is None:
30
47
  position_snapshots = []
@@ -67,6 +84,12 @@ class PortfolioSnapshot(BaseModel):
67
84
  def set_total_revenue(self, total_revenue):
68
85
  self.total_revenue = total_revenue
69
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
+
70
93
  def get_total_cost(self):
71
94
  return self.total_cost
72
95
 
@@ -102,10 +125,84 @@ class PortfolioSnapshot(BaseModel):
102
125
  portfolio_id=self.portfolio_id,
103
126
  created_at=self.created_at.strftime("%Y-%m-%d %H:%M:%S"),
104
127
  trading_symbol=self.trading_symbol,
128
+ net_size=self.net_size,
105
129
  unallocated=self.unallocated,
106
130
  pending_value=self.pending_value,
107
131
  total_net_gain=self.total_net_gain,
108
132
  total_revenue=self.total_revenue,
109
133
  total_cost=self.total_cost,
110
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", {})
111
208
  )
@@ -1,4 +1,5 @@
1
1
  from .position import Position
2
2
  from .position_snapshot import PositionSnapshot
3
+ from .position_size import PositionSize
3
4
 
4
- __all__ = ["Position", "PositionSnapshot"]
5
+ __all__ = ["Position", "PositionSnapshot", "PositionSize"]
@@ -2,6 +2,9 @@ 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,
@@ -39,6 +42,23 @@ class Position(BaseModel):
39
42
  def set_portfolio_id(self, portfolio_id):
40
43
  self.portfolio_id = portfolio_id
41
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
+
42
62
  def __repr__(self):
43
63
  return self.repr(
44
64
  symbol=self.symbol,
@@ -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,6 +1,4 @@
1
1
  from investing_algorithm_framework.domain.models.base_model import BaseModel
2
- from investing_algorithm_framework.domain.decimal_parsing import \
3
- parse_string_to_decimal
4
2
 
5
3
 
6
4
  class PositionSnapshot(BaseModel):
@@ -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