Пример #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 get_daily_ohlcv(self, k_lines_key, start, end, attributes):
     """
     :param k_lines_key: 'spot-binance-btcusdt'
     :param start_date: datetime
     :param end_date: datetime
     :return: dataframe
     """
     start_ts = str2timestamp(str(start.date()))
     end_ts = str2timestamp(str(end.date()))
     total_data = self.data[k_lines_key]
     data = total_data.loc[(total_data["timestamp"] >= start_ts) & (total_data["timestamp"] <= end_ts)][attributes]
     return data
Пример #3
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
Пример #4
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()
Пример #5
0
 def get_price(self, symbol):
     """
     :param symbol: "BTC/USDT.binance"
     :return:  回测:上一bar close_price
     """
     k_lines_key = symbol.split('.')[1] + '-spot-' + symbol.split(
         '.')[0].replace('/', '').lower()
     date = self.clock.current_date
     last_bar_timestamp = str2timestamp(str(date.date()))  # date都取日级数据
     df = self.cacher.data[k_lines_key]
     last_bar_price = df.loc[(
         df['timestamp'] == last_bar_timestamp)]['close'].tolist()[0]
     return last_bar_price
Пример #6
0
 def value(self):
     """
     :return: 持仓市值(随市场价实时变动)
     """
     if not self._context:
         return 0
     else:
         date = self._context.clock.current_date
         current_timestamp = str2timestamp(str(
             date.date()))  # 只关注date() time()舍掉
         # current_timestamp = datetime.datetime.timestamp(date)
         cmc_key = 'cmc-spot-' + self.asset + 'usd'
         df = self.context.cacher.data[cmc_key]
         return df.loc[(
             df['timestamp'] == current_timestamp)]['close'].tolist()[0]
Пример #7
0
 def next(self):
     if self._frequency in ['d', '1d', 'day', 'daily']:
         # self._current_date += datetime.timedelta(days=self._refresh_rate)
         self._current_date += datetime.timedelta(days=self._refresh_rate)
     elif self._frequency in ['m', '1m', 'min', 'minute']:
         self._current_date += datetime.timedelta(
             minutes=self._refresh_rate)
     elif self._frequency in ['5m', '5min', '5minutes']:
         self._current_date += datetime.timedelta(minutes=5 *
                                                  self._refresh_rate)
     current_timestamp = str2timestamp(str(
         self._current_date.date()))  # 只关注date() time()舍掉
     current_timestamp = str(
         datetime.datetime.fromtimestamp(current_timestamp))
     if str(self._current_date) == current_timestamp:
         self._day_bar += 1
     self._bars += 1
     self._bars_m += 1
     self._bars_start += 1