[Mod] format code with autopep8

This commit is contained in:
vn.py 2019-01-30 13:07:23 +08:00
parent d7c79327dc
commit a302bc93c5
15 changed files with 120 additions and 113 deletions

View File

@ -6,3 +6,6 @@ ignore =
W293 blank line contains whitespace W293 blank line contains whitespace
W291 trailing whitespace W291 trailing whitespace
[pycodestyle]
max_line_length = 79

View File

@ -1,15 +0,0 @@
[style]
based_on_style = google
spaces_before_comment=2, 4
SPLIT_ARGUMENTS_WHEN_COMMA_TERMINATED = true
SPLIT_ALL_COMMA_SEPARATED_VALUES = true
SPLIT_BEFORE_BITWISE_OPERATOR = true
SPLIT_BEFORE_CLOSING_BRACKET = true
SPLIT_BEFORE_DICT_SET_GENERATOR = true
SPLIT_BEFORE_DOT = true
SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN = true
SPLIT_BEFORE_FIRST_ARGUMENT = true
SPLIT_BEFORE_LOGICAL_OPERATOR = true
SPLIT_BEFORE_NAMED_ASSIGNS = true
SPLIT_COMPLEX_COMPREHENSION = true
DEDENT_CLOSING_BRACKETS = true

View File

@ -9,14 +9,15 @@ vnpy 2.0
在提交代码的时候,请遵守以下规则,以提高代码质量: 在提交代码的时候,请遵守以下规则,以提高代码质量:
* 使用[black]格式化你的代码。运行```black .```即可。 * 使用[autopep8]格式化你的代码。运行```autopep8 --in-place --recursive . ```即可。
* 使用[pylint]检查你的代码(主要检查命名规则)确保没有error和warning。在项目根目录下运行```pylint vnpy```即可。 * 使用[pylint]检查你的代码(主要检查命名规则)确保没有error和warning。在项目根目录下运行```pylint vnpy```即可。
* 使用[flake8]检查你的代码确保没有error和warning。在项目根目录下运行```flake8```即可。 * 使用[flake8]检查你的代码确保没有error和warning。在项目根目录下运行```flake8```即可。
[yapf]:https://github.com/google/yapf [autopep8]:https://github.com/hhatto/autopep8
[pylint]:https://github.com/PyCQA/pylint [pylint]:https://github.com/PyCQA/pylint
[flake8]:https://pypi.org/project/flake8/
[提交PR]:https://help.github.com/articles/creating-a-pull-request/ [提交PR]:https://help.github.com/articles/creating-a-pull-request/
[创建 Issue]:http://pylint.pycqa.org/en/latest/tutorial.html

View File

