AmirTrader commited on
Commit
67a7436
·
verified ·
1 Parent(s): 563039f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +339 -131
app.py CHANGED
@@ -1,55 +1,80 @@
1
  import pandas as pd
2
  import numpy as np
3
 
4
- import os,io
 
5
 
6
  from datetime import datetime
7
  from datetime import timedelta
8
 
9
- import hvplot as hv
10
  import holoviews as hvs
11
  import panel as pn
12
- import hvplot.pandas
 
13
 
14
  import yfinance as yf
15
 
16
  from dotenv import load_dotenv
17
- # from datasets import load_dataset
18
 
19
- from utils import upload_to_hf_dataset, download_from_hf_dataset, load_hf_dataset
 
20
 
21
- pn.extension('bokeh', template='bootstrap')
22
 
23
  def _extract_raw_data(ticker):
24
- df = yf.Ticker(ticker)
25
- return df.history(period="6mo", interval="1d").reset_index()
 
26
 
27
  def _transform_data(raw_data: pd.DataFrame):
28
- data = raw_data[["Date", "Open", "High", "Low", "Close", "Volume"]].copy(deep=True).rename(columns={
29
- "Date": "time",
30
- "Open": "open",
31
- "High": "high",
32
- "Low": "low",
33
- "Close": "close",
34
- "Volume": "volume",
35
- })
36
- t_delta = timedelta(hours=1)
37
- data['time_start'] = data.time - 9*t_delta # rectangles start
38
- data['time_end'] = data.time + 9*t_delta # rectangles end
39
- data['positive'] = ((data.close - data.open)>0).astype(int)
40
- return data
 
 
 
 
 
 
 
41
 
42
  def make_candle_stick(ticker):
43
- raw_data = _extract_raw_data(ticker = ticker)
44
  data = _transform_data(raw_data=raw_data)
45
  _delta = np.median(np.diff(data.time))
46
- candlestick = hvs.Segments(data, kdims=['time', 'low', 'time', 'high']) * hvs.Rectangles(data, kdims=['time_start','open', 'time_end', 'close'], vdims=['positive'])
47
- candlestick = candlestick.redim.label(Low='Values')
48
- candlechart = pn.Column(candlestick.opts(hvs.opts.Rectangles(color='positive', cmap=['red', 'green'], responsive=True), hvs.opts.Segments(color='black', height=400, responsive=True , show_grid=True)) ,
49
- data.hvplot(x="time", y="volume", kind="line", responsive=True, height=200).opts( show_grid=True) )
50
- # data.hvplot(y="volume", kind="bar", responsive=True, height=200) )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  return candlechart
52
 
 
53
  # Function to convert DataFrame to CSV
54
  def get_csv(df):
55
  sio = io.StringIO()
@@ -57,10 +82,11 @@ def get_csv(df):
57
  sio.seek(0)
58
  return sio
59
 
 
60
  # Function to convert the 'Ticker' column to a comma-separated string in a text file
61
  def get_text(df):
62
- tickers = df['Ticker'].tolist()
63
- tickers_str = ','.join(tickers)
64
  sio = io.StringIO()
65
  sio.write(tickers_str)
66
  sio.seek(0)
@@ -71,158 +97,340 @@ def get_text(df):
71
  load_dotenv()
72
 
73
  # Get the Hugging Face API token from the environment; either set in .env file or in the environment directly in GitHub
74
- HF_TOKEN = os.getenv('HF_TOKEN')
75
 
76
  # Get the name of the GuruFocus dataset for TradingView, Finviz, MarketBeat and TipRanks to read from
77
- dataset_name_BeatingMarket_input = os.getenv('dataset_name_BeatingMarket_input')
78
- dataset_name_TradingView_input = os.getenv('dataset_name_TradingView_input')
79
- dataset_name_GuruFocus_input = os.getenv('dataset_name_GuruFocus_input')
80
- dataset_name_FinViz_input = os.getenv('dataset_name_FinViz_input')
81
- dataset_name_TipRanks_input = os.getenv('dataset_name_TipRanks_input')
82
-
83
-
84
- current_datetime = datetime.now().strftime("%Y-%m-%d")
85
 
86
 
87
  @pn.cache()
88
  def get_tradingview(current_datetime):
89
- #Load lastest TradingView DataSet from HuggingFace Dataset which is always america.csv
90
- # download_from_hf_dataset("america.csv", dataset_name_TradingView_input, HF_TOKEN)
91
- return load_hf_dataset("america.csv", HF_TOKEN, dataset_name_TradingView_input)
 
