# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 08:11:25 2019

@author: cpace
"""
import numpy as np
from Modules.dataseries import dataseries
from Modules.indicators import bolinger
from Modules.indicators import rsi
from Modules.indicators import macd
from Modules.contractmonths import contractmonths as months
from Modules.indicators import adx

crop = 'corn'
month = 'jul'
year = 2013

out = [] # [$win,$loss, ctwin, ctloss, totcount]
days = 4

a = dataseries(crop, month, year)

final = []
total = []

def findpullback(j, npdf, k='last'):
    diffthresh = 2
    for i in range(j,len(npdf)-1):
#        if(npdf[i,5]>=20):
#            i = findnextzero(i)
#        else:
#            k='last'
        if k != 'last':  # initial look to find beginning
            if npdf[i+1,6] < 0 and npdf[i,6] > npdf[i-1,6] and abs(npdf[i,6]) > diffthresh:   #rising negative difference > 1.5
                return [i+1,'start']
            elif npdf[i+1,6] > 0 and npdf[i,6] < npdf[i-1,6] and abs(npdf[i,6]) > diffthresh: #falling positive difference > 1.5
                return [i+1,'start']
                    
        else: # last
            if npdf[j,6] > 0:  # Short postion
                if npdf[i,6] < 0 and npdf[i,6] > npdf[i-1,6] and abs(npdf[i,6]) > diffthresh: #rising negative difference > 1.5
                    return [i+1,'short']
            elif npdf[j,6] < 0:  # Long position
                if npdf[i,6] > 0 and npdf[i,6] < npdf[i-1,6] and abs(npdf[i,6]) > diffthresh: #falling positive difference > 1.5
                    return [i+1, 'long']
    return [i+1,'complete']
        
def findnextzero(i):
    for i in range(i,len(npdf)-days):
        if np.isnan(difference[i-1]) == False:
            if np.sign(difference[i]) != np.sign(difference[i-1]) or difference[i] ==0:
                return i
            

for crop in ['Wheat']:
    for year in range(2010,2018):
        contractmonths = months(crop)
        monthlist = contractmonths.months
        for month in monthlist:
            yeartotal = 0
            trades = 0
            a = dataseries(crop, month, year)
            df = a.dataseries
            df = adx(df,14).adx
            df = macd(df).difference
            
                
            npdf = np.asarray(df)
            difference = np.array(npdf[:,6],dtype='f')
            close = np.array(npdf[:,4],dtype='f')
            
            i = findnextzero(1)
            
            i, postion = findpullback(i,npdf,'first')
            
            positionentry = npdf[i,4]
            entrydate = npdf[i,0]
            look = True
            
            while look:
                i, position = findpullback(i,npdf,'last')    
                positionexit = npdf[i,4] 
                exitdate = npdf[i,0]  
                if position == 'long':
                    profit = positionexit - positionentry
                else:
                    profit = positionentry - positionexit
                
                out.append([position, entrydate, exitdate, profit, npdf[i,5]])
#                print(position + ' Position between ' + str(entrydate) + ' and ' + str(exitdate) + ' for ' + str(profit) + ' ADX = '+ str(npdf[i,5]))
                positionentry = positionexit
                entrydate = exitdate
                
                
                if i == len(npdf)-1:
                    look = False
            
            final = [0,0,0]        
            for i in range(len(out)):
                if  out[i][0] != 'complete':
                    if out[i][3] > 0:
                        win = 1
                        loss = 0
                    else:
                        win = 0
                        loss = 1
                    final = [final[0]+out[i][3], final[1] + win, final[2] + loss]
                    final.append(final[1]/(final[1]+final[2])*100)
    

a.closeconn()          