def test_availability_accessibility(self): """ Test case for a valid availability query. Reads the travel properties from test-data.json, sets the travel departureTimeEarliest to next monday at 11:00Z. Expects valid response for a transport leaving 19:00+3, one availability for the passenger adult with GUIDE_DOG accessibility feature in the reservation. """ # Trip availaibility inquiry travel = self.testdata['travel_data_accessibility'] product = self.testdata['test_products_current_date_response'] t = datetime.datetime.now() travel["travel"]["departureTimeEarliest"] = zulu.now().shift(days=(7 - t.weekday())). \ replace(hour=11, minute=00).isoformat() r = lippuclient.availability_request(self.envdata['base_url'], headers=self.headers, payload=travel) logging.info( "test_availability_accessibility, availability response: %s" % r.json()) self.assertEqual(r.status_code, 200) self.assertEqual(len(r.json()['availability']), 1) self.assertEqual(r.json()['contract'], travel['contract']) self.assertEqual(r.json()['travel']['productType'], travel['travel']['productType']) self.assertEqual(r.json()['travel']['to']['lat'], travel['travel']['to']['lat']) self.assertEqual(r.json()['travel']['to']['lon'], travel['travel']['to']['lon']) self.assertEqual(r.json()['travel']['from']['lat'], travel['travel']['from']['lat']) self.assertEqual(r.json()['travel']['from']['lon'], travel['travel']['from']['lon']) for item in r.json()['availability']: self.assertNotEqual(item['applicableForPassengers'], 'None') self.assertEqual(item['fare']['currency'], 'EUR') self.assertEqual(item['fare']['amount'], 14) self.assertEqual(item['fare']['vatPercent'], 10) for applicable in item['applicableForPassengers']: self.assertEqual(applicable['category'], 'Adult') self.assertEqual( applicable['category'] in product['products2']['suitablePassengerCategories'], True) self.assertEqual(applicable['accessibility'][0]['title'], 'GUIDE_DOG') self.assertEqual( applicable['accessibility'][0]['fare']['currency'], 'EUR') self.assertEqual( applicable['accessibility'][0]['fare']['amount'], 0) self.assertEqual( applicable['accessibility'][0]['fare']['vatPercent'], 0) self.assertEqual(r.json()['travel']['departureTime'].startswith( zulu.now().shift(days=(7 - t.weekday())). \ replace(hour=19, minute=00).format('%Y-%m-%dT%H:%M') ), True) logging.info("Departure time: %s" % zulu.parse(r.json()['travel']['departureTime']))
def test_availability_set_both_times(self): """ Test case for a valid availability query. Reads the travel properties from test-data.json, sets the travel departureTimeEarliest two days from now to 14:00Z and arrivalTimeLatest two days from now at 21:30. As both are set, expects the departureTimeEarliest to be used for query.Expects valid response for a transport leaving 20:00+3. """ # Trip availaibility inquiry travel = self.testdata['travel_data'] product = self.testdata['test_products_current_date_response'] travel["travel"]["departureTimeEarliest"] = zulu.now().shift(days=2). \ replace(hour=14, minute=00).isoformat() travel["travel"]["arrivalTimeLatest"] = zulu.now().shift(days=2). \ replace(hour=21, minute=30).isoformat() r = lippuclient.availability_request(self.envdata['base_url'], headers=self.headers, payload=travel) logging.info( "test_availability_both_arrival_time, availability response: %s" % r.json()) self.assertEqual(r.status_code, 200) self.assertEqual(len(r.json()['availability']), 3) self.assertEqual(r.json()['contract'], travel['contract']) self.assertEqual(r.json()['travel']['productType'], travel['travel']['productType']) self.assertEqual(r.json()['travel']['to']['lat'], travel['travel']['to']['lat']) self.assertEqual(r.json()['travel']['to']['lon'], travel['travel']['to']['lon']) self.assertEqual(r.json()['travel']['from']['lat'], travel['travel']['from']['lat']) self.assertEqual(r.json()['travel']['from']['lon'], travel['travel']['from']['lon']) for item in r.json()['availability']: self.assertNotEqual(item['applicableForPassengers'], 'None') for applicable in item['applicableForPassengers']: self.assertNotEqual(applicable, 'None') self.assertEqual( applicable['category'] in product['products1']['suitablePassengerCategories'], True) self.assertEqual(r.json()['travel']['departureTime'].startswith( zulu.now().shift(days=2). \ replace(hour=20, minute=00).format('%Y-%m-%dT%H:%M') ), True) self.assertEqual(r.json()['travel']['arrivalTime'].startswith( zulu.now().shift(days=2). \ replace(hour=23, minute=10).format('%Y-%m-%dT%H:%M') ), True) logging.info("Arrival time: %s" % zulu.parse(r.json()['travel']['arrivalTime']))
def test_availability_empty_extra_services(self): """ Test case for a availability query with invalid extraService. Expects valid response for a transport leaving, but with no availabilities as the one passenger has invalid extraService """ # Trip availaibility inquiry travel = self.testdata['travel_data_extra_services'] travel['passengers'][0]['extraServices'][0]['title'] = "" product = self.testdata['test_products_current_date_response'] t = datetime.datetime.now() travel["travel"]["departureTimeEarliest"] = zulu.now().shift(days=(7 - t.weekday())). \ replace(hour=11, minute=00).isoformat() r = lippuclient.availability_request(self.envdata['base_url'], headers=self.headers, payload=travel) logging.info( "test_availability_invalid_extra_services, availability response: %s" % r.json()) self.assertEqual(r.status_code, 200) self.assertEqual(len(r.json()['availability']), 0) self.assertEqual(r.json()['contract'], travel['contract']) self.assertEqual(r.json()['travel']['productType'], travel['travel']['productType']) self.assertEqual(r.json()['travel']['to']['lat'], travel['travel']['to']['lat']) self.assertEqual(r.json()['travel']['to']['lon'], travel['travel']['to']['lon']) self.assertEqual(r.json()['travel']['from']['lat'], travel['travel']['from']['lat']) self.assertEqual(r.json()['travel']['from']['lon'], travel['travel']['from']['lon'])
def run(self): logging.info(self.threadID + " - thread started, query recieved: %s",str(self.query)) logging.info(self.threadID + " REST endpoint: " + self.rest) sessionID = self.threadID #setDiscoveryIndex(sessionID) allJSONObjects = kpindex.getJSONObjectsFromElasticSearch(self.rest, self.sourceType,self.threadID,self.query,self.maxNumResults) logging.info(self.threadID + " - data retrieved from Elastic search creating index now") textData = kpindex.getAllTextData(allJSONObjects) indexes,totalDistinctKeywords = kpindex.getBookBackIndexes(self.threadID,textData,allJSONObjects) logging.info(self.threadID + " - Index creation done") documentData,totalDocuments = kpindex.getTitles(allJSONObjects) currentDateZulu = zulu.now() date = zulu.parse(currentDateZulu).isoformat()#datetime.datetime.now().isoformat() conceptData,totalConcepts=kpindex.getConcepts(allJSONObjects) metadata = {"totalDocuments":totalDocuments,"dateCreated":date,"totalKeywords":totalDistinctKeywords,"totalConcepts":totalConcepts,"title":self.title, "creator": self.creatorID} url = self.rest + self.destinationType +"/"+sessionID #insertsuccess = kpindex.insertIntoElasticSearch(indexes,documentData,conceptData,metadata,url) completedIndex = {"bookback": indexes,"allDocumentData":documentData,"metadata": metadata,"conceptIndex":conceptData} setDiscoveryIndex(sessionID,completedIndex) logging.info(self.threadID + "Index stored, thread completed")
def __init__(self): right_now = zulu.now() dt = zulu.parse(right_now) # string field self.person_id = str(uuid.uuid4()) # timestamp self.update_timestamp = right_now # string fields self.firstname = 'fn ' + str(int(dt.timestamp()*100000%100)) self.lastname = 'ln ' + str(int(dt.timestamp()*100000%99)) # int fields self.sibling_count = randint(0,4) self.child_count = randint(0,4) # float fields self.height = random() * 100 self.weight = random() * 100 # date fields self.birthdate = datetime.date.today() - datetime.timedelta(days=randint(10000,20000)) self.account_creation_date = datetime.date.today() - datetime.timedelta(days=randint(1,1000)) # array field self.given_names = [self.firstname,self.lastname] # bool field self.is_active = randint(0, 10) % 2 == 0 # byte field self.profile_picture = base64.b64encode(self.person_id.encode('utf-8'))
def test_reservation_accessibility_invalid_reservation_id(self): """ Test case for reservation with invalid accessibility requirements reservation id, reservation request fails. """ t = datetime.datetime.now() travel = self.testdata['travel_data_accessibility'] travel["travel"]["departureTimeEarliest"] = zulu.now().shift(days=(7 - t.weekday())). \ replace(hour=14, minute=00).isoformat() logging.info( "test_reservation_accessibility, availability request: %s" % travel) r_availability = lippuclient.availability_request( self.envdata['base_url'], headers=self.headers, payload=travel) logging.info( "test_reservation_accessibility, availability response: %s" % r_availability) self.assertEqual(r_availability.status_code, 200) self.assertGreater(len(r_availability.json()), 0) # Make reservation self.headers['X-Message-Id'] = str(uuid.uuid4()) travel_entitlement_id = r_availability.json( )['availability'][0]['travelEntitlementId'] reservation = { 'reservations': [{ 'travelEntitlementId': travel_entitlement_id, 'chosenAccessibilityReservationIds': [str(uuid.uuid4())], 'customerInfo': [self.testdata['customer_info']] }] } logging.info("Sending reservation %s" % reservation) r_reservation = lippuclient.reservation_request( self.envdata['base_url'], headers=self.headers, payload=reservation) logging.info( "test_reservation_accessibility, reservation response %s" % r_reservation.text) self.assertEqual(r_reservation.status_code, 404) # Test that reservation does not exits. self.headers['X-Message-Id'] = str(uuid.uuid4()) r = lippuclient.travel_entitlement_status( self.envdata['base_url'], headers=self.headers, travel_entitlement_id=travel_entitlement_id) logging.info( "test_reservation_accessibility, travel entitlement response %s" % r.text) self.assertEqual(r.status_code, 404)
def status(self, fromcall, statustext, timestamp=False ): #APRS101 Page 80 Status Reports; only basic at this time if not timestamp: statustext = statustext[:62] return fromcall.upper() + '>APRS:>' + statustext if timestamp: statustext = statustext[:55] dt = zulu.parse(zulu.now()) zt = re.findall("\d{6}", str(dt)) return fromcall.upper() + '>APRS:>' + zt[0] + 'z' + statustext
def test_availability_null_from_lat_coordinate(self): """ Test case for using null latiatude from coordinate. """ travel = self.testdata['travel_data'] travel["travel"]["departureTimeEarliest"] = zulu.now().shift(days=2).\ replace(hour=14, minute=00).isoformat() travel["travel"]["from"]["lat"] = None r = lippuclient.availability_request(self.envdata['base_url'], headers=self.headers, payload=travel) logging.info( "test_availability_null_from_lat_coordinate, availability response: %s" % r.json()) self.assertEqual(r.status_code, 400) self.assertEqual(r.json()["statusCode"], 400)
def test_availability_departure_late(self): """ Test case for using too late departure time earliest, in which case the tansport operator does not have transport to offer. """ travel = self.testdata['travel_data'] travel["travel"]["departureTimeEarliest"] = zulu.now().shift(days=2). \ replace(hour=20, minute=45).isoformat() r = lippuclient.availability_request(self.envdata['base_url'], headers=self.headers, payload=travel) logging.info( "test_availability_departure_late, availability response: %s" % r.json()) self.assertEqual(r.status_code, 400) self.assertEqual(r.json()["statusCode"], 400)
def test_coinbase_backend_downloads_rates(self): backend = CoinBaseBackend('USD') now = zulu.now() backend.refresh() self.assertLess(now, backend.last_updated) self.assertGreater(len(backend._rates), 100) rate = backend.rate('EUR') self.assertIsInstance(rate, Decimal) self.assertLess(rate, 1) rate = backend.quotation('EUR', 'CAD') self.assertIsInstance(rate, Decimal) self.assertGreater(rate, 1)
def test_availability_non_valid_token(self): """ Test case for using non valid authentication token for availability query """ travel = self.testdata['travel_data'] travel["travel"]["departureTimeEarliest"] = zulu.now().shift(days=2).\ replace(hour=14, minute=00).isoformat() headers = lippuclient.generate_headers( account_id=self.testdata['valid_client1'], token=str(uuid.uuid4()), language="fi") r = lippuclient.availability_request(self.envdata['base_url'], headers=headers, payload=travel) logging.info("test_availability_non_valid_token, response: %s" % (r.json())) self.assertEqual(r.status_code, 403)
def test_authenticate(self): """ Test case for successful authentication """ t = zulu.now() account_id = self.testdata['valid_client1'] response = lippuclient.authenticate(self.envdata['base_url'], str(uuid.uuid4()), account_id, self.testdata['key_id_client1'], self.testdata['key_path_client1'], lippuclient.ALG_RSA_SHA256) logging.info("test_authenticate, response is: %s" % response.text) self.assertEqual(response.status_code, 200) self.assertNotEqual(response.json()['token'], None) self.assertNotEqual(response.json()['expires'], None) self.assertEqual(response.json()['user'], account_id) self.assertEqual(zulu.parse(response.json()['expires']) > t, True) pass
def test_commit_auth(self): """ Test case for successful init_auth and commit_auth """ t = zulu.now() account_id = self.testdata['valid_client1'] headers = lippuclient.generate_headers(account_id=account_id) r_init = lippuclient.authentication_init_request( self.envdata['base_url'], headers, account_id) #r_init = requests.post(self.envdata['auth_url'] + '/init', # headers=headers, json={'account': account_id}) logging.info("test_commit_auth, response for init: %s" % r_init.text) self.assertEqual(r_init.status_code, 200) self.assertNotEqual(r_init.json()['nonce'], None) self.assertEqual(r_init.json()['user'], account_id) self.assertNotEqual(r_init.json()['expires'], None) self.assertEqual(zulu.parse(r_init.json()['expires']) > t, True) # Commit authentication and receive authentication token. headers['X-Message-Id'] = str(uuid.uuid4()) r_commit = lippuclient.authentication_commit_request( self.envdata['base_url'], headers, r_init.json()['nonce'], self.testdata['key_id_client1'], self.testdata['key_path_client1'], lippuclient.ALG_RSA_SHA256) logging.info("test_commit_auth, response for commit: %s" % r_commit.text) self.assertEqual(r_commit.status_code, 200) self.assertNotEqual(r_commit.json()['token'], None) self.assertNotEqual(r_commit.json()['expires'], None) self.assertEqual(r_commit.json()['user'], account_id) self.assertEqual(zulu.parse(r_commit.json()['expires']) > t, True) self.assertEqual( zulu.parse(r_commit.json()['expires']) > zulu.parse( r_init.json()['expires']), True) pass
def is_market_open(market: str) -> bool: """Checks is the specified market is currently open :returns bool""" today = str(d.date.today()) try: # times given in zulu market_hours = rs.markets.get_market_hours(market, today) open_time = d.datetime.strptime( str(market_hours['opens_at'][0:19:1]).replace('T', ' '), '%Y-%m-%d %H:%M:%S') # close time close_time = d.datetime.strptime( str(market_hours['closes_at'][0:19:1]).replace('T', ' '), '%Y-%m-%d %H:%M:%S') # current time current_time = d.datetime.strptime( str(z.now())[0:19:1].replace('T', ' '), '%Y-%m-%d %H:%M:%S') if open_time <= current_time < close_time: return True else: return False except Exception: raise Exception
def test_availability_invalid_accessibility(self): """ Test case for a availability query with invalid accessibility feature. Reads the travel properties from test-data.json, sets the travel departureTimeEarliest to next monday at 11:00Z. Expects response with zero travel availabilities. """ # Trip availaibility inquiry travel = self.testdata['travel_data_accessibility'] travel["passengers"][0]["accessibility"][0][ "title"] = "TESTING_ACCESSIBILITY" product = self.testdata['test_products_current_date_response'] t = datetime.datetime.now() travel["travel"]["departureTimeEarliest"] = zulu.now().shift(days=(7 - t.weekday())). \ replace(hour=11, minute=00).isoformat() r = lippuclient.availability_request(self.envdata['base_url'], headers=self.headers, payload=travel) logging.info( "test_availability_invalid_accessibility, availability response: %s" % r.json()) self.assertEqual(r.status_code, 400)
def main(): #login first login() #define the stock we are going to use #ticker symbol stock = "HEXO" while (True): #gets the current time timeNow = str(zulu.now()) if (availableForTrading(timeNow) and dayTrading()): #current stock price of the stock provided currentStockPrice = trader.stocks.get_latest_price(stock) logClosingPrice(timeNow, stock) movingAverage(json, stock) if (conditionToBuy and checkBalance > currentStockPrice): buy() else: print("cant buy")
def last_updated_default(self): now = zulu.now() return now - timedelta(minutes=5)
import zulu import timedelta now = zulu.now() past = now - timedelta(days - 30) print(past)
def wrapper(self, *args, **kwargs): if self.last_updated + timedelta(minutes=5) < zulu.now(): self.refresh() return func(self, *args, **kwargs)
def test_reservation_do_not_include_accessibility(self): """ Test case for reservation with leaving out accessibility requirements that were in availability request. """ t = datetime.datetime.now() travel = self.testdata['travel_data_accessibility'] travel["travel"]["departureTimeEarliest"] = zulu.now().shift(days=(7 - t.weekday())). \ replace(hour=14, minute=00).isoformat() logging.info( "test_reservation_do_not_include_accessibility, availability request: %s" % travel) r_availability = lippuclient.availability_request( self.envdata['base_url'], headers=self.headers, payload=travel) logging.info( "test_reservation_do_not_include_accessibility, availability response: %s" % r_availability) self.assertEqual(r_availability.status_code, 200) self.assertGreater(len(r_availability.json()), 0) # Make reservation self.headers['X-Message-Id'] = str(uuid.uuid4()) travel_entitlement_id = r_availability.json( )['availability'][0]['travelEntitlementId'] accessibility_id = r_availability.json( )['availability'][0]['applicableForPassengers'][0]['accessibility'][0][ 'accessibilityReservationId'] reservation = { 'reservations': [{ 'travelEntitlementId': travel_entitlement_id, 'chosenAccessibilityReservationIds': [], 'customerInfo': [self.testdata['customer_info']] }] } logging.info("Sending reservation %s" % reservation) r_reservation = lippuclient.reservation_request( self.envdata['base_url'], headers=self.headers, payload=reservation) logging.info( "test_reservation_do_not_include_accessibility, reservation response %s" % r_reservation.text) self.assertEqual(r_reservation.status_code, 200) self.assertNotEqual(r_reservation.json()['caseId'], None) self.assertNotEqual(r_reservation.json()['caseId'], '') self.assertNotEqual(r_reservation.json()['confirmedReservations'], None) self.assertEqual( r_reservation.json()['confirmedReservations'][0] ['travelEntitlementId'], travel_entitlement_id) caseId = r_reservation.json()['caseId'] # Test that reservation does not have the accessibility features in # the reservation request. self.headers['X-Message-Id'] = str(uuid.uuid4()) r = lippuclient.travel_entitlement_status( self.envdata['base_url'], headers=self.headers, travel_entitlement_id=travel_entitlement_id) logging.info( "test_reservation_do_not_include_accessibility, travel entitlement response %s" % r_reservation.text) self.assertEqual(r.json()['travelEntitlementId'], travel_entitlement_id) self.assertEqual(r.json()['accessibility'], [])
def test_reservation_extra_services_accessibility(self): """ Test case for reservation with extra services and accessibility requirements """ t = datetime.datetime.now() travel = self.testdata['travel_data_extra_services'] travel['passengers'][0]['accessibility'] = [{"title": "LOW-FLOOR"}] travel["travel"]["departureTimeEarliest"] = zulu.now().shift(days=(7 - t.weekday())). \ replace(hour=14, minute=00).isoformat() r_availability = lippuclient.availability_request( self.envdata['base_url'], headers=self.headers, payload=travel) logging.info( "test_reservation_extra_services_accessibility, availability response: %s" % r_availability) self.assertEqual(r_availability.status_code, 200) self.assertGreater(len(r_availability.json()['availability']), 0) # Make reservation self.headers['X-Message-Id'] = str(uuid.uuid4()) travel_entitlement_id = r_availability.json( )['availability'][0]['travelEntitlementId'] extra_service_id = r_availability.json()['availability'][0]\ ['applicableForPassengers'][0]['extraServices'][0]['extraServiceReservationId'] accessibility_id = r_availability.json()['availability'][0]\ ['applicableForPassengers'][0]['accessibility'][0]['accessibilityReservationId'] reservation = { 'reservations': [{ 'travelEntitlementId': travel_entitlement_id, 'chosenExtraReservationIds': [extra_service_id], 'chosenAccessibilityReservationIds': [accessibility_id], 'customerInfo': [self.testdata['customer_info']] }] } logging.info("Sending reservation %s" % reservation) r_reservation = lippuclient.reservation_request( self.envdata['base_url'], headers=self.headers, payload=reservation) logging.info("test_reservation_extra_services_accessibility, " "reservation response %s" % r_reservation.text) self.assertEqual(r_reservation.status_code, 200) self.assertNotEqual(r_reservation.json()['caseId'], None) self.assertNotEqual(r_reservation.json()['caseId'], '') self.assertNotEqual(r_reservation.json()['confirmedReservations'], None) self.assertEqual( r_reservation.json()['confirmedReservations'][0] ['travelEntitlementId'], travel_entitlement_id) caseId = r_reservation.json()['caseId'] # Test that reservation has the extra service and accessibility # requirements reserved in the reservation request. self.headers['X-Message-Id'] = str(uuid.uuid4()) r = lippuclient.travel_entitlement_status( self.envdata['base_url'], headers=self.headers, travel_entitlement_id=travel_entitlement_id) logging.info("test_reservation_extra_services_accessibility, " "travel entitlment response %s" % r_reservation.text) self.assertEqual(r.json()['travelEntitlementId'], travel_entitlement_id) self.assertEqual( r.json()['extraServices'][0]['extraServiceReservationId'], extra_service_id) self.assertEqual( r.json()['accessibility'][0]['accessibilityReservationId'], accessibility_id)
def login(): #login using the login #=============================================== #u need the 2FA to login whenever it asks trader.login( #checks the balance by loading the account and returning the buying power def checkBalance(): #dictionary with all the account data dictionary = trader.profiles.load_account_profile() return dictionary["buying_power"] #access the users portfolio #pulls all the stocks currently owned by the trader def traderStocks(json, stock): dictionary = trader.account.get_current_positions() dictDump = {} for item in dict: i = 1 if( str(trader.get_name_by_url(item['instrument'])) == str(trader.get_name_by_symbol(stock)[0])): dictDump[str(trader.get_name_by_url(item['instrument'])).upper()] = str(i) i+=1 return amount #get prices for the past week ##prices are logged every 10 minutes since the market opens ##logs from 9:30am to 4:00pm #checks the current time #calulates the next time it needs to log #checks if the current time matches the next logging time #if true then it logs #if false then it doesn't def logClosingPrice(json, timeNow, stock): #the ticker symbol #can be day week year or 5year #extended or regular #this is all the data for a specific stock for a week allDataDictionary = trader.stocks.get_historicals(stock, span = "week", bounds = "regular") #parses to get a list with just the closing price for i in range(len(allDataDictionary)): dataPriceList.append(allDataDictionary[i]["close_price"]) #opens the json file with the closing prices as per 10 mins with open('Pricesper10min.json') as json_file: closingPricesWeekDictionary = json.load(json_file) #the moving average is calculated every 10 minutes #if the current minute is a ten then its time to log logNow = False currentMinute = timeNow[14:16] if (str(currentMinute[1:2]) == "0"): logNow = True #checks if the time now is the proper logging time if (logNow): #this will format the date to match the others and then add it to the dictionary dateFormated = timeNow[0:16]+":00Z" latestPrice = str(trader.get_latest_price(stock)) closingPricesWeekDictionary[dateFormated] = latestPrice[2:10] #opens json file with the closing prices with open('Pricesper10min.json', 'w') as outfile: json.dump(closingPricesWeekDictionary, outfile, indent = 4) #open the prices per 10 minutes file #read from the file #creates a list with all the closing prices #calculate the moving average for the entire json file #compile a dictionary with all the moving averages #export all that data to the moving averages json file def movingAverage(json): #opens the json file with the closing prices as per 10 mins with open('Pricesper10min.json') as json_file: closingPricesWeekDictionary = json.load(json_file) dataPriceList = [] for key in closingPricesWeekDictionary: dataPriceList.append(closingPricesWeekDictionary[key]) datePriceList = [] for key in closingPricesWeekDictionary: datePriceList.append(key) #moving average calculation SimpleMovingAverageDictionary = {} for i in range(len(dataPriceList)-5): SMA = 0 for t in range(i,i+5): SMA += float(dataPriceList[t]) SMA = SMA / 5 SimpleMovingAverageDictionary[datePriceList[i+5]] = str(SMA) #The finished dictionary ready for json dumping with open('MovingAverage.json', 'w') as outfile: json.dump(SimpleMovingAverageDictionary, outfile, indent = 4) json_file.close() outfile.close() #checks the time #opens the blacklisted dates #checks if the date is on a blaclisted date #checks if the time is when the stock market is open def availableForTrading(timeNow): #opens the json file with the blacklisted dates with open('BlacklistedDates.json') as json_file: blacklistedDatesDictionary = json.load(json_file) json_file.close() #checks if the stock market is open by making sure it is not a blacklisted date for date in blacklistedDatesDictionary: if( str(timeNow[0:10]) == str(date) ): return False #checks if time is between 9:30am and 4:00pm hourAndMinute = int(timeNow[11:13] + timeNow[14:16]) if(hourAndMinute < 1430 or hourAndMinute > 2059): return False else: return True #opens the moving average json file #opens the latest prices json file #checks if the last price crosses the last moving average from bottom to top #if true then buy def conditionToBuy(json, currentTime, stock, currentStockPrice): #opens the json file with the moving average with open('MovingAverage.json') as json_file: MovingAverageDictionary = json.load(json_file) #open file to gather the last few prices with open('Pricesper10min.json') as json_file: Pricesper10min = json.load(json_file) MovingAverages = [] lastMovingAveragePrice = 0 #finds the last moving average price for key in MovingAverageDictionary: MovingAverages.append(MovingAverageDictionary[key]) lastMovingAveragePrice = MovingAverages[len(MovingAverages)-1] pricesLast10min = [] for key in MovingAverageDictionary: pricesLast10min.append(Pricesper10min[key]) lastPrice = pricesLast10min[len(pricesLast10min)-1] secondTolastPrice = pricesLast10min[len(pricesLast10min)-2] if (lastPrice > lastMovingAveragePrice and secondTolastPrice < lastMovingAveragePrice): buy(json, currentTime, stock, currentStockPrice) return True else: return False def buy(json, currentTime, stock, currentStockPrice): #executes the buy operation for the corresponding stock trader.orders.order_buy_limit(stock, 1, lastPrice) #open file to gather previous trades with open('buyLog.json') as json_file: Log = json.load(json_file) #adds the current time of the log and price and adds it to the list #time format 2020-01-11T20:19:00.000000+00:00 logTime = currentTime[0:19] + "Z" Log[logTime] = str(currentStockPrice) #writes to the json file with open('buyLog.json', 'w') as outfile: json.dump(Log, outfile, indent = 4) #opens the moving average json file #opens the latest prices json file #checks if the last price crosses the last moving average from bottom to top #if true then buy def conditionToSell(json, currentTime, stock, currentStockPrice): #opens the json file with the moving average with open('MovingAverage.json') as json_file: MovingAverageDictionary = json.load(json_file) #open file to gather the last few prices with open('Pricesper10min.json') as json_file: Pricesper10min = json.load(json_file) MovingAverages = [] lastMovingAveragePrice = 0 #finds the last moving average price for key in MovingAverageDictionary: MovingAverages.append(MovingAverageDictionary[key]) lastMovingAveragePrice = MovingAverages[len(MovingAverages)-1] pricesLast10min = [] for key in MovingAverageDictionary: pricesLast10min.append(Pricesper10min[key]) lastPrice = pricesLast10min[len(pricesLast10min)-1] secondTolastPrice = pricesLast10min[len(pricesLast10min)-2] if (lastPrice > lastMovingAveragePrice and secondTolastPrice < lastMovingAveragePrice): buy(json, currentTime, stock, currentStockPrice) return True else: return False # def sell(json, currentTime, stock, currentStockPrice): #executes the buy operation for the corresponding stock trader.orders.order_sell_limit(stock, 1, lastPrice) #open file to gather previous trades with open('sellLog.json') as json_file: Log = json.load(json_file) #adds the current time of the log and price and adds it to the list #time format 2020-01-11T20:19:00.000000+00:00 logTime = currentTime[0:19] + "Z" Log[logTime] = str(currentStockPrice) #writes to the json file with open('sellLog.json', 'w') as outfile: json.dump(Log, outfile, indent = 4) def main(): #login first login() #define the stock we are going to use stock = "HEXO" while (True): timeNow = str(zulu.now()) if(availableForTrading(timeNow)): currentStockPrice = trader.stocks.get_latest_price(stock) logClosingPrice(timeNow, stock) movingAverage(json, stock) main()
def refresh(self): """Refresh rates and update last_updated timestamp.""" self._rates = self._rates_refresh() self.last_updated = zulu.now()
def __init__(self, person_id, activity_id): self.person_id = person_id self.activity_id = activity_id self.post_id = str(uuid.uuid4()) self.post_content = base64.b64encode(self.person_id.encode('utf-8')) self.post_timestamp = zulu.now()