均值回歸理論
均值回歸:“跌下去的遲早要漲上來” , 選股用, 不適合做擇時,因為不知道什么時候是偏離最低
均值回歸的理論基於以下觀測:價格的波動一般會以它的均線為中心。也就是說,
當標的價格由於波動而偏離移動均線時,它將調整並重新歸於均線。
定義偏離程度:(MA-P)/MA ---MA均線,P價格
均值回歸策略:在每個調倉日進行
計算股票池中所有股票的N日均線
計算股票池中所有股票與均線的偏離度
選取偏離度最高的M只股票並調倉,比如某只股票前幾年波動較小,突然出現波動很大的情況,就有持有的價值

from jqdata import * def initialize(context): set_benchmark('000300.XSHG') set_option('use_real_price', True) set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock') g.security = get_index_stocks('000300.XSHG') g.ma_days = 30 # 均值回歸理論選30天為基准 g.stock_num = 10 # 持倉10支股票 run_monthly(handle, 1) def handle(context): sr = pd.Series(index=g.security) for stock in sr.index: # 計算偏離程度 ma = attribute_history(stock, g.ma_days)['close'].mean() p = get_current_data()[stock].day_open ratio = (ma - p)/ma sr[stock] = ratio to_hold = sr.nlargest(g.stock_num).index # 選好的股票 for stock in context.portfolio.positions: if stock not in to_hold: order_target(stock, 0) to_buy = [stock for stock in to_hold if stock not in context.portfolio.positions] if len(to_buy) > 0: cash_per_stock = context.portfolio.available_cash / len(to_buy) for stock in to_buy: order_value(stock, cash_per_stock)