def __init__(self, pstocks, dt_start, dt_end, n_ahead, capital, StampTaxRate, CommissionChargeRate): self._strategy = None # actual timescope of the back test, depending on the user setting and the available data self.timescope = None # number of extra daily data for computation (ahead of start datatime) # set in the main program self.n_ahead = n_ahead # an output class instance for the report file self.o = None # check whether datetime is proper assert dt_start < dt_end # is_Day_cst: to check whether there is at least one daily candlestick data in pstocks is_Day_cst_exist = False # load candlestick(cst) data # .stocks = {code(str): PStock,} self.stocks = {} for pstock in pstocks: # get info from filename # .ID(class StockID), .period(str) ID, period = parse_cst_filename(pstock) if period == "1Day": is_Day_cst_exist = True if ID.code not in self.stocks: self.stocks[ID.code] = PStock(pstock, dt_start, dt_end, n_ahead) else: self.stocks[ID.code].load_cst(pstock, dt_start, dt_end, n_ahead) # remind user assert is_Day_cst_exist, "At least one item in pstocks should be daily candlestick data" # for convenience, store sz cst information as class PStock self.sz = PStock("000001.sz-1Day", dt_start, dt_end, n_ahead) # for convenience, store dayily close price of sz self.sz_daily_close = self.sz.cst["1Day"]["close"].values[n_ahead:] # get sz daily time axis self.szTimeAxis = self.sz.cst["1Day"].index[n_ahead:] # pd.DataFrame.index # find missing daily candlestick data and fill them up in .stocks[code].missing_cst['1Day'] # as pd.DataFrame self.fill_missing_cst() # read candlestick data timescope from sz self.timescope = str(self.szTimeAxis[0]), str(self.szTimeAxis[-1]) # initial capital to invest, a constant once being set self._capital = capital # cash in the account, changing during the back test self._cash = capital # stock shares in the account, changing during the back test self._shares = {} # ._shares: {code(str): quantity(int)} # records. add one record after each transaction(buy or sell) # _records = [(datetime(str), cash, shares),] self._records = [] self._records.append((self.timescope[0], self._cash, self._shares.copy())) # set stamp tax rate and commission charge rate self.StampTaxRate = StampTaxRate self.CommissionChargeRate = CommissionChargeRate # to store total commission charge in the back test self._total_commission_charge = 0 # to store total stamp tax in the back test self._total_stamp_tax = 0 # trading_stocks: To store the stocks that are traded. Note that although have been loaded, # some stocks in self.stocks may not been traded in user's strategy. self.trading_stocks = set()
def __init__(self, pstocks, dt_start, dt_end, n_ahead): self._analysis = None # actual timescope of the back test, depending on the user setting and the available data self.timescope = None # number of extra daily data for computation (ahead of start datatime) # set in the main program self.n_ahead = n_ahead # check whether datetime is proper assert (dt_start < dt_end) # is_Day_cst: to check whether there is at least one daily candlestick data in pstocks is_Day_cst_exist = False # load candlestick(cst) data # .stocks = {code(str): PStock,} self.stocks = {} for pstock in pstocks: # get info from filename # .ID(class StockID), .period(str) ID, period = parse_cst_filename(pstock) if period == '1Day': is_Day_cst_exist = True if ID.code not in self.stocks: self.stocks[ID.code] = PStock(pstock, dt_start, dt_end, n_ahead) else: self.stocks[ID.code].load_cst(pstock, dt_start, dt_end, n_ahead) # remind user assert is_Day_cst_exist, "At least one item in pstocks should be daily candlestick data" # for convenience, store sz cst information as class PStock self.sz = PStock('000001.sz-1Day', dt_start, dt_end, n_ahead) # for convenience, store dayily close price of sz self.sz_daily_close = self.sz.cst['1Day']['close'].values[n_ahead:] # get sz daily time axis self.szTimeAxis = self.sz.cst['1Day'].index[ n_ahead:] # pd.DataFrame.index # find missing daily candlestick data and fill them up in .stocks[code].missing_cst['1Day'] # as pd.DataFrame self.fill_missing_cst() # read candlestick data timescope from sz self.timescope = str(self.szTimeAxis[0]), str(self.szTimeAxis[-1])
def load(self, pstocks): """ Download cst data and save them in .csv file (in /data/cst). Args: pstocks(str): filename of cst data """ end = datetime.now().date() - timedelta(days=1) # download cst data for all required pstocks for pstock in pstocks: # get info from filename # .ID(class StockID), .period(str) ID, period = parse_cst_filename(pstock) # get cst data file path fname = pstock + ".csv" pathname = os.path.join(self.dir_data, fname) if os.path.exists(pathname): # if cst data file exists # get modified date file_mtime = time.ctime(os.path.getmtime(pathname)) file_mtime = datetime.strptime(file_mtime, "%a %b %d %H:%M:%S %Y") start = file_mtime.date() # make the cst data file up-to-date if start < end: # download using tushare df = self.download(ID.code, str(start), str(end), period) if df is not None: # not empty # update cst data file df.to_csv(pathname, mode='a', header=None) else: # if cst data file not exists, download data and create it. # get listing date of the stock ListingDate = self.stock_basics.ix[ID.code]['timeToMarket'] ListingDate = datetime.strptime(str(ListingDate), '%Y%m%d').date() # download using tushare df = self.download(ID.code, str(ListingDate), str(end), period) if df is not None: # not empty # save df.to_csv(pathname)
def load(self, pstocks): """ Download cst data and save them in .csv file (in /data/cst). Args: pstocks(str): filename of cst data """ end = datetime.now().date() - timedelta(days = 1) # download cst data for all required pstocks for pstock in pstocks: # get info from filename # .ID(class StockID), .period(str) ID, period = parse_cst_filename(pstock) # get cst data file path fname = pstock + ".csv" pathname = os.path.join(self.dir_data, fname) if os.path.exists(pathname): # if cst data file exists # get modified date file_mtime = time.ctime(os.path.getmtime(pathname)) file_mtime = datetime.strptime(file_mtime, "%a %b %d %H:%M:%S %Y") start = file_mtime.date() # make the cst data file up-to-date if start < end: # download using tushare df = self.download(ID.code, str(start), str(end), period) if df is not None: # not empty # update cst data file df.to_csv(pathname, mode='a', header = None) else: # if cst data file not exists, download data and create it. # get listing date of the stock ListingDate = self.stock_basics.ix[ID.code]['timeToMarket'] ListingDate = datetime.strptime(str(ListingDate), '%Y%m%d').date() # download using tushare df = self.download(ID.code, str(ListingDate), str(end), period) if df is not None: # not empty # save df.to_csv(pathname)
def __init__(self, pstocks, dt_start, dt_end, n_ahead): self._analysis = None # actual timescope of the back test, depending on the user setting and the available data self.timescope = None # number of extra daily data for computation (ahead of start datatime) # set in the main program self.n_ahead = n_ahead # check whether datetime is proper assert(dt_start < dt_end) # is_Day_cst: to check whether there is at least one daily candlestick data in pstocks is_Day_cst_exist = False # load candlestick(cst) data # .stocks = {code(str): PStock,} self.stocks = {} for pstock in pstocks: # get info from filename # .ID(class StockID), .period(str) ID, period = parse_cst_filename(pstock) if period == '1Day': is_Day_cst_exist = True if ID.code not in self.stocks: self.stocks[ID.code] = PStock(pstock, dt_start, dt_end, n_ahead) else: self.stocks[ID.code].load_cst(pstock, dt_start, dt_end, n_ahead) # remind user assert is_Day_cst_exist, "At least one item in pstocks should be daily candlestick data" # for convenience, store sz cst information as class PStock self.sz = PStock('000001.sz-1Day', dt_start, dt_end, n_ahead) # for convenience, store dayily close price of sz self.sz_daily_close = self.sz.cst['1Day']['close'].values[n_ahead:] # get sz daily time axis self.szTimeAxis = self.sz.cst['1Day'].index[n_ahead:] # pd.DataFrame.index # find missing daily candlestick data and fill them up in .stocks[code].missing_cst['1Day'] # as pd.DataFrame self.fill_missing_cst() # read candlestick data timescope from sz self.timescope = str(self.szTimeAxis[0]), str(self.szTimeAxis[-1])
def __init__(self, pstocks, dt_start, dt_end, n_ahead, capital, StampTaxRate, CommissionChargeRate): self._strategy = None # actual timescope of the back test, depending on the user setting and the available data self.timescope = None # number of extra daily data for computation (ahead of start datatime) # set in the main program self.n_ahead = n_ahead # an output class instance for the report file self.o = None # check whether datetime is proper assert (dt_start < dt_end) # is_Day_cst: to check whether there is at least one daily candlestick data in pstocks is_Day_cst_exist = False # load candlestick(cst) data # .stocks = {code(str): PStock,} self.stocks = {} for pstock in pstocks: # get info from filename # .ID(class StockID), .period(str) ID, period = parse_cst_filename(pstock) if period == '1Day': is_Day_cst_exist = True if ID.code not in self.stocks: self.stocks[ID.code] = PStock(pstock, dt_start, dt_end, n_ahead) else: self.stocks[ID.code].load_cst(pstock, dt_start, dt_end, n_ahead) # remind user assert is_Day_cst_exist, "At least one item in pstocks should be daily candlestick data" # for convenience, store sz cst information as class PStock self.sz = PStock('000001.sz-1Day', dt_start, dt_end, n_ahead) # for convenience, store dayily close price of sz self.sz_daily_close = self.sz.cst['1Day']['close'].values[n_ahead:] # get sz daily time axis self.szTimeAxis = self.sz.cst['1Day'].index[ n_ahead:] # pd.DataFrame.index # find missing daily candlestick data and fill them up in .stocks[code].missing_cst['1Day'] # as pd.DataFrame self.fill_missing_cst() # read candlestick data timescope from sz self.timescope = str(self.szTimeAxis[0]), str(self.szTimeAxis[-1]) # initial capital to invest, a constant once being set self._capital = capital # cash in the account, changing during the back test self._cash = capital # stock shares in the account, changing during the back test self._shares = {} # ._shares: {code(str): quantity(int)} # records. add one record after each transaction(buy or sell) # _records = [(datetime(str), cash, shares),] self._records = [] self._records.append( (self.timescope[0], self._cash, self._shares.copy())) # set stamp tax rate and commission charge rate self.StampTaxRate = StampTaxRate self.CommissionChargeRate = CommissionChargeRate # to store total commission charge in the back test self._total_commission_charge = 0 # to store total stamp tax in the back test self._total_stamp_tax = 0 # trading_stocks: To store the stocks that are traded. Note that although have been loaded, # some stocks in self.stocks may not been traded in user's strategy. self.trading_stocks = set()