Civilian version of moving average quantitative trading model

9ed652ecafddb79b47a3e5f10a1196ae.gif

Preface

2021 is fleeting. Let’s take a look back at the funds we have invested in on Ant. In 2022, when the financial crisis is about to come, we will share a lazy version of our financial management strategy. I wish everyone can make a lot of money in the new year and have a happy New Year’s Day.

Fund fixed investment

My strategy is very simple. I invest a small amount every month without thinking, wait for the topic of "national stock trading" to hit the news, and then clear my position at the right time. Generally, there is an operating point every 2-3 years, and each operation window lasts for a few months. If you miss it, you have to start all over again. The selling point does not affect the buying operation, and the cycle repeats.

623c28fd578babfa318c60fdff4bf867.png

Why choose fund

  • Trading once or several times a month does not affect your job, and the complicated work is left to the machine.

  • The fund can avoid black swan events in the corresponding industry or company of a single stock. For example, LeTV’s “return to China next week” or the impact of “double reduction” on the entire education industry.

  • Compared with stocks, funds are more "sustainable" and are less disrupted by trading suspensions, ST or additional issuances.

  • In the rapidly changing stock market, the influence of policies and methods of extracting public opinion are still immature. Funds can greatly simplify the investment model for ordinary people.

Why Choose Index Funds

  • Fund managers of public funds have the "original sin of performance", which is to pursue high profit margins at all costs, because only in this way can they rank high and be "seen" by investors. Under this incentive mechanism, traders prefer a risky investment style. If they win the bet, they will earn a lot of money from handling fees. If they lose the bet, they will just change the fund code and start all over again.

  • Fund manager strategies can be confused with our own strategies, cannot be attributed, cannot be backtested and improved, and index funds reduce the concentration of "personal" risk.

Why choose fixed investment strategy

  • The relative model simplifies one variable.

  • Small regular transactions allow for better trial and error in small steps and accumulation of time series data.

  • The "bears are long and bulls are short " characteristics of A-shares , which means that evenly spaced investment points will most likely fall at the lows of the bear market, reducing costs.

About high frequency trading

  • For ordinary investors, the handling fees of high-frequency trading strategies are relatively high, and the knowledge reserves of non-financial professionals are insufficient.

  • The T+1 of A shares also relatively restricts trading operations on individual stocks (if the amount of funds is large, T can be used to improve this problem, but it also faces the phenomenon of capital impact).

  • As an ETF of a basket of stocks, the fund is not suitable for frequent trading. Those who are capable can choose leading stocks in high-growth industries for high-frequency trading.

Disadvantages

  • The investment cycle is very long and is generally calculated annually;

  • The rate of return is average (annualized is about 8%), which is far inferior to that of professional investors, let alone the currency circle;

  • Capital liquidity is poor, long-term bear markets are the norm, and the window for selling is very short;

  • The investment style is very conservative and is more focused on financial management than investment.

advantage

  • It is a completely passive investment and requires little to worry about;

  • There is no chasing ups and downs, no testing of human nature, and you can sleep peacefully every day;

  • The bear market "sows seeds" to save companies from crisis, and the bull market "distributes dividends" to share the prosperity, political correctness and positive energy of the prosperous times.

Quantitative trading platform

Ordinary fixed investment or simple intelligent fixed investment strategies can be easily operated on Alipay. As programmers, we definitely want to be more independent and controllable. Here are more quantitative trading platforms to choose from:

  • Open source vnpyhttps://github.com/vnpy/vnpy

  • jukuanhttps://www.joinquant.com/

  • rice baskethttps://www.ricequant.com/

  • Excellent minehttps://uqer.datayes.com/

Most of them use Python as the development language, which is very friendly to friends who are used to using machine learning for data analysis. Here we take Jukuan as an example. Register an account on the official website and create a new Notebook to run online. For the offline version, you need to apply for an additional free 6-month trial. Please refer to the API documentation for details.

https://www.joinquant.com/help/api/help#api:API文档

initialization

Choose the CSI 300 as the baseline, invest 10,000 yuan every month, and invest at least 10 months each time before redemption, with a target rate of return of 20%.

# 导入函数库
from jqdata import *

