Skip to content

Commit

Permalink
Merge pull request #14 from Cuttlas90/ta
Browse files Browse the repository at this point in the history
Ta
  • Loading branch information
Cuttlas90 authored Jul 24, 2024
2 parents 04504c6 + 952388c commit 39bc68d
Show file tree
Hide file tree
Showing 8 changed files with 445 additions and 1 deletion.
2 changes: 1 addition & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
page_title="وسهم",
page_icon="./assets/favicon.ico",
initial_sidebar_state='expanded')
st.session_state.ver = '0.1.8'
st.session_state.ver = '0.1.9'

STREAMLIT_STATIC_PATH = Path(st.__path__[0]) / "static/static"
CSS_PATH = STREAMLIT_STATIC_PATH / "media/"
Expand Down
2 changes: 2 additions & 0 deletions menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,7 @@ def add_menu():
st.sidebar.page_link("pages/portfolio.py", label="تحلیل پورتفو", icon="📊")
st.sidebar.page_link("pages/monte_carlo.py", label="مونته کارلو", icon="🧮")
st.sidebar.page_link("pages/leveraged_funds.py", label="صندوقهای اهرمی", icon="🧮")
st.sidebar.page_link("pages/technical.py", label="اطلاعات تکنیکال", icon="📈")
st.sidebar.page_link("pages/social_page.py", label="اطلاعات رفتاری", icon="🌐")
# st.sidebar.page_link("pages/simple_chart.py", label="نمودار ساده ماهانه", icon="📋")
st.sidebar.page_link("pages/changelog.py", label="تازه ها", icon="💬")
5 changes: 5 additions & 0 deletions pages/changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
if "ver" in st.session_state:
st.sidebar.header(f'Vasahm DashBoard `{st.session_state.ver}`')