@ -154,9 +154,9 @@ class Method(Function):
"virtual" if self.is_virtual else "", "virtual" if self.is_virtual else "",
"static" if self.is_static else "", "static" if self.is_static else "",
self.parent.name, self.parent.name,
) ) +
+ super().full_signature super().full_signature +
+ (" = 0" if self.is_pure_virtual else "") (" = 0" if self.is_pure_virtual else "")
) )
def __str__(self): def __str__(self):
@ -190,9 +190,9 @@ class CXXParser:
args=self.args, args=self.args,
unsaved_files=self.unsaved_files, unsaved_files=self.unsaved_files,
options=( options=(
TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD |
| TranslationUnit.PARSE_SKIP_FUNCTION_BODIES TranslationUnit.PARSE_SKIP_FUNCTION_BODIES |
| TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION
), ),
) )
result = CXXParseResult() result = CXXParseResult()
@ -205,8 +205,8 @@ class CXXParser:
e = CXXParser._process_enum(c) e = CXXParser._process_enum(c)
result.enums[e.name] = e result.enums[e.name] = e
elif ( elif (
c.kind == CursorKind.CLASS_DECL c.kind == CursorKind.CLASS_DECL or
or c.kind == CursorKind.STRUCT_DECL c.kind == CursorKind.STRUCT_DECL
): ):
class_ = CXXParser._process_class(c) class_ = CXXParser._process_class(c)
cname = class_.name cname = class_.name
@ -222,30 +222,30 @@ class CXXParser:
name, definition = CXXParser._process_macro_definition(c) name, definition = CXXParser._process_macro_definition(c)
result.macros[name] = definition result.macros[name] = definition
elif ( elif (
False False or
or c.kind == CursorKind.ENUM_CONSTANT_DECL c.kind == CursorKind.ENUM_CONSTANT_DECL or
or c.kind == CursorKind.CXX_METHOD c.kind == CursorKind.CXX_METHOD or
or c.kind == CursorKind.CXX_FINAL_ATTR c.kind == CursorKind.CXX_FINAL_ATTR or
or c.kind == CursorKind.DESTRUCTOR c.kind == CursorKind.DESTRUCTOR or
or c.kind == CursorKind.PARM_DECL c.kind == CursorKind.PARM_DECL or
or c.kind == CursorKind.CXX_ACCESS_SPEC_DECL c.kind == CursorKind.CXX_ACCESS_SPEC_DECL or
or c.kind == CursorKind.FIELD_DECL c.kind == CursorKind.FIELD_DECL
): ):
pass pass
elif c.kind == CursorKind.COMPOUND_STMT: elif c.kind == CursorKind.COMPOUND_STMT:
# ignore any body # ignore any body
pass pass
elif ( elif (
CXXParser._is_literal_cursor(c) CXXParser._is_literal_cursor(c) or
or c.kind == CursorKind.MACRO_INSTANTIATION c.kind == CursorKind.MACRO_INSTANTIATION or
or c.kind == CursorKind.INCLUSION_DIRECTIVE c.kind == CursorKind.INCLUSION_DIRECTIVE
): ):
# just not need to process # just not need to process
pass pass
elif ( elif (
c.kind == CursorKind.TYPE_REF c.kind == CursorKind.TYPE_REF or
or c.kind == CursorKind.UNEXPOSED_EXPR c.kind == CursorKind.UNEXPOSED_EXPR or
or c.kind == CursorKind.TRANSLATION_UNIT c.kind == CursorKind.TRANSLATION_UNIT
): ):
# i don't know what those are # i don't know what those are
pass pass

View File

@ -71,7 +71,8 @@ class PreprocessedClass(Class):
default_factory=(lambda: defaultdict(list)) default_factory=(lambda: defaultdict(list))
) )
need_wrap: bool = False # if need_wrap is true, wrap this to dict need_wrap: bool = False # if need_wrap is true, wrap this to dict
is_pure_virtual: bool = False # generator will not assign python constructor for pure virtual # generator will not assign python constructor for pure virtual
is_pure_virtual: bool = False
class PreProcessorResult: class PreProcessorResult:
@ -158,8 +159,8 @@ class PreProcessor:
# array of basic type, such as int[], char[] # array of basic type, such as int[], char[]
if ( if (
is_array_type(basic_combination) is_array_type(basic_combination) and
and array_base(basic_combination) in base_types array_base(basic_combination) in base_types
): ):
return True return True

View File