# 初始化函数,设定基准等等
def initialize(context):
    # 设定沪深300作为基准
    set_benchmark('000300.XSHG')
    # 开启动态复权模式(真实价格)
    set_option('use_real_price', True)
    # 输出内容到日志 log.info()
    log.info('初始函数开始运行且全局只运行一次')
    # 过滤掉order系列API产生的比error级别低的log
    # log.set_level('order', 'error')

    ### 股票相关设定 ###
    # 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱
    set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    
    # 要操作的基金:(g.为全局变量)
    g.security = '510300.XSHG'
    # 预期目标
    g.goal = 1.2
    # 均值窗口期
    g.during = 500
    # 定投基本值
    g.base_order_value = 10000
    # 卖出锁定周期
    g.sell_period = 10
    g.sell_timestamp = context.current_dt
    
    run_monthly(market_open, monthday=1, reference_security='000300.XSHG')

moving average strategy

Add a little strategy to your monthly mindless investment:

Buy less at high positions

c838e438b35b50a3a70a907f48f0a2c2.png b990b896b2c4bf9cb8b6be875babb402.png
# 高位买入    
def high_buy(security, base_order_value, cash, ratio):
    # 默认扣款率
    pay_ratio = 1
    
    if ratio < 0.15:
        pay_ratio = 0.9
    elif ratio < 0.50:
        pay_ratio = 0.8
    elif ratio < 1:
        pay_ratio = 0.7
    else:
        pay_ratio = 0.6
    
    # 需买入的金额
    order_value_cash = base_order_value*pay_ratio
    log.info("%s: %f, cash: %d, ratio: %f"%(security, pay_ratio, cash, ratio))
    
    if cash < order_value_cash:
        log.info("现金 %d 不足, 买入失败 %s: %d " % (cash, security, order_value_cash))
        return False
    
    log.info("高位买入 %s: %d" % (security, order_value_cash))
    order_value(security, order_value_cash)
    
    return True

Buy more at low prices

b1a5cdb0e2142269b96d029728ac04da.png 2bec703ffc61d9e0838ef540965f0342.png
# 低位买入    
def low_buy(security, base_order_value, cash, ratio):
    # 默认扣款率
    pay_ratio = 1
    
    # 近10天的最高价和最低价
    value_range = get_bars(security, count=10, unit='1d', fields=['high','low'])
    max_value = max(value_range['high'])
    min_value = min(value_range['low'])
    
    if (max_value - min_value)/max_value > 0.05:
        # 大幅度震荡,持续下跌通道中
        if ratio < 0.05:
            pay_ratio = 0.6
        elif ratio < 0.10:
            pay_ratio = 0.7
        elif ratio < 0.20:
            pay_ratio = 0.8
        elif ratio < 0.30:
            pay_ratio = 0.9
        elif ratio < 0.40:
            pay_ratio = 1
        else:
            pay_ratio = 1.1
    else:
        # 小幅度震荡,形成底部加大购买量
        if ratio < 0.5:
            pay_ratio = 1.6
        elif ratio < 0.10:
            pay_ratio = 1.7
        elif ratio < 0.20:
            pay_ratio = 1.8
        elif ratio < 0.30:
            pay_ratio = 1.9
        elif ratio < 0.40:
            pay_ratio = 2
        else:
            pay_ratio = 2.1       
    
    # 需买入的金额
    order_value_cash = base_order_value*pay_ratio
    
    if cash < order_value_cash:
        log.info("现金 %d 不足, 买入失败 %s: %d " % (cash, security, order_value_cash))
        return False
    
    log.info("低位买入 %s: %d" % (security, order_value_cash))
    order_value(security, order_value_cash)
    
    return True

Expected take profit

For the convenience of backtesting, we cannot "listen to the news" to judge. We must first meet the expected target income to stop profit.

# 卖出    
def sell(security, current_price, MA, sell_timestamp):
    log.info("sell: %f, MA: %f" %(current_price, MA))
    
    if current_price/MA < g.goal:
        return False
        
    if (sell_timestamp - g.sell_timestamp).days/30 < g.sell_period:
        return False
    
    # 卖出所有股票,使这只股票的最终持有量为0
    log.info("%s, %s, %d" % (sell_timestamp, g.sell_timestamp, (sell_timestamp - g.sell_timestamp).days))
    log.info("达到预期目标, 卖出 %s" % (security))
    order_target(security, 0)
    # 更新卖出时间戳
    g.sell_timestamp = sell_timestamp
    return True

Run strategy

Everything is ready, let's combine the above functions together and run it to see the effect.

## 开盘时运行函数
def market_open(context):
    log.info('函数运行时间(market_open):'+str(context.current_dt.time()))
    security = g.security
    
    # 平均值窗口期
    during = g.during
    
    # 获取股票的收盘价
    close_data = get_bars(security, count=during, unit='1d', fields=['close'])
    # 取得过去500天的平均价格
    MA = close_data['close'].mean()
    # 取得上一时间点价格
    current_price = close_data['close'][-1]
    # 取得当前的现金
    cash = context.portfolio.available_cash
    # 定投金额
    base_order_value = g.base_order_value
    
    if (current_price > MA):
        # 高位卖出
        sell(security, current_price, MA, context.current_dt)
        
        # 高位少买 
        high_buy(security, base_order_value, cash, (current_price-MA)/MA)
    else:
        # 低位多买
        low_buy(security, base_order_value, cash, (MA-current_price)/MA)

    #得到本次所有成交记录
    trades = get_trades()
    for _trade in trades.values():
        log.info('成交记录:'+str(_trade))
    log.info('本轮结束')
    log.info('##############################################################')
364c7def4ef34dae0b3a98b636fee7c7.png

I chose 2015 to 2021 for backtesting. It seems to be pretty good. There are many buying points. Except for a few sporadic times when the funds are used up, there are transactions almost every month. There are only 4 selling points. This aspect is limited by The "sell lock cycle", on the other hand, also reflects the phenomenon of a long-term bear market in A-shares.

8aa5294e33c69a8b1c280ac299f43431.png

The annualized return is 9.85%. The period for establishing a position for small investments here is relatively long, so the relative capital utilization rate is not high enough. The position here can be simply understood as the maximum investment scale. In actual operation, you can use fixed income as capital investment, and large amounts of funds can be used for other investments to expand the rate of return.

Choose a few more long-term periods, such as 2017 to the present, or 2019 to the present. The returns are not as good as the bull market, but they can escape the stock market meltdown and the return rate can remain stable and positive most of the time.

37b73d781b501c36949ae2186e0f20c9.png
Position analysis

Real transaction

  • Directly connect with securities institutions

  • Simulated trading, manual operation

    f44415996488e70dfabc038732d19405.png
    simulated trading

Since we don’t have many buying and selling operations, we can use the prepared strategy to send buy and sell signals through WeChat messages through simulated trading, and then conduct fund operations based on the actual situation.

# 给微信发送消息(添加模拟交易,并绑定微信生效)
send_message("买入 %s: %d" % (security, order_value_cash))

Summarize

Seeing this, I believe that friends who are engaged in deep learning will definitely want to try out a bunch of timing models. To pour cold water on it first, judging from my own experience and the lessons learned from friends who are doing quantitative trading around me, a single model is basically useless in A-shares.

a2ce0f1c6319a21602a35b39128580d0.png

The main reasons are as follows:

  • The time series model is reproducible based on historical trends. History will not simply repeat itself, but will only come back under different circumstances.

  • Numerous quantitative institutions have made the original "low-risk strategy points" fleeting and parasitic strategies rampant.

  • A-shares are a market with strong policies, and financial factors account for a small proportion.

  • The proportion of retail investors is very high, and market sentiment has a greater impact.

In addition, the above is only a technical sharing and personal experience, not investment advice. More trading strategies are waiting for guidance from financial professionals. There are also more cool operations of NLP public opinion analysis keywords to raise the daily limit. Open your imagination in the comment area.

On the self-cultivation of a leek, the great chivalrous person will take over the country.

Hey, I promised to update every Monday in 2021, and I feel like I owe a lot of debt. There are Hongmeng series, Raspberry Pi series, OCR series, and Knowledge Graph series. There are too many manuscripts and I am not in the mood to sort them out slowly. I hope to complete them in the coming year.

c236136f3b35f2c1976e1e0f8f077963.png

d76f842a9da4aa9e9d1ff1ec02d82809.gif

Guess you like

Origin blog.csdn.net/weixin_47479625/article/details/122273060