def test02(self): config = self.load_config(self._p('conf/2_test.yml')) try: run(config) except SystemExit as e: pass diff_res = sh.diff(self._p("test_output/I88_force_close.csv"), self._p("expect_output/2_I88_force_close.csv")) self.assertEqual(diff_res, "")
def test01(self): config = self.load_config(self._p('conf/1_test.yml')) try: run(config) except SystemExit as e: pass self.fetch_fields(self._p("test_output/trades.csv"), self._p("test_output/trades_filter.csv")) diff_res = sh.diff(self._p("test_output/trades_filter.csv"), self._p("expect_output/1_trades_filter.csv")) self.assertEqual(diff_res, "")
def test01(self): config = self.load_config(self._p('conf/1_test.yml')) try: run(config) except SystemExit as e: pass diff_res = sh.diff(self._p("test_output/I88_stop_profit_loss.csv"), self._p("expect_output/1_I88_stop_profit_loss.csv")) self.assertEqual(diff_res, "")
def _run_task(self, key, params, disable_output=False): logger.info("run %s, %s" % (key, params)) if disable_output: params['mod']['sys_analyser']['output_file'] = None run(params) if disable_output: return summary = self._read_pickle(key) logger.info(summary) self._all_result_dict[key] = summary
def run_test(filename): config = {"base": {"strategy_file": os.path.join(TEST_DIR, filename)}} print(u"Start test: " + str(config["base"]["strategy_file"])) result_dict = run(config)["sys_analyser"] old_pickle_file = os.path.join(TEST_OUT, filename.replace(".py", ".pkl")) if not os.path.exists(old_pickle_file): if not os.path.exists(TEST_OUT): os.makedirs(TEST_OUT) pickle.dump(result_dict, open(old_pickle_file, "wb"), protocol=2) return else: old_result_dict = pd.read_pickle(old_pickle_file) # 比较 portfolios old_df = old_result_dict["portfolio"].replace( [np.nan, np.inf, -np.inf], 0).round(0) df = result_dict["portfolio"].replace([np.nan, np.inf, -np.inf], 0).round(0) try: del old_df["dividend_receivable"] del df["dividend_receivable"] except: pass result = df.eq(old_df) if not result.all().all(): return result.all() # 比较 summary old_df = (pd.DataFrame( data=[{ "val": val } for val in old_result_dict["summary"].values()], index=old_result_dict["summary"].keys(), ).sort_index().T.fillna(0)) df = (pd.DataFrame( data=[{ "val": val } for val in result_dict["summary"].values()], index=result_dict["summary"].keys(), ).sort_index().T.fillna(0)) try: del old_df["daily_pnl"] del old_df["daily_returns"] del old_df["dividend_receivable"] del old_df["strategy_file"] del df["strategy_file"] except: pass try: del old_df["strategy_file"] del df["strategy_file"] except: pass try: assert_frame_equal(df, old_df, check_less_precise=8) except AssertionError as e: return str(e)
"available_position": True, }, "analyser": { "priority": 100, "enabled": True, "lib": 'rqalpha.mod.analyser', "record": True, "output_file": os.path.expanduser("~\\.rqalpha\\res\\" + strategy_name + "\\result.pkl"), "plot": os.path.expanduser("~"), "plot_save_file": os.path.expanduser("~\\.rqalpha\\res\\" + strategy_name + "\\result.png"), "report_save_path": os.path.expanduser("~\\.rqalpha\\res\\") } } } return config if __name__ == '__main__': run(getConfig())
def run_test(filename): config = {"base": {"strategy_file": os.path.join(TEST_DIR, filename)}} print(u"Start test: " + str(config["base"]["strategy_file"])) result_dict = run(config)['sys_analyser'] df = result_dict["portfolio"] # del df['positions'] old_pickle_file = os.path.join(TEST_OUT, filename.replace(".py", ".pkl")) if not os.path.exists(old_pickle_file): if not os.path.exists(TEST_OUT): os.makedirs(TEST_OUT) pickle.dump(result_dict, open(old_pickle_file, "wb"), protocol=2) return None, None else: old_result_dict = pd.read_pickle(old_pickle_file) # 比较 portfolios old_df = old_result_dict["portfolio"] old_df = old_df.fillna(0) old_df = old_df.replace([np.inf, -np.inf], 0) df = df.fillna(0) df = df.replace([np.inf, -np.inf], 0) # del old_df["trades"] # del df["trades"] try: del old_df["dividend_receivable"] del df["dividend_receivable"] except: pass df = df.round(0) old_df = old_df.round(0) result = df.eq(old_df) if not result.all().all(): return result.all(), (df, old_df, result) # 比较 summary old_df = pd.DataFrame( data=[{ "val": val } for val in old_result_dict["summary"].values()], index=old_result_dict["summary"].keys()).sort_index().T.fillna(0) df = pd.DataFrame( data=[{ "val": val } for val in result_dict["summary"].values()], index=result_dict["summary"].keys()).sort_index().T.fillna(0) try: del old_df['daily_pnl'] del old_df['daily_returns'] del old_df['dividend_receivable'] del old_df['strategy_file'] del df['strategy_file'] except: pass try: del old_df['strategy_file'] del df['strategy_file'] except: pass result = df.eq(old_df) if not result.all().all(): return result.all(), (old_result_dict, result_dict, result) return None, None
# 使用talib计算长短两根均线,均线以array的格式表达 short_avg = talib.SMA(prices, context.SHORTPERIOD) long_avg = talib.SMA(prices, context.LONGPERIOD) plot("short avg", short_avg[-1]) plot("long avg", long_avg[-1]) # 计算现在portfolio中股票的仓位 cur_position = context.portfolio.positions[context.s1].quantity # 计算现在portfolio中的现金可以购买多少股票 shares = context.portfolio.cash / bar_dict[context.s1].close # 如果短均线从上往下跌破长均线,也就是在目前的bar短线平均值低于长线平均值,而上一个bar的短线平均值高于长线平均值 if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0: # 进行清仓 logger.info('Sell: Datetime {}, Amount All'.format(bar_dict[context.s1].datetime)) order_target_value(context.s1, 0) # 如果短均线从下往上突破长均线,为入场信号 if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0: # 满仓入股 logger.info('Buy: Datetime {}, Amount {}'.format(bar_dict[context.s1].datetime, shares)) order_shares(context.s1, shares) if __name__ == '__main__': from ialgotest.conf.generate_config import gen_conf run(gen_conf(__file__, start='2016-03-01', end='2016-03-31', freq='1m', save_plot=True, save_output=True, report_path='/home/eshufan/rq_reports/'))
long_avg = talib.SMA(prices, context.LONGPERIOD) plot("short avg", short_avg[-1]) plot("long avg", long_avg[-1]) # 计算现在portfolio中股票的仓位 cur_position = context.portfolio.positions[context.s1].quantity # 计算现在portfolio中的现金可以购买多少股票 shares = context.portfolio.cash / bar_dict[context.s1].close # 如果短均线从上往下跌破长均线,也就是在目前的bar短线平均值低于长线平均值,而上一个bar的短线平均值高于长线平均值 if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[ -2] > 0 and cur_position > 0: # 进行清仓 order_target_value(context.s1, 0) # 如果短均线从下往上突破长均线,为入场信号 if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0: # 满仓入股 order_shares(context.s1, shares) if __name__ == '__main__': from ialgotest.conf.generate_config import gen_conf run( gen_conf(__file__, save_plot=True, save_output=True, report_path='/home/eshufan/rq_reports/'))
def test_api(): print(u"Testing API......") from rqalpha import run from tests.api.test_api_base import test_get_order_code_new, test_get_open_order_code_new, \ test_cancel_order_code_new, \ test_update_universe_code_new, test_subscribe_code_new, test_unsubscribe_code_new, \ test_get_yield_curve_code_new, \ test_history_bars_code_new, test_all_instruments_code_new, test_instruments_code_new, test_sector_code_new, \ test_concept_code_new, test_industry_code_new, test_get_trading_dates_code_new, \ test_get_previous_trading_date_code_new, test_get_next_trading_date_code_new, test_get_dividend_code_new from tests.api.test_api_stock import test_order_shares_code_new, test_order_lots_code_new, \ test_order_value_code_new, \ test_order_percent_code_new, test_order_target_value_code_new from tests.api.test_api_future import test_buy_open_code_new, test_sell_open_code_new, test_buy_close_code_new, \ test_sell_close_code_new base_api_config = { "base": { "securities": "stock", "start_date": "2016-12-01", "end_date": "2016-12-31", "frequency": "1d", "matching_type": "next_bar", "stock_starting_cash": 1000000, "strategy_file": 'rqalpha/__init__.py' }, "extra": { "log_level": "error", }, "mod": { "sys_progress": { "enabled": False, }, }, } stock_api_config = { "base": { "securities": "stock", "start_date": "2016-03-07", "end_date": "2016-03-08", "frequency": "1d", "matching_type": "next_bar", "stock_starting_cash": 100000000, "strategy_file": 'rqalpha/__init__.py' }, "extra": { "log_level": "error", }, "mod": { "sys_progress": { "enabled": False, }, }, } future_api_config = { "base": { "securities": "future", "start_date": "2016-03-07", "end_date": "2016-03-08", "frequency": "1d", "matching_type": "next_bar", "future_starting_cash": 10000000000, "strategy_file": 'rqalpha/__init__.py' }, "extra": { "log_level": "error", }, "mod": { "sys_progress": { "enabled": False, }, }, } # =================== Test Base API =================== run(base_api_config, test_get_order_code_new) run(base_api_config, test_get_open_order_code_new) run(base_api_config, test_cancel_order_code_new) run(base_api_config, test_update_universe_code_new) run(base_api_config, test_subscribe_code_new) run(base_api_config, test_unsubscribe_code_new) run(base_api_config, test_get_yield_curve_code_new) run(base_api_config, test_history_bars_code_new) run(base_api_config, test_all_instruments_code_new) run(base_api_config, test_instruments_code_new) run(base_api_config, test_sector_code_new) run(base_api_config, test_industry_code_new) run(base_api_config, test_concept_code_new) run(base_api_config, test_get_trading_dates_code_new) run(base_api_config, test_get_previous_trading_date_code_new) run(base_api_config, test_get_next_trading_date_code_new) run(base_api_config, test_get_dividend_code_new) # =================== Test Stock API =================== run(stock_api_config, test_order_shares_code_new) run(stock_api_config, test_order_lots_code_new) run(stock_api_config, test_order_value_code_new) run(stock_api_config, test_order_percent_code_new) run(stock_api_config, test_order_target_value_code_new) # =================== Test Future API =================== run(future_api_config, test_buy_open_code_new) run(future_api_config, test_sell_open_code_new) run(future_api_config, test_buy_close_code_new) run(future_api_config, test_sell_close_code_new) print(u"API test ends.")
def before_trading(context): pass # 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新 def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # bar_dict[order_book_id] 可以拿到某个证券的bar信息 # context.portfolio 可以拿到现在的投资组合状态信息 # 使用order_shares(id_or_ins, amount)方法进行落单 # TODO: 开始编写你的算法吧! logger.info(bar_dict[context.s1]) prices = history_bars(context.s1, 3, '1d', ['datetime', 'close']) logger.info([x for x in prices]) if not context.fired: # order_percent并且传入1代表买入该股票并且使其占有投资组合的100% order_percent(context.s1, 1) context.fired = True if __name__ == '__main__': from ialgotest.conf.generate_config import gen_conf run(gen_conf(__file__))
"accounts": { "stock": 100000 }, "benchmark": "000300.XSHG" }, "mod": { "mysql": { "enabled": True }, "tushare": { "enabled": False }, "sys_analyser": { "enabled": True, "plot": True, # 当不输出csv/pickle/plot 等内容时,可以通过 record 来决定是否执行该 Mod 的计算逻辑 "record": True, # 如果指定路径,则输出计算后的 pickle 文件 "output_file": "result.pkl", # 如果指定路径,则输出 report csv 文件 "report_save_path": ".", # 画图 'plot': True, # 如果指定路径,则输出 plot 对应的图片文件 'plot_save_file': "result.png" } } } #init() run(config)
def test_api(): # FIXME: Error msg is hard to understand @zjuguxi # return print(u"Testing API......") from rqalpha import run from tests.api.test_api_base import ( test_get_order_code_new, test_get_open_order_code_new, test_cancel_order_code_new, test_update_universe_code_new, test_subscribe_code_new, test_unsubscribe_code_new, test_get_yield_curve_code_new, test_history_bars_code_new, test_all_instruments_code_new, test_instruments_code_new, test_sector_code_new, test_concept_code_new, test_industry_code_new, test_get_trading_dates_code_new, test_get_previous_trading_date_code_new, test_get_next_trading_date_code_new, test_get_dividend_code_new, ) from tests.api.test_api_stock import ( test_order_shares_code_new, test_order_lots_code_new, test_order_value_code_new, test_order_percent_code_new, test_order_target_value_code_new, ) from tests.api.test_api_future import ( test_buy_open_code_new, test_sell_open_code_new, test_buy_close_code_new, test_sell_close_code_new, ) base_api_config = { "base": { "start_date": "2016-12-01", "end_date": "2016-12-31", "frequency": "1d", "matching_type": "next_bar", "strategy_file": 'rqalpha/__init__.py', "accounts": { "stock": 1000000 } }, "extra": { "log_level": "error", }, "mod": { "sys_progress": { "enabled": True, "show": True, }, }, } stock_api_config = { "base": { "start_date": "2016-03-07", "end_date": "2016-03-08", "frequency": "1d", "matching_type": "next_bar", "strategy_file": 'rqalpha/__init__.py', "accounts": { "stock": 100000000 } }, "extra": { "log_level": "error", }, "mod": { "sys_progress": { "enabled": True, "show": True, }, }, } future_api_config = { "base": { "start_date": "2016-03-07", "end_date": "2016-03-08", "frequency": "1d", "matching_type": "next_bar", "strategy_file": 'rqalpha/__init__.py', "accounts": { "future": 10000000000 } }, "extra": { "log_level": "error", }, "mod": { "sys_progress": { "enabled": True, "show": True, }, }, } # =================== Test Base API =================== tasks = [] tasks.append((base_api_config, test_get_order_code_new, "test_get_order_code_new")) tasks.append((base_api_config, test_get_open_order_code_new, "test_get_open_order_code_new")) tasks.append((base_api_config, test_cancel_order_code_new, "test_cancel_order_code_new")) tasks.append((base_api_config, test_update_universe_code_new, "test_update_universe_code_new")) tasks.append((base_api_config, test_subscribe_code_new, "test_subscribe_code_new")) tasks.append((base_api_config, test_unsubscribe_code_new, "test_unsubscribe_code_new")) tasks.append((base_api_config, test_get_yield_curve_code_new, "test_get_yield_curve_code_new")) tasks.append((base_api_config, test_history_bars_code_new, "test_history_bars_code_new")) tasks.append((base_api_config, test_all_instruments_code_new, "test_all_instruments_code_new")) tasks.append((base_api_config, test_instruments_code_new, "test_instruments_code_new")) tasks.append((base_api_config, test_sector_code_new, "test_sector_code_new")) tasks.append((base_api_config, test_industry_code_new, "test_industry_code_new")) tasks.append((base_api_config, test_concept_code_new, "test_concept_code_new")) tasks.append((base_api_config, test_get_trading_dates_code_new, "test_get_trading_dates_code_new")) tasks.append((base_api_config, test_get_previous_trading_date_code_new, "test_get_previous_trading_date_code_new")) tasks.append((base_api_config, test_get_next_trading_date_code_new, "test_get_next_trading_date_code_new")) tasks.append((base_api_config, test_get_dividend_code_new, "test_get_dividend_code_new")) # =================== Test Stock API =================== tasks.append((stock_api_config, test_order_shares_code_new, "test_order_shares_code_new")) tasks.append((stock_api_config, test_order_lots_code_new, "test_order_lots_code_new")) tasks.append((stock_api_config, test_order_value_code_new, "test_order_value_code_new")) tasks.append((stock_api_config, test_order_percent_code_new, "test_order_percent_code_new")) tasks.append((stock_api_config, test_order_target_value_code_new, "test_order_target_value_code_new")) # =================== Test Future API =================== tasks.append((future_api_config, test_buy_open_code_new, "test_buy_open_code_new")) tasks.append((future_api_config, test_sell_open_code_new, "test_sell_open_code_new")) tasks.append((future_api_config, test_buy_close_code_new, "test_buy_close_code_new")) tasks.append((future_api_config, test_sell_close_code_new, "test_sell_close_code_new")) for cfg, source_code, name in tasks: print("running", name) run(cfg, source_code) print(u"API test ends.")
"benchmark": None, "strategy_file": str(path) }, "extra": { "log_level": "verbose", }, "mod": { "sys_analyser": { "enabled": True, # "report_save_path": ".", "plot": True }, "sys_simulation": { "enabled": True, # "matching_type": "last" }, "fxdayu_source": { "enabled": True, "source": "mongo", "mongo_url": "mongodb://192.168.0.101:27017", "enable_cache": True, "cache_length": 10000 } } } if __name__ == "__main__": start = time.time() run(config=config) print("Time Cost: %s seconds" % (time.time() - start))
def run(baseConf): config["base"] = baseConf return rqalpha.run(config)
def before_trading(context): pass # 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新 def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # bar_dict[order_book_id] 可以拿到某个证券的bar信息 # context.portfolio 可以拿到现在的投资组合状态信息 # 使用order_shares(id_or_ins, amount)方法进行落单 # TODO: 开始编写你的算法吧! logger.info(bar_dict[context.s1]) # prices = history_bars(context.s1, 3, '1d', ['datetime', 'close']) # logger.info([x for x in prices]) if not context.fired: # order_percent并且传入1代表买入该股票并且使其占有投资组合的100% order_percent(context.s1, 1) context.fired = True if __name__ == '__main__': from ialgotest.conf.generate_config import gen_conf run(gen_conf(__file__, start='2016-03-01', end='2016-03-31', freq='1m'))
def run_test(filename): config = { "base": { "strategy_file": os.path.join(TEST_DIR, filename) } } print(u"Start test: " + str(config["base"]["strategy_file"])) result_dict = run(config)['sys_analyser'] df = result_dict["portfolio"] # del df['positions'] old_pickle_file = os.path.join(TEST_OUT, filename.replace(".py", ".pkl")) if not os.path.exists(old_pickle_file): if not os.path.exists(TEST_OUT): os.makedirs(TEST_OUT) pickle.dump(result_dict, open(old_pickle_file, "wb"), protocol=2) return None, None else: old_result_dict = pd.read_pickle(old_pickle_file) # 比较 portfolios old_df = old_result_dict["portfolio"] old_df = old_df.fillna(0) old_df = old_df.replace([np.inf, -np.inf], 0) df = df.fillna(0) df = df.replace([np.inf, -np.inf], 0) # del old_df["trades"] # del df["trades"] try: del old_df["dividend_receivable"] del df["dividend_receivable"] except: pass df = df.round(0) old_df = old_df.round(0) result = df.eq(old_df) if not result.all().all(): return result.all(), (df, old_df, result) # 比较 summary old_df = pd.DataFrame(data=[{"val": val} for val in old_result_dict["summary"].values()], index=old_result_dict["summary"].keys()).sort_index().T.fillna(0) df = pd.DataFrame(data=[{"val": val} for val in result_dict["summary"].values()], index=result_dict["summary"].keys()).sort_index().T.fillna(0) try: del old_df['daily_pnl'] del old_df['daily_returns'] del old_df['dividend_receivable'] del old_df['strategy_file'] del df['strategy_file'] except: pass try: del old_df['strategy_file'] del df['strategy_file'] except: pass result = df.eq(old_df) if not result.all().all(): return result.all(), (old_result_dict, result_dict, result) return None, None
def run_bt(config, self, *args, **kwargs): for func in self._pre_backtest: config = func(config) run(config, *args, **kwargs) for func in self._post_backtest: config = func(config)
"matching_type": "current_bar", "start_date": "2017-01-01", "end_date": "2018-02-06", "benchmark": "000001.XSHE", "frequency": "1d", "strategy_file": "C:/Users/think/PycharmProjects/wendou/FBB.py", "accounts": { "stock": 100000 } }, "mod": { "sys_progress": { "enabled": True, "show": True, }, "sys_analyser": { "enabled": True, "output_file": "E:/tmp/result/FBB-out-{tick}.pkl".format(tick=inst[0]) }, }, } tasks.append(config) for task in tasks: run(task) time.sleep(2) csvfile.close