当前位置:网站首页>Broadening - simple strategy test

Broadening - simple strategy test

2022-06-22 01:00:00 WinnieJiang

Several simple strategies and their back testing results , Test based on spotlight platform .

Strategy 1: Average price - Yesterday's closing price strategy ( Moving average strategy )

A detailed description : Calculate the stock for a certain period of time ( Set to days) The average closing price for the period , If it is lower than yesterday's closing price , Then use all current funds to buy stocks ; If it is higher than the closing price , Then adjust the stock position to 0, I.e. all sales .

Policy template code

def initialize(context):#  initialization 
    g.security = '600276.XSHG'#  Stock code ,XSHG: Shanghai stock exchange ,XSHE: Shenzhen Stock Exchange 
def handle_data(context, data):#  Daily cycle 
    last_price = data[g.security].close#  Get the closing price of the latest day 
    #  Get the stock before buying days The average closing price of the day 
    average_price = data[g.security].mavg(days, 'close')
    cash = context.portfolio.cash#  Get current cash 
    #  If yesterday's closing price is higher than days Daily average price , Then buy , Otherwise sell 
    if last_price > average_price:
        order_value(g.security, cash)#  Buy stocks with all your current funds 
    elif last_price < average_price:
        order_target(g.security, 0)#  Adjust the stock position to 0, I.e. all sales 

characteristic : The strategy will not buy or sell until changes are detected , Therefore, it is impossible to copy the bottom , Of course , Nor will it fall to the lowest before selling .
Conclusion : After testing , When stocks rise during the backtesting period ,days Generally, the higher, the better ; conversely , If the stock falls , Then shorten days You can stop the loss in time .

Here are some Medical companies The back test results of running this policy .

000538 Yunnan baiyao

