Guide to using the quantitative stock analysis tool QTYX - Adding a custom form stock selection strategy


aacaa86ea11a655aff6ee15e7f56ba76.png

Build your own quantification system

a9d1e0a0bee7e2889c4300d57c7ac624.png

Quantitative Stock TradingSystem QTYX is a system that can be used for both learning and practical stock trading analysis.

The purpose of sharing the QTYX system is to provide everyone with a template for building a quantitative system, and ultimately help everyone build their own system. Therefore, we provide source code for secondary development according to your own style.

For QTYX usage guide, please check the link:QTYX usage guide

QTYX has been updated iteratively, the current versionV2.7.2. Subsequent upgrades will update the document content simultaneously.

0c50a998781caa68b67c060959b7f4fb.png

DIY series description

fd7c8fd62499c899703d9989af13b8dd.png

This article belongs to the DIY series of usage strategies, which teaches you how to develop your own strategies and usage based on the QTYX source code.

The QTYX system has built-in some form stock selection strategies, such as double bottom form breakthrough, main rising wave and so on. Not only can we optimize and modify these strategies, we can also embed our own strategies in this system alone.


e5d81505388dc8abfa32153f170dfbf0.png

Pattern Stock Selection Design Framework‍‍‍‍‍

20ee6f99b1b3b4a2f3dc0da7799068c4.png

The overall design framework is shown in the figure below.

In terms of operation, you need to update stock data and select stock selection strategies on the main interface. For operation methods, please refer to the corresponding topics in the usage guide.

A multi-task solution is used when executing stock selection. Corresponding strategies are registered in each task. Stock data will be distributed to these tasks. Each task independently selects stocks and is finally merged into one stock selection result.

After the stock selection results come out, you can also superimpose some special data to carry out multi-faceted stock selection, such as financial data, fund position data, fundamental data, etc.

1f766ec38c9d93acae20ee0994e519b4.png


3ba9cc6d4f21d2f234441fb24fd8e67e.png

How to add code

a5bd35fcbfddfde6a99cd856dcaf15f2.png

Next, we will introduce how to add strategy code.

First find the file "QTYX/StrategyGath/PattenGath.py", add your own strategy function according to the unified format, such as the name "user_define_strategy", and then use Python to add your own strategy logic in the function, as shown in the following code: (Write strategy code When doing this, please pay attention to the format and content of the incoming parameters and the format of the returned data to be compatible with this system framework)

@staticmethod
    def user_define_strategy(name, code, stock_data, patlog_obj, **kwargs):


        """
        # 输入参数
        :param name:  股票名称, 平安银行
        :param code:  股票代码, 000001.SZ
        :param stock_data:  股票数据, DataFrame格式
        :param patlog_obj: 打印日志接口
        :param kwargs: dict: 配置参数, 可以直接在函数中修改
        :return:
        """


        try:
            df_search = pd.DataFrame()  # 构建一个空的dataframe用来装数据


            MA1 = stock_data["收盘价"].rolling(window=5).mean()  # 计算M日的移动平均线
            MA2 = stock_data["收盘价"].rolling(window=10).mean()  # 计算M日的移动平均线
            MA3 = stock_data["收盘价"].rolling(window=20).mean()  # 计算M日的移动平均线
            MA4 = stock_data["收盘价"].rolling(window=30).mean()  # 计算M日的移动平均线
            CLOSE = stock_data["收盘价"]
            MA1.fillna(0, inplace=True)
            MA2.fillna(0, inplace=True)
            MA3.fillna(0, inplace=True)
            MA4.fillna(0, inplace=True)


            # 循环判断是否连续N日都符合均线多头排列的特征
            for id in range(0, 4):
                T = (CLOSE[-1 - id] > MA1[-1 - id] > MA2[-1 - id] > MA3[-1 - id] > MA4[-1 - id])
                if T != True: break  # 只要有一天不满足则退出


            if id >= 3:
                # 输出满足要求的股票
                patlog_obj.re_print("符合特征: 股票 {},代码 {}".format(name, code))
                df_search = pd.DataFrame([[name, code]], index=[0], columns=["股票名称", "股票代码"])


            return df_search


        except Exception as e:
            print(e)
            return pd.DataFrame()

After writing the strategy, you need to register the strategy into the stock selection framework. First, register in the interface. Find the file "QTYX/MainlyGui/ElementGui/DefDialogs/ParaDialog.py" and add a strategy name to the "self.patten_type_cmbo" variable of the SelectModeDialog class, such as "Custom Strategy-DIY Learning". As shown in the following code:

class SelectModeDialog(wx.Dialog): # 形态选股参数/更新行情数据参数/RPS选股参数


    def __init__(self, parent,  title=u"形态选股参数配置", size=(750, 200)):
        pass


    def patten_dialog(self, sizer_object):
        # 中间代码已省略
        # 形态选股参数——形态类型选取
        self.patten_type_box = wx.StaticBox(self, -1, u'选股模型')
        self.patten_type_sizer = wx.StaticBoxSizer(self.patten_type_box, wx.HORIZONTAL)


        self.patten_type_cmbo = wx.ComboBox(self, -1, choices=["主升浪(均线多头&突破前高)", "双底形态突破", "箱体形态突破", "单针探底回升",
                                                               "自定义策略-DIY学习", "线性回归-预留"],
                                            style=wx.CB_READONLY | wx.CB_DROPDOWN)  # 选股项

After the addition is completed, you will see the corresponding options in the interface, as shown in the figure below:

1910f2bc8ed5f44ee70eb42d2b812d43.png