92
 
93
  @pn.cache()
94
  def get_marketbeat(current_datetime):
95
- return load_hf_dataset("beatingmarket.csv", HF_TOKEN, dataset_name_BeatingMarket_input)
 
 
 
96
 
97
  @pn.cache()
98
  def get_gurufocus(current_datetime):
99
- #Rading gurufocus from github action pipeline
100
- # daily_gurufocus_csvfile = f"https://raw.githubusercontent.com/alirezax2/GurusFocusCrawl/main/gurufocusuruFocus_merged_{current_datetime}.csv"
101
- # daily_gurufocus_DF = pd.read_csv(daily_gurufocus_csvfile)
102
- # daily_gurufocus_DF = load_dataset(dataset_name_GuruFocus_output , data_files="GuruFocus_merged.csv", split="train" , token=HF_TOKEN ).to_pandas()
103
- return load_hf_dataset("GuruFocus_merged.csv", HF_TOKEN, dataset_name_GuruFocus_input)
104
-
 
105
  @pn.cache()
106
  def get_finviz(current_datetime):
107
- return load_hf_dataset("FinViz.csv", HF_TOKEN, dataset_name_FinViz_input)
 
 
108
 
109
  @pn.cache()
110
  def get_tipranks(current_datetime):
111
- return load_hf_dataset("tipranks.csv", HF_TOKEN, dataset_name_TipRanks_input)
 
112
 
113
 
114
- #Reading gurufocus,finviz from local crawling pipeline; Need to update github action to merge gurufocus daily with monthly tiprank
 
115
  daily_gurufocus_DF = get_gurufocus(current_datetime)
116
  daily_finviz_DF = get_finviz(current_datetime)
117
  daily_marketbeat = get_marketbeat(current_datetime)
118
  monthly_tiprank_DF = get_tipranks(current_datetime)
119
- monthly_tiprank_DF = monthly_tiprank_DF[['Ticker','SmartScore','Market Capitalization','Sector','Industry']]
120
-
121
 
122
- daily_finviz_DF['FinVizPrice'] = pd.to_numeric(daily_finviz_DF['Price'], errors='coerce').fillna(0).astype(float)
123
- daily_finviz_DF['FinVizTarget'] = pd.to_numeric(daily_finviz_DF['Target Price'], errors='coerce').fillna(0).astype(float)
124
- daily_finviz_DF['FinVizTargetpercent'] = (100*(daily_finviz_DF['FinVizTarget']-daily_finviz_DF['FinVizPrice'])/daily_finviz_DF['FinVizPrice']).round(2)
125
- daily_finviz_DF_filtered = daily_finviz_DF[['Ticker','Price','FinVizTarget','FinVizTargetpercent']]
126
 
127
- #Merging tipranks with Gurufocus
128
- DFgurufocus = daily_gurufocus_DF[['Ticker' , 'GFValue']] # , 'GFValuediff']]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  DFmerge_tipranks_gurufocus = DFgurufocus.merge(monthly_tiprank_DF)
130
 
131
- #Merging Finviz with Merged last one
132
  DFmerge_tipranks_gurufocus = DFmerge_tipranks_gurufocus.merge(daily_finviz_DF_filtered)
133
 
134
- print(daily_marketbeat.columns)
135
  # ['Ticker', 'AverageTarget', 'MaxTarget', 'LowTarget', 'CurrentPrice']
136
- daily_marketbeat['AllTargetsAbovePrice'] = ((daily_marketbeat['MaxTarget'] > daily_marketbeat['CurrentPrice']) &
137
- (daily_marketbeat['LowTarget'] > daily_marketbeat['CurrentPrice']) &
138
- (daily_marketbeat['AverageTarget'] > daily_marketbeat['CurrentPrice'])).astype(int)
 
 
139
 
140
- #Merging daily_marketbeat with Merged last one
141
  DFmerge_tipranks_gurufocus = DFmerge_tipranks_gurufocus.merge(daily_marketbeat)
142
 
