Skip to content

[backtests]: Optimize SimulatedExecutionEngine and enhance ExecutionE… #314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 50 additions & 12 deletions gs_quant/backtests/execution_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,73 @@
under the License.
"""

from gs_quant.backtests.data_handler import DataHandler
from gs_quant.backtests.event import *
import datetime as dt
import bisect
from typing import List

from gs_quant.backtests.data_handler import DataHandler
from gs_quant.backtests.event import OrderEvent, OrderBase, FillEvent

from abc import ABC

class ExecutionEngine(object):

class ExecutionEngine(ABC):
"""Abstract base class for execution engines."""
pass


class SimulatedExecutionEngine(ExecutionEngine):
"""
Simulates order execution based on market data.

Attributes:
data_handler (DataHandler): Provides market data for execution.
orders (List[OrderEvent]): Sorted list of submitted orders by execution end time.
"""

def __init__(self, data_handler: DataHandler):
self.data_handler = data_handler
self.orders = []
self.orders: List[OrderEvent] = []

def submit_order(self, order: OrderEvent):
self.orders.append(order)
self.orders.sort(key=lambda e: e.order.execution_end_time())
"""
Submit an order and maintain sorted execution order.

def ping(self, state: dt.datetime):
Args:
order (OrderEvent): The order to be submitted.
"""
bisect.insort(self.orders, order, key=lambda e: e.order.execution_end_time())

def ping(self, state: dt.datetime) -> List[FillEvent]:
"""
Process and fill orders whose execution time has passed.

Args:
state (datetime): Current simulation time.

Returns:
List[FillEvent]: List of filled order events.
"""
fill_events = []
while self.orders:
order: OrderBase = self.orders[0].order
order_event = self.orders[0]
order: OrderBase = order_event.order
end_time = order.execution_end_time()

if end_time > state:
break
else:
fill = FillEvent(order=order,
filled_price=order.execution_price(self.data_handler),
filled_units=order.execution_quantity())

try:
fill = FillEvent(
order=order,
filled_price=order.execution_price(self.data_handler),
filled_units=order.execution_quantity()
)
fill_events.append(fill)
except Exception as e:
# Log or handle execution failure gracefully
print(f"Error processing order {order}: {e}")
finally:
self.orders.pop(0)

return fill_events