Browse Source

跳过数据不全的个股,避免中断

daniel 2 years ago
parent
commit
cb4f2beee3
2 changed files with 130 additions and 123 deletions
  1. 64 61
      backtrader/230218_backtrader.py
  2. 66 62
      backtrader/230219_backtrader.py

+ 64 - 61
backtrader/230218_backtrader.py

@@ -196,68 +196,71 @@ def backtrader(list_date, table_list, result, result_change, result_change_fall,
         # print(stock)
         stk_df = pd.read_sql_table(stock, engine)
         stk_df.time = pd.to_datetime(stk_df.time)
-        stk_df['HL'] = stk_df['HL'].map({'L': 1,
-                                         'LL': 2,
-                                         'L*': 3,
-                                         'H': 4,
-                                         'HH': 5,
-                                         'H*': 6,
-                                         '-': 7})
-
-        if len(stk_df) > 60:
-            cerebro = bt.Cerebro()
-            cerebro.addstrategy(TestStrategy, num=num, Volatility=Volatility, rate=rate)
-            cerebro.addsizer(bt.sizers.FixedSize, stake=10000)
-            data = MyPandasData(dataname=stk_df,
-                                fromdate=datetime.datetime(2017, 1, 1),
-                                todate=datetime.datetime(2022, 10, 30),
-                                datetime='time',
-                                open='open_back',
-                                close='close_back',
-                                high='high_back',
-                                low='low_back',
-                                volume='volume_back',
-                                hl='HL',
-                                dif='dif',
-                                dea='dea',
-                                macd='macd',
-                                rsi_6='rsi_6',
-                                rsi_12='rsi_12',
-                                rsi_24='rsi_24',
-                                # change,_pct='change_pct',
-                                # net_amount_main='net_amount_main',
-                                # net_pct_main='net_pct_main',
-                                # net_amount_xl='net_amount_xl',
-                                # net_pct_xl='net_pct_xl',
-                                # net_amount_l='net_amount_l',
-                                # net_pct_l='net_pct_l',
-                                # net_amount_m='net_amount_m',
-                                # net_pct_m='net_pct_m',
-                                # net_amount_s='net_amount_s',
-                                # net_pct_s='net_pct_s',
-                                )
-            # print('取值完成')
-            cerebro.adddata(data, name=stock)
-            cerebro.broker.setcash(100000.0)
-            cerebro.broker.setcommission(0.005)
-            cerebro.addanalyzer(bt.analyzers.PyFolio)
-            # 策略执行前的资金
-            # print('启动资金: %.2f' % cerebro.broker.getvalue())
-            try:
-                # 策略执行
-                cerebro.run()
-            except IndexError:
-                err_list.append(stock)
-            else:
-                if cerebro.broker.getvalue() > 100000.0:
-                    result_change.append((cerebro.broker.getvalue() / 10000 - 1))
-                    result.append(stock)
-                    # print('recode!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
-                    # print(result)
+        try:
+            stk_df['HL'] = stk_df['HL'].map({'L': 1,
+                                             'LL': 2,
+                                             'L*': 3,
+                                             'H': 4,
+                                             'HH': 5,
+                                             'H*': 6,
+                                             '-': 7})
+        except BaseException:
+            print(stock, 'HL 可能没有')
+        else:
+            if len(stk_df) > 60:
+                cerebro = bt.Cerebro()
+                cerebro.addstrategy(TestStrategy, num=num, Volatility=Volatility, rate=rate)
+                cerebro.addsizer(bt.sizers.FixedSize, stake=10000)
+                data = MyPandasData(dataname=stk_df,
+                                    fromdate=datetime.datetime(2017, 1, 1),
+                                    todate=datetime.datetime(2022, 10, 30),
+                                    datetime='time',
+                                    open='open_back',
+                                    close='close_back',
+                                    high='high_back',
+                                    low='low_back',
+                                    volume='volume_back',
+                                    hl='HL',
+                                    dif='dif',
+                                    dea='dea',
+                                    macd='macd',
+                                    rsi_6='rsi_6',
+                                    rsi_12='rsi_12',
+                                    rsi_24='rsi_24',
+                                    # change,_pct='change_pct',
+                                    # net_amount_main='net_amount_main',
+                                    # net_pct_main='net_pct_main',
+                                    # net_amount_xl='net_amount_xl',
+                                    # net_pct_xl='net_pct_xl',
+                                    # net_amount_l='net_amount_l',
+                                    # net_pct_l='net_pct_l',
+                                    # net_amount_m='net_amount_m',
+                                    # net_pct_m='net_pct_m',
+                                    # net_amount_s='net_amount_s',
+                                    # net_pct_s='net_pct_s',
+                                    )
+                # print('取值完成')
+                cerebro.adddata(data, name=stock)
+                cerebro.broker.setcash(100000.0)
+                cerebro.broker.setcommission(0.005)
+                cerebro.addanalyzer(bt.analyzers.PyFolio)
+                # 策略执行前的资金
+                # print('启动资金: %.2f' % cerebro.broker.getvalue())
+                try:
+                    # 策略执行
+                    cerebro.run()
+                except IndexError:
+                    err_list.append(stock)
                 else:
-                    result_change_fall.append((1 - cerebro.broker.getvalue() / 10000))
-                    # print('aaaaaaaaaaa')
-                    # print(result_change_fall)
+                    if cerebro.broker.getvalue() > 100000.0:
+                        result_change.append((cerebro.broker.getvalue() / 10000 - 1))
+                        result.append(stock)
+                        # print('recode!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
+                        # print(result)
+                    else:
+                        result_change_fall.append((1 - cerebro.broker.getvalue() / 10000))
+                        # print('aaaaaaaaaaa')
+                        # print(result_change_fall)
 
     if len(result) * len(result_change) * len(result_change_fall) != 0:
         print(f'以{num}内最低值波动{Volatility}为支撑、量能增长率为{rate}%,结果状态为:')

+ 66 - 62
backtrader/230219_backtrader.py

@@ -145,9 +145,10 @@ class TestStrategy(bt.Strategy):
                     and self.low[-1] > self.low[0] and self.high[-1] < self.high[0]:
                 self.order = self.buy()
                 self.pos_price = self.low[-1]
-            elif self.hl[0] == 5 and ((highest * (1 - vola)) < self.high[-2] < (highest * (1 + vola))) \
+            elif (self.hl[0] == 5 and ((highest * (1 - vola)) < self.high[-2] < (highest * (1 + vola)))) \
                     or self.dataclose[0] < self.pos_price:
                 self.order = self.close()
+                self.pos_price = 0
         '''
                 if len(self) > self.params.num:
             lowest = np.min(self.low.get(size=self.params.num))
@@ -199,68 +200,71 @@ def backtrader(list_date, table_list, result, result_change, result_change_fall,
         # print(stock)
         stk_df = pd.read_sql_table(stock, engine)
         stk_df.time = pd.to_datetime(stk_df.time)
-        stk_df['HL'] = stk_df['HL'].map({'L': 1,
-                                         'LL': 2,
-                                         'L*': 3,
-                                         'H': 4,
-                                         'HH': 5,
-                                         'H*': 6,
-                                         '-': 7})
-
-        if len(stk_df) > 60:
-            cerebro = bt.Cerebro()
-            cerebro.addstrategy(TestStrategy, num=num, Volatility=Volatility, rate=rate)
-            cerebro.addsizer(bt.sizers.FixedSize, stake=10000)
-            data = MyPandasData(dataname=stk_df,
-                                fromdate=datetime.datetime(2017, 1, 1),
-                                todate=datetime.datetime(2022, 10, 30),
-                                datetime='time',
-                                open='open_back',
-                                close='close_back',
-                                high='high_back',
-                                low='low_back',
-                                volume='volume_back',
-                                hl='HL',
-                                dif='dif',
-                                dea='dea',
-                                macd='macd',
-                                rsi_6='rsi_6',
-                                rsi_12='rsi_12',
-                                rsi_24='rsi_24',
-                                # change,_pct='change_pct',
-                                # net_amount_main='net_amount_main',
-                                # net_pct_main='net_pct_main',
-                                # net_amount_xl='net_amount_xl',
-                                # net_pct_xl='net_pct_xl',
-                                # net_amount_l='net_amount_l',
-                                # net_pct_l='net_pct_l',
-                                # net_amount_m='net_amount_m',
-                                # net_pct_m='net_pct_m',
-                                # net_amount_s='net_amount_s',
-                                # net_pct_s='net_pct_s',
-                                )
-            # print('取值完成')
-            cerebro.adddata(data, name=stock)
-            cerebro.broker.setcash(100000.0)
-            cerebro.broker.setcommission(0.005)
-            cerebro.addanalyzer(bt.analyzers.PyFolio)
-            # 策略执行前的资金
-            # print('启动资金: %.2f' % cerebro.broker.getvalue())
-            try:
-                # 策略执行
-                cerebro.run()
-            except IndexError:
-                err_list.append(stock)
-            else:
-                if cerebro.broker.getvalue() > 100000.0:
-                    result_change.append((cerebro.broker.getvalue() / 10000 - 1))
-                    result.append(stock)
-                    # print('recode!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
-                    # print(result)
+        try:
+            stk_df['HL'] = stk_df['HL'].map({'L': 1,
+                                             'LL': 2,
+                                             'L*': 3,
+                                             'H': 4,
+                                             'HH': 5,
+                                             'H*': 6,
+                                             '-': 7})
+        except BaseException:
+            print(f'{stock}数据不全,不做测试')
+        else:
+            if len(stk_df) > 60:
+                cerebro = bt.Cerebro()
+                cerebro.addstrategy(TestStrategy, num=num, Volatility=Volatility, rate=rate)
+                cerebro.addsizer(bt.sizers.FixedSize, stake=10000)
+                data = MyPandasData(dataname=stk_df,
+                                    fromdate=datetime.datetime(2017, 1, 1),
+                                    todate=datetime.datetime(2022, 10, 30),
+                                    datetime='time',
+                                    open='open_back',
+                                    close='close_back',
+                                    high='high_back',
+                                    low='low_back',
+                                    volume='volume_back',
+                                    hl='HL',
+                                    dif='dif',
+                                    dea='dea',
+                                    macd='macd',
+                                    rsi_6='rsi_6',
+                                    rsi_12='rsi_12',
+                                    rsi_24='rsi_24',
+                                    # change,_pct='change_pct',
+                                    # net_amount_main='net_amount_main',
+                                    # net_pct_main='net_pct_main',
+                                    # net_amount_xl='net_amount_xl',
+                                    # net_pct_xl='net_pct_xl',
+                                    # net_amount_l='net_amount_l',
+                                    # net_pct_l='net_pct_l',
+                                    # net_amount_m='net_amount_m',
+                                    # net_pct_m='net_pct_m',
+                                    # net_amount_s='net_amount_s',
+                                    # net_pct_s='net_pct_s',
+                                    )
+                # print('取值完成')
+                cerebro.adddata(data, name=stock)
+                cerebro.broker.setcash(100000.0)
+                cerebro.broker.setcommission(0.005)
+                cerebro.addanalyzer(bt.analyzers.PyFolio)
+                # 策略执行前的资金
+                # print('启动资金: %.2f' % cerebro.broker.getvalue())
+                try:
+                    # 策略执行
+                    cerebro.run()
+                except IndexError:
+                    err_list.append(stock)
                 else:
-                    result_change_fall.append((1 - cerebro.broker.getvalue() / 10000))
-                    # print('aaaaaaaaaaa')
-                    # print(result_change_fall)
+                    if cerebro.broker.getvalue() > 100000.0:
+                        result_change.append((cerebro.broker.getvalue() / 10000 - 1))
+                        result.append(stock)
+                        # print('recode!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
+                        # print(result)
+                    else:
+                        result_change_fall.append((1 - cerebro.broker.getvalue() / 10000))
+                        # print('aaaaaaaaaaa')
+                        # print(result_change_fall)
 
     if len(result) * len(result_change) * len(result_change_fall) != 0:
         print(f'以{num}内最低值波动{Volatility}为支撑、量能增长率为{rate}%,结果状态为:')