{"id":82,"date":"2021-10-20T13:41:06","date_gmt":"2021-10-20T05:41:06","guid":{"rendered":"http:\/\/www.qddlh.com\/?p=82"},"modified":"2021-10-20T13:41:07","modified_gmt":"2021-10-20T05:41:07","slug":"backtrader-%e5%bf%ab%e9%80%9f%e5%bc%80%e5%a7%8b%ef%bc%88%e5%ae%9a%e5%88%b6%e7%ad%96%e7%95%a5%e5%8f%82%e6%95%b0%ef%bc%89","status":"publish","type":"post","link":"https:\/\/www.qddlh.com\/?p=82","title":{"rendered":"Backtrader-\u5feb\u901f\u5f00\u59cb\uff08\u5b9a\u5236\u7b56\u7565\u53c2\u6570\uff09"},"content":{"rendered":"\n<p>\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u4f7f\u7528\u7b56\u7565\u7684\u65f6\u5019\uff0c\u6ca1\u6709\u4ec0\u4e48\u53c2\u6570\u53ef\u4ee5\u8c03\u8282\u6d4b\u8bd5\u3002\u6846\u67b6\u672c\u8eab\u662f\u652f\u6301\u53c2\u6570\u7684\uff0c\u4f7f\u7528\u8d77\u6765\u4e5f\u6bd4\u8f83\u7b80\u5355<\/p>\n\n\n\n<p>\u53c2\u6570\u7684\u5b9a\u4e49\u5f88\u7b80\u5355\uff0c\u5982\u4e0b\u6240\u793a\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>params = (('myparam', 27), ('exitbars', 5),)<\/code><\/pre>\n\n\n\n<p>\u4f7f\u7528\u4e86python\u57fa\u672c\u7684\u6570\u636e\u7ed3\u6784\u5143\u7ec4\uff08tuple\uff09\u3002\u6bcf\u4e2a\u5143\u7ec4\u67092\u4e2a\u5143\u7d20\u3002\u5176\u4e2d\uff0c\u7b2c\u4e00\u4e2a\u5143\u7d20\u4e3a\u53c2\u6570\u7684\u540d\u79f0\uff0c\u7b2c\u4e8c\u4e2a\u5143\u4e3a\u53d8\u91cf\u5bf9\u5e94\u7684\u503c\u3002\u7528\u66f4\u76f4\u89c2\u7684\u683c\u5f0f\u5c55\u793a\u5982\u4e0b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>params = (\n    ('myparam', 27),\n    ('exitbars', 5),\n)<\/code><\/pre>\n\n\n\n<p>\u9664\u4e86\u5f00\u59cb\u8d4b\u503c\u9ed8\u8ba4\u503c\uff0c\u8fd8\u53ef\u4ee5\u5728\u6846\u67b6\uff0c\u589e\u52a0\u7b56\u7565\u7684\u65f6\u5019\u8fdb\u884c\u8d4b\u503c\uff0c\u8d4b\u503c\u4e0b\u65b9\u6cd5\u5982\u4e0b\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># Add a strategy\ncerebro.addstrategy(TestStrategy, myparam=20, exitbars=7)<\/code><\/pre>\n\n\n\n<p>\u4e0b\u9762\u5b9e\u73b0\u4e00\u4e2a\u901a\u8fc7\u8bbe\u7f6e\u53c2\u6570\uff0c\u6765\u5b9e\u73b0\u53c2\u6570\u6307\u5b9a\u591a\u4e2a\u5c11\u51e0\u4ea4\u6613\u65e5\u540e\u6e05\u4ed3\u7684\u6848\u4f8b\uff0c\u6301\u80a15\u5929\u5c31\u6e05\u4ed3\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># -*- coding: utf-8 -*-\n\"\"\"\nbacktrader\u624b\u518c\u6837\u4f8b\u4ee3\u7801\n@author: \u4e00\u5757\u81ea\u7531\u7684\u7816\n\"\"\"\n#############################################################\n#import\n#############################################################\nfrom __future__ import (absolute_import, division, print_function,\n                        unicode_literals)\nimport os,sys\nimport pandas as pd\nimport backtrader as bt\n#############################################################\n#global const values\n#############################################################\n#############################################################\n#static function\n#############################################################\n#############################################################\n#class\n#############################################################\n# Create a Stratey\nclass TestStrategy(bt.Strategy):\n    params = (\n        ('exitbars', 5),\n    )\n\n    def log(self, txt, dt=None):\n        ''' Logging function for this strategy\uff0c\u8fd9\u91cc\u5b9a\u4e49\u65e5\u5fd7\u7684\u663e\u793a\u683c\u5f0f'''\n        dt = dt or self.datas&#91;0].datetime.date(0)\n        print('%s, %s' % (dt.isoformat(), txt))\n\n    def __init__(self):\n        # Keep a reference to the \"close\" line in the data&#91;0] dataseries\uff08\u83b7\u53d6\u6536\u76d8\u4ef7\uff09\n        self.dataclose = self.datas&#91;0].close\n        # To keep track of pending orders and buy price\/commission(\u4ef7\u683c\u3001\u4f63\u91d1)\n        self.order = None\n        self.buyprice = None\n        self.buycomm = None\n    \n    def notify_order(self, order):\n        if order.status in &#91;order.Submitted, order.Accepted]:\n            # Buy\/Sell order submitted\/accepted to\/by broker - Nothing to do\n            return\n        # Check if an order has been completed\n        # Attention: broker could reject order if not enough cash\n        if order.status in &#91;order.Completed]:\n            if order.isbuy():\n                # \u5b9e\u9645\u53d1\u751f\u4e70\u5355\u7684\u4ef7\u683c\uff0c\u6210\u672c\uff0c\u4f63\u91d1\n                self.log(\n                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %\n                    (order.executed.price,\n                     order.executed.value,\n                     order.executed.comm))\n                self.buyprice = order.executed.price\n                self.buycomm = order.executed.comm\n            elif order.issell():\n                #  \u5b9e\u9645\u53d1\u751f\u5356\u5355\u7684\u4ef7\u683c\uff0c\u6210\u672c\uff0c\u4f63\u91d1\n                self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %\n                         (order.executed.price,\n                          order.executed.value,\n                          order.executed.comm))\n            # \u53d1\u751f\u4e70\u5355\u65f6\u7684\u4ea4\u6613\u65e5\u7684\u7d22\u5f15\n            self.bar_executed = len(self)\n\n        elif order.status in &#91;order.Canceled, order.Margin, order.Rejected]:\n            self.log('Order Canceled\/Margin\/Rejected')\n\n        # Write down: no pending order\n        self.order = None\n\n    def notify_trade(self, trade):\n        if not trade.isclosed:\n            return\n        # \u4e00\u6b21\u5356\u51fa\u540e\u4ea4\u6613\u5b8c\u6210\u540e\u7684\u6536\u76ca\u60c5\u51b5\uff1a gross \u6bdb\u5229  net \u51c0\/\u7eaf\u5229\n        self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %\n                 (trade.pnl, trade.pnlcomm))\n\n    def next(self):\n        # Simply log the closing price of the series from the reference\uff08\u8c03\u7528\u65e5\u5fd7\u65b9\u6cd5\uff0c\u663e\u793a\u6536\u76d8\u4ef7\uff09\n        self.log('Close, %.2f' % self.dataclose&#91;0])\n        # Check if an order is pending ... if yes, we cannot send a 2nd one\n        if self.order:\n            return\n        # Check if we are in the market\uff08\u68c0\u67e5\u662f\u5426\u6301\u80a1\uff09\n        if not self.position:\n            # \u5224\u5b9a\u5f53\u524d\u4ea4\u6613\u65e5\u7684\u6536\u76d8\u4ef7\u662f\u5426\u5c0f\u4e8e\u6628\u65e5\u7684\n            if self.dataclose&#91;0] &lt; self.dataclose&#91;-1]:\n                # current close less than previous close\uff08\u5224\u5b9a\u6628\u65e5\u7684\u6536\u76d8\u4ef7\u662f\u5426\u5c0f\u4e8e\u524d\u65e5\u7684\uff09\n                if self.dataclose&#91;-1] &lt; self.dataclose&#91;-2]:\n                    # previous close less than the previous close\n                    # BUY, BUY, BUY!!! \u8d2d\u4e70\u52a8\u4f5c\uff0c\u521b\u5efa\u4e70\u5355\uff0c\u7ed9\u4e70\u5165\u4ef7\n                    self.log('BUY CREATE, %.2f' % self.dataclose&#91;0])\n                    # Keep track of the created order to avoid a 2nd order\n                    self.order = self.buy()\n        else:\n            # Already in the market ... we might sell\uff0c\u6301\u80a1\u68c0\u67e5\u662f\u5426\u5df2\u7ecf\u5927\u4e8e5\u4e2a\u4ea4\u6613\u65e5\n            if len(self) &gt;= (self.bar_executed + self.params.exitbars):\n                # SELL, SELL, SELL!!! (with all possible default parameters)\n                self.log('SELL CREATE, %.2f' % self.dataclose&#91;0])\n\n                # Keep track of the created order to avoid a 2nd order\n                self.order = self.sell()\n#############################################################\n#global values\n#############################################################\n#############################################################\n#global function\n#############################################################\n# \u901a\u8fc7\u8bfb\u53d6cvs\u6587\u4ef6\uff0c\u83b7\u53d6\u60f3\u8981\u7684\u6570\u636e\ndef get_dataframe():\n    # Get a pandas dataframe\uff08\u8fd9\u91cc\u662f\u80a1\u7968\u6570\u636e\u6587\u4ef6\u653e\u7684\u76ee\u5f55\u8def\u5f84\uff09\n    datapath = 'qtbt\\data\\stockinfo.csv'\n    # \u6570\u636e\u8f6c\u6362\u7528\u4e34\u65f6\u6587\u4ef6\u8def\u5f84\u548c\u540d\u79f0\uff0c\u7528\u5b8c\u540e\u5220\u9664\n    tmpdatapath = datapath + '.tmp'\n    print('-----------------------read csv---------------------------')\n    dataframe = pd.read_csv(datapath,\n                                skiprows=0,\n                                header=0,\n                                parse_dates=True,\n                                index_col=0)\n    # \u5b9a\u4e49\u4ea4\u6613\u65e5\u671f\u683c\u5f0f\n    dataframe.trade_date =  pd.to_datetime(dataframe.trade_date, format=\"%Y%m%d\")\n    # \u539f\u59cbcvs\u6570\u636e\u6709\u5f88\u591a\u5217\uff0c\u8fd9\u91cc\u7ec4\u7ec7\u9700\u8981\u4f7f\u7528\u7684\u6570\u636e\u5217\uff0c\u751f\u6210\u76ee\u6807\u6570\u636e\u7684tmp\u6570\u636e\u6587\u4ef6\u540e\uff0c\u8bfb\u53d6\u9700\u8981\u7684\u6570\u636e\n    dataframe&#91;'openinterest'] = '0'\n    feedsdf = dataframe&#91;&#91;'trade_date', 'open', 'high', 'low', 'close', 'vol', 'openinterest']]\n    feedsdf.columns =&#91;'datetime', 'open', 'high', 'low', 'close', 'volume', 'openinterest']\n    # \u6309\u7167\u4ea4\u6613\u65e5\u671f\u5347\u5e8f\u6392\u5217\n    feedsdf.set_index(keys='datetime', inplace =True)\n    # \u751f\u6210\u4e34\u65f6\u6587\u4ef6\n    feedsdf.iloc&#91;::-1].to_csv(tmpdatapath)\n    # \u83b7\u53d6\u9700\u8981\u4f7f\u7528\u7684\u6570\u636e\n    feedsdf = pd.read_csv(tmpdatapath, skiprows=0, header=0, parse_dates=True, index_col=0)\n    # \u5220\u9664tmp\u4e34\u65f6\u6587\u4ef6\n    if os.path.isfile(tmpdatapath):\n        os.remove(tmpdatapath)\n        print(tmpdatapath+\" removed!\")\n    # \u8fd4\u56de\u9700\u8981\u7684\u6570\u636e\n    return feedsdf\n########################################################################\n#main\n########################################################################\nif __name__ == '__main__':\n    # Create a cerebro entity(\u521b\u5efacerebro)\n    cerebro = bt.Cerebro()\n    # Add a strategy(\u52a0\u5165\u81ea\u5b9a\u4e49\u7b56\u7565,\u53ef\u4ee5\u8bbe\u7f6e\u81ea\u5b9a\u4e49\u53c2\u6570\uff0c\u65b9\u4fbf\u8c03\u8282)\n    cerebro.addstrategy(TestStrategy)\n    # Get a pandas dataframe(\u83b7\u53d6dataframe\u683c\u5f0f\u80a1\u7968\u6570\u636e)\n    feedsdf = get_dataframe()\n    # Pass it to the backtrader datafeed and add it to the cerebro(\u52a0\u5165\u6570\u636e)\n    data = bt.feeds.PandasData(dataname=feedsdf)\n    # \u52a0\u5165\u6570\u636e\u5230Cerebro\n    cerebro.adddata(data)\n    # Add a FixedSize sizer according to the stake(\u56fd\u51851\u624b\u662f100\u80a1\uff0c\u6700\u5c0f\u7684\u4ea4\u6613\u5355\u4f4d)\n    cerebro.addsizer(bt.sizers.FixedSize, stake=100)\n    # Set our desired cash start(\u7ed9\u7ecf\u7eaa\u4eba\uff0c\u53ef\u4ee5\u7406\u89e3\u4e3a\u4ea4\u6613\u6240\u80a1\u7968\u8d26\u6237\u5145\u94b1)\n    cerebro.broker.setcash(100000.0)\n    # Set the commission - 0.1% ... divide by 100 to remove the %\n    cerebro.broker.setcommission(commission=0.001)\n    # Print out the starting conditions(\u8f93\u51fa\u8d26\u6237\u91d1\u989d)\n    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())\n    # Run over everything(\u6267\u884c\u56de\u6d4b)\n    cerebro.run()\n    # Print out the final result(\u8f93\u51fa\u8d26\u6237\u91d1\u989d)\n    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())\n<\/code><\/pre>\n\n\n\n<p>\u6267\u884c\u8f93\u51fa\uff1a<\/p>\n\n\n\n<p>2021-09-14, Close, 9.21<br>2021-09-14, BUY CREATE, 9.21<br>2021-09-15, BUY EXECUTED, Price: 9.21, Cost: 921.00, Comm 0.92<br>2021-09-15, Close, 9.19<br>2021-09-16, Close, 9.12<br>2021-09-17, Close, 9.11<br>2021-09-22, Close, 9.03<br>2021-09-23, Close, 9.03<br>2021-09-24, Close, 9.02<br>2021-09-24, SELL CREATE, 9.02<br>2021-09-27, SELL EXECUTED, Price: 9.02, Cost: 921.00, Comm 0.90<br>2021-09-27, OPERATION PROFIT, GROSS -19.00, NET -20.82<br>2021-09-27, Close, 9.02<br>2021-09-28, Close, 9.03<br>2021-09-29, Close, 9.02<br>2021-09-30, Close, 9.00<br>2021-09-30, BUY CREATE, 9.00<br>Final Portfolio Value: 99734.77<\/p>\n\n\n\n<p> 2021-09-15\u4e70\u5165\uff0c 2021-09-24 \u5356\u51fa<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5728\u524d\u9762\u7684\u4f8b\u5b50\u4e2d\u4f7f\u7528\u7b56\u7565\u7684\u65f6\u5019\uff0c\u6ca1\u6709\u4ec0\u4e48\u53c2\u6570\u53ef\u4ee5\u8c03\u8282\u6d4b\u8bd5\u3002\u6846\u67b6\u672c\u8eab\u662f\u652f\u6301\u53c2\u6570\u7684\uff0c\u4f7f\u7528\u8d77\u6765\u4e5f\u6bd4\u8f83\u7b80\u5355 \u53c2\u6570\u7684\u5b9a\u4e49\u5f88\u7b80\u5355\uff0c\u5982\u4e0b\u6240\u793a\uff1a \u4f7f\u7528\u4e86python\u57fa\u672c\u7684\u6570\u636e\u7ed3\u6784\u5143\u7ec4\uff08tuple\uff09\u3002\u6bcf\u4e2a\u5143\u7ec4\u67092\u4e2a\u5143\u7d20\u3002\u5176\u4e2d\uff0c\u7b2c\u4e00\u4e2a\u5143\u7d20\u4e3a\u53c2\u6570\u7684\u540d\u79f0\uff0c\u7b2c\u4e8c\u4e2a\u5143\u4e3a [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":30,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[11],"class_list":["post-82","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-btuserguide","tag-backtrader"],"_links":{"self":[{"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/82","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=82"}],"version-history":[{"count":7,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/82\/revisions"}],"predecessor-version":[{"id":91,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/82\/revisions\/91"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/media\/30"}],"wp:attachment":[{"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=82"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=82"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=82"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}