Back

What is the most robust way to access # of days a security has been held?

What is the most robust way to access the number of days a security has been held? I've been using self.PurchaseDate[stock], as in the code below. The code below works perfect, unless my live algorithm crashes, or I stop it while securities are owned. So then, if I try to launch my algorithm, with securities already owned, it doesn't appear that a value for self.PurchaseDate[stock] exists anymore. Is there a better way to determine the number of days held?

 

for stock in self.stock_list:
if self.Portfolio[stock].Invested == True:
bought = self.PurchaseDate[stock]
time_owned_raw = now - bought
days_owned = time_owned_raw.days + 1 #need the +1 to compensate
self.do[stock] = days_owned
Update Backtest








I am still interested to know the most robust way to calculate the number of days owned, but please disregard my code. I just realized that in lieu of actually pulling the purchase date (because I couldn't figure out how to do it), self.PurchaseDate[stock] is a user defined dictionary, in which, I capture the time (self.Time) at the time of purchase. 

0

Hi AMDQuant, You can use a dictionary and make a helper function to count days. In my example (see below), we buy each stock everyday at 9:45, hold it for 5 days, and sell it. Please see below codes and backtest I attached. I'm sure there will be many better ways. Hope this would help. Thanks :)

.....

self.check_days(self.stock_list) # deploy 'check_days()' function


for stock in self.stock_list:
if not self.Portfolio[stock].Invested:
self.SetHoldings(stock, 0.5)

self.hold_day[stock] = 0 # Add stock and 0 days to the dictionary

if self.Portfolio[stock].Invested:
if self.hold_day[stock] ==5:
self.Liquidate(stock)
self.hold_day[stock] = -1 # make days -1 if sold

# Make a helper function to count holding days for each holding stock
def check_days(self, stock_list):

for stock in stock_list:
if self.Portfolio[stock].Invested:
self.hold_day[stock] += 1 # Increment on each holding stock by 1 day
0


Update Backtest





0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Loading...

This discussion is closed