 
import pandas as pd
import datetime
import numpy as np
import plotly as pl
import plotly.graph_objs as go
import matplotlib.pyplot as plt
import math
import scipy
import random
import statistics 


import datetime 
import matplotlib.dates as mdates
import matplotlib.pyplot as plt

import mplfinance as mpf

import plotly
#import plotly.plotly as py
import plotly.graph_objs as go
# these two lines allow your code to show up in a notebook
from plotly.offline import init_notebook_mode, iplot
from plotly.subplots import make_subplots
import CoreDraw
init_notebook_mode()
import market_trade.core.CoreTraidMath
import plotly.express as px


class Ishimoku:
    
    def __init__(self, base_df, options={
        'dataType':'ohcl',
        'short':9,
        'middle':26,
        'long':52,
        'backstep':26,
        'forwardstep':26
        },needFig=False,showOnlyIndex=True,drawFig=False
                ):
        
        self.base_df=base_df.reset_index(drop=True)
        self.options=options

        self.ans=self.getAns()
        if needFig:
            self.fig=self.pltShow(showOnlyIndex,drawFig)
        
        
    def getTankenSen(self):
        y=np.asarray([])
        x=np.asarray([])
        for i in range(self.options['short'],self.base_df.shape[0]):
            maxValue=max(self.base_df['high'][i-self.options['short']:i])
            minValue=min(self.base_df['low'][i-self.options['short']:i])
            y=np.append(y,(maxValue+minValue)*0.5)
            x=np.append(x,self.base_df['date'][i])
            #ts.append(max(self.base_df[self.options['colName']['high']][i-self.options['short']:i]))
        ans={'y':y,'x':x}
        return(ans)
    
    def getKijunSen(self):
        y=np.asarray([])
        x=np.asarray([])
        for i in range(self.options['middle'],self.base_df.shape[0]):
            maxValue=max(self.base_df['high'][i-self.options['middle']:i])
            minValue=min(self.base_df['low'][i-self.options['middle']:i])
            y=np.append(y,(maxValue+minValue)*0.5)
            x=np.append(x,self.base_df['date'][i])
            #ts.append(max(self.base_df[self.options['colName']['high']][i-self.options['short']:i]))
        ans={'y':y,'x':x}
        return(ans)
    
    def getChinkoSpan(self):
        y=np.asarray(self.base_df['close'][self.options['backstep']:])
        x=np.asarray(self.base_df['date'][:self.base_df.shape[0]-self.options['backstep']])
        ans={'y':y,'x':x}
        return(ans)    
    
    def getSenkouSpanA(self, data):
        y=np.asarray([])
        x=np.asarray([])
        shift=len(data['TankenSen']['y'])-len(data['KijunSen']['y'])
        for i in range(len(data['KijunSen']['x'])-self.options['forwardstep']):
            y=np.append(y,(data['KijunSen']['y'][i]+data['TankenSen']['y'][i+shift])*0.5)
            x=np.append(x,data['KijunSen']['x'][i+self.options['forwardstep']])
            
        ans={'y':y,'x':x}
        return(ans)    
    
    def getSenkouSpanB(self):
        y=np.asarray([])
        x=np.asarray([])
        for i in range(self.options['long'],self.base_df.shape[0]-self.options['forwardstep']):
            maxValue=max(self.base_df['high'][i-self.options['long']:i])
            minValue=min(self.base_df['low'][i-self.options['long']:i])
            y=np.append(y,(maxValue+minValue)*0.5)
            x=np.append(x,self.base_df['date'][i+self.options['forwardstep']])
            #ts.append(max(self.base_df[self.options['colName']['high']][i-sel        
        
        ans={'y':y,'x':x}
        return(ans)    
    
    
    
    
    
    
    def getAns(self):
        ans={}
        ans['TankenSen']=self.getTankenSen()
        ans['KijunSen']=self.getKijunSen()
        ans['ChinkoSpan']=self.getChinkoSpan()
        ans['SenkouSpanA']=self.getSenkouSpanA(ans)
        ans['SenkouSpanB']=self.getSenkouSpanB()
        #print(ans)
        return(ans)
    
    
    def pltShow(self,showOnlyIndex,drawFig):
        ans=None
        req=[]
        
        req.append({
            'vtype':'Scatter',
            'df':pd.DataFrame(
                {'value':self.ans['TankenSen']['y'],'date':self.ans['TankenSen']['x']}) ,
            'row':1,
            'col':1,
            'name':'TankenSen'
            
        })
        
        req.append({
            'vtype':'Scatter',
            'df':pd.DataFrame(
                {'value':self.ans['KijunSen']['y'],'date':self.ans['KijunSen']['x']}) ,
            'row':1,
            'col':1,
            'name':'KijunSen'
            
        })        

        req.append({
            'vtype':'Scatter',
            'df':pd.DataFrame(
                {'value':self.ans['ChinkoSpan']['y'],'date':self.ans['ChinkoSpan']['x']}) ,
            'row':1,
            'col':1,
            'name':'ChinkoSpan'
            
        })        

        req.append({
            'vtype':'Scatter',
            'df':pd.DataFrame(
                {'value':self.ans['SenkouSpanA']['y'],'date':self.ans['SenkouSpanA']['x']}) ,
            'row':1,
            'col':1,
            'name':'SenkouSpanA'
            
        }) 
        req.append({
            'vtype':'Scatter',
            'df':pd.DataFrame(
                {'value':self.ans['SenkouSpanB']['y'],'date':self.ans['SenkouSpanB']['x']}) ,
            'row':1,
            'col':1,
            'name':'SenkouSpanB'
            
        })
        
        
        if not showOnlyIndex:
            req.append({
                'vtype':'OCHL',
                'df':self.base_df,
                'row':1,
                'col':1,
                'name':'OHCL'

            })
        self.figDict=req
        ans = market_trade.core.CoreDraw.coreDraw(req,drawFig)
        #print(ans)
        return ans
