Skip to content

Commit

Permalink
1. 解决python 2.7 显示中文 乱码的问题
Browse files Browse the repository at this point in the history
2.	将大部分的提示信息包装成多语言版本。
  • Loading branch information
EricWang committed Feb 28, 2017
1 parent d83e9f3 commit e82f962
Show file tree
Hide file tree
Showing 11 changed files with 134 additions and 30 deletions.
54 changes: 50 additions & 4 deletions messages.pot
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2017-02-28 11:22+0800\n"
"POT-Creation-Date: 2017-02-28 15:07+0800\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
Expand Down Expand Up @@ -38,6 +38,40 @@ msgstr ""
msgid "benchmark {benchmark} has been de_listed on {end_date}"
msgstr ""

#: rqalpha/main.py:124
msgid ""
"\n"
"[WARNING]\n"
"Target bundle path {data_bundle_path} is not empty.\n"
"The content of this folder will be REMOVED before updating.\n"
"Are you sure to continue?\n"
" "
msgstr ""

#: rqalpha/main.py:132
msgid "try {} ..."
msgstr ""

#: rqalpha/main.py:141
msgid "downloading ..."
msgstr ""

#: rqalpha/main.py:155
msgid "Data bundle download successfully in {bundle_path}"
msgstr ""

#: rqalpha/main.py:295
msgid "unknown event from event source: {}"
msgstr ""

#: rqalpha/main.py:301
msgid "strategy run successfully, normal exit"
msgstr ""

#: rqalpha/main.py:310 rqalpha/main.py:323 rqalpha/main.py:326
msgid "strategy execute exception"
msgstr ""

#: rqalpha/plot.py:116
msgid "Total Returns"
msgstr ""
Expand Down Expand Up @@ -166,12 +200,16 @@ msgid ""
"instead."
msgstr ""

#: rqalpha/core/strategy_context.py:313 rqalpha/core/strategy_context.py:317
#: rqalpha/core/strategy_context.py:321 rqalpha/core/strategy_context.py:325
#: rqalpha/core/strategy_context.py:329
#: rqalpha/core/strategy_context.py:312 rqalpha/core/strategy_context.py:316
#: rqalpha/core/strategy_context.py:320 rqalpha/core/strategy_context.py:324
#: rqalpha/core/strategy_context.py:328
msgid "[deprecated] {} is no longer used."
msgstr ""

#: rqalpha/mod/mod_handler.py:43
msgid "loading mod {}"
msgstr ""

#: rqalpha/mod/risk_manager/frontend_validator.py:51
msgid "Order Rejected: {order_book_id} is not listed!"
msgstr ""
Expand Down Expand Up @@ -277,6 +315,10 @@ msgstr ""
msgid "{order_book_id} is expired, close all positions by system"
msgstr ""

#: rqalpha/model/account/stock_account.py:222
msgid "no split data {}"
msgstr ""

#: rqalpha/model/account/stock_account.py:231
#: rqalpha/model/account/stock_account.py:240
msgid "split {order_book_id}, {position}"
Expand All @@ -286,6 +328,10 @@ msgstr ""
msgid "split {order_book_id}, {series}"
msgstr ""

#: rqalpha/utils/__init__.py:150
msgid "not run {}({}, {}) because strategy is hold"
msgstr ""

#: rqalpha/utils/arg_checker.py:58
msgid ""
"function {}: invalid {} argument, expect a value of type {}, got {} "
Expand Down
1 change: 0 additions & 1 deletion rqalpha/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

import click
import errno
import locale
import os
import shutil

