# -*- coding: utf-8 -*-
"""
Created on Mon Feb 11 08:11:25 2019

DO NOT DELETE THIS -- THIS WORKS 75% OF THE TIME ON WHEAT

@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
from Modules.indicators import stochastics
from Modules.pnp import pnp
import datetime

#crop = 'corn'
#month = 'jul'
#year = 2013

finalout = [] # [$win,$loss, ctwin, ctloss, totcount]
finalout1 = []
days = 4

#a = dataseries(crop, month, year)

final = []
total = []

def endofrise(row, col, thresh=70):
    if npdf[row][col] <= npdf[row-1][col] and npdf[row][col] >= thresh:
        return True
    elif npdf[row][col] > 85 and npdf[row-1][col] < thresh:
        return True
    else:
        return False
    
def endoffall(row, col, thresh=30):
    if npdf[row][col] >= npdf[row-1][col] and npdf[row][col] <= thresh:
        return True
    else:
        return False
    
def istrending(trending, row, col, thresh=30, endthresh=18):  # looks like 18 for stochastics
    if npdf[row][col] >= thresh:
        return True
    elif trending and npdf[row][col] > endthresh:
        return True
    else:
        return False
    
def beginrise(row, col, thresh=30):
    if npdf[row][col] > thresh and npdf[row-1][col] < thresh and npdf[row-1][col] != 0 and npdf[row][5] != 0:
        return True
    else:
        return False
    
def beginfall(row, col, thresh=70):
    if npdf[row][col] < thresh and npdf[row-1][col] > thresh and npdf[row-1][col] != 0 and npdf[row][5] != 0:
        return True
    else:
        return False
    
def belowpnplow(row):
    month = npdf[row][0].strftime('%m')
    year = int(npdf[row][0].strftime('%Y'))
    frontmonth = {'01':'Mar', '02':'Mar', '03':'May', '04':'May', '05':'Jul', '06':'Jul', '07':'Sep', '08':'Sep', '09':'Dec', '10':'Dec', '11':'Dec', '12':'Mar'}
    if month == '12': year += 1
    b = pnp('Wheat', frontmonth[month], year)
    bestlow = b.minBestFit
    a1 = dataseries('Wheat', frontmonth[month], year)
    df1 = a1.dataseries
    data = df1.loc[df1['Date']==npdf[row][0]].Close
    if float(data.item()) < bestlow: return True
    
upper = 70
lower = 30
trend = 30   
i = 0   

for crop in ['Wheat']:
    for year in range(2019,2020):
        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 = stochastics(df).stochastics
            df = macd(df).difference
               
            npdf = np.asarray(df)
            
            i = 0 
            look = True
            long = False
            short = False
            trending = False
            position = ''
            indcol = 9
            
            while i < len(npdf)-5:
                while look and i < npdf.shape[0]-5:
                    trending = istrending(trending, i, 5, thresh=40)
                    if npdf[i,indcol]<0 and npdf[i+1,indcol]>0 and trending and not long and npdf[i-1,6]<30 and npdf[i,6]>30:
                        positionentry = npdf[i,4]
                        entrydate = npdf[i,0]
                        look = False
                        short = False
                        long = True
                        positionexit = npdf[i+5,4]
                        exitdate = npdf[i+5,0]
                        i+=4
                        break
                   
                    else:
                        i += 1
                    i+=1
                                   
#                while long and i < len(npdf):
#                    trending = istrending(trending, i, 5)
#                    if not trending and endoffall(i,indcol,lower):
#                        positionexit = npdf[i,4]
#                        exitdate = npdf[i,0]
#                        look = True
##                        short = False
#                        long = False
#                        break
#                    i += 1
#                i+=1
                
                if i > npdf.shape[0]-3:
                    positionexit = npdf[i-3,4]
                    exitdate = npdf[i-3,0]
 
                if long:
                    profit = positionexit - positionentry
                    long = False
                    position = 'Long'
                elif short:
                    profit = positionentry - positionexit
                    short = False
                    position = 'Short'
                else:
                    position = ''
                
                if position != '':
                    finalout.append([position, entrydate, exitdate, profit, positionentry, positionexit, month, year])
                    look = True
                    long = False
                    short = False
                    position = ''
                    exitdate = ''
                    positionentry = 0
                    positionexit = 0
                    entrydate = ''
            
            final = [0,0,0]        
            for i in range(len(finalout)):
                if  finalout[i][0] != 'complete':
                    if finalout[i][3] > 0:
                        win = 1
                        loss = 0
                    else:
                        win = 0
                        loss = 1
                    final = [final[0]+finalout[i][3], final[1] + win, final[2] + loss]
                    final.append(final[1]/(final[1]+final[2])*100)
                    
                    
    

a.closeconn()          