import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['WenQuanYi Micro Hei']
matplotlib.rcParams['axes.unicode_minus'] = False
import numpy as np
import pandas as pd
import time
import warnings
from sklearn import tree
warnings.filterwarnings("ignore")
from sklearn.ensemble import RandomForestClassifier
from datetime import datetime
from sklearn import linear_model
from chinese_calendar import is_workday
from datetime import timedelta
import json
import matplotlib.dates as mdate

pt='铁矿石'
#输入品种
input_path="/www/wwwroot/file.jsfsdata.com/tks_mc.xls"
#输入路径，指向当前目录的file目录
out_path="/www/wwwroot/file.jsfsdata.com/rs"
#输出路径，指向当前目录的file目录
t=30
#输入持仓时间

def get_week(date):
    apply_time = datetime.strptime(str(date),'%Y%m%d')
    time_str = apply_time.strftime("%Y-%m-%d %H:%M:%S")
    apply_week = datetime.strptime(time_str.split(" ")[0], "%Y-%m-%d").weekday()
    return apply_week

def data_done(input_path,t):
    df = pd.read_excel(input_path).iloc[1:,:3]
    df = df.dropna().reset_index(drop=True)
    df.columns = ['date','price_X','price_Q']
    df['price_X']=df['price_X'].astype(float)
    df['price_Q']=df['price_Q'].astype(float)
    df['dt'] = df['date'].apply(lambda x:int(''.join(str(x)[0:4] + str(x)[5:7]  +str(x)[8:10])))
    df['mo'] = df['date'].apply(lambda x:int(''.join(str(x)[5:7])))
    df['wk'] = df['dt'].apply(lambda x: get_week(x))
    df['jc']=None
    df['jc']=df['price_X']-df['price_Q']
    #添加参数前180，90，30, 15的期现货相关系数，已经价格在其区间内位置
    a=[15,30,90,180]
    for i in a:
        df['cor'+str(i)]=None
        df['Xd'+str(i)]=None
        df['Qd'+str(i)]=None
        for j in range(i-1,df.shape[0]):
            df['cor'+str(i)][j]=df['price_X'][(j+1-i):(j+1)].corr(df['price_Q'][(j+1-i):(j+1)])
            df['Xd'+str(i)][j]=(df['price_X'][j]-min(df['price_X'][(j+1-i):(j+1)]))/(max(df['price_X'][(j+1-i):(j+1)])-min(df['price_X'][(j+1-i):(j+1)]))
            df['Qd'+str(i)][j]=(df['price_Q'][j]-min(df['price_Q'][(j+1-i):(j+1)]))/(max(df['price_Q'][(j+1-i):(j+1)])-min(df['price_Q'][(j+1-i):(j+1)]))
    dframe=df.copy()
    #每隔10个交易日都按最低价取1/6的货，期货市场考虑在卖出时就进行对应操作
    dframe['average1']=None
    dframe['average2']=None
    dframe['if1']=0.0
    dframe['if2']=0.0
    for i in range(dframe.shape[0]-t):
        dframe['average1'][i]=0
        dframe['average2'][i]=0
        for j in range(0,6):
            k=dframe.iloc[(i+1+int(t/6)*j):(i+1+int(t/6)*j+int(t/6)),1:3].reset_index(drop=True)
            dframe['average1'][i]+=min(k.iloc[:,0])
            dframe['average2'][i]+=max(k[k['price_X']==min(k.iloc[:,0])]['price_Q'])
        dframe['average1'][i]=dframe['average1'][i]/6
        dframe['average2'][i]=dframe['average2'][i]/6
        dframe['if1'][i]+=-(dframe.iloc[i,1]-dframe['average1'][i])/dframe.iloc[i,1]
        dframe['if2'][i]+=(dframe.iloc[i,2]-dframe['average2'][i])/dframe.iloc[i,2]
    dframe['ifall']=dframe['if1']+dframe['if2']
    df['if']=((dframe['if2']>0)&(dframe['if1']<0)).astype('int')+((dframe['if2']>0.05)&(dframe['if1']<0)).astype('int')+((dframe['if2']>0.1)&(dframe['if1']<0)).astype('int')
    df=df.dropna().reset_index(drop=True)
    train = df[df['dt']>=20150000].reset_index(drop=True).iloc[:-t,:]
    test = df.iloc[-t:,:]
    return train,test,df

def get_result(input_path):
    train,test,price_data=data_done(input_path,t)
    train_data=train.drop(['date','dt'],axis=1)
    clf = tree.DecisionTreeClassifier()
    clf = clf.fit(train_data.iloc[:,2:-1],train_data.iloc[:,-1])
    test_data=pd.concat([train,test],ignore_index=True).reset_index(drop=True)
    test_data['if']=clf.predict(test_data.drop(['date','dt'],axis=1).iloc[:,2:-1])
    result=test_data[['date','price_X','price_Q','if']]
    for i in range(result.shape[0]):
        result['date'][i]=result['date'][i].strftime("%Y-%m-%d")
