Python Image Recognition

In this project, I used OpenCV for image recognition. OpenCV is a decent Computer Vision package, it has great functionality - blurring, straight line detection, contouring. I find it not as powerful as training your own neural network using Keras or Google's Tensorflow library. In the future, I will likely look into using the YOLO (You only look once) package or Tensorflow. One drawback with training your own network is that large amounts of data cannot be trained in minutes; it could take many hours or even days. I would look into setting up a GPU if you are looking to use Tensorflow in your projects. https://github.com/akhily1/ImageRecognition


Recursion Problems

The first 9 lines is a problem that adds up all of the numbers in a list using recursion. In lines 12 through 18, I used recursion to calculate the reciprocal of consecutive positive integers starting from 1.

def listNums(number): if len(number) == 1: return number[0] else: var = number[len(number)-1] number.pop() return var + listNums(number) x = listNums([3,4,8,9]) print(x) def harmonic(num): if num == 1: return num else: return 1/num + harmonic(num - 1) x = harmonic(5) print(x)

Recursion

//sum digits of int def sumDigit(num): l=len(list(str(num))) if l == 1: return(num) else: return (num % 10 + sumDigit(int(num / 10))) z=sumDigit(678910) //Find gcd of 2 numbers def gcd(a,b): if(b==0): return a else: return gcd(b,a%b) a=int(input("Enter first number:")) b=int(input("Enter second number:")) GCD=gcd(a,b) print("GCD is: "+ GCD) print(GCD)

Movie Recommender

Movie recommendation systems aim to recommend movies that users may be interested in. In our project we aim to develop a content-based movie recommendation system that can be used for different categories/features. The system will perform specific information filtering and attempt to predict how relevant the movie is to the user. Based on the prediction a recommendation can be built which presents items that are likely of interest to the user. Intuitively, a prediction or recommendation system builds up a user’s profile based on his/her records and compares it with some reference characteristics and seeks to predict the rating that a user would give to the movie that he/she hasn’t evaluated yet. Moreover, recommendations also depend on the ratings that user’s with similar movie tastes would have provided. Having filtered the information from each user’s rating for similar movies, a response will be generated, which will be provided to the user who has not watched the movie yet. Recommendation System: How does it work? We have a collection of different movies of different genres and users with different backgrounds. Users are of different age/profession/location and can rate the movies.User ratings are mapped with users who give the same rating for a movie.User can choose to take movie recommendations from people of his age group, profession and location.Our engine maps users’ profiles based on the similar ratings they give to movies. Types of Recommendations A user can choose to take recommendations from the other users of his age group, from people in his geographic location, from people in his profession. Analytics: Movie makers can benefit from our system by choosing the target genre which will be accepted by the audience. A trending genre can be chosen based upon the statistical data viewing the simple charts generated based on the genre liked by the most number of people. Movie makers can also decide the genre by drilling into the likes of the target age groups and target locations(states in the USA).

Global Alignment

This code simulates the Needleman-Wunsch Global Alignment Algorithm to find the optimal alignment of two sequences.

import numpy #prompt the user for the sequences seq1=input("Input your first sequence: ") seq2=input("Input your second sequence: ") #make the variables for the final sequences seq1final='' seq2final='' #make the variable for the final alignment score score=0 #construct the scoring matrix scoreMatrix=numpy.zeros(shape=(len(seq1)+1,len(seq2)+1)) #variables for scoring match=1 mismatch=-1 gap=-2 print('Sequence One: ',seq1) print('Sequence Two: ',seq2) print('Match: ',match) print('Mismatch: ',mismatch) print('Gap: ',gap) #construct origin dictionary origins={} for y in range(0, len(seq1)+1): for x in range(0, len(seq2)+1): #make the blank values if y==0: scoreMatrix[y,x]=gap*x origins[y,x]='left' if x==0: scoreMatrix[y,x]=gap*y origins[y,x]='up' #calculate each cell value and store its origin else: if y!=0: u=scoreMatrix[y-1,x]+gap l=scoreMatrix[y,x-1]+gap if seq1[y-1]==seq2[x-1]: d=scoreMatrix[y-1,x-1]+match else: d=scoreMatrix[y-1,x-1]+mismatch scoreMatrix[y,x]=max(u,l,d) if max(u,l,d)==u: origins[(y,x)]='up' elif max(u,l,d)==l: origins[(y,x)]='left' elif max(u,l,d)==d: origins[(y,x)]='diagnol' print(scoreMatrix) print(origins) traceCell=(len(seq1),len(seq2)) while 1==1: if origins[traceCell]=='diagnol': seq1final=seq1[traceCell[0]-1]+seq1final seq2final=seq2[traceCell[1]-1]+seq2final traceCell=(traceCell[0]-1,traceCell[1]-1) elif origins[traceCell]=='left': seq1final='-'+seq1final seq2final=str(seq2[traceCell[1]-1])+seq2final traceCell=(traceCell[0],traceCell[1]-1) elif origins[traceCell]=='up': seq1final=str(seq1[traceCell[0]-1])+seq1final seq2final='-'+seq2final traceCell=(traceCell[0]-1,traceCell[1]) if traceCell==(0,0): break print('Aligned Sequence One: ',seq1final) print('Aligned Sequence Two: ',seq2final) for one in seq1final: for two in seq2final: if one=='-': score=int(score)-2 elif two=='-': score=int(score)-2 elif one==two: score=int(score)+1 else: scoore=int(score)-1 break print('Your Alignment Score Is: ',score)

Medical Drone

