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
Here's a Python solution that implements a strategy using the RSI indicator to generate buy and sell orders as requested:
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 src.domain.abstractions.abstract_strategy import Abstract_Strategy
import pandas as pd
import numpy as np
from dataclasses import dataclass
class RSI_Strategy(Abstract_Strategy):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.price_data = []
def calculate_RSI(self, close_prices: pd.Series, window: int = 14) -> pd.Series:
# Calculate the RSI based on a given window
delta = close_prices.diff().dropna()
gain = delta.where(delta > 0, 0)
loss = -delta.where(delta < 0, 0)
avg_gain = gain.rolling(window=window).mean()
avg_loss = loss.rolling(window=window).mean()
rs = avg_gain / avg_loss
rsi = 100 - (100 / (1 + rs))
return rsi
def add_event(self, event):
# Save the close price event
self.price_data.append(
{
"datetime": event.datetime,
"close": event.close,
}
)
self.price_data = self.price_data[-(20 + 1):] # Keep only the latest 21 close prices
if len(self.price_data) >= 20:
close_prices = pd.Series([x["close"] for x in self.price_data])
rsi = self.calculate_RSI(close_prices).iloc[-1]
if rsi > 80:
# RSI > 80, send a sell order
self.send_order(
ticker=self.ticker,
price=event.close,
quantity=self.quantity,
action='sell',
type='market',
datetime=event.datetime,
)
elif rsi < 20:
# RSI < 20, send a buy order
self.send_order(
ticker=self.ticker,
price=event.close,
quantity=self.quantity,
action='buy',
type='market',
datetime=event.datetime,
)
In this implementation, we've created the RSI_Strategy class that inherits from the Abstract_Strategy class provided in the context. We calculate the RSI by adding a calculate_RSI method and then override the add_event method to generate buy and sell orders based on the RSI values. When the RSI is greater than 80, it sends a sell order, and when it's less than 20, it sends a buy order.