143
- if 'Price' in DFmerge_tipranks_gurufocus.columns and 'GFValue' in DFmerge_tipranks_gurufocus.columns:
144
- DFmerge_tipranks_gurufocus['GFValuepercent'] = 100* ( DFmerge_tipranks_gurufocus['GFValue'] - DFmerge_tipranks_gurufocus['Price']) / DFmerge_tipranks_gurufocus['Price']
145
- DFmerge_tipranks_gurufocus['GFValuepercent'] = DFmerge_tipranks_gurufocus['GFValuepercent'].round(2)
146
- DFmerge_tipranks_gurufocus['Market Capitalization'] = DFmerge_tipranks_gurufocus['Market Capitalization'] / 1e9
147
- DFmerge_tipranks_gurufocus['MarketCap'] = DFmerge_tipranks_gurufocus['Market Capitalization'].round(1)
148
- DFmerge_tipranks_gurufocus = DFmerge_tipranks_gurufocus.drop(columns=['Market Capitalization'])
149
- DFmerge_tipranks_gurufocus = DFmerge_tipranks_gurufocus[['Ticker', 'Sector', 'Industry' , 'MarketCap' , 'SmartScore', 'Price' , 'GFValue' , 'GFValuepercent' , 'FinVizTarget','FinVizTargetpercent']]
150
-
151
-
152
- #widget
153
- ticker = pn.widgets.AutocompleteInput(name='Ticker', options=list(DFmerge_tipranks_gurufocus.Ticker) , placeholder='Write Ticker here همین جا',value='ALL', restrict=False)
154
- SmartScore = pn.widgets.EditableRangeSlider(name='Smart Score', start=0, end=10, value=(9, 10), step=1)
155
- Industry = pn.widgets.CheckBoxGroup( name='Select Industry', value=list(set(DFmerge_tipranks_gurufocus.Industry)), options=list(set(DFmerge_tipranks_gurufocus.Industry)), inline=True)
156
- Sector = pn.widgets.MultiSelect( name='Select Sector', value=list(set(DFmerge_tipranks_gurufocus.Sector)), options=list(set(DFmerge_tipranks_gurufocus.Sector)) )#, inline=False)
157
- GFValuepercent = pn.widgets.FloatSlider(name='GF Value %', start=-100, end=100, step=1, value=12.0)
158
- FinVizTargetpercent = pn.widgets.FloatSlider(name='FinViz Target %', start=-100, end=100, step=1, value=12.0)
159
- MarketCap = pn.widgets.FloatSlider(name='Market Capital (B$)', start=0, end=1000, step=1, value=10)
160
- MarketBeat_radio_group = pn.widgets.RadioButtonGroup(name='MarketBeat', options=['Default', 'Above all Targets'], button_type='success')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  # Create a file download link
163
  download_button_GuruFocus = pn.widgets.FileDownload(
164
- filename=f'GuruFocus_merged_{current_datetime}.csv',
165
- callback=pn.bind(get_csv,daily_gurufocus_DF),
166
- button_type='primary',
167
- label='Download GuruFocus', width=250
 
168
  )
169
 
170
  download_button_FinViz = pn.widgets.FileDownload(
171
- filename=f'FinViz_{current_datetime}.csv',
172
- callback=pn.bind(get_csv,daily_finviz_DF),
173
- button_type='primary',
174
- label='Download FinViz', width=250
 
175
  )
176
 
177
  download_button_MarketBeat = pn.widgets.FileDownload(
178
- filename=f'MarketBeat_{current_datetime}.csv',
179
- callback=pn.bind(get_csv,daily_marketbeat),
180
- button_type='warning',
181
- label='Download MarketBeat', width=250
 
182
  )
183
 
184
  download_button_TipRanks = pn.widgets.FileDownload(
185
- filename=f'TipRanks_{current_datetime}.csv',
186
- callback=pn.bind(get_csv,monthly_tiprank_DF),
187
- button_type='warning',
188
- label='Download TipRanks', width=250
189
- )
190
-
191
- png_pane = pn.pane.GIF('https://tuozi.vip/shqu/wordpress/wp-content/themes/CorePress/static/img/loading.gif', width=200) #, height=150)
192
- def get_DF(DF,ticker,SmartScore,GFValuepercent, FinVizTargetpercent, Sector,MarketCap,MarketBeat):
193
- if ticker and ticker!="ALL":
194
- table1 = pn.widgets.Tabulator(DF.query("Ticker == @ticker"), height=200, widths=200, show_index=False)
195
- chart1 = make_candle_stick(ticker)
196
- return pn.Column(table1,chart1)
197
- else:
198
- if MarketBeat == 0:
199
- tabulator = pn.widgets.Tabulator( DF.query("SmartScore>=@SmartScore[0] & SmartScore <= @SmartScore[1] & GFValuepercent>=@GFValuepercent & FinVizTargetpercent>@FinVizTargetpercent & Sector in @Sector & MarketCap>@MarketCap & AllTargetsAbovePrice==1"), height=800, widths=200, show_index=False ,theme='modern')
200
- else:
201
- tabulator = pn.widgets.Tabulator( DF.query("SmartScore>=@SmartScore[0] & SmartScore <= @SmartScore[1] & GFValuepercent>=@GFValuepercent & FinVizTargetpercent>@FinVizTargetpercent & Sector in @Sector & MarketCap>@MarketCap"), height=800, widths=200, show_index=False ,theme='modern')
202
- tabulator.disabled = True
203
- print(tabulator.disabled)
204
- print(80*'***')
205
- return tabulator
206
-
207
- def get_DF_filter(DF,ticker,SmartScore,GFValuepercent, FinVizTargetpercent, Sector,MarketCap):
208
- return DF.query("SmartScore>=@SmartScore[0] & SmartScore <= @SmartScore[1] & GFValuepercent>=@GFValuepercent & FinVizTargetpercent>@FinVizTargetpercent & Sector in @Sector & MarketCap>@MarketCap")
209
 