My team and I used a raspberry pi to measure heart rate, blood pressure, and temperature and returned it to a web portal, which featured a functioning log in and signup page. The data was stored into an SQLITE database. the GitHub link: https://github.com/cozyrohan/Hackathon-Health-Drone


Random Number Guesser

This program generates a random number from 1 to 1000000000 and you have to guess it. The answer number wont change until you get the correct answer, however, so it isn't entirely impossible. I tried it and I got it correct in about 20 minutes. So yeah have fun wasting your time.

import random n = random.randint(1, 1000000000) guess = int(input("Enter an integer from 1 to 1000000000: ")) while n != "guess": print if guess < n: print("guess is low") guess = int(input("Enter an integer from 1 to 1000000000: ")) elif guess > n: print("guess is high") guess = int(input("Enter an integer from 1 to 1000000000: ")) else: print("you are now god")

Drone SAS Live!

Uses Raspberry Pi and RFID to register drone activity and report it to the password protected web portal.


The World of Stocks

In this project, we used data from the QUANDL API to get different calculations of stocks, such as volatility, average price, and correlation coefficient. It also allowed the user to input a stock and enter how many units and when they bought it. It then calculated the amount of money they earned with the stock. The most impressive part of this project was the implementation of machine learning to estimate the future price of an inputted stock based on previous years. We used the package, sklearn, to do the machine learning. This project was used at a hackathon.


