Esempio n. 1
0
    def daily2(self):
        if not w.isconnected():
            w.start()
        conn = sqlite3.connect(DATABASE, isolation_level=None, timeout=3)
        cur = conn.cursor()
        cur.execute('''select code from Strategy_s''')
        # 获取数据库中维护的股票代码
        codes = (code[0] for code in cur.fetchall())
        # 仅保留美股代码
        codes = tuple(filter(lambda x: not x[0].isdigit() and x != hsi, codes))
        # 获取今日日期时间戳,需要用美国东部时区的时间
        today = date.today()
        # 如果今天是北京时间周一
        if not today.weekday():
            # 换算成美国东部时间的上周五,减去三天
            stamp = today - timedelta(days=3)
        else:
            # 换算成美国时间的上个交易日,减去一天
            stamp = today - timedelta(days=1)
        stamp = stamp.strftime("%Y-%m-%d")
        # 格式化今日时间戳
        locale.setlocale(locale.LC_CTYPE, "chinese")
        stampf = "{}年{}月{}日 tz=US/Eastern".format(*stamp.split("-"))
        self.chgList = []
        high_p = w.wsd(",".join(codes), "high", stamp, stamp).Data[0]
        low_p = w.wsd(",".join(codes), "low", stamp, stamp).Data[0]
        # high_p = w.wsd(",".join(codes), "high", '2018-11-27', '2018-11-27').Data[0]
        # low_p = w.wsd(",".join(codes), "low", "2018-11-27", "2018-11-27").Data[0]
        for dd in codes:
            # 提取总表中信息
            # 取出今天数据
            dd_i = codes.index(dd)
            high = high_p[dd_i]
            low = low_p[dd_i]
            if not high or not low or high == nan or low == nan:
                continue
            print("正在更新:" + dd)
            cur.execute(f'''select * from Strategy_s where code="{dd}"''')
            dd_dict = dict(zip(Col_stg, cur.fetchone()))
            stock_tb = code_helper(dd)
            trd = dd_dict["trend"]
            hl = dd_dict["next_hl"]
            temp_hl = dd_dict["temp_hl"]
            temp_m = dd_dict['temp_m']
            from_hl = dd_dict["from_hl"]
            from_temp = dd_dict["from_temp"]
            use_space = dd_dict["use_space"]
            space_h = dd_dict["space_h"]
            space_l = dd_dict["space_l"]
            # 取出高点数据
            cur.execute(
                f'''select price from "{stock_tb}" where hl='H' order by date'''
            )
            highs = [h[0] for h in cur.fetchall()]
            pre_high = highs[-1]
            pre2_high = highs[-2]
            # 取出低点数据
            cur.execute(
                f'''select price from "{stock_tb}" where hl='L' order by date'''
            )
            lows = [l[0] for l in cur.fetchall()]
            pre_low = lows[-1]
            pre2_low = lows[-2]
            cur.execute(f'''select hl from "{stock_tb}" order by date''')
            first_hl = cur.fetchone()[0]
            if first_hl == "H":
                n1 = min(len(highs) - 1, len(lows))
                n2 = min(len(highs), len(lows))
                l2h = [(lows[i], highs[i + 1]) for i in range(n1)]
                h2l = [(highs[i], lows[i]) for i in range(n2)]
            else:
                n1 = min(len(highs), len(lows))
                n2 = min(len(highs), len(lows) - 1)
                l2h = [(lows[i], highs[i]) for i in range(n1)]
                h2l = [(highs[i], lows[i + 1]) for i in range(n2)]

            # 新增数据对策略影响
            hl_res = HLPoint.step_hl_s(hl, high, low, temp_hl, temp_m, from_hl,
                                       from_temp, pre_high, pre_low, use_space,
                                       space_h, space_l, l2h, h2l)
            if hl_res["is_high"]:
                t = w.tdaysoffset(-(from_temp + 1),
                                  stamp).Times[0].strftime("%Y-%m-%d")
                cur.execute(f"insert into '{stock_tb}' values (?,?,?,?)",
                            (t, "H", temp_hl, stamp))
                pre2_high = pre_high
                pre_high = hl_res["pre_high"]
            elif hl_res["is_low"]:
                t = w.tdaysoffset(-(from_temp + 1),
                                  stamp).Times[0].strftime("%Y-%m-%d")
                cur.execute(f"insert into '{stock_tb}' values (?,?,?,?)",
                            (t, "L", temp_hl, stamp))
                pre2_low = pre_low
                pre_low = hl_res["pre_low"]

            trdmax_res = Trend.step_trdmax_s(hl_res["hl"], low, high,
                                             hl_res["from_temp"],
                                             hl_res["from_hl"],
                                             hl_res["temp_hl"], trd)
            if trdmax_res[1]:
                self.chgList.append((dd, trdmax_res[0], trd))
                trd = trdmax_res[0]
            else:
                trd_res = Trend.step_trd_s(trd, hl_res["hl"], low, high,
                                           pre_low, pre_high, pre2_low,
                                           pre2_high)
                if trd_res != trd:
                    self.chgList.append((dd, trd_res, trd))
                    trd = trd_res

            try:
                cur.execute(
                    f'''update Strategy_s set date="{stamp}", trend="{trd}",
                                        next_hl={hl_res["hl"]}, temp_hl={hl_res["temp_hl"]}, 
                                        temp_m={hl_res["temp_m"]},
                                        from_hl={hl_res["from_hl"]}, from_temp={hl_res[
                                        "from_temp"]}, 
                                        use_space={hl_res["use_space"]}, space_h={hl_res[
                                        "space_h"]},
                                        space_l={hl_res["space_l"]} where code="{dd}"'''
                )
            except sqlite3.OperationalError as e:
                print(e)
                print(
                    f'''Sqlite error: {dd} new info: trend:{trd}, next_hl:{hl_res['hl']}, 
                     temp_hl:{hl_res['temp_hl']}, temp_m:{hl_res['temp_m']}, from_hl:{hl_res[
                      'from_hl']}, from_temp:{hl_res['from_temp']}, use_space:{hl_res[
                      'use_space']}, space_h={hl_res['space_h']}, space_l={hl_res['space_l']}'''
                )
        cur.close()
        conn.close()
        if len(codes) <= 1:
            pass
        else:
            res = self.sent()
            if res:
                mail_obj = SendEmail()
                mail_obj.buildHTML(res["chg"], res["up"], res["down"],
                                   res["consd"], res["img"], stampf)
                mail_obj.imageHTML(res["chg_img"])
                subject = ["趋势策略每日报告", "趋势策略变动报告-美股"][FREQ]
                mail_obj.setSend(subject, SENDER, RECEIVER, SENDER_KEY)
                print(stampf + f"邮件是否成功发送?{mail_obj.isSent}")
