-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
-
I have this following strategy, which it has the holding period, the duration for which a position is held before being closed. The delay is the time delay applied after a trade signal is generated before executing a trade. When I run it, it cannot distinguish between long and short positions. meaning it manages to close buy position after holding period, but not sell position.
class WeatherStrategy(Strategy):
holding_period = 30 # You can set a default value here
delay = 10
def init(self):
self.entry_time = None
self.signal_time = None # To store the time of the signal
def next(self):
signal = self.data['trade_signal']
current_time = self.data.index[-1]
s = self.data.size[-1]
if not self.position:
if signal == 1 and self.signal_time is None:
self.signal_time = current_time # Record the time of the signal
print(f"Buy signal at {current_time}")
if self.signal_time is not None and (current_time - self.signal_time) >= pd.Timedelta(minutes=self.delay):
self.signal_time = None # Reset the signal time
self.buy(size=s)
self.entry_time = current_time
print(f"Buy at {current_time}")
if signal == -1 and self.signal_time is None:
self.signal_time = current_time # Record the time of the signal
print(f"Sell signal at {current_time}")
if self.signal_time is not None and (current_time - self.signal_time) >= pd.Timedelta(minutes=self.delay):
self.signal_time = None # Reset the signal time
self.sell(size=s) # Corrected: This should be sell for short position
self.entry_time = current_time
print(f"Sell at {current_time}")
else:
time_in_trade = current_time - self.entry_time
if (self.position.is_long and time_in_trade >= pd.Timedelta(minutes=self.holding_period)):
self.position.close()
print(f"Close long position at {current_time}")
if (self.position.is_short and time_in_trade >= pd.Timedelta(minutes=self.holding_period)):
self.position.close()
print(f"Close short position at {current_time}")
some results of the print:
Buy signal at 2022年11月23日 10:27:00
Buy at 2022年11月23日 10:37:00
Close long position at 2022年11月23日 11:07:00
Sell signal at 2022年11月25日 10:27:00
Buy at 2022年11月25日 10:37:00
Close long position at 2022年11月25日 11:07:00
Sell signal at 2022年12月02日 10:27:00
Buy at 2022年12月02日 10:37:00
Close long position at 2022年12月02日 11:07:00
Sell signal at 2022年12月07日 10:27:00
Buy at 2022年12月07日 10:37:00
Close long position at 2022年12月07日 11:07:00
Sell signal at 2022年12月09日 10:27:00
Buy at 2022年12月09日 10:37:00
Close long position at 2022年12月09日 11:07:00
Sell signal at 2022年12月16日 10:27:00
Buy at 2022年12月16日 10:37:00
Close long position at 2022年12月16日 11:07:00
Beta Was this translation helpful? Give feedback.