Expand Down
1 change: 0 additions & 1 deletion rqalpha/core/strategy_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,6 @@ def get_state(self):
if key.startswith("_"):
continue
try:
# system_log.debug("persist {})
dict_data[key] = pickle.dumps(value)
except Exception as e:
user_system_log.warn("context.{} can not pickle", key)
Expand Down
23 changes: 14 additions & 9 deletions rqalpha/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,16 +116,20 @@ def update_bundle(data_bundle_path=None, confirm=True):
data_bundle_path = os.path.abspath(os.path.join(data_bundle_path, './bundle/'))
if (confirm and os.path.exists(data_bundle_path) and data_bundle_path != default_bundle_path and
os.listdir(data_bundle_path)):
click.confirm('[WARNING] Target bundle path {} is not empty. The content of this folder will be REMOVED before '
'updating. Are you sure to continue?'.format(data_bundle_path), abort=True)
click.confirm(_("""
[WARNING]
Target bundle path {data_bundle_path} is not empty.
The content of this folder will be REMOVED before updating.
Are you sure to continue?
""".format(data_bundle_path=data_bundle_path)), abort=True)

day = datetime.date.today()
tmp = os.path.join(tempfile.gettempdir(), 'rq.bundle')

while True:
url = 'http://7xjci3.com1.z0.glb.clouddn.com/bundles_v2/rqbundle_%04d%02d%02d.tar.bz2' % (
day.year, day.month, day.day)
six.print_('try {} ...'.format(url))
six.print_(_('try {} ...').format(url))
r = requests.get(url, stream=True)
if r.status_code != 200:
day = day - datetime.timedelta(days=1)
Expand All @@ -134,7 +138,7 @@ def update_bundle(data_bundle_path=None, confirm=True):
out = open(tmp, 'wb')
total_length = int(r.headers.get('content-length'))

with click.progressbar(length=total_length, label='downloading ...') as bar:
with click.progressbar(length=total_length, label=_('downloading ...')) as bar:
for data in r.iter_content(chunk_size=8192):
bar.update(len(data))
out.write(data)
Expand All @@ -148,6 +152,7 @@ def update_bundle(data_bundle_path=None, confirm=True):
tar.extractall(data_bundle_path)
tar.close()
os.remove(tmp)
six.print_(_("Data bundle download successfully in {bundle_path}").format(bundle_path=data_bundle_path))


def run(config, source_code=None):
Expand Down Expand Up @@ -287,13 +292,13 @@ def run(config, source_code=None):
env.event_bus.publish_event(EVENT.SETTLEMENT)
env.event_bus.publish_event(EVENT.POST_SETTLEMENT)
else:
raise RuntimeError('unknown event from event source: {}'.format(event))
raise RuntimeError(_('unknown event from event source: {}').format(event))

if env.profile_deco:
output_profile_result(env)

mod_handler.tear_down(const.EXIT_CODE.EXIT_SUCCESS)
system_log.debug("strategy run successfully, normal exit")
system_log.debug(_("strategy run successfully, normal exit"))

# FIXME
if 'analyser' in env.mod_dict:
Expand All @@ -302,7 +307,7 @@ def run(config, source_code=None):
if init_succeed and env.config.base.persist and persist_helper:
persist_helper.persist()

user_detail_log.exception("strategy execute exception")
user_detail_log.exception(_("strategy execute exception"))
user_system_log.error(e.error)
mod_handler.tear_down(const.EXIT_CODE.EXIT_USER_ERROR, e)
except Exception as e:
Expand All @@ -315,10 +320,10 @@ def run(config, source_code=None):
user_system_log.error(user_exc.error)
code = const.EXIT_CODE.EXIT_USER_ERROR
if not is_user_exc(exc_val):
system_log.exception("strategy execute exception")
system_log.exception(_("strategy execute exception"))
code = const.EXIT_CODE.EXIT_INTERNAL_ERROR
else:
user_detail_log.exception("strategy execute exception")
user_detail_log.exception(_("strategy execute exception"))

mod_handler.tear_down(code, user_exc)

Expand Down
3 changes: 2 additions & 1 deletion rqalpha/mod/mod_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from collections import OrderedDict

from rqalpha.utils.logger import system_log
from rqalpha.utils.i18n import gettext as _


class ModHandler(object):
Expand All @@ -39,7 +40,7 @@ def set_env(self, environment):

