Buy stocks based on stock picking mode gap, python learning the code

# Buy stocks based on the mode of picking gap
'' '
-------------------------------------- ------
1, the overall measure of things to do before returning to
the initialize (context)
1.1, set the policy parameters ----> global constants
1.2, intermediate variables ----> global variables
1.3, set back test conditions ----> JoinQuant additional required
2, a day before the opening of stock-picking strategies (strategies below, found that stocks, not to be missed)
2.1, set up fee
2.2, set up a viable pool of shares, such as filtration day suspension stock
2.3, screened on the market a full year of all of the shares of
2.4, occurred listed screening point upward gap
is defined as: the lowest price today> yesterday, the highest price, remove the daily limit stocks
rose> 5%
2.5, screening the pre-consolidation phase, such as 20-30 days maximum - low / low <15%, or less standard deviation of
2.6, the gap day daily> 50% 20 days before the mean volume, i.e. more than 15 times.
3, the transaction day
3.1, buy / sell signals Analyzing
3.2 performing buy / sell operation
4, the closing day,
no

--------------------------------------------
about when to sell?
There are three strategies, the first is to set only the profit position. That is, we do not need to pursue the highest selling point.
For example, you set the position of a decline of 3% (the proportion of self-adjusting) from recent highs as a selling point.
The second is the use of technical analysis to see important pressure, on the one hand is the average system pressure,
want to see is the daily, weekly monthly, the greater cycle, the stronger the pressure, followed by the previous high point,
density transaction zone, the area where the depth of hold-up zone, it is possible to temporarily take profit.
There is the knowledge chart technical indicators, such as watching MACD departure from the top, this relatively accurate, KDJ oversold and so on.
To analyze the proposed multi-market, 80% of the shares and the broader market will save the same trend, the market peaked, stocks generally not much better.
The third is to focus on the fundamentals, peer comparison and analysis of the current share price of PE, as well as the company and the industry point of view,
such as the total revenue of the first few rows, the first few rows of the net profit, revenue growth ranked first few, it's always market capitalization came in the first few.
If the fundamentals are ranked 10th in the industry, but the market value in the first row, which means overrated. You can choose only the profit.

'' '


#
import jqdata
import pandas as pd
import datetime as dt
import time

'' '
=============================================== =================================
overall back-tested before
============= ================================================== =================
'' '
# initialization function, like setting the reference
DEF the initialize (context):
Print' initialization method '
set_params () set # strategy constant
set_variables () # intermediate variable
set_backtest () # sensing condition is set back
print '------------------------------------ - '

# 1
# policy parameters provided
DEF set_params ():
Print' disposed strategy parameters'
g.tc transfer positions # = 15 days
g.num_stocks = 10 # the maximum number of shares of each selected tune warehouse

# 2
# intermediate variable
DEF set_variables ():
Print 'disposed intermediate variables'
gt record # 0 = run back to test days
g.if_trade = False # whether the transaction day

# 3
# Set back to test conditions
DEF set_backtest ():
Print 'set back to test conditions'

# set as a benchmark CSI 300, is the benchmark yield
set_benchmark ( '000300.XSHG')


# Enable dynamic recovery of the right mode (real prices)
Set_Option ( 'use_real_price', True)
# contents output to the log log.info ()
log.info ( 'initial function starts running and the global run only once')
# filtered error order lower than the level of the generated series API log
# log.set_level ( 'the Order', 'error')

### ### equity-related setting
fees at # stock class for each transaction is: when buying commission ten thousandths, ten thousandths of a thousands of commission when you sell one half of stamp duty, the minimum commission per trade deducted five dollars
set_order_cost (OrderCost (close_tax = 0.001, open_commission = 0.0003, close_commission = 0.0003, min_commission = 5), of the type = 'Stock')

## run function (reference_security run time reference subject; incoming subject only to distinguish the type, and therefore the incoming '000300.XSHG' or '510300.XSHG' is the same)
run before the opening #
run_daily (before_market_open, Time = 'before_open', reference_security = '000300.XSHG')
# runtime opening
run_daily (market_open, Time = 'every_bar', reference_security = '000300.XSHG')
# after the close operation
run_daily (after_market_close, time = 'after_close', reference_security = '000300.XSHG')

log.set_level ( 'Order', 'error') disposed given level #

'' '
=================== ================================================== ===========
before the opening day
==================================== ============================================
2, a day before the opening of the election shares strategies (strategies below, found that stocks, not to be missed)
2.1, set up fee
2.2, set up a viable pool of shares, such as filtration day suspension stock
2.3, a full year on the market screening of all a shares
2.4, listed screening gap up occurs point
is defined as: today's lowest price>Yesterday, the highest price, remove the daily limit stocks
rose> 5%
2.5, screening the pre-consolidation stage, such as 20-30 days, up to - low / low <15% difference or less standard
2.6, cutout day daily> 50% in the first 20 days an average daily , which is more than 15 times.
'' '
Running function front opening ##
DEF before_market_open (context):
# output runtime
log.info (' a function of time (before_market_open): '+ str ( context.current_dt.time ()))

print '---- a day before the opening of things to do ----'

set_slip_fee (context) # slippage and fees provided
# g.stocks = get_index_stocks ( '000300.XSHG' ) # CSI 300 is provided as an initial stock pool
g.stocks = get_index_stocks ( '000002.XSHG') # Set 000002.XSHG all listed A shares
# set viable stock pool
g.feasible_stocks = set_feasible_stocks (g.stocks, context)


# Micro letter to send a message (to add simulated trading, and bind micro-channel into force)
# send_message ( 'good day ~')

Stock # to operate: Ping An Bank (. G as a global variable)
# g.security = '000001.XSHE'