import sys from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow from PyQt5.uic import loadUi from PyQt5 import QtWidgets import quandl import math import dash import dash_core_components as dcc import dash_html_components as html import threading import numpy as np import datetime from sklearn.linear_model import LinearRegression from sklearn import preprocessing, model_selection, svm from sklearn.svm import SVR class MainWindow(QMainWindow): #link the UI def __init__(self): super(MainWindow, self).__init__() loadUi('homepage.ui', self) quandl.ApiConfig.api_key = "Ui3JT8HDDV3vnADUsD2k" #call the fill combobox function x=self.fillCombobox() #call the function to take the text from the combobox self.pushButton_2.clicked.connect(self.averageStock) #call the function to graph a stock self.pushButton_2.clicked.connect(self.visual) self.pushButton_3.clicked.connect(self.visual) self.pushButton_4.clicked.connect(self.visual) self.pushButton_5.clicked.connect(self.visual) #call the function to calculate calculate correlation self.pushButton_5.clicked.connect(self.calcCoCo) #call the function to graph correlation data self.pushButton.clicked.connect(self.graph) self.pushButton_4.clicked.connect(self.visual2) self.pushButton_3.clicked.connect(self.graph2) self.pushButton_4.clicked.connect(self.graph3) #call the function to graph related data self.pushButton_5.clicked.connect(self.visual3) self.pushButton_7.clicked.connect(self.futureDate) self.pushButton_8.clicked.connect(self.futureStocks) self.pushButton_9.clicked.connect(self.volatility) #function for filling the comboboxes def fillCombobox(self): companies=['WIKI/AAPL', 'WIKI/GOOGL', 'WIKI/TSLA', 'WIKI/IBM', 'WIKI/WMT', 'WIKI/T', 'WIKI/AMZN', 'WIKI/INTC', 'WIKI/NKE', 'WIKI/EA'] #fill the stock comboboxes for company in companies: self.comboBox.addItem(company) self.comboBox_2.addItem(company) self.comboBox_3.addItem(company) self.comboBox_4.addItem(company) self.comboBox_22.addItem(company) self.comboBox_19.addItem(company) self.comboBox_24.addItem(company) #fill the year comboboxes for i in range(2007, 2019): self.comboBox_6.addItem(str(i)) self.comboBox_7.addItem(str(i)) self.comboBox_8.addItem(str(i)) self.comboBox_25.addItem(str(i)) self.comboBox_26.addItem(str(i)) self.comboBox_9.addItem(str(i)) self.comboBox_11.addItem(str(i)) self.comboBox_12.addItem(str(i)) self.comboBox_18.addItem(str(i)) self.comboBox_14.addItem(str(i)) for i in range(2019, 2030): self.comboBox_23.addItem(str(i)) for i in range(13): if i < 10: self.comboBox_21.addItem("0" + str(i)) self.comboBox_17.addItem("0" + str(i)) else: self.comboBox_21.addItem(str(i)) self.comboBox_17.addItem(str(i)) for i in range(32): if i < 10: self.comboBox_15.addItem("0" + str(i)) self.comboBox_20.addItem("0" + str(i)) else: self.comboBox_15.addItem(str(i)) self.comboBox_20.addItem(str(i)) for i in range(10000, 100000, 10000): self.comboBox_16.addItem(str(i)) #function for taking the text from the comboboxes def averageStock(self): company=self.comboBox.currentText() year_start=int(self.comboBox_8.currentText()) year_end=int(self.comboBox_9.currentText()) listC = [] totalC = 0 for i in range(year_start, year_end+1): df = quandl.get(company, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() listC.append(y) totalC += y avgC = totalC / len(listC) self.textEdit_27.setText(str(avgC)) #functions to graph a stock def visual(self): threading.Thread(target=self.graph, daemon=True).start() def graph(self): #make the list for the y values company=self.comboBox_4.currentText() year_start=int(self.comboBox_7.currentText()) year_end=int(self.comboBox_6.currentText()) listC = [] totalC = 0 for i in range(year_start, year_end+1): print(i) df = quandl.get(company, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() listC.append(y) #make the list for the x values years=[] for i in range(year_start, year_end+1): years.append(i) #make the graph app = dash.Dash() app.layout = html.Div(children=[ html.H1(children=str(company)+' Graph'), html.Div(children='Graph of '+str(company)+' In The Years '+str(year_start)+' through '+str(year_end) ), dcc.Graph( id='ui-graphicvisualization', figure={ 'data': [ {'x': years, 'y': listC, 'type': 'line', 'name': company}, ], 'layout': { 'title': str(company) } } ) ]) app.run_server(port=1111) #function to calculate correlation def futureDate(self): sday = self.comboBox_15.currentText() smonth = self.comboBox_21.currentText() syear = self.comboBox_18.currentText() eday = self.comboBox_20.currentText() emonth = self.comboBox_17.currentText() eyear = self.comboBox_14.currentText() valueInvested = self.comboBox_16.currentText() inputStock = self.comboBox_22.currentText() startDay = quandl.get(str(inputStock), start_date = str(syear) + "-" + str(smonth) + "-" + str(sday) , end_date = str(syear) + "-" + str(smonth) + "-" + str(sday)) endDay = quandl.get(str(inputStock), start_date = str(eyear) + "-" + str(emonth) + "-" + str(eday) , end_date = str(eyear) + "-" + str(emonth) + "-" + str(eday)) x = startDay["High"].mean() y = endDay["High"].mean() percentChange = (y-x)/x finalAmt = int(valueInvested) * (1 + percentChange) self.textEdit_28.setText(str(finalAmt)) def futureStocks(self): company=self.comboBox_19.currentText() years=[] prices=[] for i in range(2007,2019): #make a list of years from 2007 to 2018 years.append(i) #make a list of averages for each year df=quandl.get(company, start_date=str(i)+"-01-01", end_date=str(i)+"-01-10") y=df["High"].mean() prices.append(y) print (prices) #create variable for third parameter of predict_stock_prices function futureYear=int(self.comboBox_23.currentText()) x=(futureYear-2018)*365 print (x) def predict_stock_prices(years, prices, x): years = np.reshape(years, (len(years),1 )) prices = np.reshape(prices, (len(prices),1)) svr_rbf = SVR(kernel = 'rbf', C=1e3, gamma=0.1) svr_rbf.fit(years, prices) return svr_rbf.predict(x)[0] predicted_prices = predict_stock_prices(years, prices, [[x]]) self.textEdit_32.setText(str(predicted_prices)) def volatility(self): inputStock = self.comboBox_24.currentText() year_start=int(self.comboBox_25.currentText()) year_end=int(self.comboBox_26.currentText()) listC = [] totalC = 0 num = 0 for i in range(year_start, year_end+1): df = quandl.get(inputStock, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() listC.append(y) totalC += y num += 1 avgC = totalC / len(listC) diffs= [] for i in listC: poop = (avgC - i) ** 2 diffs.append(poop) hello = 0 for i in diffs: hello += int(i) volatility = float((hello / len(listC))** 0.5) self.textEdit_35.setText(str(volatility)) def calcCoCo(self): inputCompany=self.comboBox_2.currentText() company=self.comboBox_3.currentText() year_start=int(self.comboBox_11.currentText()) year_end=int(self.comboBox_12.currentText()) listInput = [] totalInput = 0 listComp = [] totalComp = 0 for i in range(year_start, year_end+1): df = quandl.get(str(inputCompany), start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") df2 = quandl.get(str(company), start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() x= df2["High"].mean() listInput.append(y) totalInput += y listComp.append(x) totalComp += x avgInput = totalInput / len(listInput) avgComp = totalComp / len(listComp) listCompSquared = [] listInputSquared = [] mult = [] #to find the standard devations, u nee to find bot lists squared for i in listInput: listInputSquared.append(i**2) for i in listComp: listCompSquared.append(i**2) #to print out the multiplication of both the values in both lists, set a varaibe for both equal to the i'th number in each list. When i is 2 in the for loop, the variable will be list[i] for i in range(0, len(listInput)): itemInput = listInput[i] itemComp = listComp[i] mult.append(itemComp * itemInput) #find the average of he squared list sumPowInput = sum(listInputSquared) avgSquareInput = sumPowInput / len(listInputSquared) sumPowComp = sum(listCompSquared) avgSquareComp = sumPowComp / len(listCompSquared) sumMult = sum(mult) avgMult = sum(mult)/len(mult) varInput = avgSquareInput - (avgInput **2 ) varComp = avgSquareComp - (avgComp **2 ) coVar = (avgMult) - (avgInput * avgComp) CoCo = coVar / (math.sqrt(varInput * varComp)) self.textEdit_26.setText(str(CoCo)) #functions for graphing correlation between two stocks def visual2(self): threading.Thread(target=self.graph2, daemon=True).start() def graph2(self): inputCompany=self.comboBox_2.currentText() company=self.comboBox_3.currentText() year_start=int(self.comboBox_11.currentText()) year_end=int(self.comboBox_12.currentText()) listInput = [] totalInput = 0 listComp = [] totalComp = 0 for i in range(year_start, year_end+1): df = quandl.get(inputCompany, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") df2 = quandl.get(company, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() x= df2["High"].mean() listInput.append(y) totalInput += y listComp.append(x) totalComp += x avgInput = totalInput / len(listInput) avgComp = totalComp / len(listComp) listCompSquared = [] listInputSquared = [] mult = [] #to find the standard devations, u nee to find bot lists squared for i in listInput: listInputSquared.append(i**2) for i in listComp: listCompSquared.append(i**2) #to print out the multiplication of both the values in both lists, set a varaibe for both equal to the i'th number in each list. When i is 2 in the for loop, the variable will be list[i] for i in range(0, len(listInput)): itemInput = listInput[i] itemComp = listComp[i] mult.append(itemComp * itemInput) #find the average of he squared list sumPowInput = sum(listInputSquared) avgSquareInput = sumPowInput / len(listInputSquared) sumPowComp = sum(listCompSquared) avgSquareComp = sumPowComp / len(listCompSquared) sumMult = sum(mult) avgMult = sum(mult)/len(mult) varInput = avgSquareInput - (avgInput **2 ) varComp = avgSquareComp - (avgComp **2 ) coVar = (avgMult) - (avgInput * avgComp) CoCo = coVar / (math.sqrt(varInput * varComp)) #make the x list consisting of the years years=[] for i in range(year_start, year_end+1): years.append(i) app = dash.Dash() app.layout = html.Div(children=[ html.H1(children='Correlation Coefficients'), html.Div(children=''' Graphs each company with eachother '''), dcc.Graph( id='example-graph-5', figure={ 'data': [ {'x': years, 'y': listInput, 'type': 'line', 'name': inputCompany}, {'x': years, 'y': listComp, 'type': 'line', 'name': company}, ], 'layout': { 'title': 'Correlation= '+str(CoCo) } } ), ]) app.run_server(port=2222) #functions for graphing correlation between first stock and list of other stocks def visual3(self): threading.Thread(target=self.graph3, daemon=True).start() def graph3(self): inputCompany=self.comboBox_4.currentText() year_start=int(self.comboBox_7.currentText()) year_end=int(self.comboBox_6.currentText()) #list of companies to loop through companies=['WIKI/AAPL', 'WIKI/GOOGL', 'WIKI/TSLA', 'WIKI/IBM', 'WIKI/WMT', 'WIKI/T', 'WIKI/AMZN', 'WIKI/INTC', 'WIKI/NKE', 'WIKI/EA'] #dictionary with each company and its correlation coefficient stockList=[] absstock=[] absstockDiction={} randstockDiction={} stockList=[] absstock=[] absstockDiction={} randstockDiction={} avgValuesDiction={} #calculate correlation for each company and append the values to a dictionary for company in companies: listInput = [] totalInput = 0 listComp = [] totalComp = 0 for i in range(year_start, year_end+1): df = quandl.get(inputCompany, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") df2 = quandl.get(company, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() x= df2["High"].mean() listInput.append(y) totalInput += y listComp.append(x) totalComp += x avgInput = totalInput / len(listInput) avgComp = totalComp / len(listComp) listCompSquared = [] listInputSquared = [] mult = [] for i in listInput: listInputSquared.append(i**2) for i in listComp: listCompSquared.append(i**2) for i in range(0, len(listInput)): itemInput = listInput[i] itemComp = listComp[i] mult.append(itemComp * itemInput) sumPowInput = sum(listInputSquared) avgSquareInput = sumPowInput / len(listInputSquared) sumPowComp = sum(listCompSquared) avgSquareComp = sumPowComp / len(listCompSquared) sumMult = sum(mult) avgMult = sum(mult)/len(mult) varInput = avgSquareInput - (avgInput **2 ) varComp = avgSquareComp - (avgComp **2 ) coVar = (avgMult) - (avgInput * avgComp) CoCo = coVar / (math.sqrt(varInput * varComp)) #append values to dictionaries/lists randstockDiction[company]=CoCo absstockDiction[abs(CoCo)]=company absstock.append(abs(CoCo)) avgValuesDiction[inputCompany]=listInput avgValuesDiction[company]=listComp #make final sorted dictionary absstock=sorted(absstock) i=9 while i>=0: comp=absstockDiction[absstock[i]] stockList.append([comp,randstockDiction[comp]]) i=i-1 #graph the related data years=[] for i in range(year_start, year_end+1): years.append(i) app = dash.Dash() app.layout = html.Div(children=[ html.H1(children='Correlation Coefficients: Related Data'), html.Div(children=''' Graphs each company with eachother and finds the correlation coefficient. '''), dcc.Graph( id='example-graph-6', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[0][0]], 'type': 'line', 'name': stockList[0][0]}, ], 'layout': { 'title': str(stockList[0][0]) } } ), dcc.Graph( id='example-graph-7', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[1][0]], 'type': 'line', 'name': stockList[1][0]}, ], 'layout': { 'title': str(stockList[1][0]) } } ), dcc.Graph( id='example-graph-8', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[2][0]], 'type': 'line', 'name': stockList[2][0]}, ], 'layout': { 'title': str(stockList[2][0]) } } ), dcc.Graph( id='example-graph-9', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[3][0]], 'type': 'line', 'name': stockList[3][0]}, ], 'layout': { 'title': str(stockList[3][0]) } } ), dcc.Graph( id='example-graph-10', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[4][0]], 'type': 'line', 'name': stockList[4][0]}, ], 'layout': { 'title': str(stockList[4][0]) } } ), dcc.Graph( id='example-graph-11', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[5][0]], 'type': 'line', 'name': stockList[5][0]}, ], 'layout': { 'title': str(stockList[5][0]) } } ), dcc.Graph( id='example-graph-12', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[6][0]], 'type': 'line', 'name': stockList[6][0]}, ], 'layout': { 'title': str(stockList[6][0]) } } ), dcc.Graph( id='example-graph-13', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[7][0]], 'type': 'line', 'name': stockList[7][0]}, ], 'layout': { 'title': str(stockList[7][0]) } } ), dcc.Graph( id='example-graph-14', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[8][0]], 'type': 'line', 'name': stockList[8][0]}, ], 'layout': { 'title': str(stockList[8][0]) } } ), dcc.Graph( id='example-graph-15', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[9][0]], 'type': 'line', 'name': stockList[9][0]}, ], 'layout': { 'title': str(stockList[9][0]) } } ) ]) app.run_server(port=3333) app = QApplication(sys.argv) widget = MainWindow() widget.show() sys.exit(app.exec_())

