{"id":77,"date":"2021-10-16T10:38:40","date_gmt":"2021-10-16T02:38:40","guid":{"rendered":"http:\/\/www.qddlh.com\/?p=77"},"modified":"2021-10-16T10:38:40","modified_gmt":"2021-10-16T02:38:40","slug":"backtrader-%e5%bf%ab%e9%80%9f%e5%bc%80%e5%a7%8b%ef%bc%88%e5%a2%9e%e5%8a%a0%e4%ba%a4%e6%98%93%e6%89%80%e6%89%8b%e7%bb%ad%e8%b4%b9-%e4%bd%a3%e9%87%91%ef%bc%89","status":"publish","type":"post","link":"https:\/\/www.qddlh.com\/?p=77","title":{"rendered":"Backtrader-\u5feb\u901f\u5f00\u59cb\uff08\u589e\u52a0\u4ea4\u6613\u6240\u624b\u7eed\u8d39\/\u4f63\u91d1\uff09"},"content":{"rendered":"\n<p>\u5b98\u65b9\u6587\u6863\u7684\u6807\u9898\u662f\uff1ashow me the money\u3002\u5b9e\u9645\u4e0a\u4ea4\u6613\u6240\u662f\u8981\u6536\u53d6\u624b\u7eed\u8d39\u7684\u3002\u7ed9\u7684\u5b9e\u9645\u4f8b\u5b50\u548c\u56fd\u5185\u5dee\u4e0d\u591a\uff0c\u4e70\u5356\u90fd\u6536\u53d60.1%\u7684\u624b\u7eed\u8d39\uff0c\u5c31\u662f\u6240\u8c13\u7684\u5343\u5206\u4e4b\u4e00\u3002\u5f53\u7136\u56fd\u5185\u4e0d\u540c\u7684\u4eba\u4f1a\u6709\u6240\u53d8\u5316\uff0c\u5177\u4f53\u770b\u5f53\u65f6\u7b7e\u7684\u5408\u540c\u3002<\/p>\n\n\n\n<p>\u5b9e\u73b0\u65b9\u5f0f\u7279\u522b\u7b80\u5355\uff0c\u5728\u4e3b\u51fd\u6570\u4e2d\u589e\u52a0\u4e00\u884c\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># 0.1% ... divide by 100 to remove the %\ncerebro.broker.setcommission(commission=0.001)<\/code><\/pre>\n\n\n\n<p>\u8fd9\u91cc\u8981\u6ce8\u610f\uff0c\u54b1\u4eec\u770b\u5230\u7684\u6536\u76ca\u6216\u8005\u4e8f\u635f\u7684\u94b1\u6570\uff0c\u4e0d\u5305\u542b\u8fd9\u4e2a\u624b\u7eed\u8d39\u3002<\/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    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\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 + 5):\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\u540e\uff0c\u8f93\u51fa\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>-----------------------read csv---------------------------\nqtbt\\data\\stockinfo.csv.tmp removed!\nStarting Portfolio Value: 100000.00\n2020-01-02, Close, 12.47\n2020-01-03, Close, 12.60\n2020-01-06, Close, 12.46\n2020-01-07, Close, 12.50\n2020-01-08, Close, 12.32\n2020-01-09, Close, 12.37\n2020-01-10, Close, 12.39\n2020-01-13, Close, 12.41\n2020-01-14, Close, 12.43\n2020-01-15, Close, 12.25\n2020-01-16, Close, 12.20\n2020-01-16, BUY CREATE, 12.20\n2020-01-17, BUY EXECUTED, Price: 12.22, Cost: 1222.00, Comm 1.22\n2020-01-17, Close, 12.23\n2020-01-20, Close, 12.25\n2020-01-21, Close, 12.08\n2020-01-22, Close, 11.77\n...\n...\n2021-09-14, BUY CREATE, 9.21\n2021-09-15, BUY EXECUTED, Price: 9.21, Cost: 921.00, Comm 0.92\n2021-09-15, Close, 9.19\n2021-09-16, Close, 9.12\n2021-09-17, Close, 9.11\n2021-09-22, Close, 9.03\n2021-09-23, Close, 9.03\n2021-09-24, Close, 9.02\n2021-09-24, SELL CREATE, 9.02\n2021-09-27, SELL EXECUTED, Price: 9.02, Cost: 921.00, Comm 0.90\n2021-09-27, OPERATION PROFIT, GROSS -19.00, NET -20.82\n2021-09-27, Close, 9.02\n2021-09-28, Close, 9.03\n2021-09-29, Close, 9.02\n2021-09-30, Close, 9.00\n2021-09-30, BUY CREATE, 9.00\nFinal Portfolio Value: 99734.77<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u5b98\u65b9\u6587\u6863\u7684\u6807\u9898\u662f\uff1ashow me the money\u3002\u5b9e\u9645\u4e0a\u4ea4\u6613\u6240\u662f\u8981\u6536\u53d6\u624b\u7eed\u8d39\u7684\u3002\u7ed9\u7684\u5b9e\u9645\u4f8b\u5b50\u548c\u56fd\u5185\u5dee\u4e0d\u591a\uff0c\u4e70\u5356\u90fd\u6536\u53d60.1%\u7684\u624b\u7eed\u8d39\uff0c\u5c31\u662f\u6240\u8c13\u7684\u5343\u5206\u4e4b\u4e00\u3002\u5f53\u7136\u56fd\u5185\u4e0d\u540c\u7684\u4eba\u4f1a\u6709\u6240\u53d8\u5316\uff0c\u5177\u4f53\u770b\u5f53\u65f6\u7b7e\u7684\u5408\u540c\u3002 \u5b9e\u73b0\u65b9\u5f0f\u7279\u522b\u7b80\u5355\uff0c\u5728\u4e3b\u51fd\u6570\u4e2d\u589e\u52a0 [&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-77","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\/77","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=77"}],"version-history":[{"count":3,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/77\/revisions"}],"predecessor-version":[{"id":81,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/77\/revisions\/81"}],"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=77"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=77"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=77"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}