st.subheader('changelog: `version 0.1.9`', divider='rainbow')
st.markdown('''
* افزودن صفحه اظلاعات تکنیکال
* افزودن صفحه اطلاعات رفتاری
* رفع باگهای کوچک''', unsafe_allow_html=False, help=None)
st.subheader('changelog: `version 0.1.8`', divider='rainbow')
st.markdown('''
* افزودن صفحه بررسی و مقایسه صندوقهای اهرمی
Expand Down
70 changes: 70 additions & 0 deletions pages/helper/gauge_chart.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import streamlit as st
import pandas as pd
import altair as alt
from login import check_local_token
import numpy as np

from pages.helper.query import Queries
from request import get_stock_monthly
# from slider import create_range_slider
from menu import add_menu
from finta import TA
from request import vasahm_query
import plotly.graph_objs as go
import streamlit.components.v1 as components



def plot_gauge(current_value, min_value, max_value, chart_title, place):
plot_bgcolor = "#def"
quadrant_colors = [plot_bgcolor, "#2bad4e", "#85e043", "#eff229", "#f2a529", "#f25829"]
quadrant_text = ["", "<b>Strong Buy</b>", "<b>Buy</b>", "<b>Neutral</b>", "<b>Sell</b>", "<b>Strong Sell</b>"]
n_quadrants = len(quadrant_colors) - 1

hand_length = np.sqrt(2) / 4
hand_angle = np.pi * (1 - (max(min_value, min(max_value, current_value)) - min_value) / (max_value - min_value))

fig = go.Figure(
data=[
go.Pie(
values=[0.5] + (np.ones(n_quadrants) / 2 / n_quadrants).tolist(),
rotation=90,
hole=0.5,
marker_colors=quadrant_colors,
text=quadrant_text,
textinfo="text",
hoverinfo="skip",
),
],
layout=go.Layout(
showlegend=False,
margin=dict(b=0,t=10,l=10,r=10),
width=450,
height=450,
paper_bgcolor=plot_bgcolor,
annotations=[
go.layout.Annotation(
text=f"<b>{chart_title}</b>",
x=0.5, xanchor="center", xref="paper",
y=0.25, yanchor="bottom", yref="paper",
showarrow=False,
)
],
shapes=[
go.layout.Shape(
type="circle",
x0=0.48, x1=0.52,
y0=0.48, y1=0.52,
fillcolor="#333",
line_color="#333",
),
go.layout.Shape(
type="line",
x0=0.5, x1=0.5 + hand_length * np.cos(hand_angle),
y0=0.5, y1=0.5 + hand_length * np.sin(hand_angle),
line=dict(color="#333", width=4)
)
]
)
)
place.plotly_chart(fig)
35 changes: 35 additions & 0 deletions pages/helper/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,21 @@ def get_stock_data(self):
"""
return string

def get_daily_social(self):
"""return query to monthly sell value data"""
string = f"""select
number,
date
from
public.social_data
INNER JOIN stocks ON public.social_data.stock_id = stocks.id
where
stocks.name = '{self.name}'
LIMIT
30
"""
return string
def get_monthly_sell_value_data(self, dollar = False):
"""return query to monthly sell value data"""
string = f"""select
Expand Down Expand Up @@ -767,6 +782,26 @@ def _dollar_query(self, text):
INNER JOIN dollar ON ranked_dates.end_to_period::varchar = dollar.\"Jalali\"
"""
return query_string

def price_query(self, dollar = False):
"""get stock price"""
string = f"""select
date.miladi AS date,
\"openingPrice\" AS open,
\"maxPrice\" AS high,
\"minPrice\" AS low,
\"lastPrice\" AS close,
\"tradeVolume\" AS volume
from
public.stock_price
INNER JOIN stocks ON public.stock_price.stock_id = stocks.id
INNER JOIN date ON public.stock_price.\"tradeDate\" = date.jalali_3::TEXT
where
stocks.name = '{self.name}'
"""
if dollar:
string = self._dollar_query(string)
return string

QUERY_MONTHLY_COMPARE = """WITH
ranked_dates AS (
Expand Down
156 changes: 156 additions & 0 deletions pages/helper/ta_metrics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@

import streamlit as st
import pandas as pd
import altair as alt
from login import check_local_token
import numpy as np

from pages.helper.gauge_chart import plot_gauge
from pages.helper.query import Queries
from request import get_stock_monthly
# from slider import create_range_slider
from menu import add_menu
from finta import TA
from request import vasahm_query
import plotly.graph_objs as go
import streamlit.components.v1 as components


def _update_guage(a, b, c, condition):
if condition in ["EMA","SMA","VAMA", "HMA"]:
if b >= c:
a = a +1
else:
a=a-1
return a
elif condition in ["RSI","STOCH"]:
if b >= 70.0:
a = a +1
elif b <= 30.0:
a=a-1
return a
elif condition in ["ADX"]:
if b >= 50.0:
a = a +1
elif b <= 50.0:
a=a-1
return a
elif condition == "CCI":
if b >= 100.0:
a = a -1
elif b <= -100.0:
a=a+1
return a
elif condition in ["AO","MOM", "MACD"]:

if b >= 0.0:
a = a +1
elif b <= 0.0:
a=a-1
return a
elif condition in ["STOCHRSI"]:
if b >= 0.5:
a = a +1
elif b <= 0.5:
a=a-1
return a
elif condition in ["WILLIAMS"]:
if b >= -20.0:
a = a +1
elif b <= -80.0:
a=a-1
return a

def add_ta_metrics(stock_data_history, data,metric_label, col, place, num, ind):
if ind == "EMA":
smas = TA.EMA(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'],ind)
return num
elif ind == "SMA":
smas = TA.SMA(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "VAMA":
smas = TA.VAMA(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "HMA":
smas = TA.HMA(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "RSI":
smas = TA.RSI(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "STOCH":
smas = TA.STOCH(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "CCI":
smas = TA.CCI(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "ADX":
smas = TA.ADX(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "AO":
smas = TA.AO(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "MOM":
smas = TA.MOM(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "MACD":
smas = TA.MACD(stock_data_history, data[0], data[1])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "STOCHRSI":
smas = TA.STOCHRSI(stock_data_history, data[0], data[1])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "WILLIAMS":
smas = TA.WILLIAMS(stock_data_history, data[0])
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
num=_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "UO":
smas = TA.UO(stock_data_history)
sma_df = pd.DataFrame(smas)
st.write(sma_df.iloc[-1][col])
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num
elif ind == "EBBP":
smas = TA.EBBP(stock_data_history)
sma_df = pd.DataFrame(smas)
place.metric(label=metric_label, value = int(sma_df.iloc[-1][col]), delta = int(sma_df.iloc[-1][col]-sma_df.iloc[-2][col]))
_update_guage(num, sma_df.iloc[-1][col], stock_data_history.iloc[-1]['close'], ind)
return num

59 changes: 59 additions & 0 deletions pages/social_page.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""Query Workbench."""

import streamlit as st
import pandas as pd
import altair as alt

from login import check_local_token
from pages.helper.query import Queries
from request import vasahm_query
from menu import add_menu



st.set_page_config(layout='wide',
page_title="وسهم - میزکار، دسترسی آزاد اطلاعات",
page_icon="./assets/favicon.ico",
initial_sidebar_state='expanded')

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


add_menu()

df = pd.read_csv("data.csv").dropna()
list_of_name = df['name'].to_list()
if "stock" in st.query_params:
STOCK_INDEX = list_of_name.index(st.query_params.stock)
else:
STOCK_INDEX = 0
name = st.sidebar.selectbox("لیست سهام", options = list_of_name, index=STOCK_INDEX)
selected_stock = df.iloc[df.loc[df['name'] == name].index[0]]

if "ver" in st.session_state:
st.sidebar.header(f'Vasahm DashBoard `{st.session_state.ver}`')

check_local_token()
if "token" in st.session_state:

queries = Queries(name)

error, stock_data = vasahm_query(queries.get_daily_social())
if error:
st.error(stock_data, icon="🚨")
else:
if len(stock_data) > 0:
st.header("اقبال به سهم", divider='rainbow')
stock_data_history = pd.DataFrame(stock_data, columns=[
"number",
"date"])
# stock_data_history["date"] = stock_data_history[
# "date"].astype(str)

chart = alt.Chart(stock_data_history).mark_bar().encode(
# alt.Color('row_title:N', title="سرفصلها"),
alt.Y('number:Q', title="تعداد کامنت"),
alt.X('date:N',title="تاریخ")
)
st.altair_chart(chart, use_container_width=True)
Loading

0 comments on commit 39bc68d

Please sign in to comment.