# -*- coding: utf-8 -*-
"""
Created on Tue Apr  2 19:33:11 2019

@author: cpace
"""

from Modules.dataseries import dataseries
from Modules.indicators import ema as ema
import numpy as np
import matplotlib.pyplot as plt
import MySQLdb
import datetime
import calendar

crop = 'Gasoline'
month = 'Aug'
totalyearsincluded = 1
emalength = 13
positions = []
prefinal = []
final = []
win = 0
loss = 0
sumprofit = 0



abbr_to_num = {name: num for num, name in enumerate(calendar.month_abbr) if num}
monthnum = abbr_to_num[month]


print('Commodity ' + str(crop))
print('Month ' + str(month))

db = MySQLdb.connect(host="a2nlmysql13plsk.secureserver.net",  # your host 
                     user="coreypace",       # username
                     passwd="Aud12rey",     # password
                     db="FarmBusiness")   # name of the database

cur = db.cursor()

def getfirstyear(commodity):
    sql = 'select FirstYear from MarketCommodity where DBName = "' + str(commodity) + '"'
    cur.execute(sql)
    firstyear = cur.fetchall()[0][0]
    return max(firstyear,datetime.datetime.now().year - totalyearsincluded)

for year in range(getfirstyear(crop),datetime.datetime.now().year+1):
    position = 'start'
    count = 13
    looking = True
    df = dataseries(crop, month, year).dataseries
        
    xma = ema(df.Close,emalength).ema
    nRes = df.Low - xma
    
    while count < len(df)-2:
        if position == 'start':
            if nRes[count] < 0:
                position = 'short'
            else:
                position = 'long'
        
        if nRes[count] < 0 and position == 'long':
            position = 'short'
        elif nRes[count] > 0 and position == 'short':
            position = 'long'
        
        if position != 'start':
           positions.append([year, df.Date[count+1], df.Open[count+1], position])
        count += 1
        
for i in range(1,len(positions)):
    if positions[i][3] != positions[i-1][3]:
        prefinal.append([positions[i][0],positions[i][1],positions[i][2],positions[i][3]])
    
for i in range(0,len(prefinal)-1):
    if prefinal[i][3] != prefinal[i-1][3]:
        if prefinal[i][3] == 'short':
            profit = prefinal[i][2] - prefinal[i+1][2]
        else:
            profit = prefinal[i][2] - prefinal[i+1][2]
        final.append([positions[i][0],positions[i][1],positions[i][2],positions[i][3],profit])
        if profit > 0:
            win += 1
        else:
            loss +=1
        sumprofit += profit
   
#for i in range(len(final)):
#    if final[i][1] == 0:
#        loser += 1
#    else:
#        winner += 1
#        sumwins += final[i][3]
#        sumdays += final[i][1]
#        percenthigh += final[i][2]
##        d.append(final[i][2])
#        high.append(final[i][3])
#    
#    if final[i][4] > 0:
#        nextdaywin += 1
#        nextdaywinnings += final[i][4]
#        d.append(final[i][4])
#        nextdaydrawdown += final[i][5]
#        
#        if final[i][5] > maxdrawdown:
#            maxdrawdown = final[i][5]
#        
#try:
#    print(str(winner) + ' Wins (Closed below line at least 2 days)')
#    print(str(loser) + ' Losers (Closed above line next day)')
#    print(str(round(winner/(winner+loser)*100,1)) + '% Win Rate')
#    print('Avg Win - ' + str(round(sumwins/winner,3)))
#    print('Avg Days - ' + str(round(sumdays/winner,1)))
#    print('Avg Percent of High - ' + str(round(percenthigh/winner,1)) + '%')
#    print('Next Day % Winners - ' + str(round(nextdaywin/(winner+loser)*100,1)) + '%')
#    print('Average Next Day Winnings - $' + str(round(nextdaywinnings/nextdaywin,3)))
#    print('Average Next Day Drawdown - $' + str(round(nextdaydrawdown/nextdaywin,3)))
#    print('Max Next Day Drawdown - ' + str(round(maxdrawdown,2)))
#except:
#    True



cur.close()