@ -201,10 +201,10 @@ class BacktestingEngine:
s = ( s = (
DbBarData.select() DbBarData.select()
.where( .where(
(DbBarData.vt_symbol == self.vt_symbol) (DbBarData.vt_symbol == self.vt_symbol) &
& (DbBarData.interval == self.interval) (DbBarData.interval == self.interval) &
& (DbBarData.datetime >= self.start) (DbBarData.datetime >= self.start) &
& (DbBarData.datetime <= self.end) (DbBarData.datetime <= self.end)
) )
.order_by(DbBarData.datetime) .order_by(DbBarData.datetime)
) )
@ -212,9 +212,9 @@ class BacktestingEngine:
s = ( s = (
DbTickData.select() DbTickData.select()
.where( .where(
(DbTickData.vt_symbol == self.vt_symbol) (DbTickData.vt_symbol == self.vt_symbol) &
& (DbTickData.datetime >= self.start) (DbTickData.datetime >= self.start) &
& (DbTickData.datetime <= self.end) (DbTickData.datetime <= self.end)
) )
.order_by(DbTickData.datetime) .order_by(DbTickData.datetime)
) )
@ -307,7 +307,8 @@ class BacktestingEngine:
0 0
) )
df["highlevel"] = ( df["highlevel"] = (
df["balance"].rolling(min_periods=1, window=len(df), center=False).max() df["balance"].rolling(
min_periods=1, window=len(df), center=False).max()
) )
df["drawdown"] = df["balance"] - df["highlevel"] df["drawdown"] = df["balance"] - df["highlevel"]
df["ddpercent"] = df["drawdown"] / df["highlevel"] * 100 df["ddpercent"] = df["drawdown"] / df["highlevel"] * 100
@ -540,15 +541,15 @@ class BacktestingEngine:
# Check whether limit orders can be filled. # Check whether limit orders can be filled.
long_cross = ( long_cross = (
order.direction == Direction.LONG order.direction == Direction.LONG and
and order.price >= long_cross_price order.price >= long_cross_price and
and long_cross_price > 0 long_cross_price > 0
) )
short_cross = ( short_cross = (
order.direction == Direction.SHORT order.direction == Direction.SHORT and
and order.price <= short_cross_price order.price <= short_cross_price and
and short_cross_price > 0 short_cross_price > 0
) )
if not long_cross and not short_cross: if not long_cross and not short_cross:
@ -608,13 +609,13 @@ class BacktestingEngine:
for stop_order in list(self.active_stop_orders.values()): for stop_order in list(self.active_stop_orders.values()):
# Check whether stop order can be triggered. # Check whether stop order can be triggered.
long_cross = ( long_cross = (
stop_order.direction == Direction.LONG stop_order.direction == Direction.LONG and
and stop_order.price <= long_cross_price stop_order.price <= long_cross_price
) )
short_cross = ( short_cross = (
stop_order.direction == Direction.SHORT stop_order.direction == Direction.SHORT and
and stop_order.price >= short_cross_price stop_order.price >= short_cross_price
) )
if not long_cross and not short_cross: if not long_cross and not short_cross:
@ -848,7 +849,8 @@ class DailyResult:
# Holding pnl is the pnl from holding position at day start # Holding pnl is the pnl from holding position at day start
self.start_pos = start_pos self.start_pos = start_pos
self.end_pos = start_pos self.end_pos = start_pos
self.holding_pnl = self.start_pos * (self.close_price - self.pre_close) * size self.holding_pnl = self.start_pos * \
(self.close_price - self.pre_close) * size
# Trading pnl is the pnl from new trade during the day # Trading pnl is the pnl from new trade during the day
self.trade_count = len(self.trades) self.trade_count = len(self.trades)
@ -861,7 +863,8 @@ class DailyResult:
turnover = trade.price * trade.volume * size turnover = trade.price * trade.volume * size
self.trading_pnl += pos_change * (self.close_price - trade.price) * size self.trading_pnl += pos_change * \
(self.close_price - trade.price) * size
self.end_pos += pos_change self.end_pos += pos_change
self.turnover += turnover self.turnover += turnover
self.commission += turnover * rate self.commission += turnover * rate

View File

