jarvisx17 commited on
Commit
44dd150
·
1 Parent(s): 1d0d294

Update pycatchs/stls.py

Browse files
Files changed (1) hide show
  1. pycatchs/stls.py +94 -0
pycatchs/stls.py CHANGED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yfinance as yf
2
+ import pandas as pd
3
+ from datetime import datetime, timedelta
4
+ from pymongo import MongoClient
5
+ import pytz
6
+ import os
7
+
8
+ mongo_url = os.environ['MongoURL']
9
+ df_logo = pd.read_csv('https://raw.githubusercontent.com/jarvisx17/nifty500/main/Nifty500.csv')
10
+ df_logo = df_logo[['Symbol', "logo"]]
11
+ tz = pytz.timezone('Asia/Kolkata')
12
+ def UpdatedCollectionName():
13
+ current_time = datetime.now(tz)
14
+ collection_name = current_time.strftime('%Y-%m-%d')
15
+ if current_time.time() >= datetime.strptime('15:30', '%H:%M').time():
16
+ collection_name = (current_time + timedelta(days=1)).strftime('%Y-%m-%d')
17
+ return collection_name
18
+ else:
19
+ return collection_name
20
+
21
+ def get_rsi(close, lookback=14):
22
+ ret = close.diff()
23
+ up = []
24
+ down = []
25
+ for i in range(len(ret)):
26
+ if ret.iloc[i] < 0:
27
+ up.append(0)
28
+ down.append(ret.iloc[i])
29
+ else:
30
+ up.append(ret.iloc[i])
31
+ down.append(0)
32
+ up_series = pd.Series(up, index=close.index)
33
+ down_series = pd.Series(down, index=close.index).abs()
34
+ up_ewm = up_series.ewm(com=lookback - 1, adjust=False).mean()
35
+ down_ewm = down_series.ewm(com=lookback - 1, adjust=False).mean()
36
+ rs = up_ewm / down_ewm
37
+ rsi = 100 - (100 / (1 + rs))
38
+ rsi_df = pd.DataFrame(rsi, columns=['RSI'])
39
+ return rsi_df
40
+
41
+ def Stocks():
42
+ # end_date = datetime.today()
43
+ utc_now = datetime.utcnow()
44
+ indian_timezone = pytz.timezone('Asia/Kolkata')
45
+ indian_now = utc_now.replace(tzinfo=pytz.utc).astimezone(indian_timezone)
46
+ end_date = utc_now
47
+ end_date = end_date.replace(tzinfo=pytz.utc).astimezone(indian_timezone)
48
+ end_date = end_date.replace(tzinfo=pytz.utc).astimezone(indian_timezone)
49
+
50
+ start_date = end_date - timedelta(days=365)
51
+ nifty500_symbols = []
52
+ nifty500 = pd.read_csv('https://archives.nseindia.com/content/indices/ind_nifty500list.csv')
53
+ for symbol in nifty500.Symbol:
54
+ symbol = f'{symbol}.NS'
55
+ nifty500_symbols.append(symbol)
56
+
57
+ nifty500_data = pd.DataFrame()
58
+ print("Downloading data...")
59
+ for symbol in nifty500_symbols:
60
+ try:
61
+ stock_data = yf.download(symbol, start=start_date, end=end_date, progress=False)
62
+ stock_data['Symbol'] = symbol
63
+ nifty500_data = pd.concat([nifty500_data, stock_data], axis=0)
64
+ except Exception as e:
65
+ print(f"Error fetching data for {symbol}: {e}")
66
+
67
+ nifty500_data.reset_index(inplace=True)
68
+ nifty500_data['RSI'] = nifty500_data.groupby('Symbol')['Close'].apply(lambda x: get_rsi(x, lookback=14))
69
+ nifty500_data['SMA20'] = nifty500_data.groupby('Symbol')['Close'].transform(lambda x: x.rolling(window=20).mean())
70
+ nifty500_data['PercentageChange'] = nifty500_data.groupby('Symbol')['Close'].pct_change() * 100
71
+ nifty500_data_last_2_rows = nifty500_data.groupby('Symbol').tail(2)
72
+ nifty500_data_last_2_rows.reset_index(drop=True, inplace=True)
73
+ nifty500_data_last_2_rows['Prev_RSI'] = nifty500_data_last_2_rows.groupby('Symbol')['RSI'].shift(1)
74
+
75
+ filtered_data_by_stock = []
76
+ for symbol, group in nifty500_data_last_2_rows.groupby('Symbol'):
77
+ filtered_stock_data = group[(group['RSI'] >= 60) & (group['Prev_RSI'] < 60)]
78
+ if not filtered_stock_data.empty:
79
+ filtered_data_by_stock.append(filtered_stock_data)
80
+
81
+ filtered_data = pd.concat(filtered_data_by_stock)
82
+ filtered_data.reset_index(drop=True, inplace=True)
83
+ filtered_data[['Open', 'High','Low', 'Close', 'RSI', 'Prev_RSI','SMA20', 'PercentageChange']] = filtered_data[['Open', 'High','Low', 'Close', 'RSI', 'Prev_RSI', 'SMA20', 'PercentageChange']].round(2)
84
+ filtered_data = filtered_data.sort_values(by='PercentageChange', ascending=False)
85
+ filtered_data.reset_index(drop=True, inplace=True)
86
+ filtered_data = pd.merge(filtered_data, df_logo, on='Symbol', how='inner')
87
+ filtered_data = filtered_data[['Symbol', 'Date', 'Open', 'High', 'Low', 'Close', 'RSI', 'Prev_RSI','PercentageChange', "logo"]]
88
+ client = MongoClient(mongo_url)
89
+ db = client['mydatabase']
90
+ collection_name = UpdatedCollectionName()
91
+ collection = db[collection_name]
92
+ data_dict = filtered_data.to_dict(orient='records')
93
+ collection.insert_many(data_dict)
94
+ return filtered_data.to_dict(orient="records")