50 Option Trend Sellers

#!/usr/bin/env python
# coding:utf-8
from PoboAPI import *
import datetime
import time
import numpy as np
from copy import *
import pandas as pd
#设定持仓细节数据表
#g.df = {}

g.df = pd.DataFrame(columns = ['date','code','price','volume','stoploss','iv'])
print(type(g.df))
g.a = []
g.b = []
# 设定最大显示行数、列数为10000
pd.set_option('display.max_rows', 10000)
pd.set_option('display.max_columns', 10000)
pd.set_option('display.width', 10000)
    
#获取合约剩余交易日期

def stime(op):
    info1 = GetContractInfo(op)#获取合约信息
    kill = info1['行权到期日']
    #print (str(type(kill)))
    cutime = GetCurrentTime()#获取当前时间
    #调整时间格式
    if cutime.day < 10:
        cutim = str(cutime.year) + str(cutime.month) + '0' +str(cutime.day)
    elif cutime.month < 10:
        cutim = str(cutime.year) + '0' + str(cutime.month) +str(cutime.day)
    else:
        cutim = str(cutime.year) + str(cutime.month) +str(cutime.day)
    n = (kill - cutime.date()).days #这里的到期日计算进行了更新
    return n
#开始时间,用于初始化一些参数
def OnStart(context) :
    context.myacc = None
    #登录交易账号
    if context.accounts["回测期权"].Login() :
        context.myacc = context.accounts["回测期权"]

#每天行情初始化的,获取当前的50etf对应的平值期权
def OnMarketQuotationInitialEx(context, exchange,daynight):
    #过滤掉非上交所的信号
    if exchange != 'SHSE':
        return
    #获取期权标的
    g.biaodi = '510050.SHSE'
    klinedata = GetHisData2(g.biaodi,BarType.Day,count=60)
    #print(klinedata)
    lclose = klinedata[-1].close
    #20日均线入场价
    MA = GetIndicatorAsDF("MA",g.biaodi,params={60},bar_type = BarType.Day)
    #print(MA.head())
    close_20= MA.iloc[-1,4]
    #print(close_20)
    #print(lclose)
    #获取当月平价认购期权
    g.atmoc = GetAtmOptionContract(g.biaodi,0,lclose,0)  #看涨
    #print(g.atmoc)
    #订阅日K线用来驱动onbar事件
    SubscribeBar(g.atmoc,BarType.Day)
    ab = close_20-lclose
    close_save = lambda ab:lclose-ab if ab>0 else lclose+ab   #看跌
    #获取当月平价认购期权
    g.atmopc_save = GetAtmOptionContract(g.biaodi,0,lclose,0)
    #订阅日K线用来驱动onbar事件
    SubscribeBar(g.atmopc_save,BarType.Day)
    if g.df.empty:
        pass
    else:
        g.df.drop_duplicates(['date','code','volume'])
    
    
    #g.df = g.df.dropna(axis = 0)
    #g.df = g.df.drop(xx,inplace = True)
    
    #清空账号中不存在的合约
    #查
        a = g.df[g.df.volume == 0].index.tolist()
        #print('a',a)
    #删
        g.df = g.df.drop(a,inplace = True)
        #print('g.df',g.df)
#在k线出现的时候,如果没持仓就卖开,如果有就平仓
def OnBar(context,code,bartype):
            if g.df is not None:
                g.df.reset_index(drop=True)
            else:
                g.df = pd.DataFrame(columns = ['date','code','price','volume','stoploss','iv'])
#     if g.df.isnull:
#         pass
#     else:
         #xx = g.df[g.df.volume == 0].index.tolist()
    
    #c=g.a+g.b
    #g.df=g.df.drop(c)
#     if g.df is None:
#         pass
#     else:
#         g.df.drop_duplicates(['date','code','volume'])
    
    
#     #g.df = g.df.dropna(axis = 0)
#     #g.df = g.df.drop(xx,inplace = True)
    