Esempio n. 2
0
    def daily1(self):
        if not w.isconnected():
            w.start()
        conn = sqlite3.connect(DATABASE, isolation_level=None, timeout=3)
        cur = conn.cursor()
        cur.execute('''select code from Strategy_s''')
        # 获取数据库中维护的股票代码
        codes = (code[0] for code in cur.fetchall())
        # 仅保留港股和A股代码
        codes = tuple(filter(lambda x: x[0].isdigit() or x == hsi, codes))
        # 获取今日日期时间戳
        stamp = str(date.today())
        # stamp = '2018-10-25'
        # 格式化今日时间戳
        locale.setlocale(locale.LC_CTYPE, "chinese")
        stampf = date.today().strftime("%Y年%m月%d日")
        # stampf = '2018年10月19日'
        self.chgList = []
        # 提取全部样本股的价格数据
        high_p = w.wsd(",".join(codes), "high", stamp, stamp).Data[0]
        low_p = w.wsd(",".join(codes), "low", stamp, stamp).Data[0]
        trade_status = w.wsd(",".join(codes), "trade_status", stamp,
                             stamp).Data[0]
        # high_p = w.wsd(",".join(codes), "high", '2018-11-23', '2018-11-23').Data[0]
        # low_p = w.wsd(",".join(codes), "low", '2018-11-23', '2018-11-23').Data[0]
        # trade_status = w.wsd(",".join(codes), "trade_status", '2018-11-23', '2018-11-23').Data[0]
        for dd in codes:
            # 提取总表中信息
            # 取出今天数据
            print("正在更新:" + dd)
            dd_i = codes.index(dd)
            high = high_p[dd_i]
            low = low_p[dd_i]
            status = trade_status[dd_i]
            # 提取总表中信息
            if dd not in [sh, hsi] and status == "停牌一天":
                continue
            if not high or not low or high == nan or low == nan:
                continue
            cur.execute(f'''select * from Strategy_s where code="{dd}"''')
            dd_dict = dict(zip(Col_stg, cur.fetchone()))
            stock_tb = code_helper(dd)
            # dat = dd_dict["date"]
            # if dat == stamp:
            #     continue
            trd = dd_dict["trend"]
            hl = dd_dict["next_hl"]
            temp_hl = dd_dict["temp_hl"]
            temp_m = dd_dict["temp_m"]
            from_hl = dd_dict["from_hl"]
            from_temp = dd_dict["from_temp"]
            use_space = dd_dict["use_space"]
            space_h = dd_dict["space_h"]
            space_l = dd_dict["space_l"]
            # 取出高点数据
            cur.execute(
                f'''select price from "{stock_tb}" where hl='H' order by date'''
            )
            #print(cur.fetchall())
            highs = [h[0] for h in cur.fetchall()]
            pre_high = highs[-1]
            pre2_high = highs[-2]
            # 取出低点数据
            cur.execute(
                f'''select price from "{stock_tb}" where hl='L' order by date'''
            )
            lows = [l[0] for l in cur.fetchall()]
            pre_low = lows[-1]
            pre2_low = lows[-2]
            cur.execute(f'''select hl from "{stock_tb}" order by date''')
            first_hl = cur.fetchone()[0]
            if first_hl == "H":
                n1 = min(len(highs) - 1, len(lows))
                n2 = min(len(highs), len(lows))
                l2h = [(lows[i], highs[i + 1]) for i in range(n1)]
                h2l = [(highs[i], lows[i]) for i in range(n2)]
            else:
                n1 = min(len(highs), len(lows))
                n2 = min(len(highs), len(lows) - 1)
                l2h = [(lows[i], highs[i]) for i in range(n1)]
                h2l = [(highs[i], lows[i + 1]) for i in range(n2)]
            # 新增数据对策略影响
            hl_res = HLPoint.step_hl_s(hl, high, low, temp_hl, temp_m, from_hl,
                                       from_temp, pre_high, pre_low, use_space,
                                       space_h, space_l, l2h, h2l)
            if hl_res["is_high"]:
                t = w.tdaysoffset(-(from_temp + 1),
                                  stamp).Times[0].strftime("%Y-%m-%d")
                cur.execute(f"insert into '{stock_tb}' values (?,?,?,?)",
                            (t, "H", temp_hl, stamp))
                pre2_high = pre_high
                pre_high = hl_res["pre_high"]
            elif hl_res["is_low"]:
                t = w.tdaysoffset(-(from_temp + 1),
                                  stamp).Times[0].strftime("%Y-%m-%d")
                cur.execute(f"insert into '{stock_tb}' values (?,?,?,?)",
                            (t, "L", temp_hl, stamp))
                pre2_low = pre_low
                pre_low = hl_res["pre_low"]

            trdmax_res = Trend.step_trdmax_s(hl_res["hl"], low, high,
                                             hl_res["from_temp"],
                                             hl_res["from_hl"],
                                             hl_res["temp_hl"], trd)
            if trdmax_res[1]:
                self.chgList.append((dd, trdmax_res[0], trd))
                trd = trdmax_res[0]
            else:
                trd_res = Trend.step_trd_s(trd, hl_res["hl"], low, high,
                                           pre_low, pre_high, pre2_low,
                                           pre2_high)
                if trd_res != trd:
                    self.chgList.append((dd, trd_res, trd))
                    trd = trd_res

            try:
                cur.execute(
                    f'''update Strategy_s set date="{stamp}", trend="{trd}",
                                        next_hl={hl_res["hl"]}, temp_hl={hl_res["temp_hl"]}, 
                                        temp_m={hl_res["temp_m"]},
                                        from_hl={hl_res["from_hl"]}, from_temp={hl_res[
                                        "from_temp"]}, 
                                        use_space={hl_res["use_space"]}, space_h={hl_res[
                                        "space_h"]},
                                        space_l={hl_res["space_l"]} where code="{dd}"'''
                )
            except sqlite3.OperationalError as e:
                print(e)
                print(
                    f'''Sqlite error: {dd} new info: trend:{trd}, next_hl:{hl_res['hl']}, 
                     temp_hl:{hl_res['temp_hl']}, temp_m:{hl_res['temp_m']}, from_hl:{hl_res[
                      'from_hl']}, from_temp:{hl_res['from_temp']}, use_space:{hl_res[
                      'use_space']}, space_h={hl_res['space_h']}, space_l={hl_res['space_l']}'''
                )
        cur.close()
        conn.close()
        if len(codes) > 2:
            res = self.sent()
            if res:
                mail_obj = SendEmail()
                mail_obj.buildHTML(res["chg"], res["up"], res["down"],
                                   res["consd"], res["img"], stampf)
                mail_obj.imageHTML(res["chg_img"])
                subject = ["趋势策略每日报告", "趋势策略变动报告-A股、港股"][FREQ]
                mail_obj.setSend(subject, SENDER, RECEIVER, SENDER_KEY)
                print(stampf + f"邮件是否成功发送?{mail_obj.isSent}")

        self.daily2()