import pandas_datareader as pdr
import datetime
from stocktrends import Renko


ticker = 'TSLA'
ohlcv = pdr.get_data_yahoo(ticker, datetime.date.today() - datetime.timedelta(1025), datetime.date.today())
df = ohlcv.copy()

def ATR(DF, n):
    '''
    Function to calculate True Range and Average True Range
    
    Parameters
    ----------
    DF : DataFrame
        DESCRIPTION.
    n : int
        number of days.

    Returns
    -------
    DataFrame.

    '''
    df = DF.copy()
    df['H-L'] =  abs(df['High'] - df['Low'])
    df['H-PC'] = abs(df['High'] - df['Adj Close'].shift(1))
    df['L-PC'] = abs(df['Low'] - df['Adj Close'].shift(1)) # shift(n): Move n positive direction
    df['TR'] = df[['H-L', 'H-PC', 'L-PC']].max(axis=1, skipna=False)
    df['ATR'] = df['TR'].rolling(n).mean() # rolling(n): Take window of n
    # df['ATR'] = df['TR'].ewm(span=n, adjust=False, min_periods=n).mean() # Exponential mean
    
    df2 = df.drop(['H-L', 'H-PC', 'L-PC'], axis=1)
    return df2


def renko_dataframe(DF):

    '''
        Function to make renko chart
        
    '''
    
    df = DF.copy()
    df.rename(columns = {"High" : "high","Low" : "low", "Open" : "open","Close" : "close", "Volume" : "volume"}, inplace = True)
    
    df['date'] = df.index
    df.reset_index(inplace = True)
    renko_df = Renko(df)
    renko_df.brick_size = round(ATR(DF, 120)['ATR'][-1], 0)
    df2 = renko_df.get_ohlc_data()
    return df2