#     #清空账号中不存在的合约
#     #查
#         a = g.df[g.df.volume == 0].index.tolist()
#     #删
#         g.df = g.df.drop(a,inplace = True)
#         if g.df is None: 
#             pass
#         else:
#             g.df['index1']=range(g.df.shape[0])
#             g.df.set_index('index1')
            print(g.df)
            cash = context.accounts["回测期权"].AccountBalance.AvailableCashBalance
    #下单手数
            klinedatac = GetHisData2(g.atmoc,BarType.Day)
            MA = GetIndicatorAsDF("MA",g.biaodi,params={60},bar_type = BarType.Day)
            MA5_1= MA.iloc[-1,4]
            Ma20= MA.iloc[-1,1]
            Margin = OptionMargin(context.accounts["回测期权"],g.atmoc)
            if klinedatac[-1] != 0.0001:
                cshare = int(cash*0.2 / Margin)
        #print("虚call价格:", cshare,g.atmoc,klinedatac[-1].close)
    
    #获取所有持仓
            optionc = PBObj()
            optionc.buysellflag = '1'
            posiC = context.accounts["回测期权"].GetPositions(optionc) 
            HV = GetVolatilityByCode(g.biaodi, start_date = None, end_date = None, count = 20, weight_type = 0)
            b = CreateCalcObj()
            g.biaodi = '510050.SHSE'
            klinedata = GetHisData2(g.biaodi,BarType.Day,count=60)
            #print(klinedata)
            lclose = klinedata[-1].close
            GetQuote(g.atmoc).now 
                #获取持仓合约的最新价
            dyn1 = GetQuote(opcode1)
            dyn2 = GetQuote(opcode2)
            #获取持仓合约的行权价格和到期日
            info1 = GetContractInfo(opcode1)
            pr1 = info1['行权价格']
            ki1 = info1['行权到期日']
            info2 = GetContractInfo(opcode2)
            pr2 = info2['行权价格']
            #计算合约截至目前剩余天数
            sy = stime(opcode1)
            IV = b.GetImpliedVolatility(0,1,lcolse,2.7,0.22,0.04,HV,klinedatac[-1])
             
            if (len(posiC) < 1 ) and stime(g.atmoc)>0 and MA5_1<Ma20 :
                print("卖开")
       
        #下单卖开,2表示最新价
                #QuickInsertOrder(context.myacc,g.atmoc,'sell','open',PriceType(PbPriceType.Any),cshare)
                df = GetPositionsAsDF(context.accounts["回测期权"],buysellflag='buy')
                #print(df)
                if df.empty:
                    QuickInsertOrder(context.myacc,g.atmoc,'sell','open',PriceType(PbPriceType.Any),cshare)
                    #g.a = g.df[(g.df.date ==g.df.iloc[i,1])& (g.df.code == g.df.iloc[i,0])&(g.df.volume==g.df.iloc[i,6] )].index.tolist()
                        #删
                    #g.df.loc[g.a,'volume']=0
                    td = GetCurrentTime()
        
        #c = TradeDetails[price]
                    p=GetQuote(g.atmoc).now 
                    cp=2*p
        #print("第一次开仓价格",c)
                    df_insert = pd.DataFrame({'date':[td],
                                  'code':[g.atmoc],
                                  'price':[p],
                                  'volume':[cshare],
                                  'stoploss':[cp]})
                    g.df = g.df.append(df_insert,ignore_index = True)
                else:    
                
                #s1 = context.accounts["回测期权"].GetPositions(g.atmoc).volume
                    for i in range(len(df)):
                        QuickInsertOrder(context.myacc,g.atmopc_save,'buy','close',PriceType(PbPriceType.Any),df.iloc[i,3])
                        g.a = g.df[(g.df['code'] == g.atmopc_save)&(g.df['volume']==df.iloc[i,2] )].index.tolist()
                        #删
                        g.df.loc[g.a,'volume']=0
                    QuickInsertOrder(context.myacc,g.atmoc,'sell','open',PriceType(PbPriceType.Any),cshare)
        
                option = PBObj()
                option.offsetflag = '1'
                TradeDetails = context.accounts["回测期权"].GetTradeDetails(option)
        #成交合约总行数
                n = range(len(GetTradeDetailsAsDF(context.accounts["回测期权"]).index))
                option = PBObj()
                option.buysellflag = '1'
                option.contract = g.atmoc
       
                td = GetCurrentTime()
        
        #c = TradeDetails[price]
                c=GetQuote(g.atmoc).now 
                cp=2*c
        #print("第一次开仓价格",c)
                df_insert = pd.DataFrame({'date':[td],
                                  'code':[g.atmoc],
                                  'price':[c],
                                  'volume':[cshare],
                                  'stoploss':[cp]})
        
                g.df = g.df.append(df_insert,ignore_index = True)
            
            
            
            
            klinedatac = GetHisData2(g.atmopc_save,BarType.Day,count=20)
            MA = GetIndicatorAsDF("MA",g.biaodi,params={60},bar_type = BarType.Day)
            MA5_1= MA.iloc[-1,4]
            Ma20= MA.iloc[-1,1]
            Margin = OptionMargin(context.accounts["回测期权"],g.atmopc_save)
            if klinedatac != 0.0001:
                cshare = int(cash*0.2 / Margin)
            optionp = PBObj()
            optionp.buysellflag = '1'
            posiP = context.accounts["回测期权"].GetPositions(optionp)
            if (len(posiP) == 0 ) and stime(g.atmopc_save)>0 and MA5_1>Ma20:
                print("卖开")
       
        #下单卖开,2表示最新价
                #QuickInsertOrder(context.myacc,g.atmopc_save,'sell','open',PriceType(PbPriceType.Any),cshare)
                #s2 = context.accounts["回测期权"].GetPositions(g.atmopc_save).volume
                df = GetPositionsAsDF(context.accounts["回测期权"],buysellflag='buy')
                print(df)
                print("                       ")
                print(g.df)
                if df.empty:
                    QuickInsertOrder(context.myacc,g.atmopc_save,'sell','close',PriceType(PbPriceType.Any),cshare)
                    td = GetCurrentTime()
        
        #c = TradeDetails[price]
                    p=GetQuote(g.atmopc_save).now 
                    cp=2*p
        #print("第一次开仓价格",c)
                    df_insert = pd.DataFrame({'date':[td],
                                  'code':[g.atmopc_save],
                                  'price':[p],
                                  'volume':[cshare],
                                  'stoploss':[cp]})
                    #g.a = g.df[(g.df.date ==g.df.iloc[i,1])& (g.df.code == g.df.iloc[i,0])&(g.df.volume==g.df.iloc[i,6] )].index.tolist()
                        #删
                    #g.df.loc[g.a,'volume']=0
                else:    
                
                #s1 = context.accounts["回测期权"].GetPositions(g.atmoc).volume
                    for i in range(len(df)):
                        QuickInsertOrder(context.myacc,g.atmopc_save,'buy','close',PriceType(PbPriceType.Any),df.iloc[i,3])
                        g.a = g.df[(g.df['code'] == g.atmopc_save)&(g.df['volume']==df.iloc[i,2] )].index.tolist()
                        #删
                        g.df.loc[g.a,'volume']=0
                    QuickInsertOrder(context.myacc,g.atmopc_save,'sell','open',PriceType(PbPriceType.Any),cshare)
               
                option = PBObj()
                option.offsetflag = '0'
                TradeDetails = context.accounts["回测期权"].GetTradeDetails(option)
        #成交合约总行数
                n = range(len(GetTradeDetailsAsDF(context.accounts["回测期权"]).index))
                option = PBObj()
                option.buysellflag = '1'
                option.contract = g.atmopc_save
       
                td = GetCurrentTime()
        
        #c = TradeDetails[price]
                p=GetQuote(g.atmopc_save).now 
                cp=2*p
        #print("第一次开仓价格",c)
                df_insert = pd.DataFrame({'date':[td],
                                  'code':[g.atmopc_save],
                                  'price':[p],
                                  'volume':[cshare],
                                  'stoploss':[cp]})
        
                g.df = g.df.append(df_insert,ignore_index = True) 
