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
@@ -0,0 +1,568 @@
1
+ from typing import List, Union
2
+ from datetime import datetime, timezone, timedelta
3
+
4
+ import polars as pl
5
+
6
+ from investing_algorithm_framework.domain import DataProvider, \
7
+ OperationalException, DataSource, DataType, TimeFrame, \
8
+ convert_polars_to_pandas
9
+
10
+
11
+ class CSVOHLCVDataProvider(DataProvider):
12
+ """
13
+ Implementation of Data Provider for OHLCV data. OHLCV data
14
+ will be loaded from a CSV file. The CSV file should contain
15
+ the following columns: Datetime, Open, High, Low, Close, Volume.
16
+ The Datetime column should be in UTC timezone and in milliseconds.
17
+ The data will be loaded into a Polars DataFrame and will be kept in memory.
18
+
19
+ Attributes:
20
+ data_type (DataType): The type of data provided by this provider,
21
+ which is OHLCV.
22
+ data_provider_identifier (str): Identifier for the CSV OHLCV data
23
+ provider.
24
+ _start_date_data_source (datetime): The start date of the data
25
+ source, determined from the first row of the data.
26
+ _end_date_data_source (datetime): The end date of the data
27
+ source, determined from the last row of the data.
28
+ data (polars.DataFrame): The OHLCV data loaded from the CSV file.
29
+ """
30
+ data_type = DataType.OHLCV
31
+ data_provider_identifier = "csv_ohlcv_data_provider"
32
+
33
+ def __init__(
34
+ self,
35
+ storage_path: str,
36
+ symbol: str,
37
+ time_frame: str,
38
+ market: str,
39
+ window_size=None,
40
+ data_provider_identifier: str = None,
41
+ pandas: bool = False,
42
+ ):
43
+ """
44
+ Initialize the CSV Data Provider.
45
+
46
+ Args:
47
+ storage_path (str): Path to the CSV file.
48
+ symbol (str): The symbol for which the data is provided.
49
+ time_frame (str): The time frame for the data.
50
+ market (str, optional): The market for the data. Defaults to None.
51
+ window_size (int, optional): The window size for the data.
52
+ Defaults to None.
53
+ """
54
+ if data_provider_identifier is None:
55
+ data_provider_identifier = self.data_provider_identifier
56
+ super().__init__(
57
+ symbol=symbol,
58
+ market=market,
59
+ time_frame=time_frame,
60
+ window_size=window_size,
61
+ storage_path=storage_path,
62
+ data_provider_identifier=data_provider_identifier,
63
+ data_type=DataType.OHLCV.value
64
+ )
65
+ self._start_date_data_source = None
66
+ self._end_date_data_source = None
67
+ self._columns = ["Datetime", "Open", "High", "Low", "Close", "Volume"]
68
+ self.window_cache = {}
69
+ self._load_data(self.storage_path)
70
+ self.pandas = pandas
71
+ self.number_of_missing_data_points = 0
72
+ self.missing_data_point_dates: List[datetime] = []
73
+
74
+ def has_data(
75
+ self,
76
+ data_source: DataSource,
77
+ start_date: datetime = None,
78
+ end_date: datetime = None
79
+ ) -> bool:
80
+ """
81
+ Implementation of the has_data method to check if
82
+ the data provider has data for the given data source.
83
+
84
+ Args:
85
+ data_source (DataSource): The data source to check.
86
+ start_date (datetime, optional): The start date for the data.
87
+ Defaults to None.
88
+ end_date (datetime, optional): The end date for the data.
89
+ Defaults to None.
90
+
91
+ Returns:
92
+ bool: True if the data provider has data for the given data source,
93
+ False otherwise.
94
+ """
95
+ if start_date is None and end_date is None:
96
+ return False
97
+
98
+ if DataType.OHLCV.equals(data_source.data_type) and \
99
+ data_source.symbol == self.symbol and \
100
+ data_source.time_frame.equals(self.time_frame) and \
101
+ data_source.market == self.market:
102
+
103
+ if end_date > self._end_date_data_source:
104
+ return False
105
+
106
+ if data_source.window_size is not None:
107
+ minutes = TimeFrame.from_value(
108
+ data_source.time_frame
109
+ ).amount_of_minutes * data_source.window_size
110
+ required_start_date = end_date - timedelta(
111
+ minutes=minutes
112
+ )
113
+
114
+ if required_start_date < self._start_date_data_source:
115
+ return False
116
+ else:
117
+ required_start_date = start_date
118
+ if required_start_date < self._start_date_data_source:
119
+ return False
120
+
121
+ return True
122
+
123
+ return False
124
+
125
+ def get_data(
126
+ self,
127
+ date: datetime = None,
128
+ start_date: datetime = None,
129
+ end_date: datetime = None,
130
+ save: bool = False,
131
+ ):
132
+ """
133
+ Fetches OHLCV data for a given symbol and date range.
134
+ If no date range is provided, it returns the entire dataset.
135
+
136
+ Args:
137
+ date (datetime, optional): A specific date to fetch data for.
138
+ Defaults to None.
139
+ start_date (datetime, optional): The start date for the data.
140
+ Defaults to None.
141
+ end_date (datetime, optional): The end date for the data.
142
+ Defaults to None.
143
+ save (bool, optional): Whether to save the data to a file.
144
+
145
+ Returns:
146
+ polars.DataFrame: A DataFrame containing the OHLCV data for the
147
+ specified symbol and date range.
148
+ """
149
+ windows_size = self.window_size
150
+
151
+ if start_date is None and end_date is None:
152
+ end_date = datetime.now(tz=timezone.utc)
153
+ time_frame = TimeFrame.from_value(self.time_frame)
154
+ start_date = end_date - timedelta(
155
+ minutes=time_frame.amount_of_minutes() * windows_size
156
+ )
157
+ elif start_date is None and end_date is not None:
158
+ start_date = end_date - timedelta(
159
+ minutes=TimeFrame.from_value(
160
+ self.time_frame
161
+ ).amount_of_minutes * windows_size
162
+ )
163
+ df = self.data
164
+ df = df.filter(
165
+ (df['Datetime'] >= start_date) & (df['Datetime'] <= end_date)
166
+ )
167
+ return df
168
+
169
+ if start_date is not None:
170
+ end_date = start_date + timedelta(
171
+ minutes=TimeFrame.from_value(self.time_frame)
172
+ .amount_of_minutes * windows_size
173
+ )
174
+
175
+ if start_date < self._start_date_data_source:
176
+ return pl.DataFrame()
177
+
178
+ if start_date > self._end_date_data_source:
179
+ return pl.DataFrame()
180
+
181
+ df = self.data
182
+ df = df.filter(
183
+ (df['Datetime'] >= start_date) & (df['Datetime'] <= end_date)
184
+ )
185
+ return df
186
+
187
+ if end_date is not None:
188
+ start_date = end_date - timedelta(
189
+ minutes=TimeFrame.from_value(
190
+ self.time_frame
191
+ ).amount_of_minutes * windows_size
192
+ )
193
+
194
+ if end_date < self._start_date_data_source:
195
+ return pl.DataFrame()
196
+
197
+ if end_date > self._end_date_data_source:
198
+ return pl.DataFrame()
199
+
200
+ df = self.data
201
+ df = df.filter(
202
+ (df['Datetime'] >= start_date) & (df['Datetime'] <= end_date)
203
+ )
204
+ return df
205
+
206
+ return self.data
207
+
208
+ def prepare_backtest_data(
209
+ self,
210
+ backtest_start_date,
211
+ backtest_end_date
212
+ ) -> None:
213
+ """
214
+ Prepares backtest data for a given symbol and date range.
215
+
216
+ Args:
217
+ backtest_start_date (datetime): The start date for the
218
+ backtest data.
219
+ backtest_end_date (datetime): The end date for the
220
+ backtest data.
221
+
222
+ Raises:
223
+ OperationalException: If the backtest start date is before the
224
+ start date of the data source or if the backtest end date is
225
+ after the end date of the data source.
226
+
227
+ Returns:
228
+ None
229
+ """
230
+
231
+ if backtest_start_date < self._start_date_data_source:
232
+ raise OperationalException(
233
+ f"Backtest start date {backtest_start_date} is before the "
234
+ f"start date {self._start_date_data_source}"
235
+ )
236
+
237
+ if backtest_end_date > self._end_date_data_source:
238
+ raise OperationalException(
239
+ f"Backtest end date {backtest_end_date} is after the "
240
+ f"end date {self._end_date_data_source}"
241
+ )
242
+
243
+ # There must be at least backtest_start_date - window_size * time_frame
244
+ # data available to create a sliding window.
245
+ required_start_date = backtest_start_date - \
246
+ timedelta(
247
+ minutes=TimeFrame.from_value(self.time_frame)
248
+ .amount_of_minutes * self.window_size
249
+ )
250
+
251
+ # Create cache with sliding windows
252
+ self._precompute_sliding_windows(
253
+ window_size=self.window_size,
254
+ start_date=backtest_start_date,
255
+ end_date=backtest_end_date
256
+ )
257
+
258
+ if required_start_date < self._start_date_data_source:
259
+ self.number_of_missing_data_points = (
260
+ self._start_date_data_source - required_start_date
261
+ ).total_seconds() / (
262
+ TimeFrame.from_value(self.time_frame).amount_of_minutes * 60
263
+ )
264
+
265
+ n_min = TimeFrame.from_value(self.time_frame).amount_of_minutes
266
+
267
+ # Assume self.data is a Polars DataFrame with a "Datetime" column
268
+ expected_dates = pl.datetime_range(
269
+ start=required_start_date,
270
+ end=backtest_end_date,
271
+ interval=f"{n_min}m",
272
+ eager=True
273
+ ).to_list()
274
+
275
+ actual_dates = self.data["Datetime"].to_list()
276
+
277
+ # Find missing dates
278
+ self.missing_data_point_dates = sorted(
279
+ set(expected_dates) - set(actual_dates)
280
+ )
281
+
282
+ def get_backtest_data(
283
+ self,
284
+ backtest_index_date: datetime,
285
+ backtest_start_date: datetime = None,
286
+ backtest_end_date: datetime = None,
287
+ data_source: DataSource = None
288
+ ) -> None:
289
+ """
290
+ Fetches backtest data for a given datasource
291
+
292
+ Args:
293
+ backtest_index_date (datetime): The date for which to fetch
294
+ backtest data.
295
+ backtest_start_date (datetime): The start date for the
296
+ backtest data.
297
+ backtest_end_date (datetime): The end date for the
298
+ backtest data.
299
+ data_source (Optional[DataSource]): The data source specification
300
+ that matches a data provider.
301
+
302
+ Raises:
303
+ OperationalException: If the requested backtest date range
304
+ is outside the available data range.
305
+
306
+ Returns:
307
+ pl.DataFrame: The backtest data for the given datasource.
308
+ """
309
+ if backtest_start_date is not None and \
310
+ backtest_end_date is not None:
311
+
312
+ if backtest_start_date < self._start_date_data_source:
313
+
314
+ if data_source is not None:
315
+ raise OperationalException(
316
+ f"Request data date {backtest_end_date} "
317
+ f"is after the range of "
318
+ f"the available data "
319
+ f"{self._start_date_data_source} "
320
+ f"- {self._end_date_data_source}."
321
+ f" for data source {data_source.identifier}."
322
+ )
323
+
324
+ raise OperationalException(
325
+ f"Request data date {backtest_start_date} "
326
+ f"is before the range of "
327
+ f"the available data "
328
+ f"{self._start_date_data_source} "
329
+ f"- {self._end_date_data_source}."
330
+ )
331
+
332
+ if backtest_end_date > self._end_date_data_source:
333
+
334
+ if data_source is not None:
335
+ raise OperationalException(
336
+ f"Request data date {backtest_end_date} "
337
+ f"is after the range of "
338
+ f"the available data "
339
+ f"{self._start_date_data_source} "
340
+ f"- {self._end_date_data_source}."
341
+ f" for data source {data_source.identifier}."
342
+ )
343
+
344
+ raise OperationalException(
345
+ f"Request data date {backtest_end_date} "
346
+ f"is after the range of "
347
+ f"the available data "
348
+ f"{self._start_date_data_source} "
349
+ f"- {self._end_date_data_source}."
350
+ )
351
+
352
+ data = self.data.filter(
353
+ (pl.col("Datetime") >= backtest_start_date) &
354
+ (pl.col("Datetime") <= backtest_end_date)
355
+ )
356
+ else:
357
+ try:
358
+ data = self.window_cache[backtest_index_date]
359
+ except KeyError:
360
+
361
+ try:
362
+ # Return the key in the cache that is closest to the
363
+ # backtest_index_date but not after it.
364
+ closest_key = min(
365
+ [k for k in self.window_cache.keys()
366
+ if k >= backtest_index_date]
367
+ )
368
+ data = self.window_cache[closest_key]
369
+ except ValueError:
370
+
371
+ if data_source is not None:
372
+ raise OperationalException(
373
+ "No data available for the "
374
+ f"date: {backtest_index_date} "
375
+ "within the prepared backtest data "
376
+ f"for data source {data_source.identifier}."
377
+ )
378
+
379
+ raise OperationalException(
380
+ "No data available for the "
381
+ f"date: {backtest_index_date} "
382
+ "within the prepared backtest data."
383
+ )
384
+
385
+ if self.pandas:
386
+ data = convert_polars_to_pandas(data)
387
+
388
+ return data
389
+
390
+ def _load_data(self, storage_path):
391
+ """
392
+ Load OHLCV data from a CSV file into a Polars DataFrame.
393
+ The CSV file should contain the following columns:
394
+
395
+ Datetime, Open, High, Low, Close, Volume.
396
+
397
+ The Datetime column should be in UTC timezone and in milliseconds.
398
+
399
+ Args:
400
+ storage_path (str): The path to the CSV file containing OHLCV data.
401
+
402
+ Raises:
403
+ OperationalException: If the CSV file does not contain all
404
+ required OHLCV columns.
405
+
406
+ Returns:
407
+ None
408
+ """
409
+ df = pl.read_csv(storage_path)
410
+
411
+ # Check if all column names are in the csv file
412
+ if not all(column in df.columns for column in self._columns):
413
+ # Identify missing columns
414
+ missing_columns = [column for column in self._columns if
415
+ column not in df.columns]
416
+ raise OperationalException(
417
+ f"Csv file {storage_path} does not contain "
418
+ f"all required ohlcv columns. "
419
+ f"Missing columns: {missing_columns}"
420
+ )
421
+
422
+ self.data = pl.read_csv(
423
+ storage_path,
424
+ schema_overrides={"Datetime": pl.Datetime},
425
+ low_memory=True
426
+ ).with_columns(
427
+ pl.col("Datetime").cast(
428
+ pl.Datetime(time_unit="ms", time_zone="UTC")
429
+ )
430
+ )
431
+
432
+ first_row = self.data.head(1)
433
+ last_row = self.data.tail(1)
434
+ self._start_date_data_source = first_row["Datetime"][0]
435
+ self._end_date_data_source = last_row["Datetime"][0]
436
+
437
+ def _precompute_sliding_windows(
438
+ self,
439
+ window_size: int,
440
+ start_date: datetime,
441
+ end_date: datetime
442
+ ) -> None:
443
+ """
444
+ Precompute all sliding windows for fast retrieval in backtest mode.
445
+
446
+ A sliding window is calculated as a subset of the data. It will
447
+ take for each timestamp in the data a window of size `window_size`
448
+ and stores it in a cache with the last timestamp of the window.
449
+
450
+ So if the window size is 200, the first window will be
451
+ the first 200 rows of the data, the second window will be
452
+ the rows 1 to 200, the third window will be the rows
453
+ 2 to 201, and so on until the last window which will be
454
+ the last 200 rows of the data.
455
+
456
+ Args:
457
+ window_size (int): The size of the sliding window to precompute.
458
+ start_date (datetime, optional): The start date for the sliding
459
+ windows.
460
+ end_date (datetime, optional): The end date for the sliding
461
+ windows.
462
+
463
+ Returns:
464
+ None
465
+ """
466
+ self.window_cache = {}
467
+ timestamps = self.data["Datetime"].to_list()
468
+
469
+ # Only select the entries after the start date
470
+ timestamps = [
471
+ ts for ts in timestamps
472
+ if start_date <= ts <= end_date
473
+ ]
474
+
475
+ # Create sliding windows of size <window_size> for each timestamp
476
+ # in the data with the given the time frame and window size
477
+ for timestamp in timestamps:
478
+ # Use timestamp as key
479
+ self.window_cache[timestamp] = self.data.filter(
480
+ (self.data["Datetime"] <= timestamp) &
481
+ (self.data["Datetime"] >= timestamp - timedelta(
482
+ minutes=self.time_frame.amount_of_minutes * window_size
483
+ ))
484
+ )
485
+
486
+ def copy(self, data_source: DataSource) -> "DataProvider":
487
+ """
488
+ Create a copy of the data provider with the given data source.
489
+
490
+ Args:
491
+ data_source (DataSource): The data source to copy.
492
+
493
+ Returns:
494
+ DataProvider: A new instance of the data provider with the
495
+ specified data source.
496
+ """
497
+
498
+ storage_path = data_source.storage_path
499
+
500
+ if storage_path is None:
501
+ storage_path = self.storage_path
502
+
503
+ return CSVOHLCVDataProvider(
504
+ storage_path=storage_path,
505
+ symbol=data_source.symbol,
506
+ time_frame=data_source.time_frame,
507
+ market=data_source.market,
508
+ window_size=data_source.window_size,
509
+ data_provider_identifier=self.data_provider_identifier,
510
+ pandas=data_source.pandas
511
+ )
512
+
513
+ def get_number_of_data_points(
514
+ self,
515
+ start_date: datetime,
516
+ end_date: datetime
517
+ ) -> int:
518
+
519
+ """
520
+ Returns the number of data points available between the given
521
+ start and end dates.
522
+
523
+ Args:
524
+ start_date (datetime): The start date for checking missing data.
525
+ end_date (datetime): The end date for checking missing data.
526
+
527
+ Returns:
528
+ int: The number of available data points between the given
529
+ start and end dates.
530
+ """
531
+ available_dates = [
532
+ date for date in self.data["Datetime"].to_list()
533
+ if start_date <= date <= end_date
534
+ ]
535
+ return len(available_dates)
536
+
537
+ def get_missing_data_dates(
538
+ self,
539
+ start_date: datetime,
540
+ end_date: datetime,
541
+ ) -> List[datetime]:
542
+ """
543
+ Returns a list of dates for which data is missing between the
544
+ given start and end dates.
545
+
546
+ Args:
547
+ start_date (datetime): The start date for checking missing data.
548
+ end_date (datetime): The end date for checking missing data.
549
+
550
+ Returns:
551
+ List[datetime]: A list of dates for which data is missing
552
+ between the given start and end dates.
553
+ """
554
+ missing_dates = [
555
+ date for date in self.missing_data_point_dates
556
+ if start_date <= date <= end_date
557
+ ]
558
+ return missing_dates
559
+
560
+ def get_data_source_file_path(self) -> Union[str, None]:
561
+ """
562
+ Get the file path of the data source if stored in local storage.
563
+
564
+ Returns:
565
+ Union[str, None]: The file path of the data source if stored
566
+ locally, otherwise None.
567
+ """
568
+ return self.storage_path