Dennis
October 19, 2023, 7:02am
1
I have this code which plots year-to-date(YTD) candlestick chart for indices. The code is able to plot one index at a time. I’m unable to write a loop which will generate all 4 charts using one code without having to repeat the code for each index.
import streamlit as st
import yfinance as yf
import plotly.graph_objs as go
djia_symbol = “^DJI”
Fetch historical data for DJIA
data_dj = yf.download(djia_symbol, period=“ytd”, interval=“1d”)
Create a candlestick chart
fig = go.Figure(data=[go.Candlestick(
x=data_dj.index,
open=data_dj[‘Open’],
high=data_dj[‘High’],
low=data_dj[‘Low’],
close=data_dj[‘Close’],
name=“Candlesticks”,
)])
Set chart layout and title
fig.update_layout(
title=f’DJIA’,
xaxis_title=‘’,
yaxis_title=‘Price’,
xaxis_rangeslider_visible=False,
plot_bgcolor= ‘lightgray’,
width=300,
height=300
)
st.write(fig)
the indices are Dow Jones(^DJI), S&P 500(^GSPC), NASDAQ(^IXIC), NYSE Composite(^NYA)
anyone who can write a loop which can generate all the charts using one code?
arnaud
October 20, 2023, 1:29pm
2
Hey @Dennis !
Have you tried something? It seems like all filterings and charts are downstream of one variable called dija_symbol.
You could probably explore doing a for loop to execute this whole code for other symbols like "^GSPC" and so on, what do you think?
Hi @Dennis ,
Once try this below code.I tried this code and it is working..
import streamlit as st
import yfinance as yf
import plotly.graph_objs as go
List of index symbols
index_symbols = [“^DJI”, “^GSPC”, “^IXIC”, “^NYA”]
Loop through the index symbols
for index_symbol in index_symbols:
# Fetch historical data for the current index
data = yf.download(index_symbol, period=“ytd”, interval=“1d”)
# Create a candlestick chart
fig = go.Figure(data=[go.Candlestick(
x=data.index,
open=data['Open'],
high=data['High'],
low=data['Low'],
close=data['Close'],
name="Candlesticks",
)])
# Set chart layout and title
fig.update_layout(
title=f"{index_symbol} - Year-to-Date Candlestick Chart",
xaxis_title='',
yaxis_title='Price',
xaxis_rangeslider_visible=False,
plot_bgcolor='lightgray',
width=800,
height=600
)
# Display the chart using Streamlit
st.write(fig)
Dennis
October 23, 2023, 6:37am
4
sai_krishna1:
fig.update_layout(
title=f"{index_symbol} - Year-to-Date Candlestick Chart",
xaxis_title='',
yaxis_title='Price',
xaxis_rangeslider_visible=False,
plot_bgcolor='lightgray',
width=800,
height=600
)
Hello krishna, I tried this code and it’s only printing one chart the last one only. Do you mind posting the screen shot of the code and another for the output please.