@ -68,8 +68,6 @@ class CtaManager(QtWidgets.QWidget):
scroll_area.setWidgetResizable(True) scroll_area.setWidgetResizable(True)
scroll_area.setWidget(scroll_widget) scroll_area.setWidget(scroll_widget)
# bottom_height = 300
self.log_monitor = LogMonitor(self.main_engine, self.event_engine) self.log_monitor = LogMonitor(self.main_engine, self.event_engine)
self.stop_order_monitor = StopOrderMonitor( self.stop_order_monitor = StopOrderMonitor(

View File

@ -86,7 +86,8 @@ class BitmexGateway(BaseGateway):
proxy_host = setting["proxy_host"] proxy_host = setting["proxy_host"]
proxy_port = setting["proxy_port"] proxy_port = setting["proxy_port"]
self.rest_api.connect(key, secret, session, server, proxy_host, proxy_port) self.rest_api.connect(key, secret, session,
server, proxy_host, proxy_port)
self.ws_api.connect(key, secret, server, proxy_host, proxy_port) self.ws_api.connect(key, secret, server, proxy_host, proxy_port)
@ -407,7 +408,8 @@ class BitmexWebsocketApi(WebsocketClient):
msg = f"触发异常,状态码:{exception_type},信息:{exception_value}" msg = f"触发异常,状态码:{exception_type},信息:{exception_value}"
self.gateway.write_log(msg) self.gateway.write_log(msg)
sys.stderr.write(self.exception_detail(exception_type, exception_value, tb)) sys.stderr.write(self.exception_detail(
exception_type, exception_value, tb))
def authenticate(self): def authenticate(self):
""" """
@ -450,7 +452,8 @@ class BitmexWebsocketApi(WebsocketClient):
return return
tick.last_price = d["price"] tick.last_price = d["price"]
tick.datetime = datetime.strptime(d["timestamp"], "%Y-%m-%dT%H:%M:%S.%fZ") tick.datetime = datetime.strptime(
d["timestamp"], "%Y-%m-%dT%H:%M:%S.%fZ")
self.gateway.on_tick(copy(tick)) self.gateway.on_tick(copy(tick))
def on_depth(self, d): def on_depth(self, d):
@ -470,7 +473,8 @@ class BitmexWebsocketApi(WebsocketClient):
tick.__setattr__("ask_price_%s" % (n + 1), price) tick.__setattr__("ask_price_%s" % (n + 1), price)
tick.__setattr__("ask_volume_%s" % (n + 1), volume) tick.__setattr__("ask_volume_%s" % (n + 1), volume)
tick.datetime = datetime.strptime(d["timestamp"], "%Y-%m-%dT%H:%M:%S.%fZ") tick.datetime = datetime.strptime(
d["timestamp"], "%Y-%m-%dT%H:%M:%S.%fZ")
self.gateway.on_tick(copy(tick)) self.gateway.on_tick(copy(tick))
def on_trade(self, d): def on_trade(self, d):
@ -552,7 +556,8 @@ class BitmexWebsocketApi(WebsocketClient):
accountid = str(d["account"]) accountid = str(d["account"])
account = self.accounts.get(accountid, None) account = self.accounts.get(accountid, None)
if not account: if not account:
account = AccountData(accountid=accountid, gateway_name=self.gateway_name) account = AccountData(accountid=accountid,
gateway_name=self.gateway_name)
self.accounts[accountid] = account self.accounts[accountid] = account
account.balance = d.get("marginBalance", account.balance) account.balance = d.get("marginBalance", account.balance)

View File

@ -322,7 +322,8 @@ class FutuGateway(BaseGateway):
account = AccountData( account = AccountData(
accountid=f"{self.gateway_name}_{self.market}", accountid=f"{self.gateway_name}_{self.market}",
balance=float(row["total_assets"]), balance=float(row["total_assets"]),
frozen=(float(row["total_assets"]) - float(row["avl_withdrawal_cash"])), frozen=(float(row["total_assets"]) -
float(row["avl_withdrawal_cash"])),
gateway_name=self.gateway_name, gateway_name=self.gateway_name,
) )
self.on_account(account) self.on_account(account)
@ -412,7 +413,8 @@ class FutuGateway(BaseGateway):
date = row["data_date"].replace("-", "") date = row["data_date"].replace("-", "")
time = row["data_time"] time = row["data_time"]
tick.datetime = datetime.strptime(f"{date} {time}", "%Y%m%d %H:%M:%S") tick.datetime = datetime.strptime(
f"{date} {time}", "%Y%m%d %H:%M:%S")
tick.open_price = row["open_price"] tick.open_price = row["open_price"]
tick.high_price = row["high_price"] tick.high_price = row["high_price"]
tick.low_price = row["low_price"] tick.low_price = row["low_price"]

View File

@ -9,7 +9,6 @@ class Direction(Enum):
""" """
Direction of order/trade/position. Direction of order/trade/position.
""" """
LONG = "" LONG = ""
SHORT = "" SHORT = ""
NET = "" NET = ""
@ -19,7 +18,6 @@ class Offset(Enum):
""" """
Offset of order/trade. Offset of order/trade.
""" """
NONE = "" NONE = ""
OPEN = "" OPEN = ""
CLOSE = "" CLOSE = ""
@ -31,7 +29,6 @@ class Status(Enum):
""" """
Order status. Order status.
""" """
SUBMITTING = "提交中" SUBMITTING = "提交中"
NOTTRADED = "未成交" NOTTRADED = "未成交"
PARTTRADED = "部分成交" PARTTRADED = "部分成交"
@ -44,7 +41,6 @@ class Product(Enum):
""" """
Product class. Product class.
""" """
EQUITY = "股票" EQUITY = "股票"
FUTURES = "期货" FUTURES = "期货"
OPTION = "期权" OPTION = "期权"
@ -60,7 +56,6 @@ class PriceType(Enum):
""" """
Order price type. Order price type.
""" """
LIMIT = "限价" LIMIT = "限价"
MARKET = "市价" MARKET = "市价"
FAK = "FAK" FAK = "FAK"
@ -71,7 +66,6 @@ class OptionType(Enum):
""" """
Option type. Option type.
""" """
CALL = "看涨期权" CALL = "看涨期权"
PUT = "看跌期权" PUT = "看跌期权"
@ -80,7 +74,6 @@ class Exchange(Enum):
""" """
Exchange. Exchange.
""" """
# Chinese # Chinese
CFFEX = "CFFEX" CFFEX = "CFFEX"
SHFE = "SHFE" SHFE = "SHFE"
@ -109,13 +102,15 @@ class Currency(Enum):
""" """
Currency. Currency.
""" """
USD = "USD" USD = "USD"
HKD = "HKD" HKD = "HKD"
CNY = "CNY" CNY = "CNY"
class Interval(Enum): class Interval(Enum):
"""
Interval of bar data.
"""
MINUTE = "1m" MINUTE = "1m"
HOUR = "1h" HOUR = "1h"
DAILY = "d" DAILY = "d"

View File

@ -304,7 +304,8 @@ class BaseMonitor(QtWidgets.QTableWidget):
""" """
Save table data into a csv file Save table data into a csv file
""" """
path, _ = QtWidgets.QFileDialog.getSaveFileName(self, "保存数据", "", "CSV(*.csv)") path, _ = QtWidgets.QFileDialog.getSaveFileName(
self, "保存数据", "", "CSV(*.csv)")
if not path: if not path:
return return
@ -499,7 +500,8 @@ class ConnectDialog(QtWidgets.QDialog):
self.setWindowTitle(f"连接{self.gateway_name}") self.setWindowTitle(f"连接{self.gateway_name}")
# Default setting provides field name, field data type and field default value. # Default setting provides field name, field data type and field default value.
default_setting = self.main_engine.get_default_setting(self.gateway_name) default_setting = self.main_engine.get_default_setting(
self.gateway_name)
# Saved setting provides field data used last time. # Saved setting provides field data used last time.
loaded_setting = load_setting(self.filename) loaded_setting = load_setting(self.filename)
@ -588,13 +590,15 @@ class TradingWidget(QtWidgets.QWidget):
self.name_line.setReadOnly(True) self.name_line.setReadOnly(True)
self.direction_combo = QtWidgets.QComboBox() self.direction_combo = QtWidgets.QComboBox()
self.direction_combo.addItems([Direction.LONG.value, Direction.SHORT.value]) self.direction_combo.addItems(
[Direction.LONG.value, Direction.SHORT.value])
self.offset_combo = QtWidgets.QComboBox() self.offset_combo = QtWidgets.QComboBox()
self.offset_combo.addItems([offset.value for offset in Offset]) self.offset_combo.addItems([offset.value for offset in Offset])
self.price_type_combo = QtWidgets.QComboBox() self.price_type_combo = QtWidgets.QComboBox()
self.price_type_combo.addItems([price_type.value for price_type in PriceType]) self.price_type_combo.addItems(
[price_type.value for price_type in PriceType])
double_validator = QtGui.QDoubleValidator() double_validator = QtGui.QDoubleValidator()
double_validator.setBottom(0) double_validator.setBottom(0)
@ -637,11 +641,16 @@ class TradingWidget(QtWidgets.QWidget):
self.bp4_label = self.create_label(bid_color) self.bp4_label = self.create_label(bid_color)
self.bp5_label = self.create_label(bid_color) self.bp5_label = self.create_label(bid_color)
self.bv1_label = self.create_label(bid_color, alignment=QtCore.Qt.AlignRight) self.bv1_label = self.create_label(
self.bv2_label = self.create_label(bid_color, alignment=QtCore.Qt.AlignRight) bid_color, alignment=QtCore.Qt.AlignRight)
self.bv3_label = self.create_label(bid_color, alignment=QtCore.Qt.AlignRight) self.bv2_label = self.create_label(
self.bv4_label = self.create_label(bid_color, alignment=QtCore.Qt.AlignRight) bid_color, alignment=QtCore.Qt.AlignRight)
self.bv5_label = self.create_label(bid_color, alignment=QtCore.Qt.AlignRight) self.bv3_label = self.create_label(
bid_color, alignment=QtCore.Qt.AlignRight)
self.bv4_label = self.create_label(
bid_color, alignment=QtCore.Qt.AlignRight)
self.bv5_label = self.create_label(
bid_color, alignment=QtCore.Qt.AlignRight)
self.ap1_label = self.create_label(ask_color) self.ap1_label = self.create_label(ask_color)
self.ap2_label = self.create_label(ask_color) self.ap2_label = self.create_label(ask_color)
@ -649,11 +658,16 @@ class TradingWidget(QtWidgets.QWidget):
self.ap4_label = self.create_label(ask_color) self.ap4_label = self.create_label(ask_color)
self.ap5_label = self.create_label(ask_color) self.ap5_label = self.create_label(ask_color)
self.av1_label = self.create_label(ask_color, alignment=QtCore.Qt.AlignRight) self.av1_label = self.create_label(
self.av2_label = self.create_label(ask_color, alignment=QtCore.Qt.AlignRight) ask_color, alignment=QtCore.Qt.AlignRight)
self.av3_label = self.create_label(ask_color, alignment=QtCore.Qt.AlignRight) self.av2_label = self.create_label(
self.av4_label = self.create_label(ask_color, alignment=QtCore.Qt.AlignRight) ask_color, alignment=QtCore.Qt.AlignRight)
self.av5_label = self.create_label(ask_color, alignment=QtCore.Qt.AlignRight) self.av3_label = self.create_label(
ask_color, alignment=QtCore.Qt.AlignRight)
self.av4_label = self.create_label(
ask_color, alignment=QtCore.Qt.AlignRight)
self.av5_label = self.create_label(
ask_color, alignment=QtCore.Qt.AlignRight)
self.lp_label = self.create_label() self.lp_label = self.create_label()
self.return_label = self.create_label(alignment=QtCore.Qt.AlignRight) self.return_label = self.create_label(alignment=QtCore.Qt.AlignRight)