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)
"\n\nSince you have picked the present year and month, the file will only print up to today's date :)" ) for i in range(day_difference): count = i day = real_date1 + timedelta( days=count) # we now have all the dates of month str_day = day.strftime(date_format) with open(file_name, mode="rt", encoding="utf8") as g, \ open(file_name, mode="at", encoding="utf8") as f: f.write(str(str_day) + ",") cnt = 0 code_cnt = 0 for code in new_list: # 'GBP','EUR','CAD' cnt += 1 for key, value in sorted(exrates.get_exrates(str_day).items()): if key == code: # writes the rate on file code_cnt += 1 if len(new_list) == cnt: f.write(str(value) + "\n") else: f.write(str(value) + ",") if code_cnt == 0: if len(new_list) == cnt: f.write("-" + "\n") # writes '-' on file else: f.write("-,")
encoding="utf8") as histFile: histWriter = csv.writer(histFile, delimiter=",") #Write the first row of titles in the created file. histFile.write("Date, {}\n".format(",".join(currLst))) #Going through every day between date1 and date2. while date1 <= date2: finish = False tempLst = list() if date1 == date2: finish = True #Write the current date. histFile.write("{},".format(date1.strftime(date_format))) #Get the exchange rates data for the current date. ratesDict = ex.get_exrates(date1.strftime(date_format)) #If there is data for the codes on currLst on that date, write them in the file. #Else write "-" instead. for i in range(len(currLst)): if currLst[i] in ratesDict: tempLst.append(ratesDict[currLst[i]]) else: tempLst.append("-") histFile.write("{}\n".format(",".join(tempLst))) if finish: break #Write the current date. histFile.write("{},".format(date1.strftime(date_format))) #Get the exchange rates data for the current date. ratesDict = ex.get_exrates(date1.strftime(date_format))
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
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: k_curr = key v_curr = value # assigns new names for currency
A pandas module object (A data frame) that is used to read from the csv file 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
"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: k_curr = key v_curr = value # assigns new names for currency
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)) except ValueError: print("\nDear sir, please make sure you input in right format")
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
print("\n\nSince you have picked the present year and month, the file will only print up to today's date :)") for i in range(day_difference): count = i day = real_date1 + timedelta(days=count) # we now have all the dates of month str_day = day.strftime(date_format) with open(file_name, mode="rt", encoding="utf8") as g, \ open(file_name, mode="at", encoding="utf8") as f: f.write(str(str_day) + ",") cnt = 0 code_cnt = 0 for code in new_list: # 'GBP','EUR','CAD' cnt += 1 for key, value in sorted(exrates.get_exrates(str_day).items()): if key == code: # writes the rate on file code_cnt += 1 if len(new_list) == cnt: f.write(str(value) + "\n") else: f.write(str(value) + ",") if code_cnt == 0: if len(new_list) == cnt: f.write("-" + "\n") # writes '-' on file else: f.write("-,")
for element in currLst] #uppercasing all currLst elemnts. with open("{}.csv".format(file_name), mode="wt", encoding="utf8") as hmgFile: hmgWriter = csv.writer(hmgFile, delimiter=",") hmgFile.write("Date, {}\n".format(",".join(currLst))) # Starting calculating the change from day two. date = date + timedelta(days=1) #Going through every day between date and until_date. while date < until_date: tempLst = list() #Write the current date in the current row hmgFile.write("{},".format(date.strftime(date_format))) #Getting the exchange rates data for the current day and the previous one. PreratesDict = ex.get_exrates( (date - timedelta(days=1)).strftime(date_format)) ratesDict = ex.get_exrates(date.strftime(date_format)) # Going through every currency code in currLst. # If there is data of exchange rate for the currency for the current date # and the previous one, compute the change pecentage. # If not, consider it as zero change. for i in range(len(currLst)): if currLst[i] in ratesDict and currLst[i] in PreratesDict: tempLst.append( str((float(ratesDict[currLst[i]]) / float(PreratesDict[currLst[i]]) - 1) * 100)) else: tempLst.append("0") hmgFile.write("{}\n".format(",".join(tempLst))) date = date + timedelta(days=1)
for i in range(len(currLst)): # A temporary float veriable to store the minimum change of a certain currency. minChange = 0.0 # A temporary float veriable to store the minimum change of a certain currency. maxChange = 0.0 # A temporary float veriable to store the difference between the maximum value # of a certain currency compared to the value on 'date1'. maxDiff = 0.0 # A temporary float veriable to store the difference between the max and min change. difference = 0.0 #Finding the Maximal change while tempDate <= date2: # Setting dictionries of exchange rates for a current day and the previous. PreRatesDict = ex.get_exrates(date1.strftime(date_format)) RatesDict = ex.get_exrates(tempDate.strftime(date_format)) #The currency code must exist in the exchange rates dictionaries, #else it get zero as a value because there was no currency and the difference is zero. if currLst[i] in RatesDict and currLst[i] in PreRatesDict: #Every time 'tempDate' changes, 'todayChange' gets updated too. #The change is represented with %. todayChange = abs(float(RatesDict[currLst[i]])/float(PreRatesDict[currLst[i]])-1)*100 #Every time there is a change bigger than maxChange, update maxChange. if maxChange < todayChange: maxChange = todayChange maxDiff = float(RatesDict[currLst[i]]) - float(PreRatesDict[currLst[i]])