210
- download_button_Filter = pn.widgets.FileDownload(
211
- filename=f'Filter_{current_datetime}.csv',
212
- callback=pn.bind(get_csv,pn.bind(get_DF_filter, DF=DFmerge_tipranks_gurufocus,ticker=ticker,SmartScore=SmartScore,GFValuepercent=GFValuepercent, FinVizTargetpercent=FinVizTargetpercent, Sector=Sector ,MarketCap=MarketCap) ),
213
- button_type='danger',
214
- label='Download your Filter', width=250
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  )
217
 
218
  download_button_watchlist = pn.widgets.FileDownload(
219
- filename=f'watchlist_{current_datetime}.txt',
220
- callback=pn.bind(get_text,pn.bind(get_DF_filter, DF=DFmerge_tipranks_gurufocus,ticker=ticker,SmartScore=SmartScore,GFValuepercent=GFValuepercent, FinVizTargetpercent=FinVizTargetpercent, Sector=Sector ,MarketCap=MarketCap) ),
221
- button_type='success',
222
- label='Download Watchlist', width=250
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  )
224
 
225
- pn.extension('tabulator')
226
- bound_plot = pn.bind(get_DF, DF=DFmerge_tipranks_gurufocus,ticker=ticker,SmartScore=SmartScore,GFValuepercent=GFValuepercent, FinVizTargetpercent=FinVizTargetpercent, Sector=Sector ,MarketCap=MarketCap,MarketBeat=MarketBeat_radio_group)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
 
228
- pn.Column(pn.Row(pn.Column(ticker,SmartScore,GFValuepercent, FinVizTargetpercent, MarketCap, MarketBeat_radio_group, png_pane, download_button_GuruFocus,download_button_FinViz , download_button_MarketBeat, download_button_TipRanks, download_button_Filter, download_button_watchlist),bound_plot)).servable(title="Fair Value Ranking - Merged Gurufocus & Tipranks & FinViz & MorningStars & MarketBeat")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import pandas as pd
2
  import numpy as np
3
 
4
+ import os
5
+ import io
6
 
7
  from datetime import datetime
8
  from datetime import timedelta
9
 
 
10
  import holoviews as hvs
11
  import panel as pn
12
+ # import hvplot as hv
13
+ # import hvplot.pandas
14
 
15
  import yfinance as yf
16
 
17
  from dotenv import load_dotenv
 
18
 
19
+ # from datasets import load_dataset
20
+ from utils import load_hf_dataset # ,upload_to_hf_dataset, download_from_hf_dataset
21
 
22
+ pn.extension("bokeh", template="bootstrap")
23
 
24
  def _extract_raw_data(ticker):
25
+ df = yf.Ticker(ticker)
26
+ return df.history(period="6mo", interval="1d").reset_index()
27
+
28
 
29
  def _transform_data(raw_data: pd.DataFrame):
30
+ data = (
31
+ raw_data[["Date", "Open", "High", "Low", "Close", "Volume"]]
32
+ .copy(deep=True)
33
+ .rename(
34
+ columns={
35
+ "Date": "time",
36
+ "Open": "open",
37
+ "High": "high",
38
+ "Low": "low",
39
+ "Close": "close",
40
+ "Volume": "volume",
41
+ }
42
+ )
43
+ )
44
+ t_delta = timedelta(hours=1)
45
+ data["time_start"] = data.time - 9 * t_delta # rectangles start
46
+ data["time_end"] = data.time + 9 * t_delta # rectangles end
47
+ data["positive"] = ((data.close - data.open) > 0).astype(int)
48
+ return data
49
+
50
 
