sizer.py 这个类主要用于设定 sizer 用于计算具体的手数,设计合理的话,有可能可以减轻策略的编写的代码量。文件中代码同样比较少,注释比较简单。
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from .utils.py3 import with_metaclass
from .metabase import MetaParams
# Sizer 类,其他的 sizer 需要继承这个类并且重写 _getsizing 类
class Sizer(with_metaclass(MetaParams, object)):
'''This is the base class for *Sizers*. Any *sizer* should subclass this
and override the ``_getsizing`` method
Member Attribs:
- ``strategy``: will be set by the strategy in which the sizer is working
Gives access to the entire api of the strategy, for example if the
actual data position would be needed in ``_getsizing``::
position = self.strategy.getposition(data)
- ``broker``: will be set by the strategy in which the sizer is working
Gives access to information some complex sizers may need like portfolio
value, ..
# strategy 代表在使用 sizer 的 strategy 策略,可以通过 strategy 调用所有的 strategy 的 api
# broker 代表使用 strategy 所在的 broker,可以用于获取信息进行计算复杂的手数
'''
strategy = None
broker = None
# 获取下单使用的具体的手数
def getsizing(self, data, isbuy):
comminfo = self.broker.getcommissioninfo(data)
return self._getsizing(comminfo, self.broker.getcash(), data, isbuy)
def _getsizing(self, comminfo, cash, data, isbuy):
'''This method has to be overriden by subclasses of Sizer to provide
the sizing functionality
Params:
- ``comminfo``: The CommissionInfo instance that contains
information about the commission for the data and allows
calculation of position value, operation cost, commision for the
operation
- ``cash``: current available cash in the *broker*
- ``data``: target of the operation
- ``isbuy``: will be ``True`` for *buy* operations and ``False``
for *sell* operations
The method has to return the actual size (an int) to be executed. If
``0`` is returned nothing will be executed.
The absolute value of the returned value will be used
# 这个方法在使用的 时候需要被重写,传入四个参数:
# comminfo 代表佣金的实例,可以用于获取佣金等信息
# cash 代表当前可以使用的现金
# data 代表在那个数据上进行交易
# isbuy 代表在 buy 操作的时候是 True,sell 的时候代表是 False
'''
raise NotImplementedError
# 设置策略和 broker
def set(self, strategy, broker):
self.strategy = strategy
self.broker = broker
# SizerBase 类
SizerBase = Sizer # alias for old naming