GMashtalyar

Commands

.

import streamlit as st
import time

st.title ("this is the app title")
st.header("this is the markdown")
st.markdown("this is the header")
st.subheader("this is the subheader")
st.caption("this is the caption")
st.code("x=2021")
st.latex(r''' a+a r^1+a r^2+a r^3 ''')

st.checkbox('yes')
st.button('Click')
st.radio('Выберите машину',['мерс','бмв'])
st.selectbox('Pick your gender',['Boy','Girl'])
st.multiselect('choose a planet',['Jupiter', 'Mars', 'neptune'])
st.select_slider('Pick a mark', ['Bad', 'Good', 'Excellent'])
st.slider('Pick a number', 0, 50)

st.number_input('Pick a number', 0, 10)
st.text_input('Введите текст')
st.date_input('Выберите дату в формате YYYY-MM-DD')
st.time_input('School time')
st.text_area('Description')
st.file_uploader('Загрузите документ')
st.color_picker('Choose your favorite color')

st.balloons()
st.subheader('Progress bar')
st.progress(10)
st.subheader("Wait for the exception")
with st.spinner('Wait for it'):
    time.sleep(10)
    st.success("You did it !")

st.success("You did it !")
st.error("Error")
st.warning("Warning")
st.info("It's easy to build a streamlit app")
st.exception(RuntimeError("RuntimeError exception"))

st.sidebar.title("The title")
st.sidebar.button("Click")
st.sidebar.radio("Pick your gender", ["Male", "Female"])

container = st.container()
container.write("This is inside the container")
st.write("This is outside the container")

Cheatsheets

.

import streamlit as st


screen = st.sidebar.selectbox("Subject", ("Parsing", "Pandas", "Openpyxl"))
st.title(screen)



if screen == 'Parsing':
    st.subheader("Direct api requests:")
    st.code("response = requests.get; response.json()['data'][0]['images'][\"downsized_medium\"][\"url\"]")
    st.subheader("Sending json request:")
    st.code("param=")
    st.json({
    "year_from": 2016,
    "year_to": 2017,
    "catalog_filter": [{"mark": "BMW"}],
    "section": "all",
    "category": "cars",
    "sort": "fresh_relevance_1-desc",
    "page": 2,
    })
    st.code("response = requests.post(url, json=param, headers=HEADERS)")
    st.subheader("Using LXML/XPATH way:")
    st.write("Step1: Need to send a get request to a proger link (ex/ Mustangs that cost more than 200k.)")
    st.write("Step2: Need to parse proper xpath.")
    st.write("Step3: Extract data from the variable.")
    st.code("year_xpath = tree.xpath('//div[@class=\"ListingItem__year\"]//text()')")
    st.subheader("Fetching:")
    st.write("Passing full params to the link (headers, body, method).")
    st.subheader("Selenium:")
    st.write("Need to navigate browser and pass needed xpaths to extract data.")

if screen == 'Pandas':
    st.subheader("Browsing dataframe:")
    st.code("""df.shape df.columns df.index df.dtypes df.describe() df.head(3)
    """)
    st.subheader("Looking at unique values")
    st.code("regions = list(df['Regions'].unique())")
    st.subheader("Filtering data:")
    st.code("filter = df.query('price > 50000')")
    st.subheader("Setting index:")
    st.code("data.set_index([\"Some index\"], inplace=True)")
    st.subheader("Merging datasets by index:")
    st.code("merged_data = data1.merge(data2, left_index=True, right_index=True, how=\"outer\")")
    st.subheader("Changing data:")
    st.code("data.loc[(data['Column1'] == 'variable1') & (data['Column2'] == 'variable2') & (data['Column3'] == 'variable3'), 'Column4'] = 'newdata'")


