Basketball

This program creates a basketball from python turtle graphics.

from turtle import * screen = Screen() screen.setup(800, 800) penup() goto(0, -350) pendown() begin_fill() color("orange") circle(350) end_fill() pensize(5) color("black") circle(350) penup() setheading(40) goto(-225, -268) pendown() circle(350, 100) penup() setheading(220) goto(225, 268) pendown() circle(350, 100) penup() goto(0, 350) pendown() right(50) forward(700) penup() goto(-350, 0) pendown() left(90) forward(700)
Akshay Jun 07

This is amazing!!!!!!!!!

Repeating triangle

This program draws a triangle repeatedly depending on the range input by the user.

from turtle import * colors = ["green"] for x in range(0, 3600, 5): pencolor(colors[x%1]) forward(x) left(120)
Akshay Jun 05

This is amazing!

My K Nearest Neighbor Algorithm...without using SKLearn...

I created a KNN Algorithm by making my own data set with tuples storing the x-value, y-value, and color of 9 points, asking the user for the x and y-values of their data point and how many dots are being taken into account, then determining the distance between the point and the ones in the data set. I stored these distances in a dictionary, with the points being the keys and the distances being the values, and sorted it from the lowest distance to the highest. After, I totaled up the number of points with each color out of the inputted number of nearest points. Finally, I classified the inputted point based on which of the colors was the most prominent out of those points.


#Importing import numpy as np import math as math import operator #Data data = [(1, 2, "red"), (10, 8, "blue"), (5, 6, "green"), (4, 1, "red"), (8, 8, "blue"), (3, 1, "green"), (1, 2, "red"), (8, 10, "blue"), (6, 5, "green")] #Store Points(X/Y Values) x = int(input("What's your x-value?")) y = int(input("What's your y-value?")) #Store # of points being taken into account(K Value) k= int(input("How many closest dots do you want to take into account?")) point = (x, y) print(point) #Distance Formula def distance(x2, y2): return math.sqrt((x2-x)**2+(y2-y)**2) #Find/Store Distances of All Points(Loop/Dictionary) knndict = {} for n in data: z = distance(n[0],n[1]) print(z) knndict[n] = z #Ordering The Dictionary(Least Distance) knndicts = sorted(knndict.items(), key=operator.itemgetter(1)) print(knndicts) #Voting Process green = 0 blue = 0 red = 0 for n in range(0, k, 1): if knndicts[n][0][2] == "green": green += 1 if knndicts[n][0][2] == "blue": blue += 1 if knndicts[n][0][2] == "red": red += 1 print(green) print(blue) print(red) #Determining the Color if green > blue and green > red: print("Your dot's color has been classified as green!") elif blue > green and blue > red: print("Your dot's color has been classified as blue!") elif red > green and red > blue: print("Your dot's color has been classified as red!") else: print("Unfortunately, your dot could not be classified. Try picking a different number of closest dots next time.")

Snake Pygame

This is the popular game snake. I specified a block size to build the blocks and make the snake faster.


import pygame import time import random pygame.init() white = (255,255,255) black = (0,0,0) red = (255,0,0) green = (0,155,0) width = 800 height = 600 gameDisplay = pygame.display.set_mode((width,height)) pygame.display.set_caption('Slither') clock = pygame.time.Clock() blockSize = 23 FPS = 30 font = pygame.font.SysFont(None, 25) def snake(blockSize, snakelist): for XnY in snakelist: pygame.draw.rect(gameDisplay, green, [XnY[0],XnY[1],blockSize,blockSize]) def text_objects(text,color): textSurface = font.render(text, True, color) return textSurface, textSurface.get_rect() def message_to_screen(msg,color): textSurf, textRect = text_objects(msg,color) textRect.center = (width / 2), (height / 2) gameDisplay.blit(textSurf, textRect) def gameLoop(): gameExit = False gameOver = False xCoord = width/2 yCoord = height/2 xChange = 0 yChange = 0 snakeList = [] snakeLength = 1 randAppleX = round(random.randrange(0, width-blockSize)) randAppleY = round(random.randrange(0, height-blockSize)) while not gameExit: while gameOver == True: gameDisplay.fill(white) message_to_screen("Game over, press C to play again or Q to quit", red) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: gameOver = False gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: gameExit = True gameOver = False if event.key == pygame.K_c: gameLoop() for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: xChange = -blockSize yChange = 0 elif event.key == pygame.K_RIGHT: xChange = blockSize yChange = 0 elif event.key == pygame.K_UP: yChange = -blockSize xChange = 0 elif event.key == pygame.K_DOWN: yChange = blockSize xChange = 0 if xCoord >= width or xCoord < 0 or yCoord >= height or yCoord < 0: gameOver = True xCoord += xChange yCoord += yChange gameDisplay.fill(white) AppleThickness = 30 pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, AppleThickness, AppleThickness]) snakeHead = [] snakeHead.append(xCoord) snakeHead.append(yCoord) snakeList.append(snakeHead) if len(snakeList) > snakeLength: del snakeList[0] for eachSegment in snakeList[:-1]: if eachSegment == snakeHead: gameOver = True snake(blockSize, snakeList) pygame.display.update() if xCoord > randAppleX and xCoord < randAppleX + AppleThickness or xCoord + blockSize > randAppleX and xCoord + blockSize < randAppleX+ AppleThickness: if yCoord > randAppleY and yCoord < randAppleY + AppleThickness: randAppleX = round(random.randrange(0, width-blockSize)) randAppleY = round(random.randrange(0, height-blockSize)) snakeLength += 1 elif yCoord + blockSize > randAppleY and yCoord + blockSize < randAppleY+ AppleThickness: randAppleX = round(random.randrange(0, width-blockSize)) randAppleY = round(random.randrange(0, height-blockSize))#/10.0)*10.0 snakeLength += 1 clock.tick(FPS) pygame.quit() quit() gameLoop()

My K Nearest Neighbor Algorithm so far...without SKLearn...

Nowhere near done but I'll get there eventually...

#Importing import numpy as np import matplotlib.pyplot as plt import math as math #Data data = [(1, 2, "red"), (10, 8, "blue"), (5, 6, "green"), (4, 1, "red"), (8, 8, "blue"), (3, 1, "green"), (1, 2, "red"), (8, 10, "blue"), (6, 5, "green")] #Points x = int(input("What's your x-value?")) y = int(input("What's your y-value?")) point = (x, y) print(point) #Distance for i in range(0, 9, 1) def distance(x, y, x2, y2): return sqrt(x2-x)**2+(y2-y)**2

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_())
1