Time :2019/3/1-2020/3/1
days:30 Japan
Strategic benefits : − 27.05 % \color{#55FF55}{-27.05\%} 27.05%
Benchmark returns : 7.38 % \color{#FF0000}{7.38\%} 7.38%
0
A brief analysis of the reasons : Yunnan baiyao since 2019 year 3 It has been falling for months , As long as you buy, you will lose . If the time is one year ahead , You will get the following results .
Time :2018/3/1-2019/3/1
days:30 Japan
Strategic benefits : 7.85 % \color{#FF0000}{7.85\%} 7.85%
Benchmark returns : − 6.81 % \color{#55FF55}{-6.81\%} 6.81%
1
Conclusion : Yunnan Baiyao year fluctuated greatly , It is relatively stable during the year .

600276 Hengrui pharmaceutical

Hengrui pharmaceutical, as the leading stock of domestic innovative drugs , The momentum is good , The following are the back test results .
Time :2019/3/1-2020/3/1
days:45 Japan
Strategic benefits : 13.59 % \color{#FF0000}{13.59\%} 13.59%
Benchmark returns : 7.38 % \color{#FF0000}{7.38\%} 7.38%
2

601607 Shanghai medicine

Time :2019/12/1-2020/3/1( In the near future )
days:30 Japan
Strategic benefits : 4.61 % \color{#FF0000}{4.61\%} 4.61%
Benchmark returns : 2.91 % \color{#FF0000}{2.91\%} 2.91%
3

Trade export listed company test

Time :2019/12/1-2020/3/1
days:30 Japan
Benchmark returns : 2.91 % \color{#FF0000}{2.91\%} 2.91%

Stock code The name of the stock Industry Strategic benefits
600146 Win global clothing -11.27%
300078 Cisco healthcare Electronics -22.94%
002489 Zhejiang Yongqiang Leisure products -11.37%
002611 Oriental Seiko Industrial machinery -10.76%
002640 Cross border communication Internet retail 1.59%

Conclusion : Affected by epidemic situation and policies , Cross border export trading companies have been greatly affected recently .

Strategy 2: Average price crossover strategy ( Double moving average strategy )

The basic idea : A double moving average is two moving averages , such as 5 The daily average and 10 ma . A short period moving average crosses a long period moving average from bottom to top , Then form “ kdj ”, Instead of “ Dead fork ”. When the double average is golden , This indicates that the stock has been very strong in the near future , On the contrary, it is very weak . Buy when you are strong , Sell when you are weak .

Policy template code ( This is set to 5 Day and 20 ma )

#  Initialization function 
def initialize(context):
    g.security='300027.XSHE'
    # Set to run every day 
    run_daily(handle)
    
def handle(context):
    security=g.security
    n5=5
    n20=20  
    #  Get the closing price of the stock 
    close_data = attribute_history(security, n20, '1d',"close",df=False)
    print(close_data)
    #  Get past  ma_n1  Average price per day 
    ma_n5 = close_data['close'][-n5:].mean()
    #  Get past  ma_n2  Average price per day 
    ma_n20 = close_data['close'][-n20:].mean()
    print(ma_n5,ma_n20)
    #  Get current cash 
    cash = context.portfolio.available_cash
    
    #  If there is a current balance 
    if ma_n5 > ma_n20:
        #  Use all  cash  Buy shares ,order_value Is the buying and selling value 
        order_value(security, cash)
        #  Record this purchase 
        log.info("Buying %s" % security)

    #  If n5 The daily average is less than n20 ma , And currently has a position 
    elif ma_n5 < ma_n20 and context.portfolio.positions[security].closeable_amount > 0:
        #  Sell all ,order_target It's the number of purchases and sales 
        order_target(security, 0)

    #  draw n5 Daily average price 
    record(ma_n5=ma_n5)
    #  draw n20 Daily average price 
    record(ma_n20=ma_n20)

Strategy 3: Follow up strategy

A detailed description : When the stock is closed 2 Hours before , namely 13:00 Judge the selected stock . If today's increase exceeds 4%: Current price / Today's opening price >1.040, Then use all current funds to buy stocks ; All of them were sold at the opening of the next day .
* notes : Self focusing width API- The strategy of chasing up multiple stocks was modified

Policy template code

#  Initializer ,  The whole back test only runs once 
def initialize(context):
    g.stock = '600160.XSHG'
    #  Let's start each morning  morning_sell_all
    run_daily(morning_sell_all, '09:30')

def morning_sell_all(context):
    
    order_target(g.stock, 0)

#  Run in the first second of every minute , data  Is the slice data of the last minute 
def handle_data(context, data):

    #  Judge whether it is at the last of the day 2 Hours , We only chase up the last 2 Hours to meet the conditions of chasing up the stock 
    if context.current_dt.hour < 13:
        return
    
    #  Get the current price 
    price = data[g.stock].close

    current_data = get_current_data()
    last_close = current_data[g.stock].day_open

    if price/last_close > 1.040 and price/last_close < 1.099:
    
        #  Get the current fund balance 
        cash = context.portfolio.available_cash
        order_value(g.stock, cash)

Test with Juhua shares
4

Strategy cross test

Parameter description
Time :2019/3/1-2020-3/1
Benchmark returns :7.38%
A strategy :days=30
Strategy two :5 Day and 20 Daily double average
Three strategies : Increase threshold :4%

Real estate companies

notes : Evergrande 、 Financial innovation 、 Wanda 、 Country garden 、SOHO None in A Shares of the listed

Stock code The name of the stock A strategy Strategy two Three strategies
000002 vanke A0.35%-5.91%-4.50%
000402 Financial Street -9.87%-8.85%0.50%
002146 Rongsheng development -7.56%-7.16%0.61%
600048 Poly real estate -9.04%-8.83%-6.88%
Listed banks

The big Banks

Stock code The name of the stock A strategy Strategy two Three strategies
601398 Industrial and Commercial Bank of China -5.33%-4.28%-1.02%
601328 Bank of Communications -9.58%-15.65%0.00%
601288 Agricultural bank of -9.92%-10.21%0.00%
601818 Everbright Bank -4.21%-2.35%-10.49%

City Commercial Bank

Stock code The name of the stock A strategy Strategy two Three strategies
600926 Bank of Hangzhou -14.54%-7.73%-2.48%
601009 Bank of nanjing 1.95%1.86%-6.74%
601169 Bank of Beijing -16.41%-11.44%0.00%
002142 Bank of Ningbo 11.02%15.36%-1.44%

Policy banks

Stock code The name of the stock A strategy Strategy two Three strategies
600000 Pudong Development Bank -12.70%-8.12%102.72%

Strategy 4( Security Selection ): Small market value strategy

A detailed description : Find the lowest market value every day stocksnum Only stocks as stocks to be bought . If the market value of the stock already held is not small enough to be included in the stock to be purchased , Sell these shares . Buy the stock you want to buy , The purchase amount is... Of the currently available funds stocksnum One of the points .

Policy template code

def initialize(context):
  run_daily(period,time='every_bar')
  #  Set the number of shares to trade 
  g.stocksnum = 7
  #  Set the trading cycle 
  g.period = 13
  #  Record the number of days the policy is running 
  g.days = 0

def period(context):
  #  Determine whether the days of strategy implementation can be divided by the rotation frequency 1
  if g.days % g.period == 0:
      #  Code : Find the top companies with the lowest market value stocksnum Only stocks as stocks to be bought 
      #  Get the component code of Shanghai index and Shenzhen Composite Index and connect , That is all A The stock code of all stocks in the stock market 
      #  You can connect two with a plus sign list
      scu = get_index_stocks('000001.XSHG')+get_index_stocks('399106.XSHE')
      #  Selected in scu The market value within the ranks of the smallest top stocksnum Stock only 
      q=query(valuation.code
                  ).filter(
                      valuation.code.in_(scu)
                  ).order_by( 
                      valuation.market_cap.asc()
                  ).limit(g.stocksnum)
      df = get_fundamentals(q)
      #  Select the stock code and convert to list
      buylist=list(df['code'])

      #  Code : If the market value of the stock already held is not small enough to be included in the stock to be purchased , Sell these shares .
      #  Make a judgment about every stock that you currently own : Is it no longer buylist in , If so, sell 
      for stock in context.portfolio.positions:
          if stock not in buylist: # If stock be not in buylist
              order_target(stock, 0) # adjustment stock Our position is 0, Sell 

      #  Code : Buy the stock you want to buy , The purchase amount is... Of available funds stocksnum One of the points 
      #  Divide the money into g.stocksnum Share 
      position_per_stk = context.portfolio.cash/g.stocksnum
      #  use position_per_stk The size of g.stocksnum Share the money to buy buylist Shares in 
      for stock in buylist:
          order_value(stock, position_per_stk)
  #  Increase the number of days for policy implementation 1 
  g.days = g.days + 1 

Several sets of tests
Time :2019/8/1-2020/2/1
Strategic benefits : 11.95 % \color{#FF0000}{11.95\%} 11.95%
Benchmark returns : 4.39 % \color{#FF0000}{4.39\%} 4.39%
5
Time :2015/8/1-2020/2/1
Strategic benefits : 214.65 % \color{#FF0000}{214.65\%} 214.65%
Benchmark returns : 4.90 % \color{#FF0000}{4.90\%} 4.90%
6

原网站

版权声明
本文为[WinnieJiang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206212353034964.html