I try to make an operation but it says "unsupported operand type(s) for *: 'float' and 'decimal.Decimal' "

I’ve been trying to type some code but when I do an arithmetic operation with the variables, I gives me the typeerror “unsupported operand type(s) for *: ‘float’ and ‘decimal.Decimal’”

import statistics

from forex_python.converter import CurrencyRates

c = CurrencyRates(force_decimal=True)

from datetime import datetime, timedelta

yesterday = datetime.now() - timedelta(days=1)

oneweekago = datetime.now() - timedelta(days=7)

onefortnightago = datetime.now() - timedelta(days=15)

onemonthago = datetime.now() - timedelta(days=30)

d = ((c.get_rate('EUR', 'USD') - c.get_rate('EUR', 'USD', yesterday)) / c.get_rate('EUR', 'USD'))

w = ((c.get_rate('EUR', 'USD') - c.get_rate('EUR', 'USD', oneweekago)) / c.get_rate('EUR', 'USD'))

fn = ((c.get_rate('EUR', 'USD') - c.get_rate('EUR', 'USD', onefortnightago)) / c.get_rate('EUR', 'USD'))

m = ((c.get_rate('EUR', 'USD') - c.get_rate('EUR', 'USD', onemonthago)) / c.get_rate('EUR', 'USD'))

finalvalue = - float(0.19) * d - float(0.16) * w - float(0.07) * fn - float(0.03) * m

print(f"The estimated future currency growth is {finalvalue}")

Does anyone know how I can solve that error?

If you’re not using an IDE with some debug options, you can always use so-called ‘debug printing’ to check the object types, such as d, for example.

Insert print(type(d)) after the d = ((c.get... as it could be that this (or the w or the fn or the m) are not of the correct object type for the finalvalue = ... statement.

.get_rate returns a Decimal (from the decimal module), so d, etc, are a Decimal values.

You’re then trying to mix floats with those decimals using multiplication, but that’s not allowed. You need to one of them to a type that’s compatible with the other. I suggest converting the decimal to a float:

finalvalue = - 0.19 * float(d) - 0.16 * float(w) - 0.07 * float(fn) - 0.03 * float(m)

Alternatively:

d = float((c.get_rate('EUR', 'USD') - c.get_rate('EUR', 'USD', yesterday)) / c.get_rate('EUR', 'USD'))

and then just:

finalvalue = - 0.19 * d - 0.16 * w - 0.07 * fn - 0.03 * m

I also see that you were converting a float to a float, e.g. float(0.19), which is pointless!

Try removing the force_decimal=True part:

# change this
c = CurrencyRates(force_decimal=True)

# to this
c = CurrencyRates()

and see if that makes a difference.