# #第二次开仓
#             if (len(posiC) > 0 ) and stime(g.atmoc) ==20 and MA5_1<Ma20:
#                 print("卖开")
       
#         #下单卖开,2表示最新价
#                 QuickInsertOrder(context.myacc,g.atmoc,'sell','open',PriceType(PbPriceType.Any),cshare)
        
#                 option = PBObj()
#                 option.offsetflag = '0'
#                 TradeDetails = context.accounts["回测期权"].GetTradeDetails(option)
#         #成交合约总行数
#                 n = range(len(GetTradeDetailsAsDF(context.accounts["回测期权"]).index))
#                 option = PBObj()
#                 option.buysellflag = '0'
#                 option.contract = g.atmoc
       
#                 td = GetCurrentTime()
        
#         #c = TradeDetails[price]
#                 c=GetQuote(g.atmoc).now 
#                 cp=2*c
#                 df_insert = pd.DataFrame({'date':[td],
#                                   'code':[g.atmoc],
#                                   'price':[c],
#                                   'volume':[cshare],
#                                   'stoploss':[cp]})
        
#                 g.df = g.df.append(df_insert,ignore_index = True)
# #第3次开仓
#             if (len(posiC) > 0 ) and stime(g.atmoc) ==10 and MA5_1<Ma20:
#                 print("卖开")
       
