From 509c785451387e02f504dc59c2578e665e5ebdac Mon Sep 17 00:00:00 2001 From: fasiondog Date: Wed, 4 Oct 2017 00:34:24 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E5=B8=AE=E5=8A=A9=E4=BF=A1?= =?UTF-8?q?=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/hikyuu/doc.h | 8 +- libs/hikyuu/trade_manage/Performance.h | 22 +- .../trade_manage/_Performance.cpp | 6 +- .../trade_manage/_TradeManager.cpp | 28 +- .../trade_sys/trade_sys_main.cpp | 1 + tools/hikyuu/trade_manage/trade.py | 49 --- tools/hikyuu/trade_manage/trade_doc.py | 331 ++++++++++++++++++ tools/hikyuu/trade_sys/__init__.py | 26 +- tools/hikyuu/trade_sys/condition.py | 187 +++++++++- tools/hikyuu/trade_sys/environment.py | 151 +++++++- tools/hikyuu/trade_sys/moneymanager.py | 256 +++++++++++++- tools/hikyuu/trade_sys/profitgoal.py | 30 +- tools/hikyuu/trade_sys/signal.py | 287 +++++++++++++-- tools/hikyuu/trade_sys/slippage.py | 30 +- tools/hikyuu/trade_sys/stoploss.py | 105 +++++- tools/hikyuu/trade_sys/system.py | 26 +- 16 files changed, 1382 insertions(+), 161 deletions(-) diff --git a/libs/hikyuu/doc.h b/libs/hikyuu/doc.h index 7d6b994b..85667867 100644 --- a/libs/hikyuu/doc.h +++ b/libs/hikyuu/doc.h @@ -60,8 +60,12 @@ * 交易管理可理解为一个模拟账户进行模拟交易。一般使用 crtTM 创建交易管理实例。 * @ingroup TradeManager * - * @defgroup OrderBroker TradeManager 订单代理类 - * 订单代理类,实现实际的订单操作及程序化的订单 + * @defgroup OrderBroker OrderBroker 订单代理 + * 订单代理,实现实际的订单操作及程序化的订单 + * @ingroup TradeManager + * + * @defgroup Performance Performance 绩效统计 + * 对交易进行绩效统计 * @ingroup TradeManager * * @defgroup TradeSystem TradeSystem 系统交易框架 diff --git a/libs/hikyuu/trade_manage/Performance.h b/libs/hikyuu/trade_manage/Performance.h index fd0ff901..19c078df 100644 --- a/libs/hikyuu/trade_manage/Performance.h +++ b/libs/hikyuu/trade_manage/Performance.h @@ -13,27 +13,41 @@ namespace hku { -/* +/** * 简单绩效统计 + * @ingroup Performance */ class HKU_API Performance { public: Performance(); virtual ~Performance(); + /** 复位,清除已计算的结果 */ void reset(); + /** 按指标名称获取指标值,必须在运行 statistics 或 report 之后生效 */ double get(const string& name) const; + + /** 同 get */ double operator[](const string& name) const { return get(name); } + /** + * 简单的文本统计报告,用于直接输出打印 + * @param tm + * @param datetime 指定的截止时刻 + * @return + */ string report(const TradeManagerPtr& tm, const Datetime& datetime = Datetime::now()); - /* - * 根据交易记录,统计截至某一日期的系统绩效, datetime必须大于等于lastDatetime, + /** + * 根据交易记录,统计截至某一时刻的系统绩效, datetime必须大于等于lastDatetime, * 以便用于计算当前市值 + * @param tm 指定的交易管理实例 + * @param datetime 统计截止时刻 */ - void statistics(const TradeManagerPtr& tm, const Datetime& datetime); + void statistics(const TradeManagerPtr& tm, + const Datetime& datetime = Datetime::now()); typedef map map_type; diff --git a/libs/hikyuu_python/trade_manage/_Performance.cpp b/libs/hikyuu_python/trade_manage/_Performance.cpp index e02e73a7..95e76e39 100644 --- a/libs/hikyuu_python/trade_manage/_Performance.cpp +++ b/libs/hikyuu_python/trade_manage/_Performance.cpp @@ -14,8 +14,10 @@ using namespace hku; void export_Performance() { class_("Performance", init<>()) .def("reset", &Performance::reset) - .def("report", &Performance::report) - .def("statistics", &Performance::statistics) + .def("report", &Performance::report, + (arg("tm"), arg("datetime")=Datetime::now())) + .def("statistics", &Performance::statistics, + (arg("tm"), arg("datetime")=Datetime::now())) .def("get", &Performance::get) .def("__getitem__", &Performance::get) ; diff --git a/libs/hikyuu_python/trade_manage/_TradeManager.cpp b/libs/hikyuu_python/trade_manage/_TradeManager.cpp index 9b9c0543..62971453 100644 --- a/libs/hikyuu_python/trade_manage/_TradeManager.cpp +++ b/libs/hikyuu_python/trade_manage/_TradeManager.cpp @@ -89,12 +89,12 @@ void export_TradeManager() { .def("regBroker", &TradeManager::regBroker) .def("clearBroker", &TradeManager::clearBroker) - .def("getMarginRate", &TradeManager::getMarginRate) + //.def("getMarginRate", &TradeManager::getMarginRate) .def("have", &TradeManager::have) .def("getStockNumber", &TradeManager::getStockNumber) - .def("getShortStockNumber", &TradeManager::getShortStockNumber) + //.def("getShortStockNumber", &TradeManager::getShortStockNumber) .def("getHoldNumber", &TradeManager::getHoldNumber) - .def("getShortHoldNumber", &TradeManager::getShortHoldNumber) + //.def("getShortHoldNumber", &TradeManager::getShortHoldNumber) .def("getTradeList", &TradeManager::getTradeList, return_value_policy()) .def("getPositionList", &TradeManager::getPositionList) @@ -104,9 +104,9 @@ void export_TradeManager() { .def("getBuyCost", &TradeManager::getBuyCost) .def("getSellCost", &TradeManager::getSellCost) //.def("getBorrowCashCost", &TradeManager::getBorrowCashCost) - .def("getReturnCashCost", &TradeManager::getReturnCashCost) - .def("getBorrowStockCost", &TradeManager::getBorrowStockCost) - .def("getReturnStockCost", &TradeManager::getReturnStockCost) + //.def("getReturnCashCost", &TradeManager::getReturnCashCost) + //.def("getBorrowStockCost", &TradeManager::getBorrowStockCost) + //.def("getReturnStockCost", &TradeManager::getReturnStockCost) .def("cash", &TradeManager::cash, cash_overload()) .def("getFunds", getFunds_1, getFunds_1_overload()) .def("getFunds", getFunds_2, getFunds_2_overload()) @@ -117,12 +117,12 @@ void export_TradeManager() { .def("checkin", &TradeManager::checkin) .def("checkout", &TradeManager::checkout) - .def("checkinStock", &TradeManager::checkinStock) - .def("checkoutStock", &TradeManager::checkoutStock) - .def("borrowCash", &TradeManager::borrowCash) - .def("returnCash", &TradeManager::returnCash) - .def("borrowStock", &TradeManager::borrowStock) - .def("returnStock", &TradeManager::returnStock) + //.def("checkinStock", &TradeManager::checkinStock) + //.def("checkoutStock", &TradeManager::checkoutStock) + //.def("borrowCash", &TradeManager::borrowCash) + //.def("returnCash", &TradeManager::returnCash) + //.def("borrowStock", &TradeManager::borrowStock) + //.def("returnStock", &TradeManager::returnStock) //.def("buy", &TradeManager::buy, buy_overload()) .def("buy", &TradeManager::buy, buy_overload(args("datetime", "stock", "realPrice", @@ -131,8 +131,8 @@ void export_TradeManager() { .def("sell", &TradeManager::sell, sell_overload(args("datetime", "stock", "realPrice", "num", "stoploss", "goalPrice", "planPrice", "part"))) - .def("buyShort", &TradeManager::buyShort, buyShort_overload()) - .def("sellShort", &TradeManager::sellShort, sellShort_overload()) + //.def("buyShort", &TradeManager::buyShort, buyShort_overload()) + //.def("sellShort", &TradeManager::sellShort, sellShort_overload()) .def("tocsv", &TradeManager::tocsv) diff --git a/libs/hikyuu_python/trade_sys/trade_sys_main.cpp b/libs/hikyuu_python/trade_sys/trade_sys_main.cpp index 2290f21a..9c3fce87 100644 --- a/libs/hikyuu_python/trade_sys/trade_sys_main.cpp +++ b/libs/hikyuu_python/trade_sys/trade_sys_main.cpp @@ -21,6 +21,7 @@ void export_Selector(); void export_AllocateMoney(); BOOST_PYTHON_MODULE(_trade_sys) { + docstring_options doc_options(false); export_Environment(); export_Condition(); export_MoneyManager(); diff --git a/tools/hikyuu/trade_manage/trade.py b/tools/hikyuu/trade_manage/trade.py index bb64802b..a90acd90 100644 --- a/tools/hikyuu/trade_manage/trade.py +++ b/tools/hikyuu/trade_manage/trade.py @@ -128,52 +128,3 @@ try: except: pass - -TC_FixedA.__doc__ = """ - 2015年8月1日之前沪深A股交易成本算法,计算每次买入或卖出的成本 - 计算规则为: - 1)上证交易所 - 买入:佣金+过户费 - 卖出:佣金+过户费+印花税 - 2)深证交易所: - 买入:佣金 - 卖出:佣金+印花税 - 佣金和过户费均有最低值,当前佣金比例为千分之1.8(最低5元),印花税为千分之一 - 上证过户费为交易数量的千分之一,不足1元,按一元计 - 参数: - commission 佣金比例,默认千分之1.8,即0.0018 - lowest_commission 最低佣金值,默认5元 - stamptax 印花税,默认千分之一,即0.001 - transferfee 过户费,默认每股千分之一,即0.001 - lowest_transferfee 最低过户费,默认1元 - """ - - -TC_FixedA2015.__doc__ = """ - 2015年8月1日及之后沪深A股交易成本算法,计算每次买入或卖出的成本 - 计算规则为: - 1)上证交易所 - 买入:佣金+过户费 - 卖出:佣金+过户费+印花税 - 2)深证交易所: - 买入:佣金 - 卖出:佣金+印花税 - 佣金最低5元 - 上证过户费为交易金额的千分之0.02 - 参数: - commission 佣金比例,默认千分之1.8,即0.0018 - lowest_commission 最低佣金值,默认5元 - stamptax 印花税,默认千分之一,即0.001 - transferfee 过户费,默认每股千分之一,即0.001 - """ - - -crtTM.__doc__ = """ - 创建交易管理模块,管理帐户的交易记录及资金使用情况 - 考虑的移滑价差需要使用当日的最高或最低价,所以不在该模块内进行处理 - 参数: - datetime 账户建立日期, 默认1990-1-1 - initCash 初始现金,默认100000 - costFunc 交易成本算法,默认零成本算法TC_Zero() - name 账户名称,默认“SYS” - """ \ No newline at end of file diff --git a/tools/hikyuu/trade_manage/trade_doc.py b/tools/hikyuu/trade_manage/trade_doc.py index 76a871ac..6084fce2 100644 --- a/tools/hikyuu/trade_manage/trade_doc.py +++ b/tools/hikyuu/trade_manage/trade_doc.py @@ -305,4 +305,335 @@ clone(self) :rtype: TradeManager """ +TradeManager.regBroker.__doc__ = """ +regBroker(self, broker) + + 注册订单代理。可执行多次该命令注册多个订单代理。 + + :param OrderBrokerBase broker: 订单代理实例 +""" +TradeManager.clearBroker.__doc__ = """ +clearBroker(self) + + 清空所有已注册订单代理 +""" + +TradeManager.have.__doc__ = """ +have(self, stock) + + 当前是否持有指定的证券 + + :param Stock stock: 指定证券 + :rtype: bool +""" + +TradeManager.getStockNumber.__doc__ = """ +getStockNumber(self) + + 当前持有的证券种类数量,即当前持有几只股票(非各个股票的持仓数) + + :rtype: int +""" + +TradeManager.getHoldNumber.__doc__ = """ +getHoldNumber(self, datetime, stock) + + 获取指定时刻指定证券的持有数量 + + :param Datetime datetime: 指定时刻 + :param Stock stock: 指定的证券 + :rtype: int +""" + +TradeManager.getTradeList.__doc__ = """ +getTradeList(self) + + 获取全部交易记录 + + :rtype: TradeRecordList +""" + +TradeManager.getPositionList.__doc__ = """ +getPositionList(self) + + 获取当前全部持仓记录 + + :rtype: PositionRecordList +""" + +TradeManager.getHistoryPositionList.__doc__ = """ +getHistoryPositionList(self) + + 获取全部历史持仓记录,即已平仓记录 + + :rtype: PositionRecordList +""" + +TradeManager.getPosition.__doc__ = """ +getPosition(self, stock) + + 获取指定证券的当前持仓记录,如当前未持有该票,返回PositionRecord() + + :param Stock stock: 指定的证券 + :rtype: PositionRecord +""" + +TradeManager.getBuyCost.__doc__ = """ +getBuyCost(self, datetime, stock, price, num) + + 计算买入成本 + + :param Datetime datetime: 交易时间 + :param Stock stock: 交易的证券 + :param float price: 买入价格 + :param int num: 买入数量 + :rtype: CostRecord +""" + +TradeManager.getSellCost.__doc__ = """ +getSellCost(self, datetime, stock, price, num) + + 计算卖出成本 + + :param Datetime datetime: 交易时间 + :param Stock stock: 交易的证券 + :param float price: 卖出价格 + :param int num: 卖出数量 + :rtype: CostRecord +""" + +TradeManager.cash.__doc__ = """ +cash(self, datetime[, ktype=KQuery.KType.DAY]) + + 获取指定日期的现金。(注:如果不带日期参数,无法根据权息信息调整持仓。) + + :param Datetime datetime: 指定时刻 + :param ktype: K线类型 + :rtype: float +""" + +TradeManager.getFunds.__doc__ = """ +getFunds(self[,ktype = KQuery.DAY]) + + 获取账户当前时刻的资产详情 + + :param KQuery.KType ktype: K线类型 + :rtype: FundsRecord + +getFunds(self, datetime, [ktype = KQuery.DAY]) + + 获取指定时刻的资产市值详情 + + :param Datetime datetime: 指定时刻 + :param KQuery.KType ktype: K线类型 + :rtype: FundsRecord +""" + +TradeManager.getFundsCurve.__doc__ = """ +getFundsCurve(self, dates[, ktype = KQuery.DAY]) + + 获取资产净值曲线 + + :param DatetimeList dates: 日期列表,根据该日期列表获取其对应的资产净值曲线 + :param KQuery.KType ktype: K线类型,必须与日期列表匹配 + :return: 资产净值列表 + :rtype: PriceList +""" + +TradeManager.getProfitCurve.__doc__ = """ +getProfitCurve(self, dates[, ktype = KQuery.DAY]) + + 获取收益曲线,即扣除历次存入资金后的资产净值曲线 + + :param DatetimeList dates: 日期列表,根据该日期列表获取其对应的收益曲线,应为递增顺序 + :param KQuery.KType ktype: K线类型,必须与日期列表匹配 + :return: 收益曲线 + :rtype: PriceList +""" + +TradeManager.checkin.__doc__ = """ +checkin(self, datetime, cash) + + 向账户内存入现金 + + :param Datetime datetime: 交易时间 + :param float cash: 存入的现金量 + :rtype: TradeRecord +""" + +TradeManager.checkout.__doc__ = """ +checkout(self, datetime, cash) + + 从账户内取出现金 + + :param Datetime datetime: 交易时间 + :param float cash: 取出的资金量 + :rtype: TradeRecord +""" + +TradeManager.buy.__doc__ = """ +buy(self, datetime, stock, realPrice, number[, stoploss=0.0, goalPrice=0.0, planPrice=0.0, part=System.INVALID]) + + 买入操作 + + :param Datetime datetime: 买入时间 + :param Stock stock: 买入的证券 + :param float realPrice: 实际买入价格 + :param int num: 买入数量 + :param float stoploss: 止损价 + :param float goalPrice: 目标价格 + :param float planPrice: 计划买入价格 + :param SystemPart part: 交易指示来源 + :rtype: TradeRecord +""" + +TradeManager.sell.__doc__ = """ +sell(self, datetime, stock, realPrice[, number=Constant.null_size, stoploss=0.0, goalPrice=0.0, planPrice=0.0, part=System.INVALID]) + + 卖出操作 + + :param Datetime datetime: 卖出时间 + :param Stock stock: 卖出的证券 + :param float realPrice: 实际卖出价格 + :param int num: 卖出数量,如果等于Constant.null_size,表示全部卖出 + :param float stoploss: 新的止损价 + :param float goalPrice: 新的目标价格 + :param float planPrice: 原计划卖出价格 + :param SystemPart part: 交易指示来源 + :rtype: TradeRecord +""" + +TradeManager.tocsv.__doc__ = """ +tocsv(self, path) + + 以csv格式输出交易记录、未平仓记录、已平仓记录、资产净值曲线 + + :param string path: 输出文件所在目录 +""" + + +#------------------------------------------------------------------ +# Performance +#------------------------------------------------------------------ + +Performance.__doc__ = """简单绩效统计""" + +Performance.reset.__doc__ = """ +reset(self) + + 复位,清除已计算的结果 +""" + +Performance.report.__doc__ = """ +report(self, tm[, datetime=Datetime.now()]) + + 简单的文本统计报告,用于直接输出打印 + + :param TradeManager tm: 指定的交易管理实例 + :param Datetime datetime: 统计截止时刻 + :rtype: str +""" + +Performance.statistics.__doc__ = """ +statistics(self, tm[, datetime=Datetime.now()]) + + 根据交易记录,统计截至某一时刻的系统绩效, datetime必须大于等于lastDatetime + + :param TradeManager tm: 指定的交易管理实例 + :param Datetime datetime: 统计截止时刻 +""" + +Performance.get.__doc__ = """ +get(self, name) + + 按指标名称获取指标值,必须在运行 statistics 或 report 之后生效 + + :param str name: 指标名称 + :rtype: float +""" + +Performance.__getitem__.__doc__ = """ +__getitem__(self, name) + + 同 get 方法。按指标名称获取指标值,必须在运行 statistics 或 report 之后生效 + + :param str name: 指标名称 + :rtype: float +""" + + +#------------------------------------------------------------------ +# build_in +#------------------------------------------------------------------ + +crtTM.__doc__ = """ +crtTM([datetime = Datetime(199001010000), initcash = 100000, costfunc = TC_Zero(), name = "SYS"]) + + 创建交易管理模块,管理帐户的交易记录及资金使用情况 + + :param Datetime datetime: 账户建立日期 + :param float initcash: 初始资金 + :param TradeCost costfunc: 交易成本算法 + :param string name: 账户名称 + :rtype: TradeManager +""" + +TC_TestStub.__doc__ = """ +""" + +TC_FixedA.__doc__ = """ +TC_FixedA([commission=0.0018, lowestCommission=5.0, stamptax=0.001, transferfee=0.001, lowestTransferfee=1.0]) + + 2015年8月1日之前的A股交易成本算法。上证过户费为交易数量的千分之一,不足1元,按1元计。 + + 计算规则如下:: + + 1)上证交易所 + 买入:佣金+过户费 + 卖出:佣金+过户费+印花税 + 2)深证交易所: + 买入:佣金 + 卖出:佣金+印花税 + + 其中,佣金最低5元 + + :param float commission: 佣金比例 + :param float lowestCommission: 最低佣金值 + :param float stamptax: 印花税 + :param float transferfee: 过户费 + :param float lowestTransferfee: 最低过户费 + :return: :py:class:`TradeCostBase` 子类实例 +""" + + +TC_FixedA2015.__doc__ = """ +TC_FixedA2015([commission=0.0018, lowestCommission=5.0, stamptax=0.001, transferfee=0.00002]) + + 2015年8月1日及之后的A股交易成本算法,上证过户费改为成交金额的千分之0.02 + + 计算规则如下:: + + 1)上证交易所 + 买入:佣金+过户费 + 卖出:佣金+过户费+印花税 + 2)深证交易所: + 买入:佣金 + 卖出:佣金+印花税 + + 其中,佣金最低5元 + + :param float commission: 佣金比例 + :param float lowestCommission: 最低佣金值 + :param float stamptax: 印花税 + :param float transferfee: 过户费 + :return: :py:class:`TradeCostBase` 子类实例 +""" + +TC_Zero.__doc__ = """ +TC_Zero() + + 创建零成本算法实例 +""" + +TC_TestStub.__doc__ = """仅用于测试""" diff --git a/tools/hikyuu/trade_sys/__init__.py b/tools/hikyuu/trade_sys/__init__.py index b1b10946..6e1d76d8 100644 --- a/tools/hikyuu/trade_sys/__init__.py +++ b/tools/hikyuu/trade_sys/__init__.py @@ -1,11 +1,29 @@ #!/usr/bin/python # -*- coding: utf8 -*- # cp936 +# +# The MIT License (MIT) +# +# Copyright (c) 2010-2017 fasiondog +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. -#=============================================================================== -# 作者:fasiondog -# 历史:1)20130213, Added by fasiondog -#=============================================================================== __all__ = ['system', 'environment', 'condition', 'moneymanager', 'signal', 'stoploss', 'profitgoal', 'slippage'] diff --git a/tools/hikyuu/trade_sys/condition.py b/tools/hikyuu/trade_sys/condition.py index 76b76d6c..be6b9e83 100644 --- a/tools/hikyuu/trade_sys/condition.py +++ b/tools/hikyuu/trade_sys/condition.py @@ -1,27 +1,36 @@ #!/usr/bin/python # -*- coding: utf8 -*- # cp936 +# +# The MIT License (MIT) +# +# Copyright (c) 2010-2017 fasiondog +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. -#=============================================================================== -# 作者:fasiondog -# 历史:1)20130419, Added by fasiondog -#=============================================================================== -from . import _trade_sys as csys +from ._trade_sys import ConditionBase, CN_OPLine from hikyuu.util.unicode import (unicodeFunc, reprFunc) -ConditionBase = csys.ConditionBase ConditionBase.__unicode__ = unicodeFunc ConditionBase.__repr__ = reprFunc -CN_OPLine = csys.CN_OPLine - -CN_OPLine.__doc__ += """\n - 固定使用股票最小交易量进行交易,计算权益曲线的op值,当权益曲线高于op时,系统有效,否则无效。 - - :param Operand op: Operand实例 - :return: 系统有效条件实例 -""" def cn_init(self, name, params): super(self.__class__, self).__init__(name) @@ -45,3 +54,153 @@ def crtCN(func, params={}, name='crtCN'): return meta_x(name, params) +#------------------------------------------------------------------ +# add doc-string +#------------------------------------------------------------------ + +ConditionBase.__doc__ = """ +系统有效条件基类 + +自定义系统有效条件接口: + + ConditionBase._calculate() - 【必须】子类计算接口 + ConditionBase._clone() - 【必须】克隆接口 + ConditionBase._reset() - 【可选】重载私有变量 +""" + +ConditionBase.name.__doc__ = """名称""" + +ConditionBase.__init__.__doc__ = """ +__init__(self[, name="ConditionBase"]) + + 初始化构造函数 + + :param str name: 名称 +""" + +ConditionBase.getParam.__doc__ = """ +getParam(self, name) + + 获取指定的参数 + + :param str name: 参数名称 + :return: 参数值 + :raises out_of_range: 无此参数 +""" + +ConditionBase.setParam.__doc__ = """ +setParam(self, name, value) + + 设置参数 + + :param str name: 参数名称 + :param value: 参数值 + :type value: int | bool | float | string + :raises logic_error: Unsupported type! 不支持的参数类型 +""" + +ConditionBase.isValid.__doc__ = """ +isValid(self, datetime) + + 指定时间系统是否有效 + + :param Datetime datetime: 指定时间 + :return: True 有效 | False 无效 +""" + +ConditionBase.setTO.__doc__ = """ +setTO(self, k) + + :param KData k: 设置交易对象 +""" + +ConditionBase.getTO.__doc__ = """ +getTO(self) + + :return: 交易对象 + :rtype: KData +""" + +ConditionBase.setTM.__doc__ = """ +setTM(self, tm) + + :param TradeManager tm: 设置交易管理账户 +""" + +ConditionBase.getTM.__doc__ = """ +getTM(self) + + 获取交易管理账户 + + :return: 交易管理账户 + :rtype: TradeManager +""" + +ConditionBase.setSG.__doc__ = """ +setSG(self, sg) + + 设置交易信号指示器 + + :param SignalBase sg: +""" + +ConditionBase.getSG.__doc__ = """ +getSG(self) + + 获取信号指示器 + + :rtype: SignalBase +""" + +ConditionBase.reset.__doc__ = """ +reset(self) + + 复位操作 +""" + +ConditionBase.clone.__doc__ = """ +clone(self) + + 克隆操作 +""" + +ConditionBase._addValid.__doc__ = """ +_addValid(self, datetime) + + 加入有效时间,在_calculate中调用 + + :param Datetime datetime: 有效时间 +""" + +ConditionBase._calculate.__doc__ = """ +_calculate(self) + + 【重载接口】子类计算接口 +""" + +ConditionBase._reset.__doc__ = """ +_reset(self) + + 【重载接口】子类复位接口,复位内部私有变量 +""" + +ConditionBase._clone.__doc__ = """ +_clone(self) + + 【重载接口】子类克隆接口 +""" + + +#------------------------------------------------------------------ +# add doc-string for build_in func +#------------------------------------------------------------------ + +CN_OPLine.__doc__ = """ +CN_OPLine(op) + + 固定使用股票最小交易量进行交易,计算权益曲线的op值,当权益曲线高于op时,系统有效,否则无效。 + + :param Operand op: Operand实例 + :return: 系统有效条件实例 + :rtype: ConditionBase +""" diff --git a/tools/hikyuu/trade_sys/environment.py b/tools/hikyuu/trade_sys/environment.py index 3c0360bd..a282a4dc 100644 --- a/tools/hikyuu/trade_sys/environment.py +++ b/tools/hikyuu/trade_sys/environment.py @@ -1,20 +1,37 @@ #!/usr/bin/python # -*- coding: utf8 -*- # cp936 +# +# The MIT License (MIT) +# +# Copyright (c) 2010-2017 fasiondog +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. -#=============================================================================== -# 作者:fasiondog -# 历史:1)20130419, Added by fasiondog -#=============================================================================== -from . import _trade_sys as csys +from ._trade_sys import EnvironmentBase, EV_TwoLine from hikyuu.util.unicode import (unicodeFunc, reprFunc) -EnvironmentBase = csys.EnvironmentBase + EnvironmentBase.__unicode__ = unicodeFunc EnvironmentBase.__repr__ = reprFunc -EV_TwoLine = csys.EV_TwoLine def ev_init(self, name, params): super(self.__class__, self).__init__(name) @@ -23,6 +40,7 @@ def ev_init(self, name, params): for k,v in params.items(): self.setParam(k, v) + def crtEV(func, params={}, name='crtEV'): """ 快速创建自定义不带私有属性的市场环境判断策略 @@ -38,7 +56,124 @@ def crtEV(func, params={}, name='crtEV'): return meta_x(name, params) -EV_TwoLine.__doc__ += """\n + +#------------------------------------------------------------------ +# add doc-string +#------------------------------------------------------------------ + +EnvironmentBase.__doc__ = """ +市场环境判定策略基类 + +自定义市场环境判定策略接口: + + EnvironmentBase._calculate() - 【必须】子类计算接口 + EnvironmentBase._clone() - 【必须】克隆接口 + EnvironmentBase._reset() - 【可选】重载私有变量 +""" + +EnvironmentBase.__init__.__doc__ = """ +__init__(self[, name='EnvironmentBase']) + + 初始化构造函数 + + :param str name: 名称 +""" + +EnvironmentBase.name.__doc__ = """名称""" + +EnvironmentBase.getParam.__doc__ = """ +getParam(self, name) + + 获取指定的参数 + + :param str name: 参数名称 + :return: 参数值 + :raises out_of_range: 无此参数 +""" + +EnvironmentBase.setParam.__doc__ = """ +setParam(self, name, value) + + 设置参数 + + :param str name: 参数名称 + :param value: 参数值 + :type value: int | bool | float | string + :raises logic_error: Unsupported type! 不支持的参数类型 +""" + +EnvironmentBase.setQuery.__doc__ = """ +setQuery(self, query) + + 设置查询条件 + + :param KQuery query: 查询条件 +""" + +EnvironmentBase.getQuery.__doc__ = """ +getQuery(self) + + 获取查询条件 + + :return: 查询条件 + :rtype: KQuery +""" + +EnvironmentBase.isValid.__doc__ = """ +isValid(self, datetime) + + 指定时间系统是否有效 + + :param Datetime datetime: 指定时间 + :return: True 有效 | False 无效 +""" + +EnvironmentBase._addValid.__doc__ = """ +_addValid(self, datetime) + + 加入有效时间,在_calculate中调用 + + :param Datetime datetime: 有效时间 +""" + +EnvironmentBase.reset.__doc__ = """ +reset(self) + + 复位操作 +""" + +EnvironmentBase.clone.__doc__ = """ +clone(self) + + 克隆操作 +""" + +EnvironmentBase._reset.__doc__ = """ +_reset(self) + + 【重载接口】子类复位接口,用于复位内部私有变量 +""" + +EnvironmentBase._clone.__doc__ = """ +_clone(self) + + 【重载接口】子类克隆接口 +""" + +EnvironmentBase._calculate.__doc__ = """ +_calculate(self) + + 【重载接口】子类计算接口 +""" + + +#------------------------------------------------------------------ +# add doc-string for build_in func +#------------------------------------------------------------------ + +EV_TwoLine.__doc__ = """ +EV_TwoLine(fast, slow[, market = 'SH']) + 快慢线判断策略,市场指数的快线大于慢线时,市场有效,否则无效。 :param Operand fast: 快线指标 diff --git a/tools/hikyuu/trade_sys/moneymanager.py b/tools/hikyuu/trade_sys/moneymanager.py index 3f8d9d29..66d1a459 100644 --- a/tools/hikyuu/trade_sys/moneymanager.py +++ b/tools/hikyuu/trade_sys/moneymanager.py @@ -1,27 +1,44 @@ #!/usr/bin/python # -*- coding: utf8 -*- # cp936 +# +# The MIT License (MIT) +# +# Copyright (c) 2010-2017 fasiondog +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. -#=============================================================================== -# 作者:fasiondog -# 历史:1)20130419, Added by fasiondog -#=============================================================================== -from . import _trade_sys as csys +from ._trade_sys import (MoneyManagerBase, + MM_Nothing, + MM_FixedRisk, + MM_FixedCapital, + MM_FixedCount, + MM_FixedPercent, + MM_FixedUnits, + MM_WilliamsFixedRisk) from hikyuu.util.unicode import (unicodeFunc, reprFunc) -MoneyManagerBase = csys.MoneyManagerBase + MoneyManagerBase.__unicode__ = unicodeFunc MoneyManagerBase.__repr__ = reprFunc -MM_FixedRisk = csys.MM_FixedRisk -MM_FixedCapital = csys.MM_FixedCapital -MM_FixedCount = csys.MM_FixedCount -MM_FixedPercent = csys.MM_FixedPercent -MM_FixedUnits = csys.MM_FixedUnits -MM_FixedCapital = csys.MM_FixedCapital -MM_WilliamsFixedRisk = csys.MM_WilliamsFixedRisk -MM_Nothing = csys.MM_Nothing def mm_init(self, name, params): super(self.__class__, self).__init__(name) @@ -44,21 +61,224 @@ def crtMM(func, params={}, name='crtMM'): meta_x._calculate = func return meta_x(name, params) -MM_Nothing.__doc__ += """\n + +#------------------------------------------------------------------ +# add doc-string +#------------------------------------------------------------------ + +MoneyManagerBase.__doc__ = """ +资金管理策略基类 + +公共参数: + + auto-checkin=False (bool) : 当账户现金不足以买入资金管理策略指示的买入数量时, + 自动向账户中补充存入(checkin)足够的现金。 + max-stock=200 (int) : 最大持有的证券种类数量(即持有几只股票,而非各个股票的持仓数) + +自定义资金管理策略接口: + + MoneyManagerBase.buyNotify() - 【可选】接收实际买入通知,预留用于多次增减仓处理 + MoneyManagerBase.sellNotify() - 【可选】接收实际卖出通知,预留用于多次增减仓处理 + MoneyManagerBase._getBuyNumber() - 【必须】获取指定交易对象可买入的数量 + MoneyManagerBase._getSellNumber() - 【可选】获取指定交易对象可卖出的数量, + 如未重载,默认为卖出全部已持仓数量 + MoneyManagerBase._reset() - 【可选】重置私有属性 + MoneyManagerBase._clone() - 【必须】克隆接口 +""" + +MoneyManagerBase.name.__doc__ = """名称""" + +MoneyManagerBase.__init__.__doc__ = """ +__init__(self[, name="MoneyManagerBase]) + + 初始化构造函数 + + :param str name: 名称 +""" + +MoneyManagerBase.getParam.__doc__ = """ +getParam(self, name) + + 获取指定的参数 + + .. note:: + + 所有的资金管理策略具有参数“auto-checkin”(bool类型,默认为False), + 其含义为“当账户现金不足以买入资金管理策略指示的买入数量时,自动向账户中 + 补充存入(checkin)足够的现金。 + + :param str name: 参数名称 + :return: 参数值 + :raises out_of_range: 无此参数 +""" + +MoneyManagerBase.setParam.__doc__ = """ +setParam(self, name, value) + + 设置参数 + + :param str name: 参数名称 + :param value: 参数值 + :type value: int | bool | float | string + :raises logic_error: Unsupported type! 不支持的参数类型 +""" + +MoneyManagerBase.reset.__doc__ = """ +reset(self) + + 复位操作 +""" + +MoneyManagerBase.clone.__doc__ = """ +clone(self) + + 克隆操作 +""" + +MoneyManagerBase.buyNotify.__doc__ = """ +buyNotify(self, trade_record) + + 【重载接口】交易系统发生实际买入操作时,通知交易变化情况, + 一般存在多次增减仓的情况才需要重载。 + + :param TradeRecord trade_record: 发生实际买入时的实际买入交易记录 +""" + +MoneyManagerBase.sellNotify.__doc__ = """ +sellNotify(self, trade_record) + + 【重载接口】交易系统发生实际卖出操作时,通知实际交易变化情况, + 一般存在多次增减仓的情况才需要重载。 + + :param TradeRecord trade_record: 发生实际卖出时的实际卖出交易记录 +""" + +MoneyManagerBase.getBuyNumber.__doc__ = """ +getBuyNumber(self, datetime, stock, price, risk) + + 获取指定交易对象可买入的数量 + + :param Datetime datetime: 交易时间 + :param Stock stock: 交易对象 + :param float price: 交易价格 + :param float risk: 交易承担的风险,如果为0,表示全部损失,即市值跌至0元 + :return: 可买入数量 + :rtype: int +""" + +MoneyManagerBase.getSellNumber.__doc__ = """ +getSellNumber(self, datetime, stock, price, risk) + + 获取指定交易对象可卖出的数量 + + :param Datetime datetime: 交易时间 + :param Stock stock: 交易对象 + :param float price: 交易价格 + :param float risk: 新的交易承担的风险,如果为0,表示全部损失,即市值跌至0元 + :return: 可卖出数量 + :rtype: int +""" + +MoneyManagerBase._getBuyNumber.__doc__ = """ +_getBuyNumber(self, datetime, stock, price, risk) + + 【重载接口】获取指定交易对象可买入的数量 + + :param Datetime datetime: 交易时间 + :param Stock stock: 交易对象 + :param float price: 交易价格 + :param float risk: 交易承担的风险,如果为0,表示全部损失,即市值跌至0元 + :return: 可买入数量 + :rtype: int +""" + +MoneyManagerBase._getSellNumber.__doc__ = """ +_getSellNumber(self, datetime, stock, price, risk) + + 【重载接口】获取指定交易对象可卖出的数量。如未重载,默认为卖出全部已持仓数量。 + + :param Datetime datetime: 交易时间 + :param Stock stock: 交易对象 + :param float price: 交易价格 + :param float risk: 新的交易承担的风险,如果为0,表示全部损失,即市值跌至0元 + :return: 可卖出数量 + :rtype: int +""" + +MoneyManagerBase._reset.__doc__ = """ +_reset(self) + + 【重载接口】子类复位接口,复位内部私有变量 +""" + +MoneyManagerBase._clone.__doc__ = """ +_clone(self) + + 【重载接口】子类克隆接口 +""" + + +#------------------------------------------------------------------ +# add doc-string for build_in func +#------------------------------------------------------------------ + +MM_Nothing.__doc__ = """ +MM_Nothing() + 特殊的资金管理策略,相当于不做资金管理,有多少钱买多少。 """ -MM_FixedCount.__doc__ += """\n +MM_FixedRisk.__doc__ = """ +MM_FixedRisk([risk = 1000.00]) + + 固定风险资金管理策略对每笔交易限定一个预先确定的或者固定的资金风险, + 如每笔交易固定风险1000元。公式:交易数量 = 固定风险 / 交易风险。 + + :param float risk: 固定风险 + :return: 资金管理策略实例 +""" + +MM_FixedCapital.__doc__ = """ +MM_FixedCapital([capital = 10000.0]) + + 固定资本资金管理策略 + + :param float capital: 固定资本单位 + :return: 资金管理策略实例 +""" + +MM_FixedCount.__doc__ = """ +MM_FixedCount([n = 100]) + 固定交易数量资金管理策略。每次买入固定的数量。 :param int n: 每次买入的数量(应该是交易对象最小交易数量的整数,此处程序没有此进行判断) :return: 资金管理策略实例 """ -MM_FixedPercent.__doc__ += """\n - 固定百分比风险模型。公式:P(头寸规模)= 账户余额 * 百分比 / R(每股的交易风险)。[BOOK3]_, [BOOK4]_ . +MM_FixedPercent.__doc__ = """ +MM_FixedPercent([p = 0.03]) + + 固定百分比风险模型。公式:P(头寸规模)= 账户余额 * 百分比 / R(每股的交易风险)。 :param float p: 百分比 :return: 资金管理策略实例 """ +MM_FixedUnits.__doc__ = """ +MM_FixedUnits([n = 33]) + + 固定单位资金管理策略 + + :param int n: n个资金单位 + :return: 资金管理策略实例 +""" + +MM_WilliamsFixedRisk.__doc__ = """ +MM_WilliamsFixedRisk([p=0.1, max_loss=1000.0]) + + 威廉斯固定风险资金管理策略 +""" + + + diff --git a/tools/hikyuu/trade_sys/profitgoal.py b/tools/hikyuu/trade_sys/profitgoal.py index 53cefd1a..315a2598 100644 --- a/tools/hikyuu/trade_sys/profitgoal.py +++ b/tools/hikyuu/trade_sys/profitgoal.py @@ -1,11 +1,29 @@ #!/usr/bin/python # -*- coding: utf8 -*- # cp936 +# +# The MIT License (MIT) +# +# Copyright (c) 2010-2017 fasiondog +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. -#=============================================================================== -# 作者:fasiondog -# 历史:1)20130419, Added by fasiondog -#=============================================================================== from . import _trade_sys as csys from hikyuu.util.unicode import (unicodeFunc, reprFunc) @@ -17,13 +35,13 @@ ProfitGoalBase.__repr__ = reprFunc PG_NoGoal = csys.PG_NoGoal PG_FixedPercent = csys.PG_FixedPercent -PG_NoGoal.__doc__ += """\n +PG_NoGoal.__doc__ = """\n 无盈利目标策略,通常为了进行测试或对比。 :return: 盈利目标策略实例 """ -PG_FixedPercent.__doc__ += """\n +PG_FixedPercent.__doc__ = """\n 固定百分比盈利目标,目标价格 = 买入价格 * (1 + p) :param float p: 百分比 diff --git a/tools/hikyuu/trade_sys/signal.py b/tools/hikyuu/trade_sys/signal.py index feb97b0f..80b5e578 100644 --- a/tools/hikyuu/trade_sys/signal.py +++ b/tools/hikyuu/trade_sys/signal.py @@ -1,25 +1,43 @@ #!/usr/bin/python # -*- coding: utf8 -*- # cp936 +# +# The MIT License (MIT) +# +# Copyright (c) 2010-2017 fasiondog +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. -#=============================================================================== -# 作者:fasiondog -# 历史:1)20130419, Added by fasiondog -#=============================================================================== -from . import _trade_sys as csys +from ._trade_sys import (SignalBase, + SG_Bool, + SG_Single, + SG_Single2, + SG_Cross, + SG_CrossGold, + SG_Flex) from hikyuu.util.unicode import (unicodeFunc, reprFunc) -SignalBase = csys.SignalBase + SignalBase.__unicode__ = unicodeFunc SignalBase.__repr__ = reprFunc -SG_Single = csys.SG_Single -SG_Single2 = csys.SG_Single2 -SG_Cross = csys.SG_Cross -SG_CrossGold = csys.SG_CrossGold -SG_Flex = csys.SG_Flex -SG_Bool = csys.SG_Bool def sig_init(self, name, params): super(self.__class__, self).__init__(name) @@ -42,7 +60,222 @@ def crtSG(func, params={}, name='crtSG'): meta_x._calculate = func return meta_x(name, params) -SG_Flex.__doc__ += """\n + + +#------------------------------------------------------------------ +# add doc-string +#------------------------------------------------------------------ + +SignalBase.__doc__ = """ +信号指示器负责产生买入、卖出信号。 + +公共参数: + + alternate (bool|True) :买入和卖出信号是否交替出现。单线型的信号通常通过拐点、 + 斜率等判断信号的产生,此种情况下可能出现连续出现买入 + 信号或连续出现卖出信号的情况,此时可通过该参数控制买入、 + 卖出信号是否交替出现。而双线交叉型的信号通常本身买入和 + 卖出已经是交替出现,此时该参数无效。 + +自定义的信号指示器接口: + + SignalBase._calculate() - 【必须】子类计算接口 + SignalBase._clone() - 【必须】克隆接口 + SignalBase._reset() - 【可选】重载私有变量 + + +示例1(不含私有变量,海龟交易策略): + + from hikyuu.trade_sys.signal import SignalBase + from hikyuu.indicator import HHV, LLV, CLOSE, REF + + class TurtleSignal(SignalBase): + def __init__(self, n = 20): + super(TurtleSignal, self).__init__("TurtleSignal") + self.setParam("n", 20) + + def _clone(self): + return TurtleSignal() + + def _calculate(self): + n = self.getParam("n") + k = self.getTO() + c = CLOSE(k) + h = REF(HHV(c, n), 1) #前n日高点 + L = REF(LLV(c, n), 1) #前n日低点 + for i in range(h.discard, len(k)): + if (c[i] >= h[i]): + self._addBuySignal(k[i].datetime) + elif (c[i] <= L[i]): + self._addSellSignal(k[i].datetime) + + if __name__ == "__main__": + from examples_init import * + + sg = TurtleSignal() + s = getStock("sh000001") + k = s.getKData(Query(-500)) + + #只有设置交易对象时,才会开始实际计算 + sg.setTO(k) + dates = k.getDatetimeList() + for d in dates: + if (sg.shouldBuy(d)): + print("买入:%s" % d) + elif (sg.shouldSell(d)): + print("卖出: %s" % d) + +示例2(含私有属性): + + class SignalPython(SignalBase): + def __init__(self): + super(SignalPython, self).__init__("SignalPython") + self._x = 0 #私有属性 + self.setParam("test", 30) + + def _reset(self): + self._x = 0 + + def _clone(self): + p = SignalPython() + p._x = self._x + return p + + def _calculate(self): + self._addBuySignal(Datetime(201201210000)) + self._addSellSignal(Datetime(201201300000)) +""" + +SignalBase.name.__doc__ = """名称""" + +SignalBase.__init__.__doc__ = """ +__init__(self[, name="SignalBase"]) + + :param str name: 名称 +""" + +SignalBase.getParam.__doc__ = """ +getParam(self, name) + + 获取指定的参数 + + :param str name: 参数名称 + :return: 参数值 + :raises out_of_range: 无此参数 +""" + +SignalBase.setParam.__doc__ = """ +setParam(self, name, value) + + 设置参数 + + :param str name: 参数名称 + :param value: 参数值 + :type value: int | bool | float | string + :raises logic_error: Unsupported type! 不支持的参数类型 +""" + +SignalBase.setTO.__doc__ = """ +setTO(self, k) + + :param KData k: 设置交易对象 +""" + +SignalBase.getTO.__doc__ = """ +getTO(self) + + :return: 交易对象 + :rtype: KData +""" + +SignalBase.shouldBuy.__doc__ = """ +shouldBuy(self, datetime) + + 指定时刻是否可以买入 + + :param Datetime datetime: 指定时刻 + :rtype: bool +""" + +SignalBase.shouldSell.__doc__ = """ +shouldSell(self, datetime) + + 指定时刻是否可以卖出 + + :param Datetime datetime: 指定时刻 + :rtype: bool +""" + +SignalBase.getBuySignal.__doc__ = """ +getBuySignal(self) + + 获取所有买入指示日期列表 + + :rtype: DatetimeList +""" + +SignalBase.getSellSignal.__doc__ = """ +getSellSignal(self) + + 获取所有卖出指示日期列表 + + :rtype: DatetimeList +""" + +SignalBase._addBuySignal.__doc__ = """ +_addBuySignal(self, datetime) + + 加入买入信号,在_calculate中调用 + + :param Datetime datetime: 指示买入的日期 +""" + +SignalBase._addSellSignal.__doc__ = """ +_addSellSignal(self, datetime) + + 加入卖出信号,在_calculate中调用 + + :param Datetime datetime: 指示卖出的日期 +""" + +SignalBase.reset.__doc__ = """ +reset(self) + + 复位操作 +""" + +SignalBase.clone.__doc__ = """ +clone(self) + + 克隆操作 +""" + +SignalBase._calculate.__doc__ = """ +_calculate(self) + + 【重载接口】子类计算接口 +""" + +SignalBase._reset.__doc__ = """ +_reset(self) + + 【重载接口】子类复位接口,复位内部私有变量 +""" + +SignalBase._clone.__doc__ = """ +_clone(self) + + 【重载接口】子类克隆接口 +""" + + +#------------------------------------------------------------------ +# add doc-string for build_in func +#------------------------------------------------------------------ + +SG_Flex.__doc__ = """ +SG_Flex(ind, slow_n[, kpart = 'CLOSE']) + 使用自身的EMA(slow_n)作为慢线,自身作为快线,快线向上穿越慢线买入,快线向下穿越慢线卖出。 :param Operand ind: @@ -51,10 +284,10 @@ SG_Flex.__doc__ += """\n :return: 信号指示器 """ -SG_Cross.__doc__ += """\n - 双线交叉指示器,当快线从下向上穿越慢线时,买入; - 当快线从上向下穿越慢线时,卖出。 - 如:5日MA上穿10日MA时买入,5日MA线下穿MA10日线时卖出:: +SG_Cross.__doc__ = """ +SG_Cross(fast, slow[, kpart = "CLOSE"]) + + 双线交叉指示器,当快线从下向上穿越慢线时,买入;当快线从上向下穿越慢线时,卖出。如:5日MA上穿10日MA时买入,5日MA线下穿MA10日线时卖出:: SG_Cross(OP(MA(n=10)), OP(MA(n=30))) @@ -64,7 +297,9 @@ SG_Cross.__doc__ += """\n :return: 信号指示器 """ -SG_CrossGold.__doc__ += """\n +SG_CrossGold.__doc__ = """ +SG_CrossGold(fast, slow[, kpart = "CLOSE"]) + 金叉指示器,当快线从下向上穿越慢线且快线和慢线的方向都是向上时为金叉,买入; 当快线从上向下穿越慢线且快线和慢线的方向都是向下时死叉,卖出。:: @@ -73,10 +308,12 @@ SG_CrossGold.__doc__ += """\n :param Operand fast: 快线 :param Operand slow: 慢线 :param string kpart: OPEN|HIGH|LOW|CLOSE|AMO|VOL|KDATA - :return: 信号指示器 + :return: 信号指示器 """ -SG_Single.__doc__ += """\n +SG_Single.__doc__ = """ +SG_Single(ind[, filter_n = 10, filter_p = 0.1, kpart='CLOSE']) + 生成单线拐点信号指示器。使用《精明交易者》 [BOOK1]_ 中给出的曲线拐点算法判断曲线趋势,公式见下:: filter = percentage * STDEV((AMA-AMA[1], N) @@ -92,7 +329,9 @@ SG_Single.__doc__ += """\n :return: 信号指示器 """ -SG_Single2.__doc__ += """\n +SG_Single2.__doc__ = """ +SG_Single2(ind[, filter_n = 10, filter_p = 0.1, kpart='CLOSE']) + 生成单线拐点信号指示器2 [BOOK1]_:: filter = percentage * STDEV((AMA-AMA[1], N) @@ -107,8 +346,10 @@ SG_Single2.__doc__ += """\n :return: 信号指示器 """ -SG_Bool.__doc__ += """\n - 使用运算结果为类似bool数组的Operand分别作为买入、卖出指示。 +SG_Bool.__doc__ = """ +SG_Bool(buy, sell[, kpart='CLOSE']) + + 布尔信号指示器,使用运算结果为类似bool数组的Operand分别作为买入、卖出指示。 :param Operand buy: 买入指示(结果Indicator中相应位置>0则代表买入) :param Operand sell: 卖出指示(结果Indicator中相应位置>0则代表卖出) diff --git a/tools/hikyuu/trade_sys/slippage.py b/tools/hikyuu/trade_sys/slippage.py index 319272d5..afd83cef 100644 --- a/tools/hikyuu/trade_sys/slippage.py +++ b/tools/hikyuu/trade_sys/slippage.py @@ -1,11 +1,29 @@ #!/usr/bin/python # -*- coding: utf8 -*- # cp936 +# +# The MIT License (MIT) +# +# Copyright (c) 2010-2017 fasiondog +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. -#=============================================================================== -# 作者:fasiondog -# 历史:1)20130419, Added by fasiondog -#=============================================================================== from . import _trade_sys as csys from hikyuu.util.unicode import (unicodeFunc, reprFunc) @@ -39,14 +57,14 @@ def crtSL(func, params={}, name='crtSL'): return meta_x(name, params) -SL_FixedPercent.__doc__ += """\n +SL_FixedPercent.__doc__ = """\n 固定百分比移滑价差算法,买入实际价格 = 计划买入价格 * (1 + p),卖出实际价格 = 计划卖出价格 * (1 - p) :param float p: 偏移的固定百分比 :return: 移滑价差算法实例 """ -SL_FixedValue.__doc__ += """\n +SL_FixedValue.__doc__ = """\n 固定价格移滑价差算法,买入实际价格 = 计划买入价格 + 偏移价格,卖出实际价格 = 计划卖出价格 - 偏移价格 :param float p: 偏移价格 diff --git a/tools/hikyuu/trade_sys/stoploss.py b/tools/hikyuu/trade_sys/stoploss.py index 5bd978e9..9fb1332b 100644 --- a/tools/hikyuu/trade_sys/stoploss.py +++ b/tools/hikyuu/trade_sys/stoploss.py @@ -1,11 +1,29 @@ #!/usr/bin/python # -*- coding: utf8 -*- # cp936 +# +# The MIT License (MIT) +# +# Copyright (c) 2010-2017 fasiondog +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. -#=============================================================================== -# 作者:fasiondog -# 历史:1)20130419, Added by fasiondog -#=============================================================================== from . import _trade_sys as csys from hikyuu.util.unicode import (unicodeFunc, reprFunc) @@ -39,23 +57,96 @@ def crtST(func, params={}, name='crtST'): meta_x._calculate = func return meta_x(name, params) -ST_FixedPercent.__doc__ += """\n + +#------------------------------------------------------------------ +# add doc-string +#------------------------------------------------------------------ + +StoplossBase.__doc__ = """ +止损/止赢算法基类 + +自定义止损/止赢策略接口: + + SignalBase._calculate() - 【必须】子类计算接口 + SignalBase._clone() - 【必须】克隆接口 + SignalBase._reset() - 【可选】重载私有变量 +""" + +StoplossBase.name.__doc__ = """名称""" + +StoplossBase.__init__.__doc__ = """ +__init__(self[, name="StoplossBase"]) + + :param str name: 名称 +""" + +StoplossBase.getParam.__doc__ = """ +getParam(self, name) + + 获取指定的参数 + + :param str name: 参数名称 + :return: 参数值 + :raises out_of_range: 无此参数 +""" + +StoplossBase.setParam.__doc__ = """ +setParam(self, name, value) + + 设置参数 + + :param str name: 参数名称 + :param value: 参数值 + :type value: int | bool | float | string + :raises logic_error: Unsupported type! 不支持的参数类型 +""" + +StoplossBase.setTM.__doc__ = """ +setTM(self, tm) + + 设置交易管理实例 + + :param TradeManager tm: 交易管理实例 +""" + +StoplossBase.getTM.__doc__ = """ +getTM(self) + + 获取交易管理实例 + + :rtype: TradeManager +""" + + + +#------------------------------------------------------------------ +# add doc-string for build_in func +#------------------------------------------------------------------ + +ST_FixedPercent.__doc__ = """ +ST_FixedPercent([p=0.03]) + 固定百分比止损策略,即当价格低于买入价格的某一百分比时止损 :param float p: 百分比(0,1] :return: 止损/止赢策略实例 """ -ST_Indicator.__doc__ += """\n +ST_Indicator.__doc__ = """ +ST_Indicator(op[, kpart="CLOSE"]) + 使用技术指标作为止损价。如使用10日EMA作为止损::: ST_Indicator(OP(EMA(n=10))) :param Operand op: :param string kpart: KDATA|OPEN|HIGH|LOW|CLOSE|AMO|VOL + :return: 止损/止赢策略实例 """ -ST_Saftyloss.__doc__ += """\n +ST_Saftyloss.__doc__ = """ +ST_Saftyloss([n1=10, n2=3, p=2.0]) + 参见《走进我的交易室》(2007年 地震出版社) 亚历山大.艾尔德(Alexander Elder) P202 计算说明:在回溯周期内(一般为10到20天),将所有向下穿越的长度相加除以向下穿越的次数, 得到噪音均值(即回溯期内所有最低价低于前一日最低价的长度除以次数),并用今日 diff --git a/tools/hikyuu/trade_sys/system.py b/tools/hikyuu/trade_sys/system.py index 18343176..2b9650ec 100644 --- a/tools/hikyuu/trade_sys/system.py +++ b/tools/hikyuu/trade_sys/system.py @@ -1,11 +1,29 @@ #!/usr/bin/python # -*- coding: utf8 -*- # cp936 +# +# The MIT License (MIT) +# +# Copyright (c) 2010-2017 fasiondog +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. -#=============================================================================== -# 作者:fasiondog -# 历史:1)20130419, Added by fasiondog -#=============================================================================== from . import _trade_sys as csys from hikyuu.util.unicode import (unicodeFunc, reprFunc)