if screen == 'Openpyxl':
    st.subheader("Inserting data:")
    st.code("""
    workbook = load_workbook('workbook.xlsx')
    sheet = workbook['Sheet1']

    def some_function(i, x):  # вставляем данные из Pandas
    sheet[f'{i}6'] = data.iat[0, x]
    sheet[f'{i}7'] = data.iat[1, x]
    sheet[f'{i}8'] = data.iat[2, x]
    sheet[f'{i}9'] = data.iat[3, x]

    some_function(A,1)
    some_function(B,2)
    some_function(C,3)
    
    workbook.save('workbook.xlsx')
    """)

Finance Chart

.

import pandas as pd
import streamlit as st
import yfinance

# https://github.com/paduel/streamlit_finance_chart


def load_data():
    components = pd.read_html('https://en.wikipedia.org/wiki/List_of_S'
                    '%26P_500_companies')[0]
    return components.drop('SEC filings', axis=1).set_index('Symbol')


def load_quotes(asset):
    return yfinance.download(asset)


components = load_data()
title = st.empty()
st.sidebar.title("Options")

def label(symbol):
    a = components.loc[symbol]
    return symbol + ' - ' + a.Security

if st.sidebar.checkbox('View companies list'):
    st.dataframe(components[['Security',
                                 'GICS Sector',
                                 'Date first added',
                                 'Founded']])

st.sidebar.subheader('Select asset')
asset = st.sidebar.selectbox('Click below to select a new asset',
                                 components.index.sort_values(), index=3,
                                 format_func=label)
title.title(components.loc[asset].Security)
if st.sidebar.checkbox('View company info', True):
    st.table(components.loc[asset])
data0 = load_quotes(asset)
data = data0.copy().dropna()
data.index.name = None

section = st.sidebar.slider('Number of quotes', min_value=30,
                        max_value=min([2000, data.shape[0]]),
                        value=500,  step=10)

data2 = data[-section:]['Adj Close'].to_frame('Adj Close')

sma = st.sidebar.checkbox('SMA')
if sma:
        period= st.sidebar.slider('SMA period', min_value=5, max_value=500,
                             value=20,  step=1)
        data[f'SMA {period}'] = data['Adj Close'].rolling(period ).mean()
        data2[f'SMA {period}'] = data[f'SMA {period}'].reindex(data2.index)

sma2 = st.sidebar.checkbox('SMA2')
if sma2:
    period2= st.sidebar.slider('SMA2 period', min_value=5, max_value=500,
                             value=100,  step=1)
    data[f'SMA2 {period2}'] = data['Adj Close'].rolling(period2).mean()
    data2[f'SMA2 {period2}'] = data[f'SMA2 {period2}'].reindex(data2.index)

st.subheader('Chart')
st.line_chart(data2)

if st.sidebar.checkbox('View stadistic'):
    st.subheader('Stadistic')
    st.table(data2.describe())

if st.sidebar.checkbox('View quotes'):
    st.subheader(f'{asset} historical data')
    st.write(data2)

st.sidebar.title("About")
st.sidebar.info('This app is a simple example of '
                    'using Strealit to create a financial data web app.\n'
                    '\nIt is maintained by [Paduel]('
                    'https://twitter.com/paduel_py).\n\n'
                    'Check the code at https://github.com/paduel/streamlit_finance_chart')

Alpha Vantage

.

import streamlit as st
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.sectorperformance import SectorPerformances
import pandas_datareader.data as web
from datetime import datetime
import nasdaqdatalink as nasdaq
import pandas as pd

NASDAQ_api_key = ''
AlphavantageKey = ""

ts = TimeSeries(key=AlphavantageKey, output_format='pandas')
sp = SectorPerformances(key=AlphavantageKey)


ticker = st.sidebar.text_input("Ticker", 'MSFT').upper()
end_date = st.sidebar.date_input('end date', value=datetime.now()).strftime("%Y-%m-%d")
start_date = st.sidebar.date_input('start date', value=datetime(2020, 5, 31)).strftime("%Y-%m-%d")


def get_ticker_daily(ticker_input):
    ticker_data, ticker_metadata = ts.get_daily(symbol=ticker_input, outputsize='full')
    # ticker_data, ticker_metadata = nasdaq.get("WIKI/" + ticker, start_date=start_date, end_date=end_date)

    return ticker_data, ticker_metadata


