def update(self): # 若标记的长度比历史数据更长,则无法回测并报错 if len(self.history_price) < len(self.choose_position): print( 'Error! The length of choose_position is larger than that of history_price!' ) return # 若标记的长度比历史数据更短,则用0补齐标记数组及amount数组使之与历史数据长度一致 if len(self.history_price) > len(self.choose_position): for i in range( len(self.history_price) - len(self.choose_position)): self.choose_position.append(0) self.choose_amount.append(0) real_capital = 0 now_hold = 0 capital = [] capital_return = [] for t in range(len(self.history_price)): if t > 0: capital_return.append( now_hold * (self.history_price[t] - self.history_price[t - 1])) if t == 0: capital_return.append(0) self.total_amount = self.total_amount + self.choose_amount[t] if self.choose_position[t] == 1: now_hold = now_hold + self.choose_amount[t] real_capital = real_capital + self.choose_amount[ t] * self.history_price[t] if self.choose_position[t] == 2: real_capital = real_capital * ( (now_hold - self.choose_amount[t]) / now_hold) if MathUtils.double_compare(now_hold - self.choose_amount[t], 0) < 0: print("Error! Hold can't be smaller than 0!") now_hold = now_hold - self.choose_amount[t] capital.append(real_capital) max_draw_down = -float("inf") temp_sum_return = [capital_return[0]] for i in range(1, len(capital_return)): temp = temp_sum_return[i - 1] + capital_return[i] if MathUtils.double_compare(-temp, max_draw_down) > 0: max_draw_down = -temp temp_sum_return.append(temp) self.sum_return = np.array(temp_sum_return) self.capital = np.array(capital) self.capital_return = np.array(capital_return) self.max_draw_down = max_draw_down self.final_return = self.sum_return[-1]
def add_choose_position(self, is_buy: bool, position: int, amount: float): # 不检查hold是否充足,在update时再进行检查,但检查amount是否为非负数 if MathUtils.double_compare(amount, 0) < 0: print("Error! Amount can't be smaller than 0!") return # 若两数组长度不够,则用 0 补齐长度 if len(self.choose_position) <= position: for i in range(position - len(self.choose_position) + 1): self.choose_position.append(0) self.choose_amount.append(0) # 在对应的位置上加上标记及amount if is_buy: self.choose_position[position] = 1 else: self.choose_position[position] = 2 self.choose_amount[position] = amount