{"id":56,"date":"2021-10-07T21:22:52","date_gmt":"2021-10-07T13:22:52","guid":{"rendered":"http:\/\/www.qddlh.com\/?p=56"},"modified":"2021-10-07T21:22:52","modified_gmt":"2021-10-07T13:22:52","slug":"backtrader-%e5%bf%ab%e9%80%9f%e5%bc%80%e5%a7%8b%ef%bc%88%e7%bb%99%e7%ad%96%e7%95%a5%e5%a2%9e%e5%8a%a0%e9%80%bb%e8%be%91%ef%bc%89","status":"publish","type":"post","link":"https:\/\/www.qddlh.com\/?p=56","title":{"rendered":"Backtrader-\u5feb\u901f\u5f00\u59cb\uff08\u7ed9\u7b56\u7565\u589e\u52a0\u903b\u8f91\uff09"},"content":{"rendered":"\n<p>\u672c\u7ae0\u8282\u5728\u7b56\u7565\u4e2d\u52a0\u5165\u5982\u679c\u6536\u76d8\u4ef7\u4e09\u8fde\u8dcc\u5c31\u8ba9\u7ecf\u7eaa\u4eba\uff08broker\uff09\u8d2d\u4e70\u80a1\u7968\u7684\u903b\u8f91<\/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\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        # \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\u8d2d\u4e70\u7528\u6536\u76d8\u4ef7\u8d2d\u4e70\n                self.log('BUY CREATE, %.2f' % self.dataclose&#91;0])\n                self.buy()\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    # 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\u7684\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\n...\n...\n2021-09-17, BUY CREATE, 9.11\n2021-09-22, Close, 9.03\n2021-09-22, BUY CREATE, 9.03\n2021-09-23, Close, 9.03\n2021-09-24, Close, 9.02\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<\/code><\/pre>\n\n\n\n<p>\u5173\u4e8e\u4e0a\u9762\u7684\u4ee3\u7801\uff0c\u867d\u7136\u7ed9\u80a1\u7968\u7ecf\u7eaa\u4eba\u53d1\u51fa\u4e86\u8d2d\u4e70\u7684\u6307\u4ee4\uff0c\u4f46\u662f\u4e0d\u77e5\u9053\u662f\u5426\u6267\u884c\uff0c\u4f55\u65f6\u6267\u884c\uff0c\u6267\u884c\u8d2d\u4e70\u4ef7\u683c\u5982\u4f55\u3002\u540c\u6837\u8d2d\u4e70\u591a\u5c11\u80a1\u7968\uff0c\u4e70\u4ec0\u4e48\u80a1\u7968\uff0c\u8ba2\u5355\u662f\u5982\u4f55\u6267\u884c\u7684\u4e5f\u6ca1\u6709\u8bf4\u660e\u3002\u5982\u679c\u6ca1\u6709\u6307\u5b9a\u7cfb\u7edf\u4f1a\u4ee5\u5f53\u524d\u4ea4\u6613\u65e5\u7684\u6570\u636e\u4ee5\u4e0b\u4e00\u4e2a\u4ea4\u6613\u65e5\u7684\u5f00\u76d8\u4ef7\u8d2d\u4e701\u624b\u80a1\u7968\u3002\u867d\u7136\u8d2d\u4e70\u4e86\uff0c\u5927\u5bb6\u90fd\u77e5\u9053\u80a1\u7968\u4ea4\u6613\u662f\u6709\u4f63\u91d1\u548c\u5370\u82b1\u7a0e\u7684\uff0c\u8fd9\u91cc\u4e5f\u6ca1\u6709\u8bbe\u5b9a\u4efb\u4f55\u7684\u4f63\u91d1\u3002\u8fd9\u4e2a\u9700\u8981\u4e0b\u4e00\u4e2a\u7bc7\u6587\u7ae0\u5b8c\u5584\u3002<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u672c\u7ae0\u8282\u5728\u7b56\u7565\u4e2d\u52a0\u5165\u5982\u679c\u6536\u76d8\u4ef7\u4e09\u8fde\u8dcc\u5c31\u8ba9\u7ecf\u7eaa\u4eba\uff08broker\uff09\u8d2d\u4e70\u80a1\u7968\u7684\u903b\u8f91 \u6267\u884c\u540e\u7684\u8f93\u51fa\uff1a \u5173\u4e8e\u4e0a\u9762\u7684\u4ee3\u7801\uff0c\u867d\u7136\u7ed9\u80a1\u7968\u7ecf\u7eaa\u4eba\u53d1\u51fa\u4e86\u8d2d\u4e70\u7684\u6307\u4ee4\uff0c\u4f46\u662f\u4e0d\u77e5\u9053\u662f\u5426\u6267\u884c\uff0c\u4f55\u65f6\u6267\u884c\uff0c\u6267\u884c\u8d2d\u4e70\u4ef7\u683c\u5982\u4f55\u3002\u540c\u6837\u8d2d\u4e70\u591a\u5c11\u80a1\u7968\uff0c\u4e70\u4ec0\u4e48\u80a1\u7968\uff0c\u8ba2\u5355\u662f\u5982\u4f55\u6267\u884c\u7684\u4e5f\u6ca1 [&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-56","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\/56","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=56"}],"version-history":[{"count":3,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/56\/revisions"}],"predecessor-version":[{"id":59,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/56\/revisions\/59"}],"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=56"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=56"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=56"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}