ITPub博客

首页 > 应用开发 > Python > VNPY利用邮件引擎,把参数优化结果作为附件发送给预定邮箱

VNPY利用邮件引擎,把参数优化结果作为附件发送给预定邮箱

原创 Python 作者:张国平 时间:2022-12-13 12:29:31 0 删除 编辑

一个简单的引用,分成两步,第一步增强邮件引擎,使得可以发送附件邮件,第二部在回测widget的里面加入一个新方法,在优化完成适合被调用。
下面代码是加入EmailEngine,新增一个add_attch, 增强send_email,不是很优雅,不过不会对已有用到send_email的不会又太大影响。

    def add_attch(self,msg,attch_dir,filename):
        """
        给邮件信息对象添加附件
        """
        file_path = os.path.join(attch_dir, filename)
        ctype, encoding = mimetypes.guess_type(file_path)
        if ctype is None:
            ctype = "application/octet-stream"
        maintype, subtype = ctype.split("/")
        with open(file_path, "rb") as r:
            msg.add_attachment(
                r.read(), maintype=maintype, subtype=subtype, filename=filename)
        return msg
    def send_email(self, subject: str, content: str, receiver: str = "",attch_dir = "",filename = "") -> None:
        """"""
        # Start email engine when sending first email.
        if not self.active:
            self.start()
        # Use default receiver if not specified.
        if not receiver:
            receiver = SETTINGS["email.receiver"]
        msg = EmailMessage()
        msg["From"] = SETTINGS["email.sender"]
        msg["To"] = receiver
        msg["Subject"] = subject
        msg.set_content(content)
        if attch_dir:
            msg = self.add_attch(msg,attch_dir,filename)
        self.queue.put(msg)

然后在BacktesterManager这个类里面新增一个方法,优化结果csv保存到一个预定folder,并发送

    def save_and_send_csv(self) -> None:
        """
        Save table data into a csv file
        """
        filepath  = r"C:\Desktop"
        filename = self.symbol_line.currentText() + self.start_date_edit.dateTime().toPyDateTime() + ".csv"
        path = os.path.join(filepath, filename)
        with open(path, "w", encoding='utf-8-sig') as f:
            writer = csv.writer(f, lineterminator="\n")
            writer.writerow(["参数", self.target_display])
            for tp in self.backtester_engine.get_result_values():
                setting, target_value, _ = tp
                row_data = [str(setting), str(target_value)]
                writer.writerow(row_data)
       self.main_engine.send_email_attchment(subject = filename , content = filename , attch_dir = filepath, filename = filename )


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/22259926/viewspace-2927868/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
SAP 金融风险管理产品专家

注册时间:2009-08-05

  • 博文量
    229
  • 访问量
    636018