Пример #1
0
 def get_benchmark_values(self, dates):
     # 不管几点,要对应整点的的日级数据
     # start = str_to_timestamp(str((str_to_datetime(dates[0]) - datetime.timedelta(days=self.refresh_rate)).date()))
     start = str2timestamp(
         str((str2datetime(dates[0]) - datetime.timedelta(days=1)).date()))
     end = str2timestamp(str((str2datetime(dates[-1])).date()))
     bm_values = self.benchmark.loc[(self.benchmark["timestamp"] >= start)
                                    & (self.benchmark["timestamp"] <= end)]
     # bm_values = bm_values.loc[bm_values.index[::self.refresh_rate]]['close'].tolist()
     bm_values = bm_values['close'].tolist()
     return bm_values
Пример #2
0
    def __init__(self,
                 start_date=None,
                 end_date=None,
                 frequency=None,
                 refresh_rate=None,
                 trigger_time=None):
        """
        :param start_date: 初始日期
        :param end_date: 结束日期
        """
        self._str_date = start_date + ' ' + trigger_time[
            0] if trigger_time else start_date
        self._current_date = str2datetime(self._str_date)  # 当前日期 datetime
        self._previous_date = None
        self._current_timestamp = None  # 当前日期 时间戳
        self._end_timestamp = str2timestamp(end_date)  # 结束日期 时间戳
        self._bars = 0
        self._bars_m = 0  # 开始bars数量
        self._bars_start = 0
        self._day_bar = 0
        self._run_start = time.time()  # 记录run运行时间
        self._datestart = time.time()
        self._run_end = None

        self._frequency = frequency
        self._refresh_rate = refresh_rate
Пример #3
0
    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()
Пример #4
0
 def get_benchmark_values(self, dates):
     # 不管几点,要对应整点的的日级数据
     # start = str_to_timestamp(str((str_to_datetime(dates[0]) - datetime.timedelta(days=self.refresh_rate)).date()))
     if self.context.frequency in ['d', '1d', 'day', '1day']:
         start = str((str2datetime(dates[0]) -
                      datetime.timedelta(days=self.refresh_rate)))
         end = str((str2datetime(dates[-1])))
         bm_values = self.benchmark.loc[
             (self.benchmark["timestamp"] >= start)
             & (self.benchmark["timestamp"] <= end)]
         bm_values = bm_values.loc[
             bm_values.index[::self.refresh_rate]]['close'].tolist()
     else:
         start = str((
             str2datetime(dates[0]) -
             datetime.timedelta(days=1)))  #benchmarkvalue只取对应基准的日价值,所以每日值都取
         end = str((str2datetime(dates[-1])))
         bm_values = self.benchmark.loc[
             (self.benchmark["timestamp"] >= start)
             & (self.benchmark["timestamp"] <= end)]
         bm_values = bm_values['close'].tolist()
     return bm_values
Пример #5
0
 def get_dates_values_positions_orders(self):
     """
     :return: dates、values、positions、orders
     """
     values = list()
     dates = list()
     portfolio_position = dict()
     orders = dict()
     benchmarks = self.benchmark
     values.append(self.context.init_position_total)
     for date, pf in self.rebalance_history.items():
         values.append(
             sum([
                 asset['total_amount']
                 for asset in pf['portfolio_position']['detail'].values()
             ]))
         dates.append(date)
         portfolio_position[date] = pf['portfolio_position']
         orders[date] = pf['orders']
     date1 = []
     value1 = []
     portfolio_position1 = dict()
     orders1 = dict()
     freq1 = self.context.frequency
     if freq1 in ['d', '1d', 'day', '1day']:
         for i, v in enumerate(dates):
             if v in benchmarks['timestamp'].values:
                 date1.append(dates[i])
                 value1.append(values[i])
                 portfolio_position1[dates[i]] = portfolio_position[
                     dates[i]]
                 orders1[dates[i]] = orders[dates[i]]
     else:
         for i, v in enumerate(dates):
             if v in benchmarks['timestamp'].values:
                 countbar = 0
                 maxnum = random.uniform(5, 10)
                 date1.append(dates[i])
                 value1.append(values[i])
                 portfolio_position1[dates[i]] = portfolio_position[
                     dates[i]]
             if orders[dates[i]]:
                 currentdate = str2datetime(dates[i]).replace(hour=0,
                                                              minute=0,
                                                              second=0,
                                                              microsecond=0)
                 if bool(orders1):
                     if (str(currentdate)) not in orders1.keys():
                         orders1[str(currentdate)] = []
                     tempdate = list(orders1.keys())[-1]
                     orderdate = str2datetime(tempdate).replace(
                         hour=0, minute=0, second=0, microsecond=0)
                     if currentdate == orderdate:
                         countbar += 1
                         if countbar <= maxnum:
                             orders1[str(currentdate)].append(
                                 orders[dates[i]][0])
                     else:
                         orders1[str(currentdate)].append(
                             orders[dates[i]][0])
                 else:
                     currentdate = str2datetime(dates[i]).replace(
                         hour=0, minute=0, second=0, microsecond=0)
                     orders1[str(currentdate)] = []
                     orders1[str(currentdate)].append(orders[dates[i]][0])
     dates = date1
     values = value1
     portfolio_position = portfolio_position1
     orders = orders1
     return dates, values, portfolio_position, orders