Then register in the stock picking framework. Find the file "QTYX/MainlyGui/UserFrame.py" and add the policy name just created to the "register_info" variable of the "patten_analy_execute" function. Remember to make one-to-one correspondence between the name in the interface and the function name. As shown in the following code:

def patten_analy_execute(self, stock_code):


        register_info = {"双底形态突破": Base_Patten_Group.double_bottom_search,
                         "箱体形态突破": Base_Patten_Group.bottom_average_break,
                         "单针探底回升": Base_Patten_Group.needle_bottom_raise,
                         "主升浪(均线多头&突破前高)": Base_Patten_Group.main_rise_wave,
                         "自定义策略-DIY学习": Base_Patten_Group.user_define_strategy,
                         }
        # 中间代码已省略 
        return df_return # 有效则添加至分析结果文件中

In addition, each strategy has its algorithm parameters, and a dialog box for filling in the parameters needs to be created. Find the file "QTYX/MainlyGui/ElementGui/DefDialogs/SpecDialog.py" and add a dialog class, such as the name "UserDefStrategyDialog". If you are using it yourself and the parameters have been determined, you can directly fix the parameter values ​​in the strategy code. You only need to leave an empty shell in the interface, which is simpler. As shown in the following code:

class UserDefStrategyDialog(wx.Dialog):  # 用户自定义参数界面


    def __init__(self, parent, title=u"自定义提示信息", size=(500, 360)):
        wx.Dialog.__init__(self, parent, -1, title, size=size, style=wx.DEFAULT_FRAME_STYLE)
        # 中间代码已省略
        # 创建FlexGridSizer布局网格
        # rows 定义GridSizer行数
        # cols 定义GridSizer列数
        # vgap 定义垂直方向上行间距
        # hgap 定义水平方向上列间距
        self.FlexGridSizer = wx.FlexGridSizer(rows=1, cols=2, vgap=0, hgap=0)


        self.ok_btn = wx.Button(self, wx.ID_OK, u"确认")
        self.ok_btn.SetDefault()
        self.cancel_btn = wx.Button(self, wx.ID_CANCEL, u"取消")


        self.FlexGridSizer.Add(self.ok_btn, proportion=1, border=1, flag=wx.ALL | wx.EXPAND)
        self.FlexGridSizer.Add(self.cancel_btn, proportion=1, border=1, flag=wx.ALL | wx.EXPAND)


        self.FlexGridSizer.SetFlexibleDirection(wx.BOTH)
        self.SetSizerAndFit(self.FlexGridSizer)
        self.Centre()


    def feedback_paras(self):


        self.user_para = dict()


        return self.user_para

Next, import the dialog box function "UserDefStrategyDialog" into the file "QTYX/MainlyGui/UserFrame.py". As shown in the following code:

from MainlyGui.ElementGui.DefDialogs.SpecDialog import UserDefStrategyDialog

Next, in the file "QTYX/MainlyGui/UserFrame.py", find the event function "_ev_patten_select_func" and register the dialog box function "UserDefStrategyDialog" in it. Remember to make one-to-one correspondence between the name in the interface and the function name.

def _ev_patten_select_func(self, event):


        pass
        register_info = {"主升浪(均线多头&突破前高)":{"对话框函数": MainRiseWaveDialog,
                                        "日志信息":"主升浪形态选股正在执行..."},
                        "双底形态突破": {"对话框函数": DouBottomDialog,
                                        "日志信息":"双底形态选股正在执行..."},
                         "箱体形态突破":{"对话框函数": BreakBottomDialog,
                                        "日志信息":"底部形态选股正在执行..."},
                         "单针探底回升": {"对话框函数": NeedleBottomDialog,
                                    "日志信息": "单针探底回升选股正在执行..."},
                         "自定义策略-DIY学习":{"对话框函数": UserDefStrategyDialog,
                                    "日志信息": "单针探底回升选股正在执行..."}


                         }


        pass

When the stock selection results are finally generated, if you want to superimpose the characteristic data, just find the function "patten_analy_result" in the file "QTYX/MainlyGui/UserFrame.py" and superimpose the characteristic data into the pattern stock selection file.

def patten_analy_result(self):


        pass


        if self.patten_paras[u"北向资金持股"] == True:
           pass


        if self.patten_paras[u"每日基本面指标"] == True:
           pass


        if self.patten_paras[u"叠加利润报表"] == True:
           pass


        Base_File_Oper.save_csv_file(df_search, f"全市场选股结果/{self.patten_paras['选股模型']}分析结果_{select_date.strftime('%Y-%m-%d')}_高速版.csv")
        self.patlog.re_print("\n形态分析完成!明细查看路径ConfigFiles/全市场选股结果/")

The featured data categories you want to overlay are checked on the stock selection configuration interface and modified in the "SelectModeDialog" class of "QTYX/MainlyGui/ElementGui/DefDialogs/ParaDialog.py".

f4dd4eb7fe8f426c24a0684d18c0a5a7.png

673a9bf1f07af3316399ce7885498ac8.png

Summarize

b6a95c0a441e80862bd25d6fe15af77d.png

The above is how to add your own stock selection strategy in the QTYX system. The routine code will be reflected in version 2.7.2 for your reference and learning. It will inevitably not be smooth sailing during the debugging process. Please remember to use print to print logs and troubleshoot problems. I wish you all can build your own quantitative system as soon as possible!

illustrate

Friends who want to join Knowledge Planet's "Fun with Stock Quantitative Trading" remember to call me on WeChat to get benefits!

Click for introduction to Knowledge Planet:Overview of the essence of Knowledge Planet’s "Fun with Stock Quantitative Trading"

f17a772473aefbdac5105bf0c430cced.jpeg

Guess you like

Origin blog.csdn.net/hangzhouyx/article/details/134258158