Skip to content

Commit

Permalink
Rename some classes:
Browse files Browse the repository at this point in the history
Order -> SimpleOrder
OrderBase -> Order
Asset -> OHLCAsset
AssetBase -> Asset
  • Loading branch information
bsdz committed Mar 17, 2024
1 parent d798d46 commit 1249b0c
Show file tree
Hide file tree
Showing 14 changed files with 740 additions and 729 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ celerybeat.pid
# Environments
.env
.venv
.venv.*
env/
venv/
ENV/
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Below is an example usage (the performance of the example strategy won't be good
```python
import pandas as pd

from yabte.backtest import Strategy, StrategyRunner, Order, Book
from yabte.backtest import Strategy, StrategyRunner, SimpleOrder, Book
from yabte.utilities.plot.plotly.strategy_runner import plot_strategy_runner
from yabte.utilities.strategy_helpers import crossover
from yabte.tests._helpers import generate_nasdaq_dataset
Expand Down Expand Up @@ -64,9 +64,9 @@ class SMAXO(Strategy):
data = df.loc[ix_2d, ("CloseSMAShort", "CloseSMALong")].dropna()
if len(data) == 2:
if crossover(data.CloseSMAShort, data.CloseSMALong):
self.orders.append(Order(asset_name=symbol, size=-100))
self.orders.append(SimpleOrder(asset_name=symbol, size=-100))
elif crossover(data.CloseSMALong, data.CloseSMAShort):
self.orders.append(Order(asset_name=symbol, size=100))
self.orders.append(SimpleOrder(asset_name=symbol, size=100))


# load some data
Expand Down
12 changes: 6 additions & 6 deletions docs/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ A typical strategy looks as follows:

.. code-block:: python
from yabte.backtest import Strategy, StrategyRunner, Order, Book, Asset
from yabte.backtest import Strategy, StrategyRunner, SimpleOrder, Book, OHLCAsset
from yabte.utilities.strategy_helpers import crossover
# All strategies inherit from the Strategy base class.
Expand Down Expand Up @@ -80,19 +80,19 @@ A typical strategy looks as follows:
# executed the next day. There are different types
# of order, e.g. positional and basket and some orders
# support hooks for running arbitrary checks for limits etc.
self.orders.append(Order(asset_name=symbol, size=-100))
self.orders.append(SimpleOrder(asset_name=symbol, size=-100))
elif crossover(data.CloseSMALong, data.CloseSMAShort):
self.orders.append(Order(asset_name=symbol, size=100))
self.orders.append(SimpleOrder(asset_name=symbol, size=100))
To run our strategy, we use a StrategyRunner:

.. code-block:: python
# The Asset class is any pricable object with accompanying High, Low, Close,
# Open & Volume field data. One can subclass Asset to support different field
# The OHLCAsset class is any pricable object with accompanying High, Low, Close,
# Open & Volume field data. One can subclass OHLCAsset to support different field
# types, e.g. Volatility.
assets = [Asset(name="GOOG", denom="USD"), Asset(name="MSFT", denom="USD")]
assets = [OHLCAsset(name="GOOG", denom="USD"), OHLCAsset(name="MSFT", denom="USD")]
sr = StrategyRunner(
# Data is provided as a pandas dataframe with two level
Expand Down
4 changes: 2 additions & 2 deletions docs/yabte.backtest.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Strategy
:members:
:member-order: bysource

Order
SimpleOrder
-----
.. autoclass:: yabte.backtest.order.OrderStatus
:members:
Expand Down Expand Up @@ -39,7 +39,7 @@ Book
:members:
:member-order: bysource

Asset
OHLCAsset
-----

.. automodule:: yabte.backtest.asset
Expand Down
1,352 changes: 676 additions & 676 deletions notebooks/Delta_Hedging.ipynb

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions notebooks/Readme_Example.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -21706,10 +21706,10 @@
"source": [
"import pandas as pd\n",
"\n",
"from yabte.backtest import Strategy, StrategyRunner, Order, Book\n",
"from yabte.backtest import Book, SimpleOrder, Strategy, StrategyRunner\n",
"from yabte.tests._helpers import generate_nasdaq_dataset\n",
"from yabte.utilities.plot.plotly.strategy_runner import plot_strategy_runner\n",
"from yabte.utilities.strategy_helpers import crossover\n",
"from yabte.tests._helpers import generate_nasdaq_dataset\n",
"\n",
"\n",
"class SMAXO(Strategy):\n",
Expand Down Expand Up @@ -21745,9 +21745,9 @@
" data = df.loc[ix_2d, (\"CloseSMAShort\", \"CloseSMALong\")].dropna()\n",
" if len(data) == 2:\n",
" if crossover(data.CloseSMAShort, data.CloseSMALong):\n",
" self.orders.append(Order(asset_name=symbol, size=-100))\n",
" self.orders.append(SimpleOrder(asset_name=symbol, size=-100))\n",
" elif crossover(data.CloseSMALong, data.CloseSMAShort):\n",
" self.orders.append(Order(asset_name=symbol, size=100))\n",
" self.orders.append(SimpleOrder(asset_name=symbol, size=100))\n",
"\n",
"\n",
"# load some data\n",
Expand Down
8 changes: 4 additions & 4 deletions yabte/backtest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,32 @@
ADFI_AVAILABLE_AT_CLOSE,
ADFI_AVAILABLE_AT_OPEN,
ADFI_REQUIRED,
Asset,
AssetDataFieldInfo,
AssetName,
OHLCAsset,
)
from yabte.backtest.book import Book, BookMandate, BookName
from yabte.backtest.order import (
BasketOrder,
Order,
OrderSizeType,
OrderStatus,
PositionalBasketOrder,
PositionalOrder,
PositionalOrderCheckType,
SimpleOrder,
)
from yabte.backtest.strategy import Strategy, StrategyRunner
from yabte.backtest.transaction import CashTransaction, Trade

__all__ = [
"Asset",
"OHLCAsset",
"AssetDataFieldInfo",
"AssetName",
"Book",
"BookName",
"BookMandate",
"CashTransaction",
"Order",
"SimpleOrder",
"OrderSizeType",
"OrderStatus",
"BasketOrder",
Expand Down
6 changes: 3 additions & 3 deletions yabte/backtest/asset.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import pandas as pd
from mypy_extensions import mypyc_attr

__all__ = ["Asset"]
__all__ = ["OHLCAsset"]


# use ints until mypyc supports IntFlag
Expand All @@ -25,7 +25,7 @@

@mypyc_attr(allow_interpreted_subclasses=True)
@dataclass(kw_only=True)
class AssetBase:
class Asset:
"""Anything that has a price."""

name: AssetName
Expand Down Expand Up @@ -97,7 +97,7 @@ def _filter_data(self, data: T) -> T:

@mypyc_attr(allow_interpreted_subclasses=True)
@dataclass(kw_only=True)
class Asset(AssetBase):
class OHLCAsset(Asset):
"""Assets whose price history is represented by High, Low, Open, Close and Volume
fields."""

Expand Down
12 changes: 6 additions & 6 deletions yabte/backtest/order.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

logger = logging.getLogger(__name__)

__all__ = ["Order", "PositionalOrder", "BasketOrder", "PositionalBasketOrder"]
__all__ = ["SimpleOrder", "PositionalOrder", "BasketOrder", "PositionalBasketOrder"]


class OrderStatus(Enum):
Expand Down Expand Up @@ -53,7 +53,7 @@ class OrderSizeType(Enum):

@mypyc_attr(allow_interpreted_subclasses=True)
@dataclass(kw_only=True)
class OrderBase:
class Order:
"""Base class for all orders."""

status: OrderStatus = OrderStatus.OPEN
Expand All @@ -62,7 +62,7 @@ class OrderBase:
book: BookName | Book | None = field(repr=False, default=None)
"""Target book."""

suborders: List[OrderBase] = field(default_factory=list)
suborders: List[Order] = field(default_factory=list)
"""Additional orders to be executed the following timestep."""

label: Optional[str] = None
Expand Down Expand Up @@ -106,7 +106,7 @@ def apply(self, ts: pd.Timestamp, day_data: pd.Series, asset_map: Dict[str, Asse

@mypyc_attr(allow_interpreted_subclasses=True)
@dataclass(kw_only=True)
class Order(OrderBase):
class SimpleOrder(Order):
"""Simple market order."""

asset_name: AssetName
Expand Down Expand Up @@ -189,7 +189,7 @@ class PositionalOrderCheckType(Enum):

@mypyc_attr(allow_interpreted_subclasses=True)
@dataclass(kw_only=True)
class PositionalOrder(Order):
class PositionalOrder(SimpleOrder):
"""Ensures current position is `size` and will close out existing positions to
achieve this."""

Expand Down Expand Up @@ -249,7 +249,7 @@ def apply(self, ts: pd.Timestamp, day_data: pd.Series, asset_map: Dict[str, Asse

@mypyc_attr(allow_interpreted_subclasses=True)
@dataclass
class BasketOrder(OrderBase):
class BasketOrder(Order):
"""Combine multiple assets into a single order."""

asset_names: List[AssetName]
Expand Down
8 changes: 4 additions & 4 deletions yabte/backtest/strategy.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from .asset import ADFI_AVAILABLE_AT_OPEN, Asset, AssetName
from .book import Book, BookMandate, BookName
from .order import Order, OrderBase, OrderStatus
from .order import Order, OrderStatus

logger = logging.getLogger(__name__)

Expand All @@ -34,10 +34,10 @@ def __iter__(self):
def popleft(self):
return self.deque.popleft()

def append(self, order: OrderBase):
def append(self, order: Order):
return self.deque.append(order)

def extend(self, orders: Iterable[OrderBase]):
def extend(self, orders: Iterable[Order]):
return self.deque.extend(orders)

def sort_by_priority(self):
Expand All @@ -46,7 +46,7 @@ def sort_by_priority(self):
self.deque.clear()
self.deque.extend(ou_sorted)

def remove_duplicate_keys(self) -> List[OrderBase]:
def remove_duplicate_keys(self) -> List[Order]:
"""Remove older orders with same key.
Returns a list of orders than were removed with status set to REPLACED.
Expand Down
4 changes: 2 additions & 2 deletions yabte/tests/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pandas as pd

from yabte.backtest.asset import Asset
from yabte.backtest.asset import OHLCAsset

data_dir = Path(__file__).parent / "data"
notebooks_dir = Path(__file__).parents[2] / "notebooks"
Expand All @@ -13,7 +13,7 @@ def generate_nasdaq_dataset():
dfs = []
for csv_pth in (data_dir / "nasdaq").glob("*.csv"):
name = csv_pth.stem
assets.append(Asset(name=name, denom="USD"))
assets.append(OHLCAsset(name=name, denom="USD"))
df = pd.read_csv(csv_pth, index_col=0, parse_dates=[0])
df.columns = pd.MultiIndex.from_tuples([(name, f) for f in df.columns])
dfs.append(df)
Expand Down
5 changes: 4 additions & 1 deletion yabte/tests/test_notebooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,7 @@ def test_notebooks_smoke(self):
with nb.open() as f:
nb = nbformat.read(f, as_version=4)
# will raise exception if issue, eg missing module
ep.preprocess(nb, {"metadata": {"path": str(notebooks_dir)}})
nb_node, resources = ep.preprocess(
nb, {"metadata": {"path": str(notebooks_dir)}}
)
foo = 1
1 change: 1 addition & 0 deletions yabte/tests/test_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def _gbm_recover_weiner(T, N, M, r, p, sigma):
class SimulationTestCase(NumpyTestCase):
def setUp(self):
self.rng = np.random.default_rng(12345)
super().setUp()

def test_weiner_simple(self):
R = [[1, 0.9], [0.9, 1]]
Expand Down
Loading

0 comments on commit 1249b0c

Please sign in to comment.