Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert OHLC values to Renko chart in Python?

I have been trying to match the Renko chart on Tradingview for the past few hours and still can't seem to figure out what I am doing wrong.

So far my algo spits out the right values except in cases where the trend reverses.

import math
import pandas as pd


def bricks_series(df: pd.DataFrame, step=50):
    prices = df['close']
    first_brick = math.floor(prices.iloc[0] / step) * step
    bricks = [first_brick]
    for price in prices:
        if price > (bricks[-1] + step):
            step_mult = math.floor((price - bricks[-1]) / step)
            next_bricks = [bricks[-1] + (mult * step) for mult in range(1, step_mult + 1)]
            bricks += next_bricks
        elif price < bricks[-1] - step:
            step_mult = math.ceil((bricks[-1] - price) / step)
            next_bricks = [bricks[-1] - (mult * step) for mult in range(1, step_mult + 1)]
            bricks += next_bricks
        else:
            continue
    return bricks


if __name__ == "__main__":
    df = pd.read_csv("binance_daily.csv")
    renko_bricks = bricks_series(df)

Here is my ohlc data. https://drive.google.com/open?id=1Psn8XYBwJ9F5JCTpF0ffxQx_vcLSFyD4

and here is the chart I am trying to replicate. https://www.tradingview.com/chart/lyXNhcbs/

like image 435
pAulseperformance Avatar asked Mar 09 '26 04:03

pAulseperformance


1 Answers

You can use lib "Renko" to get renko-chart and also get renko-blocks and then convert to ohlc-dataframe code:

# !pip install renko yfinance
from renko import Renko
import yfinance as yf
ticker = "AAPL"
ohlcv_data = yf.download(ticker, period="1y")
ohlcv_data.columns = ohlcv_data.columns.str.lower()
renko = Renko(brick_size=5, data=ohlcv_data.close)
renko.create_renko()
renko_ohlc = pd.DataFrame(renko.bricks)
# fill nan
mask_upL = renko_ohlc[renko_ohlc.type == 'up'].low.isna()
mask_upL = mask_upL[mask_upL == True].index
mask_downL = renko_ohlc[renko_ohlc.type == 'down'].low.isna()
mask_downL = mask_downL[mask_downL == True].index
mask_upH = renko_ohlc[renko_ohlc.type == 'up'].high.isna()
mask_upH = mask_upH[mask_upH == True].index
mask_downH = renko_ohlc[renko_ohlc.type == 'down'].high.isna()
mask_downH = mask_downH[mask_downH == True].index
renko_ohlc.loc[mask_upL, 'low'] = renko_ohlc.loc[mask_upL, 'open']
renko_ohlc.loc[mask_downL, 'low'] = renko_ohlc.loc[mask_downL, 'close']
renko_ohlc.loc[mask_upH, 'high'] = renko_ohlc.loc[mask_upH, 'close']
renko_ohlc.loc[mask_downH, 'high'] = renko_ohlc.loc[mask_downH, 'open']
renko_ohlc = renko_ohlc[1:]
print(renko_ohlc)
renko.draw_chart()

Output chart: enter image description here Output ohlc-dataframe: enter image description here

like image 87
V Z Avatar answered Mar 10 '26 19:03

V Z