Python with csv file, currency conversion - python

I'd like to print different number using different currency rate depending on the date.
import csv
def load_exchange_rates(test1):
exchange_rates = {}
with open(test1, newline='') as file:
reader = csv.reader(file, delimiter=';')
next(reader)
for row in reader:
if '' in row[1:]:
continue
date = row[0]
exchange_rates['EUR'] = float(row[1])
exchange_rates['AUD'] = float(row[2])
exchange_rates['GBP'] = float(row[3])
return exchange_rates
def u_to_e(exchange_rates):
usd = float(input("Give USD to convert: "))
print(round(usd, 1), "USD in EUR is", round(usd*exchange_rates['EUR'], 2), "EUR")
def u_to_a(exchange_rates):
usd = float(input("Give USD to convert: "))
print(round(usd, 1), "USD in AUD is", round(usd*exchange_rates['AUD'], 2), "AUD")
def u_to_g(exchange_rates):
usd = float(input("Give USD to convert: "))
print(round(usd, 1), "USD in GBP is", round(usd*exchange_rates['GBP'], 2), "GBP")
while True:
print("ACME(tm) US DOLLAR EXCHANGE RATE APP")
print("1) LOAD currency exchange rate data from a file")
print("2) USE AVERAGE exchange rate")
print("3) USE HIGHEST exchange rate")
print("4) USE LOWEST exchange rate")
print("5) CONVERT USD TO EUR")
print("6) CONVERT USD TO AUD")
print("7) CONVERT USD TO GBP")
print("0) QUIT program")
choice = input("Choose what to do: ")
if choice == '1':
f_name = input("Give name of the data file: ")
with open(f_name, 'r') as f:
reader = csv.reader(f, delimiter=';')
data = list(reader)
if len(data) > 1:
start_date = data[1][0]
end_date = data[-1][0]
days = len(data) - 1
print(f"Data loaded successfully! Currency exchange data is from {days} days between {start_date} and {end_date}.")
exchange_rates = load_exchange_rates(f_name)
elif choice == '2':
print("Using the average currency exchange rate.")
print("")
elif choice == '3':
print("Using the highest currency exchange rate.")
print("")
elif choice == '4':
print("Using the lowest currency exchange rate")
print("")
elif choice == '5':
u_to_e(exchange_rates)
print("")
elif choice == '6':
u_to_a(exchange_rates)
print("")
elif choice == '7':
u_to_g(exchange_rates)
print("")
else:
break
ACME(tm) US DOLLAR EXCHANGE RATE APP
LOAD currency exchange rate data from a file
USE AVERAGE exchange rate
USE HIGHEST exchange rate
USE LOWEST exchange rate
CONVERT USD TO EUR
CONVERT USD TO AUD
CONVERT USD TO GBP
QUIT program
Choose what to do: 5
Give USD to convert: 1
1.0 USD in EUR is 0.81 EUR`
ACME(tm) US DOLLAR EXCHANGE RATE APP
LOAD currency exchange rate data from a file
USE AVERAGE exchange rate
USE HIGHEST exchange rate
USE LOWEST exchange rate
CONVERT USD TO EUR
CONVERT USD TO AUD
CONVERT USD TO GBP
QUIT program
Choose what to do: 5
Give USD to convert: 1
1.0 USD in EUR is 0.81 EUR
ACME(tm) US DOLLAR EXCHANGE RATE APP
LOAD currency exchange rate data from a file
USE AVERAGE exchange rate
USE HIGHEST exchange rate
USE LOWEST exchange rate
CONVERT USD TO EUR
CONVERT USD TO AUD
CONVERT USD TO GBP
QUIT program
Choose what to do: 5
Give USD to convert: 1
1.0 USD in EUR is 0.88 EUR
ACME(tm) US DOLLAR EXCHANGE RATE APP
LOAD currency exchange rate data from a file
USE AVERAGE exchange rate
USE HIGHEST exchange rate
USE LOWEST exchange rate
CONVERT USD TO EUR
CONVERT USD TO AUD
CONVERT UST TO GBP
QUIT program
Choose what to do: 5
Give USD to convert: 1
1.0 USD in EUR is 0.93 EUR
DATE;USD-EUR;USD-AUD;USD-GBP
1.1.2020;;;
2.1.2020;0.893416;1.430001;0.757867
3.1.2020;0.897102;1.438145;0.763569
4.1.2020;;;
5.1.2020;;;
6.1.2020;0.893336;1.439968;0.761256
7.1.2020;0.895095;1.454619;0.762469
8.1.2020;0.899685;1.45704;0.763545
9.1.2020;0.90009;1.457516;0.767642
10.1.2020;0.901632;1.454513;0.764674
11.1.2020;;;
12.1.2020;;;
I tried to use different currency depending on the date but it seems always same currency rate. How to fix it?

Related

How can I price Digital option with short maturity

I am trying to price a Digital Call option using Quantlib Python package, but I have an inconsistent result. I am trying to price a deep ITM option with a 1 day maturity. The thing is that it returns me 0, which doesn't make sense. Could you please help me?
def Digital_Call(s0: float,
strike: float,
risk_free: float,
vol: float,
today: datetime,
maturity: datetime,
cash_payoff: float):
"Output: option_npv"
dividend_yield = 0
riskFreeTS = ql.YieldTermStructureHandle(ql.FlatForward(today, risk_free, ql.ActualActual()))
dividendTS = ql.YieldTermStructureHandle(ql.FlatForward(today, dividend_yield, ql.ActualActual()))
volatility = ql.BlackVolTermStructureHandle(ql.BlackConstantVol(today, ql.NullCalendar(), vol, ql.ActualActual()))
initialValue = ql.QuoteHandle(ql.SimpleQuote(s0))
process = ql.BlackScholesMertonProcess(initialValue, dividendTS, riskFreeTS, volatility)
engine = ql.AnalyticEuropeanEngine(process)
option_type = ql.Option.Call
option = ql.VanillaOption(ql.CashOrNothingPayoff(option_type, strike, cash_payoff), ql.EuropeanExercise(maturity))
option.setPricingEngine(engine)
return option
s0=150
strike = 14.36
risk_free = 0.0302373913
#risk_free = 0
vol = 0.2567723271
today = datetime(2022,9,28)
maturity = datetime(2022,9,30) #it doesn't work with Maturity of both 1 & 2 days
cash_payoff = 30
It returns 0.
Thank You

Python crypto buy-sell bot

This is a simple trading bot working with gate.io api. It does almost what we want but 2 features are missing.
1-When I enter the token name in the terminal, it has to automatically buy it 3% more than the market price.
2-When the price rises as much as I have determined, it has to automatically sell back all the tokens it bought.
How can I add these features?
import ccxt, time
import utils.config
from utils.telegram_bot import post_message
# Create the GateIO exchange object using CCXT
exchange = ccxt.gateio({
'apiKey': utils.config.GATEIO_API_KEY,
'secret': utils.config.GATEIO_SECRET_KEY,
})
# Get the market and balance data from GateIO
markets = exchange.fetch_markets()
balance = exchange.fetch_total_balance()
# Get all the available symbols from GateIO
symbols = [symbol for symbol in [market['symbol'] for market in markets]]
# Placeholder for keeping the price at the time of buying
entryPrice = 0
def symbol_check(symbol):
if symbol in symbols:
print(f"Good news!, {symbol} exists in Gate.io")
return True
else:
print(f"Sorry, {symbol} does not exist in Gate.io")
return False
def buy(symbol):
global entryPrice
# Pick a price more than the last ticker data, to make sure that we can fulfill order
price = exchange.fetch_ticker(symbol)['last'] * 1.01
entryPrice = price
# Get the current USDT balance in GateIO
balance = exchange.fetch_total_balance()
coin = symbol.split('/')[0]
usdt_balance = balance['USDT']
# Calculate the amount of coin that we can buy, apply a small margin for rounding errors in balance
amount = (usdt_balance * 0.999) / (price)
# Create the limit buy order
exchange.create_limit_buy_order(symbol, amount=amount, price=price)
# Notify the user both on Telegram and CLI
message = f"You have {usdt_balance} USDT in your account. Buying {amount} {coin} for {price}"
print(message)
post_message(message)
def sell(symbol):
# Pick a price less than the last ticker data, to make sure that we can fulfill order
price = exchange.fetch_ticker(symbol)['last'] * 0.99
# Get the current coin balance in GateIO
balance = exchange.fetch_total_balance()
coin = symbol.split('/')[0]
coin_balance = balance[coin]
# Create the limit sell order
exchange.create_limit_sell_order(symbol, amount=coin_balance, price=price)
# Notify the user both on Telegram and CLI
message = f"You have {coin_balance} {coin} in your account. Selling them for {price}"
print(message)
post_message(message)
def sellBearish(symbol):
global entryPrice
bestPrice = exchange.fetch_ticker(symbol)['last']
balance = exchange.fetch_total_balance()
while True:
price = exchange.fetch_ticker(symbol)['last']
# Update the best price if we have a new best price
if price > bestPrice:
bestPrice = price
# If the price has dropped 3% percent w.r.t. the best price, sell the coins and get the profit
elif price < (0.97 * bestPrice):
coin = symbol.split('/')[0]
coin_balance = balance[coin]
exchange.create_limit_sell_order(symbol, amount=coin_balance, price=price*0.99)
# Notify the user both on Telegram and CLI
message = f"You have {coin_balance} {coin} in your account.\nSelling them for {price*0.99}\nYour profit is{price/entryPrice*100}"
print(message)
post_message(message)

Label dataframe column with regular expression

I have a dataframe(original_df) with column description, and I want to create another column Label by searching for keyword in the description using regular expression e.g
description Label
fund trf 0049614823 transfers
alat transfer transfers
data purchase via airtime
alat pos buy pos
alat web buy others
atm wd rch debit money withdrawals
alat pos buy pos
salar alert charges salary
mtn purchase via airtime
top- up purchase via airtime
The psedocode I came up with was
Input- description column and regular expression
Use the regular expression to search for patterns in the description column
loop through the description and create a label based on the
description keyword
return the full dataframe with label column
I tried implementing that here but I didn't get the logic right and I am getting a keyword error
I have also tried all that I could possibly do at the moment but still can't come up with the right logic
df = original_df['description'].sample(100)
position = 0
while position < len(df):
if any(re.search(r"(tnf|trsf|trtr|trf|transfer)",df[position])):
original_df['Label'] == 'transfers'
elif any(re.search(r'(airtime|data|vtu|recharge|mtn|glo|top-up)',df[position])):
original_df['Label'] == 'aitime
elif any(re.search(r'(pos|web pos|)',df[position])):
original_df['Label'] == 'pos
elif any(re.search(r'(salary|sal|salar|allow|allowance)',df[position])):
original_df['Label'] == 'salary'
elif any(re.search(r'(loan|repayment|lend|borrow)',df[position])):
original_df['Label'] == 'loan'
elif any(re.search(r'(withdrawal|cshw|wdr|wd|wdl|withdraw|cwdr|cwd|cdwl|csw)',df[position])):
return 'withdrawals'
position += 1
return others
print(df_sample)
You can put your regex logic into a function and apply that to the DataFrame. This way you can avoid your manual looping pseudocode.
Code:
import pandas as pd
df = pd.DataFrame({ 'description': [
'fund trf 0049614823',
'alat transfer',
'data purchase via',
'alat pos buy',
'alat web buy',
'atm wd rch debit money',
'alat pos buy',
'salar alert charges',
'mtn purchase via',
'top- up purchase via',
]})
description
0
fund trf 0049614823
1
alat transfer
2
data purchase via
3
alat pos buy
4
alat web buy
5
atm wd rch debit money
6
alat pos buy
7
salar alert charges
8
mtn purchase via
9
top- up purchase via
Create a label() function based on your regex code:
import re
def label(row):
if re.search(r'(tnf|trsf|trtr|trf|transfer)', row.description):
result = 'transfers'
elif re.search(r'(airtime|data|vtu|recharge|mtn|glo|top-up)', row.description):
result = 'airtime'
elif re.search(r'(pos|web pos)', row.description):
result = 'pos'
elif re.search(r'(salary|sal|salar|allow|allowance)', row.description):
result = 'salary'
elif re.search(r'(loan|repayment|lend|borrow)', row.description):
result = 'loan'
elif re.search(r'(withdrawal|cshw|wdr|wd|wdl|withdraw|cwdr|cwd|cdwl|csw)', row.description):
result = 'withdrawals'
else:
result = 'other'
return result
Then apply the label() function to the rows of df:
df['label'] = df.apply(label, axis=1)
description
label
0
fund trf 0049614823
transfers
1
alat transfer
transfers
2
data purchase via
airtime
3
alat pos buy
pos
4
alat web buy
pos
5
atm wd rch debit money
pos
6
alat pos buy
pos
7
salar alert charges
pos
8
mtn purchase via
airtime
9
top- up purchase via
pos

For loop doesn't go all around a dictionary

so i have the code down below
import requests
import json
with open("forex_rates.json", "r") as file:
rate = json.load(file)
nrate = rate
Base = input("enter your base currency: ")
if Base not in rate["rates"]:
print("That's not a valid currency...")
Base = input("enter your base currency: ")
with open("forex_rates.json", "r") as file:
nrate["base"] = Base
for i in rate["rates"]:
nrate["rates"][i] = rate["rates"].get(i) / rate["rates"].get(Base)
print(nrate["rates"])
I'm trying to make a program that converts different currencies, for example:
1 EUR --> 1.18 USD
and in order to do this I have to edit the forex rates everytime depending on the base value
when i finished up the code i ran t and it worked all fine and it converted all values until it hit the same value in the forex value file
like if i convert from USD it will change all currency values depending on USD but when it hits the USD in the file the loop breaks
i tried for so long 'till i tried moving USD to the very bottom of the file as there is nothing after it to break. and it worked but that's for USD only.
when i change the base value inside the program it breaks again
for people saying the code isn't even finished i'd say that i almost finished this part of the program the converting part which i believe the most difficult and any other code left is only the GUI and some multiplying math
and i'll list the forex data below
#sorry if it's too big
{
"success":true,
"timestamp":1597402446,
"base":"EUR",
"date":"2020-08-14",
"rates":{
"AED":4.335266,
"AFN":91.176403,
"ALL":123.979569,
"AMD":572.651268,
"ANG":2.125143,
"AOA":695.22591,
"ARS":86.213707,
"AUD":1.651881,
"AWG":2.124558,
"AZN":2.001576,
"BAM":1.954795,
"BBD":2.390258,
"BDT":100.546318,
"BGN":1.956895,
"BHD":0.444938,
"BIF":2283.56194,
"BMD":1.18031,
"BND":1.622912,
"BOB":8.173103,
"BRL":6.336422,
"BSD":1.183874,
"BTC":0.0001,
"BTN":88.576746,
"BWP":13.863097,
"BYN":2.914727,
"BYR":23134.077322,
"BZD":2.38624,
"CAD":1.562064,
"CDF":2302.785095,
"CHF":1.074967,
"CLF":0.033942,
"CLP":936.574514,
"CNY":8.203627,
"COP":4452.129574,
"CRC":704.672423,
"CUC":1.18031,
"CUP":31.278217,
"CVE":110.201987,
"CZK":26.106129,
"DJF":210.746982,
"DKK":7.446693,
"DOP":69.149105,
"DZD":151.514114,
"EGP":18.805169,
"ERN":17.704664,
"ETB":42.448715,
"EUR":1,
"FJD":2.523208,
"FKP":0.90119,
"GBP":0.900976,
"GEL":3.647475,
"GGP":0.90119,
"GHS":6.811663,
"GIP":0.90119,
"GMD":61.163652,
"GNF":11418.288925,
"GTQ":9.116687,
"GYD":247.470583,
"HKD":9.14817,
"HNL":29.203723,
"HRK":7.531326,
"HTG":132.978265,
"HUF":346.161502,
"IDR":17595.177253,
"ILS":4.019203,
"IMP":0.90119,
"INR":88.434024,
"IQD":1413.229387,
"IRR":49696.95603,
"ISK":161.076893,
"JEP":0.90119,
"JMD":176.632894,
"JOD":0.836814,
"JPY":125.951475,
"KES":127.822789,
"KGS":92.238283,
"KHR":4859.521032,
"KMF":491.421896,
"KPW":1062.314938,
"KRW":1401.210938,
"KWD":0.360975,
"KYD":0.986486,
"KZT":496.331879,
"LAK":10752.381531,
"LBP":1789.879783,
"LKR":216.488093,
"LRD":235.294815,
"LSL":20.549263,
"LTL":3.485149,
"LVL":0.713958,
"LYD":1.626859,
"MAD":10.913322,
"MDL":19.82872,
"MGA":4566.909302,
"MKD":61.58448,
"MMK":1610.391686,
"MNT":3362.205621,
"MOP":9.449856,
"MRO":421.37087,
"MUR":46.799002,
"MVR":18.243058,
"MWK":879.737053,
"MXN":26.199071,
"MYR":4.949633,
"MZN":83.979304,
"NAD":20.548996,
"NGN":449.107914,
"NIO":41.242296,
"NOK":10.544902,
"NPR":141.752962,
"NZD":1.80663,
"OMR":0.454403,
"PAB":1.183663,
"PEN":4.2222,
"PGK":4.165565,
"PHP":57.516411,
"PKR":199.282277,
"PLN":4.396536,
"PYG":8227.988848,
"QAR":4.297547,
"RON":4.835722,
"RSD":117.576625,
"RUB":86.625365,
"RWF":1142.595148,
"SAR":4.426709,
"SBD":9.756128,
"SCR":21.044237,
"SDG":65.300702,
"SEK":10.291595,
"SGD":1.620105,
"SHP":0.90119,
"SLL":11537.53114,
"SOS":689.301231,
"SRD":8.802808,
"STD":25132.067341,
"SVC":10.358743,
"SYP":603.981109,
"SZL":20.627972,
"THB":36.753085,
"TJS":12.208818,
"TMT":4.131085,
"TND":3.240537,
"TOP":2.698542,
"TRY":8.706498,
"TTD":8.006077,
"TWD":34.707966,
"TZS":2744.220413,
"UAH":32.433598,
"UGX":4343.852885,
"USD":1.18031,
"UYU":50.261259,
"UZS":12111.300903,
"VEF":11.788346,
"VND":27353.095658,
"VUV":134.283098,
"WST":3.09309,
"XAF":655.754247,
"XAG":0.044343,
"XAU":0.000606,
"XCD":3.189847,
"XDR":0.840933,
"XOF":655.720927,
"XPF":119.624668,
"YER":295.426891,
"ZAR":20.617975,
"ZMK":10624.212769,
"ZMW":21.85909,
"ZWL":380.05997
}
}

IF/ELSE Control flow in Python to work out price of courier service from 4 choices

I cannot seem to understand how to use if/else in the following question:
You need to design a program for a courier company to calculate the cost of sending a parcel.
Ask the user to enter the price of the package they would like to purchase.
Ask the user to enter the total distance of the delivery in kilometers.
Now, add on the delivery costs to get the final cost of the product. There are four categories to factor in when determining a parcel’s final cost, each with two options based on the customer’s delivery preferences. (Use an if else statement based on the choice they make)
Delivery via air ($0.36 per km) or via freight ($0.25 per km)
Full insurance ($50.00) or limited insurance ($25.00)
Gift option ($15.00) or not ($0.00)
Priority delivery ($100.00) or standard delivery ($20.00)
Write code to work out the total cost of the package based on the options
selected in each category.
#Mohseen Ramjan
I used some of the original code, but simplified it a bit.
I am no expert, and I'm sure even this code can be improved a lot.
===== NOTE: our currency is Rand, thus the use of the 'R' =====
But maybe you'll understand this a bit better:
main_product_price = int(float(input("""Please enter the price of the package you would like to purchase:
(Only use numbers, do not inlcude 'R')\n""")))
total_distance = int(float(input("\nPlease enter the total distance of the delivery in Kilometers:\n")))
print ("\nNow please choose your shipping preferences;")
print ("\nWould you prefere Air at R0.36 per km, or Freight at R0.25 per km?")
freight_choise = input("Enter: 'Air' or 'Freight'\n")
cost_per_distance = 0
if freight_choise in ['Freight']:
cost_per_distance = 0.25
elif freight_choise in ['Air']:
cost_per_distance = 0.36
print ("\nWould you prefere Full insurance (R50.00), or Limited insurance (R25.00)?")
insurance_choise = input("Enter: 'Full' or 'Limited'?\n")
insurance_cost = 0
if insurance_choise in ['Full']:
insurance_cost = 50
elif insurance_choise in ['Limited']:
insurance_cost = 25
print ("\nWould you like to add a Gift for R15.00?")
gift_choise = input("Enter: 'Yes please' or 'No thanks'\n")
gift_cost = 0
if gift_choise in ['Yes please']:
gift_cost = 15
elif gift_choise in ['No thanks']:
gift_cost = 0
print ("\nWould you prefere Priority delivery for R100.00, or Standard delivery for R20.00?")
delivery_choise = input("Enter: 'Priority' or 'Standard'\n")
priority_or_standard_delivery = 0
if delivery_choise in ['Priority']:
priority_or_standard_delivery = 100
elif delivery_choise in ['Standard']:
priority_or_standard_delivery = 20
total_cost = main_product_price + total_distance*cost_per_distance + insurance_cost + gift_cost + priority_or_standard_delivery
print (f"""\nThis is your Total cost:
R{total_cost}""")
# Courier cost of delivering parcel
# You can and should add your own assertions and checks if the user input is valid
# I used a list instead of '==' so that you can expand the response options
# There are many other ways to do it, this is just my quick and dirty method
# But I suppose you could iterate from here
def user_input():
price_of_package = float(input('Input price of package.\n'))
total_distance = float(input('Input total distance in km\n'))
freight_or_air = input('Input freight or air delivery?\n').lower()
full_or_limited_insurance = input('Input full or limited insurance?\n').lower()
gift_or_not = input('Is this a gift?\n').lower()
priority_or_standard = input('Is this priority or standard delivery?\n').lower()
cost_per_distance = 0
if freight_or_air in ['freight']:
cost_per_distance = 0.25
elif freight_or_air in ['air']:
cost_per_distance = 0.36
cost_of_insurance = 0
if full_or_limited_insurance in ['full']:
cost_of_insurance = 50.00
elif full_or_limited_insurance in ['limited']:
cost_of_insurance = 25.00
cost_of_gift = 0
if gift_or_not in ['yes']:
cost_of_gift = 15
cost_of_delivery = 0
if priority_or_standard in ['priority']:
cost_of_delivery = 100
elif priority_or_standard in ['standard']:
cost_of_delivery = 20
print (f'\nThe user has specified that\n\
price of package: {price_of_package}\n\
total distance: {total_distance}\n\
freight or air: {freight_or_air}\n\
cost per distance {cost_per_distance}\n\
type of insurance: {full_or_limited_insurance}\n\
cost of insurance: {cost_per_distance}\n\
if it is a gift: {gift_or_not}\n\
cost of gift: {cost_of_gift}\n\
type of delivery: {priority_or_standard}\n\
cost of delivery: {cost_of_delivery}.')
return price_of_package, total_distance, cost_per_distance,\
cost_of_insurance, cost_of_gift, cost_of_delivery
def total_cost():
price_of_package, total_distance, cost_per_distance,\
cost_of_insurance, cost_of_gift, cost_of_delivery = user_input()
total_cost = price_of_package + total_distance*cost_per_distance +\
cost_of_insurance + cost_of_gift + cost_of_delivery
print (f'\nThe total cost is {total_cost}.')
return total_cost

Categories

Resources