Is it possible to run a strategy starting with a certain amount of the stock already bought?
Rob Shih last edited by
Hi all! Just wondering, is it possible to run a strategy where it starts out with a portion of your cash already bought into the stock? For example, starting out with $10k cash, $5k worth of the stock, and then running the strategy from there. If so, what would be the best way to do this or simulate something close to it? Thanks in advance for any help!
vladisld last edited by
is it possible to run a strategy where it starts out with a portion of your cash already bought into the stock?
There are some scenarios where back-testing should continue from some point in time - where the back-testing results for the earlier period of time are already available ( stored somewhere ). Sometimes both the analyzer data and broker position should be loaded prior to continuing the back-testing.
In my case I'm doing it in my analyzer
create_analysismethod - but the same could be accomplished in strategy itself.
Something like this:
class MyAnalyzer(bt.Analyzer): # strategydb is something I'm using to persist the information about # backtesting results for specified time period - exact details are not # important right now. params = ( ('strategydb', None), # strategy database is passed as a parameter ) def create_analysis(self): if self.p.strategydb: # we've got a database with potential history data # use it for calculating incremental optimization results ... some code here to retrieve the previous results from strategydb # this will update the position directly inside the strategy broker data_pos = self.strategy.broker.positions[self.data] # pos_size,pos_price and stop_date are loaded from strategydb - don't ask how data_pos.set(pos_size, pos_price) # in some scenarios broker requires the datetime to be specified data_pos.datetime = datetime.combine(bt.num2date(sparams.stop_date), time())
It may look like cheating - but it works in my case - for back-testing only of cause ;-)
@vladisld Hi, I'm trying out your method and I'm getting stuck at setting the datetime attribute . Could you please kindly enlighten me what this value is supposed to be? and how is this value being managed during the whole backtesting process?
vladisld last edited by
@jacksonx Please see the comments in the code. Backtrader broker requires position's
datetimeattribute to be set. The value is not that important and could be any valid python datetime object. In my case this date is taken from the previously stored transaction.
@vladisld Thanks for the reply!
I've adapted your method and and set all property attributes of the position (including size, price, datetime, adjbase, upopened and upclosed) saved from a previous run inside the start() function of an analyser, and it works just the way I wanted. This helps a lot! Cheers!