{"id":60,"date":"2021-10-10T15:22:26","date_gmt":"2021-10-10T07:22:26","guid":{"rendered":"http:\/\/www.qddlh.com\/?p=60"},"modified":"2021-10-10T15:22:26","modified_gmt":"2021-10-10T07:22:26","slug":"backtrader-%e5%bf%ab%e9%80%9f%e5%bc%80%e5%a7%8b%ef%bc%88%e5%a2%9e%e5%8a%a0%e5%8d%96%e5%87%ba%e9%80%bb%e8%be%91%ef%bc%89","status":"publish","type":"post","link":"https:\/\/www.qddlh.com\/?p=60","title":{"rendered":"Backtrader-\u5feb\u901f\u5f00\u59cb\uff08\u589e\u52a0\u5356\u51fa\u903b\u8f91\uff09"},"content":{"rendered":"\n<p>\u5b66\u4e60\u901a\u8fc7\u7b56\u7565\u4e70\u5165\uff0c\u901a\u8fc7\u7b56\u7565\u5356\u51fa\u4e5f\u662f\u4e0d\u53ef\u6216\u7f3a\u7684\u3002\u6846\u67b6\u67093\u4e2a\u529f\u80fd\u4e3a\u4e86\u6211\u4eec\u63d0\u4f9b\u7684\u5b9e\u73b0\u7b56\u7565\u5356\u51fa\u57fa\u7840\uff1a<\/p>\n\n\n\n<p>1 \u53ef\u4ee5\u901a\u8fc7\u504f\u79fb\u6765\u8bbf\u95ee\u6570\u636e\u96c6<\/p>\n\n\n\n<p>2 \u901a\u8fc7\u4e70\u548c\u5356\u7684\u65b9\u6cd5\uff0c\u5b9e\u73b0\u751f\u6210\u5bf9\u5e94\u7684\u8ba2\u5355<\/p>\n\n\n\n<p>3 \u5982\u679c\u8ba2\u5355\u7684\u72b6\u6001\u53d1\u751f\u53d8\u5316\uff0c\u7b56\u7565\u8fd8\u4f1a\u8c03\u7528<em>notify<\/em>\u65b9\u6cd5\uff0c\u901a\u77e5\u81ea\u5df1\u5b9e\u73b0\u540e\u7eed\u5904\u7406<\/p>\n\n\n\n<p>\u8fd9\u91cc\u5148\u5b9e\u73b0\u4e00\u4e2a\u7b80\u5355\u7684\u7b56\u7565\uff1a<\/p>\n\n\n\n<p>\u65e0\u8bba\u6da8\u8dcc\uff0c\u662f\u5426\u8d5a\u94b1\u6216\u8005\u4e8f\u635f\uff0c\u8fc75\u4e2a\u4ea4\u6613\u65e5\u540e\u5356\u51fa<\/p>\n\n\n\n<p>\u4e3a\u4e86\u7b80\u5355\u547d\u4ee4\uff0c\u8fd9\u91cc\u505a\u4e00\u4e2a\u7ea6\u5b9a\uff0c\u53ea\u6709\u7a7a\u4ed3\u7684\u65f6\u5019\u624d\u80fd\u8d2d\u4e70\uff0c\u5982\u8fc7\u6709\u6301\u80a1\u7684\u60c5\u51b5\u4e0b\u5c31\u4e0d\u4f1a\u6267\u884c\u4e70\u5165<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># -*- coding: utf-8 -*-\r\n\"\"\"\r\nbacktrader\u624b\u518c\u6837\u4f8b\u4ee3\u7801\r\n@author: \u4e00\u5757\u81ea\u7531\u7684\u7816\r\n\"\"\"\r\n#############################################################\r\n#import\r\n#############################################################\r\nfrom __future__ import (absolute_import, division, print_function,\r\n                        unicode_literals)\r\nimport os,sys\r\nimport pandas as pd\r\nimport backtrader as bt\r\n#############################################################\r\n#global const values\r\n#############################################################\r\n#############################################################\r\n#static function\r\n#############################################################\r\n#############################################################\r\n#class\r\n#############################################################\r\n# Create a Stratey\r\nclass TestStrategy(bt.Strategy):\r\n    def log(self, txt, dt=None):\r\n        ''' Logging function for this strategy\uff0c\u8fd9\u91cc\u5b9a\u4e49\u65e5\u5fd7\u7684\u663e\u793a\u683c\u5f0f'''\r\n        dt = dt or self.datas&#91;0].datetime.date(0)\r\n        print('%s, %s' % (dt.isoformat(), txt))\r\n\r\n    def __init__(self):\r\n        # Keep a reference to the \"close\" line in the data&#91;0] dataseries\uff08\u83b7\u53d6\u6536\u76d8\u4ef7\uff09\r\n        self.dataclose = self.datas&#91;0].close\r\n        # To keep track of pending orders\r\n        self.order = None\r\n    \r\n    def notify_order(self, order):\r\n        if order.status in &#91;order.Submitted, order.Accepted]:\r\n            # Buy\/Sell order submitted\/accepted to\/by broker - Nothing to do\r\n            return\r\n        # Check if an order has been completed\r\n        # Attention: broker could reject order if not enough cash\r\n        if order.status in &#91;order.Completed]:\r\n            if order.isbuy():\r\n                self.log('BUY EXECUTED, %.2f' % order.executed.price)\r\n            elif order.issell():\r\n                self.log('SELL EXECUTED, %.2f' % order.executed.price)\r\n\r\n            self.bar_executed = len(self)\r\n\r\n        elif order.status in &#91;order.Canceled, order.Margin, order.Rejected]:\r\n            self.log('Order Canceled\/Margin\/Rejected')\r\n\r\n        # Write down: no pending order\r\n        self.order = None\r\n\r\n    def next(self):\r\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\r\n        self.log('Close, %.2f' % self.dataclose&#91;0])\r\n        # Check if an order is pending ... if yes, we cannot send a 2nd one\r\n        if self.order:\r\n            return\r\n        # Check if we are in the market\uff08\u68c0\u67e5\u662f\u5426\u6301\u80a1\uff09\r\n        if not self.position:\r\n            # \u5224\u5b9a\u5f53\u524d\u4ea4\u6613\u65e5\u7684\u6536\u76d8\u4ef7\u662f\u5426\u5c0f\u4e8e\u6628\u65e5\u7684\r\n            if self.dataclose&#91;0] &lt; self.dataclose&#91;-1]:\r\n                # current close less than previous close\uff08\u5224\u5b9a\u6628\u65e5\u7684\u6536\u76d8\u4ef7\u662f\u5426\u5c0f\u4e8e\u524d\u65e5\u7684\uff09\r\n                if self.dataclose&#91;-1] &lt; self.dataclose&#91;-2]:\r\n                    # previous close less than the previous close\r\n                    # BUY, BUY, BUY!!! \u89e6\u53d1\u8d2d\u4e70\u52a8\u4f5c\r\n                    self.log('BUY CREATE, %.2f' % self.dataclose&#91;0])\r\n                    # Keep track of the created order to avoid a 2nd order\r\n                    self.order = self.buy()\r\n        else:\r\n            # Already in the market ... we might sell\uff0c\u6301\u80a1\u68c0\u67e5\u662f\u5426\u5df2\u7ecf\u5927\u4e8e5\u4e2a\u4ea4\u6613\u65e5\r\n            if len(self) >= (self.bar_executed + 5):\r\n                # SELL, SELL, SELL!!! (with all possible default parameters)\r\n                self.log('SELL CREATE, %.2f' % self.dataclose&#91;0])\r\n\r\n                # Keep track of the created order to avoid a 2nd order\r\n                self.order = self.sell()\r\n#############################################################\r\n#global values\r\n#############################################################\r\n#############################################################\r\n#global function\r\n#############################################################\r\n# \u901a\u8fc7\u8bfb\u53d6cvs\u6587\u4ef6\uff0c\u83b7\u53d6\u60f3\u8981\u7684\u6570\u636e\r\ndef get_dataframe():\r\n    # Get a pandas dataframe\uff08\u8fd9\u91cc\u662f\u80a1\u7968\u6570\u636e\u6587\u4ef6\u653e\u7684\u76ee\u5f55\u8def\u5f84\uff09\r\n    datapath = 'qtbt\\data\\stockinfo.csv'\r\n    # \u6570\u636e\u8f6c\u6362\u7528\u4e34\u65f6\u6587\u4ef6\u8def\u5f84\u548c\u540d\u79f0\uff0c\u7528\u5b8c\u540e\u5220\u9664\r\n    tmpdatapath = datapath + '.tmp'\r\n    print('-----------------------read csv---------------------------')\r\n    dataframe = pd.read_csv(datapath,\r\n                                skiprows=0,\r\n                                header=0,\r\n                                parse_dates=True,\r\n                                index_col=0)\r\n    # \u5b9a\u4e49\u4ea4\u6613\u65e5\u671f\u683c\u5f0f\r\n    dataframe.trade_date =  pd.to_datetime(dataframe.trade_date, format=\"%Y%m%d\")\r\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\r\n    dataframe&#91;'openinterest'] = '0'\r\n    feedsdf = dataframe&#91;&#91;'trade_date', 'open', 'high', 'low', 'close', 'vol', 'openinterest']]\r\n    feedsdf.columns =&#91;'datetime', 'open', 'high', 'low', 'close', 'volume', 'openinterest']\r\n    # \u6309\u7167\u4ea4\u6613\u65e5\u671f\u5347\u5e8f\u6392\u5217\r\n    feedsdf.set_index(keys='datetime', inplace =True)\r\n    # \u751f\u6210\u4e34\u65f6\u6587\u4ef6\r\n    feedsdf.iloc&#91;::-1].to_csv(tmpdatapath)\r\n    # \u83b7\u53d6\u9700\u8981\u4f7f\u7528\u7684\u6570\u636e\r\n    feedsdf = pd.read_csv(tmpdatapath, skiprows=0, header=0, parse_dates=True, index_col=0)\r\n    # \u5220\u9664tmp\u4e34\u65f6\u6587\u4ef6\r\n    if os.path.isfile(tmpdatapath):\r\n        os.remove(tmpdatapath)\r\n        print(tmpdatapath+\" removed!\")\r\n    # \u8fd4\u56de\u9700\u8981\u7684\u6570\u636e\r\n    return feedsdf\r\n########################################################################\r\n#main\r\n########################################################################\r\nif __name__ == '__main__':\r\n    # Create a cerebro entity(\u521b\u5efacerebro)\r\n    cerebro = bt.Cerebro()\r\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)\r\n    cerebro.addstrategy(TestStrategy)\r\n    # Get a pandas dataframe(\u83b7\u53d6dataframe\u683c\u5f0f\u80a1\u7968\u6570\u636e)\r\n    feedsdf = get_dataframe()\r\n    # Pass it to the backtrader datafeed and add it to the cerebro(\u52a0\u5165\u6570\u636e)\r\n    data = bt.feeds.PandasData(dataname=feedsdf)\r\n    # \u52a0\u5165\u6570\u636e\u5230Cerebro\r\n    cerebro.adddata(data)\r\n    # Add a FixedSize sizer according to the stake(\u56fd\u51851\u624b\u662f100\u80a1\uff0c\u6700\u5c0f\u7684\u4ea4\u6613\u5355\u4f4d)\r\n    cerebro.addsizer(bt.sizers.FixedSize, stake=100)\r\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)\r\n    cerebro.broker.setcash(100000.0)\r\n    # Print out the starting conditions(\u8f93\u51fa\u8d26\u6237\u91d1\u989d)\r\n    print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())\r\n    # Run over everything(\u6267\u884c\u56de\u6d4b)\r\n    cerebro.run()\r\n    # Print out the final result(\u8f93\u51fa\u8d26\u6237\u91d1\u989d)\r\n    print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())\r\n\r\n<\/code><\/pre>\n\n\n\n<p>\u6267\u884c\u540e\u8f93\u51fa\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>-----------------------read csv---------------------------\r\nqtbt\\data\\stockinfo.csv.tmp removed!\r\nStarting Portfolio Value: 100000.00 \r\n2020-01-02, Close, 12.47\r\n2020-01-03, Close, 12.60\r\n2020-01-06, Close, 12.46\r\n2020-01-07, Close, 12.50\r\n2020-01-08, Close, 12.32\r\n2020-01-09, Close, 12.37\r\n2020-01-10, Close, 12.39\r\n2020-01-13, Close, 12.41\r\n2020-01-14, Close, 12.43\r\n2020-01-15, Close, 12.25\r\n2020-01-16, Close, 12.20\r\n2020-01-16, BUY CREATE, 12.20\r\n2020-01-17, BUY EXECUTED, 12.22\n...\n...\n2021-09-17, Close, 9.11\r\n2021-09-22, Close, 9.03\r\n2021-09-23, Close, 9.03\r\n2021-09-24, Close, 9.02\r\n2021-09-24, SELL CREATE, 9.02\r\n2021-09-27, SELL EXECUTED, 9.02\r\n2021-09-27, Close, 9.02\r\n2021-09-28, Close, 9.03\r\n2021-09-29, Close, 9.02\r\n2021-09-30, Close, 9.00\r\n2021-09-30, BUY CREATE, 9.00\r\nFinal Portfolio Value: 99810.00<\/code><\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5b66\u4e60\u901a\u8fc7\u7b56\u7565\u4e70\u5165\uff0c\u901a\u8fc7\u7b56\u7565\u5356\u51fa\u4e5f\u662f\u4e0d\u53ef\u6216\u7f3a\u7684\u3002\u6846\u67b6\u67093\u4e2a\u529f\u80fd\u4e3a\u4e86\u6211\u4eec\u63d0\u4f9b\u7684\u5b9e\u73b0\u7b56\u7565\u5356\u51fa\u57fa\u7840\uff1a 1 \u53ef\u4ee5\u901a\u8fc7\u504f\u79fb\u6765\u8bbf\u95ee\u6570\u636e\u96c6 2 \u901a\u8fc7\u4e70\u548c\u5356\u7684\u65b9\u6cd5\uff0c\u5b9e\u73b0\u751f\u6210\u5bf9\u5e94\u7684\u8ba2\u5355 3 \u5982\u679c\u8ba2\u5355\u7684\u72b6\u6001\u53d1\u751f\u53d8\u5316\uff0c\u7b56\u7565\u8fd8\u4f1a\u8c03\u7528notify\u65b9\u6cd5\uff0c\u901a\u77e5\u81ea\u5df1\u5b9e\u73b0\u540e\u7eed [&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-60","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\/60","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=60"}],"version-history":[{"count":2,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/60\/revisions"}],"predecessor-version":[{"id":76,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/60\/revisions\/76"}],"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=60"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=60"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=60"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}