51
  def make_candle_stick(ticker):
52
+ raw_data = _extract_raw_data(ticker=ticker)
53
  data = _transform_data(raw_data=raw_data)
54
  _delta = np.median(np.diff(data.time))
55
+ candlestick = hvs.Segments(
56
+ data, kdims=["time", "low", "time", "high"]
57
+ ) * hvs.Rectangles(
58
+ data, kdims=["time_start", "open", "time_end", "close"], vdims=["positive"]
59
+ )
60
+ candlestick = candlestick.redim.label(Low="Values")
61
+ candlechart = pn.Column(
62
+ candlestick.opts(
63
+ hvs.opts.Rectangles(
64
+ color="positive", cmap=["red", "green"], responsive=True
65
+ ),
66
+ hvs.opts.Segments(
67
+ color="black", height=400, responsive=True, show_grid=True
68
+ ),
69
+ ),
70
+ data.hvplot(
71
+ x="time", y="volume", kind="line", responsive=True, height=200
72
+ ).opts(show_grid=True),
73
+ )
74
+ # data.hvplot(y="volume", kind="bar", responsive=True, height=200) )
75
  return candlechart
76
 
77
+
78
  # Function to convert DataFrame to CSV
79
  def get_csv(df):
80
  sio = io.StringIO()
 
82
  sio.seek(0)
83
  return sio
84
 
85
+
86
  # Function to convert the 'Ticker' column to a comma-separated string in a text file
87
  def get_text(df):
88
+ tickers = df["Ticker"].tolist()
89
+ tickers_str = ",".join(tickers)
90
  sio = io.StringIO()
91
  sio.write(tickers_str)
92
  sio.seek(0)
 
97
  load_dotenv()
98
 
99
  # Get the Hugging Face API token from the environment; either set in .env file or in the environment directly in GitHub
100
+ HF_TOKEN = os.getenv("HF_TOKEN")
101
 
102
  # Get the name of the GuruFocus dataset for TradingView, Finviz, MarketBeat and TipRanks to read from
103
+ dataset_name_BeatingMarket_input = os.getenv("dataset_name_BeatingMarket_input")
104
+ dataset_name_TradingView_input = os.getenv("dataset_name_TradingView_input")
105
+ dataset_name_GuruFocus_input = os.getenv("dataset_name_GuruFocus_input")
106
+ dataset_name_FinViz_input = os.getenv("dataset_name_FinViz_input")
107
+ dataset_name_TipRanks_input = os.getenv("dataset_name_TipRanks_input")
 
 
 
108
 
109
 
110
  @pn.cache()
111
  def get_tradingview(current_datetime):
112
+ # Load lastest TradingView DataSet from HuggingFace Dataset which is always america.csv
113
+ # download_from_hf_dataset("america.csv", dataset_name_TradingView_input, HF_TOKEN)
114
+ return load_hf_dataset("america.csv", HF_TOKEN, dataset_name_TradingView_input)
115
+
116
 
117
  @pn.cache()
118
  def get_marketbeat(current_datetime):
119
+ return load_hf_dataset(
120
+ "beatingmarket.csv", HF_TOKEN, dataset_name_BeatingMarket_input
121
+ )
122
+
123
 
124
  @pn.cache()
125
  def get_gurufocus(current_datetime):
126
+ # Load lastest GuruFocus DataSet from HuggingFace Dataset which is always GuruFocus_merged.csv
127
+ # daily_gurufocus_DF = load_dataset(dataset_name_GuruFocus_output , data_files="GuruFocus_merged.csv", split="train" , token=HF_TOKEN ).to_pandas()
128
+ return load_hf_dataset(
129
+ "GuruFocus_merged.csv", HF_TOKEN, dataset_name_GuruFocus_input
130
+ )
131
+
132
+
133
  @pn.cache()
134
  def get_finviz(current_datetime):
135
+ # Load lastest FinViz DataSet from HuggingFace Dataset which is always FinViz.csv
136
+ return load_hf_dataset("FinViz.csv", HF_TOKEN, dataset_name_FinViz_input)
137
+
138
 
139
  @pn.cache()
140
  def get_tipranks(current_datetime):
141
+ # Load lastest TipRanks DataSet from HuggingFace Dataset which is always tipranks.csv
142
+ return load_hf_dataset("tipranks.csv", HF_TOKEN, dataset_name_TipRanks_input)
143
 
