rajan-nse 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,162 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Rajan Bajaj
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.3
2
+ Name: rajan_nse
3
+ Version: 1.0.0
4
+ Summary: A python package
5
+ Project-URL: Homepage, https://github.com/rajanbajaj/rajan_nse
6
+ Project-URL: Issues, https://github.com/rajanbajaj/rajan_nse/issues
7
+ Author-email: Rajan Bajaj <rajanbajajkota@gmail.com>
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.8
13
+ Description-Content-Type: text/markdown
14
+
15
+ # rajan_nse
16
+ Python package for nse calculations
@@ -0,0 +1,2 @@
1
+ # rajan_nse
2
+ Python package for nse calculations
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "rajan_nse"
7
+ version = "1.0.0"
8
+ authors = [
9
+ { name="Rajan Bajaj", email="rajanbajajkota@gmail.com" },
10
+ ]
11
+ description = "A python package"
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+
20
+ [project.urls]
21
+ Homepage = "https://github.com/rajanbajaj/rajan_nse"
22
+ Issues = "https://github.com/rajanbajaj/rajan_nse/issues"
@@ -0,0 +1,126 @@
1
+ from rajan_nse.Session import Session
2
+ from rajan_nse.TechnicalIndicators import TechnicalIndicators
3
+ from rajan_nse.NseData import NseData
4
+
5
+ class CandleStickPatterns:
6
+ def __init__(self) -> None:
7
+ self.session = Session("https://www.nseindia.com")
8
+ self.technicalIndicators = TechnicalIndicators()
9
+ self.nseData = NseData()
10
+ pass
11
+
12
+ def dojiPattern(self, symbol, live=True):
13
+
14
+ if live:
15
+ current_data = self.nseData.getCurrentData(symbol)
16
+
17
+ day_open = current_data['priceInfo']['open']
18
+ day_close = current_data['priceInfo']['lastPrice']
19
+
20
+ # parity of 0.05 adjusted in day closing and lastPrice
21
+ condition1 = day_open / day_close >= 0.995
22
+ condition2 = day_open / day_close <= 1.005
23
+ else:
24
+ data = self.nseData.getHistoricalData(symbol)
25
+ day_open = data['data'][0]['CH_OPENING_PRICE']
26
+ day_close = data['data'][0]['CH_CLOSING_PRICE']
27
+ condition1 = day_open / day_close >= 0.9995
28
+ condition2 = day_open / day_close <= 1.0005
29
+
30
+ return (
31
+ condition1 and
32
+ condition2
33
+ )
34
+
35
+ def hammerPattern(self, symbol, live=True):
36
+ data = self.nseData.getHistoricalData(symbol)
37
+
38
+ if live:
39
+ current_data = self.nseData.getCurrentData(symbol)
40
+
41
+ day_high = current_data['priceInfo']['intraDayHighLow']['max']
42
+ day_low = current_data['priceInfo']['intraDayHighLow']['min']
43
+ day_open = current_data['priceInfo']['open']
44
+ day_close = current_data['priceInfo']['lastPrice']
45
+ prev_day_high = data['data'][0]['CH_TRADE_HIGH_PRICE']
46
+ else:
47
+ day_high = data['data'][0]['CH_TRADE_HIGH_PRICE']
48
+ day_low = data['data'][0]['CH_TRADE_LOW_PRICE']
49
+ day_open = data['data'][0]['CH_OPENING_PRICE']
50
+ day_close = data['data'][0]['CH_CLOSING_PRICE']
51
+ prev_day_high = data['data'][1]['CH_TRADE_HIGH_PRICE']
52
+
53
+ condition1 = day_high > day_low
54
+ condition2 = (day_open-day_close) <= (day_high-day_low) * 0.32
55
+ condition3 = day_open >= day_close
56
+ condition4 = (day_high - day_close) <= (day_high - day_low) * 0.4
57
+ condition5 = (day_close - day_open) <= (day_high-day_low) * 0.32
58
+ condition6 = day_open <= day_close
59
+ condition7 = (day_high - day_open) <= (day_high - day_low) * 0.4
60
+ condition8 = day_close > 10
61
+ condition9 = day_high <= prev_day_high
62
+ condition10 = day_close >= self.technicalIndicators.sma(symbol)
63
+ condition11 = self.technicalIndicators.rsi(symbol, 14) > 30
64
+
65
+ return (
66
+ condition1 and
67
+ (
68
+ (
69
+ condition2 and
70
+ condition3 and
71
+ condition4
72
+ ) or
73
+ (
74
+ condition5 and
75
+ condition6 and
76
+ condition7
77
+ )
78
+ ) and
79
+ condition8 and
80
+ condition9 and
81
+ condition10 and
82
+ condition11
83
+ )
84
+
85
+ def bullishEngullfingPattern(self, symbol, live=True):
86
+ data = self.nseData.getHistoricalData(symbol)
87
+
88
+ if live:
89
+ current_data = self.nseData.getCurrentData(symbol)
90
+
91
+ day_high = current_data['priceInfo']['intraDayHighLow']['max']
92
+ day_low = current_data['priceInfo']['intraDayHighLow']['min']
93
+ day_open = current_data['priceInfo']['open']
94
+ day_close = current_data['priceInfo']['lastPrice']
95
+ prev_day_high = data['data'][0]['CH_TRADE_HIGH_PRICE']
96
+ prev_day_low = data['data'][0]['CH_TRADE_LOW_PRICE']
97
+ prev_day_open = data['data'][0]['CH_OPENING_PRICE']
98
+ prev_day_close = data['data'][0]['CH_CLOSING_PRICE']
99
+ two_prev_day_close = data['data'][1]['CH_CLOSING_PRICE']
100
+ three_prev_day_close = data['data'][2]['CH_CLOSING_PRICE']
101
+ pass
102
+ else:
103
+ day_high = data['data'][0]['CH_TRADE_HIGH_PRICE']
104
+ day_low = data['data'][0]['CH_TRADE_LOW_PRICE']
105
+ day_open = data['data'][0]['CH_OPENING_PRICE']
106
+ day_close = data['data'][0]['CH_CLOSING_PRICE']
107
+ prev_day_high = data['data'][1]['CH_TRADE_HIGH_PRICE']
108
+ prev_day_low = data['data'][1]['CH_TRADE_LOW_PRICE']
109
+ prev_day_open = data['data'][1]['CH_OPENING_PRICE']
110
+ prev_day_close = data['data'][1]['CH_CLOSING_PRICE']
111
+ two_prev_day_close = data['data'][2]['CH_CLOSING_PRICE']
112
+ three_prev_day_close = data['data'][3]['CH_CLOSING_PRICE']
113
+
114
+ condition1 = prev_day_close < prev_day_open # prev day candel is red
115
+ condition2 = day_close > day_open # current day candle is green
116
+ condition3 = day_close >= prev_day_open and day_open <= prev_day_close # engulf
117
+ condition4 = two_prev_day_close > prev_day_close
118
+ condition5 = three_prev_day_close > two_prev_day_close
119
+
120
+ return (
121
+ condition1 and
122
+ condition2 and
123
+ condition3 and
124
+ condition4 and
125
+ condition5
126
+ )
@@ -0,0 +1,57 @@
1
+ from datetime import date, timedelta
2
+ from rajan_nse.Session import Session
3
+
4
+ class NseData:
5
+ def __init__(self) -> None:
6
+ self.session = Session("https://www.nseindia.com")
7
+ pass
8
+
9
+ def getCurrentData(self, symbol):
10
+ # https://www.nseindia.com/api/quote-equity?symbol=X
11
+ data = self.session.makeRequest(
12
+ url = "https://www.nseindia.com/api/quote-equity",
13
+ params = {
14
+ 'symbol': symbol,
15
+ }
16
+ )
17
+
18
+ # data = {"info":{"symbol":"X","companyName":"X Limited","industry":"COMPUTERS - SOFTWARE","activeSeries":["EQ"],"debtSeries":[],"isFNOSec":true,"isCASec":false,"isSLBSec":true,"isDebtSec":false,"isSuspended":false,"tempSuspendedSeries":[],"isETFSec":false,"isDelisted":false,"isin":"INE075A01022","isMunicipalBond":false,"isTop10":false,"identifier":"XEQN"},"metadata":{"series":"EQ","symbol":"X","isin":"INE075A01022","status":"Listed","listingDate":"08-Nov-1995","industry":"Computers - Software & Consulting","lastUpdateTime":"02-Jul-2024 15:24:00","pdSectorPe":24.77,"pdSymbolPe":24.77,"pdSectorInd":"NIFTY IT "},"securityInfo":{"boardStatus":"Main","tradingStatus":"Active","tradingSegment":"Normal Market","sessionNo":"-","slb":"Yes","classOfShare":"Equity","derivatives":"Yes","surveillance":{"surv":null,"desc":null},"faceValue":2,"issuedSize":5230164205},"sddDetails":{"SDDAuditor":"-","SDDStatus":"-"},"priceInfo":{"lastPrice":537.55,"change":10.199999999999932,"pChange":1.9341992983786729,"previousClose":527.35,"open":529.3,"close":0,"vwap":538.33,"lowerCP":"474.65","upperCP":"580.05","pPriceBand":"No Band","basePrice":527.35,"intraDayHighLow":{"min":528.3,"max":545,"value":537.55},"weekHighLow":{"min":375.05,"minDate":"26-Oct-2023","max":545.9,"maxDate":"19-Feb-2024","value":537.55},"iNavValue":null,"checkINAV":false},"industryInfo":{"macro":"Information Technology","sector":"Information Technology","industry":"IT - Software","basicIndustry":"Computers - Software & Consulting"},"preOpenMarket":{"preopen":[{"price":474.65,"buyQty":0,"sellQty":604},{"price":480,"buyQty":0,"sellQty":500},{"price":501,"buyQty":0,"sellQty":7161},{"price":503.6,"buyQty":0,"sellQty":10},{"price":529.3,"buyQty":0,"sellQty":0,"iep":true},{"price":551.05,"buyQty":306,"sellQty":0},{"price":551.1,"buyQty":8,"sellQty":0},{"price":580,"buyQty":20,"sellQty":0},{"price":580.05,"buyQty":205,"sellQty":0}],"ato":{"buy":24235,"sell":2858},"IEP":529.3,"totalTradedVolume":98656,"finalPrice":529.3,"finalQuantity":98656,"lastUpdateTime":"02-Jul-2024 09:08:03","totalBuyQuantity":79562,"totalSellQuantity":304045,"atoBuyQty":24235,"atoSellQty":2858,"Change":1.9499999999999318,"perChange":0.3697733952782652,"prevClose":527.35}}
19
+ return data
20
+
21
+ def getHistoricalData(self, symbol, delta = 200, to_date = date.today()):
22
+ # https://www.nseindia.com/api/historical/cm/equity?symbol=BAJFINANCE&series=["EQ"]&from=30-06-2024&to=01-07-2024
23
+ # get quote historical details
24
+
25
+ from_date = to_date - timedelta(days=delta)
26
+ to_date_formated = to_date.strftime("%d-%m-%Y")
27
+ from_date_formated = from_date.strftime("%d-%m-%Y")
28
+
29
+ data = self.session.makeRequest(
30
+ url = "https://www.nseindia.com/api/historical/cm/equity",
31
+ params = {
32
+ 'symbol': symbol,
33
+ # 'series': '\["EQ"\]',
34
+ 'from': from_date_formated,
35
+ 'to': to_date_formated,
36
+ }
37
+ )
38
+
39
+ #data['data'] = [{CH_TRADE_HIGH_PRICE, CH_TRADE_LOW_PRICE, CH_OPENING_PRICE, CH_CLOSING_PRICE, CH_TOT_TRADED_QTY}, {}, ...]
40
+ return data
41
+
42
+ def fiftyTwoWeekHighLow(self, symbol, live=True):
43
+ current_data = self.getCurrentData(symbol)
44
+ if live:
45
+ return {
46
+ 'high': current_data['priceInfo']['weekHighLow']['max'],
47
+ 'low': current_data['priceInfo']['weekHighLow']['min'],
48
+ 'price': current_data['priceInfo']['lastPrice']
49
+
50
+ }
51
+ else:
52
+ historical_data = self.getHistoricalData(symbol, 20)
53
+ return {
54
+ 'high': current_data['priceInfo']['weekHighLow']['max'],
55
+ 'low': current_data['priceInfo']['weekHighLow']['min'],
56
+ 'price': historical_data['data'][0]['CH_CLOSING_PRICE']
57
+ }
@@ -0,0 +1,30 @@
1
+ import requests
2
+
3
+ class Session:
4
+ headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, '
5
+ 'like Gecko) '
6
+ 'Chrome/80.0.3987.149 Safari/537.36',
7
+ 'accept-language': 'en,gu;q=0.9,hi;q=0.8', 'accept-encoding': 'gzip, deflate, br'}
8
+ cookies = {}
9
+
10
+ def __init__(self, base_url):
11
+ self.session = requests.Session()
12
+ self.base_url = base_url
13
+ self.createNewSession()
14
+
15
+ def createNewSession(self):
16
+ session = requests.Session()
17
+ request = self.makeRequest(self.base_url)
18
+
19
+ def makeRequest(self, url, params=None):
20
+ try:
21
+ if params == None:
22
+ r = self.session.get(url=url, headers=self.headers, cookies=self.cookies)
23
+ else:
24
+ r = self.session.get(url=url, headers=self.headers, cookies=self.cookies, params=params)
25
+
26
+ self.cookies = dict(r.cookies)
27
+ return r.json()
28
+ except Exception as e:
29
+ # print(e)
30
+ return
@@ -0,0 +1,43 @@
1
+ from datetime import date, timedelta
2
+ from pandas import DataFrame
3
+ from rajan_nse.Session import Session
4
+ from rajan_nse.helpers import *
5
+
6
+ class Strategies:
7
+ def __init__(self):
8
+ self.session = Session("https://www.nseindia.com")
9
+
10
+ """
11
+ This function returns the list of insder trading data withing given delta (days)
12
+ """
13
+ def insderTradingData(self, symbol, delta = 90):
14
+ df = getInsiderTradingDataWithSymbol(self.session, symbol, delta)
15
+ return df
16
+
17
+
18
+
19
+ """
20
+ This function will return the list of stocks which are
21
+ filtered by promoter buy back strategy with following
22
+ seven steps.
23
+ 1. Get the list of stocks which are intraday traded in last 90 days (3months)
24
+ 2. Filter out the stocks in which traded value is less than 1cr
25
+ 3. Filter out the stocks in which promoter holding is less than 50%
26
+ 4. Filter out the stocks based on sast data
27
+ 5/6/7. Individual stock analysis for promoter details
28
+ """
29
+ def promoterBuyBackStocks(self, delta = 90, to_date = date.today(), save_to_file = False):
30
+ from_date = to_date - timedelta(days=delta)
31
+ to_date_formated = to_date.strftime("%d-%m-%Y")
32
+ from_date_formated = from_date.replace(day=to_date.day).strftime("%d-%m-%Y")
33
+ data = filterBasedOnPromoterBuyBackStrategy(self.session, to_date_formated, from_date_formated)
34
+
35
+ # save data to file
36
+ try:
37
+ if save_to_file:
38
+ DataFrame.to_csv(DataFrame(data), 'final-'+ to_date_formated +'.csv')
39
+ except Exception as e:
40
+ # print(e)
41
+ return
42
+
43
+ return data
@@ -0,0 +1,100 @@
1
+ import numpy as np
2
+ from datetime import date, timedelta
3
+ from rajan_nse.NseData import NseData
4
+ from rajan_nse.Session import Session
5
+
6
+ class TechnicalIndicators:
7
+ def __init__(self) -> None:
8
+ self.session = Session("https://www.nseindia.com")
9
+ self.nseData = NseData()
10
+ pass
11
+
12
+ def sma(self, symbol=None, period=200, data=None):
13
+ if data is None:
14
+ data = self.nseData.getHistoricalData(symbol)['data']
15
+
16
+ try:
17
+ sum = 0
18
+ data_length = len(data)
19
+ if (period < data_length):
20
+ for i in range(0, period):
21
+ sum += data[i]['CH_CLOSING_PRICE']
22
+ return sum / period
23
+ else:
24
+ for tmp in data:
25
+ sum += tmp['CH_CLOSING_PRICE']
26
+ return sum / len(data)
27
+ except:
28
+ return -1
29
+
30
+ def rsi(self, symbol, period = 14):
31
+ data = self.nseData.getHistoricalData(symbol)['data']
32
+
33
+ assert len(data) >= 14, "Insufficient data: Need at least 14 rows"
34
+
35
+ prices = [day['CH_CLOSING_PRICE'] for day in data[:14]]
36
+
37
+ # Calculate price changes
38
+ price_changes = np.diff(prices)
39
+
40
+ # Separate gains and losses
41
+ gains = np.maximum(price_changes, 0)
42
+ losses = np.abs(np.minimum(price_changes, 0))
43
+
44
+ # # Calculate the average gains and losses
45
+ avg_gain = self.sma(data=gains, period=period)
46
+ avg_loss = self.sma(data=losses, period=period)
47
+
48
+ # # Calculate the Relative Strength (RS)
49
+ rs = avg_gain / avg_loss
50
+
51
+ # # Calculate the RSI
52
+ rsi = 100 - (100 / (1 + rs))
53
+
54
+ # # Adjust the length of RSI to match the input prices length
55
+ # # The first (period-1) RSI values are NaN since we don't have enough data points to calculate them
56
+ # rsi = np.concatenate((np.full(period-1, np.nan), rsi))
57
+
58
+ return rsi
59
+
60
+ """
61
+ Chaikin Money Flow (CMF) developed by Marc Chaikin is a volume-weighted
62
+ average of accumulation and distribution over a specified period. The standard
63
+ CMF period is 21 days. The principle behind the Chaikin Money Flow is the nearer
64
+ the closing price is to the high, the more accumulation has taken place.
65
+ Conversely, the nearer the closing price is to the low, the more distribution
66
+ has taken place. If the price action consistently closes above the bar's midpoint
67
+ on increasing volume, the Chaikin Money Flow will be positive. Conversely, if the
68
+ price action consistently closes below the bar's midpoint on increasing volume, the
69
+ Chaikin Money Flow will be a negative value.
70
+ Calculations:
71
+ CMF = n-day Sum of [(((C - L) - (H - C)) / (H - L)) x Vol] / n-day Sum of Vol
72
+ Where: n = number of periods, typically 21 H = high L = low C = close Vol = volume
73
+ """
74
+ def cmf(self, symbol, period = 21):
75
+ data = self.nseData.getHistoricalData(symbol)['data']
76
+
77
+ sum_a = 0
78
+ sum_b = 0
79
+ data_length = len(data)
80
+ if (period < data_length):
81
+ for i in range(0, period):
82
+ sum_a += (((data[i]['CH_CLOSING_PRICE'] - data[i]['CH_TRADE_LOW_PRICE'] ) - (data[i]['CH_TRADE_HIGH_PRICE'] - data[i]['CH_CLOSING_PRICE'] )) / (data[i]['CH_TRADE_HIGH_PRICE'] - data[i]['CH_TRADE_LOW_PRICE'] )) * data[i]['CH_TOT_TRADED_QTY']
83
+ sum_b += data[i]['CH_TOT_TRADED_QTY']
84
+ else:
85
+ for tmp in data:
86
+ sum_a += (((tmp['CH_CLOSING_PRICE'] - tmp['CH_TRADE_LOW_PRICE'] ) - (tmp['CH_TRADE_HIGH_PRICE'] - tmp['CH_CLOSING_PRICE'] )) / (tmp['CH_TRADE_HIGH_PRICE'] - tmp['CH_TRADE_LOW_PRICE'] )) * tmp['CH_TOT_TRADED_QTY']
87
+ sum_b += tmp['CH_TOT_TRADED_QTY']
88
+ return sum_a / sum_b
89
+
90
+ # delta is percentage range of price from 52 weeks high
91
+ def near52WeekHigh(self, symbol, live=False, delta=5):
92
+ # data = {high:, low:, price:}
93
+ data = self.nseData.fiftyTwoWeekHighLow(symbol, live)
94
+ return (abs(data['high'] - data['price']) / data['high']) * 100 <= delta
95
+
96
+ # delta is percentage range of price from 52 weeks low
97
+ def near52WeekLow(self, symbol, live=False, delta=5):
98
+ # data = {high:, low:, price:}
99
+ data = self.nseData.fiftyTwoWeekHighLow(symbol, live)
100
+ return (abs(data['low'] - data['price']) / data['low']) * 100 <= delta
File without changes
@@ -0,0 +1,178 @@
1
+ from datetime import date, timedelta
2
+ from pandas import DataFrame, to_numeric
3
+ from time import sleep
4
+ from tqdm import tqdm
5
+ from alive_progress import alive_bar
6
+ from rajan_nse.Session import Session
7
+
8
+ def isPromoterFilterPassed(session: Session, symbol):
9
+ try:
10
+ data = session.makeRequest(
11
+ url = "https://www.nseindia.com/api/corp-info",
12
+ params = {
13
+ 'market': 'equities',
14
+ 'corpType': 'promoterenc',
15
+ 'symbol': symbol
16
+ }
17
+ )
18
+ return float(data[0]['per1']) > 50 and float(data[0]['per2']) == 0 and float(data[0]['per3']) == 0.00
19
+ except:
20
+ print('promoter', symbol, data)
21
+
22
+ def isSastRegulationFilterPassed(session: Session, symbol):
23
+ try:
24
+ data = session.makeRequest(
25
+ url = "https://www.nseindia.com/api/corp-info",
26
+ params = {
27
+ 'market': 'equities',
28
+ 'corpType': 'sast',
29
+ 'symbol': symbol
30
+ }
31
+ )
32
+ sast_df = DataFrame(data)
33
+
34
+ if sast_df.empty:
35
+ return True
36
+
37
+ sast_df['noOfShareSale'] = to_numeric(sast_df['noOfShareSale'])
38
+ sast_df = sast_df['noOfShareSale'].replace('-', 0)
39
+ return sast_df.sum() == 0
40
+ except:
41
+ print('sast', symbol)
42
+
43
+ def findAvgPrice(session: Session, to_date_formated, from_date_formated, symbol):
44
+ try:
45
+ # https://www.nseindia.com/api/corporates-pit?index=equities&from_date=25-03-2024&to_date=25-06-2024&symbol=BAJFINANCE
46
+ data = session.makeRequest(
47
+ url = "https://www.nseindia.com/api/corporates-pit",
48
+ params = {
49
+ 'index': 'equities',
50
+ 'from_date': from_date_formated,
51
+ 'to_date': to_date_formated,
52
+ 'symbol': symbol
53
+ }
54
+ )
55
+
56
+ df = DataFrame(data["data"])
57
+ filter = (df['personCategory'] == 'Promoters') | (df['personCategory'] == 'Promoter Group')
58
+ df = df.where(filter)
59
+
60
+ filter = df['secType'] == 'Equity Shares'
61
+ df = df.where(filter)
62
+
63
+ avg_price = -1
64
+ if (df.where(df['tdpTransactionType'] == 'Sell').dropna().size == 0):
65
+ filter = df['tdpTransactionType'] == 'Buy'
66
+ df = df.where(filter)
67
+
68
+ df['secVal'] = to_numeric(df['secVal'])
69
+ df['secAcq'] = to_numeric(df['secAcq'])
70
+ value = df['secVal'].sum()
71
+ qty = df['secAcq'].sum()
72
+ if qty != 0:
73
+ avg_price = value / qty
74
+
75
+
76
+ return avg_price
77
+ except:
78
+ print('average', symbol)
79
+ return -1
80
+
81
+ def lastPrice(session: Session,symbol):
82
+ # https://www.nseindia.com/api/quote-equity?symbol=360ONE
83
+ # get quote details
84
+
85
+ data = session.makeRequest(
86
+ url = "https://www.nseindia.com/api/quote-equity",
87
+ params = {
88
+ 'symbol': symbol,
89
+ }
90
+ )
91
+ price_info = data['priceInfo']
92
+ industry_info = data['industryInfo']
93
+ pre_open_info = data['preOpenMarket']
94
+ last_price = price_info['lastPrice']
95
+
96
+ return last_price
97
+
98
+ def getInsiderTradingData(session: Session, to_date_formated, from_date_formated):
99
+ data = session.makeRequest(
100
+ url="https://www.nseindia.com/api/corporates-pit",
101
+ params= {
102
+ 'index': 'equities',
103
+ 'from_date': from_date_formated,
104
+ 'to_date': to_date_formated
105
+ }
106
+ )
107
+
108
+ df = DataFrame(data["data"])
109
+ return df
110
+
111
+ def getInsiderTradingDataWithSymbol(session: Session, symbol, delta = 90):
112
+ to_date = date.today()
113
+ from_date = to_date - timedelta(days=delta)
114
+ to_date_formated = to_date.strftime("%d-%m-%Y")
115
+ from_date_formated = from_date.strftime("%d-%m-%Y")
116
+
117
+ data = session.makeRequest(
118
+ url="https://www.nseindia.com/api/corporates-pit",
119
+ params= {
120
+ 'index': 'equities',
121
+ 'from_date': from_date_formated,
122
+ 'to_date': to_date_formated,
123
+ 'symbol': symbol
124
+ }
125
+ )
126
+
127
+ df = DataFrame(data["data"])
128
+ return df
129
+
130
+ def filterStocksBasedOnValueThreshold(session: Session, to_date_formated, from_date_formated, threshold=10000000):
131
+
132
+ df = getInsiderTradingData(session, to_date_formated=to_date_formated, from_date_formated=from_date_formated)
133
+ df = df[['symbol', 'secVal']]
134
+ df['symbol'] = df['symbol'].replace(' ', '')
135
+ df['secVal'] = df['secVal'].replace('-', 0)
136
+ df['secVal'] = to_numeric(df['secVal'])
137
+
138
+ df = df.groupby('symbol').sum()
139
+ df.sort_values('secVal', inplace=True)
140
+
141
+ filter = df["secVal"] > threshold
142
+ df.where(filter, inplace=True)
143
+
144
+ df.sort_values('secVal', inplace=True)
145
+ df = df.dropna()
146
+
147
+ filtered_stock_symbols = df['secVal'].keys()
148
+ df['secVal'].to_csv('stocks_' + to_date_formated + '.tmp.csv')
149
+ return filtered_stock_symbols
150
+
151
+ def filterStocksBasedOnPromoterAndSast(session: Session, to_date_formated, from_date_formated):
152
+ # pledge details
153
+ # https://www.nseindia.com/api/corp-info?symbol=360ONE&corpType=promoterenc&market=equities
154
+ #
155
+ # check sast regulation data
156
+ # https://www.nseindia.com/api/corp-info?symbol=360ONE&corpType=sast&market=equities
157
+ stocks = []
158
+ failed = []
159
+ filtered_stock_symbols = filterStocksBasedOnValueThreshold(session, to_date_formated, from_date_formated)
160
+ with alive_bar(filtered_stock_symbols.size, force_tty=True) as bar:
161
+ for symbol in filtered_stock_symbols:
162
+ if(isPromoterFilterPassed(session, symbol) and isSastRegulationFilterPassed(session, symbol)):
163
+ stocks.append(symbol)
164
+ bar()
165
+ return stocks
166
+
167
+ def filterBasedOnPromoterBuyBackStrategy(session: Session, to_date_formated, from_date_formated ,allowed_diff = 0.05):
168
+ final = []
169
+ stocks = filterStocksBasedOnPromoterAndSast(session, to_date_formated, from_date_formated)
170
+ with alive_bar(len(stocks), force_tty=True) as bar:
171
+ for symbol in stocks:
172
+ avg_price = findAvgPrice(session, to_date_formated, from_date_formated, symbol)
173
+ last_price = lastPrice(session, symbol)
174
+ diff = (last_price - avg_price) / abs(avg_price)
175
+ if avg_price != -1 and diff < allowed_diff:
176
+ final.append([symbol, avg_price, last_price])
177
+ bar()
178
+ return final
@@ -0,0 +1,40 @@
1
+ from rajan_nse.Strategies import Strategies
2
+ from rajan_nse.TechnicalIndicators import TechnicalIndicators
3
+ from rajan_nse.NseData import NseData
4
+ from pandas import DataFrame
5
+
6
+ # TODO add rajan.nse
7
+ from CandleStickPatterns import CandleStickPatterns
8
+
9
+ if __name__ == "__main__":
10
+ # strategies = Strategies()
11
+ # data = strategies.promoterBuyBackStocks(300)
12
+ # print(data)
13
+ # DataFrame.to_csv(DataFrame(data), 'final.csv')
14
+
15
+ # strategies = Strategies()
16
+ # data = strategies.insderTradingData("UDS", 200)
17
+ # if not data.empty:
18
+ # print(data[["date", "symbol", "secVal", "secAcq", "tdpTransactionType", "secType", "personCategory"]])
19
+
20
+ # candleStickPatterns = CandleStickPatterns()
21
+ # result = candleStickPatterns.hammerPattern('BRITANNIA')
22
+ # print(result)
23
+
24
+ # candleStickPatterns = CandleStickPatterns()
25
+ # result = candleStickPatterns.bullishEngullfingPattern('BIGBLOC')
26
+ # print(result)
27
+
28
+ # candleStickPatterns = CandleStickPatterns()
29
+ # result = candleStickPatterns.dojiPattern('ASIANPAINT', False)
30
+ # print(result)
31
+
32
+ technicalIndicators = TechnicalIndicators()
33
+
34
+ print(technicalIndicators.sma('RELIANCE'))
35
+ print(technicalIndicators.sma('RELIANCE', 14))
36
+ print(technicalIndicators.rsi('RELIANCE'))
37
+ print(technicalIndicators.cmf('RELIANCE'))
38
+ print(technicalIndicators.near52WeekHigh('RELIANCE'))
39
+ print(technicalIndicators.near52WeekLow('RELIANCE'))
40
+