{"id":51,"date":"2021-10-06T15:57:42","date_gmt":"2021-10-06T07:57:42","guid":{"rendered":"http:\/\/www.qddlh.com\/?p=51"},"modified":"2021-10-06T15:57:43","modified_gmt":"2021-10-06T07:57:43","slug":"backtrader-%e5%bf%ab%e9%80%9f%e5%bc%80%e5%a7%8b%ef%bc%88%e7%ac%ac%e4%b8%80%e4%b8%aa%e7%ad%96%e7%95%a5%ef%bc%89","status":"publish","type":"post","link":"https:\/\/www.qddlh.com\/?p=51","title":{"rendered":"Backtrader-\u5feb\u901f\u5f00\u59cb\uff08\u7b2c\u4e00\u4e2a\u7b56\u7565\uff09"},"content":{"rendered":"\n<p>\u4ea4\u6613\u7528\u7684\u8d44\u91d1\u548c\u5386\u53f2\u6570\u636e\u5df2\u7ecf\u4ea4\u7ed9\u7ecf\u7eaa\u4eba\uff08broker\uff09\uff0c\u8fd8\u53bb\u4e00\u4e2a\u7b56\u7565\uff0c\u544a\u8bc9\u7ecf\u7eaa\u4eba\u6309\u7167\u7b56\u7565\u8fdb\u884c\u4ea4\u6613\u3002\u4e0b\u9762\u5148\u5b9e\u73b0\u4e00\u4e2a\u7b80\u5355\u7684\u7b56\u7565\uff0c\u8ba9\u7ecf\u7eaa\u4eba\u8f93\u51fa\u6bcf\u5929\u4ea4\u6613\u7684\u6536\u76d8\u4ef7<\/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\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#############################################################\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>\u811a\u672c\u6267\u884c\u540e\u8f93\u5165\u5982\u4e0b\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\n...\n...\n2021-09-13, Close, 9.39\r\n2021-09-14, Close, 9.21\r\n2021-09-15, Close, 9.19\r\n2021-09-16, Close, 9.12\r\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-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\nFinal Portfolio Value: 100000.00<\/code><\/pre>\n\n\n\n<p>\u5bf9\u4e0a\u9762 TestStrategy \u7684\u6e90\u7801\u505a\u4e00\u4e9b\u8bf4\u660e\uff1a<\/p>\n\n\n\n<p>1 \u5728\u8c03\u7528 TestStrategy  \u7684 __init__ \u65f6\u5982\u679c\u6ca1\u6709\u7279\u522b\u6307\u5b9a\u53c2\u6570\uff0c\u5c31\u5df2\u7ecf\u52a0\u8f7d\u6240\u6709\u9700\u8981\u5206\u6790\u7684\u6570\u636e<\/p>\n\n\n\n<p>2 \u6570\u636e\u7684\u7ec4\u7ec7\u683c\u5f0f\u4e3a\u6807\u51c6\u7684python List\u7ed3\u6784\uff0c\u53ef\u4ee5\u6309\u7167\u4ea4\u6613\u65e5\u987a\u5e8f\u9010\u4e2a\u653e\u5165\u5230\u7b56\u7565\u5bf9\u8c61\u4e2d\u8bbf\u95ee<\/p>\n\n\n\n<p>3 self.datas[0]\u662f\u5f53\u524d\u4ea4\u6613\u65e5\u8bbf\u95ee\u6570\u636e\u5217\u8868\u4e2d\u7684\u7b2c\u4e00\u4e2a\u6570\u636e\uff0c\u4e5f\u662f\u4ea4\u6613\u64cd\u4f5c\u7684\u9ed8\u8ba4\u6570\u636e<\/p>\n\n\n\n<p>4 self.dataclose=self.datas[0].close \u76f4\u63a5\u8bfb\u53d6\u6570\u636e\u884c\u4e2d\u7684\u6536\u76d8\u4ef7\uff0c\u4fdd\u5b58\u5728 dataclose \u6210\u5458\u53d8\u91cf\u4e2d\uff0c\u65b9\u4fbf\u4ee5\u540e\u8bbf\u95ee<\/p>\n\n\n\n<p>5  TestStrategy \u7684next\u65b9\u6cd5\u83b7\u53d6\u5f53\u524d\u4ea4\u6613\u65e5\u7684\u6570\u636e\uff08self.datas[0]\uff09\u3002\u5728\u8fd9\u4e2a\u65b9\u6cd5\u4e2d\u4e3b\u8981\u5b9e\u73b0\u5404\u79cd\u903b\u8f91\u548c\u6307\u6807\u7684\u5b9e\u73b0<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u4ea4\u6613\u7528\u7684\u8d44\u91d1\u548c\u5386\u53f2\u6570\u636e\u5df2\u7ecf\u4ea4\u7ed9\u7ecf\u7eaa\u4eba\uff08broker\uff09\uff0c\u8fd8\u53bb\u4e00\u4e2a\u7b56\u7565\uff0c\u544a\u8bc9\u7ecf\u7eaa\u4eba\u6309\u7167\u7b56\u7565\u8fdb\u884c\u4ea4\u6613\u3002\u4e0b\u9762\u5148\u5b9e\u73b0\u4e00\u4e2a\u7b80\u5355\u7684\u7b56\u7565\uff0c\u8ba9\u7ecf\u7eaa\u4eba\u8f93\u51fa\u6bcf\u5929\u4ea4\u6613\u7684\u6536\u76d8\u4ef7 \u811a\u672c\u6267\u884c\u540e\u8f93\u5165\u5982\u4e0b\uff1a \u5bf9\u4e0a\u9762 TestStrategy \u7684\u6e90\u7801\u505a\u4e00\u4e9b\u8bf4\u660e\uff1a 1 \u5728\u8c03\u7528  [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":30,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[11],"class_list":["post-51","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\/51","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=51"}],"version-history":[{"count":3,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/51\/revisions"}],"predecessor-version":[{"id":55,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=\/wp\/v2\/posts\/51\/revisions\/55"}],"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=51"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=51"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.qddlh.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=51"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}