# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

from Modules.dataseries import dataseries
from Modules.indicators import rsi
import numpy as np
import pandas as pd
import calendar
from datetime import datetime, timedelta
import matplotlib.pyplot as plt


crop = 'Corn'
month = 'May'
high = []

def ishigh(i):
    if npdf[i-1,5] < npdf[i,5] > npdf[i+1,5]:
        return True
    else: return False

def timediff(i,j):
    td = npdf[j,0]-npdf[i,0]
    return td.total_seconds() / timedelta(days=1).total_seconds()
    
def getm(i,j):
    return (npdf[j,5]-npdf[i,5])/timediff(i,j)

def getb(i,j):
    return (npdf[i,5] - getm(i,j) * timediff(i,j))

def gety(m, i, b, base):
    return m * timediff(base,i) + npdf[base,5]

# add data cols by year
out = []
startprice = []
         
for year in range(2006,2007):
    df = dataseries(crop, month, year).dataseries
    df = rsi(df,period = 4).rsi
    npdf = np.asarray(df)

    for h in range(4,len(npdf)-1):
        if ishigh(h):
            high.append(h)
       
    plt.plot(npdf[:,0],npdf[:,5])
    for point in range(len(high)):
        plt.annotate('%s' % npdf[high[point],0], xy=[npdf[high[point],0],npdf[high[point],5]])
    
    for i in range(0, len(high)-2):
    #for i in range(13,14):
        base = high[i]
        for j in range(i+1,len(high)-1):
            removeline = False
            second = high[j]
            if npdf[second,5] > npdf[base,5]: break
            m = getm(base, second)
            if m >= -0.3: continue
            b = getb(base, second)
            
    #        Check there are no points between two points on the line above line
            for q in range(i+1,j):
                if npdf[high[q],5] > gety(m,high[q],b,base) * 1.1: 
                    removeline = True
            
            if removeline: break
            
            for k in range(high[j+1],len(npdf)-5):
                y = gety(m,k,b,base)
                if npdf[k,5] > y * 1.1: 
                    if len(out)>0:
                        out.append(k) 
                        startprice.append([df.Date[k], df.Close[k], df.Close[k+5],m])
                    break
                if npdf[k,5]*0.95 < y <= npdf[k,5]*1.05:
                    out.append(k)
            if len(out) > 1:
                plt.plot([npdf[base,0],npdf[out[len(out)-1],0]],[gety(m,base,b,base),gety(m,out[len(out)-1],b,base)])
                plt.plot(np.asarray(df.Date[out]),np.asarray(df.RSI[out]),'r*')
            out = []


#plt.show()
    
