Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Is there a wait function? #265

Unanswered
pascalchristian asked this question in Q&A
Discussion options

Is there a wait function for closing/reversing a position? For example entering into a short position (based on criterias) then wait X trading days, then close the position? Thanks

You must be logged in to vote

Replies: 2 comments 4 replies

Comment options

I'll be very interested in seeing a better answer here, I solved it in what is probably the most ugly manner.

class example(Strategy):
 n1 = 1
 n2 = 20
 relax = 5 # how many days/periods to wait before trading again
 relax = pd.to_timedelta(relax, unit="D") # convert to a timedelta object
 def init(self):
 super().init()
 self.sma1 = self.I(SMA, self.data.Close, self.n1)
 self.sma2 = self.I(SMA, self.data.Close, self.n2)
 def next(self):
 super().next()
 price = self.data.Close[-1]
 if len(self.closed_trades) == 0: # If there hasn't been any trades yet
 last_trade_time = self.data.index[0]
 elif len(self.trades) == 0: # We are in cash no open trades
 last_trade_time = self.closed_trades[-1].exit_time # When did we exit our last trade
 else: # We have an open position
 last_trade_time = max(
 self.trades[-1].entry_time, self.closed_trades[-1].exit_time
 ) # the max of when we either entered that trade or exited it last
 current_time = self.data.index[-1] 
 dayssince = (
 current_time - last_trade_time
 ) # this will be used in concert with relax variable
 # Bullish Markets ---------------------------------
 if (
 not self.position.is_long
 and crossover(self.sma1, self.sma2)
 ):
 self.buy(size=0.9)
 elif (
 self.position.is_long
 and crossover(self.sma1, self.sma2)
 and dayssince > self.relax # Checks to make sure it has been at least the proper amount of days since last trade
 ):
 ...rest of code here....
You must be logged in to vote
2 replies
Comment options

btw there is a barsscince function in the lib.py module but I couldn't quite figure it out so I want with the above ugly method. I'm sure @kernc will be once again rolling his eyes at my bastardization of his beautiful library. ;)

def barssince(condition: Sequence[bool], default=np.inf) -> int:
 """
 Return the number of bars since `condition` sequence was last `True`,
 or if never, return `default`.
 >>> barssince(self.data.Close > self.data.Open)
 3
 """
 return next(compress(range(len(condition)), reversed(condition)), default)
Comment options

Untested, something like:

cur_time = self.data.index[-1]
for trade in self.trades:
 if barssince(cur_time < trade.entry_time) >= 5:
 trade.close()

I guess it's not its best use-case. 😅

Comment options

How about:

import pandas as pd
...
 def next(self):
 cur_time = self.data.index[-1]
 for trade in self.trades:
 if cur_time - trade.entry_time >= pd.Timedelta('5 days'):
 trade.close()
You must be logged in to vote
2 replies
Comment options

I had an idea for a composable base strategy HoldNBarsStrategy that does exactly above but didn't yet manage to come round to forging it.

Comment options

I'd vote for that because I still haven't figured out to get mine to work with the optimizer without even more coding.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /