The daily income is tens of thousands, and Jack's annual income is one million?

Long-time readers should know that I have traded in stocks for more than two years.

From the initial fund to the later stocks, the amount has been small, and it has been added to 300,000 at most.

When the rally is at its best, there is a floating profit of nearly 10,000 every day , and occasionally there is a floating profit of nearly 20,000 .

Those good times have come to an end since the stock market went into a difficult mode in February.

At the beginning of the year, most of the floating profit of tens of thousands of yuan was also lost. In addition, the plan was to use a lot of money this year, and the body was hollowed out.

The stock market investment is a lot more conservative, basically fixed at a low position of around 100,000, and the focus is on participation.

There have always been readers who wanted to read my articles on financial management. At first they agreed, and then they thought about it carefully.

You said, I'm a technical blogger and I write about financial management. Isn't that not a good job ?

Besides, I didn't come from a financial background. Although I made some small money in the stock market by luck, we are not professionals after all, and we dare not give orders randomly.

I suddenly changed my mind recently, financial management + technology, I can do this ~

I like to learn new knowledge , not only limited to computer technology, but always be curious and want to learn everything.

Coincidentally, I plan to publish a quantitative trading video in the near future to discuss the application of artificial intelligence technology in investing in the stock market.

Learning and learning, I found that the water here is very deep, "I can't hold it".

Quantitative trading is not as easy to do as I thought, and there is a lot of knowledge to learn.

In one weekend, I got in the door.

Today, let’s sort out and share the basics of quantitative trading and warm up for the video.

Quantitative trading

Quantitative trading is a securities investment method that uses computer technology to trade with the help of modern statistics and mathematics.

The main knowledge points covered are as follows:

You can understand mathematics, programming, finance, and algorithms, and you can make up where you can't.

Quantitative Platform

Grasp data, write strategies, and trade online. If you do it by yourself, the cost is too high, which is not conducive to the initial learning.

I have investigated some quantitative analysis platforms that can help us focus on learning strategies for quantitative trading.

I think the platforms that can be used to get started are:

  • Poly wide

  • vnpy

There are many platforms for quantitative trading, such as Nuggets, Mikuang, Youkuang, etc.

But for beginners, you can look directly at this polykuan and vnpy.

The Jukuan community is active, and there are many technical tutorials, suitable for beginners.

https://www.joinquant.com/study

There are a lot of knowledge points here that can be learned, and there are also many bigwigs sharing their strategies.

The reason why vnpy is recommended is that it is open source and can systematically learn how to build a quantitative trading system.

https://github.com/vnpy/vnpy

If you want to implement a quantitative trading framework yourself, you can refer to a lot of code from here.

Small scale chopper

The use of the Jukuan quantitative trading platform is relatively simple.

We take this platform as an example to explain a simple quantitative strategy.

We return to the essence of the problem , buying stocks is nothing more than two points:

  • Which stock to buy

  • when to buy and when to sell

1. Which stock to buy

Investors, choosing stocks, the most direct way is to look at the financial statements .

At least include the balance sheet, profit and loss statement, cash flow statement, these three tables.

There is just too much data here, and each table has a variety of metrics.

These indicator data, in quantitative trading, are called factors.

I understand that it is a feature that is often said in our machine learning, and each factor can be counted as a feature of a dimension.

We can use these known data to construct multi-dimensional feature data, and then hand it over to the machine learning algorithm to let the algorithm judge whether the stock is worth buying.

This goes back to the old-fashioned question of doing algorithms, which features to choose to fit the data.

That's it, feature engineering starts.

These lowest-level features belong to a basic factor.

In quantitative trading, more "higher-dimensional" factors, ie features, can also be calculated based on these data.

For example, the return on net assets, the English abbreviation is called ROE.

ROE is the percentage ratio of a company's after-tax profit divided by its net assets .

That is, ROE = net profit / net assets

Net profit, on the income statement, and net assets, on the balance sheet.

ROE reflects the level of return on shareholders' equity and is used to measure the efficiency of a company's use of its own capital.

The higher the indicator value, the higher the return on investment . This indicator reflects the ability of own capital to obtain net income.

ROE is a "high-dimensional" feature calculated through some "low-dimensional" features.

Selecting stocks is actually based on these indicators, choosing stocks that you think are worth investing in.

In order to simplify the strategy, here is a simple, single, use of this ROE, as an indicator of our value stock selection ideas.

Simple and violent, calculate the ROE of all the current stocks, sort from large to small, and select top10 as our stock position.

2. When to buy and when to sell

Investors want to buy low and sell high .

10 yuan to buy, 100 yuan to sell, make a difference, earn 90.

The essence of this problem is: buy low and sell high.

But the reality is often cruel.

When to buy and when to sell, in quantitative trading, there is an indicator, the relative strength of resistance and support, which is RSRS.

To understand the relative strength of resistance support, you must first know what resistance and support are.

The resistance level refers to the pressure that may be encountered when the target price rises, that is, the price at which the trader believes that the seller's power begins to overtake the buyer, so that it is difficult for the price to continue to rise or fall back from there;

The support level is the price at which traders believe that the buyer's power has begun to overtake the seller, thereby stopping the decline or rebounding.

The relative strength of resistance and support is a way of using resistance and support. It no longer regards resistance and support as a fixed value, but as a variable, which reflects a trader's perception of the top and bottom of the current market state. Anticipatory judgment.

We illustrate the application logic of the relative strength of support and resistance by classifying different market states:

The market is in a rising bull market:

  • If support is significantly stronger than resistance, the bull market continues and prices accelerate

  • If resistance is significantly stronger than support, the bull market may be coming to an end and prices have peaked

The market is in turmoil:

  • If support is significantly stronger than resistance, a bull market may be about to start

  • If resistance is significantly stronger than support, a bear market may be about to start

The market is in a falling bear market:

  • If support is significantly stronger than resistance, the bear market may be coming to an end and prices have bottomed

  • If resistance is significantly stronger than support, the bear market continues and price declines accelerate

The daily high and low prices are a kind of resistance and support levels, which are the resistance and support recognized by the trading behavior of all market participants on that day. A natural idea is to build a linear regression of highs and lows and calculate the slope. which is:

When the slope value is large, the support strength is greater than the resistance strength. In the bull market, the resistance is getting smaller and the upper space is large; in the bear market, the support is getting stronger and the downward momentum is about to stop.

When the slope value is small, the resistance strength is greater than the support strength. In the bull market, the resistance is getting stronger, and the upward momentum is gradually stopped; in the bear market, the support is gradually sent, and the downward space is getting bigger and bigger.

There are two methods for calculating the RSRS indicator. The first method is to directly use the slope as the indicator value, and the second method is to standardize on the basis of the slope.

Taking the second method as an example, the RSRS slope standard sub-index timing strategy is as follows:

Small scale chopper

OK, which stock to buy, and when to buy and when to sell, these two problems are solved, and we can start writing code.

Here you need to master first, how to use Jukuan, and some APIs.

This part is relatively simple, just go directly to the official manual of the platform.

Write the following code:

'''
策略思路:
选股:财务指标选股
择时:RSRS择时
持仓:有开仓信号时持有10只股票,不满足时保持空仓

'''
# 导入函数库
import statsmodels.api as sm
from pandas.stats.api import ols

# 初始化函数,设定基准等等
def initialize(context):
    # 开启动态复权模式(真实价格)
    set_option('use_real_price', True)
    # 过滤掉order系列API产生的比error级别低的log
    # log.set_level('order', 'error')
    set_parameter(context)
    ### 股票相关设定 ###
    # 股票类每笔交易时的手续费是:买入时佣金万分之三,卖出时佣金万分之三加千分之一印花税, 每笔交易佣金最低扣5块钱
    set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    
    ## 运行函数(reference_security为运行时间的参考标的;传入的标的只做种类区分,因此传入'000300.XSHG'或'510300.XSHG'是一样的)
      # 开盘前运行
    run_daily(before_market_open, time='before_open', reference_security='000300.XSHG') 
      # 开盘时运行
    run_daily(market_open, time='open', reference_security='000300.XSHG')
      # 收盘后运行
    #run_daily(after_market_close, time='after_close', reference_security='000300.XSHG')
    
'''
==============================参数设置部分================================
'''
def set_parameter(context):
    # 设置RSRS指标中N, M的值
    #统计周期
    g.N = 18
    #统计样本长度
    g.M = 1100
    #首次运行判断
    g.init = True
    #持仓股票数
    g.stock_num = 10
    #风险参考基准
    g.security = '000300.XSHG'
    # 设定策略运行基准
    set_benchmark(g.security)
    #记录策略运行天数
    g.days = 0
    #set_benchmark(g.stock)
    # 买入阈值
    g.buy = 0.7
    g.sell = -0.7
    #用于记录回归后的beta值,即斜率
    g.ans = []
    #用于计算被决定系数加权修正后的贝塔值
    g.ans_rightdev= []
    
    # 计算2005年1月5日至回测开始日期的RSRS斜率指标
    prices = get_price(g.security, '2005-01-05', context.previous_date, '1d', ['high', 'low'])
    highs = prices.high
    lows = prices.low
    g.ans = []
    for i in range(len(highs))[g.N:]:
        data_high = highs.iloc[i-g.N+1:i+1]
        data_low = lows.iloc[i-g.N+1:i+1]
        X = sm.add_constant(data_low)
        model = sm.OLS(data_high,X)
        results = model.fit()
        g.ans.append(results.params[1])
        #计算r2
        g.ans_rightdev.append(results.rsquared)
    
## 开盘前运行函数     
def before_market_open(context):
    # 输出运行时间
    #log.info('函数运行时间(before_market_open):'+str(context.current_dt.time()))
    g.days += 1
    # 给微信发送消息(添加模拟交易,并绑定微信生效)
    send_message('策略正常,运行第%s天~'%g.days)

## 开盘时运行函数
def market_open(context):
    security = g.security
    # 填入各个日期的RSRS斜率值
    beta=0
    r2=0
    if g.init:
        g.init = False
    else:
        #RSRS斜率指标定义
        prices = attribute_history(security, g.N, '1d', ['high', 'low'])
        highs = prices.high
        lows = prices.low
        X = sm.add_constant(lows)
        model = sm.OLS(highs, X)
        beta = model.fit().params[1]
        g.ans.append(beta)
        #计算r2
        r2=model.fit().rsquared
        g.ans_rightdev.append(r2)
    
    # 计算标准化的RSRS指标
    # 计算均值序列    
    section = g.ans[-g.M:]
    # 计算均值序列
    mu = np.mean(section)
    # 计算标准化RSRS指标序列
    sigma = np.std(section)
    zscore = (section[-1]-mu)/sigma  
    #计算右偏RSRS标准分
    zscore_rightdev= zscore*beta*r2
    
    # 如果上一时间点的RSRS斜率大于买入阈值, 则全仓买入
    if zscore_rightdev > g.buy:
        # 记录这次买入
        log.info("市场风险在合理范围")
        #满足条件运行交易
        trade_func(context)
    # 如果上一时间点的RSRS斜率小于卖出阈值, 则空仓卖出
    elif (zscore_rightdev < g.sell) and (len(context.portfolio.positions.keys()) > 0):
        # 记录这次卖出
        log.info("市场风险过大,保持空仓状态")
        # 卖出所有股票,使这只股票的最终持有量为0
        for s in context.portfolio.positions.keys():
            order_target(s, 0)
            
#策略选股买卖部分    
def trade_func(context):
    #获取股票池
    df = get_fundamentals(query(valuation.code,valuation.pb_ratio,indicator.roe))
    #进行pb,roe大于0筛选
    df = df[(df['roe']>0) & (df['pb_ratio']>0)].sort('pb_ratio')
    #以股票名词作为index
    df.index = df['code'].values
    #取roe倒数
    df['1/roe'] = 1/df['roe']
    #获取综合得分
    df['point'] = df[['pb_ratio','1/roe']].rank().T.apply(f_sum)
    #按得分进行排序,取指定数量的股票
    df = df.sort('point')[:g.stock_num]
    pool = df.index
    log.info('总共选出%s只股票'%len(pool))
    #得到每只股票应该分配的资金
    cash = context.portfolio.total_value/len(pool)
    #获取已经持仓列表
    hold_stock = context.portfolio.positions.keys() 
    #卖出不在持仓中的股票
    for s in hold_stock:
        if s not in pool:
            order_target(s,0)
    #买入股票
    for s in pool:
        order_target_value(s,cash)
#打分工具
def f_sum(x):
    return sum(x)
        
## 收盘后运行函数  
def after_market_close(context):
    #得到当天所有成交记录
    trades = get_trades()
    for _trade in trades.values():
        log.info('成交记录:'+str(_trade))
    #打印账户总资产
    log.info('今日账户总资产:%s'%round(context.portfolio.total_value,2))
    #log.info('##############################################################')

Write the code on the left, enter the backtest time and amount, and you can run it.

I directly backtested the effect from January 2010 to January 2020, and the return on investment for ten years:

It took off directly, the initial capital was 500,000, and it made several million, very stable!

I backtested the returns for one and a half years from January 2020 to June 2021:

It underperformed the market by 8.35%, but it did not lose any money, and the annualized rate could also be 11.40%, which is okay.

Summarize

This strategy, without using historical data, is based on some current indicators to make decisions.

Investment and financial management, knowledge in this area, still needs to be learned, not investing in the stock market, buying a bank on a regular basis is also good.

We study hard in the cold window. On the one hand, we want to learn something, make money, and live a comfortable life.

Schools teach us all kinds of basic knowledge, but they rarely teach us directly how to make money, manage money, and manage our wealth.

So, teach yourself. Life is about tossing, and learning all kinds of knowledge is very good and interesting.

Now, although the stock market is a difficult mode, there are still many opportunities, and we can also use this time to supplement our knowledge.

This issue is hardcore, friends who like it, forward it, like it, and let me see it.

Interested, continue to come out later.

Finally, I will send you a copy to help me get the data structure of BAT and other first-tier manufacturers . It was written by a Google master, and it is very useful for students who have weak algorithms or need to improve:

Google and Ali's Leetcode brushing notes

As well as the BAT algorithm engineer learning route, books + videos , complete learning routes and instructions that I have compiled , it will definitely help those who want to become algorithm engineers:

How I became an algorithm engineer, super detailed learning path

I'm Jack, see you next time!

Guess you like

Origin blog.csdn.net/c406495762/article/details/118532397