def main(): '''main to test the program: inputs a date, and prints the list of currencies for which there is a date, in format requested ''' datetext = input("Greetings User! please enter a date:") #value vaildation using the function above, loop untill correct format, with mentioning problem while inputdate(datetext) == False: #printing error! sys.stderr.write( "\Value Error! invalid input-choose an available date\n") datetext = input( " Let's give it another try! " + "\n" + " please enter a date:" + '\n' + " i.e. 'YYYY-MM-DD' stracture, an exsample for a vaild format is 2017-03-11" + '\n') inputdate(datetext) #using the date the user entered, to withdraw the dictionery from exrates file, get_exrate fuction and sorted by code. date_Rates = sorted(exrates.get_exrates(datetext)) #marging two dictionery, to get the name and code in one dictionery curlist = exrates.get_currencies() #the format requested format_list = '{name} ({code})' #creating the list, using the format above, while check every code in the updated code list Final_list = [ format_list.format(name=curlist.get(code, "<unknonwn>"), code=code) for code in date_Rates ] print('\nHere is a list of correncies available to ' + datetext + " : \n") #print the values of the list print('\n'.join(Final_list))
def main(): ''' inputs two integers - year and mouth.later, it inputs currencies code. the program is builting a graph, of the month and the currencies change in percentage relative to the USD ''' while True: try: #getting the current year now_year = datetime.datetime.now().year #input the year, and vaild it year = input("Type in the year with four digits: ") #assuming no dates befor 2000 has history while valid_number(year, now_year) == False or year.isdigit( ) == False or int(year) < 2000: year = input( "somthing wen't wrong....\n Type in the year with four digits: " ) #getting the current month now_month = datetime.datetime.now().month #input the month, and vaild it month = input("Type in the month with two digits: ") while valid_number(month, now_month) == False or month.isdigit() == False: month = input( "somthing wen't wrong....\n Type in the month with two digits: " ) #the currect month is yet to publish all the exchange rate, therefor a edge case..... while int(year) == int(now_year) and int(month) >= int(now_month): print("funny! you tried seeing the future?! try again....") month = input( "somthing wen't wrong....\n Type in the month with two digits: " ) while valid_number( month, now_month) == False or month.isdigit() == False: month = input( "somthing wen't wrong....\n Type in the month with two digits: " ) #vaild the currencies currencies = exrates.get_currencies() currency_lst = str( input("enter currency codes: separate them with comma (,)\n")) currency_fix_lst = currency_lst.upper().split(",") #remove spaces currency_fix_lst = [cur.strip(' ') for cur in currency_fix_lst] #only 3 values key for currency, and making sure the currency exists while all( currency.strip(" ") not in currencies for currency in currency_fix_lst) == True: #as requested to use sys.stderr.write( "\nsomthing went wrong! are you sure its a vaild currency? - try again\n" ) #input the currencies requested again, if cur dosent exists currency_lst = str( input( 'try entering a comma-separated code and space\n i.e. "ILS, USD" is the correct format\n' )) currency_fix_lst = currency_lst.upper().split(",") #remove spaces currency_fix_lst = [cur.strip(' ') for cur in currency_fix_lst] #getting the file name for later - creation of file file_name = input("in which name you wish to save the graph?: \n") year = int(year) month = int(month) #start day as the first of each month, end date as the last start_dateF = datetime.date(year, month, int(1)) end_dateF = datetime.date( year, month, int(calendar.monthrange(year, month)[-1])) #creating pandas database daterange = date_range(start_dateF, end_dateF) #for each currency, loop by date, to fill all the delta between the dates above for each_currency in currency_fix_lst: #deleting empty space for a vaild format each_currency = each_currency.strip(" ") if each_currency in currencies: #getting the rates of the day exrates_base = exrates.get_exrates( start_dateF.strftime("%Y-%m-%d")) #list of x values to the plt - dates date_val = [] #list of y values to the plt - currencies values exchange_val = [] #loop over dates, using oandas module for date in daterange: #as long as the date in a vaild logical stracture date_str = date.strftime("%Y-%m-%d") #get the exchange rates for the date in the correct format exrates_date = exrates.get_exrates(date_str) #list of dates in month date_val.append(date.strftime("%Y-%m-%d")) if each_currency in exrates_base and each_currency in exrates_date: diff_val = (float(exrates_date[each_currency]) / float(exrates_base[each_currency]) - 1) * 100 exchange_val.append(diff_val) else: exchange_val.append(0) #moving to the next values, to save the previous exrates_base = exrates_date #creating the graph for each currency, with label plt.plot(exchange_val, label=each_currency) #plot creating #setting x values regarding the date entered earlier plt.xlim(0, calendar.monthrange(year, month)[-1]) #nicer visuallisation for the graph plt.grid(True) plt.title('History of one Month Graph changes') plt.legend() plt.ylabel('Change in (%)') plt.xlabel('Days of : ' + str(year) + '/' + str(month)) #saving the graph as .png file plt.savefig(os.path.join('data', '{}.png'.format(file_name))) print('{}.png'.format(file_name) + ' was succesfully created!') break except ValueError as V: print(V)
def main(): ''' main program that inputs two dates, an amount, and codes of two currencies. it then prints a table, with the amount converted between those currencies, in both directions ''' while True: try: #input values, the time preiod to convert, the amount and the currencies basic_date = input("Please enter first date: ") #value vaildation using the function above, loop untill correct format, with mentioning problem while inputdate(basic_date) == False: basic_date = input( " ValueError! Let's give it another try! " + "\n" + " please enter a date:" + '\n' + " i.e. 'YYYY-MM-DD' stracture, an exsample for a vaild format is 2017-03-11" + '\n') inputdate(basic_date) end_date = input("Please enter second date: ") #value vaildation using the function above, loop untill correct format, with mentioning problem while inputdate(end_date) == False: end_date = input( " ValueError! Let's give it another try! " + "\n" + " please enter a date:" + '\n' + " i.e. 'YYYY-MM-DD' stracture, an exsample for a vaild format is 2017-03-11" + '\n') inputdate(end_date) while True: amount = input("Enter the amount you wish to convert: ") try: val = float(amount) if val < 0: # if not a positive int print message and ask for input again print( "Sorry, input must be a positive amount, try again" ) continue break except ValueError: print("come on! I asked for an amount.. not string") #vaild the currencies currencies = exrates.get_currencies() currency_lst = str( input( "enter two currency codes: separate them with comma (,)\n") ) currency_fix_lst = currency_lst.upper().split(",") #remove spaces currency_fix_lst = [cur.strip(' ') for cur in currency_fix_lst] #only 3 values key for currency, and making sure the currency exists while all(currency.strip() not in currencies for currency in currency_fix_lst) == True or len(currency_fix_lst) != 2: #as requested to use sys.stderr.write( "\nsomthing went wrong! are you sure its two vaild currencies? - try again\n" ) #input the currencies requested again, if cur dosent exists currency_lst = str( input( 'try entering two currencies with a comma-separated\n i.e. "ILS, USD" is the correct format\n' )) currency_fix_lst = currency_lst.upper().split(",") #creating currencies in the correct format first_cur = str(currency_fix_lst)[2:5] sec_cur = str(currency_fix_lst[::-1])[2:5] #using the function above to return values in table data = convert_time_period(float(amount), first_cur, sec_cur, basic_date, end_date) print( "\n Here is a list of convertion between two currencies, amount converted: " + amount + " \n") print("Date", '{0:>30}'.format(first_cur + '#To#' + sec_cur), '{0:>30}'.format(sec_cur + '#To#' + first_cur)) for key, line in data.items(): print(key, '{0:>30}'.format(line[0]), '{0:>30}'.format(line[1])) break except ValueError: print('ohhhhh.......there has been a Value Error.... try again!') break
sec_realdate = datetime.strptime(sec_date, date_format) day_difference = (sec_realdate - real_date1).days string = input( "Enter a list of currency codes with no spaces e.g. (GBP,eur,cAd): " ) # makes sure it is a string list_ = string.split(",") L = list() for i in list_: i = i.upper() L.append(i) b = sorted(exrates.get_currencies().items() ) # imports the currency list, only these currencies will be saved new_list = list() cnt = 0 for code in L: # 'GBP', 'EUR', 'CAD' for key, value in b: if key == code: cnt += 1 new_list.append(code) if cnt == 0: sys.stderr.write( "Error! The input is invalid, please choose at least one valid currency code" ) sys.exit(1) # stops program print()
#!/usr/bin/env python3 """ Created on Tue Aug 11 14:50:23 2015 @author: Ben Longbottom-Smith Prints the list of all the supported currencies and their codes in a tabular form, with the names in the first column and their respective codes in the second one, sorted by their names. The data has to be retrieved using the get_currencies function. """ import exrates b = sorted(exrates.get_currencies().items()) # uses 'get_currencies' function empty_dic = dict() for key, value in b: tmp = value value = key # swaps my key and value items over key = tmp empty_dic[key] = value good_dic = sorted(empty_dic.items()) # sorted by 'names' now print("All the supported currencies:\n") space = 37 - len(str("Name")) print("Name" + space*" " + " | " + "Code") print(len(str("Name" + space*" " + " | " + "Code"))*"-")
"Please enter all currencies' codes you want to check (comma-separated): " )) file_name = str( input( "Please enter a path or just a file name to store the data: ")) # If date1 is later, switch the values between date1 and date2 if date1 > date2: tempdate = date2 date2 = date1 date1 = tempdate # Getting reed of any unnecessary white sapces in currLst. currLst = (" ".join(currLst.split(","))).split() currDict = ex.get_currencies() fixed_currLst = list( ) # A new list to store only the currencies that exist in currencies list (currDict). # Every currency that did not ever exist we ignore. we add only existent currency codes. for i in range(len(currLst)): if currLst[i].upper() in currDict: fixed_currLst.append(currLst[i]) # updating currLst and adding only existent currencies. currLst = fixed_currLst # If there are no valid currencies, the input is considered invalid. if currLst == list(): raise ValueError() #Uppercasing all currLst's values. currLst = [element.upper() for element in currLst]
def main(): '''to preform the main: inputs two dates, and codes of two currencies and a file name created a file of cscv of the given name. saves exchange rates on the given time period ''' while True: try: #input date parameters start_date = input("enter the start date: ") while inputdate(start_date) == False: start_date = input( " ValueError! Let's give it another try! " + "\n" + " please enter a date:" + '\n' + " i.e. 'YYYY-MM-DD' stracture, an exsample for a vaild format is 2017-03-11" + '\n') inputdate(start_date) end_date = input("enter the end date: ") while inputdate(end_date) == False: end_date = input( " ValueError! Let's give it another try! " + "\n" + " please enter a date:" + '\n' + " i.e. 'YYYY-MM-DD' stracture, an exsample for a vaild format is 2017-03-11" + '\n') inputdate(end_date) #vaild the currencies currencies = exrates.get_currencies() currency_lst = str( input( "enter two currency codes: separate them with comma (,)\n") ) currency_fix_lst = currency_lst.upper().split(",") #remove spaces currency_fix_lst = [cur.strip(' ') for cur in currency_fix_lst] while all( currency.strip(" ") not in currencies for currency in currency_fix_lst) == True: #as requested to use sys.stderr.write( "\nsomthing went wrong! invalid currency - try again\n") #input the currencies requested again, if cur dosent exists, one currect currency is enoght currency_lst = str( input( 'wait a Minute! are you sure its a vaild currency?\n try entering a comma-separated code \n i.e. "ILS, USD" is the correct format' )) currency_fix_lst = currency_lst.upper().split(",") #input the file requested name file_name = input("choose a file name: ") with open(os.path.join('data', '{}.csv'.format(file_name)), mode="wt", encoding="utf8") as file_name: file_name.write('Date,') for currency in currency_fix_lst: #deleting empty space for a vaild format currency = currency.strip(" ") #write only the currencies available if currency in currencies: file_name.write(str(currency)) file_name.write(",") #allowing new input for the loop file_name.write("\n") #vaild the order of the input dates start_dateF, end_dateF = chron_time(start_date, end_date) #loop over dates, using oandas module daterange = pd.date_range(start_dateF, end_dateF) #loop by date, to fill all the delta between the dates above for date in daterange: #as long as the date in a vaild logical stracture date_str = date.strftime("%Y-%m-%d") exrates_date = exrates.get_exrates(date_str) #insert to the file the requested values file_name.write(str(date_str)) #to each of the currency for currency1 in currency_fix_lst: #deleting empty space for a vaild format currency1 = currency1.strip(" ") if currency1 in currencies: file_name.write(",") if currency1 not in exrates_date: file_name.write("-") else: file_name.write(str(exrates_date[currency1])) #moving to the next value in the time periot requested file_name.write("\n") print("successfully created! go to data folder to check") except ValueError: #bad format Value print( "ohh ohhh......Value Error - are you sure the date exists? try again..." ) continue else: break
if real_date <= present_date: # checks if date is in the future break else: print("Date must not be in the future! Time travel is impossible :) \n" ) pass except ValueError: if some_date == "": some_date = time.strftime("%Y-%m-%d") # current date break else: print("Not a valid date! Enter another :) \n") pass print() b = sorted(exrates.get_currencies().items()) a = sorted(exrates.get_exrates(some_date).items()) curr_dic = dict() for key, value in b: tmp = value value = key # swaps my currency key and value items over key = tmp curr_dic[key] = value curr_dic = sorted(curr_dic.items()) # sorted by name empty_dic = dict() for key, value in curr_dic:
that was created earlier (ertFile). then it is sorted by the currency codes and displayed in a tabular form. """ import os, csv, urllib3 import exrates as ex import pandas as pd while True: try: date = str(input("Please enter a year in 'YYYY/MM/DD' format: ")) #forming the requested date in the right format ex.get_exrates(date) #creating an exrates file (if isn't there one already) currencyDict = ex.get_currencies() #All currencies dictionary #reading from the created exchange rates file and writing to a new ert file. #the ert file will eventually be the output data. with open(os.path.join("data","rates-{}.csv".format(date)), mode="rt", encoding="utf8") as exFile,\ open(os.path.join("data","ert-{}.csv".format(date)), mode="wt",encoding="utf8") as ertFile: exReader = csv.reader(exFile, delimiter = ",") #creating a "reader" object for "rates-..." file. exFile.readline() ertWriter = csv.writer(ertFile , delimiter = ",")#creating a "writer" object for ertFile. ertFile.write("Name (code), Exchange Rate\n") #Adding column titles for row in exReader: #going through every row in the exchange rate file. [code, exrate] = row noData = True for key in currencyDict:
exratesDict: Dictionary A dictionary of all exchange rates that exist on a certain date. noData: Boolean A veriable that if it's True, it means there is no data for a certain currency on a given date. If it's False then it means we found data for the currency. """ import pprint, urllib3 import exrates as ex while True: try: date = str(input("Please enter a year in 'YYYY/MM/DD' format: ")) currencyDict = ex.get_currencies() # Getting the currencies' list. exratesList = sorted(ex.get_exrates( date)) # Getting a sorted exchange rates data for the given date. for el in exratesList: #Going through every currency code (key) in the exrates dictionary. noData = True for key in currencyDict: #Comparing every code on exratesList to the codes (keys) on currencyDict. if el == key: #If the data exists, print it's name and code. set the noData to False because there is data. print("{} ({})".format(currencyDict[key], key)) noData = False break #If there is no data for a certain currency print this: if noData == True: print("<unknown> ({})".format(el))
def main(): '''main to test the program - the program allowing the user to enter 2 dates, it then will calculate for each date between them the change in precents, and finally will print the extremes value in the given time periot ''' while True: try: #input date parameters start_date = input("enter the start date: ") while inputdate(start_date) == False: start_date = input( " ValueError! Let's give it another try! " + "\n" + " please enter a date:" + '\n' + " i.e. 'YYYY-MM-DD' stracture, an exsample for a vaild format is 2017-03-11" + '\n') inputdate(start_date) end_date = input("enter the end date: ") while inputdate(end_date) == False: end_date = input( " ValueError! Let's give it another try! " + "\n" + " please enter a date:" + '\n' + " i.e. 'YYYY-MM-DD' stracture, an exsample for a vaild format is 2017-03-11" + '\n') inputdate(end_date) #input the currencies requested currency_lst = str( input("enter a comma-separated list of currency codes: ")) currency_fix_lst = currency_lst.upper().split(",") #saving the currencies available using the module exrates currency_file = exrates.get_currencies() #remove spaces currency_fix_lst = [cur.strip(' ') for cur in currency_fix_lst] #vaildation for currencies entered, allowing capiral and lowers letters if all( currency.strip(" ") not in currency_file for currency in currency_fix_lst) == True: #as requested to use sys.stderr.write( "\nsomthing went wrong! invalid currency - try again\n") continue with open(os.path.join('data', 'analyze request.csv'), mode="wt", encoding="utf8") as diff_file: #begin writing in the file, the titles diff_file.write('Date,') for currency in currency_fix_lst: currency = currency.strip(" ") if currency in currency_file: diff_file.write(str(currency)) diff_file.write(",") #new line for the values diff_file.write("\n") #vaild the order of the input dates, with function start_dateF, end_dateF = chron_time(start_date, end_date) #loop over dates, using oandas module daterange = pd.date_range(start_dateF, end_dateF) #base to calculate all of the changes exrates_base_date = exrates.get_exrates(start_dateF) #loop by date, to fill all the delta between the dates above for date in daterange: #witdraw the rates for the requested date date_str = date.strftime("%Y-%m-%d") exrates_date = exrates.get_exrates(date_str) #insert to the file the requested values diff_file.write(date_str) #to each of the currency for coin in currency_fix_lst: #deleting empty space for a vaild format coin = coin.strip(" ") if coin in currency_file: diff_file.write(",") if coin in exrates_date and coin in exrates_base_date: diff = ( (float(exrates_date[coin]) / float(exrates_base_date[coin])) - 1) * 100 diff_file.write(str(diff)) else: #if currency dossent exists it will write - as requested diff_file.write("-") #moving the writing forward - new line for new date diff_file.write("\n") #saving last day list to calculate diff between each day and his previous... exrates_base_date = exrates_date user_date = pd.read_csv(os.path.join('data', 'analyze request.csv'), sep=',', encoding='utf8') #using a function te create the table as required design_table(user_date) except ValueError: #bad format Value print( "ohh ohhh......Value Error - are you sure the date exists? try again..." ) except PermissionError: print( "the file is probbly open, close it beform preforming this program" ) else: break
else: sec_date = (str(nxt_year) + "-" + str(nxt_mth) + "-01") sec_realdate = datetime.strptime(sec_date, date_format) day_difference = (sec_realdate - real_date1).days string = input("Enter a list of currency codes with no spaces e.g. (GBP,eur,cAd): ") # makes sure it is a string list_ = string.split(",") L = list() for i in list_: i = i.upper() L.append(i) b = sorted(exrates.get_currencies().items()) # imports the currency list, only these currencies will be saved new_list = list() cnt = 0 for code in L: # 'GBP', 'EUR', 'CAD' for key, value in b: if key == code: cnt += 1 new_list.append(code) if cnt == 0: sys.stderr.write("Error! The input is invalid, please choose at least one valid currency code") sys.exit(1) # stops program print() file_name = input("Enter a file name e.g. (including '.csv'): ") with open(file_name, mode="wt", encoding="utf8") as g: # need to re-save old data, then write more
#!/usr/bin/env python3 """ Created on Tue Aug 11 14:50:23 2015 @author: Ben Longbottom-Smith Prints the list of all the supported currencies and their codes in a tabular form, with the names in the first column and their respective codes in the second one, sorted by their names. The data has to be retrieved using the get_currencies function. """ import exrates b = sorted(exrates.get_currencies().items()) # uses 'get_currencies' function empty_dic = dict() for key, value in b: tmp = value value = key # swaps my key and value items over key = tmp empty_dic[key] = value good_dic = sorted(empty_dic.items()) # sorted by 'names' now print("All the supported currencies:\n") space = 37 - len(str("Name")) print("Name" + space * " " + " | " + "Code") print(len(str("Name" + space * " " + " | " + "Code")) * "-") for key, value in good_dic: