chrisvnz commited on
Commit
b988502
·
1 Parent(s): 4b50feb

Update app.py

Browse files

Changed logic, added stochastic checker, split outputs for bullish and bearish lists for easier processing

Files changed (1) hide show
  1. app.py +40 -39
app.py CHANGED
@@ -1,31 +1,13 @@
1
  import gradio as gr
2
- from gradio.inputs import File as InputFile
3
  from gradio.outputs import File as OutputFile
4
- from yahoo_fin import stock_info as si
5
  import yfinance as yf
6
  import pandas as pd
7
  import pandas_ta as ta
8
  import csv
 
9
 
10
- def detect_head_and_shoulders(hist):
11
- local_max = hist['Close'][-60:][((hist['Close'][-60:].shift(1) < hist['Close'][-60:]) & (hist['Close'][-60:].shift(-1) < hist['Close'][-60:]))]
12
- if len(local_max) < 3:
13
- return False
14
- peaks = local_max[-3:]
15
- if peaks[0] < peaks[1] and peaks[2] < peaks[1] and abs(peaks[0] - peaks[2]) < peaks[1]*0.05:
16
- return True
17
- return False
18
-
19
- def detect_inverted_head_and_shoulders(hist):
20
- local_min = hist['Close'][-60:][((hist['Close'][-60:].shift(1) > hist['Close'][-60:]) & (hist['Close'][-60:].shift(-1) > hist['Close'][-60:]))]
21
- if len(local_min) < 3:
22
- return False
23
- valleys = local_min[-3:]
24
- if valleys[0] > valleys[1] and valleys[2] > valleys[1] and abs(valleys[0] - valleys[2]) < valleys[1]*0.05:
25
- return True
26
- return False
27
-
28
- def process_csv(csv_file):
29
  all_tickers = []
30
  with open(csv_file.name, 'r') as file:
31
  reader = csv.reader(file)
@@ -34,8 +16,10 @@ def process_csv(csv_file):
34
  all_tickers.append(row[0]) # Append the value in the first column
35
 
36
  ttl_tickers = len(all_tickers)
37
- filtered_tickers = []
 
38
  for ticker in all_tickers:
 
39
  try:
40
  data = yf.Ticker(ticker)
41
  hist = data.history(period="1y", actions=False)
@@ -45,31 +29,48 @@ def process_csv(csv_file):
45
  hist.ta.ema(close='Close', length=100, append=True)
46
  hist.ta.sma(close='Close', length=150, append=True)
47
  stoch = hist.ta.stoch(high='High', low='Low', close='Close')
48
- if all(hist['EMA_20'][-10:] > hist['EMA_50'][-10:]) and all(hist['EMA_50'][-10:] > hist['EMA_100'][-10:]) and all(hist['EMA_100'][-10:] > hist['SMA_150'][-10:]) and stoch['STOCHk_14_3_3'][-1] < 30:
49
- filtered_tickers.append([ticker, hist['Close'][-1], hist['Volume'][-1], 'Bullish', 'Head and Shoulders' if detect_head_and_shoulders(hist) else '', 'Inverted Head and Shoulders' if detect_inverted_head_and_shoulders(hist) else ''])
50
- elif all(hist['EMA_20'][-10:] < hist['EMA_50'][-10:]) and all(hist['EMA_50'][-10:] < hist['EMA_100'][-10:]) and all(hist['EMA_100'][-10:] < hist['SMA_150'][-10:]) and stoch['STOCHk_14_3_3'][-1] > 70:
51
- filtered_tickers.append([ticker, hist['Close'][-1], hist['Volume'][-1], 'Bearish', 'Head and Shoulders' if detect_head_and_shoulders(hist) else '', 'Inverted Head and Shoulders' if detect_inverted_head_and_shoulders(hist) else ''])
52
  except Exception as e:
53
  print(f"An error occurred with ticker {ticker}: {e}")
54
 
55
- df = pd.DataFrame(filtered_tickers, columns=['Ticker', 'Close', 'Volume', 'Trend', 'Head and Shoulders', 'Inverted Head and Shoulders'])
56
- output_xlsx = 'ema_stacks_list.xlsx'
57
- df.to_excel(output_xlsx, index=False)
58
- output_txt = 'pyScreener.txt'
59
- with open(output_txt, 'w') as f:
60
- for ticker in df['Ticker']:
 
 
 
 
 
 
 
 
 
 
61
  f.write(f"{ticker}\n")
62
- return output_xlsx, output_txt
 
63
 
64
  iface = gr.Interface(
65
  fn=process_csv,
66
- inputs=InputFile(label="Upload CSV"),
 
 
 
 
67
  outputs=[
68
- OutputFile(label="Download XLSX"),
69
- OutputFile(label="Download TXT")
 
 
70
  ],
71
- title="Stock Shortlist",
72
- description="Upload a CSV file with columns: Ticker | Description | Industry | Market Capitalization | Sector from TradingView and get shortlisted, stacked EMA trends in return."
73
  )
74
 
75
- iface.launch()
 
1
  import gradio as gr
2
+ from gradio.inputs import File as InputFile, Number as InputNumber
3
  from gradio.outputs import File as OutputFile
 
4
  import yfinance as yf
5
  import pandas as pd
6
  import pandas_ta as ta
7
  import csv
8
+ import os
9
 
10
+ def process_csv(csv_file, bullish_stoch_value, bearish_stoch_value):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  all_tickers = []
12
  with open(csv_file.name, 'r') as file:
13
  reader = csv.reader(file)
 
16
  all_tickers.append(row[0]) # Append the value in the first column
17
 
18
  ttl_tickers = len(all_tickers)
19
+ bullish_tickers = []
20
+ bearish_tickers = []
21
  for ticker in all_tickers:
22
+ print(f"Processing {ticker} ({all_tickers.index(ticker)+1}/{ttl_tickers})")
23
  try:
24
  data = yf.Ticker(ticker)
25
  hist = data.history(period="1y", actions=False)
 
29
  hist.ta.ema(close='Close', length=100, append=True)
30
  hist.ta.sma(close='Close', length=150, append=True)
31
  stoch = hist.ta.stoch(high='High', low='Low', close='Close')
32
+ if all(hist['EMA_20'][-10:] > hist['EMA_50'][-10:]) and all(hist['EMA_50'][-10:] > hist['EMA_100'][-10:]) and all(hist['EMA_100'][-10:] > hist['SMA_150'][-10:]) and all(stoch['STOCHk_14_3_3'][-3:] < bullish_stoch_value):
33
+ bullish_tickers.append([ticker, hist['Close'][-1], hist['Volume'][-1], 'Bullish'])
34
+ elif all(hist['EMA_20'][-10:] < hist['EMA_50'][-10:]) and all(hist['EMA_50'][-10:] < hist['EMA_100'][-10:]) and all(hist['EMA_100'][-10:] < hist['SMA_150'][-10:]) and all(stoch['STOCHk_14_3_3'][-3:] > bearish_stoch_value):
35
+ bearish_tickers.append([ticker, hist['Close'][-1], hist['Volume'][-1], 'Bearish'])
36
  except Exception as e:
37
  print(f"An error occurred with ticker {ticker}: {e}")
38
 
39
+ df_bullish = pd.DataFrame(bullish_tickers, columns=['Ticker', 'Close', 'Volume', 'Trend'])
40
+ df_bearish = pd.DataFrame(bearish_tickers, columns=['Ticker', 'Close', 'Volume', 'Trend'])
41
+
42
+ base_filename = os.path.splitext(os.path.basename(csv_file.name))[0]
43
+ output_bullish_xlsx = f'{base_filename}-bullish.xlsx'
44
+ output_bearish_xlsx = f'{base_filename}-bearish.xlsx'
45
+ df_bullish.to_excel(output_bullish_xlsx, index=False)
46
+ df_bearish.to_excel(output_bearish_xlsx, index=False)
47
+
48
+ output_bullish_txt = f'{base_filename}-bullish.txt'
49
+ output_bearish_txt = f'{base_filename}-bearish.txt'
50
+ with open(output_bullish_txt, 'w') as f:
51
+ for ticker in df_bullish['Ticker']:
52
+ f.write(f"{ticker}\n")
53
+ with open(output_bearish_txt, 'w') as f:
54
+ for ticker in df_bearish['Ticker']:
55
  f.write(f"{ticker}\n")
56
+
57
+ return output_bullish_xlsx, output_bearish_xlsx, output_bullish_txt, output_bearish_txt
58
 
59
  iface = gr.Interface(
60
  fn=process_csv,
61
+ inputs=[
62
+ InputFile(label="Upload CSV"),
63
+ InputNumber(label="Bullish Stochastic Value", default=30),
64
+ InputNumber(label="Bearish Stochastic Value", default=70)
65
+ ],
66
  outputs=[
67
+ OutputFile(label="Download Bullish XLSX"),
68
+ OutputFile(label="Download Bearish XLSX"),
69
+ OutputFile(label="Download Bullish TXT"),
70
+ OutputFile(label="Download Bearish TXT")
71
  ],
72
+ title="Stock Analysis",
73
+ description="Upload a CSV file and get XLSX and TXT files in return."
74
  )
75
 
76
+ iface.launch()