#    t1 =test_data.iloc[-1, 0]
#    worklist = []
#    while len(worklist)<5:
#        t1 = t1 + timedelta(1)
#        if is_workday(t1):
#            worklist.append(t1)
#    worklist = pd.DataFrame(worklist)
#    worklist.columns = ['date'] 
#    price_data=price_data.drop(['date','dt','if'],axis=1)
#    price_tdata=price_data.iloc[-5:,2:]
#    price_data.iloc[5:,2:]=price_data.iloc[:-5,2:].values
#    price_train=price_data.iloc[5:,:].reset_index(drop=True)
#    model =  linear_model.LinearRegression()
#    model.fit(X=price_train.iloc[:,2:],y=price_train.iloc[:,0])
#    worklist['price_X']=model.predict(price_tdata)
#    model.fit(X=price_train.iloc[:,2:],y=price_train.iloc[:,1])
#    worklist['price_Q']=model.predict(price_tdata)
#    result=pd.concat([result,worklist],ignore_index=True).reset_index(drop=True)
    return result

result=get_result(input_path)

df = pd.read_excel(input_path).iloc[1:,:3]

plt.figure(figsize=(8,5))
hui_data = result[result['date']>'2018-12-31'].reset_index(drop=True)
xs = [datetime.strptime(str(d), '%Y-%m-%d %H:%M:%S').date() for d in hui_data['date']]
a=xs[-1]
plt.plot(xs,hui_data['price_X'],label=df.columns.values[-2])
plt.plot(xs,hui_data['price_Q'],label=df.columns.values[-1])
plt.gcf().autofmt_xdate() 
mc=hui_data[hui_data['if']>0].reset_index(drop=True)
xs = [datetime.strptime(str(d), '%Y-%m-%d %H:%M:%S').date() for d in mc['date']]
plt.plot(xs,mc['price_Q'],'o', ms=2,color='green',label="适合卖出套保点")
plt.legend(loc=2)
plt.title('期现卖出套保模型策略（'+pt+'）',fontsize=20)
plt.ylabel('期/现货价格', fontdict={ 'size'   : 10})
k=[]
jc= hui_data['price_X'].iloc[-1]-hui_data['price_Q'].iloc[-1]
j1=(hui_data['price_X'].iloc[-1]-min(hui_data['price_X'].iloc[-180:-1]))/(max(hui_data['price_X'].iloc[-180:-1])-min(hui_data['price_X'].iloc[-180:-1]))
j2=(hui_data['price_Q'].iloc[-1]-min(hui_data['price_Q'].iloc[-180:-1]))/(max(hui_data['price_Q'].iloc[-180:-1])-min(hui_data['price_Q'].iloc[-180:-1]))
bj=['低','中','高']
if int(j1*4)==0:
    jj1=bj[0]
elif int(j1*4)>=3:
    jj1=bj[2]
else:
    jj1=bj[1]
if int(j2*4)==0:
    jj2=bj[0]
elif int(j2*4)>=3:
    jj2=bj[2]
else:
    jj2=bj[1]
xs = [datetime.strptime(str(d), '%Y-%m-%d %H:%M:%S').date() for d in hui_data['date']]
half = len(xs) // 2
wt=max(hui_data['price_Q'].max(),hui_data['price_X'].max())-min(hui_data['price_Q'].min(),hui_data['price_X'].min())
plt.xlabel( '参考要素：当前基差'+str(round(jc,2))+'，现货绝对价格处于'+jj1+'位，期货绝对价格处于'+jj2+'位，季节因素;', fontsize=10 , color='black')
if hui_data['if'].iloc[-1]==0:
    annatation =str(hui_data['date'].iloc[-1])+ '不适合对'+pt+'当前活跃合约进行卖出操作'
    k.append(annatation)
    plt.text(a,hui_data['price_Q'].iloc[-1]+15 , '不卖出', ha='center', va='bottom', fontsize=20 , color='green')
elif hui_data['if'].iloc[-1]==1:
    annatation = str(hui_data['date'].iloc[-1])+ '适合对'+pt+'当前活跃合约进行卖出操作,卖出等级1颗星,持仓时间为'+str(t)+'天'
    k.append(annatation)
    plt.text(a,hui_data['price_Q'].iloc[-1]+15 , '卖出\n*', ha='center', va='bottom', fontsize=20 ,color='green')
    plt.plot(a,hui_data['price_Q'].iloc[-1],'o', ms=10, c='green')
elif hui_data['if'].iloc[-1]==2:
    annatation = str(hui_data['date'].iloc[-1])+ '适合对'+pt+'当前活跃合约进行卖出操作,卖出等级2颗星,持仓时间为'+str(t)+'天'
    k.append(annatation)
    plt.text(a,hui_data['price_Q'].iloc[-1]+15 , '卖出\n**', ha='center', va='bottom', fontsize=20 ,color='green')
    plt.plot(a,hui_data['price_Q'].iloc[-1],'o', ms=10, c='green')
elif hui_data['if'].iloc[-1]==3:
    annatation = str(hui_data['date'].iloc[-1])+ '适合对'+pt+'当前活跃合约进行卖出操作,卖出等级3颗星,持仓时间为'+str(t)+'天'
    k.append(annatation)
    plt.text(a,hui_data['price_Q'].iloc[-1]+15 , '卖出\n***', ha='center', va='bottom', fontsize=20 ,color='green')   
    plt.plot(a,hui_data['price_Q'].iloc[-1],'o', ms=10, c='green')
plt.savefig(out_path+'/tksmc.png',dpi=100)
#plt.show()
k.append('参考要素：当前基差'+str(round(jc,2))+'，现货绝对价格处于'+jj1+'位，期货绝对价格处于'+jj2+'位，季节因素')
with open(out_path+'/'+pt+'卖出套保推荐结果.json','w',encoding='utf-8') as f:
    json.dump(k,f,ensure_ascii=False)