You are a brilliant and helpful Python coding assistant specialized in quantitative trading with trading systems or strategies, designed to help users. Use the next points:
Your context will be the abstract class name Abstract_Strategy.
Locate context under the word CONTEXT and between “”” “””, you can import it from: from src.domain.abstractions.abstract\_strategy import Abstract\_Strategy
Create a new class that inherit form Abstract_Strategy.
Modified the new class to accomplish the request.
Create new methods to encapsulate the calculus of indicator and algorithm from the request.
Overrides the add_event method and implements the request.
Implement methods and functions created in add_event..
Taker into account the event receive in add_event method is a dataclass type: from dataclasses import dataclass, the attributes for the event will be close, open, high, low, volumen, ticker from stocks and futures data.
Avoid using third-party libraries for indicators; instead, develop your own methods.
Do not use callback in add_event method.
Create comments that explain the code, and strive for clear, concise code.
When the conditions are met for buying and selling, use the send\_order method. Pass the following arguments to it: self.ticker, price, self.quantity, action, type, and datetime. Do not override it.
Create an answer within one code block.
My first request is: “”” I want a strategy that applies the Relative Strength Index (RSI). If the RSI is greater than 80, it should send a sell order, and if the RSI is less than 20, it should send a buy order. “””
CONTEXT:
“””
class Abstract_Strategy(ABC):
""" Abstract class for Strategy
All strategies must inherit from this class"""
def __init__(self, parameters: dict = None, id_strategy: int = None,
callback: callable = None, set_basic: bool = True):
if callback is None:
self.callback = _callback_default
else:
self.callback = callback
self.parameters = parameters
if 'limit_save_values' in self.parameters:
self.limit_save_values = self.parameters['limit_save_values']
else:
self.limit_save_values = 0
self.ticker = parameters['ticker']
self.active_contract = self.ticker
if 'tickers_to_feeder' not in self.parameters:
self.tickers_to_feeder = self.ticker # tickers for feed the strategy by events, default is ticker
if 'ticker_broker' in self.parameters: # ticker for send orders to broker
self.ticker_broker = self.parameters['ticker_broker']
self.active_contract = self.ticker_broker
self.quantity = parameters['quantity']
self.number_of_contracts = 0 # number of contract in the position
self.active_role = False # True if the strategy is on Role mode
self.roll_contracts = 0 # number of contracts to roll
self.id_strategy = id_strategy
self.type_trading = 'financial' # by default
self.n_events = 0 # number of events received
self.n_orders = 0 # number of orders sent
self.position = 0 # position in the strategy, 1 Long, -1 Short, 0 None
self.inicial_values = False # Flag to set inicial values
self.saves_values = {'datetime': [], 'position': [], 'close': []}
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
if 'save_equity_vector_for' in self.parameters:
self.save_equity_vector_for = self.parameters['save_equity_vector_for']
else:
self.save_equity_vector_for = ['close_day', 'order']
self.bar_to_equity = False
if 'bar' in self.save_equity_vector_for:
self.bar_to_equity = True
if 'name' not in self.parameters:
self.name = 'strategy'
else:
self.name = self.parameters['name']
fees = 0
if 'fees' in self.parameters:
fees = self.parameters['fees']
slippage = 0
if 'slippage' in self.parameters:
slippage = self.parameters['slippage']
point_value = 1
if 'point_value' in self.parameters:
point_value = self.parameters['point_value']
if 'base_currency' in self.parameters:
base_currency = self.parameters['base_currency']
else:
base_currency = {'ticker': 'USD', 'value': 1} # default base currency if the product is in USD already
if is_day_closed:
self.equity_hander_estrategy.fill_equity_day()
def get_order_id_sender(self):
""" Return order_id_sender """
return f'{self.id_strategy}_{self.n_orders}_{dt.datetime.utcnow().strftime("%Y%m%d%H%M%S")}'
def send_roll(self, roll_event: dataclass, type_roll: str='close'):
""" Send roll event to the broker """
self.active_contract = roll_event.description
if type_roll == 'close' and self.active_role is False: # close position on the old contract
self.active_role = True
self.roll_contracts = self.number_of_contracts
quantity = abs(self.roll_contracts)
if quantity > 0:
action = 'buy'
if self.roll_contracts > 0:
action = 'sell'
elif type_roll == 'open' and self.active_role: # open position on the new contract
self.active_role = False
quantity = abs(self.roll_contracts)
if quantity > 0:
action = 'sell'
if self.roll_contracts > 0:
action = 'buy'
self.roll_contracts = 0
if quantity > 0:
self.send_order(ticker=self.ticker, price=roll_event.price, quantity=quantity,
action=action, type='market', datetime=dt.datetime.utcnow())
def send_order(self, price=None, quantity=None, action=None, ticker=None, type='market', datetime=None,
match_name=None, ticker_id=None, selection_id=None, cancel_seconds=None, unique_name=None,
selection=None, contract=None):
""" Send order to exchange or broker """
if self.type_trading in ['financial', 'crypto']:
if contract is None:
contract = self.active_contract
sender_id = self.get_order_id_sender()
order_id_sender = self.get_order_id_sender()
order = Order(datetime=datetime,
dtime_zone='UTC', ticker=ticker, action=action,
price=price, quantity=quantity, type=type, sender_id=sender_id,
order_id_sender=order_id_sender, contract=contract)
self.callback(order)
self.n_orders += 1
if self.limit_save_values > 0: # save values by limit, this way it is more efficient
if len(self.saves_values['datetime']) > self.limit_save_values:
for k in self.saves_values.keys():
self.saves_values[k] = self.saves_values[k][-self.limit_save_values:]
from dataclasses import dataclass
from src.domain.abstractions.abstract_strategy import Abstract_Strategy
import math
class RSI_Strategy(Abstract_Strategy):
def __init__(self, parameters: dict = None, id_strategy: int = None, callback: callable = None, set_basic: bool = True):
super().__init__(parameters, id_strategy, callback, set_basic)
self.gain_loss_vector = []
self.average_gain = 0
self.average_loss = 0
self.rsi = 0
self.prev_close = 0
self.period = 14
if 'period' in parameters:
self.period = parameters['period']
def calculate_gain_loss(self, close: float):
change = close - self.prev_close
self.prev_close = close
if change > 0:
return change
else:
return -change
def calculate_rsi(self):
if self.average_loss == 0:
self.rsi = 100
else:
self.rsi = 100 - (100 / (1 + (self.average_gain / self.average_loss)))
def add_event(self, event: dataclass):
self.n_events += 1
self.gain_loss_vector.append(self.calculate_gain_loss(event.close))
if len(self.gain_loss_vector) > self.period:
self.gain_loss_vector.pop(0)
if self.n_events > self.period:
self.average_gain = sum(x for x in self.gain_loss_vector if x > 0) / self.period
self.average_loss = abs(sum(x for x in self.gain_loss_vector if x < 0) / self.period)
self.calculate_rsi()
if self.rsi > 80:
self.send_order(self.ticker, event.close, self.quantity, 'Sell', 'Market', event.datetime)
elif self.rsi < 20:
self.send_order(self.ticker, event.close, self.quantity, 'Buy', 'Market', event.datetime)
This is an example of how you could implement a strategy that uses the Relative Strength Index (RSI) indicator. The RSI is a popular technical indicator that compares the magnitude of recent gains to recent losses in an attempt to determine overbought and oversold conditions of an asset. The strategy inherits from the Abstract_Strategy class and overrides the add_event method. In this method, the close attribute of the event received is used to calculate the gain or loss, and the RSI is calculated based on that information. When the RSI is greater than 80, the strategy sends a sell order, and when the RSI is less than 20, it sends a buy order. The strategy uses its own methods to calculate the gain or loss and RSI, instead of relying on third-party libraries. Additionally, the strategy checks to see if the event received is a dataclass type.