Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def set_loggers(config):
from rqalpha.utils.logger import user_log, user_system_log, user_detail_log, system_log, basic_system_log, std_log
from rqalpha.utils.logger import user_std_handler, init_logger
from rqalpha.utils import logger
extra_config = config.extra
init_logger()
for log in [basic_system_log, system_log, std_log, user_system_log, user_detail_log]:
log.level = getattr(logbook, config.extra.log_level.upper(), logbook.NOTSET)
user_log.level = logbook.DEBUG
if extra_config.log_level.upper() != "NONE":
if not extra_config.user_log_disabled:
user_log.handlers.append(user_std_handler)
if not extra_config.user_system_log_disabled:
user_system_log.handlers.append(user_std_handler)
for logger_name, level in extra_config.logger:
getattr(logger, logger_name).level = getattr(logbook, level.upper())
u'Microsoft Yahei',
u'Heiti SC',
u'Heiti TC',
u'STHeiti',
u'WenQuanYi Zen Hei',
u'WenQuanYi Micro Hei',
u"文泉驿微米黑",
u'SimHei',
] + rcParams['font.sans-serif']
rcParams['axes.unicode_minus'] = False
use_chinese_fonts = True
font = findfont(FontProperties(family=['sans-serif']))
if "/matplotlib/" in font:
use_chinese_fonts = False
system_log.warn("Missing Chinese fonts. Fallback to English.")
summary = result_dict["summary"]
title = summary['strategy_file']
portfolio = result_dict["portfolio"]
benchmark_portfolio = result_dict.get("benchmark_portfolio")
index = portfolio.index
# max drawdown
portfolio_value = portfolio.unit_net_value * portfolio.units
xs = portfolio_value.values
rt = portfolio.unit_net_value.values
max_dd_end = np.argmax(np.maximum.accumulate(xs) / xs)
if max_dd_end == 0:
data_source = BaseDataSource(config.base.data_bundle_path)
data_proxy = DataProxy(data_source)
order_book_id_list = sorted(ins.order_book_id for ins in data_proxy.all_instruments("CS"))
def record_market_data(total_df):
for order_book_id, item in total_df.iterrows():
redis_client[order_book_id] = json.dumps(item.to_dict())
retry_cnt = 0
while True:
try:
total_df = get_realtime_quotes(order_book_id_list, include_limit=True)
except (OSError, IOError) as e:
system_log.exception("get_realtime_quotes socket error. retry {} {}", retry_cnt, e)
time.sleep(retry_cnt * 2)
retry_cnt += 1
continue
system_log.info("Fetching snapshots, size {}", len(total_df))
record_market_data(total_df)
time.sleep(1)
retry_cnt = 0
def set_state(self, state):
state = jsonpickle.loads(state.decode('utf-8'))
for key, value in six.iteritems(state):
try:
self._objects[key].set_state(value)
except KeyError:
system_log.warn('core object state for {} ignored'.format(key))
def apply_settlement(self, event):
prev_trading_date = self._env.data_proxy.get_previous_trading_date(self._env.trading_dt).date()
system_log.info("booking settlement on {}".format(prev_trading_date))
super(Booking, self).apply_settlement(prev_trading_date)
self.clock_engine_thread.start()
if not self.mod_config.redis_uri:
self.quotation_engine_thread.start()
while running:
real_dt = datetime.datetime.now()
while True:
try:
dt, event_type = self.event_queue.get(timeout=1)
break
except Empty:
continue
system_log.debug("real_dt {}, dt {}, event {}", real_dt, dt, event_type)
yield Event(event_type, calendar_dt=real_dt, trading_dt=dt)
def _exception_handler(e):
try:
sys.excepthook(e.error.exc_type, e.error.exc_val, e.error.exc_tb)
except Exception as e:
system_log.exception("hook exception failed")
user_system_log.error(e.error)
if not is_user_exc(e.error.exc_val):
code = const.EXIT_CODE.EXIT_INTERNAL_ERROR
system_log.error(_(u"strategy execute exception"), exc=e)
else:
code = const.EXIT_CODE.EXIT_USER_ERROR
user_detail_log.error(_(u"strategy execute exception"), exc=e)
return code
def start_up(self, env, mod_config):
self.env = env
self.mod_config = mod_config
if env.config.base.run_type != RUN_TYPE.LIVE_TRADING:
system_log.info("Mod booking will only run in live trading")
return
if env.config.base.init_positions:
raise RuntimeError("RQAlpha receive init positions. rqalpha_mod_sys_booking does not support init_positions")
self.booking_account = BookingAccount(register_event=True)
# 昨仓
trades = []
position_list = self._get_old_position_list()
for position_dict in position_list:
if position_dict["buy_quantity"] != 0:
trade = self._create_trade(
position_dict["order_book_id"],
position_dict["buy_quantity"],
SIDE.BUY,
def wrapper(*args, **kwargs):
if not Environment.get_instance().config.extra.is_hold:
return func(*args, **kwargs)
else:
system_log.debug(_(u"not run {}({}, {}) because strategy is hold").format(func, args, kwargs))
def tear_down(self, *args):
result = {}
for mod_name, __ in reversed(self._mod_list):
try:
basic_system_log.debug(_(u"mod tear_down [START] {}").format(mod_name))
ret = self._mod_dict[mod_name].tear_down(*args)
basic_system_log.debug(_(u"mod tear_down [END] {}").format(mod_name))
except Exception as e:
system_log.exception("tear down fail for {}", mod_name)
continue
if ret is not None:
result[mod_name] = ret
return result