The World Of Stocks



import sys from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QApplication, QDialog, QMainWindow from PyQt5.uic import loadUi from PyQt5 import QtWidgets import quandl import math import dash import dash_core_components as dcc import dash_html_components as html import threading import numpy as np import datetime from sklearn.linear_model import LinearRegression from sklearn import preprocessing, model_selection, svm from sklearn.svm import SVR class MainWindow(QMainWindow): #link the UI def __init__(self): super(MainWindow, self).__init__() loadUi('homepage.ui', self) quandl.ApiConfig.api_key = "Ui3JT8HDDV3vnADUsD2k" #call the fill combobox function x=self.fillCombobox() #call the function to take the text from the combobox self.pushButton_2.clicked.connect(self.averageStock) #call the function to graph a stock self.pushButton_2.clicked.connect(self.visual) self.pushButton_3.clicked.connect(self.visual) self.pushButton_4.clicked.connect(self.visual) self.pushButton_5.clicked.connect(self.visual) #call the function to calculate calculate correlation self.pushButton_5.clicked.connect(self.calcCoCo) #call the function to graph correlation data self.pushButton.clicked.connect(self.graph) self.pushButton_4.clicked.connect(self.visual2) self.pushButton_3.clicked.connect(self.graph2) self.pushButton_4.clicked.connect(self.graph3) #call the function to graph related data self.pushButton_5.clicked.connect(self.visual3) self.pushButton_7.clicked.connect(self.futureDate) self.pushButton_8.clicked.connect(self.futureStocks) self.pushButton_9.clicked.connect(self.volatility) #function for filling the comboboxes def fillCombobox(self): companies=['WIKI/AAPL', 'WIKI/GOOGL', 'WIKI/TSLA', 'WIKI/IBM', 'WIKI/WMT', 'WIKI/T', 'WIKI/AMZN', 'WIKI/INTC', 'WIKI/NKE', 'WIKI/EA'] #fill the stock comboboxes for company in companies: self.comboBox.addItem(company) self.comboBox_2.addItem(company) self.comboBox_3.addItem(company) self.comboBox_4.addItem(company) self.comboBox_22.addItem(company) self.comboBox_19.addItem(company) self.comboBox_24.addItem(company) #fill the year comboboxes for i in range(2007, 2019): self.comboBox_6.addItem(str(i)) self.comboBox_7.addItem(str(i)) self.comboBox_8.addItem(str(i)) self.comboBox_25.addItem(str(i)) self.comboBox_26.addItem(str(i)) self.comboBox_9.addItem(str(i)) self.comboBox_11.addItem(str(i)) self.comboBox_12.addItem(str(i)) self.comboBox_18.addItem(str(i)) self.comboBox_14.addItem(str(i)) for i in range(2019, 2030): self.comboBox_23.addItem(str(i)) for i in range(13): if i < 10: self.comboBox_21.addItem("0" + str(i)) self.comboBox_17.addItem("0" + str(i)) else: self.comboBox_21.addItem(str(i)) self.comboBox_17.addItem(str(i)) for i in range(32): if i < 10: self.comboBox_15.addItem("0" + str(i)) self.comboBox_20.addItem("0" + str(i)) else: self.comboBox_15.addItem(str(i)) self.comboBox_20.addItem(str(i)) for i in range(10000, 100000, 10000): self.comboBox_16.addItem(str(i)) #function for taking the text from the comboboxes def averageStock(self): company=self.comboBox.currentText() year_start=int(self.comboBox_8.currentText()) year_end=int(self.comboBox_9.currentText()) listC = [] totalC = 0 for i in range(year_start, year_end+1): df = quandl.get(company, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() listC.append(y) totalC += y avgC = totalC / len(listC) self.textEdit_27.setText(str(avgC)) #functions to graph a stock def visual(self): threading.Thread(target=self.graph, daemon=True).start() def graph(self): #make the list for the y values company=self.comboBox_4.currentText() year_start=int(self.comboBox_7.currentText()) year_end=int(self.comboBox_6.currentText()) listC = [] totalC = 0 for i in range(year_start, year_end+1): print(i) df = quandl.get(company, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() listC.append(y) #make the list for the x values years=[] for i in range(year_start, year_end+1): years.append(i) #make the graph app = dash.Dash() app.layout = html.Div(children=[ html.H1(children=str(company)+' Graph'), html.Div(children='Graph of '+str(company)+' In The Years '+str(year_start)+' through '+str(year_end) ), dcc.Graph( id='ui-graphicvisualization', figure={ 'data': [ {'x': years, 'y': listC, 'type': 'line', 'name': company}, ], 'layout': { 'title': str(company) } } ) ]) app.run_server(port=1111) #function to calculate correlation def futureDate(self): sday = self.comboBox_15.currentText() smonth = self.comboBox_21.currentText() syear = self.comboBox_18.currentText() eday = self.comboBox_20.currentText() emonth = self.comboBox_17.currentText() eyear = self.comboBox_14.currentText() valueInvested = self.comboBox_16.currentText() inputStock = self.comboBox_22.currentText() startDay = quandl.get(str(inputStock), start_date = str(syear) + "-" + str(smonth) + "-" + str(sday) , end_date = str(syear) + "-" + str(smonth) + "-" + str(sday)) endDay = quandl.get(str(inputStock), start_date = str(eyear) + "-" + str(emonth) + "-" + str(eday) , end_date = str(eyear) + "-" + str(emonth) + "-" + str(eday)) x = startDay["High"].mean() y = endDay["High"].mean() percentChange = (y-x)/x finalAmt = int(valueInvested) * (1 + percentChange) self.textEdit_28.setText(str(finalAmt)) def futureStocks(self): company=self.comboBox_19.currentText() years=[] prices=[] for i in range(2007,2019): #make a list of years from 2007 to 2018 years.append(i) #make a list of averages for each year df=quandl.get(company, start_date=str(i)+"-01-01", end_date=str(i)+"-01-10") y=df["High"].mean() prices.append(y) print (prices) #create variable for third parameter of predict_stock_prices function futureYear=int(self.comboBox_23.currentText()) x=(futureYear-2018)*365 print (x) def predict_stock_prices(years, prices, x): years = np.reshape(years, (len(years),1 )) prices = np.reshape(prices, (len(prices),1)) svr_rbf = SVR(kernel = 'rbf', C=1e3, gamma=0.1) svr_rbf.fit(years, prices) return svr_rbf.predict(x)[0] predicted_prices = predict_stock_prices(years, prices, [[x]]) self.textEdit_32.setText(str(predicted_prices)) def volatility(self): inputStock = self.comboBox_24.currentText() year_start=int(self.comboBox_25.currentText()) year_end=int(self.comboBox_26.currentText()) listC = [] totalC = 0 num = 0 for i in range(year_start, year_end+1): df = quandl.get(inputStock, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() listC.append(y) totalC += y num += 1 avgC = totalC / len(listC) diffs= [] for i in listC: poop = (avgC - i) ** 2 diffs.append(poop) hello = 0 for i in diffs: hello += int(i) volatility = float((hello / len(listC))** 0.5) self.textEdit_35.setText(str(volatility)) def calcCoCo(self): inputCompany=self.comboBox_2.currentText() company=self.comboBox_3.currentText() year_start=int(self.comboBox_11.currentText()) year_end=int(self.comboBox_12.currentText()) listInput = [] totalInput = 0 listComp = [] totalComp = 0 for i in range(year_start, year_end+1): df = quandl.get(str(inputCompany), start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") df2 = quandl.get(str(company), start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() x= df2["High"].mean() listInput.append(y) totalInput += y listComp.append(x) totalComp += x avgInput = totalInput / len(listInput) avgComp = totalComp / len(listComp) listCompSquared = [] listInputSquared = [] mult = [] #to find the standard devations, u nee to find bot lists squared for i in listInput: listInputSquared.append(i**2) for i in listComp: listCompSquared.append(i**2) #to print out the multiplication of both the values in both lists, set a varaibe for both equal to the i'th number in each list. When i is 2 in the for loop, the variable will be list[i] for i in range(0, len(listInput)): itemInput = listInput[i] itemComp = listComp[i] mult.append(itemComp * itemInput) #find the average of he squared list sumPowInput = sum(listInputSquared) avgSquareInput = sumPowInput / len(listInputSquared) sumPowComp = sum(listCompSquared) avgSquareComp = sumPowComp / len(listCompSquared) sumMult = sum(mult) avgMult = sum(mult)/len(mult) varInput = avgSquareInput - (avgInput **2 ) varComp = avgSquareComp - (avgComp **2 ) coVar = (avgMult) - (avgInput * avgComp) CoCo = coVar / (math.sqrt(varInput * varComp)) self.textEdit_26.setText(str(CoCo)) #functions for graphing correlation between two stocks def visual2(self): threading.Thread(target=self.graph2, daemon=True).start() def graph2(self): inputCompany=self.comboBox_2.currentText() company=self.comboBox_3.currentText() year_start=int(self.comboBox_11.currentText()) year_end=int(self.comboBox_12.currentText()) listInput = [] totalInput = 0 listComp = [] totalComp = 0 for i in range(year_start, year_end+1): df = quandl.get(inputCompany, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") df2 = quandl.get(company, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() x= df2["High"].mean() listInput.append(y) totalInput += y listComp.append(x) totalComp += x avgInput = totalInput / len(listInput) avgComp = totalComp / len(listComp) listCompSquared = [] listInputSquared = [] mult = [] #to find the standard devations, u nee to find bot lists squared for i in listInput: listInputSquared.append(i**2) for i in listComp: listCompSquared.append(i**2) #to print out the multiplication of both the values in both lists, set a varaibe for both equal to the i'th number in each list. When i is 2 in the for loop, the variable will be list[i] for i in range(0, len(listInput)): itemInput = listInput[i] itemComp = listComp[i] mult.append(itemComp * itemInput) #find the average of he squared list sumPowInput = sum(listInputSquared) avgSquareInput = sumPowInput / len(listInputSquared) sumPowComp = sum(listCompSquared) avgSquareComp = sumPowComp / len(listCompSquared) sumMult = sum(mult) avgMult = sum(mult)/len(mult) varInput = avgSquareInput - (avgInput **2 ) varComp = avgSquareComp - (avgComp **2 ) coVar = (avgMult) - (avgInput * avgComp) CoCo = coVar / (math.sqrt(varInput * varComp)) #make the x list consisting of the years years=[] for i in range(year_start, year_end+1): years.append(i) app = dash.Dash() app.layout = html.Div(children=[ html.H1(children='Correlation Coefficients'), html.Div(children=''' Graphs each company with eachother '''), dcc.Graph( id='example-graph-5', figure={ 'data': [ {'x': years, 'y': listInput, 'type': 'line', 'name': inputCompany}, {'x': years, 'y': listComp, 'type': 'line', 'name': company}, ], 'layout': { 'title': 'Correlation= '+str(CoCo) } } ), ]) app.run_server(port=2222) #functions for graphing correlation between first stock and list of other stocks def visual3(self): threading.Thread(target=self.graph3, daemon=True).start() def graph3(self): inputCompany=self.comboBox_4.currentText() year_start=int(self.comboBox_7.currentText()) year_end=int(self.comboBox_6.currentText()) #list of companies to loop through companies=['WIKI/AAPL', 'WIKI/GOOGL', 'WIKI/TSLA', 'WIKI/IBM', 'WIKI/WMT', 'WIKI/T', 'WIKI/AMZN', 'WIKI/INTC', 'WIKI/NKE', 'WIKI/EA'] #dictionary with each company and its correlation coefficient stockList=[] absstock=[] absstockDiction={} randstockDiction={} stockList=[] absstock=[] absstockDiction={} randstockDiction={} avgValuesDiction={} #calculate correlation for each company and append the values to a dictionary for company in companies: listInput = [] totalInput = 0 listComp = [] totalComp = 0 for i in range(year_start, year_end+1): df = quandl.get(inputCompany, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") df2 = quandl.get(company, start_date = str(i)+"-01-01", end_date = str(i)+"-12-31") y = df["High"].mean() x= df2["High"].mean() listInput.append(y) totalInput += y listComp.append(x) totalComp += x avgInput = totalInput / len(listInput) avgComp = totalComp / len(listComp) listCompSquared = [] listInputSquared = [] mult = [] for i in listInput: listInputSquared.append(i**2) for i in listComp: listCompSquared.append(i**2) for i in range(0, len(listInput)): itemInput = listInput[i] itemComp = listComp[i] mult.append(itemComp * itemInput) sumPowInput = sum(listInputSquared) avgSquareInput = sumPowInput / len(listInputSquared) sumPowComp = sum(listCompSquared) avgSquareComp = sumPowComp / len(listCompSquared) sumMult = sum(mult) avgMult = sum(mult)/len(mult) varInput = avgSquareInput - (avgInput **2 ) varComp = avgSquareComp - (avgComp **2 ) coVar = (avgMult) - (avgInput * avgComp) CoCo = coVar / (math.sqrt(varInput * varComp)) #append values to dictionaries/lists randstockDiction[company]=CoCo absstockDiction[abs(CoCo)]=company absstock.append(abs(CoCo)) avgValuesDiction[inputCompany]=listInput avgValuesDiction[company]=listComp #make final sorted dictionary absstock=sorted(absstock) i=9 while i>=0: comp=absstockDiction[absstock[i]] stockList.append([comp,randstockDiction[comp]]) i=i-1 #graph the related data years=[] for i in range(year_start, year_end+1): years.append(i) app = dash.Dash() app.layout = html.Div(children=[ html.H1(children='Correlation Coefficients: Related Data'), html.Div(children=''' Graphs each company with eachother and finds the correlation coefficient. '''), dcc.Graph( id='example-graph-6', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[0][0]], 'type': 'line', 'name': stockList[0][0]}, ], 'layout': { 'title': str(stockList[0][0]) } } ), dcc.Graph( id='example-graph-7', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[1][0]], 'type': 'line', 'name': stockList[1][0]}, ], 'layout': { 'title': str(stockList[1][0]) } } ), dcc.Graph( id='example-graph-8', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[2][0]], 'type': 'line', 'name': stockList[2][0]}, ], 'layout': { 'title': str(stockList[2][0]) } } ), dcc.Graph( id='example-graph-9', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[3][0]], 'type': 'line', 'name': stockList[3][0]}, ], 'layout': { 'title': str(stockList[3][0]) } } ), dcc.Graph( id='example-graph-10', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[4][0]], 'type': 'line', 'name': stockList[4][0]}, ], 'layout': { 'title': str(stockList[4][0]) } } ), dcc.Graph( id='example-graph-11', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[5][0]], 'type': 'line', 'name': stockList[5][0]}, ], 'layout': { 'title': str(stockList[5][0]) } } ), dcc.Graph( id='example-graph-12', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[6][0]], 'type': 'line', 'name': stockList[6][0]}, ], 'layout': { 'title': str(stockList[6][0]) } } ), dcc.Graph( id='example-graph-13', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[7][0]], 'type': 'line', 'name': stockList[7][0]}, ], 'layout': { 'title': str(stockList[7][0]) } } ), dcc.Graph( id='example-graph-14', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[8][0]], 'type': 'line', 'name': stockList[8][0]}, ], 'layout': { 'title': str(stockList[8][0]) } } ), dcc.Graph( id='example-graph-15', figure={ 'data': [ {'x': years, 'y': avgValuesDiction[inputCompany], 'type': 'line', 'name': inputCompany}, {'x': years, 'y': avgValuesDiction[stockList[9][0]], 'type': 'line', 'name': stockList[9][0]}, ], 'layout': { 'title': str(stockList[9][0]) } } ) ]) app.run_server(port=3333) app = QApplication(sys.argv) widget = MainWindow() widget.show() sys.exit(app.exec_())

