async def _handle_data(self): # print("******************************************************************") clock = self.context.clock current_date = clock.current_date logger.current_date = current_date current_timestamp = clock.current_timestamp # print(current_date) prebars=clock.pre_bar pre_start = str(str2datetime(self.start) - datetime.timedelta(days=prebars)) try: if not self.cache_data: self.cache_data = self.context.prepare_data(self.universe, self.all_assets, self.benchmark, self.frequency, pre_start, self.end, self.timezone) except Exception: output({"display_type": "error", "error_msg": traceback.format_exc()}) return 1 # 记录初始持仓 start = self.start + ' ' + self.trigger_time[0] if self.trigger_time else self.start # 只支持一个trigger_time if current_timestamp == str2timestamp(start): for name, account in self.portfolio.accounts.items(): for asset, position in account.current_position.items(): position.context = self.context init_portfolio_position = dict() for asset in self.context.asset_varieties: init_pp_detail = PortfolioPosition(self.context, asset, self.portfolio.accounts).detail() init_portfolio_position[asset] = init_pp_detail self.context.init_portfolio_position = init_portfolio_position self.context.init_position_total = sum([asset['total_amount'] for asset in init_portfolio_position.values()]) self.context.init_total_account_position = {} for name in self.context.accounts_name: name_position = "{}_position".format(name) total_amount = 0 for asset,value in self.context.init_portfolio_position.items(): if name in value['consist_of'].keys(): total_amount += value['consist_of'][name]['amount'] self.context.init_total_account_position[name_position] = total_amount # logger.info('【记录初始持仓时间】:{} s'.format(str(time.time() - start2)[:5])) try: if str(current_date) in self.strategy_dates: self.handle_data(self.context) except Exception: output({"display_type": "error", "error_msg": traceback.format_exc()}) return 1 self.portfolio.record_history()
def record_history(self): pp_detail = dict() pp_total = dict() orders = list() all_total_profit = None last_profit_and_loss = None date = self.context.current_datetime() last_date = self.context.previous_datetime() for name, account in self.accounts.items(): account = account.to_dict() orders.extend(account['orders']) account['orders'].clear() self.rebalance_history[date] = { 'portfolio_position': { 'detail': dict(), 'total': dict() }, 'orders': dict() } for asset in self.context.asset_varieties: # TODO list to dict pp_detail[asset] = PortfolioPosition(self.context, asset, self.accounts).detail() # portfolio_position.append(pp_detail) all_total_profit = round( sum([i['total_amount'] for i in pp_detail.values()]), 4) # 各个持仓百分比 for asset in self.context.asset_varieties: pp_detail[asset]['percentage_of_positions'] = round( pp_detail[asset]['total_amount'] / all_total_profit, 4) if self.first_flag: last_profit_and_loss = 0 for asset in self.context.asset_varieties: pp_detail[asset]["last_profit_and_loss"] = 0 self.first_flag = False else: last_profit_and_loss = round( (all_total_profit / self.rebalance_history[last_date] ["portfolio_position"]['total']["profit"]) - 1, 4) for asset in self.context.asset_varieties: try: profit_and_loss = round(( pp_detail[asset]["total_amount"] / self.rebalance_history[last_date]["portfolio_position"] ['detail'][asset]["total_amount"]) - 1, 4) except: profit_and_loss = 0 pp_detail[asset]["last_profit_and_loss"] = profit_and_loss self.rebalance_history[date]['orders'] = orders pp_total = { "assets": self.context.asset_varieties, "profit": all_total_profit, "last_profit_and_loss": last_profit_and_loss } self.rebalance_history[date]["portfolio_position"][ 'detail'] = pp_detail self.rebalance_history[date]["portfolio_position"]['total'] = pp_total