 
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 market_trade.core.CoreTraidMath
import market_trade.core.CoreDraw
init_notebook_mode()

class ADXI:
    
    def __init__(self, base_df, options={
        'dataType':'ohcl',

    }, needFig=False,showOnlyIndex=True,drawFig=False):
        self.base_df=base_df.reset_index(drop=True)
        self.options=options
        #self.norm_df=self.nornalize()
        #self.col=col
        #self.npCol=np.asarray(self.norm_df[self.col], dtype=np.float32)
        #self.options=options
        self.ans=self.getAns()
        if needFig:
            self.fig=self.pltShow(showOnlyIndex,drawFig)
        

    def getDM(self):
        
        #m,p=self.getMP()
        dm_m=np.asarray([])
        dm_p=np.asarray([])
        tr=np.asarray([])

        
        for i in range(1,self.base_df.shape[0]):
            if (self.base_df['open'][i]>=
                self.base_df['open'][i-1]):
                dm_p=np.append(dm_p,self.base_df['open'][i]-self.base_df['open'][i-1])
            else:
                dm_p=np.append(dm_p,0)
            if (self.base_df['close'][i]<=self.base_df['close'][i-1]):
                dm_m=np.append(dm_m,self.base_df['close'][i-1]-self.base_df['close'][i])
            else:
                dm_m=np.append(dm_m,0)            

            tr=np.append(tr,
                         max(self.base_df['close'][i-1],self.base_df['high'][i])-
                         min(self.base_df['close'][i-1],self.base_df['low'][i]))
        
        
        setattr(self,'dm_m',dm_m)
        setattr(self,'dm_p',dm_p)
        setattr(self,'tr',tr)
        
        return dm_m,dm_p
    
    def getEMA(self,Col):
        ser = pd.Series(Col, copy=False)
        op={'dataType':'series',
            'action':'findMean',
            'actionOptions':{'MeanType':'EMA','span':10}
        }        
        ans=np.asarray(CoreTraidMath.CoreMath(ser,op).ans)
        #print(ans)
        #ans = np.asarray(ser.ewm(span=40,adjust=False).mean().to_list())
        #print(ans)
        #return(np.asarray(ser.ewm(span=40,adjust=False).mean().to_list()))
        return ans
    
    def getDI(self):
        dm,dp=self.getDM()
        
        dip=self.getEMA(dp/self.tr)
        dim=self.getEMA(dm/self.tr)
        
        return dim,dip
    
    def getAns(self):

        dim,dip=self.getDI()
        np.seterr(invalid='ignore')
        col=abs(np.true_divide((dim-dip),(dim+dip)))
        setattr(self,'col',col)
        
        adx=self.getEMA(col)
        
        ans={
            'DIM':dim*100,
            'DIP':dip*100,
            'ADX':adx*100
        }
        
        
        
        return ans
    
    def pltShow(self,showOnlyIndex,drawFig):
        ans=None
        req=[]
        
        row=1
        if not showOnlyIndex:
            
            row=2
            req.append({
                'vtype':'OCHL',
                'df':self.base_df,
                'row':1,
                'col':1,
                'name':'OHCL'

            })
            
        req.append({
            'vtype':'Scatter',
            'df':pd.DataFrame(
                {'value':self.ans['ADX'],'date':self.base_df['date'].to_list()[1:]}) ,
            'row':row,
            'col':1,
            'name':'SenkouSpanB'
            
        })
        req.append({
            'vtype':'Scatter',
            'df':pd.DataFrame(
                {'value':self.ans['DIP'],'date':self.base_df['date'].to_list()[1:]}) ,
            'row':row,
            'col':1,
            'name':'+DI'
            
        })
        req.append({
            'vtype':'Scatter',
            'df':pd.DataFrame(
                {'value':self.ans['DIM'],'date':self.base_df['date'].to_list()[1:]}) ,
            'row':row,
            'col':1,
            'name':'-DI'
            
        })
        
        self.figDict=req
        

                
        ans = market_trade.core.CoreDraw.coreDraw(req,drawFig)

        
        return ans
        
    

    




        
 
    
