To jest wersja 4.5 z Linear Regression i Holt_Winter methode
import streamlit as st
from streamlit.errors import StreamlitAPIException
import pandas as pd
import numpy as np
import datetime as dt
from datetime import datetime, timedelta, date
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import yfinance as yf
from sklearn.linear_model import LinearRegression
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from streamlit import set_page_config
Set page configuration for full width
set_page_config(layout=âwideâ)
start definicji strony
st.title(âThe main indicators of the global economy based on data from NYSEâ)
#st.subheader(âWe can compare different trend estimationâ)
Definicje
today = date.today()
comm_dict = {âEURUSD=Xâ:âUSD_EURâ,âCNY=Xâ:âUSD/CNYâ,âCL=Fâ:âCrude_Oilâ,
â^DJIâ:âDJI30â,âGC=Fâ:âGoldâ,â^IXICâ:âNASDAQâ,
â^GSPCâ:âSP_500â,â^TNXâ:â10_YBâ,
âHG=Fâ:âCopperâ,âGBPUSD=Xâ:âUSD_GBPâ,
âJPY=Xâ:âUSD_JPYâ,âEURPLN=Xâ:âEUR/PLNâ,âPLN=Xâ:âPLN/USDâ
,â^FVXâ:â5_YBâ,âRUB=Xâ:âUSD/RUBâ,âPL=Fâ:âPlatinumâ,
âSI=Fâ:âSilverâ,âNG=Fâ:âNatural Gasâ,âZR=Fâ:âRice Futuresâ,
âZS=Fâ:âSoy Futuresâ,âKE=Fâ:âKC HRW Wheat Futuresâ}
Pobieranie danych
def comm_f(comm):
global df_c, df_c1
for label, name in comm_dict.items():
if name == comm:
df_c = pd.DataFrame(yf.download(fâ{label}', start=â2000-09-01â, end = today,interval=â1dâ))
df_c1 = df_c.reset_index()
return df_c, df_c1
Dane historyczne
def comm_data(comm):
global Tab_his2
shape_test=
sh = df_c1.shape[0]
start_date = df_c1.Date.min()
end_date = df_c1.Date.max()
close_max = â{:.2f}â.format(df_c1[âCloseâ].max())
close_min = â{:.2f}â.format(df_c1[âCloseâ].min())
last_close = â{:.2f}â.format(df_c1[âCloseâ].iloc[-1])
v = (comm, sh, start_date,end_date,close_max,close_min,last_close)
shape_test.append(v)
Tab_length = pd.DataFrame(shape_test, columns= [âNameâ,âRowsâ, âStart_Dateâ, âEnd_Dateâ,âClose_maxâ,âClose_minâ,âLast_closeâ])
Tab_his = Tab_length[[âStart_Dateâ,âEnd_Dateâ,âClose_maxâ,âClose_minâ,âLast_closeâ]]
Tab_his[âStart_Dateâ] = Tab_his[âStart_Dateâ].dt.strftime(â%Y-%m-%dâ)
Tab_his[âEnd_Dateâ] = Tab_his[âEnd_Dateâ].dt.strftime(â%Y-%m-%dâ)
Tab_his1 = Tab_his.T
Tab_his2 = Tab_his1.style.hide(axis=âcolumnsâ)
return Tab_his2
st.sidebar.title(âCommodities, Indexies, Currencies & Bondsâ)
comm = st.sidebar.selectbox(âWhat do you want to analyse today ?â, list(comm_dict.values()))
comm_f(comm)
st.sidebar.write(âYou selected:â, comm)
comm_data(comm)
st.sidebar.table(Tab_his2)
tu wstawimy wykresy 15 minutowe
def t1_f(char1):
global tf_c1
for label, name in comm_dict.items():
if name == char1:
box = yf.Ticker(label)
tf_c = pd.DataFrame(box.history(period=â1dâ, interval=â1mâ))
tf_c1 = tf_c[-100:]
return tf_c1
def t2_f(char2):
global tf_c2
for label, name in comm_dict.items():
if name == char2:
box = yf.Ticker(label)
tf_c = pd.DataFrame(box.history(period=â1dâ, interval=â1mâ))
tf_c2 = tf_c[-100:]
return tf_c2
def t3_f(char3):
global tf_c3
for label, name in comm_dict.items():
if name == char3:
box = yf.Ticker(label)
tf_c = pd.DataFrame(box.history(period=â1dâ, interval=â1mâ))
tf_c3 = tf_c[-100:]
return tf_c3
try:
M15_charts = st.multiselect(âDaily trading dynamicsâ, list(comm_dict.values()),[âCrude_Oilâ,âUSD/CNYâ,âDJI30â],key = ââ)
char1 = M15_charts[0]
char2 = M15_charts[1]
char3 = M15_charts[2]
t1_f(char1)
t2_f(char2)
t3_f(char3)
except (NameError, IndexError, KeyError):
pass
subplots
colors = [âyellowâ,âredâ,âblueâ, âgreenâ]
fig_two = make_subplots(rows=1, cols=3, subplot_titles=(char1, char2, char3))
for i, col in enumerate(tf_c1.columns[0:4]):
fig_two.add_trace(go.Scatter(x=tf_c1.index, y=tf_c1[col], mode=âlinesâ, name=col, line=dict(color=colors[i])), row=1, col=1)
for i, col in enumerate(tf_c2.columns[0:4]):
fig_two.add_trace(go.Scatter(x=tf_c2.index, y=tf_c2[col], mode=âlinesâ, name=col, line=dict(color=colors[i])), row=1, col=2)
for i, col in enumerate(tf_c3.columns[0:4]):
fig_two.add_trace(go.Scatter(x=tf_c3.index, y=tf_c3[col], mode=âlinesâ, name=col, line=dict(color=colors[i])), row=1, col=3)
for i in range(2):
fig_two.update_traces(showlegend=False, row=1, col=i+1)
fig_two.update_traces(showlegend=True, row=1, col=3)
fig_two.update_layout(width=1000, height=500)
st.plotly_chart(fig_two)
st.write(âFirst add new financial instrument than remove first one on the leftâ)
tutaj wprowadzamy kod do wykresĂłw
st.subheader(comm+â Prices in NYSEâ)
xy = (list(df_c1.index)[-1] + 1)
oil_p = st.slider(âHow long prices history you need?â, 0, xy, 100, key = ââ)
numm = st.number_input(âEnter the number of days for moving averageâ,value=30, key = ââ)
st.write(fâCustom mean of {numm} days ')
df_c1[(fâM{numm}')]= df_c1[âCloseâ].rolling(window=numm).mean()
df_c1[âM90â]= df_c1[âCloseâ].rolling(window=90).mean()
df_c_XDays = df_c1.iloc[xy - oil_p:xy]
fig1 = px.line(df_c_XDays,x=âDateâ, y=[âHighâ,(fâM{numm}â),âM90â],color_discrete_map={
âHighâ:â#d62728â,(fâM{numm}â): â#f0f921â,âM90â:â#0d0887â}, width=1200, height=400)
st.plotly_chart(fig1, use_container_width=True)
def yf_chart(comm):
fig_yf = go.Figure(data=[go.Candlestick(x=df_c_XDays[âDateâ], open=df_c_XDays[âOpenâ], high=df_c_XDays[âHighâ],
low=df_c_XDays[âLowâ], close=df_c_XDays[âCloseâ])])
fig_yf.update_layout(title=f"{comm} Candlestick Chart for last {oil_p} days", xaxis_title='Date', yaxis_title='Price')
fig_yf.update_layout(width=1000, height=600)
fig_yf.update_traces(increasing_line_color='green', decreasing_line_color='red')
fig_yf.update_traces(line=dict(width=6))
st.plotly_chart(fig_yf)
yf_chart(comm)
Wykres rr - zmiennoĹÄ dzienna
def volat(comm):
box1 =
for xa in df_c1[-500:].index:
n0 = df_c1.Close[xa]
n1 = df_c1.Close[xa]+1
rr = fâ{((n1 - n0)/n0):.4f}%â
v = (rr)
box1.append(v)
box1_tab = pd.DataFrame(box1, columns= ['Rate_of_Return'])
tl = pd.DataFrame(df_c1['Date'][-500:]).reset_index()
rr_t = pd.concat([tl, box1_tab], axis = 1, ignore_index=True)
rr_t.rename(columns= {0:'Index1',1:'Date', 2:'Rate_of_Return'},inplace=True)
rr_tab = rr_t[['Date', 'Rate_of_Return']]
fig_rr = px.line(rr_tab,x='Date', y=['Rate_of_Return'],color_discrete_map={'Rate_of_return':'green'},
width=1000, height=500)
st.plotly_chart(fig_rr, use_container_width=True)
if st.checkbox(fâVolatility of {comm} for lat 500 daysâ,key = ââ):
st.subheader(fâDaily price volatility of {comm}')
volat(comm)
Estymacja przy pomocy Linear Regression
def LR_f(comm):
size = num1
X = df_c1['Open'].values.reshape(-1, 1)
y = df_c1['Close'].values
model = LinearRegression()
model.fit(X, y)
future_dates = [datetime.today() + timedelta(days=i) for i in range(0, size)]
future_open = [[open_val] for open_val in df_c1['Open'].tail(size)]
predicted_close = model.predict(future_open)
predicted_df = pd.DataFrame({'Date': future_dates, 'Predicted Close': predicted_close})
predicted_df['Date'] = predicted_df['Date'].dt.strftime('%Y-%m-%d')
LR_tab = pd.DataFrame(predicted_df)
df_c12 = pd.concat([df_c1, LR_tab], ignore_index=True)
xbb = (list(df_c12.index)[-1] + 1)
df_c13 = df_c12.iloc[xbb - 90:xbb]
fig_lr = px.line(df_c13,x='Date', y=['High','Close','Predicted Close'],color_discrete_map={
'High':'#0d0887','Close':'#f0f921','Predicted Close':'#d62728'},
width=1000, height=500)
fig_lr.add_vline(x = today,line_width=3, line_dash="dash", line_color="lightgreen")
st.plotly_chart(fig_lr, use_container_width=True)
if st.checkbox(âTrend estimation with linear regression modelâ,key = â<L_reg>â):
st.subheader(comm+â Linear regression trend estimationâ)
num1 = st.number_input(âEnter the number of days for trend estimationâ, value=10, key = ââ)
st.write(fâThe estimation for {num1} days ')
LR_f(comm)
Estymacja Holt_Winters
def HW_f(comm):
size = num2
closing_price = df_c1['Close']
model = ExponentialSmoothing(closing_price, trend='add')
fitted_model = model.fit()
forecast = fitted_model.forecast(steps=size)
a1 = df_c1.index[-1]
fo_dates = pd.date_range(start=df_c1.Date[a1] + pd.Timedelta(days=1), periods=size, freq='D')
fo_table = pd.DataFrame({'Date': fo_dates, 'Prediction Close': forecast})
df_c13 = pd.concat([df_c1, fo_table], ignore_index=True)
xbc = (list(df_c13.index)[-1] + 1)
df_c14 = df_c13.iloc[xbc - 90:xbc]
df_c14['Date'] = df_c14['Date'].dt.strftime('%Y-%m-%d')
fig_hw = px.line(df_c14, x='Date', y=['High', 'Close', 'Prediction Close'], color_discrete_map={
'High': '#bcbd22', 'Close': '#17becf', 'Prediction Close': '#d62728'}, width=1000, height=500)
fig_hw.add_vline(x = today,line_width=3, line_dash="dash", line_color="black")
st.plotly_chart(fig_hw, use_container_width=True)
if st.checkbox(âTrend estimation with Holt-Winters methodâ,key = â<HW_est>â):
st.subheader(comm+â Holt-Winters trend estimationâ)
num2 = st.number_input(âEnter the number of days for trend estimationâ, value=10, key = ââ)
st.write(fâThe estimation for {num2} days ')
HW_f(comm)
definicja wykresu obortĂłw
def vol_chart(comm):
volc = [âCrude_Oilâ,âGoldâ,âCopperâ,âPlatinumâ,âSilverâ,âNatural Gasâ,âRice Futuresâ,âSoy Futuresâ,âKC HRW Wheat Futuresâ]
if comm in volc:
Co_V = df_c1[['Date', 'Volume']]
Co_V['Co_V_M']= Co_V['Volume'].rolling(window=90).mean().fillna(0)
V_end = (list(Co_V.index)[-1] + 1)
st.subheader(comm+' Volume in NYSE')
Vol = st.slider('How long prices history you need?', 0, V_end, 100, key = "<volume>")
Co_V_XD = Co_V.iloc[V_end - Vol:V_end]
fig3 = px.area(Co_V_XD, x='Date', y='Volume',color_discrete_map={'Volume':'#1f77b4'})
fig3.add_traces(go.Scatter(x= Co_V_XD.Date, y= Co_V_XD.Co_V_M, mode = 'lines', line_color='red'))
fig3.update_traces(name='90 Days Mean', showlegend = False)
st.plotly_chart(fig3, use_container_width=True)
vol_chart(comm)
tu poblikujemy komentarz z yf
@st.cache_data
def news_stream():
comm_dict1 = {âEURUSD=Xâ:âUSD_EURâ,âCNY=Xâ:âUSD/CNYâ,âCL=Fâ:âCrude_Oilâ,â^DJIâ:âDJI30â}
subs = âfinance.yahoo.comâ
news =
today = date.today()
for label, name in comm_dict1.items():
Comm_news = yf.Ticker(name)
info = Comm_news.get_news()
info_link = list(info[0].values())
for i in info_link:
try:
if subs in i:
v = (today,name,i)
news.append(v)
news_tab = pd.DataFrame(news, columns= ['Date','Topic','Link'])
except TypeError:
pass
st.sidebar.subheader(f'News from Yahoo Finance from {today}')
st.sidebar.write('News about '+news_tab.Topic[0])
st.sidebar.markdown(news_tab.Link[0])
st.sidebar.write('News about '+news_tab.Topic[1])
st.sidebar.markdown(news_tab.Link[1])
st.sidebar.write('News about '+news_tab.Topic[2])
st.sidebar.markdown(news_tab.Link[2])
st.sidebar.write('News about '+news_tab.Topic[3])
st.sidebar.markdown(news_tab.Link[3])
news_stream()