├── Aboutus.html ├── Login.html ├── MACDsignal.py ├── OTP_5_forecast.ipynb ├── OTP_Forecasting.ipynb ├── OTP_Other_Indicators.ipynb ├── OTP_forecast_model_reload.py ├── OTP_forecast_model_train.py ├── OTP_prediction.ipynb ├── Option-Trading-Prediction-Model-main (2).zip ├── README.md ├── bbChart.py ├── bbSignal.py ├── flaskApp.py ├── index.html ├── index.js ├── livedata.py ├── model.h5 ├── model1.h5 ├── model1.json ├── model_5_28.h5 ├── model_5_28.json ├── prediction.ipynb ├── prediction.py └── pythoncsvtojson.py /Aboutus.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Document 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 9 | 11 | Login 12 | 13 | 14 | 15 | 16 |
17 |
18 |
19 |
20 |
21 |
22 | 24 | 25 | 27 | 28 |
29 | 31 | 33 |
34 | 35 | Already have an account ? 36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | 45 | 46 | 49 | 50 | 53 | -------------------------------------------------------------------------------- /MACDsignal.py: -------------------------------------------------------------------------------- 1 | #Data Source 2 | !pip install yfinance 3 | import yfinance as yf 4 | 5 | #Data viz 6 | import plotly.graph_objs as go 7 | import plotly as pt 8 | !pip install pandas_ta 9 | import pandas_ta as ta 10 | import matplotlib.pyplot as plt 11 | from datetime import date 12 | import numpy as np 13 | import pandas as pd 14 | import pandas_datareader.data as webd 15 | 16 | 17 | data = yf.download(tickers='^NSEI', period='1d', interval='1m') 18 | macd = ta.macd(data['Close']) 19 | 20 | ## Now that we've got the MACD columns, we'll merge them with our main dataframe. 21 | data = pd.concat([data, macd], axis=1).reindex(data.index) 22 | 23 | def MACD_Strategy(df, risk): 24 | MACD_Buy=[] 25 | MACD_Sell=[] 26 | position=False 27 | 28 | for i in range(0, len(df)): 29 | if df['MACD_12_26_9'][i] > df['MACDs_12_26_9'][i] : 30 | MACD_Sell.append(np.nan) 31 | if position ==False: 32 | MACD_Buy.append(df['Close'][i]) 33 | position=True 34 | else: 35 | MACD_Buy.append(np.nan) 36 | elif df['MACD_12_26_9'][i] < df['MACDs_12_26_9'][i] : 37 | MACD_Buy.append(np.nan) 38 | if position == True: 39 | MACD_Sell.append(df['Close'][i]) 40 | position=False 41 | else: 42 | MACD_Sell.append(np.nan) 43 | elif position == True and df['Close'][i] < MACD_Buy[-1] * (1 - risk): 44 | MACD_Sell.append(df["Close"][i]) 45 | MACD_Buy.append(np.nan) 46 | position = False 47 | elif position == True and df['Close'][i] < df['Close'][i - 1] * (1 - risk): 48 | MACD_Sell.append(df["Close"][i]) 49 | MACD_Buy.append(np.nan) 50 | position = False 51 | else: 52 | MACD_Buy.append(np.nan) 53 | MACD_Sell.append(np.nan) 54 | 55 | data['MACD_Buy_Signal_price'] = MACD_Buy 56 | data['MACD_Sell_Signal_price'] = MACD_Sell 57 | 58 | ## Included a Risk factor in our strategy. If the current price goes beyond the acceptable limits 59 | ## or if the current price goes beyond the specified percentage, we'll sell. 60 | ##In simple terms, we've added a STOP LOSS and a Trailing Stop loss to our strategy. 61 | MACD_strategy = MACD_Strategy(data, 0.025) 62 | 63 | def MACD_color(data): 64 | MACD_color = [] 65 | for i in range(0, len(data)): 66 | if data['MACDh_12_26_9'][i] > data['MACDh_12_26_9'][i - 1]: 67 | MACD_color.append(True) 68 | else: 69 | MACD_color.append(False) 70 | return MACD_color 71 | 72 | data['positive'] = MACD_color(data) 73 | 74 | ## plot 75 | plt.rcParams.update({'font.size': 10}) 76 | fig, ax1 = plt.subplots(figsize=(14,8)) 77 | fig.suptitle('NIFTY50', fontsize=10, backgroundcolor='blue', color='white') 78 | ax1 = plt.subplot2grid((14, 8), (0, 0), rowspan=8, colspan=14) 79 | ax1.set_ylabel('Price in ₨') 80 | ax1.plot('Close',data=data, label='Close Price', linewidth=0.5, color='blue') 81 | ax1.scatter(data.index, data['MACD_Buy_Signal_price'], color='green', marker='^', alpha=1) 82 | ax1.scatter(data.index, data['MACD_Sell_Signal_price'], color='red', marker='v', alpha=1) 83 | ax1.legend() 84 | ax1.grid() 85 | ax1.set_xlabel('Date', fontsize=8) 86 | 87 | 88 | -------------------------------------------------------------------------------- /OTP_forecast_model_reload.py: -------------------------------------------------------------------------------- 1 | # import libraries 2 | import pandas as pd 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | from sklearn.preprocessing import MinMaxScaler 6 | !pip install yfinance 7 | import yfinance as yf 8 | from datetime import date 9 | from pandas_datareader import data as pdr 10 | yf.pdr_override() 11 | 12 | # deep learning libraries 13 | import keras 14 | from keras.models import Sequential 15 | from keras.layers import LSTM 16 | from keras.layers import Dropout 17 | from keras.models import Sequential 18 | from keras.layers import Dense 19 | from keras.models import model_from_json 20 | import numpy 21 | import os 22 | 23 | 24 | # fetch data for training 25 | def SaveData(df, filename): 26 | df.to_csv(filename + '.csv') 27 | today = date.today() 28 | dataname='^NSEI'+'_'+str(today) 29 | data=pdr.get_data_yahoo('^NSEI', start='2015-01-01', end=today) 30 | SaveData(data, dataname) 31 | data= pd.read_csv(dataname+'.csv') 32 | 33 | # drop not required column 34 | data.drop(columns=['Adj Close'], inplace=True) 35 | data['Date'] = pd.to_datetime(data['Date']) 36 | 37 | # 80% will be used for traning, and 20% for testing 38 | train_size = 0.8 # 80% 39 | split_index = int(train_size * data.shape[0]) 40 | 41 | factors_column = ['Open', 'High', 'Low', 'Close', 'Volume'] 42 | y_col_index = 3 # Close 43 | 44 | train_set = data[factors_column].values[:split_index] 45 | test_set = data[factors_column].values[split_index:] 46 | 47 | # scale our price from 0 to 1 48 | sc = MinMaxScaler(feature_range = (0, 1)) 49 | train_set_scaled = sc.fit_transform(train_set) 50 | test_set_scaled = sc.fit_transform(test_set) 51 | 52 | # Predicting Closing Price 53 | # Generate windowed timestamp data 54 | # this function will combine data of 20 days (we can change it using time_window parameter) 55 | time_window = 28 # 60 days 56 | days_step =1 # skip 1 days in between, can be set to 1 day 57 | 58 | # later... 59 | 60 | # load json and create model 61 | json_file = open('model_5_28.json', 'r') 62 | loaded_model_json = json_file.read() 63 | json_file.close() 64 | loaded_model = model_from_json(loaded_model_json) 65 | # load weights into new model 66 | loaded_model.load_weights("model_5_28.h5") 67 | print("Loaded model from disk") 68 | 69 | 70 | ## future forecasting 71 | def predict_n_days(df, n=30, step=0.1): 72 | for i in range(n): 73 | X = df[factors_column].values[df.shape[0] - time_window::step] 74 | X = sc.transform(X) 75 | y = loaded_model.predict(np.expand_dims(X, axis=0)) 76 | y = sc.inverse_transform(y)[0] 77 | 78 | next_day_prediction = {key: value for key, value in zip(factors_column, y)} 79 | next_day_prediction['Date'] = df.iloc[-1].Date + pd.Timedelta(days=1) 80 | 81 | df = df.append(next_day_prediction, ignore_index=True) 82 | return df 83 | 84 | 85 | days = 5 86 | # days_step =0.1 87 | predicted_df = predict_n_days(data, days, days_step) 88 | 89 | # evaluate loaded model on test data 90 | #loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) 91 | #score = loaded_model.evaluate(X_train,y_train, verbose=0) 92 | #print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1] * 100)) 93 | 94 | fig = plt.figure(figsize=(25, 7)) 95 | # plt.plot(data.Date, data.Close, 'r-', label = 'Option Close') 96 | plt.plot(predicted_df.Date.values[-days:], predicted_df.Close[-days:], 'b--', label='Future Prediction') 97 | 98 | plt.title('NIFTY50 Prediction') 99 | plt.xlabel('Date') 100 | plt.ylabel('NIFTY50') 101 | plt.legend() 102 | plt.show() -------------------------------------------------------------------------------- /OTP_forecast_model_train.py: -------------------------------------------------------------------------------- 1 | # import libraries 2 | import pandas as pd 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | from sklearn.preprocessing import MinMaxScaler 6 | !pip 7 | install 8 | yfinance 9 | import yfinance as yf 10 | from datetime import date 11 | from pandas_datareader import data as pdr 12 | 13 | yf.pdr_override() 14 | 15 | # deep learning libraries 16 | import keras 17 | from keras.models import Sequential 18 | from keras.layers import LSTM 19 | from keras.layers import Dropout 20 | 21 | 22 | # fetch data for training 23 | def SaveData(df, filename): 24 | df.to_csv(filename + '.csv') 25 | 26 | 27 | today = date.today() 28 | dataname = '^NSEI' + '_' + str(today) 29 | data = pdr.get_data_yahoo('^NSEI', start='2015-01-01', end=today) 30 | SaveData(data, dataname) 31 | data = pd.read_csv(dataname + '.csv') 32 | 33 | # drop not required column 34 | data.drop(columns=['Adj Close'], inplace=True) 35 | data['Date'] = pd.to_datetime(data['Date']) 36 | 37 | # 80% will be used for traning, and 20% for testing 38 | train_size = 0.8 # 80% 39 | split_index = int(train_size * data.shape[0]) 40 | 41 | factors_column = ['Open', 'High', 'Low', 'Close', 'Volume'] 42 | y_col_index = 3 # Close 43 | 44 | train_set = data[factors_column].values[:split_index] 45 | test_set = data[factors_column].values[split_index:] 46 | 47 | # scale our price from 0 to 1 48 | sc = MinMaxScaler(feature_range=(0, 1)) 49 | train_set_scaled = sc.fit_transform(train_set) 50 | test_set_scaled = sc.fit_transform(test_set) 51 | 52 | # Predicting Closing Price 53 | # Generate windowed timestamp data 54 | # this function will combine data of 20 days (we can change it using time_window parameter) 55 | time_window = 28 # 28 days 56 | days_step = 1 # skip 1 days in between, can be set to 1 day 57 | 58 | 59 | def generate_data(series, time_window=4, days_step=1): 60 | X = [] 61 | y = [] 62 | for i in range(28, len(series)): 63 | X.append(series[i - time_window: i: days_step]) 64 | y.append( 65 | series[i]) # <---- only changed this, insetead of taking only closing price, every column value is used 66 | return (np.array(X), np.array(y)) 67 | 68 | 69 | X_train, y_train = generate_data(train_set_scaled, time_window, days_step) 70 | X_test, y_test = generate_data(test_set_scaled, time_window, days_step) 71 | 72 | model = Sequential() 73 | 74 | # layer 1 75 | model.add(LSTM(units=64, return_sequences=True, input_shape=X_train.shape[1:])) 76 | model.add(Dropout(0.2)) 77 | 78 | # layer 2 79 | model.add(LSTM(units=32, return_sequences=True)) 80 | model.add(Dropout(0.2)) 81 | 82 | # layer 3 83 | model.add(LSTM(units=16, return_sequences=True)) 84 | model.add(Dropout(0.2)) 85 | 86 | # layer 4 87 | model.add(LSTM(units=8, return_sequences=True)) 88 | model.add(Dropout(0.2)) 89 | 90 | # layer 4 91 | model.add(LSTM(units=5)) 92 | 93 | # Compile and train LSTM Network 94 | model.compile(optimizer='adam', loss='mean_squared_error') 95 | history = model.fit(X_train, 96 | y_train, 97 | epochs=1000, 98 | batch_size=64, 99 | validation_data=(X_test, y_test)) 100 | 101 | 102 | ## future forecasting 103 | def predict_n_days(df, n=30, step=0.1): 104 | for i in range(n): 105 | X = df[factors_column].values[df.shape[0] - time_window::step] 106 | X = sc.transform(X) 107 | y = model.predict(np.expand_dims(X, axis=0)) 108 | y = sc.inverse_transform(y)[0] 109 | 110 | next_day_prediction = {key: value for key, value in zip(factors_column, y)} 111 | next_day_prediction['Date'] = df.iloc[-1].Date + pd.Timedelta(days=1) 112 | 113 | df = df.append(next_day_prediction, ignore_index=True) 114 | return df 115 | 116 | 117 | days = 5 118 | # days_step =0.1 119 | predicted_df = predict_n_days(data, days, days_step) 120 | 121 | fig = plt.figure(figsize=(25, 7)) 122 | # plt.plot(data.Date, data.Close, 'r-', label = 'Option Close') 123 | plt.plot(predicted_df.Date.values[-days:], predicted_df.Close[-days:], 'b--', label='Future Prediction') 124 | 125 | plt.title('Nifty50 Forecasting') 126 | plt.xlabel('Date') 127 | plt.ylabel('Nifty50') 128 | plt.legend() 129 | plt.show() 130 | 131 | # MLP for OTP model Serialize to JSON and HDF5 132 | from keras.models import Sequential 133 | from keras.layers import Dense 134 | from keras.models import model_from_json 135 | import numpy 136 | import os 137 | 138 | # serialize model to JSON 139 | model_json = model.to_json() 140 | with open("model_5_28.json", "w") as json_file: 141 | json_file.write(model_json) 142 | # serialize weights to HDF5 143 | model.save_weights("model_5_28.h5") 144 | print("Saved model to disk") 145 | 146 | -------------------------------------------------------------------------------- /Option-Trading-Prediction-Model-main (2).zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kurveakshay/Options-Trading-using-Artificial-Neural-Network-and-Algorithmic-Trading/d513cb05705ef49064ec318a036feea560350991/Option-Trading-Prediction-Model-main (2).zip -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Sem-6-Project -------------------------------------------------------------------------------- /bbChart.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | 4 | #Data Source 5 | !pip install yfinance 6 | import yfinance as yf 7 | 8 | #Data viz 9 | import plotly.graph_objs as go 10 | import plotly as pt 11 | data = yf.download(tickers='^NSEI', period='1d', interval='1m') 12 | #Interval required 1 minute 13 | data['Middle Band'] = data['Close'].rolling(window=21).mean() 14 | data['Upper Band'] = data['Middle Band'] + 1.96*data['Close'].rolling(window=21).std() 15 | data['Lower Band'] = data['Middle Band'] - 1.96*data['Close'].rolling(window=21).std() 16 | 17 | #declare figure 18 | fig = go.Figure() 19 | 20 | fig.add_trace(go.Scatter(x=data.index, y= data['Middle Band'],line=dict(color='blue', width=.7), name = 'Middle Band')) 21 | fig.add_trace(go.Scatter(x=data.index, y= data['Upper Band'],line=dict(color='red', width=1.5), name = 'Upper Band (Put)')) 22 | fig.add_trace(go.Scatter(x=data.index, y= data['Lower Band'],line=dict(color='green', width=1.5), name = 'Lower Band (Call)')) 23 | 24 | 25 | #Candlestick 26 | fig.add_trace(go.Candlestick(x=data.index, 27 | open=data['Open'], 28 | high=data['High'], 29 | low=data['Low'], 30 | close=data['Close'], name = 'market data')) 31 | 32 | # Add titles 33 | fig.update_layout( 34 | title='NSEI live price put_call prediction', 35 | yaxis_title='NIFTY50') 36 | 37 | # X-Axes 38 | fig.update_xaxes( 39 | rangeslider_visible=True, 40 | rangeselector=dict( 41 | buttons=list([ 42 | dict(count=1, label="1m", step="minute", stepmode="backward"), 43 | dict(count=5, label="5m", step="minute", stepmode="backward"), 44 | dict(count=15, label="15m", step="minute", stepmode="backward"), 45 | dict(count=45, label="45m", step="minute", stepmode="backward"), 46 | dict(count=1, label="HTD", step="hour", stepmode="todate"), 47 | dict(count=3, label="3h", step="hour", stepmode="backward"), 48 | dict(step="all") 49 | ]) 50 | ) 51 | ) 52 | 53 | 54 | #Show 55 | fig.show() 56 | pt.offline.plot(fig,filename='bbplot.html') -------------------------------------------------------------------------------- /bbSignal.py: -------------------------------------------------------------------------------- 1 | #Data Source 2 | !pip install yfinance 3 | import yfinance as yf 4 | 5 | #Data viz 6 | import plotly.graph_objs as go 7 | import plotly as pt 8 | !pip install pandas_ta 9 | import pandas_ta as ta 10 | import matplotlib.pyplot as plt 11 | from datetime import date 12 | import numpy as np 13 | import pandas as pd 14 | import pandas_datareader.data as webd 15 | 16 | plt.style.use('fivethirtyeight') 17 | yf.pdr_override() 18 | data = yf.download(tickers='^NSEI', period='1d', interval='1m') 19 | def bb_strategy(data): 20 | bbBuy = [] 21 | bbSell = [] 22 | position = False 23 | bb = ta.bbands(data['Close'], length=20,std=2) 24 | data = pd.concat([data, bb], axis=1).reindex(data.index) 25 | 26 | for i in range(len(data)): 27 | if data['Close'][i] < data['BBL_20_2.0'][i]: 28 | if position == False : 29 | bbBuy.append(data['Adj Close'][i]) 30 | bbSell.append(np.nan) 31 | position = True 32 | else: 33 | bbBuy.append(np.nan) 34 | bbSell.append(np.nan) 35 | elif data['Close'][i] > data['BBU_20_2.0'][i]: 36 | if position == True: 37 | bbBuy.append(np.nan) 38 | bbSell.append(data['Close'][i]) 39 | position = False #To indicate that I actually went there 40 | else: 41 | bbBuy.append(np.nan) 42 | bbSell.append(np.nan) 43 | else : 44 | bbBuy.append(np.nan) 45 | bbSell.append(np.nan) 46 | 47 | data['bb_Buy_Signal_price'] = bbBuy 48 | data['bb_Sell_Signal_price'] = bbSell 49 | 50 | return data 51 | 52 | data = bb_strategy(data) 53 | 54 | #plot 55 | fig, ax1 = plt.subplots(figsize=(14,8)) 56 | fig.suptitle('NIFTY 50', fontsize=10, backgroundcolor='blue', color='white') 57 | ax1 = plt.subplot2grid((14, 8), (0, 0), rowspan=8, colspan=14) 58 | ax1.set_ylabel('Price in ₨') 59 | ax1.plot(data['Adj Close'],label='Close Price', linewidth=0.5, color='blue') 60 | ax1.scatter(data.index, data['bb_Buy_Signal_price'], color='green', marker='^', alpha=1) 61 | ax1.scatter(data.index, data['bb_Sell_Signal_price'], color='red', marker='v', alpha=1) 62 | ax1.legend() 63 | ax1.grid() 64 | ax1.set_xlabel('Date', fontsize=8) 65 | plt.show() 66 | #pt.offline.plot(fig,filename='bbindicator.html') 67 | -------------------------------------------------------------------------------- /flaskApp.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, render_template 2 | app = Flask(__name__) 3 | 4 | 5 | @app.route('/') 6 | @app.route("/home") 7 | def home(): 8 | return render_template("table.html") 9 | 10 | 11 | @app.route("/graph") 12 | def graph(): 13 | return render_template("positives.html") 14 | 15 | 16 | if __name__ == '__main__': 17 | app.run(debug=True, port=8080) 18 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Option Predictor 8 | 9 | 10 |
11 |
12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | const chart = LightweightCharts.createChart(document.body, { 2 | width: 400, 3 | height: 300, 4 | }); 5 | const lineSeries = chart.addLineSeries(); 6 | lineSeries.setData([ 7 | { 'time': "2019-04-11", 'value': 80.01 }, 8 | { 'time': "2019-04-12", 'value': 96.63 }, 9 | { 'time': "2019-04-13", 'value': 76.64 }, 10 | { 'time': "2019-04-14", 'value': 81.89 }, 11 | ]); 12 | 13 | 14 | 15 | 16 | function makeDate(){ 17 | object = {}; 18 | object['time'] = "2019-04-11"; 19 | object['value'] = "80.0"; 20 | return object; 21 | } 22 | 23 | lineSeries.addLineSeries(makeDate()); 24 | -------------------------------------------------------------------------------- /livedata.py: -------------------------------------------------------------------------------- 1 | import time 2 | import requests 3 | import threading 4 | from bs4 import BeautifulSoup 5 | 6 | symbol = "%5ENSEI" 7 | def set_url(symbol): 8 | return f'https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?region=US&lang=en-US&includePrePost=false&interval=5m&useYfid=true&range=1d&corsDomain=finance.yahoo.com&.tsrc=finance' 9 | url = set_url(symbol) 10 | print(url) 11 | headers = { 12 | 'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Mobile Safari/537.36'} 13 | 14 | 15 | def get_data(): 16 | r = requests.get(url, headers=headers) 17 | objects = r.text 18 | file_path = r'C:\Users\sidhu\Desktop\Final Project\Sem-6-Project-main\demofile3.js' 19 | with open(file_path, 'w') as output_file: 20 | print('''objects = {0} 21 | console.log(objects['chart']['result'][0]['meta']['regularMarketPrice']) 22 | console.log(objects['chart']['result'][0]['meta']['chartPreviousClose']) 23 | console.log(objects['chart']['result'][0]['meta']['previousClose']) 24 | console.log(objects['chart']['result'][0]['meta']['regularMarketTime']) 25 | '''.format(objects), file=output_file) 26 | 27 | 28 | 29 | 30 | def printit(): 31 | threading.Timer(1.0, printit).start() 32 | get_data() 33 | 34 | printit() 35 | 36 | 37 | 38 | # f = open("demofile3.txt", "w+") 39 | # print(objects,file = demofile3.js) 40 | # f.close() 41 | -------------------------------------------------------------------------------- /model.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kurveakshay/Options-Trading-using-Artificial-Neural-Network-and-Algorithmic-Trading/d513cb05705ef49064ec318a036feea560350991/model.h5 -------------------------------------------------------------------------------- /model1.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kurveakshay/Options-Trading-using-Artificial-Neural-Network-and-Algorithmic-Trading/d513cb05705ef49064ec318a036feea560350991/model1.h5 -------------------------------------------------------------------------------- /model1.json: -------------------------------------------------------------------------------- 1 | {"class_name": "Sequential", "config": {"name": "sequential", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": [null, 7, 5], "dtype": "float32", "sparse": false, "ragged": false, "name": "lstm_input"}}, {"class_name": "LSTM", "config": {"name": "lstm", "trainable": true, "batch_input_shape": [null, 7, 5], "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 50, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "unit_forget_bias": true, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2}}, {"class_name": "Dropout", "config": {"name": "dropout", "trainable": true, "dtype": "float32", "rate": 0.2, "noise_shape": null, "seed": null}}, {"class_name": "LSTM", "config": {"name": "lstm_1", "trainable": true, "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 30, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "unit_forget_bias": true, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2}}, {"class_name": "Dropout", "config": {"name": "dropout_1", "trainable": true, "dtype": "float32", "rate": 0.2, "noise_shape": null, "seed": null}}, {"class_name": "LSTM", "config": {"name": "lstm_2", "trainable": true, "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 10, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "unit_forget_bias": true, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2}}, {"class_name": "Dropout", "config": {"name": "dropout_2", "trainable": true, "dtype": "float32", "rate": 0.2, "noise_shape": null, "seed": null}}, {"class_name": "LSTM", "config": {"name": "lstm_3", "trainable": true, "dtype": "float32", "return_sequences": false, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 1, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "unit_forget_bias": true, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2}}]}, "keras_version": "2.8.0", "backend": "tensorflow"} -------------------------------------------------------------------------------- /model_5_28.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kurveakshay/Options-Trading-using-Artificial-Neural-Network-and-Algorithmic-Trading/d513cb05705ef49064ec318a036feea560350991/model_5_28.h5 -------------------------------------------------------------------------------- /model_5_28.json: -------------------------------------------------------------------------------- 1 | {"class_name": "Sequential", "config": {"name": "sequential", "layers": [{"class_name": "InputLayer", "config": {"batch_input_shape": [null, 28, 5], "dtype": "float32", "sparse": false, "ragged": false, "name": "lstm_input"}}, {"class_name": "LSTM", "config": {"name": "lstm", "trainable": true, "batch_input_shape": [null, 28, 5], "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 64, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "unit_forget_bias": true, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2}}, {"class_name": "Dropout", "config": {"name": "dropout", "trainable": true, "dtype": "float32", "rate": 0.2, "noise_shape": null, "seed": null}}, {"class_name": "LSTM", "config": {"name": "lstm_1", "trainable": true, "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 32, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "unit_forget_bias": true, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2}}, {"class_name": "Dropout", "config": {"name": "dropout_1", "trainable": true, "dtype": "float32", "rate": 0.2, "noise_shape": null, "seed": null}}, {"class_name": "LSTM", "config": {"name": "lstm_2", "trainable": true, "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 16, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "unit_forget_bias": true, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2}}, {"class_name": "Dropout", "config": {"name": "dropout_2", "trainable": true, "dtype": "float32", "rate": 0.2, "noise_shape": null, "seed": null}}, {"class_name": "LSTM", "config": {"name": "lstm_3", "trainable": true, "dtype": "float32", "return_sequences": true, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 8, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "unit_forget_bias": true, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2}}, {"class_name": "Dropout", "config": {"name": "dropout_3", "trainable": true, "dtype": "float32", "rate": 0.2, "noise_shape": null, "seed": null}}, {"class_name": "LSTM", "config": {"name": "lstm_4", "trainable": true, "dtype": "float32", "return_sequences": false, "return_state": false, "go_backwards": false, "stateful": false, "unroll": false, "time_major": false, "units": 5, "activation": "tanh", "recurrent_activation": "sigmoid", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "recurrent_initializer": {"class_name": "Orthogonal", "config": {"gain": 1.0, "seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "unit_forget_bias": true, "kernel_regularizer": null, "recurrent_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "recurrent_constraint": null, "bias_constraint": null, "dropout": 0.0, "recurrent_dropout": 0.0, "implementation": 2}}]}, "keras_version": "2.8.0", "backend": "tensorflow"} -------------------------------------------------------------------------------- /prediction.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": { 7 | "colab": { 8 | "base_uri": "https://localhost:8080/", 9 | "height": 1000 10 | }, 11 | "id": "E74RoHruk8Uz", 12 | "outputId": "751f11f5-7a17-4db1-a87c-75e127facebe" 13 | }, 14 | "outputs": [ 15 | { 16 | "name": "stderr", 17 | "output_type": "stream", 18 | "text": [ 19 | "ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n", 20 | "instabot-py 0.7.18 requires requests==2.22.0, but you have requests 2.27.1 which is incompatible.\n", 21 | "fyers-apiv2 2.0.5 requires requests==2.25.1, but you have requests 2.27.1 which is incompatible.\n", 22 | "WARNING: You are using pip version 21.3.1; however, version 22.0.4 is available.\n", 23 | "You should consider upgrading via the 'c:\\python\\python39\\python.exe -m pip install --upgrade pip' command.\n" 24 | ] 25 | }, 26 | { 27 | "name": "stdout", 28 | "output_type": "stream", 29 | "text": [ 30 | "Collecting yfinance\n", 31 | " Downloading yfinance-0.1.70-py2.py3-none-any.whl (26 kB)\n", 32 | "Collecting requests>=2.26\n", 33 | " Downloading requests-2.27.1-py2.py3-none-any.whl (63 kB)\n", 34 | "Requirement already satisfied: numpy>=1.15 in c:\\python\\python39\\lib\\site-packages (from yfinance) (1.21.1)\n", 35 | "Collecting lxml>=4.5.1\n", 36 | " Downloading lxml-4.8.0-cp39-cp39-win_amd64.whl (3.6 MB)\n", 37 | "Collecting multitasking>=0.0.7\n", 38 | " Downloading multitasking-0.0.10.tar.gz (8.2 kB)\n", 39 | " Preparing metadata (setup.py): started\n", 40 | " Preparing metadata (setup.py): finished with status 'done'\n", 41 | "Requirement already satisfied: pandas>=0.24.0 in c:\\python\\python39\\lib\\site-packages (from yfinance) (1.3.3)\n", 42 | "Requirement already satisfied: python-dateutil>=2.7.3 in c:\\python\\python39\\lib\\site-packages (from pandas>=0.24.0->yfinance) (2.8.2)\n", 43 | "Requirement already satisfied: pytz>=2017.3 in c:\\python\\python39\\lib\\site-packages (from pandas>=0.24.0->yfinance) (2021.1)\n", 44 | "Requirement already satisfied: urllib3<1.27,>=1.21.1 in c:\\python\\python39\\lib\\site-packages (from requests>=2.26->yfinance) (1.25.11)\n", 45 | "Requirement already satisfied: certifi>=2017.4.17 in c:\\python\\python39\\lib\\site-packages (from requests>=2.26->yfinance) (2021.5.30)\n", 46 | "Requirement already satisfied: idna<4,>=2.5 in c:\\python\\python39\\lib\\site-packages (from requests>=2.26->yfinance) (2.8)\n", 47 | "Requirement already satisfied: charset-normalizer~=2.0.0 in c:\\python\\python39\\lib\\site-packages (from requests>=2.26->yfinance) (2.0.6)\n", 48 | "Requirement already satisfied: six>=1.5 in c:\\python\\python39\\lib\\site-packages (from python-dateutil>=2.7.3->pandas>=0.24.0->yfinance) (1.16.0)\n", 49 | "Using legacy 'setup.py install' for multitasking, since package 'wheel' is not installed.\n", 50 | "Installing collected packages: requests, multitasking, lxml, yfinance\n", 51 | " Attempting uninstall: requests\n", 52 | " Found existing installation: requests 2.25.1\n", 53 | " Uninstalling requests-2.25.1:\n", 54 | " Successfully uninstalled requests-2.25.1\n", 55 | " Running setup.py install for multitasking: started\n", 56 | " Running setup.py install for multitasking: finished with status 'done'\n", 57 | "Successfully installed lxml-4.8.0 multitasking-0.0.10 requests-2.27.1 yfinance-0.1.70\n" 58 | ] 59 | }, 60 | { 61 | "ename": "ModuleNotFoundError", 62 | "evalue": "No module named 'plotly'", 63 | "output_type": "error", 64 | "traceback": [ 65 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 66 | "\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", 67 | "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_28844/1395772255.py\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[1;31m#Data viz\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 9\u001b[1;33m \u001b[1;32mimport\u001b[0m \u001b[0mplotly\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mgraph_objs\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mgo\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 10\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 11\u001b[0m \u001b[0mdata\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0myf\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdownload\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtickers\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'^NSEI'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mperiod\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'1d'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0minterval\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'1m'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", 68 | "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'plotly'" 69 | ] 70 | } 71 | ], 72 | "source": [ 73 | "import numpy as np\n", 74 | "import pandas as pd\n", 75 | "\n", 76 | "#Data Source\n", 77 | "!pip install yfinance\n", 78 | "import yfinance as yf\n", 79 | "\n", 80 | "#Data viz\n", 81 | "import plotly.graph_objs as go\n", 82 | "\n", 83 | "data = yf.download(tickers='^NSEI', period='1d', interval='1m')\n", 84 | "#Interval required 1 minute\n", 85 | "data['Middle Band'] = data['Close'].rolling(window=21).mean()\n", 86 | "data['Upper Band'] = data['Middle Band'] + 1.96*data['Close'].rolling(window=21).std()\n", 87 | "data['Lower Band'] = data['Middle Band'] - 1.96*data['Close'].rolling(window=21).std()\n", 88 | "\n", 89 | "#declare figure\n", 90 | "fig = go.Figure()\n", 91 | "\n", 92 | "fig.add_trace(go.Scatter(x=data.index, y= data['Middle Band'],line=dict(color='blue', width=.7), name = 'Middle Band'))\n", 93 | "fig.add_trace(go.Scatter(x=data.index, y= data['Upper Band'],line=dict(color='red', width=1.5), name = 'Upper Band (Sell)'))\n", 94 | "fig.add_trace(go.Scatter(x=data.index, y= data['Lower Band'],line=dict(color='green', width=1.5), name = 'Lower Band (Buy)'))\n", 95 | "\n", 96 | "\n", 97 | "#Candlestick\n", 98 | "fig.add_trace(go.Candlestick(x=data.index,\n", 99 | " open=data['Open'],\n", 100 | " high=data['High'],\n", 101 | " low=data['Low'],\n", 102 | " close=data['Close'], name = 'market data'))\n", 103 | "\n", 104 | "# Add titles\n", 105 | "fig.update_layout(\n", 106 | " title='NSEI live price buy_sell prediction',\n", 107 | " yaxis_title='NIFTY50')\n", 108 | "\n", 109 | "# X-Axes\n", 110 | "fig.update_xaxes(\n", 111 | " rangeslider_visible=True,\n", 112 | " rangeselector=dict(\n", 113 | " buttons=list([\n", 114 | " dict(count=15, label=\"15m\", step=\"minute\", stepmode=\"backward\"),\n", 115 | " dict(count=45, label=\"45m\", step=\"minute\", stepmode=\"backward\"),\n", 116 | " dict(count=1, label=\"HTD\", step=\"hour\", stepmode=\"todate\"),\n", 117 | " dict(count=3, label=\"3h\", step=\"hour\", stepmode=\"backward\"),\n", 118 | " dict(step=\"all\")\n", 119 | " ])\n", 120 | " )\n", 121 | ")\n", 122 | "\n", 123 | "#Show\n", 124 | "fig.show()" 125 | ] 126 | }, 127 | { 128 | "cell_type": "code", 129 | "execution_count": 3, 130 | "metadata": { 131 | "colab": { 132 | "base_uri": "https://localhost:8080/", 133 | "height": 441 134 | }, 135 | "id": "FO8rnO9-lMlz", 136 | "outputId": "1b625878-4e3f-4f41-cbfe-cd7c508c2271" 137 | }, 138 | "outputs": [ 139 | { 140 | "name": "stdout", 141 | "output_type": "stream", 142 | "text": [ 143 | "\r[*********************100%***********************] 1 of 1 completed\n" 144 | ] 145 | }, 146 | { 147 | "data": { 148 | "text/html": [ 149 | "\n", 150 | "
\n", 151 | "
\n", 152 | "
\n", 153 | "\n", 166 | "\n", 167 | " \n", 168 | " \n", 169 | " \n", 170 | " \n", 171 | " \n", 172 | " \n", 173 | " \n", 174 | " \n", 175 | " \n", 176 | " \n", 177 | " \n", 178 | " \n", 179 | " \n", 180 | " \n", 181 | " \n", 182 | " \n", 183 | " \n", 184 | " \n", 185 | " \n", 186 | " \n", 187 | " \n", 188 | " \n", 189 | " \n", 190 | " \n", 191 | " \n", 192 | " \n", 193 | " \n", 194 | " \n", 195 | " \n", 196 | " \n", 197 | " \n", 198 | " \n", 199 | " \n", 200 | " \n", 201 | " \n", 202 | " \n", 203 | " \n", 204 | " \n", 205 | " \n", 206 | " \n", 207 | " \n", 208 | " \n", 209 | " \n", 210 | " \n", 211 | " \n", 212 | " \n", 213 | " \n", 214 | " \n", 215 | " \n", 216 | " \n", 217 | " \n", 218 | " \n", 219 | " \n", 220 | " \n", 221 | " \n", 222 | " \n", 223 | " \n", 224 | " \n", 225 | " \n", 226 | " \n", 227 | " \n", 228 | " \n", 229 | " \n", 230 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | " \n", 244 | " \n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " \n", 249 | " \n", 250 | " \n", 251 | " \n", 252 | " \n", 253 | " \n", 254 | " \n", 255 | " \n", 256 | " \n", 257 | " \n", 258 | " \n", 259 | " \n", 260 | " \n", 261 | " \n", 262 | " \n", 263 | " \n", 264 | " \n", 265 | " \n", 266 | " \n", 267 | " \n", 268 | " \n", 269 | " \n", 270 | " \n", 271 | " \n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | " \n", 276 | " \n", 277 | " \n", 278 | " \n", 279 | "
DatetimeOpenHighLowCloseVolume
02021-12-30 09:15:00+05:3017201.44921917216.30078117148.80078117208.7500000
12021-12-30 09:30:00+05:3017208.69921917221.25000017201.00000017218.2500000
22021-12-30 09:45:00+05:3017220.30078117237.34960917213.65039117230.3007810
32021-12-30 10:00:00+05:3017230.15039117248.25000017225.84960917247.9003910
42021-12-30 10:15:00+05:3017247.59960917264.00000017243.19921917257.6992190
.....................
14912022-03-28 13:15:00+05:3017216.65039117225.40039117179.30078117200.4003910
14922022-03-28 13:30:00+05:3017200.09960917200.09960917136.15039117151.0000000
14932022-03-28 13:45:00+05:3017150.69921917182.55078117150.09960917175.8496090
14942022-03-28 14:00:00+05:3017175.84960917193.55078117165.59960917166.4003910
14952022-03-28 14:10:21+05:3017165.30078117165.30078117165.30078117165.3007810
\n", 280 | "