#
# Set viable stock pool: Filter day suspension stock
# Input: initial_stocks is of type list, represents the initial stock pool; context (see the API)
# Output: unsuspened_stocks is of type list, showing the date of non-suspended stock pool, namely: viable stock pool
DEF set_feasible_stocks (initial_stocks, context):
# determines whether the initial stock pool stock suspension, returns List
# Print 'disposed viable stock pool: stock suspension was filtered off day', context.current_dt.day
# Print 'current epoch% 10s '% (context.current_dt.strftime ( "% Y-M-% D%"))
paused_info = [] # store information corresponding to whether the stock suspension array
liste_Date_info = [] # storage time corresponding to the listing
# basic stock information table - STK_STOCKINFO can find
stock_info get_all_securities = ([ 'Stock']);


# get_current_data ♠ - get the current time data
current_data = get_current_data ()
Print 'Print -', initial_stocks
Print 'reprinting - current time data object returned is empty ', current_data

for I in initial_stocks:
# I each stock code to traverse out
# Then paused to judge whether the stock suspension, False indicates that no suspension
paused_info.append (current_data [i] .paused)

# Print 'acquire all stock data', stock_info [i] .start_date
# listed on how to get a full year of stock
# to acquire all shares data .start_data
# Print 'current period:% 10s-- stock market period:% 10s'% (context.current_dt.strftime ( "% Y-% m-% d"), stock_info.at [i, 'start_date'])
# Print 'current period:% 10s-- stock market during the'% ((stock_info.at [i, 'start_date'] - context.current_dt) .days)
time to market # storage is full year, if yo is YES
isGoPublicOneYear = calculate_goPublick_OneYear (context.current_dt.strftime ( "% Y-M-% D%"), STR (stock_info.at [I, 'START_DATE']))
liste_Date_info.append (isGoPublicOneYear)
IF = isGoPublicOneYear False =:
Print 'listed shares less than one year% 10s:% 10s'% ( i, stock_info.at [i, 'display_name'])


df_paused_public_info = pd.DataFrame({'paused_info':paused_info,'liste_Date_info':liste_Date_info},index = initial_stocks)
# print 'df_paused_public_info:\n',df_paused_public_info
unsuspened_stocks = list(df_paused_public_info.index[(df_paused_public_info.paused_info == False) and (df_paused_public_info.liste_Date_info == True)])

# print '最后获得的index',unsuspened_stocks


unsuspened_stocks return

# calculate whether day trading hours time to market for at least one year
DEF calculate_goPublick_OneYear (currentTime, goPublicTime):
currentTimeDate = time.strptime (currentTime, "% Y-% M-% d")
the y-, m, d = currentTimeDate [0 : 3]

= the time.strptime goPublicTimeDate (goPublicTime, "% Y-M-% D%")
Y2, M2, D2 = goPublicTimeDate [0:. 3]

# Print (dt.datetime (Y, m, D) -dt.datetime (Y2 ., M2, D2)) Days

. IF ((dt.datetime (Y, m, D) -dt.datetime (Y2, M2, D2)) Days)> 366:
return True
the else:
return False


#. 5
# depending the slip point and the time period setting fees
# input: context (see the API)
# output: none
DEF set_slip_fee (context):
Print 'depending on the set period of time and the fee-slip'
# point to the slide 0
set_slippage ( FixedSlippage (0))
# depending on the set period of time fee
print 'depending on the set period of time fee'
dt = context.current_dt
IF dt> a datetime.datetime (2013,1,. 1):
set_commission (PerTrade (= buy_cost 0.0003, sell_cost = 0.0013, (min_cost) =. 5))

elif dt> A datetime.datetime (2011,1,. 1):
set_commission(PerTrade(buy_cost=0.001, sell_cost=0.002, min_cost=5))

elif dt>datetime.datetime(2009,1, 1):
set_commission(PerTrade(buy_cost=0.002, sell_cost=0.003, min_cost=5))
else:
set_commission(PerTrade(buy_cost=0.003, sell_cost=0.004, min_cost=5))


'' '
=============================================== =================================
daily transaction
============== ================================================== ================
'' '
running time function ## opening
DEF market_open (context):
log.info (' a function of time (market_open): '+ str ( context.current_dt .time ()))
Security = g.security
# get the stock's closing price
CLOSE_DATA = attribute_history (Security, 5, '1D', [ 'use close'])
# get the average price over the past five days
MA5 = close_data [ 'close' ] .mean ()
# get on a point in time prices
CURRENT_PRICE = CLOSE_DATA [ 'use Close'] [- 1]
# get current cash
cash = context.portfolio.available_cash

# If the price is higher than the five days at a time point average price of 1%, then buy the whole store
IF CURRENT_PRICE> 1.01 * MA5:
# The record buying
log.info ( "price is higher than the average price of 1 %%, buy S% "% (Security))
# with all the cash to buy shares
# ORDER_VALUE (Security, cash)
# If the last time the price is lower than the average price of five days, then sell short positions
elif current_price <MA5 and context.portfolio.positions [Security] .closeable_amount> 0:
# the record sold
log.info ( "prices are lower than average price, sold S%"% (Security))
# sell all shares, so that the final amount of the stock holdings is 0
# order_target (Security, 0)

'' '
=============================================== =================================
day after the close
============== ================================================== ================
'' '

After ## closing operation function
DEF after_market_close (context):
log.info (STR ( 'a function of time (after_market_close):' + STR (context.current_dt.time ())))
# transaction records to obtain all day
trades = get_trades ( )
for _trade in trades.values ():
log.info ( 'transaction record:' + STR (_trade))
log.info ( 'end of the day')
log.info ( '########### ################################################## # ')

Guess you like

Origin www.cnblogs.com/medik/p/11108627.html