def SimulacionEMA(): symbols = input("Input a symbol or many separated by comma (Input ALL to Simulate for all symbols): ") if symbols.upper() == "ALL": symbols = DatabaseActions.getAll() else: symbols = symbols.split(",") for symbol in symbols: historico = DatabaseActions.getHistoric(symbol) SimulationEMA.simular(symbol,historico)
def GraphicsTechnicalAnalysis(): symbols = input("Input a symbol or many separated by comma(Input ALL to Calculate for all symbols): ") if symbols.upper() == "ALL": symbols = DatabaseActions.getAll() else: symbols = symbols.split(",") for symbol in symbols: historic = DatabaseActions.getHistoric(symbol) TechnicalAnalysis.GraphicsStoch(historic, symbol, parameters)
def ConnectToAPI(symbol, datefrom, resolution): logger = Logs.setup_logger("ConnectToAPI", "Logs/APIRequest.log", console=False) try: logger.info datefrom = datefrom.replace( tzinfo=tz.tzlocal()).astimezone(tz.tzutc()).replace(hour=21, minute=00, second=00) if datetime.datetime.now().hour < 17: toDate = datetime.datetime.today().replace( tzinfo=tz.tzlocal()).astimezone(tz.tzutc()).replace(hour=21, minute=00, second=00) - datetime.timedelta(days = 1) else: toDate = datetime.datetime.today().replace( tzinfo=tz.tzlocal()).astimezone(tz.tzutc()).replace(hour=21, minute=00, second=00) fromTimeStamp = int(calendar.timegm(datefrom.timetuple())) toTimeStamp = int(calendar.timegm(toDate.timetuple())) conn = http.client.HTTPConnection("www.invertironline.com") args = {"symbolName": symbol, "exchange": "BCBA", "resolution": resolution, "from": fromTimeStamp, "to": toTimeStamp} parameters = urllib.parse.urlencode(args) endpoint = "/api/cotizaciones/history?{}".format(parameters) logger.info("Requesting data {}".format(endpoint)) conn.request("GET", endpoint) res = conn.getresponse() data = res.read() info = json.loads(data.decode("utf-8")) info = info["bars"] conn.close() if not(info): return True for entry in info: t = entry["time"] o = entry["open"] c = entry["close"] h = entry["high"] l = entry["low"] dateandtime = datetime.datetime.utcfromtimestamp(t) date = str(dateandtime.date().isoformat()) DatabaseActions.insertToDatabase( date, symbol, o, h, l, c) logger.info("Data requested and sent") return False except: logger.error("Error requesting data and sending it to database") return False
def actualizar(): symbols = input("Input a symbol or many separated by comma (Input ALL to update all symbols): ") if symbols.upper() == "ALL": symbols = DatabaseActions.getAll() else: symbols = symbols.split(",") for symbol in symbols: APIRequest.scrapping(symbol)
def historico(): symbol = input("Input a symbol: ") historico = DatabaseActions.getHistoric(symbol) historicDF = {} for key in historico: historicDF[datetime.datetime.fromisoformat(key)] = historico[key] df = pd.DataFrame.from_dict(historicDF, orient='index').tail(50).rename(columns={ 'o': 'Open', 'h': 'High', 'l': 'Low', 'c': 'Close' }) op = input("¿Agregar RSI? S/N: ") if op.lower() == 's': titulo = 'RSI' periodo = int(input("Ingrese el periodo: ")) RSI = RelativeStrengthIndex.RSI(historico, periodo) df[titulo] = df.index.to_series().map(RSI) op = input("¿Agregar EMA? S/N: ") while op.lower() == 's': titulo = input("Ingrese un titulo para la EMA: ") periodo = int(input("Ingrese el periodo: ")) EMAS = ExponentialMovingAverage.EMA(historico, periodo) df[titulo] = df.index.to_series().map(EMAS) op = input("¿Agregar otra EMA? S/N: ") print(df) data = df.tail(30) columns = list(data.columns)[4:] fig = plt.figure() fig.set_size_inches((20, 16)) ax_candle = fig.add_axes((0, 0.05, 1, 0.9)) ax_candle.xaxis_date() if 'RSI' in columns: ax_candle = fig.add_axes((0, 0.30, 1, 0.7)) ax_rsi = fig.add_axes((0, 0.05, 1, 0.2), sharex=ax_candle) ax_rsi.set_ylabel("(%)") ax_rsi.plot(data.index, [70] * len(data.index), label="overbought") ax_rsi.plot(data.index, [30] * len(data.index), label="oversold") ax_rsi.plot(data.index, data["RSI"], label="RSI") ax_rsi.legend(loc="center left") ohlc = [] for date, row in data.iterrows(): Open, High, Low, Close = row[:4] ohlc.append([date2num(date), Open, High, Low, Close]) for column in columns: if column != 'RSI': ax_candle.plot(data.index, data[column], label=column) candlestick_ohlc(ax_candle, ohlc, colorup="g", colordown="r") ax_candle.legend() plt.show()
def scrapping(symbol): logger = Logs.setup_logger("scrapping", "Logs/APIRequest.log", console=False) try: lastDate = DatabaseActions.getLastDate(symbol) if datetime.datetime.now().hour < 17: day = datetime.datetime.today().date() - datetime.timedelta(days = 1) else: day = datetime.datetime.today().date() empty = False while (lastDate < day.isoformat() and not(empty)): if len(lastDate) > 0: empty = ConnectToAPI( symbol, datetime.datetime.fromisoformat(lastDate), "D") else: empty = ConnectToAPI(symbol, datetime.datetime(1900, 1, 1), "D") lastDate = DatabaseActions.getLastDate(symbol) except: logger.error(sys.exc_info()[1])
def DisplayResults(aramgame): aramgame = json.loads(aramgame) teammates, opponents, gameWin = DatabaseActions.GetResults(aramgame) if gameWin == False: print "---------------------\nTEAM ONE\n---------------------" else: print "---------------------\nTEAM ONE -- WINNERS\n---------------------" for champion in teammates: print championdictionary[str(champion)]["championName"] if gameWin == False: print "---------------------\nTEAM TWO -- WINNERS\n---------------------" else: print "---------------------\nTEAM TWO\n---------------------" for champion in opponents: print championdictionary[str(champion)]["championName"] print "\n\n\n"
def PredictGame(wizard, aramgame): aramgame = json.loads(aramgame) teammates, opponents, gameWin = DatabaseActions.GetResults(aramgame) #writes a vector of which champions were on which team followed by the result gamevector = [0] * len(championdictionary) for champion in teammates: gamevector[championdictionary[str(champion)]["Id"] - 1] = 1 for champion in opponents: gamevector[championdictionary[str(champion)]["Id"] - 1] = -1 prediction = wizard.activate(gamevector)[0] #Check to see if we were correct correct = (True if int(round(prediction)) == gameWin else False) #For data sorting we will describe all our certainties as affirmative cases (over 50%) if prediction < 0.5: prediction = 1 - prediction return prediction, correct
import pybrain from pybrain.tools.shortcuts import buildNetwork from pybrain.datasets.supervised import SupervisedDataSet from pybrain.supervised.trainers.backprop import BackpropTrainer from pybrain.tools.customxml.networkwriter import NetworkWriter from pybrain.structure.networks.feedforward import FeedForwardNetwork from pybrain.structure.modules.linearlayer import LinearLayer from pybrain.structure.modules.sigmoidlayer import SigmoidLayer from pybrain.structure.connections.full import FullConnection from pybrain.structure.modules.biasunit import BiasUnit # Next we transform the data into a vectorized format so that it can be used as a training set aramdata = open("ARAMData.txt","r") #ChampionDictionary holds all the riot static data about each champion. The Riot IDs are the keys of the dictionary championdictionary = DatabaseActions.CreateChampionDictionary() #Creates a Neural Network of Appropriate size predictionNet = FeedForwardNetwork() inLayer = LinearLayer(len(championdictionary)) hiddenLayer = SigmoidLayer(5) outLayer = SigmoidLayer(1) predictionNet.addInputModule(inLayer) predictionNet.addModule(hiddenLayer) predictionNet.addOutputModule(outLayer) predictionNet.addModule(BiasUnit(name = 'bias')) in_to_hidden = FullConnection(inLayer,hiddenLayer) hidden_to_out = FullConnection(hiddenLayer,outLayer)
#We use the list of player Ids to both get ARAM games and to get new players to look at. #We use the variable currentplayerId to keep track of which users have already been called from our list. currentplayerId = 0 #Opens the txt file that we will be writing our ARAM Game data into aramdata = open("ARAMData.txt", "w") #Keep finding more data until our database reaches the requested size while len(gameIds) < DBSize: #Prints our current progress print("Starting data of player " + str(playerIds[currentplayerId]) + " " + str(100 * len(gameIds) / float(DBSize)) + "% complete") #GetHistory returns the Riot API data given a player's ID playerhistory = DatabaseActions.GetHistory(playerIds[currentplayerId]) #UsableGames removes all games that are repeats, too old, or not ARAMs from a player's history playerhistory = DatabaseActions.UsableGames(playerhistory, gameIds) #Adds new gameIds to our list and writes the game data to the file "ARAMData.txt" for game in playerhistory["games"]: gameIds.append(game["gameId"]) aramdata.write(json.dumps(game)) aramdata.write("\n") ##I'm not sure why python had issues combining the last two lines. Tried a couple of fixes and then moved on. whatever. #Looks at the games we recently added and adds the Ids of the other players from those games to our list of IDs if they weren't already there for game in playerhistory["games"]: newIds = [player["summonerId"] for player in game["fellowPlayers"]] playerIds = playerIds + newIds
else: if symbol in list(parameters.index): print(parameters.loc[[symbol]]) else: print("Symbol not in parameters.xlsx") if __name__ == "__main__": if (not (os.path.exists("Logs"))): os.makedirs("Logs") if (not (os.path.exists("Graphics"))): os.makedirs("Graphics") if (not (os.path.exists("Simulations"))): os.makedirs("Simulations") try: DatabaseActions.testConnection() except: raise Exception( "Error connecting to database. Please check the connection string and the server connection." ) logger = Logs.setup_logger("scrapping", "Logs/APIRequest.log") op = '1' parameters = pd.read_excel('Parameters.xlsx') parameters = parameters.sort_values(by='Simbolo') parameters = parameters.set_index('Simbolo') while op.lower() != 'q': print("Select an option") print("1 - Update Symbol") print("2 - Show historic data") print("3 - Create technical analysis graphics with saved parameters")