1496 rows × 6 columns

\n", 281 | "
\n", 282 | " \n", 292 | " \n", 293 | " \n", 330 | "\n", 331 | " \n", 355 | "
\n", 356 | "
\n", 357 | " " 358 | ], 359 | "text/plain": [ 360 | " Datetime Open High Low \\\n", 361 | "0 2021-12-30 09:15:00+05:30 17201.449219 17216.300781 17148.800781 \n", 362 | "1 2021-12-30 09:30:00+05:30 17208.699219 17221.250000 17201.000000 \n", 363 | "2 2021-12-30 09:45:00+05:30 17220.300781 17237.349609 17213.650391 \n", 364 | "3 2021-12-30 10:00:00+05:30 17230.150391 17248.250000 17225.849609 \n", 365 | "4 2021-12-30 10:15:00+05:30 17247.599609 17264.000000 17243.199219 \n", 366 | "... ... ... ... ... \n", 367 | "1491 2022-03-28 13:15:00+05:30 17216.650391 17225.400391 17179.300781 \n", 368 | "1492 2022-03-28 13:30:00+05:30 17200.099609 17200.099609 17136.150391 \n", 369 | "1493 2022-03-28 13:45:00+05:30 17150.699219 17182.550781 17150.099609 \n", 370 | "1494 2022-03-28 14:00:00+05:30 17175.849609 17193.550781 17165.599609 \n", 371 | "1495 2022-03-28 14:10:21+05:30 17165.300781 17165.300781 17165.300781 \n", 372 | "\n", 373 | " Close Volume \n", 374 | "0 17208.750000 0 \n", 375 | "1 17218.250000 0 \n", 376 | "2 17230.300781 0 \n", 377 | "3 17247.900391 0 \n", 378 | "4 17257.699219 0 \n", 379 | "... ... ... \n", 380 | "1491 17200.400391 0 \n", 381 | "1492 17151.000000 0 \n", 382 | "1493 17175.849609 0 \n", 383 | "1494 17166.400391 0 \n", 384 | "1495 17165.300781 0 \n", 385 | "\n", 386 | "[1496 rows x 6 columns]" 387 | ] 388 | }, 389 | "execution_count": 3, 390 | "metadata": {}, 391 | "output_type": "execute_result" 392 | } 393 | ], 394 | "source": [ 395 | "from datetime import date\n", 396 | "from pandas_datareader import data as pdr\n", 397 | "yf.pdr_override()\n", 398 | "data = yf.download( # or pdr.get_data_yahoo(...\n", 399 | " # tickers list or string as well\n", 400 | " tickers = '^NSEI',\n", 401 | "\n", 402 | " # use \"period\" instead of start/end\n", 403 | " # valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max\n", 404 | " # (optional, default is '1mo')\n", 405 | " period = \"60d\",\n", 406 | "\n", 407 | " # fetch data by interval (including intraday if period < 60 days)\n", 408 | " # valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo\n", 409 | " # (optional, default is '1d')\n", 410 | " interval = \"15m\",\n", 411 | "\n", 412 | " # group by ticker (to access via data['SPY'])\n", 413 | " # (optional, default is 'column')\n", 414 | "\n", 415 | " # adjust all OHLC automatically\n", 416 | " # (optional, default is False)\n", 417 | " auto_adjust = True,\n", 418 | "\n", 419 | " # download pre/post regular market hours data\n", 420 | " # (optional, default is False)\n", 421 | " prepost = True\n", 422 | " )\n", 423 | "data\n", 424 | "def SaveData(df, filename):\n", 425 | " df.to_csv(filename + '.csv')\n", 426 | "today = date.today()\n", 427 | "dataname='^NSEI'+'_'+str(today)\n", 428 | "SaveData(data, dataname)\n", 429 | "data= pd.read_csv(dataname+'.csv')\n", 430 | "data" 431 | ] 432 | } 433 | ], 434 | "metadata": { 435 | "colab": { 436 | "name": "prediction.ipynb", 437 | "provenance": [] 438 | }, 439 | "kernelspec": { 440 | "display_name": "Python 3", 441 | "name": "python3" 442 | }, 443 | "language_info": { 444 | "codemirror_mode": { 445 | "name": "ipython", 446 | "version": 3 447 | }, 448 | "file_extension": ".py", 449 | "mimetype": "text/x-python", 450 | "name": "python", 451 | "nbconvert_exporter": "python", 452 | "pygments_lexer": "ipython3", 453 | "version": "3.9.6" 454 | } 455 | }, 456 | "nbformat": 4, 457 | "nbformat_minor": 0 458 | } 459 | -------------------------------------------------------------------------------- /prediction.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """prediction.ipynb 3 | 4 | Automatically generated by Colaboratory. 5 | 6 | Original file is located at 7 | https://colab.research.google.com/drive/18qJw_0S7uqq4tgmomj55HNo9Pu45-D2D 8 | """ 9 | 10 | import time 11 | 12 | 13 | while(True): 14 | import numpy as np 15 | import pandas as pd 16 | 17 | # Data Source 18 | import yfinance as yf 19 | 20 | # Data viz 21 | import plotly.offline 22 | import plotly.graph_objs as go 23 | 24 | data = yf.download(tickers='^NSEI', period='1d', interval='1m') 25 | # Interval required 1 minute 26 | data['Middle Band'] = data['Close'].rolling(window=21).mean() 27 | data['Upper Band'] = data['Middle Band'] + \ 28 | 1.96*data['Close'].rolling(window=21).std() 29 | data['Lower Band'] = data['Middle Band'] - \ 30 | 1.96*data['Close'].rolling(window=21).std() 31 | 32 | # declare figure 33 | fig = go.Figure() 34 | 35 | fig.add_trace(go.Scatter(x=data.index, y=data['Middle Band'], line=dict( 36 | color='blue', width=.7), name='Middle Band')) 37 | fig.add_trace(go.Scatter(x=data.index, y=data['Upper Band'], line=dict( 38 | color='red', width=1.5), name='Upper Band (Sell)')) 39 | fig.add_trace(go.Scatter(x=data.index, y=data['Lower Band'], line=dict( 40 | color='green', width=1.5), name='Lower Band (Buy)')) 41 | 42 | 43 | # Candlestick 44 | fig.add_trace(go.Candlestick(x=data.index, 45 | open=data['Open'], 46 | high=data['High'], 47 | low=data['Low'], 48 | close=data['Close'], name='market data')) 49 | 50 | # Add titles 51 | fig.update_layout( 52 | title='NSEI live price buy_sell prediction', 53 | yaxis_title='NIFTY50') 54 | 55 | # X-Axes 56 | fig.update_xaxes( 57 | rangeslider_visible=True, 58 | rangeselector=dict( 59 | buttons=list([ 60 | dict(count=15, label="15m", step="minute", stepmode="backward"), 61 | dict(count=45, label="45m", step="minute", stepmode="backward"), 62 | dict(count=1, label="HTD", step="hour", stepmode="todate"), 63 | dict(count=3, label="3h", step="hour", stepmode="backward"), 64 | dict(step="all") 65 | ]) 66 | ) 67 | ) 68 | 69 | # Show 70 | fig.show() 71 | plotly.offline.plot(fig, filename=r'C:\Users\sidhu\Desktop\Final Project\Sem-6-Project\templates\positives.html') 72 | 73 | time.sleep(300) 74 | -------------------------------------------------------------------------------- /pythoncsvtojson.py: -------------------------------------------------------------------------------- 1 | import excel2json 2 | 3 | excel2json.convert_from_file('.xlsx') 4 | --------------------------------------------------------------------------------