def __init__(self, worker, event, engine=None, callback=False): self.worker = worker self.event = event self.res = None self.callback = callback self.task_id = QA_util_random_with_topic('Task') self.engine = engine
def __init__(self, strategy_name=None, user=None, market_type=MARKET_TYPE.STOCK_CN, frequence=FREQUENCE.DAY, broker=BROKER_TYPE.BACKETEST, portfolio=None, account_cookie=None, sell_available=None, init_assets=None, cash=None, history=None, margin_level=False, allow_t0=False, allow_sellopen=False): super().__init__() self._history_headers = ['datetime', 'code', 'price', 'amount', 'order_id', 'trade_id', 'commission','tax'] # 信息类: self.strategy_name = strategy_name self.user = user self.market_type = market_type self.portfolio = portfolio self.account_cookie = QA_util_random_with_topic( 'Acc') if account_cookie is None else account_cookie self.broker = broker self.frequence = frequence self.market_data = None self._currenttime = None # 资产类 self.init_assets = 1000000 if init_assets is None else init_assets self.cash = [self.init_assets] if cash is None else cash self.cash_available = self.cash[-1] # 可用资金 self.sell_available = sell_available self.history = [] if history is None else history self.time_index = [] # 规则类 # 两个规则 # 1.是否允许t+0 及买入及结算 # 2.是否允许卖空开仓 # 3.是否允许保证金交易/ 如果不是false 就需要制定保证金比例(dict形式) self.allow_t0 = allow_t0 self.allow_sellopen = allow_sellopen self.margin_level = margin_level
def __init__(self, strategy_name=None, user_cookie=None, market_type=MARKET_TYPE.STOCK_CN, frequence=FREQUENCE.DAY, broker=BROKER_TYPE.BACKETEST, portfolio_cookie=None, account_cookie=None, sell_available={}, init_assets=None, cash=None, history=None, commission_coeff=0.00025, tax_coeff=0.0015, margin_level=False, allow_t0=False, allow_sellopen=False): """ :param strategy_name: 策略名称 :param user_cookie: 用户cookie :param market_type: 市场类别 默认QA.MARKET_TYPE.STOCK_CN A股股票 :param frequence: 账户级别 默认日线QA.FREQUENCE.DAY :param broker: BROEKR类 默认回测 QA.BROKER_TYPE.BACKTEST :param portfolio_cookie: 组合cookie :param account_cookie: 账户cookie :param sell_available: 可卖股票数 :param init_assets: 初始资产 默认 1000000 元 (100万) :param cash: 可用现金 默认 是 初始资产 list 类型 :param history: 交易历史 :param commission_coeff: 交易佣金 :默认 万2.5 float 类型 :param tax_coeff: 印花税 :默认 千1.5 float 类型 :param margin_level: 保证金比例 默认False :param allow_t0: 是否允许t+0交易 默认False :param allow_sellopen: 是否允许卖空开仓 默认False """ super().__init__() self._history_headers = ['datetime', 'code', 'price', 'amount', 'order_id', 'trade_id', 'account_cookie', 'commission', 'tax'] ######################################################################## # 信息类: self.strategy_name = strategy_name self.user_cookie = user_cookie self.market_type = market_type self.portfolio_cookie = portfolio_cookie self.account_cookie = QA_util_random_with_topic( 'Acc') if account_cookie is None else account_cookie self.broker = broker self.frequence = frequence self.market_data = None self._currenttime = None self.commission_coeff = commission_coeff self.tax_coeff = tax_coeff self.running_time = datetime.datetime.now() ######################################################################## # 资产类 self.orders = QA_OrderQueue() # 历史委托单 self.init_assets = 1000000 if init_assets is None else init_assets self.cash = [self.init_assets] if cash is None else cash self.cash_available = self.cash[-1] # 可用资金 self.sell_available = sell_available self.history = [] if history is None else history self.time_index = [] ######################################################################## # 规则类 # 两个规则 # 1.是否允许t+0 及买入及结算 # 2.是否允许卖空开仓 # 3.是否允许保证金交易/ 如果不是false 就需要制定保证金比例(dict形式) self.allow_t0 = allow_t0 self.allow_sellopen = allow_sellopen self.margin_level = margin_level
def __init__(self): ''' 随机初始化 user_cookie 的值 Acc+4数字id+4位大小写随机 ''' self.setting = QA_Setting() self.portfolio_list = {} self.user_cookie = QA_util_random_with_topic('USER')
def __init__( self, user_cookie=None, username='******', phone='defalut', level='l1', utype='guests', password='******', coins=10000, money=0, ): """[summary] Keyword Arguments: user_cookie {[type]} -- [description] (default: {None}) 随机初始化 user_cookie 的值 Acc+4数字id+4位大小写随机 username {str} -- [description] (default: {'defalut'}) phone {str} -- [description] (default: {'defalut'}) level {str} -- [description] (default: {'l1'}) utype {str} -- [description] (default: {'guests'}) password {str} -- [description] (default: {'default'}) coins {int} -- [description] (default: {10000}) 关于积分系统: 积分系统用于订阅策略, 取消订阅策略是不会增加积分的 """ self.setting = QA_Setting() self.portfolio_list = {} # ============================== self.phone = phone self.level = level self.utype = utype self.password = password self.username = username self.user_cookie = QA_util_random_with_topic( 'USER') if user_cookie is None else user_cookie self.coins = coins # 积分 self.money = money # 钱 # ============================== self._subscribed_strategy = {} self._subscribed_code = [] self._signals = [] # 预期收到的信号 self._cash = [] self._history = [] # =============================== self.coins_history = [] self.coins_history_headers = [ 'cost_coins', 'strategy_id', 'start', 'last', 'strategy_uuid', 'event' ] self.sync()
def post(self): backtest_name = self.get_argument( 'strategy_name', QA_util_random_with_topic('strategy')) backtest_content = self.get_argument('strategy_content') try: with open('{}{}{}.py'.format(cache_path, os.sep, backtest_name), 'w') as f: f.write(backtest_content) self.write('ok') except Exception as e: self.write(e)
def post(self): backtest_name = self.get_argument( 'strategy_name', QA_util_random_with_topic('strategy')) backtest_content = self.get_argument('strategy_content') filex = '{}{}{}.py'.format(cache_path, os.sep, backtest_name) try: with open(filex, 'w', encoding='utf-8') as f: f.write(backtest_content) self.write({'status': 'success', 'filepath': filex}) except Exception as e: self.write({'status': 'wrong', 'filepath': ''})
def get(self): """[summary] Arguments: QABaseHandler {[type]} -- [description] """ backtest_content=self.get_argument('strategy_content') try: with open('{}{}{}.py'.format(cache_path,os.sep,QA_util_random_with_topic('strategy')),'w') as f: f.write(backtest_content) self.write('ok') except Exception as e: self.write(e)
def __init__( self, user_cookie=None, username='******', phone='defalut', level='l1', utype='guests', password='******', coins=10000, wechat_id=None, money=0, *args, **kwargs ): """[summary] Keyword Arguments: user_cookie {[type]} -- [description] (default: {None}) 随机初始化 user_cookie 的值 Acc+4数字id+4位大小写随机 username {str} -- [description] (default: {'defalut'}) phone {str} -- [description] (default: {'defalut'}) level {str} -- [description] (default: {'l1'}) utype {str} -- [description] (default: {'guests'}) password {str} -- [description] (default: {'default'}) coins {int} -- [description] (default: {10000}) 关于积分系统: 积分系统用于订阅策略, 取消订阅策略是不会增加积分的 """ #self.setting = QA_Setting() self.client = DATABASE.user ## user_cookie/ username / wechat_id self.client.create_index( [ ("user_cookie", ASCENDING), ("username", ASCENDING), ("wechat_id", ASCENDING) ], unique=True ) self.portfolio_list = [] # ============================== self.phone = phone self.level = level self.utype = utype self.password = password self.username = username self.wechat_id = wechat_id if wechat_id is not None: if self.username == 'default': """基于web的初始化 """ self.username = wechat_id self.password = '******' else: """ 另一种 无 WECHATID 的模式, 适合本地python的调试 @yutiansut """ if self.username == 'default': """基于web的初始化 """ self.username = '******' self.password = '******' self.user_cookie = QA_util_random_with_topic( 'USER' ) if user_cookie is None else user_cookie self.coins = coins # 积分 self.money = money # 钱 # ============================== self._subscribed_strategy = {} """ self._subscribed_code: { 'stock_cn': { '000001': ['1min','5min'], '600010': ['tick'] }, 'future_cn': { 'rb1910.SHFE':['tick','60min'], 'IF1909.IFFEX':['tick','1min'] }, 'index_cn': { '000300': ['1min'] } } """ self._subscribed_code = { MARKET_TYPE.STOCK_CN: [], MARKET_TYPE.FUTURE_CN: [], MARKET_TYPE.INDEX_CN: [], MARKET_TYPE.OPTION_CN: [] } self._signals = [] # 预期收到的信号 self._cash = [] self._history = [] # =============================== self.coins_history = [] self.coins_history_headers = [ 'cost_coins', 'strategy_id', 'start', 'last', 'strategy_uuid', 'event' ] self.sync()
def __init__(self, strategy_name=None, user_cookie=None, portfolio_cookie=None, account_cookie=None, market_type=MARKET_TYPE.STOCK_CN, frequence=FREQUENCE.DAY, broker=BROKER_TYPE.BACKETEST, init_hold={}, init_cash=1000000, commission_coeff=0.00025, tax_coeff=0.001, margin_level=False, allow_t0=False, allow_sellopen=False, running_environment=RUNNING_ENVIRONMENT.BACKETEST): """ :param [str] strategy_name: 策略名称 :param [str] user_cookie: 用户cookie :param [str] portfolio_cookie: 组合cookie :param [str] account_cookie: 账户cookie :param [dict] init_hold 初始化时的股票资产 :param [float] init_cash: 初始化资金 :param [float] commission_coeff: 交易佣金 :默认 万2.5 float 类型 :param [float] tax_coeff: 印花税 :默认 千1.5 float 类型 :param [Bool] margin_level: 保证金比例 默认False :param [Bool] allow_t0: 是否允许t+0交易 默认False :param [Bool] allow_sellopen: 是否允许卖空开仓 默认False :param [QA.PARAM] market_type: 市场类别 默认QA.MARKET_TYPE.STOCK_CN A股股票 :param [QA.PARAM] frequence: 账户级别 默认日线QA.FREQUENCE.DAY :param [QA.PARAM] broker: BROEKR类 默认回测 QA.BROKER_TYPE.BACKTEST :param [QA.PARAM] running_environment 当前运行环境 默认Backtest # 2018/06/11 init_assets 从float变为dict,并且不作为输入,作为只读属性 # :param [float] init_assets: 初始资产 默认 1000000 元 (100万) init_assets:{ cash: xxx, stock: {'000001':2000}, init_date: '2018-02-05', init_datetime: '2018-02-05 15:00:00' } # 2018/06/11 取消在初始化的时候的cash和history输入 # :param [list] cash: 可用现金 默认 是 初始资产 list 类型 # :param [list] history: 交易历史 # 2018/11/9 修改保证金交易 # 我们把冻结的保证金 看做是未来的已实现交易: # 如==> 当前的一手空单 认为是未来的卖出成交(已知价格 不知时间) # 因此我们如此对于保证金交易进行评估: # 账户买入: 多单开仓: cash 下降x 保证金增加x 增加一手未来的卖出合约(持仓) ==> 平仓: cash上升 保证金恢复 cash + frozen(平仓释放) + 未平仓位 cash, available_cash frozen{ RB1901: { towards 2: {avg_money : xxx, amount: xxx, queue: collection.deque()}, towards -2: {avg_money, amount, queue: collection.deque()} }, IF1901: { towards 2: {avg_money, amount,queue: collection.deque()}, towards -2: {avg_money, amount,queue: collection.deque()} } } } hold: { RB1901: { 1, amount, # 多单待平仓 -1, amount # 空单待平仓 } } """ super().__init__() # warnings.warn('QUANTAXIS 1.0.46 has changed the init_assets ==> init_cash, please pay attention to this change if you using init_cash to initial an account class,\ # ', DeprecationWarning, stacklevel=2) self._history_headers = [ 'datetime', 'code', 'price', 'amount', 'cash', 'order_id', 'realorder_id', 'trade_id', 'account_cookie', 'commission', 'tax', 'message' ] ######################################################################## # 信息类: self.strategy_name = strategy_name self.user_cookie = user_cookie self.portfolio_cookie = portfolio_cookie self.account_cookie = QA_util_random_with_topic( 'Acc') if account_cookie is None else account_cookie self.market_type = market_type self.broker = broker self.frequence = frequence self.running_environment = running_environment ######################################################################## self._market_data = None self._currenttime = None self.commission_coeff = commission_coeff self.tax_coeff = tax_coeff self.datetime = None self.running_time = datetime.datetime.now() self.quantaxis_version = __version__ ######################################################################## # 资产类 self.orders = QA_OrderQueue() # 历史委托单 self.init_cash = init_cash self.init_hold = pd.Series(init_hold, name='amount') if isinstance( init_hold, dict) else init_hold self.init_hold.index.name = 'code' self.cash = [self.init_cash] self.cash_available = self.cash[-1] # 可用资金 self.sell_available = copy.deepcopy(self.init_hold) self.buy_available = copy.deepcopy(self.init_hold) self.history = [] self.time_index = [] ######################################################################## # 规则类 # 1.是否允许t+0 及买入及结算 # 2.是否允许卖空开仓 # 3.是否允许保证金交易/ 如果不是false 就需要制定保证金比例(dict形式) # 期货: allow_t0 True allow_sellopen True # self.allow_t0 = allow_t0 self.allow_sellopen = allow_sellopen self.margin_level = margin_level # 保证金比例 """期货的多开/空开 ==> 资金冻结进保证金 frozen 对应平仓的时候, 释放保证金 1. frozen 是一个dict : {[code]:queue} key是标的 value是对应的交易queue """ self.frozen = {} # 冻结资金(保证金)
def __init__(self, strategy_name=None, user_cookie=None, portfolio_cookie=None, account_cookie=None, market_type=MARKET_TYPE.STOCK_CN, frequence=FREQUENCE.DAY, broker=BROKER_TYPE.BACKETEST, init_hold={}, init_cash=1000000, commission_coeff=0.00025, tax_coeff=0.0015, margin_level=False, allow_t0=False, allow_sellopen=False, running_environment=RUNNING_ENVIRONMENT.BACKETEST): """ :param [str] strategy_name: 策略名称 :param [str] user_cookie: 用户cookie :param [str] portfolio_cookie: 组合cookie :param [str] account_cookie: 账户cookie :param [dict] init_hold 初始化时的股票资产 :param [float] init_cash: 初始化资金 :param [float] commission_coeff: 交易佣金 :默认 万2.5 float 类型 :param [float] tax_coeff: 印花税 :默认 千1.5 float 类型 :param [Bool] margin_level: 保证金比例 默认False :param [Bool] allow_t0: 是否允许t+0交易 默认False :param [Bool] allow_sellopen: 是否允许卖空开仓 默认False :param [QA.PARAM] market_type: 市场类别 默认QA.MARKET_TYPE.STOCK_CN A股股票 :param [QA.PARAM] frequence: 账户级别 默认日线QA.FREQUENCE.DAY :param [QA.PARAM] broker: BROEKR类 默认回测 QA.BROKER_TYPE.BACKTEST :param [QA.PARAM] running_environment 当前运行环境 默认Backtest # 2018/06/11 init_assets 从float变为dict,并且不作为输入,作为只读属性 # :param [float] init_assets: 初始资产 默认 1000000 元 (100万) init_assets:{ cash: xxx, stock: {'000001':2000}, init_date: '2018-02-05', init_datetime: '2018-02-05 15:00:00' } # 2018/06/11 取消在初始化的时候的cash和history输入 # :param [list] cash: 可用现金 默认 是 初始资产 list 类型 # :param [list] history: 交易历史 """ super().__init__() warnings.warn( 'QUANTAXIS 1.0.46 has changed the init_assets ==> init_cash, please pay attention to this change if you using init_cash to initial an account class,\ ', DeprecationWarning, stacklevel=2) self._history_headers = [ 'datetime', 'code', 'price', 'amount', 'cash', 'order_id', 'trade_id', 'account_cookie', 'commission', 'tax' ] ######################################################################## # 信息类: self.strategy_name = strategy_name self.user_cookie = user_cookie self.portfolio_cookie = portfolio_cookie self.account_cookie = QA_util_random_with_topic( 'Acc') if account_cookie is None else account_cookie self.market_type = market_type self.broker = broker self.frequence = frequence self.running_environment = running_environment ######################################################################## self.market_data = None self._currenttime = None self.commission_coeff = commission_coeff self.tax_coeff = tax_coeff self.datetime = None self.running_time = datetime.datetime.now() self.quantaxis_version = __version__ ######################################################################## # 资产类 self.orders = QA_OrderQueue() # 历史委托单 self.init_cash = init_cash self.init_hold = pd.Series(init_hold, name='amount') if isinstance( init_hold, dict) else init_hold self.init_hold.index.name = 'code' self.cash = [self.init_cash] self.cash_available = self.cash[-1] # 可用资金 self.sell_available = copy.deepcopy(self.init_hold) self.buy_available = copy.deepcopy(self.init_hold) self.history = [] self.time_index = [] ######################################################################## # 规则类 # 两个规则 # 1.是否允许t+0 及买入及结算 # 2.是否允许卖空开仓 # 3.是否允许保证金交易/ 如果不是false 就需要制定保证金比例(dict形式) self.allow_t0 = allow_t0 self.allow_sellopen = allow_sellopen self.margin_level = margin_level
def __init__(self): self.setting = QA_Setting() self.portfolio_list = {} self.user_cookie = QA_util_random_with_topic('USER')
def QA_VectorBacktest_adv(backtest_id = None, code_list = None, in_sample_year_list = None, out_sample_year_list = None, in_sample_timeperiod = None, out_sample_timeperiod = None, all_yeal_list = None, all_timeperiod = None, data_engine = None, data_freq = None, func = None, comission = 0.00025, params=None, params_optimize_dict=None, if_optimize_parameters=False, root_save_path=None, if_reload_save_files=True, if_legend=True, code_num_each_process = 5 ): backtest_id = QA_util_random_with_topic(topic='backtest', lens=8) if backtest_id == None else backtest_id print('######################################################################################') print('此次回测的回测id:{}'.format(backtest_id)) print('此次回测的回测根目录:{}'.format(root_save_path)) if_in_sample = False if_out_sample = False if_all_sample = False backtest_list = [] if (in_sample_year_list!=None)|(in_sample_timeperiod != None): if_in_sample = True backtest_list.append('样本内') if (out_sample_year_list!=None)|(out_sample_timeperiod != None): if_out_sample = True backtest_list.append('样本外') if (all_yeal_list!=None)|(all_timeperiod != None): if_all_sample = True backtest_list.append('全样本') print('此次回测的回测列表:{}'.format(backtest_list)) if if_in_sample: in_sample_path = os.path.join(root_save_path,backtest_id,'in_sample') print('此次回测的样本内回测目录:{}'.format(in_sample_path)) if if_out_sample: out_sample_path = os.path.join(root_save_path, backtest_id, 'out_sample') print('此次回测的样本外回测目录:{}'.format(out_sample_path)) if if_all_sample: all_sample_path = os.path.join(root_save_path, backtest_id, 'all_sample') print('此次回测的全样本回测目录:{}'.format(all_sample_path)) '''样本内回测''' if if_in_sample: if in_sample_timeperiod==None: print('开始样本内测试,样本内测试年份:{}'.format(in_sample_year_list)) data_start = min(in_sample_year_list)+'-01-01 00:00:00' data_end = max(in_sample_year_list)+'-12-31 23:59:00' run_year_list = in_sample_year_list elif in_sample_year_list==None: print('开始样本内测试,样本内测试开始时间:{},样本内测试结束时间:{}'.format(in_sample_timeperiod[0],in_sample_timeperiod[1])) data_start = in_sample_timeperiod[0] data_end = in_sample_timeperiod[1] run_year_list = None result,simple_result,params_res,res_group_average,simple_res_group_average,params_res_group_average = QA_VectorBacktest(data = data_engine(code_list,data_start,data_end,data_freq).data, func = func, comission = comission, params = params, params_optimize_dict = params_optimize_dict, run_year_list = run_year_list, if_optimize_parameters = True, if_reorder_params = True, save_path = in_sample_path, if_reload_save_files = if_reload_save_files, if_legend= if_legend, code_list= code_list, code_num_each_process = code_num_each_process )