Translation Project

The program accepts a file (txt, rtf, docx, pdf) or text written in and returns a translated copy of it. (UI in video attached).


import sys import os import docx2txt import PyPDF2 from google.cloud import translate, speech from google.cloud.speech import enums from google.cloud.speech import types from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QFileDialog from dialog import Ui_Dialog #Creates the class and initializes the main window and buttons. class AppWindow(Ui_Dialog): def __init__(self, dialog): Ui_Dialog.__init__(self) self.filename = "" self.txtname = "" self.langChosen = "" self.textg = "" self.c = "" self.setupUi(dialog) self.langSelected() self.bb.clicked.connect(self.openFile) self.re.clicked.connect(self.translation) self.pushButton.clicked.connect(self.copyText) #Code used to open a file def openFile(self): options = QFileDialog.Options() self.filename, _ = QFileDialog.getOpenFileName(options=options) self.textc() #Asks user to select a language from a dropdown menu and saves it def langSelected(self): os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="Translate-9130762d473c (2).json" # Instantiates a client translate_client = translate.Client() results = translate_client.get_languages() line = "" for i in range(0, len(results)): line += u'{name} ({language})'.format(**results[i]) + ", " self.comboBox.addItem(line) line = "" self.comboBox.activated[str].connect(self.onActivated) def onActivated(self, text): print("hello") self.langChosen = text #Translates and prints new file in language selected using the dropdown menu. def textc(self): typeOfFile = self.filename print(typeOfFile) if typeOfFile.endswith(".pdf"): pdfFileObj = open(typeOfFile, 'rb') print(pdfFileObj) pdf = PyPDF2.PdfFileReader(pdfFileObj) totalPages = pdf.getNumPages() print(totalPages) p_text = "" for page in range(totalPages): p = pdf.getPage(page) p_text += p.extractText() self.fileText.setText(p_text) self.textg = p_text elif typeOfFile.endswith(".txt"): txtFileObj = open(typeOfFile, 'rb') eachLine = "" for line in txtFileObj: print(line) eachLine += line self.fileText.setText(eachLine) self.textg = eachLine elif typeOfFile.endswith(".rtf"): rtfFileObj = open(typeOfFile, 'rb') eachLine1 = "" for line1 in rtfFileObj: print(line1) eachLine1 += line1 self.fileText.setText(eachLine1) self.textg = eachLine1 elif typeOfFile.endswith(".docx"): text = docx2txt.process(str(typeOfFile)) self.fileText.setText(text) self.textg = text else: print("Sorry, Not a supported file type at the moment.") def copyText(self): options2 = QFileDialog.Options() self.txtname, _ = QFileDialog.getOpenFileName(options=options2) self.copyFile() def copyFile(self): #myfile = self.txtname myText = self.textEdit.toPlainText() print(myText) with open(self.txtname, 'a') as f: f.write(myText) def translation(self): #Asks user to enter on of the target provided and translates the file (pdf so far) translate_client = translate.Client() target = self.langChosen typeOfFile = self.filename print(target) print(typeOfFile) start = target.rfind("(") end = target.rfind(")") choice = "" for i in range(start+1, end): choice += target[i] print(choice) if typeOfFile.endswith(".pdf"): newFile = translate_client.translate(self.textg, target_language=choice) self.textEdit.setText(u'Translation: {}'.format(newFile['translatedText'])) elif typeOfFile.endswith(".txt"): newFile2 = translate_client.translate(self.textg, target_language=choice) self.textEdit.setText(u'Translation: {}'.format(newFile2['translatedText'])) elif typeOfFile.endswith(".rtf"): newFile3 = translate_client.translate(self.textg, target_language=choice) self.textEdit.setText(u'Translation: {}'.format(newFile3['translatedText'])) elif typeOfFile.endswith("docx"): newFile1 = translate_client.translate(self.textg, target_language=choice) self.textEdit.setText(u'Translation: {}'.format(newFile1['translatedText'])) app = QtWidgets.QApplication(sys.argv) dialog = QtWidgets.QDialog() prog = AppWindow(dialog) dialog.show() sys.exit(app.exec_())