144
 
145
+ # Reading gurufocus,finviz from crawling pipelines with GitHub Action
146
+ current_datetime = datetime.now().strftime("%Y-%m-%d")
147
  daily_gurufocus_DF = get_gurufocus(current_datetime)
148
  daily_finviz_DF = get_finviz(current_datetime)
149
  daily_marketbeat = get_marketbeat(current_datetime)
150
  monthly_tiprank_DF = get_tipranks(current_datetime)
 
 
151
 
152
+ # TipRanks
153
+ monthly_tiprank_DF = monthly_tiprank_DF[["Ticker", "SmartScore"]]
 
 
154
 
155
+ # FinViz
156
+ daily_finviz_DF["FinVizPrice"] = (
157
+ pd.to_numeric(daily_finviz_DF["Price"], errors="coerce").fillna(0).astype(float)
158
+ )
159
+ daily_finviz_DF["FinVizTarget"] = (
160
+ pd.to_numeric(daily_finviz_DF["Target Price"], errors="coerce")
161
+ .fillna(0)
162
+ .astype(float)
163
+ )
164
+ daily_finviz_DF["FinVizTargetpercent"] = (
165
+ 100
166
+ * (daily_finviz_DF["FinVizTarget"] - daily_finviz_DF["FinVizPrice"])
167
+ / daily_finviz_DF["FinVizPrice"]
168
+ ).round(2)
169
+ daily_finviz_DF_filtered = daily_finviz_DF[
170
+ ["Ticker", "Price", "FinVizTarget", "FinVizTargetpercent"]
171
+ ]
172
+
173
+ # Merging tipranks with Gurufocus
174
+ DFgurufocus = daily_gurufocus_DF[
175
+ ["Ticker", "GFValue", "Market Capitalization", "Sector", "Industry"]
176
+ ] # , 'GFValuediff']]
177
  DFmerge_tipranks_gurufocus = DFgurufocus.merge(monthly_tiprank_DF)
178
 
179
+ # Merging Finviz with Merged last one
180
  DFmerge_tipranks_gurufocus = DFmerge_tipranks_gurufocus.merge(daily_finviz_DF_filtered)
181
 
 
182
  # ['Ticker', 'AverageTarget', 'MaxTarget', 'LowTarget', 'CurrentPrice']
183
+ daily_marketbeat["MarketBeat"] = (
184
+ (daily_marketbeat["MaxTarget"] > daily_marketbeat["CurrentPrice"])
185
+ & (daily_marketbeat["LowTarget"] > daily_marketbeat["CurrentPrice"])
186
+ & (daily_marketbeat["AverageTarget"] > daily_marketbeat["CurrentPrice"])
187
+ ).astype(int)
188
 
189
+ # Merging daily_marketbeat with Merged last one
190
  DFmerge_tipranks_gurufocus = DFmerge_tipranks_gurufocus.merge(daily_marketbeat)
191
 