self._mod_list.sort(key=lambda item: item[1].priority)
for mod_name, mod_config in self._mod_list:
system_log.debug('loading mod {}', mod_name)
system_log.debug(_('loading mod {}').format(mod_name))
mod_module = import_module(mod_config.lib)
mod = mod_module.load_mod()
self._mod_dict[mod_name] = mod
Expand Down
6 changes: 1 addition & 5 deletions rqalpha/model/account/stock_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def _handle_split(self, trading_date):
for order_book_id, position in six.iteritems(self.portfolio.positions):
split_df = rqdatac.get_split(order_book_id, start_date="2005-01-01", end_date="2099-01-01")
if split_df is None:
system_log.warn("no split data {}", order_book_id)
system_log.warn(_("no split data {}").foramt(order_book_id))
continue
try:
series = split_df.loc[trading_date]
Expand Down Expand Up @@ -260,10 +260,6 @@ def _handle_dividend_payable(self, trading_date):
dividend_cash = dividend_per_share * dividend_info.quantity
self.portfolio._dividend_receivable -= dividend_cash
self.portfolio._cash += dividend_cash
# user_system_log.info(_("get dividend {dividend} for {order_book_id}").format(
# dividend=dividend_cash,
# order_book_id=order_book_id,
# ))
to_delete_dividend.append(order_book_id)

for order_book_id in to_delete_dividend:
Expand Down
3 changes: 2 additions & 1 deletion rqalpha/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from ..const import EXC_TYPE, INSTRUMENT_TYPE, ACCOUNT_TYPE, UNDERLYING_SYMBOL_PATTERN, NIGHT_TRADING_NS
from ..utils.datetime_func import TimeRange
from ..utils.default_future_info import STOCK_TRADING_PERIOD, TRADING_PERIOD_DICT
from ..utils.i18n import gettext as _


def safe_round(value, ndigits=3):
Expand Down Expand Up @@ -146,7 +147,7 @@ def wrapper(*args, **kwargs):
if not Environment.get_instance().is_strategy_hold:
return func(*args, **kwargs)
else:
system_log.debug("not run {}({}, {}) because strategy is hold", func, args, kwargs)
system_log.debug(_("not run {}({}, {}) because strategy is hold").format(func, args, kwargs))

return wrapper

Expand Down
2 changes: 1 addition & 1 deletion rqalpha/utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ def set_locale(lc):
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
locale.setlocale(locale.LC_CTYPE, "en_US.UTF-8")
os.environ['TZ'] = 'Asia/Shanghai'
localization.set_locale([lc])
except Exception as e:
if os.name != 'nt':
raise
localization.set_locale([lc])


def parse_config(config_args, base_config_path=None, click_type=True, source_code=None):
Expand Down
6 changes: 5 additions & 1 deletion rqalpha/utils/i18n.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,8 @@ def set_locale(self, locales, trans_dir=None):


def gettext(message):
return localization.trans.gettext(message)
trans_txt = localization.trans.gettext(message)
try:
return trans_txt.decode('utf-8')
except AttributeError:
return trans_txt
Binary file modified rqalpha/utils/translations/zh_Hans_CN/LC_MESSAGES/messages.mo
Binary file not shown.
65 changes: 59 additions & 6 deletions rqalpha/utils/translations/zh_Hans_CN/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ msgid ""
msgstr ""
"Project-Id-Version: PROJECT VERSION\n"
"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n"
"POT-Creation-Date: 2017-02-28 11:22+0800\n"
"POT-Creation-Date: 2017-02-28 15:07+0800\n"
"PO-Revision-Date: 2016-10-24 21:20+0800\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language: zh_Hans_CN\n"
Expand Down Expand Up @@ -41,6 +41,46 @@ msgstr "benchmark {benchmark} 在 {start_date} 还未上市。请重新选择起
msgid "benchmark {benchmark} has been de_listed on {end_date}"
msgstr "benchmark {benchmark} 在 {end_date} 已退市。请重新选择结束日期或benchmark。"

