How to covert a normal data frame into candlestick dataframe?

Viewed 65
fig = go.Figure()
fig.add_trace(
  go.Scatter(x=alldates, y=countriesData[0]["ToxPi Score"], 
  name="Suffolk",customdata=countriesData[0],hovertemplate=common_template)
)
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
    buttons=list([
        dict(count=1, label="1m", step="month", stepmode="backward"),
        dict(count=6, label="6m", step="month", stepmode="backward"),
        dict(count=1, label="YTD", step="year", stepmode="todate"),
        dict(count=1, label="1y", step="year", stepmode="backward"),
        dict(step="all")
    ])
 )
 )

fig.show()

enter image description here

My dataframe looks like this

I am working on a simple dataset in which i have plotted ToxPi score of a state according to dates.

Now i need to plot this data into candlestick format according to given directions

Open value: ToxPi value at the first day in a given range of 7 days. Close value: ToxPi value at the last (7th) day in a given range of 7 days. High value: The highest ToxPi value in a given range of 7 days. Low value: The lowest ToxPi value in a given range of 7 days.

I can't figure out the way how to covert it or separate the data into weekly format

EDIT

After updating datetime column in df it looks like this

Please Help Thanx in advance.

1 Answers

Although I am not completely clear in what is meant by a "given range of 7 days", my guess is that a 7 day rolling calculation should be used to calculate open, high, low, and close, and that your data has a grain of 1 day.

I am not sure if your countriesData[0] has a datetime column, so we'll use the alldates array you passed to go.Scatter:

df = countriesData[0].copy()
df["date_time"] = alldates
df["date_time"] = pd.to_datetime(df["date_time"])
df = df.set_index("date_time")

## create your features Open, Close, High, Low:
df["Open"] = df["ToxPi Score"].rolling("7D").apply(lambda row: row.iloc[0])
df["Close"] = df["ToxPi Score"].rolling("7D").apply(lambda row: row.iloc[-1])
df["High"] = df["ToxPi Score"].rolling("7D").max()
df["Low"] = df["ToxPi Score"].rolling("7D").max()

Then you can use your modified DataFrame to construct a candlestick chart:

fig = go.Figure(data=[go.Candlestick(
    x=df.index,
    open=df["Open"],
    high=df["High"],
    low=df["Low"],
    close=df["Close"]
)])
Related