192
+ if (
193
+ "Price" in DFmerge_tipranks_gurufocus.columns
194
+ and "GFValue" in DFmerge_tipranks_gurufocus.columns
195
+ ):
196
+ DFmerge_tipranks_gurufocus["GFValuepercent"] = (
197
+ 100
198
+ * (DFmerge_tipranks_gurufocus["GFValue"] - DFmerge_tipranks_gurufocus["Price"])
199
+ / DFmerge_tipranks_gurufocus["Price"]
200
+ )
201
+ DFmerge_tipranks_gurufocus["GFValuepercent"] = DFmerge_tipranks_gurufocus[
202
+ "GFValuepercent"
203
+ ].round(2)
204
+ DFmerge_tipranks_gurufocus["Market Capitalization"] = (
205
+ DFmerge_tipranks_gurufocus["Market Capitalization"] / 1e9
206
+ )
207
+ DFmerge_tipranks_gurufocus["MarketCap"] = DFmerge_tipranks_gurufocus[
208
+ "Market Capitalization"
209
+ ].round(1)
210
+ DFmerge_tipranks_gurufocus = DFmerge_tipranks_gurufocus.drop(
211
+ columns=["Market Capitalization"]
212
+ )
213
+ DFmerge_tipranks_gurufocus = DFmerge_tipranks_gurufocus[
214
+ [
215
+ "Ticker",
216
+ "Sector",
217
+ "Industry",
218
+ "MarketCap",
219
+ "SmartScore",
220
+ "Price",
221
+ "GFValue",
222
+ "GFValuepercent",
223
+ "FinVizTarget",
224
+ "FinVizTargetpercent",
225
+ "MarketBeat",
226
+ ]
227
+ ]
228
+
229
+
230
+ # widget
231
+ ticker = pn.widgets.AutocompleteInput(
232
+ name="Ticker",
233
+ options=list(DFmerge_tipranks_gurufocus.Ticker),
234
+ placeholder="Write Ticker here همین جا",
235
+ value="ALL",
236
+ restrict=False,
237
+ )
238
+ SmartScore = pn.widgets.EditableRangeSlider(
239
+ name="Smart Score", start=0, end=10, value=(9, 10), step=1
240
+ )
241
+ Industry = pn.widgets.CheckBoxGroup(
242
+ name="Select Industry",
243
+ value=list(set(DFmerge_tipranks_gurufocus.Industry)),
244
+ options=list(set(DFmerge_tipranks_gurufocus.Industry)),
245
+ inline=True,
246
+ )
247
+ Sector = pn.widgets.MultiSelect(
248
+ name="Select Sector",
249
+ value=list(set(DFmerge_tipranks_gurufocus.Sector)),
250
+ options=list(set(DFmerge_tipranks_gurufocus.Sector)),
251
+ ) # , inline=False)
252
+ GFValuepercent = pn.widgets.FloatSlider(
253
+ name="GF Value %", start=-100, end=100, step=1, value=12.0
254
+ )
255
+ FinVizTargetpercent = pn.widgets.FloatSlider(
256
+ name="FinViz Target %", start=-100, end=100, step=1, value=12.0
257
+ )
258
+ MarketCap = pn.widgets.FloatSlider(
259
+ name="Market Capital (B$)", start=0, end=1000, step=1, value=10
260
+ )
261
+ MarketBeat_radio_group = pn.widgets.RadioButtonGroup(
262
+ name="MarketBeat",
263
+ options=["Default Targets", "Above all Targets"],
264
+ button_type="success",
265
+ value="Above all Targets",
266
+ )
267
 
268
  # Create a file download link
269
  download_button_GuruFocus = pn.widgets.FileDownload(
270
+ filename=f"GuruFocus_merged_{current_datetime}.csv",
271
+ callback=pn.bind(get_csv, daily_gurufocus_DF),
272
+ button_type="primary",
273
+ label="Download GuruFocus",
274
+ width=250,
275
  )
276
 
277
  download_button_FinViz = pn.widgets.FileDownload(
278
+ filename=f"FinViz_{current_datetime}.csv",
279
+ callback=pn.bind(get_csv, daily_finviz_DF),
280
+ button_type="primary",
281
+ label="Download FinViz",
282
+ width=250,
283
  )
284
 
285
  download_button_MarketBeat = pn.widgets.FileDownload(
286
+ filename=f"MarketBeat_{current_datetime}.csv",
287
+ callback=pn.bind(get_csv, daily_marketbeat),
288
+ button_type="warning",
289
+ label="Download MarketBeat",
290
+ width=250,
291
  )
292
 
