How to add time frame for candle using plotly library in Python?

Question:

I want to add a time frame for candlestick on a chart using plotly library. Is there a way to do that without iterating through data and taking every 4th tick (for 4h chart) and calculating high and low in between and all the calculations done in the background?

data = requests.get(url).json()

date = []
open = []
high = []
low = []
close = []
i = 0
k = 4
for tick in data:
    date.append(tick['time'])
    open.append(tick['open'])
    high.append(tick['high'])
    low.append(tick['low'])
    close.append(tick['close'])


fig = go.Figure(data=[go.Candlestick
                x=date,
                open=open,
                high=high,
                low=low,
                close=close)])

fig.update_layout(xaxis_rangeslider_visible=False, template='plotly_dark')

I couldn’t find solution for this that is helpful

Asked By: Alej4ndr0

||

Answers:

You can use the resample() method in the Pandas library to calculate the open, high, low, and close values for each time frame. For example, if you want to create a 4-hour candlestick chart, you can use the following code:

import pandas as pd

# Load data from URL
data = requests.get(url).json()

# Convert data to Pandas DataFrame
df = pd.DataFrame(data)

# Set the 'time' column as the index of the DataFrame
df = df.set_index('time')

# Calculate the open, high, low, and close values for each 4-hour time frame
df_4h = df.resample('4H').agg({'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last'})

# Create the candlestick chart using the calculated time frame values
fig = go.Figure(data=[go.Candlestick(
    x=df_4h.index,
    open=df_4h['open'],
    high=df_4h['high'],
    low=df_4h['low'],
    close=df_4h['close'])])

fig.update_layout(xaxis_rangeslider_visible=False, template='plotly_dark')

This code calculates the open, high, low, and close values for each 4-hour time frame using the resample() method and then creates a candlestick chart using these values. You can adjust the time frame by changing the argument passed to the resample() method (e.g. ‘1H’ for a 1-hour time frame, ‘1D’ for a 1-day time frame, etc.).

Answered By: DobbyTheElf
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.