How to create a free stock screener in python
FREE STOCK SCREENER in PYTHON
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
import sqlite3
import math
import threading
import time
import datetime
from datetime import date
from datetime import timedelta
from fyers_api import fyersModel
from fyers_api import accessToken
root = Tk()
style= ttk.Style()
style.theme_use('winnative')
#style.configure("TCombobox", fieldbackground= "black", background= "white")
#style.configure("TListbox", fieldbackground= "black", background= "yellow")
count=0
indicator=[]
condition=[]
value=[]
andOr=[]
stockEl=[]
stopThread=False
def clearWidgets():
global count
for widgets in midFrame.winfo_children():
widgets.destroy()
indicator.clear()
condition.clear()
value.clear()
andOr.clear()
count=0
count=(len(StockstoScan['values']))
i=0
while(i<count):
StockstoScan['values']={}
i+=1
def startThread():
t1=threading.Thread(target=startScan)
t1.start()
def stopScan():
global stopThread
stopThread=True
def session_pop():
global top
top=Toplevel(root)
global sessionVar
sessionVar=Entry(top)
sessionVar.grid(row=0,column=0)
Button(top,text="SUBMIT",command=connect_fyers).grid(row=0,column=1)
def connect_fyers():
global fyers
session=accessToken.SessionModel(client_id="XXXXX",
secret_key="YYYYY",redirect_uri="https://trade.fyers.in/",
response_type="code", grant_type="authorization_code",
state="abcdefg",scope="",nonce="")
response = session.generate_authcode()
#https://api.fyers.in/api/v2/generate-authcode?client_id=XXXXXX&redirect_uri=https://fyers.in&response_type=code&state=sample_state&nonce=sample_nonce
auth_code=sessionVar.get()
top.destroy()
session.set_token(auth_code)
response = session.generate_token()
access_token = response["access_token"]
fyers = fyersModel.FyersModel(client_id="XXXXXX", token=access_token,log_path="E:\python")
profile=fyers.get_profile()
print(profile["data"]["name"])
def create_scan():
global count
e1=Entry(midFrame)
e1.grid(row=count,column=0)
indicator.append(e1)
e2=Entry(midFrame)
e2.grid(row=count,column=1)
condition.append(e2)
e3=Entry(midFrame)
e3.grid(row=count,column=2)
value.append(e3)
#Button(midFrame,text="ADD ANOTHER",width=17).grid(row=count,column=3)
combo=ttk.Combobox(midFrame,
values=["0",
"OR",
"AND",
],width=17)
combo.grid(row=count,column=3)
andOr.append(combo)
count+=1
def startScan():
global stopThread
temp=Stocks
if(len(StockstoScan['values'])>1):
temp=StockstoScan
count=(len(temp['values']))
print(count)
scannedLists=[]
while(True):
start=1
lBox.delete(0,"end")
scanLimit=int(w1.get())
while(start<count):
print(temp['values'][start])
i=0
global hisData
data = {"symbol":"NSE:"+temp['values'][start]+"-EQ","resolution":timeFrame.get(),"date_format":"1","range_from":str(date.today()-timedelta(days = 99)),"range_to":str(date.today()),"cont_flag":"1"}
hisData=((fyers.history(data)))
result=True
while(i<len(indicator)):
if(i!=0):
if(andOr[i-1].get()=="AND"):
result=result and cond_check(i)
elif(andOr[i-1].get()=="OR"):
result=result or cond_check(i)
else:
result=result and cond_check(i)
i+=1
if(result==True):
lBox.insert(i,temp['values'][start])
scanLimit-=1
if(scanLimit==0):
break
start+=1
if(stopThread==True):
break
statusVar.set(str(start)+" Stocks Scanned")
if((stopThread==True)or(repeatScan.get()=="REPEAT")):
stopThread=False
break
else:
time.sleep(int(repeatScan.get()))
def checkValue(arr,name):
for row in arr:
if(row==name):
return True
return False
def cond_check(number):
if(condition[number].get()=="<"):
if(eval(indicator[number].get())<eval(value[number].get())):
return True
else:
return False
elif(condition[number].get()==">"):
if(eval(indicator[number].get())>eval(value[number].get())):
return True
else:
return False
elif(condition[number].get()=="="):
if(eval(indicator[number].get())==eval(value[number].get())):
return True
else:
return False
def checkEval():
print(eval("close(0)"))
def close(loc):
return(hisData["candles"][len(hisData["candles"])-1+loc][4])
def high(loc):
return(hisData["candles"][len(hisData["candles"])-1+loc][2])
def low(loc):
return(hisData["candles"][len(hisData["candles"])-1+loc][3])
def openn(loc):
return(hisData["candles"][len(hisData["candles"])-1+loc][1])
def vol(loc):
return(hisData["candles"][len(hisData["candles"])-1+loc][5])
def sma(number):
sum=0
period=number
while(number>0):
sum+=close(-(number-1))
number-=1
return(sum/period)
def ema(number):
period=number*2
emaVal=0
while(number<(period)):
emaVal+=close(-(number))
number+=1
emaVal=(emaVal/(period/2))
period=period/2
number=int(period)
k=2/(period+1)
while(number>0):
emaVal=k*((close(-(number-1)))-emaVal)+emaVal
number-=1
return(emaVal)
def rsi():
length=len(hisData["candles"])
i=1
turns=length
avgGain=0
avgLoss=0
while(i<15):
if((hisData["candles"][i][4])>(hisData["candles"][i-1][4])):
avgGain+=(hisData["candles"][i][4])-(hisData["candles"][i-1][4])
elif((hisData["candles"][i][4])<(hisData["candles"][i-1][4])):
avgLoss+=(hisData["candles"][i-1][4])-(hisData["candles"][i][4])
i+=1
avgGain=avgGain/14
avgLoss=avgLoss/14
rsiVal=100-(100/(1+(avgGain/avgLoss)))
print(rsiVal)
i=15
while(i<length):
if((hisData["candles"][i][4])>(hisData["candles"][i-1][4])):
avgGain=((avgGain*13)+(hisData["candles"][i][4])-(hisData["candles"][i-1][4]))/14
elif((hisData["candles"][i][4])<(hisData["candles"][i-1][4])):
avgLoss=((avgLoss*13)+(hisData["candles"][i-1][4])-(hisData["candles"][i][4]))/14
i+=1
rsiVal=100-(100/(1+(avgGain/avgLoss)))
return rsiVal
def boU():
movAvg=sma(20)
i=0
length=len(hisData["candles"])
sum=0
while(i<20):
sum+=(close(-i)-movAvg)**2
i+=1
sum=sum/19
sum=math.sqrt(sum)
sum=movAvg+sum*2
return(sum)
def boD():
movAvg=sma(20)
i=0
length=len(hisData["candles"])
sum=0
while(i<20):
sum+=(close(-i)-movAvg)**2
i+=1
sum=sum/19
sum=math.sqrt(sum)
sum=movAvg-sum*2
return(sum)
def boM():
return sma(20)
def listStocks(event):
count=(len(Stocks['values']))
i=0
while(i<count):
Stocks['values']={}
i+=1
#conn=sqlite3.connect("fyers.db")
#cursor=conn.execute("select * from stocks where indexName='"+event.widget.get()+"'")
f = open("E:/python/"+event.widget.get()+".txt")
fList=f.read()
finList=fList.split(",")
for row in finList:
Stocks['values']+=(row,)
Stocks.current(1)
print(Stocks['values'][1])
def addStocks():
StockstoScan['values']+=(Stocks.get(),)
StockstoScan.current(1)
def maxHigh(num,start):
maxValue=high(start)
i=1
while(i<num):
if(high(start-i)>maxValue):
maxValue=high(start-i)
i+=1
return maxValue
def maxLow(num,start):
maxValue=low(start)
i=1
while(i<num):
if(low(start-i)>maxValue):
maxValue=low(start-i)
i+=1
return maxValue
def maxopenn(num,start):
maxValue=openn(start)
i=1
while(i<num):
if(openn(start-i)>maxValue):
maxValue=openn(start-i)
i+=1
return maxValue
def maxClose(num,start):
maxValue=close(start)
i=1
while(i<num):
if(close(start-i)>maxValue):
maxValue=close(start-i)
i+=1
return maxValue
def minHigh(num,start):
minValue=high(start)
i=1
while(i<num):
if(high(start-i)<minValue):
minValue=high(start-i)
i+=1
return minValue
def minLow(num,start):
minValue=low(start)
i=1
while(i<num):
if(low(start-i)<minValue):
minValue=low(start-i)
i+=1
return minValue
def minopenn(num,start):
minValue=openn(start)
i=1
while(i<num):
if(openn(start-i)<minValue):
minValue=openn(start-i)
i+=1
return minValue
def minClose(num,start):
minValue=close(start)
i=1
while(i<num):
if(close(start-i)<minValue):
minValue=close(start-i)
i+=1
return minValue
def maxVol(num,start):
maxValue=vol(start)
i=1
while(i<num):
if(vol(start-i)>maxValue):
maxValue=vol(start-i)
i+=1
return maxValue
def saveScan():
conn=sqlite3.connect("fyers.db")
i=0
default=""
while(i<len(indicator)):
default=andOr[i].get()
if(andOr[i].get()==""):
default="0"
query="insert into scanner(name,query1,query2,query3,query4)values('"+scanName.get()+"','"+indicator[i].get()+"','"+condition[i].get()+"','"+value[i].get()+"','"+default+"')"
conn.execute(query)
i+=1
conn.commit()
conn.close()
def viewScan():
conn=sqlite3.connect("fyers.db")
query="select distinct name from scanner"
cursor=conn.execute(query)
count=(len(savedScan['values']))
i=0
while(i<count):
savedScan['values']={}
i+=1
for row in cursor:
savedScan['values']+=(row,)
conn.close()
def viewSaved(event):
global count
clearWidgets()
conn=sqlite3.connect("fyers.db")
query="select * from scanner where name='"+savedScan.get()+"' order by query4 desc"
cursor=conn.execute(query)
for row in cursor:
create_scan()
print(count)
indicator[count-2].insert(0,row[1])
condition[count-2].insert(0,row[2])
value[count-2].insert(0,row[3])
andOr[count-2].set(row[4])
conn.close()
def deleteScan():
conn=sqlite3.connect("fyers.db")
i=0
query="delete from scanner where name='"+savedScan.get()+"'"
conn.execute(query)
conn.commit()
conn.close()
viewScan()
clearWidgets()
def placeOrder(stockName):
leverageValue=int(leverage.get())
quantityValue=float(amount.get())
productType="INTRADAY"
lossValue=0
typeValue=2
data = {"symbols":"NSE:"+stockName+"-EQ"}
lp=fyers.quotes(data)["d"][0]["v"]["lp"]
quantityValue=int(quantityValue*leverageValue/lp)
if(orderType.get()==1):
lossValue=(float(lossLimit.get())/quantityValue)
triggerPrice=int(lossValue*100)
triggerPrice=triggerPrice-triggerPrice%5
lossValue=triggerPrice/100
if(orderSide.get()==1):
lossValue=lp-lossValue
elif(orderSide.get()==-1):
lossValue=lp+lossValue
triggerPrice=int(lossValue*100)-int(lossValue*100)%5
lossValue=triggerPrice/100
productType="CO"
elif(orderType.get()==3):
productType="CNC"
limitValue=0
if(placeType.get()==2):
limitValue=lp
typeValue=1
data = {
"symbol":"NSE:"+stockName+"-EQ",
"qty":quantityValue,
"type":typeValue,
"side":orderSide.get(),
"productType":productType,
"limitPrice":limitValue,
"stopPrice":0,
"validity":"DAY",
"disclosedQty":0,
"offlineOrder":"False",
"stopLoss":lossValue,
"takeProfit":0
}
fyers.place_order(data)
print(data)
def firstHigh(period):
i=0
while(i<len(hisData["candles"])):
epoc=(hisData["candles"][len(hisData["candles"])-1-i][0])
time_val = str(datetime.datetime.fromtimestamp(epoc))
time_val=time_val[11:19]
if(time_val=="09:15:00"):
break
i+=1
maxHigh=(hisData["candles"][len(hisData["candles"])-i-1][2])
j=1
while(j<period):
if((hisData["candles"][len(hisData["candles"])+j-i-1][2])>maxHigh):
maxHigh=hisData["candles"][len(hisData["candles"])+j-i-1][2]
j+=1
return(maxHigh)
def firstLow(period):
i=0
while(i<len(hisData["candles"])):
epoc=(hisData["candles"][len(hisData["candles"])-1-i][0])
time_val = str(datetime.datetime.fromtimestamp(epoc))
time_val=time_val[11:19]
if(time_val=="09:15:00"):
break
i+=1
maxHigh=(hisData["candles"][len(hisData["candles"])-i-1][3])
j=1
while(j<period):
if((hisData["candles"][len(hisData["candles"])+j-i-1][3])<maxHigh):
maxHigh=hisData["candles"][len(hisData["candles"])+j-i-1][3]
j+=1
return(maxHigh)
def volMA(number):
sum=0
period=number
while(number>0):
sum+=vol(-(number-1))
number-=1
return(sum/period)
def todayHigh():
i=0
while(i<len(hisData["candles"])):
epoc=(hisData["candles"][len(hisData["candles"])-1-i][0])
time_val = str(datetime.datetime.fromtimestamp(epoc))
time_val=time_val[11:19]
if(time_val=="09:15:00"):
break
i+=1
maxHigh=(hisData["candles"][len(hisData["candles"])-i-1][2])
i-=1
while(i>0):
if((hisData["candles"][len(hisData["candles"])-i-1][2])>maxHigh):
maxHigh=hisData["candles"][len(hisData["candles"])-i-1][2]
i-=1
return(maxHigh)
def todayLow():
i=0
while(i<len(hisData["candles"])):
epoc=(hisData["candles"][len(hisData["candles"])-1-i][0])
time_val = str(datetime.datetime.fromtimestamp(epoc))
time_val=time_val[11:19]
if(time_val=="09:15:00"):
break
i+=1
maxHigh=(hisData["candles"][len(hisData["candles"])-i-1][3])
i-=1
while(i>0):
if((hisData["candles"][len(hisData["candles"])-i-1][3])<maxHigh):
maxHigh=hisData["candles"][len(hisData["candles"])-i-1][3]
i-=1
return(maxHigh)
global tempData
fromVal=99
toVal=0
hisLength=0
data = {"symbol":"NSE:"+Stocks['values'][1]+"-EQ","resolution":timeFrame.get(),"date_format":"1","range_from":str(date.today()-timedelta(days = fromVal)),"range_to":str(date.today()-timedelta(days = toVal)),"cont_flag":"1"}
tempData=(fyers.history(data))
hisLength=len(tempData["candles"])
while(hisLength<200):
fromVal+=100
toVal+=100
data = {"symbol":"NSE:"+Stocks['values'][1]+"-EQ","resolution":timeFrame.get(),"date_format":"1","range_from":str(date.today()-timedelta(days = fromVal)),"range_to":str(date.today()-timedelta(days = toVal)),"cont_flag":"1"}
tempData+=(fyers.history(data))
hisLength=len(tempData["candles"])
print(len(tempData["candles"]))
print((tempData["candles"][len(tempData["candles"])-1][4]))
#return(hisData["candles"][0][4])
topFrame=Frame(root)
topFrame=Frame(root)
topFrame.pack(side=TOP,fill=X)
Button(topFrame,text="INTRADAY STOCK SCANNER").pack(side=TOP,fill=X)
Button(topFrame,text="SESSION",command=session_pop).pack(fill=X)
timeFrame = ttk.Combobox(topFrame,
values=['D','1','2','3','5','10','15','20','30','60','120','240'],width=13)
timeFrame.current(5)
timeFrame.pack(side=LEFT,fill=X)
category = ttk.Combobox(topFrame,
values=['NIFTY 50','NIFTY NEXT 50','NIFTY 100','NIFTY 200','NIFTY 500',
'NIFTY MIDCAP 150','NIFTY SMALLCAP 150','NIFTY BANK','NIFTY AUTO','NIFTY FMCG',
'NIFTY IT','NIFTY MEDIA','NIFTY METAL','NIFTY PHARMA','NIFTY PSU BANK','NIFTY REALTY'
],width=10)
category.current(0)
category.pack(side=LEFT,expand=True,fill=X)
category.bind("<<ComboboxSelected>>", listStocks)
#category.bind("<<ComboboxSelected>>", callbackFunc)
Button(topFrame,text="ADD STRATEGY",command=create_scan).pack(side=LEFT,expand=True,fill=X)
setFrame=Frame(root)
setFrame.pack(expand=True,fill=X)
Stocks = ttk.Combobox(setFrame,
values=[""],width=10)
Stocks.pack(side=LEFT,expand=True,fill=X)
Button(setFrame,text="ADD TO SCAN",command=addStocks).pack(side=LEFT,expand=True,fill=X)
StockstoScan = ttk.Combobox(setFrame,
values=[""],width=10)
StockstoScan.pack(side=LEFT,expand=True,fill=X)
midFrame=Frame(root)
midFrame.pack(expand=True,fill=X)
exFrame=Frame(root)
exFrame.pack(expand=True,fill=X)
Button(exFrame,text="RESET",command=clearWidgets).pack(side=LEFT,expand=True,fill=X)
repeatScan = ttk.Combobox(exFrame,
values=[
"REPEAT",
"1",
"5",
"10","30","60","300","600","900","1800","3600"],width=10)
repeatScan.current(0)
repeatScan.pack(side=LEFT,expand=True,fill=X)
ttk.Label(exFrame,text="LIMIT").pack(side=LEFT,expand=True,fill=X)
w1 = Spinbox(exFrame,width=10, from_=1, to=1000)
w1.pack(side=LEFT,expand=True,fill=X)
Button(exFrame,text="START",command=startThread).pack(side=LEFT,expand=True,fill=X)
Button(exFrame,text="STOP",command=stopScan).pack(side=LEFT,expand=True,fill=X)
resultFrame=Frame(root)
resultFrame.pack()
resultFrame1=Frame(resultFrame)
resultFrame1.pack(side=LEFT,fill='x')
lBox=Listbox(resultFrame1,width=84)
lBox.pack(side=LEFT)
botFrame=Frame(root)
botFrame.pack(side=TOP,expand=True,fill=X)
savedScan = ttk.Combobox(botFrame,
values=[""],width=10)
#savedScan.current(0)
savedScan.pack(side=LEFT,expand=True,fill=X)
savedScan.bind("<<ComboboxSelected>>", viewSaved)
scanName=Entry(botFrame)
scanName.pack(side=LEFT,expand=True,fill=X)
Button(botFrame,text="REFRESH",command=viewScan).pack(side=LEFT,expand=True,fill=X)
Button(botFrame,text="SAVE",command=saveScan).pack(side=LEFT,expand=True,fill=X)
Button(botFrame,text="DELETE",command=deleteScan).pack(side=LEFT,expand=True,fill=X)
statusVar = StringVar()
statusBar=Label(root,textvariable=statusVar)
statusBar.pack(side=LEFT)
root.attributes('-topmost',True)
root.mainloop()
CREATING DATABASE
import sqlite3
conn=sqlite3.connect("fyers.db")
query="create table scanner(name text not null,query1 text not null,query2 text not null,query3 text not null,query4 text,primary key(name,query4))"
conn.execute(query)
conn.commit()
conn.close()
Comments
Post a Comment