try:
    price_data, price_meta_data = get_ticker_daily(ticker)
    market_data, market_meta_data = get_ticker_daily('SPY')
    md_chart_1 = f"Price of **{ticker}**"
    md_chart_2 = f"APR daily change of **{ticker}**"
except:
    price_data, price_meta_data = get_ticker_daily('MSFT')
    market_data, market_meta_data = get_ticker_daily('SPY')
    md_chart_1 = f"Invalid ticker **{ticker}** showing **MSFT** price"
    md_chart_2 = f"Invalid ticker **{ticker}** showing **MSFT** APR daily change of"


def apr_change(pandas_series_input):
    return ((pandas_series_input - pandas_series_input.shift(periods=-1,
                                                             fill_value=0)) / pandas_series_input) * 100 * 252


price_data['change'] = apr_change(price_data['4. close'])
market_data['change'] = apr_change(market_data['4. close'])

price_data_filtered = price_data[end_date:start_date]
market_data_filtered = market_data[end_date:start_date]
stock_market_correlation = price_data_filtered['change'].corr(market_data_filtered['change'], method='pearson')

treasury_yield = nasdaq.get("FRED/TB3MS", start_date=start_date, end_date=end_date)
rfr = treasury_yield['Value'].mean()

stock_volatility = price_data_filtered['change'].std()
market_volatility = market_data_filtered['change'].std()
stock_excess_return = price_data_filtered['change'].mean() - rfr
maket_excess_return = market_data_filtered['change'].mean() - rfr
beta = stock_market_correlation * stock_volatility / market_volatility
alpha = stock_excess_return - beta * maket_excess_return
sharpe = stock_excess_return / stock_volatility
metrics_df = pd.DataFrame(data={
    'mkt correlation': [stock_market_correlation],
    'alpha': [alpha],
    'beta': [beta],
    'Sharpe ratio': [sharpe]})
metrics_df.index = [ticker]

st.markdown(md_chart_1)
st.line_chart(price_data_filtered['4. close'])
st.markdown(md_chart_2)
st.line_chart(price_data_filtered['change'])

st.table(metrics_df)

Nasdaq

.

NASDAQ_api_key = ''
nasdaq.ApiConfig.api_key = NASDAQ_api_key


ticker = st.sidebar.text_input("Ticker", 'MSFT')
end_date = st.sidebar.date_input('end date', value=datetime.now())
start_date = st.sidebar.date_input('start date', value=datetime(2015, 1, 1))

ticker_df = nasdaq.get("WIKI/" + ticker, start_date=start_date, end_date=end_date)

st.markdown(f"Price pf **{ticker}**")
st.line_chart(ticker_df['Close'])
st.markdown(f"Volume pf **{ticker}**")
st.line_chart(ticker_df['Volume'])


usa = nasdaq.get('RATEINF/INFLATION_USA', start_date='2010-01-01', end_date='2022-08-31')
# gbr = nasdaq.get('RATEINF/INFLATION_GBR', start_date='2022-01-01', end_date='2022-08-31')
# che = nasdaq.get('RATEINF/INFLATION_CHE', start_date='2022-01-01', end_date='2022-08-31')
# jpn = nasdaq.get('RATEINF/INFLATION_JPN', start_date='2022-01-01', end_date='2022-08-31')
# ita = nasdaq.get('RATEINF/INFLATION_ITA', start_date='2022-01-01', end_date='2022-08-31')
# fra = nasdaq.get('RATEINF/INFLATION_FRA', start_date='2022-01-01', end_date='2022-08-31')
# deu = nasdaq.get('RATEINF/INFLATION_DEU', start_date='2022-01-01', end_date='2022-08-31')
# rus = nasdaq.get('RATEINF/INFLATION_RUS', start_date='2022-01-01', end_date='2022-08-31')
st.line_chart(usa)