def get_forex(cur1="GBP", cur2="USD", folder="ETF_Analysis"): def get_date(d): return dt.datetime.strptime(d, '%Y-%m-%d') data = pd.read_csv(folder+'/All_data.csv', index_col=0) dates=list(data.index.values)[1:] filename = '/forex_{}_{}.csv'.format(cur1, cur2) try: forex = pd.read_csv(folder+filename) data_dates = list(forex.loc[:, "Date"]) for day, i in zip(dates, range(len(dates))): if day not in data_dates: print("Getting new rate: " + day) forex.loc[i] = [day]+[get_rate(cur1, cur2, get_date(day[:10]).date())] except FileNotFoundError as _: forex = pd.DataFrame(columns=["Date", "FX"]) for day, i in zip(dates, range(len(dates))): print("Getting rate for " + day) forex.loc[i] = [day]+[get_rate(cur1, cur2, get_date(day[:10]).date())] forex = forex.set_index("Date") forex.to_csv(folder+filename) return forex
def convert_cb(amount, curr, dt): converter = forex_python.converter.CurrencyRates() dt = datetime.datetime.utcfromtimestamp(dt) rate = converter.get_rate(curr, ACCOUNT_CURR, dt) return str( rate * float(amount) ) # Difference with PayPal rate ranges from 0.95 to 1.12, it's the same on average.
def rate_gen(self, to): if not type(to) == str: raise TypeError('to must be a string.') for x in self.date_spread: monthly_rates = [] for y in x: monthly_rates.append(get_rate(self.orig_curr, to, y)) self.rates.append(monthly_rates)
def getFxRates(): """Retrieve the current foreign exchange rates for USD and GBP""" forex = [] forex = get_rates('USD') forex = pd.DataFrame([forex], columns=forex.keys()) #self.forex.loc[:, 'GBP'] GBPUSD = forex['GBP'].values date_obj = datetime.datetime(2020, 5, 17) # print(date_obj) test = get_rate('USD', 'GBP', date_obj) # print(test) return GBPUSD
def get_forex(cur1="GBP", cur2="USD", folder="ETF_Analysis"): def get_date(d): # Convert string date format to datetime return dt.datetime.strptime(d, '%Y-%m-%d') # Get the data collected so far and extrapolate the dates data = pd.read_csv(folder + '/All_data.csv', index_col=0) dates = list(data.index.values)[1:] # Set filename between the two currencies (GBP --> USD) filename = 'forex_{}_{}.csv'.format(cur1, cur2) try: # Check if the file exists forex = pd.read_csv(filename) # Get all the dates for which we have an exchange rate data_dates = list(forex.loc[:, "Date"]) # Loop through all the dates for day, i in zip(dates, range(len(dates))): # Check if we have the exchange rate for day if day not in data_dates: print("Getting new rate: " + day) # Add exchange rate to the i-th row of forex dataframe forex.loc[i] = [day] + [ get_rate(cur1, cur2, get_date(day[:10]).date()) ] except FileNotFoundError as _: # Since the file does not exist, loop through all dates and gather the exchange rate for each date forex = pd.DataFrame(columns=["Date", "FX"]) for day, i in zip(dates, range(len(dates))): print("Getting rate for " + day) forex.loc[i] = [day] + [ get_rate(cur1, cur2, get_date(day[:10]).date()) ] # Set the index of forex dataframe to the date and save to filename forex = forex.set_index("Date") forex.to_csv(filename)
def write_to_file(val_from, val_to, amount, year=datetime.datetime.today().year, month=datetime.datetime.today().month, day=datetime.datetime.today().day): file = open('history.txt', 'a') file.write( 'Конвертировал ' + str(amount) + ' ' + str(val_from) + ' в ' + str(val_to) + ' по курсу ' + str( round( get_rate(val_from, val_to, date_obj=datetime.date(year, month, day)), 3)) + ' и получил ' + str( round( convert(val_from, val_to, amount, date_obj=datetime.date(year, month, day)), 3)) + '\n') file.close()
def get_data(): #create date range list base = datetime.datetime.today() date_list = [base - datetime.timedelta(days=x) for x in range(725)] prices = [] curr = Currency('GBPUSD') for date in date_list: #time.sleep(1) try: price = get_rate("USD", "CAD", date) prices.append({'price': price, 'date': date}) if price not in curr.price_data: curr.price_data.append(price) append_list_as_row('./csv/gbpusd.csv', [price, date]) curr.inds.append(curr.count) curr.count +=1 curr.check_AO() print(price) except: print('uhoh', date) curr.show_data()
def test_get_rate_with_valid_codes_same_currency(self): rate = get_rate('USD', 'USD') # rate should be 1. self.assertEqual(1., rate)
from datetime import datetime from forex_python.converter import get_rate t = datetime(2018, 6, 17) t = t.replace(minute=9, hour=16, second=10) rate = get_rate("EUR", "USD", t) print(t, " - ", rate) t = datetime(2018, 7, 18) t = t.replace(minute=5, hour=16, second=10) rate = get_rate("USD", "EUR", t) print(t, " - ", rate)
def currency_exchange(request, owned, needed): datetime_object = datetime.now() datetime_week_old = datetime_object - timedelta(days=7) now = get_rate(owned, needed, datetime_object) then = get_rate(owned, needed, datetime_week_old) percentage = int((now - then) * 10000) / 100 if request.method == "POST": exchange_form = ExchangeForm(data=request.POST) if exchange_form.is_valid(): # saving transaction fee = d.Decimal("0.96") obj = CurrencyExchangeModel() obj.value_exchanged = exchange_form.cleaned_data['value_exchanged'] obj.exchanged_currency = owned obj.acquired_currency = needed obj.date = datetime.now() obj.exchange_rate = round(get_rate(owned, needed, datetime.now()), 2) obj.value2_acquired = round( fee * exchange_form.cleaned_data['value_exchanged'] * d.Decimal(obj.exchange_rate), 2) obj.user = request.user obj.save() # exchange usr = get_object_or_404(Currency_owned, user=request.user) owned_client = 'SELECT c."{}" FROM currency_currency_owned as c WHERE user_id={};'.format( obj.exchanged_currency, usr.user_id) needed_client = 'SELECT c."{}" FROM currency_currency_owned as c WHERE user_id={};'.format( obj.acquired_currency, usr.user_id) with connection.cursor() as cursor: cursor.execute(owned_client) owned_client = cursor.fetchone() cursor.execute(needed_client) needed_client = cursor.fetchone() owned_client = d.Decimal(round(owned_client[0], 2)) needed_client = d.Decimal(round(needed_client[0], 2)) if owned_client > obj.value_exchanged: giving = 'UPDATE currency_currency_owned SET "{}"={} WHERE user_id={};'.format( obj.exchanged_currency, owned_client - obj.value_exchanged, usr.user_id) getting = 'UPDATE currency_currency_owned SET "{}"={} WHERE user_id={};'.format( obj.acquired_currency, needed_client + obj.value2_acquired, usr.user_id) try: with connection.cursor() as cursor: cursor.execute(giving) cursor.execute(getting) registered = True except (Exception): return HttpResponse('<h1>Databese connection lost</h1>') else: return HttpResponse( '<h1>Form not valid - in construction ...</h1>') else: print(exchange_form.error_class) return redirect('main_page') context = { 'exchange_form': ExchangeForm(), 'owned': owned, 'needed': needed, 'percentage': percentage, } return render(request, 'currency/exchange_panel.html', context)
def test_get_rate_with_valid_codes(self): rate = get_rate('USD', 'INR') # check if return value is float self.assertTrue(isinstance(rate, float))
from datetime import timedelta, datetime from forex_python.converter import get_rate start_date = datetime(2019,1,1) end_date = datetime.now() conversion_usd_gbp = [] for n in range(int ((end_date - start_date).days)): conversion_usd_gbp.append(get_rate('USD', 'GBP', (start_date + timedelta(n)))) print(conversion_usd_gbp)
import matplotlib.pyplot as plt import pandas as pd rateUSD = 'USD' #input() rate1 = 'GBP' #input() rate2 = 'EUR' #input() year = 2018 #input() month = 8 #input() dateList = [] rate1List = [] rate2List = [] dayCount = cal.monthrange(year, month)[1] for i in range(1,dayCount + 1): d = datetime(year, month, i) fx1 = get_rate(rate1, rateUSD, d) fx2 = get_rate(rate2, rateUSD, d) dateList.append(str(d)) rate1List.append(fx1) rate2List.append(fx2) forexDict = {'date': dateList, 'rate1': rate1List, 'rate2': rate2List} forexDF = pd.DataFrame.from_dict(data=forexDict) forexDF['date'] = pd.to_datetime(forexDF['date']) forexDF.set_index('date', inplace=True) plt.plot(forexDF) plt.xlabel('Date') plt.xticks(rotation=60)
np.set_printoptions(suppress=True) import useful_defs_prd as prd cs = prd.palette() ############################################################################## # Do some stuff ############################################################################## path = (r"C:\Users\Phil\Documents\GitHub\latest-python\Stocks and shares" r"\investment log.txt") file = open(path, 'r', encoding='utf-8') data = file.readlines() yesterday = date.today() - timedelta(1) total_paid = 0 total_current_worth = 0 current_USDGBP = float(get_rate("USD", "GBP", yesterday)) print(current_USDGBP) print(yesterday) for i0, val in enumerate(data[1:]): share = str(val.split("\t")[1]) amt = float(val.split("\t")[2]) paid = float(val.split("\t")[3]) date = str(val.split("\t")[4]) current_share = pdr.get_data_yahoo(share, yesterday, yesterday) current_price_USD = float(current_share['Adj Close']) current_price_GBP = current_price_USD * current_USDGBP current_worth = current_price_GBP * amt total_current_worth = current_worth + total_current_worth total_paid = total_paid + paid
import datetime from forex_python.converter import get_rate from csv import writer import time import matplotlib.pyplot as plt import numpy as np """"t = datetime(2021, 1, 18) # the 18th of October, 2001 get_rate("USD", "GBP", t) p = get_rate("GBP", "USD", t) print(p)""" def append_list_as_row(file,list_of_elem): # Open file in append mode with open(file, 'a+', newline='') as write_obj: # Create a writer object from csv module csv_writer = writer(write_obj) # Add contents of list as last row in the csv file csv_writer.writerow(list_of_elem) class Currency(): def __init__(self, name): self.name = name self.price_data = [] self.ao = [] self.buy_ps = [] self.sell_ps = [] self.buy_period = [] self.profit = [] self.buy_pos = [] self.sell_pos = []
import forex_python import numpy as np from forex_python.converter import get_rate from forex_python.bitcoin import BtcConverter print("stocks") style.use('ggplot') start = dt.datetime(2000, 1, 1) end = dt.datetime(2017, 12, 1) df = web.DataReader('GOOGL', 'yahoo', start, end) print(df.head(3)) print("\n") print("forex") t = dt.datetime(2001, 10, 18) get_rate("USD", "EUR", t) print("USD to EUR") print(get_rate("USD", "EUR", t)) print("\n") b = BtcConverter() print("bitcoin") print(b.get_latest_price('USD')) print("USD\n") #code starts now print("code starts now\n") with open("AllStocks1.csv", "r") as StocksFile: StocksFileReader = csv.reader(StocksFile) StocksList = [] for row in StocksFileReader:
#!/usr/bin/env python 3 """Currency conversion utility w/argument parsing. """ import argparse from forex_python.converter import get_rate EUR_TO_USD = get_rate('EUR', 'USD') def convert_usd_to_eur(usd): """Convert USD to EUR. """ return usd / EUR_TO_USD def convert_eur_to_usd(eur): """Convert EUR to USD. """ return eur * EUR_TO_USD def parse_cli_args(): """Define command line parser w/arguments. """ parser = argparse.ArgumentParser( description="Currency conversion utility.") group = parser.add_mutually_exclusive_group() group.add_argument("--usd-to-eur", help="convert usd to eur", nargs='+',
df['Date'] = df.index df["Year"] = df.Date.dt.strftime('%Y') df["Month"] = df.Date.dt.strftime('%m') df["Day"] = df.Date.dt.strftime('%d') df[int_float] = df[int_float].apply(pd.to_numeric, errors='coerce') year = list(df.Year) month = list(df.Month) day = list(df.Day) for y, m, d in zip(year, month, day): TheDay = datetime(y, m, d) # the 18th of October, 2001 df = pd.DataFrame({ 'Date': [TheDay], str(main_currency): [1], 'GBP': [get_rate(str(main_currency), "GBP", TheDay)] }) df['USD'] = get_rate(str(main_currency), "USD", TheDay) df['EUR'] = get_rate(str(main_currency), "EUR", TheDay) df["DateKey"] = df.Date.dt.strftime('%Y-%m-01') df.to_sql(name='v1', con=sqlite_db, index=False, if_exists='append') #replace append pivot_columns = ['Date', 'DateKey'] for df in pd.read_sql_query('select * from v1', sqlite_db, chunksize=chunksize): df = pd.melt(df, id_vars=pivot_columns, var_name="Currency", value_name="Value") df.to_sql(name='v2', con=sqlite_db, index=False,
def test_get_rate_with_date(self): date_obj = datetime.datetime.strptime('2010-05-10', "%Y-%m-%d").date() rate = get_rate('USD', 'INR', date_obj) # check if return value is float self.assertTrue(isinstance(rate, float))
def convert_cb(amount, curr, dt): converter = forex_python.converter.CurrencyRates() dt = datetime.datetime.utcfromtimestamp(dt) rate = converter.get_rate(curr, ACCOUNT_CURR, dt) return "{0:.2f}".format(rate * float(amount))