roboquant 0.1.6__tar.gz

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 (53) hide show
  1. roboquant-0.1.6/LICENSE +201 -0
  2. roboquant-0.1.6/PKG-INFO +105 -0
  3. roboquant-0.1.6/README.md +69 -0
  4. roboquant-0.1.6/pyproject.toml +49 -0
  5. roboquant-0.1.6/roboquant/__init__.py +33 -0
  6. roboquant-0.1.6/roboquant/account.py +127 -0
  7. roboquant-0.1.6/roboquant/brokers/__init__.py +2 -0
  8. roboquant-0.1.6/roboquant/brokers/broker.py +18 -0
  9. roboquant-0.1.6/roboquant/brokers/ibkrbroker.py +211 -0
  10. roboquant-0.1.6/roboquant/brokers/simbroker.py +191 -0
  11. roboquant-0.1.6/roboquant/config.py +20 -0
  12. roboquant-0.1.6/roboquant/event.py +131 -0
  13. roboquant-0.1.6/roboquant/feeds/__init__.py +13 -0
  14. roboquant-0.1.6/roboquant/feeds/candlefeed.py +60 -0
  15. roboquant-0.1.6/roboquant/feeds/csvfeed.py +95 -0
  16. roboquant-0.1.6/roboquant/feeds/eventchannel.py +74 -0
  17. roboquant-0.1.6/roboquant/feeds/feed.py +14 -0
  18. roboquant-0.1.6/roboquant/feeds/feedutil.py +73 -0
  19. roboquant-0.1.6/roboquant/feeds/historicfeed.py +58 -0
  20. roboquant-0.1.6/roboquant/feeds/randomwalk.py +56 -0
  21. roboquant-0.1.6/roboquant/feeds/sqllitefeed.py +103 -0
  22. roboquant-0.1.6/roboquant/feeds/tiingohistoricfeed.py +125 -0
  23. roboquant-0.1.6/roboquant/feeds/tiingolivefeed.py +126 -0
  24. roboquant-0.1.6/roboquant/feeds/yahoofeed.py +51 -0
  25. roboquant-0.1.6/roboquant/order.py +107 -0
  26. roboquant-0.1.6/roboquant/roboquant.py +67 -0
  27. roboquant-0.1.6/roboquant/strategies/__init__.py +7 -0
  28. roboquant-0.1.6/roboquant/strategies/buffer.py +80 -0
  29. roboquant-0.1.6/roboquant/strategies/candlestrategy.py +40 -0
  30. roboquant-0.1.6/roboquant/strategies/emacrossover.py +57 -0
  31. roboquant-0.1.6/roboquant/strategies/featureset.py +130 -0
  32. roboquant-0.1.6/roboquant/strategies/multistrategy.py +45 -0
  33. roboquant-0.1.6/roboquant/strategies/nopstrategy.py +13 -0
  34. roboquant-0.1.6/roboquant/strategies/rnnstrategy.py +187 -0
  35. roboquant-0.1.6/roboquant/strategies/smacrossover.py +45 -0
  36. roboquant-0.1.6/roboquant/strategies/strategy.py +21 -0
  37. roboquant-0.1.6/roboquant/timeframe.py +135 -0
  38. roboquant-0.1.6/roboquant/trackers/__init__.py +6 -0
  39. roboquant-0.1.6/roboquant/trackers/basictracker.py +64 -0
  40. roboquant-0.1.6/roboquant/trackers/capmtracker.py +66 -0
  41. roboquant-0.1.6/roboquant/trackers/equitytracker.py +18 -0
  42. roboquant-0.1.6/roboquant/trackers/standardtracker.py +173 -0
  43. roboquant-0.1.6/roboquant/trackers/tensorboardtracker.py +31 -0
  44. roboquant-0.1.6/roboquant/trackers/tracker.py +18 -0
  45. roboquant-0.1.6/roboquant/traders/__init__.py +2 -0
  46. roboquant-0.1.6/roboquant/traders/flextrader.py +128 -0
  47. roboquant-0.1.6/roboquant/traders/trader.py +17 -0
  48. roboquant-0.1.6/roboquant.egg-info/PKG-INFO +105 -0
  49. roboquant-0.1.6/roboquant.egg-info/SOURCES.txt +51 -0
  50. roboquant-0.1.6/roboquant.egg-info/dependency_links.txt +1 -0
  51. roboquant-0.1.6/roboquant.egg-info/requires.txt +14 -0
  52. roboquant-0.1.6/roboquant.egg-info/top_level.txt +1 -0
  53. roboquant-0.1.6/setup.cfg +4 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 Neural Layer
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.1
2
+ Name: roboquant
3
+ Version: 0.1.6
4
+ Summary: A fast algo-trading platform
5
+ Author-email: roboquant team <info@roboquant.org>
6
+ Project-URL: Homepage, https://roboquant.org
7
+ Project-URL: Repository, https://github.com/neurallayer/rq.git
8
+ Project-URL: Issues, https://github.com/neurallayer/rq/issues
9
+ Keywords: trading,investment,finance,crypto,stocks,exchange,forex
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Programming Language :: Python
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: License :: OSI Approved :: Apache Software License
19
+ Classifier: Operating System :: OS Independent
20
+ Classifier: Topic :: Office/Business :: Financial
21
+ Classifier: Topic :: Office/Business :: Financial :: Investment
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: numpy>=1.25.2
26
+ Requires-Dist: prettytable~=3.9.0
27
+ Requires-Dist: websocket-client~=1.7.0
28
+ Requires-Dist: requests>=2.31.0
29
+ Provides-Extra: torch
30
+ Requires-Dist: torch>=2.1.0; extra == "torch"
31
+ Requires-Dist: tensorboard>=2.15.2; extra == "torch"
32
+ Provides-Extra: yahoo
33
+ Requires-Dist: yfinance~=0.2.36; extra == "yahoo"
34
+ Provides-Extra: all
35
+ Requires-Dist: roboquant[torch,yahoo]; extra == "all"
36
+
37
+
38
+ # Introduction
39
+ Roboquant is an open-source algorithmic trading platform. It is flexible, user-friendly and completely free to use. It is designed for anyone serious about algo-trading. So whether you are a beginning retail trader or an established trading firm, roboquant can help you to develop robust and fully automated trading strategies.
40
+
41
+ ![roboquant logo](https://github.com/neurallayer/roboquant/raw/main/docs/roboquant_header.png)
42
+
43
+ # Install
44
+ Roboquant can be installed like most other Python packages, using for example pip or conda. Just make sure you have Python version 3.10 or higher installed.
45
+
46
+ ```shell
47
+ python3 -m pip install --upgrade roboquant
48
+ ```
49
+
50
+ If you want to use PyTorch based strategies and YahooFinance market data, you can install roboquant using the following command:
51
+
52
+ ```shell
53
+ python3 -m pip install --upgrade roboquant[all]
54
+ ```
55
+
56
+ # Usage
57
+ The following code snippet shows the code required to run a full back-test on a number of stocks.
58
+
59
+ ```python
60
+ from roboquant import *
61
+
62
+ feed = YahooFeed("TSLA", "AMZN", "IBM")
63
+ strategy = EMACrossover()
64
+ roboquant = Roboquant(strategy)
65
+ tracker = StandardTracker()
66
+
67
+ roboquant.run(feed, tracker)
68
+ print(tracker)
69
+ ```
70
+
71
+ # Building from source
72
+ Go to directory where you have downloaded the py_oboquant project and run the following commands to create a virtual environment:
73
+
74
+ ```shell
75
+ python3 -m venv .venv
76
+ source .venv/bin/activate
77
+ ```
78
+
79
+ Now install the required packages and build roboquant in this virtual environment:
80
+
81
+ ```shell
82
+ pip install -r requirements.txt
83
+ python -m build
84
+ ```
85
+
86
+ To run the unittest:
87
+
88
+ ```shell
89
+ python -m unittest discover -s tests/unit
90
+ ```
91
+
92
+ To install it:
93
+
94
+ ```shell
95
+ pip install .
96
+ ```
97
+
98
+
99
+ ## Interactive Brokers
100
+
101
+ Unfortunatly Interactive Brokers doesn't allow their Python client library to be redistributed by third parties. However it is freely available to be downloaded and installed. Please follow the instructions found [here](https://ibkrcampus.com/ibkr-quant-news/interactive-brokers-python-api-native-a-step-by-step-guide/) (download and install version 10.19).
102
+
103
+ # Kotlin version
104
+ Next to this Python version of `roboquant`, there is also a Koltin version available. Both (will) share a similar API, just the used computer language is different.
105
+ Which one to use, depends very much on personal preference, skills and use-case.
@@ -0,0 +1,69 @@
1
+
2
+ # Introduction
3
+ Roboquant is an open-source algorithmic trading platform. It is flexible, user-friendly and completely free to use. It is designed for anyone serious about algo-trading. So whether you are a beginning retail trader or an established trading firm, roboquant can help you to develop robust and fully automated trading strategies.
4
+
5
+ ![roboquant logo](https://github.com/neurallayer/roboquant/raw/main/docs/roboquant_header.png)
6
+
7
+ # Install
8
+ Roboquant can be installed like most other Python packages, using for example pip or conda. Just make sure you have Python version 3.10 or higher installed.
9
+
10
+ ```shell
11
+ python3 -m pip install --upgrade roboquant
12
+ ```
13
+
14
+ If you want to use PyTorch based strategies and YahooFinance market data, you can install roboquant using the following command:
15
+
16
+ ```shell
17
+ python3 -m pip install --upgrade roboquant[all]
18
+ ```
19
+
20
+ # Usage
21
+ The following code snippet shows the code required to run a full back-test on a number of stocks.
22
+
23
+ ```python
24
+ from roboquant import *
25
+
26
+ feed = YahooFeed("TSLA", "AMZN", "IBM")
27
+ strategy = EMACrossover()
28
+ roboquant = Roboquant(strategy)
29
+ tracker = StandardTracker()
30
+
31
+ roboquant.run(feed, tracker)
32
+ print(tracker)
33
+ ```
34
+
35
+ # Building from source
36
+ Go to directory where you have downloaded the py_oboquant project and run the following commands to create a virtual environment:
37
+
38
+ ```shell
39
+ python3 -m venv .venv
40
+ source .venv/bin/activate
41
+ ```
42
+
43
+ Now install the required packages and build roboquant in this virtual environment:
44
+
45
+ ```shell
46
+ pip install -r requirements.txt
47
+ python -m build
48
+ ```
49
+
50
+ To run the unittest:
51
+
52
+ ```shell
53
+ python -m unittest discover -s tests/unit
54
+ ```
55
+
56
+ To install it:
57
+
58
+ ```shell
59
+ pip install .
60
+ ```
61
+
62
+
63
+ ## Interactive Brokers
64
+
65
+ Unfortunatly Interactive Brokers doesn't allow their Python client library to be redistributed by third parties. However it is freely available to be downloaded and installed. Please follow the instructions found [here](https://ibkrcampus.com/ibkr-quant-news/interactive-brokers-python-api-native-a-step-by-step-guide/) (download and install version 10.19).
66
+
67
+ # Kotlin version
68
+ Next to this Python version of `roboquant`, there is also a Koltin version available. Both (will) share a similar API, just the used computer language is different.
69
+ Which one to use, depends very much on personal preference, skills and use-case.
@@ -0,0 +1,49 @@
1
+ [tool.black]
2
+ line-length = 127
3
+
4
+ [tool.flake8]
5
+ max-line-length = 127
6
+
7
+ [build-system]
8
+ requires = ["setuptools>=61.0"]
9
+ build-backend = "setuptools.build_meta"
10
+
11
+ [project]
12
+ name = "roboquant"
13
+ version = "0.1.6"
14
+ authors = [ { name="roboquant team", email="info@roboquant.org" },]
15
+ description = "A fast algo-trading platform"
16
+ readme = "README.md"
17
+ requires-python = ">=3.10"
18
+ classifiers = [
19
+ "Development Status :: 3 - Alpha",
20
+ "Intended Audience :: Developers",
21
+ "Programming Language :: Python",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3 :: Only",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "License :: OSI Approved :: Apache Software License",
28
+ "Operating System :: OS Independent",
29
+ "Topic :: Office/Business :: Financial",
30
+ "Topic :: Office/Business :: Financial :: Investment"
31
+ ]
32
+ keywords = ["trading", "investment", "finance", "crypto", "stocks", "exchange", "forex"]
33
+ dependencies = [
34
+ "numpy>=1.25.2",
35
+ "prettytable~=3.9.0",
36
+ "websocket-client~=1.7.0",
37
+ "requests>=2.31.0",
38
+ ]
39
+
40
+ [project.optional-dependencies]
41
+ torch = ["torch>=2.1.0", "tensorboard>=2.15.2"]
42
+ yahoo = ["yfinance~=0.2.36"]
43
+ all = [ "roboquant[torch,yahoo]" ]
44
+
45
+
46
+ [project.urls]
47
+ Homepage = "https://roboquant.org"
48
+ Repository = "https://github.com/neurallayer/rq.git"
49
+ Issues = "https://github.com/neurallayer/rq/issues"
@@ -0,0 +1,33 @@
1
+ from .account import Account, OptionAccount, Position
2
+ from .roboquant import Roboquant
3
+
4
+ from .event import Event, PriceItem, Candle, Trade, Quote
5
+ from .order import Order, OrderStatus
6
+ from .timeframe import Timeframe
7
+ from .config import Config
8
+
9
+
10
+ from roboquant.brokers import Broker, SimBroker
11
+ from roboquant.traders import Trader, FlexTrader
12
+ from roboquant.trackers import Tracker, StandardTracker, BasicTracker, CAPMTracker, EquityTracker, TensorboardTracker
13
+ from roboquant.strategies import (
14
+ Strategy,
15
+ EMACrossover,
16
+ SMACrossover,
17
+ CandleStrategy,
18
+ NOPStrategy,
19
+ NumpyBuffer,
20
+ OHLCVBuffer,
21
+ )
22
+ from roboquant.feeds import (
23
+ Feed,
24
+ CSVFeed,
25
+ SQLFeed,
26
+ RandomWalk,
27
+ YahooFeed,
28
+ TiingoLiveFeed,
29
+ TiingoHistoricFeed,
30
+ CandleFeed,
31
+ EventChannel,
32
+ feedutil
33
+ )
@@ -0,0 +1,127 @@
1
+ from dataclasses import dataclass
2
+ from datetime import datetime
3
+ from decimal import Decimal
4
+ from roboquant.order import Order
5
+ from prettytable import PrettyTable
6
+
7
+
8
+ @dataclass(slots=True, frozen=True)
9
+ class Position:
10
+ """Position of a symbol"""
11
+
12
+ size: Decimal
13
+ """Position size"""
14
+
15
+ avg_price: float
16
+ """Average price paid denoted in the currency of the symbol"""
17
+
18
+
19
+ class Account:
20
+ """The account maintains the following state during a run:
21
+
22
+ - Available cash for trading (also sometimes referred to as buying power)
23
+ - Open positions
24
+ - Open orders
25
+ - Total equity value of the account
26
+ - Last time the account was updated
27
+
28
+ Only the broker updates the state of the account and does this only during its `sync` method.
29
+ """
30
+
31
+ def __init__(self):
32
+ self.buying_power: float = 0.0
33
+ self.positions: dict[str, Position] = {}
34
+ self.orders: list[Order] = []
35
+ self.last_update: datetime = datetime.fromisoformat("1900-01-01T00:00:00+00:00")
36
+ self.equity = 0.0
37
+
38
+ def get_value(self, symbol: str, size: Decimal, price: float) -> float:
39
+ """Return the total value of the provided contract size denoted in the base currency of the account.
40
+ The default implementation returns `size * price`.
41
+
42
+ The bahavior of this method can be changed for symbols denoted in a different currency and/or contract size by providing
43
+ a different value_calculator.
44
+ """
45
+ return float(size) * price
46
+
47
+ def mkt_value(self, prices: dict[str, float]) -> float:
48
+ """Return the the market value of all the open positions in the account using the provided prices."""
49
+ return sum([self.get_value(symbol, pos.size, prices[symbol]) for symbol, pos in self.positions.items()], 0.0)
50
+
51
+ def unrealized_pnl(self, prices: dict[str, float]) -> float:
52
+ return sum(
53
+ [
54
+ self.get_value(symbol, pos.size, prices[symbol] - pos.avg_price)
55
+ for symbol, pos in self.positions.items()
56
+ ],
57
+ 0.0,
58
+ )
59
+
60
+ def has_open_order(self, symbol: str) -> bool:
61
+ """Return True if there an open order for the symbol, False otherwise"""
62
+
63
+ for order in self.orders:
64
+ if order.symbol == symbol and not order.closed:
65
+ return True
66
+ return False
67
+
68
+ def get_position_size(self, symbol) -> Decimal:
69
+ pos = self.positions.get(symbol)
70
+ return pos.size if pos else Decimal(0)
71
+
72
+ def open_orders(self):
73
+ """Return a list with the open orders"""
74
+ return [order for order in self.orders if not order.closed]
75
+
76
+ def __repr__(self) -> str:
77
+ p = PrettyTable(["account", "value"], align="r", float_format="12.2")
78
+ p.add_row(["buying power", self.buying_power])
79
+ p.add_row(["equity", self.equity])
80
+ p.add_row(["positions", len(self.positions)])
81
+ p.add_row(["orders", len(self.orders)])
82
+ p.add_row(["last update", self.last_update.strftime("%Y-%m-%d %H:%M:%S")])
83
+ result = p.get_string() + "\n\n"
84
+
85
+ p = PrettyTable(["symbol", "position size", "avg price"], align="r", float_format="12.2")
86
+ for symbol, pos in self.positions.items():
87
+ p.add_row([symbol, pos.size, pos.avg_price])
88
+ result += p.get_string() + "\n\n"
89
+
90
+ p = PrettyTable(
91
+ ["symbol", "order size", "order id", "limit", "status", "closed"], align="r", float_format="12.2"
92
+ )
93
+ for order in self.orders:
94
+ p.add_row([order.symbol, order.size, order.id, order.limit, order.status.name, order.closed])
95
+ result += p.get_string() + "\n"
96
+
97
+ return result
98
+
99
+
100
+ class OptionAccount(Account):
101
+ """
102
+ This account handles common option contracts of size 100 and 10. Serves as an example.
103
+ If no contract size is registered for a symbol, it creates one based on the symbol name.
104
+ """
105
+
106
+ def __init__(self):
107
+ super().__init__()
108
+ self._contract_sizes: dict[str, float] = {}
109
+
110
+ def register(self, symbol: str, contract_size: float = 100.0):
111
+ """Register a certain contract-size for a symbol"""
112
+ self._contract_sizes[symbol] = contract_size
113
+
114
+ def get_value(self, symbol: str, size: Decimal, price: float) -> float:
115
+ contract_size = self._contract_sizes.get(symbol)
116
+
117
+ # If nithng registered we try to defer the contract size from the symbol
118
+ if contract_size is None:
119
+ if len(symbol) == 21:
120
+ # OCC compliant option symbol
121
+ symbol = symbol[0:6].rstrip()
122
+ contract_size = 10.0 if symbol[-1] == "7" else 100.0
123
+ else:
124
+ # not an option symbol
125
+ contract_size = 1.0
126
+
127
+ return contract_size * float(size) * price
@@ -0,0 +1,2 @@
1
+ from .broker import Broker
2
+ from .simbroker import SimBroker
@@ -0,0 +1,18 @@
1
+
2
+ from typing import Protocol
3
+ from roboquant.account import Account
4
+ from roboquant.event import Event
5
+ from roboquant.order import Order
6
+
7
+
8
+
9
+ class Broker(Protocol):
10
+ """A broker handles the placed orders and communicates its state through the account object"""
11
+
12
+ def place_orders(self, *orders: Order):
13
+ """Place zero or more orders at this broker."""
14
+ ...
15
+
16
+ def sync(self, event: Event | None = None) -> Account:
17
+ """Sync the state, and return an updated account to reflect the latest state."""
18
+ ...