Skip to content

Commit

Permalink
finish portfolio page & some linting
Browse files Browse the repository at this point in the history
  • Loading branch information
Cuttlas90 committed Feb 1, 2024
1 parent 24c5654 commit 76b7e4a
Show file tree
Hide file tree
Showing 7 changed files with 166 additions and 95 deletions.
21 changes: 12 additions & 9 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
"""Plot Some main monthly and quarterly charts"""


import streamlit as st
import pandas as pd
import plotly.express as px
import plost
from request import vasahm_query
from slider import create_slider
from request import get_nonce
from request import get_key
import altair as alt

st.session_state.ver = '0.1.3'
from request import vasahm_query, get_nonce, get_key


st.session_state.ver = '0.1.5'

st.set_page_config(layout='wide',
page_title="Vasahm Dashboard",
Expand Down Expand Up @@ -42,6 +42,7 @@


def get_email_callback():
"""Send nonce to entered email."""
has_error, message = get_nonce(st.session_state.email)
if has_error:
st.error(message, icon="🚨")
Expand All @@ -53,6 +54,7 @@ def get_email_callback():
submit_nonce.form_submit_button("ارسال", on_click = get_nonce_callback )

def get_nonce_callback():
"""Confirm nonce for login."""
has_error, message = get_key(st.session_state.email, st.session_state.nonce)
if has_error:
st.error(message, icon="🚨")
Expand All @@ -63,7 +65,7 @@ def get_nonce_callback():

if "token" not in st .session_state:
get_email = st.form("get_email")
email = get_email.text_input('ایمیل خود را وارد کنید',
email = get_email.text_input('ایمیل خود را وارد کنید',
placeholder='example@mail.com',
key="email")
# Every form must have a submit button.
Expand Down Expand Up @@ -246,7 +248,8 @@ def get_nonce_callback():
columns='rowTitle',
values='value',
aggfunc='sum').reset_index()
pivot_df["profit_ratio"] = pivot_df["سود(زیان) خالص"].astype(float)/pivot_df["درآمدهای عملیاتی"].astype(float)
pivot_df["profit_ratio"] = (pivot_df["سود(زیان) خالص"].astype(float)
/pivot_df["درآمدهای عملیاتی"].astype(float))
pe_df=pivot_df[["profit_ratio", "endToPeriod"]]
st.line_chart(data=pe_df, x="endToPeriod",
y="profit_ratio",
Expand Down
2 changes: 0 additions & 2 deletions pages/01_Dollar_Base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
from request import get_key
import altair as alt

st.session_state.ver = '0.1.2'

st.set_page_config(layout='wide',
page_title="Vasahm Dashboard",
page_icon="./assets/favicon.ico",
Expand Down
170 changes: 100 additions & 70 deletions pages/04_Portfolio.py
Original file line number Diff line number Diff line change
@@ -1,93 +1,83 @@
import requests
"""Module providing a logic that let user understand his portfolio performance
in compare to other indexes or funds."""

import streamlit as st
import pandas as pd
import plotly.express as px
import plost
from request import vasahm_query
from slider import create_slider
from request import get_nonce
from request import get_key
import altair as alt

st.session_state.ver = '0.1.2'
from request import vasahm_query, get_nonce, get_key, index_price_history, index_price_history2

st.set_page_config(layout='wide',
page_title="Vasahm Dashboard",
page_icon="./assets/favicon.ico",
initial_sidebar_state='expanded')

with open( "style.css" ) as css:
with open("style.css", encoding="utf-8") as css:
st.markdown( f'<style>{css.read()}</style>' , unsafe_allow_html= True)

def index_price_history(insCode):
url = f"https://cdn.tsetmc.com/api/ClosingPrice/GetChartData/{insCode}/D"
header = {"User-Agent": "PostmanRuntime/7.29.0"}
response = requests.get(url, headers=header).json()
shiraz = pd.json_normalize(response['closingPriceChartData'])
shiraz['datetime'] = pd.to_datetime(shiraz["dEven"]+19603987200, unit='s').dt.strftime("%Y%m%d").astype(int)
return shiraz

def index_price_history2(insCode):
url = f"https://cdn.tsetmc.com/api/Index/GetIndexB2History/{insCode}"
header = {"User-Agent": "PostmanRuntime/7.29.0"}
response = requests.get(url, headers=header).json()
return pd.json_normalize(response['indexB2'])


df = pd.read_csv("data.csv").dropna()
list_of_name = df['name'].to_list()
# st.sidebar.image(image="./assets/logo.png")
def del_porto_submition_variable():
"""Deletes portfolio_analyzer form that let user to
fill a new form again."""
del st.session_state.porto_submition
if "portfolio_analyzer" in locals():
del portfolio_analyzer

st.sidebar.header(f'Vasahm DashBoard `{st.session_state.ver}`')

def add_submit_state():
"""Create st.session_state['porto_submition'] that help logic
whether user submit his portfolio or not."""
st.session_state["porto_submition"] = True

def create_query_String():
string = ""
for i in range(st.session_state.portfo_number - 1):
stro = f"stock_name_{i}"
string = string + f"stocks.name = '{st.session_state[stro]}' OR "
stro = f"stock_name_{st.session_state.portfo_number - 1}"
string = string + f"stocks.name = '{st.session_state[stro]}'"
return string
def create_query_string():
"""Create a query string for retrieving all portfolio prices."""
temp_str = ""
for _ in range(st.session_state.portfo_number):
stock_name_i = f"stock_name_{_}"
temp_str = temp_str + f"stocks.name = '{st.session_state[stock_name_i]}' OR "
return temp_str[:-4]

def create_form():

"""Create a form that let user enter his portfolio."""
portfolio_analyzer = st.form("portfolio_analyzer")

cols2 = portfolio_analyzer.columns(2, gap="small")
cols2[0].text_input('تاریخ شروع', placeholder='14010130', key=f"portfolio_month_start")
cols2[1].text_input('تاریخ شروع', placeholder='14010130', key=f"portfolio_month_finish")
cols = portfolio_analyzer.columns(3, gap="small")
for i in range(st.session_state.portfo_number):
cols[0].selectbox("لیست سهام", options = list_of_name, key=f"stock_name_{i}")
cols[1].text_input('قیمت خرید', placeholder='12345', key=f"stock_number_{i}")
cols[2].text_input('سهم از کل پورتفو (درصد)', placeholder='20', key=f"stock_percent_{i}")
# Every form must have a submit button.
options = portfolio_analyzer.multiselect(
cols2[0].text_input('تاریخ شروع', placeholder='14010130', key="portfolio_month_start")
cols2[1].text_input('تاریخ پایان', placeholder='14010130', key="portfolio_month_finish")
cols = portfolio_analyzer.columns(2, gap="small")
for _ in range(st.session_state.portfo_number):
cols[0].selectbox("لیست سهام", options = list_of_name, key=f"stock_name_{_}")
cols[1].number_input('سهم از کل پورتفو (درصد)',
min_value=1,
max_value=100,
step=1,
placeholder='20',
key=f"stock_percent_{_}"
)
portfolio_analyzer.multiselect(
'شاخصهای مورد نظر خود برای مقایسه را انتخاب کنید',
['شاخص کل', 'شاخص همزون', 'طلا', 'زعفران (نهال)'],
['شاخص کل'], key="indexes")
portfolio_analyzer.form_submit_button("بررسی عملکرد سبد", on_click=add_submit_state)

def get_email_callback():
hasError, message = get_nonce(st.session_state.email)
if hasError:
"""Send nonce to entered email."""
has_error, message = get_nonce(st.session_state.email)
if has_error:
st.error(message, icon="🚨")
else:
submit_nonce = st.form("submit_nonce")
nonce = submit_nonce.text_input('کد تایید خود را وارد کنید', placeholder='XXXX', key="nonce")
submitted = submit_nonce.form_submit_button("ارسال", on_click = get_nonce_callback )
submit_nonce.text_input('کد تایید خود را وارد کنید', placeholder='XXXX', key="nonce")
submit_nonce.form_submit_button("ارسال", on_click = get_nonce_callback )

def get_nonce_callback():
hasError, message = get_key(st.session_state.email, st.session_state.nonce)
if hasError:
"""Confirm nonce for login."""
has_error, message = get_key(st.session_state.email, st.session_state.nonce)
if has_error:
st.error(message, icon="🚨")
del st.session_state["nonce"]
else:
Expand All @@ -96,11 +86,11 @@ def get_nonce_callback():

if "token" not in st .session_state:
get_email = st.form("get_email")
email = get_email.text_input('ایمیل خود را وارد کنید', placeholder='example@mail.com', key="email")
# Every form must have a submit button.
email = get_email.text_input('ایمیل خود را وارد کنید',
placeholder='example@mail.com',
key="email")
submitted = get_email.form_submit_button("دریافت کد", on_click = get_email_callback )
else:

if "porto_submition" not in st.session_state:
st.number_input('تعداد سهام موجود در سبد خود را وارد کنید',
min_value=1,
Expand All @@ -118,45 +108,85 @@ def get_nonce_callback():
type="secondary",
disabled=False,
use_container_width=True)
string = create_query_String()
st.write(st.session_state.stock_name_1)
i = 1
stro = f"stock_name_{i}"
st.write(stro)
st.write(st.session_state[stro])
string = create_query_string()
queryString = f"""
SELECT stocks.name as name, "tradeDate", "lastAdjPrice"
SELECT stocks.name as name, "tradeDate", "lastAdjPrice","tradeDateGre"
FROM public."stockPrice"
INNER JOIN stocks ON "stockPrice".stock_id = stocks.id
where
({string})
and "tradeDate" > '{st.session_state.portfolio_month_start}'
and "tradeDate" < '{st.session_state.portfolio_month_finish}'
order by "tradeDate";"""
st.write(queryString)

error, stock_data = vasahm_query(queryString)
if error:
st.error(stock_data, icon="🚨")
else:
stock_data_history = pd.DataFrame(stock_data, columns=["name",
"tradeDate",
"lastAdjPrice"])
# st.dataframe(stock_data_history)
pivot_df = stock_data_history.pivot_table(index='tradeDate',
"lastAdjPrice",
"tradeDateGre"])
pivot_df = stock_data_history.pivot_table(index='tradeDateGre',
columns='name',
values='lastAdjPrice',
aggfunc='sum').reset_index()
pivot_df.fillna(method='ffill')
pivot_df['date'] = pd.to_datetime(pivot_df['tradeDateGre'], format="%Y-%m-%dT%H:%M:%S")
pivot_df['datetime'] = pivot_df["date"].dt.strftime("%Y%m%d").astype(str)
pivot_df = pivot_df.drop(columns=['date', 'tradeDateGre'])
pivot_df.fillna(method='ffill', inplace=True)
pivot_df['پورتفو'] = 0
for i in range(st.session_state.portfo_number):
stro = f"stock_name_{i}"
stro1 = f"stock_percent_{i}"
pivot_df['پورتفو'] = pivot_df['پورتفو'] + (
pivot_df[st.session_state[stro]].astype(int)*st.session_state[stro1]/100
)
pivot_df = pivot_df.drop(columns=[st.session_state[stro]])
ind = {}
for i in st.session_state.indexes:
if i == "طلا":
ind["tala"] = index_price_history(46700660505281786)
ind["طلا"] = index_price_history(46700660505281786, "طلا")
pivot_df = pivot_df.merge(ind["طلا"], how='left',on='datetime')
elif i == 'زعفران (نهال)':
ind["nahal"] = index_price_history(12913156843322499)
ind["زعفران (نهال)"] = index_price_history(12913156843322499, "زعفران (نهال)")
pivot_df = pivot_df.merge(ind["زعفران (نهال)"], how='left',on='datetime')
elif i == 'شاخص همزون':
ind["kol"] = index_price_history2(67130298613737946)
ind["شاخص هموزن"] = index_price_history2(67130298613737946, "شاخص هموزن")
pivot_df = pivot_df.merge(ind["شاخص هموزن"], how='left',on='datetime')
elif i == 'شاخص کل':
ind["ham"] = index_price_history2(32097828799138957)
st.dataframe(pivot_df)


ind["شاخص کل"] = index_price_history2(32097828799138957, "شاخص کل")
pivot_df = pivot_df.merge(ind["شاخص کل"], how='left',on='datetime')

pivot_df.fillna(method='ffill', inplace=True)
pivot_df['datetime'] = pd.to_datetime(
pivot_df['datetime'],
format='%Y%m%d',
errors='coerce')
pivot_df.sort_values('datetime', inplace=True)
change_df = pivot_df[['datetime']]
my_list = pivot_df.columns.values.tolist()
my_list.remove('datetime')
for i in my_list:
change_df[i] = pivot_df[i].pct_change().fillna(0).cumsum()
# change_df[i] = change_df[i].map('{:.2%}'.format)

p2 = change_df.melt(id_vars=['datetime'], var_name='column_name', value_name='value')
p2.fillna(0, inplace=True)
# st.line_chart(p2,x="datetime", y="value", color="column_name", height=500)

chart_product = alt.Chart(p2, height=600).mark_line().encode(
alt.X('datetime:T', title='تاریخ'),
alt.Y('value:Q', title="میزان عمکرد").axis(format='%'),
alt.Color('column_name:N', title='دسته ها'),

)
chart_product.configure_title(
fontSize=20,
font='Vazirmatn',
)

chart_product.configure(
font='Vazirmatn'
)
st.altair_chart(chart_product, use_container_width=True)
10 changes: 8 additions & 2 deletions pages/10_Changelog.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
"""Page log for changes and new improvement in project."""

import streamlit as st

with open( "style.css" ) as css:
with open("style.css", encoding="utf-8") as css:
st.markdown( f'<style>{css.read()}</style>' , unsafe_allow_html= True)

st.subheader('changelog: `version 0.1.5`', divider='rainbow')
st.markdown('''
* اضافه شدن صفحه بررسی عملکرد پورتفو
* رفع باگهای کوچک''', unsafe_allow_html=False, help=None)
st.subheader('changelog: `version 0.1.4`', divider='rainbow')
st.markdown('''
* اضافه کردن نمودار پی به ای
Expand All @@ -24,4 +30,4 @@
* گزارش ماهانه فروش
* گزارش تعداد تولید
* گزارش تعداد فروش
* درآمدهای عملیاتی و سود''', unsafe_allow_html=False, help=None)
* درآمدهای عملیاتی و سود''', unsafe_allow_html=False, help=None)
Loading

0 comments on commit 76b7e4a

Please sign in to comment.