#: rqalpha/main.py:124
msgid ""
"\n"
"[WARNING]\n"
"Target bundle path {data_bundle_path} is not empty.\n"
"The content of this folder will be REMOVED before updating.\n"
"Are you sure to continue?\n"
" "
msgstr ""
"\n"
"[WARNING]\n"
"目标数据源路径 {data_bundle_path} 不为空\n"
"更新操作首先会清空该文件件下所有内容\n"
"您确定要继续吗?\n"
" "

#: rqalpha/main.py:132
msgid "try {} ..."
msgstr "尝试 {} ..."

#: rqalpha/main.py:141
msgid "downloading ..."
msgstr "下载中 ..."

#: rqalpha/main.py:155
msgid "Data bundle download successfully in {bundle_path}"
msgstr "数据下载成功: {bundle_path}"

#: rqalpha/main.py:295
msgid "unknown event from event source: {}"
msgstr "从 event source 中获取的无效事件: {}"

#: rqalpha/main.py:301
msgid "strategy run successfully, normal exit"
msgstr "策略运行成功,正常退出"

#: rqalpha/main.py:310 rqalpha/main.py:323 rqalpha/main.py:326
msgid "strategy execute exception"
msgstr "策略运行产生异常"

#: rqalpha/plot.py:116
msgid "Total Returns"
msgstr "回测收益"
Expand Down Expand Up @@ -169,12 +209,16 @@ msgid ""
"instead."
msgstr "[deprecated] before_night_trading 已经不再使用,请使用 before_trading 代替。"

#: rqalpha/core/strategy_context.py:313 rqalpha/core/strategy_context.py:317
#: rqalpha/core/strategy_context.py:321 rqalpha/core/strategy_context.py:325
#: rqalpha/core/strategy_context.py:329
#: rqalpha/core/strategy_context.py:312 rqalpha/core/strategy_context.py:316
#: rqalpha/core/strategy_context.py:320 rqalpha/core/strategy_context.py:324
#: rqalpha/core/strategy_context.py:328
msgid "[deprecated] {} is no longer used."
msgstr "[deprecated] {} 已经不再使用。"

#: rqalpha/mod/mod_handler.py:43
msgid "loading mod {}"
msgstr "载入 Mod {}"

#: rqalpha/mod/risk_manager/frontend_validator.py:51
msgid "Order Rejected: {order_book_id} is not listed!"
msgstr "订单被拒单: {order_book_id} 未上市。"
Expand Down Expand Up @@ -280,6 +324,10 @@ msgstr "无效的 滑点 设置: 其值范围为 [0, 1]"
msgid "{order_book_id} is expired, close all positions by system"
msgstr "{order_book_id} 已退市/交割,系统自动平仓。"

#: rqalpha/model/account/stock_account.py:222
msgid "no split data {}"
msgstr "没有拆股数据 {}"

#: rqalpha/model/account/stock_account.py:231
#: rqalpha/model/account/stock_account.py:240
msgid "split {order_book_id}, {position}"
Expand All @@ -289,6 +337,10 @@ msgstr "拆股 {order_book_id}, {position}"
msgid "split {order_book_id}, {series}"
msgstr "拆股 {order_book_id}, {series}"

#: rqalpha/utils/__init__.py:150
msgid "not run {}({}, {}) because strategy is hold"
msgstr "因为策略上一次运行还没接触,取消执行 {}({}, {})"

#: rqalpha/utils/arg_checker.py:58
msgid ""
"function {}: invalid {} argument, expect a value of type {}, got {} "
Expand Down Expand Up @@ -387,8 +439,9 @@ msgid ""
" "
msgstr ""
"\n"
"您使用的配置文件 {config_file_path} "
"版本过久,可能会导致RQAlpha运行错误。已为您替换为新的配置文件,旧的配置文件备份存储于 {back_config_file_path}"
"您使用的配置文件 {config_file_path} \n"
"版本过久,可能会导致RQAlpha运行错误。\n"
"已为您替换为新的配置文件,旧的配置文件备份存储于 {back_config_file_path}\n"
" "

#: rqalpha/utils/config.py:136
Expand Down

0 comments on commit e82f962

Please sign in to comment.