293
  download_button_TipRanks = pn.widgets.FileDownload(
294
+ filename=f"TipRanks_{current_datetime}.csv",
295
+ callback=pn.bind(get_csv, monthly_tiprank_DF),
296
+ button_type="warning",
297
+ label="Download TipRanks",
298
+ width=250,
299
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
 
 
 
 
 
 
301
 
302
+ def get_DF_filter(
303
+ DF, ticker, SmartScore, GFValuepercent, FinVizTargetpercent, Sector, MarketCap
304
+ ):
305
+ return DF.query(
306
+ "SmartScore>=@SmartScore[0] & SmartScore <= @SmartScore[1] & GFValuepercent>=@GFValuepercent & FinVizTargetpercent>@FinVizTargetpercent & Sector in @Sector & MarketCap>@MarketCap"
307
+ )
308
+
309
+ download_button_Filter = pn.widgets.FileDownload(
310
+ filename=f"Filter_{current_datetime}.csv",
311
+ callback=pn.bind(
312
+ get_csv,
313
+ pn.bind(
314
+ get_DF_filter,
315
+ DF=DFmerge_tipranks_gurufocus,
316
+ ticker=ticker,
317
+ SmartScore=SmartScore,
318
+ GFValuepercent=GFValuepercent,
319
+ FinVizTargetpercent=FinVizTargetpercent,
320
+ Sector=Sector,
321
+ MarketCap=MarketCap,
322
+ ),
323
+ ),
324
+ button_type="danger",
325
+ label="Download your Filter",
326
+ width=250,
327
  )
328
 
329
  download_button_watchlist = pn.widgets.FileDownload(
330
+ filename=f"watchlist_{current_datetime}.txt",
331
+ callback=pn.bind(
332
+ get_text,
333
+ pn.bind(
334
+ get_DF_filter,
335
+ DF=DFmerge_tipranks_gurufocus,
336
+ ticker=ticker,
337
+ SmartScore=SmartScore,
338
+ GFValuepercent=GFValuepercent,
339
+ FinVizTargetpercent=FinVizTargetpercent,
340
+ Sector=Sector,
341
+ MarketCap=MarketCap,
342
+ ),
343
+ ),
344
+ button_type="success",
345
+ label="Download Watchlist",
346
+ width=250,
347
  )
348
 
349
+ png_pane = pn.pane.GIF(
350
+ "https://tuozi.vip/shqu/wordpress/wp-content/themes/CorePress/static/img/loading.gif",
351
+ width=200,
352
+ ) # , height=150)
353
+ png_pane2 = pn.pane.GIF(
354
+ "https://www.mywallstreetadvisor.com/_next/image?url=%2FMyWallStreetAdvisorLOGO.png&w=64&q=75",
355
+ width=50,
356
+ ) # , height=150)
357
+
358
+
359
+ def get_DF(
360
+ DF,
361
+ ticker,
362
+ SmartScore,
363
+ GFValuepercent,
364
+ FinVizTargetpercent,
365
+ Sector,
366
+ MarketCap,
367
+ MarketBeat,
368
+ ):
369
+ if ticker and ticker != "ALL":
370
+ table1 = pn.widgets.Tabulator(
371
+ DF.query("Ticker == @ticker"), height=200, widths=200, show_index=False
372
+ )
373
+ table1.disabled = True
374
+ chart1 = make_candle_stick(ticker)
375
+ return pn.Column(table1, chart1)
376
+ else:
377
+ if MarketBeat == "Above all Targets":
378
+ tabulator = pn.widgets.Tabulator(
379
+ DF.query(
380
+ "SmartScore>=@SmartScore[0] & SmartScore <= @SmartScore[1] & GFValuepercent>=@GFValuepercent & FinVizTargetpercent>@FinVizTargetpercent & Sector in @Sector & MarketCap>@MarketCap & MarketBeat==1"
381
+ ),
382
+ height=800,
383
+ widths=200,
384
+ show_index=False,
385
+ theme="modern",
386
+ )
387
+ else:
388
+ tabulator = pn.widgets.Tabulator(
389
+ DF.query(
390
+ "SmartScore>=@SmartScore[0] & SmartScore <= @SmartScore[1] & GFValuepercent>=@GFValuepercent & FinVizTargetpercent>@FinVizTargetpercent & Sector in @Sector & MarketCap>@MarketCap"
391
+ ),
392
+ height=800,
393
+ widths=200,
394
+ show_index=False,
395
+ theme="modern",
396
+ )
397
+ tabulator.disabled = True
398
+ return tabulator
399
+
400
+
401
+ pn.extension("tabulator")
402
+ bound_plot = pn.bind(
403
+ get_DF,
404
+ DF=DFmerge_tipranks_gurufocus,
405
+ ticker=ticker,
406
+ SmartScore=SmartScore,
407
+ GFValuepercent=GFValuepercent,
408
+ FinVizTargetpercent=FinVizTargetpercent,
409
+ Sector=Sector,
410
+ MarketCap=MarketCap,
411
+ MarketBeat=MarketBeat_radio_group,
412
+ )
413
 
414
+ pn.Column(
415
+ pn.Row(
416
+ pn.Column(
417
+ pn.Row(png_pane2, align="center"),
418
+ ticker,
419
+ SmartScore,
420
+ GFValuepercent,
421
+ FinVizTargetpercent,
422
+ MarketCap,
423
+ pn.Row(MarketBeat_radio_group, align="start"),
424
+ png_pane,
425
+ download_button_GuruFocus,
426
+ download_button_FinViz,
427
+ download_button_MarketBeat,
428
+ download_button_TipRanks,
429
+ download_button_Filter,
430
+ download_button_watchlist,
431
+ ),
432
+ pn.Row(bound_plot, align="center"),
433
+ )
434
+ ).servable(
435
+ title="Fair Value Ranking - Merged Gurufocus & Tipranks & FinViz & MorningStars & MarketBeat"
436
+ )