#         #下单卖开,2表示最新价
#                 QuickInsertOrder(context.myacc,g.atmoc,'sell','open',PriceType(PbPriceType.Any),cshare)
        
#                 option = PBObj()
#                 option.offsetflag = '0'
#                 TradeDetails = context.accounts["回测期权"].GetTradeDetails(option)
#         #成交合约总行数
#                 n = range(len(GetTradeDetailsAsDF(context.accounts["回测期权"]).index))
#                 option = PBObj()
#                 option.buysellflag = '0'
#                 option.contract = g.atmoc
       
#                 td = GetCurrentTime()
        
#         #c = TradeDetails[price]
#                 c=GetQuote(g.atmoc).now 
#                 cp=2*c
           
#         #print("第一次开仓价格",c)
#                 df_insert = pd.DataFrame({'date':[td],
#                                   'code':[g.atmoc],
#                                   'price':[c],
#                                   'volume':[cshare],
#                                   'stoploss':[cp]})
#                 g.df = g.df.append(df_insert,ignore_index = True)

#z止损研究
        #下单卖开,2表示最新价
            """ 
            if len(g.df.index) > 0:
                for x in range(len(g.df.index)): 
                    position = str(g.df.iloc[x,0])  
                        
                    if position != None and GetQuote(position)!=None:
                        l = GetQuote(position).now
                    #内在价格
                        BSPrice = GetOptionBSPriceByCode(g.atmoc, stime(position), pricetype = "lastclose", r = 0.03)
                    #时间价值
                        Tprice =  l - BSPrice
                        if  l != None :
                    #亏损大于时间价值,开始准备
                            if stime(position) != 0 and \
                                l - g.df.iloc[x,4] > 0:
#                                     print("平仓")      
#                                     QuickInsertOrder(context.myacc,g.df.iloc[x,0],'sell','close',PriceType(PbPriceType.Any),g.df.iloc[x,6])          
#                                     print("代码",position)
#                                     print("进场日期",g.df.iloc[x,1])
#                                     print("手数",g.df.iloc[x,6])
#                                     print("进厂价",g.df.iloc[x,4],"当期价格",l)
#                                     print("当前日期",GetCurrentTime())
                                    self.log('开始止损')
                                    QuickInsertOrder(context.myacc,g.atmopc_save,'buy','open',PriceType(PbPriceType.Any),g.df.iloc[x,6])
                        #查
                                    #g.a = g.df[(g.df.date ==g.df.iloc[x,1])& (g.df.code == g.df.iloc[x,0])&(g.df.volume==g.df.iloc[x,6] )].index.tolist()
                        #删
                                   # g.df.loc[g.a,'volume']=0
                        
                       
                            elif stime(position) == 0 :
                                print("到期")                
                                QuickInsertOrder(context.myacc,g.df.iloc[x,0],'sell','close',PriceType(PbPriceType.Any),g.df.iloc[x,6])
                                QuickInsertOrder(context.myacc,g.df.iloc[x,0],'buy','close',PriceType(PbPriceType.Any),g.df.iloc[x,6])
                        #查
                                g.b = g.df[(g.df.date ==g.df.iloc[x,1])& (g.df.code == g.df.iloc[x,0])&(g.df.volume==g.df.iloc[x,6] )].index.tolist()
                        #删
                        
                        
                                g.df.loc[g.b,'volume']=0
                            else:
                                pass
                        else:
                            pass
                    else:
                        pass
   
            else:
                pass
    """
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324322891&siteId=291194637
50