Skip to content

Commit

Permalink
added info to order
Browse files Browse the repository at this point in the history
  • Loading branch information
jbaron committed Mar 9, 2024
1 parent b6d687c commit eb4088c
Show file tree
Hide file tree
Showing 10 changed files with 54 additions and 22 deletions.
1 change: 1 addition & 0 deletions .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ max-line-length = 127
per-file-ignores =
# imported but unused
__init__.py: F401
exclude =.git,__pycache__,docs,old,build,dist,.venv,.pytest_cache,.vscode,.github
18 changes: 18 additions & 0 deletions bin/publish.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
source .venv/bin/activate

# QA
flake8 roboquant tests || exit 1
pylint roboquant tests || exit 1
python -m unittest discover -s tests/unit || exit 1

# Build
rm -rf dist
python -m build || exit 1

# Publish
read -p "Publish (y/n)? " ANSWER
if [ "$ANSWER" = "y" ]; then
twine upload dist/*; exit 0
else
echo "Not published"; exit 1
fi
5 changes: 1 addition & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
[tool.black]
line-length = 127

[tool.flake8]
max-line-length = 127

[tool.pytest.ini_options]
minversion = "8.0"
addopts = "-ra -q"
Expand All @@ -12,7 +9,7 @@ testpaths = [
]

[tool.pyright]
reportOptionalOperand = "off"
reportOptionalOperand = "none"

[tool.pylint.'MESSAGES CONTROL']
max-line-length = 127
Expand Down
8 changes: 4 additions & 4 deletions roboquant/brokers/simbroker.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ def _get_execution_price(self, order, item) -> float:
correction = self.slippage if order.is_buy else -self.slippage
return price * (1.0 + correction)

def _simulate_market(self, order: Order, item) -> _Trx | None:
"""Simulate a market for the three order types"""
def _execute(self, order: Order, item) -> _Trx | None:
"""Simulate a market execution for the three order types"""

price = self._get_execution_price(order, item)
fill = self._get_fill(order, price)
Expand Down Expand Up @@ -122,7 +122,7 @@ def _get_fill(self, order, price) -> Decimal:

def __update_mkt_prices(self, price_items):
"""track the latest market prices for all open positions"""
for symbol in self._account.positions.keys():
for symbol in self._account.positions:
if item := price_items.get(symbol):
self._prices[symbol] = item.price(self.price_type)

Expand Down Expand Up @@ -164,7 +164,7 @@ def _process_create_orders(self, prices):
else:
if (item := prices.get(order.symbol)) is not None:
state.expires_at = state.expires_at or self._account.last_update + timedelta(days=90)
trx = self._simulate_market(order, item)
trx = self._execute(order, item)
if trx is not None:
self._update_account(trx)
order.fill += trx.size
Expand Down
5 changes: 4 additions & 1 deletion roboquant/journals/journal.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@

class Journal(Protocol):
"""
A journal allows for the tracking and/or logging of one or more metrics during a run.
A journal enables the tracking and/or logging of one or more metrics during a run.
A journal can hold detailed records of all your trading activities in the financial markets.
It serves as a tool to track and analyze their performance, decisions, and outcomes over time
"""

def track(self, event: Event, account: Account, signals: dict[str, Signal], orders: list[Order]):
Expand Down
7 changes: 3 additions & 4 deletions roboquant/journals/tensorboardjournal.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@ class TensorboardJournal(Journal):

def __init__(self, writer, *metrics: Metric):
"""
Params:
- writer: a tensorboard writer instance (`tensorboard.summary.Writer`)
- metrics: the metrics that should be calculated and be added to the tensorboard writer
Parameters:
writer: a tensorboard writer instance (`tensorboard.summary.Writer`)
metrics: the metrics that should be calculated and be added to the tensorboard writer
"""
self.__writer = writer
self._step = 0
Expand Down
12 changes: 8 additions & 4 deletions roboquant/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from dataclasses import dataclass
from decimal import Decimal
from enum import Flag, auto
from typing import Any


class OrderStatus(Flag):
Expand Down Expand Up @@ -36,7 +37,7 @@ def __repr__(self):
return self.name


@dataclass
@dataclass(slots=True)
class Order:
"""
A trading order.
Expand All @@ -50,11 +51,13 @@ class Order:
symbol: str
size: Decimal
limit: float | None
info: dict[str, Any]

id: str | None
status: OrderStatus
fill: Decimal

def __init__(self, symbol: str, size: Decimal | str | int | float, limit: float | None = None):
def __init__(self, symbol: str, size: Decimal | str | int | float, limit: float | None = None, **kwargs):
self.symbol = symbol
self.size = Decimal(size)
assert not self.size.is_zero(), "Cannot create a new order with size is zero"
Expand All @@ -63,6 +66,7 @@ def __init__(self, symbol: str, size: Decimal | str | int | float, limit: float
self.id: str | None = None
self.status: OrderStatus = OrderStatus.INITIAL
self.fill = Decimal(0)
self.info = kwargs

@property
def open(self) -> bool:
Expand Down Expand Up @@ -99,15 +103,15 @@ def update(self, size: Decimal | str | int | float | None = None, limit: float |

size = Decimal(size) if size is not None else None
if size is not None:
assert not size.is_zero(), "size cannot be set to zero, use order.cancel() instead"
assert not size.is_zero(), "size cannot be set to zero, use order.cancel() to cancel an order"

result = copy(self)
result.size = size or result.size
result.limit = limit or result.limit
return result

def __copy__(self):
result = Order(self.symbol, self.size, self.limit)
result = Order(self.symbol, self.size, self.limit, **self.info)
result.id = self.id
result.status = self.status
result.fill = self.fill
Expand Down
5 changes: 3 additions & 2 deletions tests/samples/close_positions_ibkr.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,18 @@
logging.basicConfig()
logging.getLogger("roboquant").setLevel(level=logging.INFO)

ibkr = IBKRBroker()
ibkr = IBKRBroker.use_tws()
account = ibkr.sync()
print(account)

orders = [Order(symbol, - pos.size) for symbol, pos in account.positions.items()]

# close all but the first 10 positions
ibkr.place_orders(orders[10:])
for _ in range(10):
for _ in range(20):
sleep(1)
account = ibkr.sync()
print()
print(account)

ibkr.disconnect()
10 changes: 10 additions & 0 deletions tests/unit/test_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ def test_order_create(self):
order = Order("AAPL", Decimal(100))
self.assertEqual(Decimal(100), order.size)

def test_order_info(self):
order = Order("AAPL", 100, tif="ABC")
info = order.info
self.assertIn("tif", info)

order.id = "test"
update = order.update(size=50)
info = update.info
self.assertIn("tif", info)

def test_order_update(self):
order = Order("AAPL", 100)
order.id = "update1"
Expand Down
5 changes: 2 additions & 3 deletions tests/unit/test_torch.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import logging
import unittest

from torch import nn
Expand Down Expand Up @@ -27,8 +26,8 @@ def forward(self, inputs):
class TestTorch(unittest.TestCase):

def test_lstm_model(self):
logging.basicConfig()
logging.getLogger("roboquant.strategies").setLevel(level=logging.INFO)
# logging.basicConfig()
# logging.getLogger("roboquant.strategies").setLevel(level=logging.INFO)
# Setup
symbol = "AAPL"
prediction = 10
Expand Down

0 comments on commit eb4088c

Please sign in to comment.