Spaces:
Running
Running
File size: 10,957 Bytes
7015834 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
import dateutil.relativedelta
import streamlit as st
import pandas as pd
import yfinance as yf
import plotly.graph_objects as go
import datetime
import dateutil
import ta
import plotly.express as px
import pandas_ta as pta
import numpy as np
npNaN = np.nan
st.set_page_config(
page_title="Stock Analysis",
page_icon="page_with_curl",
layout='wide'
)
st.title("Stock Analysis")
col1,col2,col3 =st.columns(3)
today= datetime.date.today()
with col1:
ticker =st.text_input("Stocker Ticker","TSLA")
with col2:
start_date = st.date_input("choose Start Date",datetime.date(today.year -1,today.month,today.day))
with col3:
end_date = st.date_input("choose End Date",datetime.date(today.year,today.month,today.day))
st.subheader(ticker)
stock = yf.Ticker(ticker)
try:
info = stock.get_info()
st.write(stock.info['longBusinessSummary'])
st.write("**Sector:**",stock.info['sector'])
st.write("**Full Time Employees:**",stock.info['fullTimeEmployees'])
st.write("**Website:**",stock.info['website'])
except Exception as e:
print(f"Error: {e}")
col1= st.columns(1)[0]
with col1:
df = pd.DataFrame({
"Metric": ["Market Cap", "Beta", "EPS", "PE Ratio","profitMargins",'revenuePerShare','financialCurrency'],
"Value": [
stock.info['marketCap'],
stock.info['beta'],
stock.info['trailingEps'],
stock.info['trailingPE'],
stock.info['profitMargins'],
stock.info['revenuePerShare'],
stock.info['financialCurrency']
]
})
st.dataframe(df.style.set_properties(**{'font-size': '20px'}),width=1000)
data = yf.download(ticker,start=start_date,end= end_date)
col1,col2,col3 = st.columns(3)
daily_change = data['Close'].iloc[-1] - data['Close'].iloc[-2]
col1.metric("Daily Change",str(round(data['Close'].iloc[-1],2)),str(round(daily_change,2)))
# Display historical data based on start and end date
filtered_data = data[(data.index >= pd.to_datetime(start_date)) & (data.index <= pd.to_datetime(end_date))]
st.title(f"Historical Data ({start_date} to {end_date})")
st.dataframe(filtered_data.sort_index(ascending=False).round(3).style.set_properties(**{'font-size': '20px'}), width=1000)
col1,col2,col3,col4,col5,col6,col7=st.columns([1,1,1,1,1,1,1])
num_period=''
with col1:
if st.button("5D"):
num_period="5d"
with col2:
if st.button("1M"):
num_period="1mo"
with col3:
if st.button("6M"):
num_period="6mo"
with col4:
if st.button("YTD"):
num_period='ytd'
with col5:
if st.button("1Y"):
num_period='1y'
with col6:
if st.button("5Y"):
num_period='5y'
with col7:
if st.button("MAX"):
num_period= 'max'
##
def filter_data(dataframe,num_period):
if num_period =='1mo':
date = dataframe.index[-1] + dateutil.relativedelta.relativedelta(months=-1)
elif num_period == '5d':
date =dataframe.index[-1] + dateutil.relativedelta.relativedelta(days=-5)
elif num_period == '6mo':
date =dataframe.index[-1] + dateutil.relativedelta.relativedelta(months=-6)
elif num_period == '1y':
date =dataframe.index[-1] + dateutil.relativedelta.relativedelta(years=-1)
elif num_period == '5y':
date =dataframe.index[-1] + dateutil.relativedelta.relativedelta(years=-5)
elif num_period == 'ytd':
date = datetime.datetime(dataframe.index[-1].year,1,1).strftime("%Y-%m-%d")
else:
date = dataframe.index[0]
dataframe_reset = dataframe.reset_index() # Reset index to create a 'Date' column
return dataframe_reset[dataframe_reset['Date'] > date]
def close_chart(dataframe,num_period=False):
if num_period:
dataframe =filter_data(dataframe,num_period)
fig =go.Figure()
fig.add_trace(go.Scatter(
x=dataframe['Date'],y= dataframe['Open'],
mode='lines',
name ='Open',line =dict(width=2,color='#5ab7ff')
))
fig.add_trace(go.Scatter(
x=dataframe['Date'],y= dataframe['Close'],
mode='lines',
name ='Close',line =dict(width=2,color='black')
))
fig.add_trace(go.Scatter(
x=dataframe["Date"],y= dataframe['High'],
mode='lines',
name ='High',line =dict(width=2,color='#0078ff')
))
fig.add_trace(go.Scatter(
x=dataframe["Date"],y= dataframe['Low'],
mode='lines',
name ='Low',line =dict(width=2,color='red')
))
fig.update_xaxes(rangeslider_visible = True)
fig.update_layout(
height=500,
margin=dict(l=0, r=20, t=20, b=0),
plot_bgcolor='white',
paper_bgcolor='#E1EFFF',
legend=dict(yanchor='top', xanchor='right'),
xaxis_title="Date", # Add this
yaxis_title="Price", # Add this
)
return fig
def candlestick(dataframe,num_period):
dataframe = filter_data(dataframe,num_period)
fig=go.Figure()
fig.add_trace(go.Candlestick(x=dataframe['Date'],
open =dataframe['Open'],high=dataframe['High'],
low = dataframe['Low'],close=dataframe['Close']
))
fig.update_layout(
xaxis_title="Date", # Add this
yaxis_title="Price", # Add this
showlegend=False,
height=500,
margin=dict(l=0, r=20, t=20, b=0),
plot_bgcolor='white',
paper_bgcolor='#E1EFFF'
)
return fig
def RSI(dataframe,num_period):
dataframe['RSI']= pta.rsi(dataframe['Close'])
dataframe = filter_data(dataframe,num_period)
fig = go.Figure()
fig.add_trace(go.Scatter(
x=dataframe['Date'],
y=dataframe.RSI,name='RSI',marker_color='orange',line= dict(width=2,color ='orange'),
))
fig.add_trace(go.Scatter(
x=dataframe['Date'],
y=[70]*len(dataframe),name='Overbought',marker_color='red',line= dict(width=2,color ='red',dash='dash'),
))
fig.add_trace(go.Scatter(
x=dataframe['Date'],
y=[30]*len(dataframe),fill='tonexty',name='Oversold',marker_color='#79da84',
line= dict(width=2,color ='#79da84',dash='dash')
))
fig.update_layout(
xaxis_title='Date',
yaxis_title='RSI',
height=500,
margin=dict(l=0, r=20, t=20, b=0),
plot_bgcolor='white',
paper_bgcolor='#E1EFFF'
)
return fig
def Moving_average(dataframe,num_period):
dataframe['SMA_50']=pta.sma(dataframe['Close'],50)
dataframe = filter_data(dataframe,num_period)
if dataframe['SMA_50'].isna().sum() > 0:
st.warning("Not enough data to calculate the moving average.")
fig=go.Figure()
fig.add_trace(go.Scatter(
x=dataframe['Date'],y= dataframe['Open'],
mode='lines',
name ='Open',line =dict(width=2,color='#5ab7ff')
))
fig.add_trace(go.Scatter(
x=dataframe['Date'],y= dataframe['Close'],
mode='lines',
name ='Open',line =dict(width=2,color='black')
))
fig.add_trace(go.Scatter(
x=dataframe["Date"],y= dataframe['High'],
mode='lines',
name ='Open',line =dict(width=2,color='#0078ff')
))
fig.add_trace(go.Scatter(
x=dataframe["Date"],y= dataframe['Low'],
mode='lines',
name ='Open',line =dict(width=2,color='red')
))
fig.add_traces(go.Scatter(
x=dataframe["Date"],y= dataframe['SMA_50'],
mode='lines',
name ='SMA 50',line =dict(width=2,color='purple')
))
fig.update_xaxes(rangeslider_visible = True)
fig.update_layout(
xaxis_title="Date", # Add this
yaxis_title="Price", # Add this
height=500,
margin=dict(l=0, r=20, t=20, b=0),
plot_bgcolor='white',
paper_bgcolor='#E1EFFF',
legend=dict(yanchor='top', xanchor='right')
)
return fig
def MACD(dataframe,num_period):
macd = pta.macd(dataframe['Close']).iloc[:,0]
macd_signal = pta.macd(dataframe['Close']).iloc[:,1]
macd_hist =pta.macd(dataframe['Close']).iloc[:,2]
dataframe['MACD'] = macd
dataframe['MACD-Signal']=macd_signal
dataframe['MACD-Hist']=macd_hist
dataframe = filter_data(dataframe,num_period)
fig = go.Figure()
fig.add_trace(go.Scatter(
x=dataframe['Date'],
y=dataframe['MACD'],name='RSI',marker_color='orange',line=dict(width=2,color='orange'),
))
fig.add_trace(go.Scatter(
x=dataframe['Date'],
y=dataframe['MACD-Signal'],name='Overbought',marker_color ='red',line =dict(width=2,color='red',dash='dash'),
))
c=['red' if cl<0 else 'green' for cl in macd_hist]
return fig
col1,col2,col3 = st.columns([1,1,4])
with col1:
char_type =st.selectbox('',('Candle','line'))
with col2:
if char_type == 'Candle':
indicators = st.selectbox('',('RSI','MACD'))
else:
indicators = st.selectbox('',('RSI','Moving Average','MACD'))
ticker_ = yf.Ticker(ticker)
new_df1=ticker_.history(period='max')
data1= ticker_.history(period='max')
if num_period == '':
if char_type == 'Candle' and indicators == 'RSI':
st.plotly_chart(candlestick(new_df1,'1y'),use_container_width=True)
st.plotly_chart(RSI(new_df1,'1y'),use_container_width=True)
if char_type == 'Candle' and indicators == 'MACD':
st.plotly_chart(candlestick(new_df1,'1y'),use_container_width=True)
st.plotly_chart(MACD(new_df1,'1y'),use_container_width=True)
if char_type == 'line' and indicators == 'RSI':
st.plotly_chart(close_chart(new_df1,'1y'),use_container_width=True)
st.plotly_chart(RSI(new_df1,'1y'),use_container_width=True)
if char_type == 'line' and indicators == 'Moving Average':
st.plotly_chart(Moving_average(new_df1,'1y'),use_container_width=True)
if char_type == 'line' and indicators == 'MACD':
st.plotly_chart(close_chart(new_df1,'1y'),use_container_width=True)
st.plotly_chart(MACD(new_df1,'1y'),use_container_width=True)
else:
if char_type == 'Candle' and indicators == 'RSI':
st.plotly_chart(candlestick(new_df1,num_period),use_container_width=True)
st.plotly_chart(RSI(new_df1,num_period),use_container_width=True)
if char_type == 'Candle' and indicators == 'MACD':
st.plotly_chart(candlestick(new_df1,num_period),use_container_width=True)
st.plotly_chart(MACD(new_df1,num_period),use_container_width=True)
if char_type == 'line' and indicators == 'RSI':
st.plotly_chart(close_chart(new_df1,num_period),use_container_width=True)
st.plotly_chart(RSI(new_df1,num_period),use_container_width=True)
if char_type == 'line' and indicators == 'Moving Average':
st.plotly_chart(Moving_average(new_df1,num_period),use_container_width=True)
if char_type == 'line' and indicators == 'MACD':
st.plotly_chart(close_chart(new_df1,num_period),use_container_width=True)
st.plotly_chart(MACD(new_df1,num_period),use_container_width=True)
|