Demo entry 6661081

trading algorithm

   

Submitted by anonymous on Nov 20, 2017 at 05:45
Language: Python 3. Code size: 5.9 kB.

import pandas as pd
from pandas import Series,DataFrame
import numpy as np
import talib
import datetime
import time

# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
    # 在context中保存全局变量
    context.SHORTPERIOD = 12
    context.LONGPERIOD = 26
    context.SMOOTHPERIOD = 9
    context.OBSERVATION = 100
    # 实时打印日志
    scheduler.run_daily(handle_bar, time_rule=market_open(minute=10))
    
    df = all_instruments(type='CS')
    SZ = df[df['exchange'] == 'XSHE']
    k=SZ.iloc[:,8]
    k=k.tolist()
    test=get_price(k, start_date='2014-01-01', end_date='2015-01-01',frequency='1d', fields='close', adjust_type='pre', skip_suspended=False)
    testall=test.dropna(axis=1,how='any')
    ndf = testall.corr()
    ndf=ndf-np.diag(np.diag(ndf))
    c1=ndf.min(1).dropna(axis=0,how='any')
    
    four1up=[]
    for i in range(0,len(c1)):
        a1=ndf[ndf.ix[0].isnull().values==False].iloc[i:i+1,]
        a2=a1[a1==c1[i]]
        a3=a2.dropna(axis=1,how='any')
        h = a3.columns[0]   
        four1up.append(h)
    list=['cov-']
    df3=pd.DataFrame(c1,columns=list)
    list1=['stock-']
    df4=pd.DataFrame(four1up,index=c1.index,columns=list1)
    covar1=df3.join(df4)
    b=covar1['stock-'].tolist()
    context.targetstock=max(b,key=b.count)
    context.s1=covar1[(covar1['stock-']==context.targetstock) & (covar1['cov-'] <= -0.5)].index.tolist()
    logger.info(context.targetstock,context.s1)
# before_trading此函数会在每天策略交易开始前被调用,当天只会被调用一次
def before_trading(context):
    cons=len(context.s1)
    targetstock = context.targetstock
    stock1 = context.s1
    u = context.now
    
    if  (u.year)==(2016) or (u.year)==(2017):
        cons=len(context.s2)
        targetstock = context.targetstock2
        stock1 = context.s2
    for i in stock1:
        test=history_bars(i, 365, '1d', fields='close', skip_suspended=True, include_now=False)
        test1=history_bars(targetstock, 365, '1d', fields='close', skip_suspended=True, include_now=False)
        s1=Series(test) #转为series类型
        s2=Series(test1)
        covnum=s1.corr(s2)
        if covnum >= -0.5:
            cons=cons-1
        context.cons = cons
    logger.info(context.cons)
# 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
def handle_bar(context, bar_dict):
    targetstock = context.targetstock
    stock1 = context.s1
    u = context.now
    for i in stock1:
        if  (u.day, u.month, u.year)==(1,1,2016) or (u.day, u.month, u.year)==(1,1,2017):
        
            curPosition = context.portfolio.positions[i].quantity
        # 清仓
            if curPosition > 0:
                order_target_value(i, 0)   
    
    if  (u.year)==(2016) or (u.year)==(2017):
        targetstock = context.targetstock2
        stock1 = context.s2
    for i in stock1:
        test=history_bars(i, 365, '1d', fields='close', skip_suspended=True, include_now=False)
        test1=history_bars(targetstock, 365, '1d', fields='close', skip_suspended=True, include_now=False)
        s1=Series(test) #转为series类型
        s2=Series(test1)
        covnum=s1.corr(s2)
    # 开始编写你的主要的算法逻辑
        if  covnum >= -0.5:
        # 获取该股票的仓位
            curPosition = context.portfolio.positions[i].quantity
        # 清仓
            if curPosition > 0:
                order_target_value(i, 0)
                
    for i in stock1:
        test=history_bars(i, 365, '1d', fields='close', skip_suspended=True, include_now=False)
        test1=history_bars(targetstock, 365, '1d', fields='close', skip_suspended=True, include_now=False)
        s1=Series(test) #转为series类型
        s2=Series(test1)
        covnum=s1.corr(s2)
        prices1 = history_bars(targetstock, context.OBSERVATION, '1d', 'close')
        macd1, signal1, hist1 = talib.MACD(prices1, context.SHORTPERIOD,context.LONGPERIOD, context.SMOOTHPERIOD)            
        if  covnum <= -0.5 and context.cons != 0 and macd1[-1] - signal1[-1] < 0 and macd1[-2] - signal1[-2] > 0:
    # bar_dict[order_book_id] 可以拿到某个证券的bar信息
        # 满仓入股
            order_target_percent(i, 1/context.cons)
        if  macd1[-1] - signal1[-1] > 0 and macd1[-2] - signal1[-2] < 0:
        # 获取该股票的仓位
            curPosition = context.portfolio.positions[i].quantity
        # 清仓
            if curPosition > 0:
                order_target_value(i, 0)
    
# after_trading函数会在每天交易结束后被调用,当天只会被调用一次
def after_trading(context):
    u = context.now
    
    if  (u.day, u.month, u.year)==(31,12,2015) or (u.day, u.month, u.year)==(30,12,2016):

        df = all_instruments(type='CS')
        SZ = df[df['exchange'] == 'XSHE']
        k=SZ.iloc[:,8]
        k=k.tolist()
        test=get_price(k, start_date=datetime.datetime(year=u.year - 1, month = u.month, day = u.day).strftime('%Y-%m-%d'), end_date=datetime.datetime(year=u.year, month = u.month, day = u.day-1).strftime('%Y-%m-%d'),frequency='1d', fields='close', adjust_type='pre', skip_suspended=False)
        testall=test.dropna(axis=1,how='any')
        ndf = testall.corr()
        ndf=ndf-np.diag(np.diag(ndf))
        c1=ndf.min(1).dropna(axis=0,how='any')
    
        four1up=[]
        for i in range(0,len(c1)):
            a1=ndf[ndf.ix[0].isnull().values==False].iloc[i:i+1,]
            a2=a1[a1==c1[i]]
            a3=a2.dropna(axis=1,how='any')
            h = a3.columns[0]   
            four1up.append(h)
        list=['cov-']
        df3=pd.DataFrame(c1,columns=list)
        list1=['stock-']
        df4=pd.DataFrame(four1up,index=c1.index,columns=list1)
        covar1=df3.join(df4)
        b=covar1['stock-'].tolist()
        targetstock2=max(b,key=b.count)
        context.s2=covar1[(covar1['stock-']==targetstock2) & (covar1['cov-'] <= -0.5)].index.tolist()
        context.targetstock2=targetstock2
        
        logger.info(context.targetstock2,context.s2)

This snippet took 0.02 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).