Grading Software

grading software

weight = int(input("What is your weight")) ScoreEarned = int(input("What is your score")) Extracredit = int(input("Were scores shifted")) if Extracredit == 1: print("Your score was shifted") if Extracredit == 2: print("Your score was not shifted") totalpoints = (ScoreEarned) print("totalpoints = " + str(ScoreEarned) + " / 100") x = 100.0/ weight weightedscore1 = ScoreEarned / x print(weightedscore1) print("This software will read your final test score") print(" Final:") Weight = int(input("weight(1-100)?" )) ScoreEarned = int(input("Score Earned?" )) Scoreshifted = int(input("Were scores shifted (1=yes, 2= no)? ")) if Scoreshifted == 1: Amount= int(input("By how much were they shifted?" )) totalpoints = ScoreEarned print("totalpoints= " + str(ScoreEarned) + " / 100") x = 100.0/Weight print(x) Weightedscore2 = ScoreEarned / x print(Weightedscore2) print("This software will read your homework grade") print("Homework:") Weight = int(input("Weight(1-100)?")) Numofassignments = int(input("Number of assignments?")) total = 0 totalpoints = 0 for i in range(1, Numofassignments+1, 1): Score = int(input("What was your score for this assignment ?" + str(i))) total = total + Score Maxpoints = int(input("What was the max score for this assignment ?" + str(i))) totalpoints = totalpoints + Maxpoints print("total points = " + str(total) + " / " + str(totalpoints)) percent = total / totalpoints wScore = percent * Weight print("Weightedscore3 = " + str(wScore) + " / " + str(Weight)) OverallPercentage = weightedscore1 + Weightedscore2 + wScore print(OverallPercentage)
1 ... 24 25 26 27