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()