Пример #1
0
 def test_derives_missing_inverse_rates(self):
     rates = [
         {"from": "FOO", "to": "BAR", "conversion": Decimal("1.23")},
         {"from": "BAR", "to": "BAZ", "conversion": Decimal("0.95")},
         {"from": "BAZ", "to": "QUX", "conversion": Decimal("1.11")},
         {"from": "BAT", "to": "QUX", "conversion": Decimal("1.01")}]
     converter = Rates(rates)
     self.assertEqual(converter.conversion("FOO", "BAT"), Decimal("1.2842"))
Пример #2
0
def get_sum_in_currency(currency):
    amount = 0
    cash = Wallet().get()
    for curr in cash:
        amount += cash[curr] * (1 if curr == currency else get_rate_ratio(
            Rates().get(curr),
            Rates().get(currency)))

    return amount
Пример #3
0
    def setUp(self):
        """
        Ensures that `utils.pog_converter.PogConverter.__init__` is not executed
        when

        `from rates import Rates`

        Occurs, which would erroneously report that `rates.Rates.__init__` has
        been covered when just running pytest on `test_rates.py`
        """
        with mock.patch("rates.Rates.__init__") as RatesInit:
            RatesInit.return_value = None
            from rates import Rates

            self.rates = Rates()
Пример #4
0
    def __init__(self, currencies):
        self.args = vars(parse_init_params())
        set_logger_options(self.args['debug'])
        logger.info('Starting app ...')

        self.rate = Rates(['EUR', 'USD'])

        cash = {}
        for currency in currencies:
            if currency in self.args:
                cash[currency] = self.args[currency]
        self.wallet = Wallet(cash)
Пример #5
0
def get_wallet_statement():
    cash = Wallet().get()

    text = ''
    for currency in cash:
        text += '{}: {}\n'.format(currency, cash[currency])
    text += '\n'
    for currency in cash:
        if currency.lower() != 'rub':
            text += 'rub-{}: {}\n'.format(currency.lower(),
                                          Rates().get(currency))
        else:
            text += 'usd-eur: {}\n'.format(
                get_rate_ratio(Rates().get('eur'),
                               Rates().get('usd')))
    text += '\n'
    text += 'sum:'
    for currency in cash:
        text += ' {} {} /'.format(currency, get_sum_in_currency(currency))

    return text[:-2]
Пример #6
0
    def test_init(self, parse_csv):
        """
        Only import within the scope of this test so that subsequent tests can
        remove the __init__ call, ensuring the __init__ lines and the functions
        invoked therein are properly unit tested
        """
        from rates import Rates

        self.rates = Rates()
        assert self.rates.currency_to_series_id == {}
        assert self.rates.series == {}
        assert self.rates.observations == {}
        parse_csv.assert_called_once()
Пример #7
0
from argparser import get_args
from inputs import get_year_input, get_month_input, get_currency_input
from rates import Rates

args = get_args()
rates = Rates()


def main():
    print("Welcome to the Historical Rate Calculator")
    year = args.year if args.year else get_year_input(rates)
    month = args.month if args.month else get_month_input(rates)
    currency = args.currency if args.currency else get_currency_input(rates)
    conversion_rate = rates.get_rate(year, month, currency)
    print(f"Conversion rate of {currency} to CAD: {conversion_rate}")


if __name__ == "__main__":
    main()
Пример #8
0
from rates import Rates

if __name__ == '__main__':
    rates = Rates()
    print('Print "%currency%=%amount%" to get exchange rates\n'
          'Print "Add ABC/DEF=xxx" to add exchange rate or check existing one\n'
          'print "Save" to permanently save changes\n'
          'print "Exit" to quit an application')
    while True:
        request = input('Enter your request\n')
        if '/' in request and '=' in request:
            rates.change_rate(request.split('=')[0], float(request.split('=')[1]))
        elif '=' in request:
            rates.print_rates(request.split("=")[0], float(request.split("=")[1]))
        elif request == 'Exit':
            break
        elif request == 'Save':
            rates.save_rates()
        else:
            print('Incorrect request')
Пример #9
0
class Test_Rates(TestCase):
    def setUp(self):
        """
        Ensures that `utils.pog_converter.PogConverter.__init__` is not executed
        when

        `from rates import Rates`

        Occurs, which would erroneously report that `rates.Rates.__init__` has
        been covered when just running pytest on `test_rates.py`
        """
        with mock.patch("rates.Rates.__init__") as RatesInit:
            RatesInit.return_value = None
            from rates import Rates

            self.rates = Rates()

    @mock.patch("csv.reader")
    @mock.patch("builtins.open", new_callable=mock.mock_open, read_data="data")
    def test_parse_csv(self, mock_open, csv_reader):
        mock_csv_contents = [
            ["STUFF"],
            [],
            [],
            ["THAT"],
            [],
            ["SHOULD BE IGNORED"],
            [],
            [],
            ["SERIES"],
            ["id", "label", "description"],
            ["somefakeid", "AUD/CAD", "AUD to CAD"],
            ["anotherfakeid", "JPY/CAD", "JPY to CAD"],
            ["onemorefakeid", "EUR/CAD", "EUR to CAD"],
            [],
            ["OBSERVATIONS"],
            ["date", "somefakeid", "anotherfakeid", "onemorefakeid"],
            ["2017-01-01", 1.00, 0.50, 0.25],
            ["2018-01-01", 0.50, 0.25, 0.125],
            ["2019-01-01", 0.75, 0.33, 0.15],
            [],
        ]
        real_csv_filename = "FX_RATES_MONTHLY-sd-2017-01-01.csv"
        csv_reader.return_value = mock_csv_contents
        self.rates.currency_to_series_id = {}
        self.rates.series = {}
        self.rates.observations = {}
        self.rates.parse_csv()

        mock_open.assert_called_once_with(real_csv_filename)
        csv_reader.assert_called_once_with(mock_open.return_value)
        assert self.rates.series == {
            "somefakeid": {
                "label": "AUD/CAD",
                "description": "AUD to CAD"
            },
            "anotherfakeid": {
                "label": "JPY/CAD",
                "description": "JPY to CAD"
            },
            "onemorefakeid": {
                "label": "EUR/CAD",
                "description": "EUR to CAD",
            },
        }
        assert self.rates.currency_to_series_id == {
            "AUD": "somefakeid",
            "JPY": "anotherfakeid",
            "EUR": "onemorefakeid",
        }
        assert self.rates.observations == {
            2017: {
                1: {
                    "somefakeid": 1.0,
                    "anotherfakeid": 0.5
                }
            },
            2018: {
                1: {
                    "somefakeid": 0.5,
                    "anotherfakeid": 0.25
                }
            },
            2019: {
                1: {
                    "somefakeid": 0.75,
                    "anotherfakeid": 0.33
                }
            },
        }

    def test_get_supported_years(self):
        mock_supported_years = [2017, 2018, 2019]
        self.rates.observations = {}
        for year in mock_supported_years:
            self.rates.observations[year] = {}

        assert self.rates.get_supported_years() == mock_supported_years

    def test_get_supported_currencies(self):
        mock_supported_currencies = ["AUD", "EUR", "JPY"]
        self.rates.currency_to_series_id = {}
        for currency in mock_supported_currencies:
            self.rates.currency_to_series_id[currency] = {}

        assert (
            self.rates.get_supported_currencies() == mock_supported_currencies)

    @mock.patch("rates.Rates.get_supported_years")
    def test_check_valid_year_input_valid_year(self, get_supported_years):
        captured_error = None
        get_supported_years.return_value = [2017, 2018, 2019]
        try:
            self.rates.check_valid_year(get_supported_years.return_value[0])
        except Exception as err:
            captured_error = err
        get_supported_years.assert_called_once()
        assert captured_error == None

    @mock.patch("rates.Rates.get_supported_years")
    def test_check_valid_year_input_invalid_year(self, get_supported_years):
        get_supported_years.return_value = [2017, 2018, 2019]
        inputted_year = 2016
        captured_error = None
        try:
            self.rates.check_valid_year(inputted_year)
        except Exception as err:
            captured_error = err
        get_supported_years.assert_called_once()
        assert str(captured_error) == (
            f"Unsupported year: {inputted_year}\n"
            f"Supported years include: {get_supported_years.return_value}")

    def test_check_valid_month_input_valid_month(self):
        captured_error = None
        try:
            self.rates.check_valid_month(1)
        except Exception as err:
            captured_error = err
        assert captured_error == None

    def test_check_valid_month_input_invalid_month(self):
        captured_error = None
        inputted_month = 0
        try:
            self.rates.check_valid_month(inputted_month)
        except Exception as err:
            captured_error = err
        assert str(captured_error) == (f"Invalid month: {inputted_month}\n"
                                       f"Month must be a value between 1-12")

    @mock.patch("rates.Rates.get_supported_currencies")
    def test_check_valid_currency_input_valid_currency(
        self,
        get_supported_currencies,
    ):
        inputted_currency = "AUD"
        get_supported_currencies.return_value = [inputted_currency]
        captured_error = None
        try:
            self.rates.check_valid_currency(inputted_currency)
        except Exception as err:
            captured_error = err
        get_supported_currencies.assert_called_once()
        assert captured_error == None

    @mock.patch("rates.Rates.get_supported_currencies")
    def test_check_valid_currency_input_invalid_currency(
        self,
        get_supported_currencies,
    ):
        inputted_currency = "JPY"
        get_supported_currencies.return_value = ["AUD"]
        captured_error = None
        try:
            self.rates.check_valid_currency(inputted_currency)
        except Exception as err:
            captured_error = err
        get_supported_currencies.assert_called_once()
        assert str(captured_error) == (
            f"Unsupported currency: {inputted_currency}\n"
            f"Supported currencies include: "
            f"{get_supported_currencies.return_value}")

    @mock.patch("rates.Rates.check_valid_year")
    @mock.patch("rates.Rates.check_valid_month")
    @mock.patch("rates.Rates.check_valid_currency")
    def test_get_rate(
        self,
        check_valid_currency,
        check_valid_month,
        check_valid_year,
    ):
        year = 2017
        month = 1
        currency = "AUD"
        series_id = "somefakeid"
        mock_rate = 1.00

        self.rates.currency_to_series_id = {
            currency: series_id,
        }
        self.rates.observations = {year: {month: {series_id: mock_rate}}}

        returned_rate = self.rates.get_rate(year, month, currency)

        check_valid_currency.assert_called_once()
        check_valid_month.assert_called_once()
        check_valid_year.assert_called_once()

        assert (returned_rate
                == self.rates.observations[year][month][series_id]
                and returned_rate == mock_rate)
Пример #10
0
    maxAverageDiameterThreshold = args.maxAverageDiameterThreshold

    # call samplegenerator which calls RNAxplorer (in matrix2d objects) and executes a clustering (2D or DIANA, etc.) only to select
    # new structure representatives for samplegeneration.
    structures = samplegenerator.mainloop(twoDSamplingParameters)

    # call final clusteralg.
    clusters = DIANA.doClustering(structures, maxDiameterThreshold,
                                  maxAverageDiameterThreshold)
    DIANA.printClusters(clusters)
    representatives = selectRepresentatives(seq, clusters)

    # prepare representatives and sort them, to make the comparison of the output easier.
    repsAndEnergies = [(x, RNA.energy_of_struct(seq, x))
                       for x in representatives]
    repsAndEnergies.sort(key=operator.itemgetter(1, 0))

    # rate computation.
    rateMatrix = Rates.arrheniusRates(seq, repsAndEnergies)

    # write files for treekin (matrix and structures)
    fw = filewriter.FileWriter()
    fw.writeMatrixToFile(rateMatrix, param.RatesFilePath)
    fw.writeRepresentativesToFile(seq, repsAndEnergies,
                                  param.StructuresFilePath)

    # run treekin
    to_call = "cat " + param.StructuresFilePath + " | treekin --p0 " + str(param.StartStructureID) + "=1 --ratesfile " + param.RatesFilePath + " --t0 " + \
            str(param.StartTime) + " --t8 " + str(param.EndTime) + " -m I > " + param.KineticFile
    os.system(to_call)
from pandas.tseries.offsets import BDay
import pandas as pd
import matplotlib.pyplot as plt

import logging
import os
import sys
from datetime import date, datetime, timedelta
from functools import wraps
import re

logging.basicConfig(level=logging.WARNING)

logger = logging.getLogger(__name__)

rates = Rates(caching_period_minutes=10)


def timed_rates_update(func):
    """Декоратор обновляющий кеш котировок"""
    @wraps(func)
    def _wrapped(*args, **kwargs):
        global rates
        rates.update_rates_cache()
        return func(*args, **kwargs)

    return _wrapped


def get_rates():
    """Возвращает форматированный список котировок"""
Пример #12
0
def print_usage():
    print("""Usage:
    value currency                          : conversion,  e.g.: 10 USD
    currency_from / currency_to = value     : to set rate, e.g.: USD/RUB=66
    q : exit
    """)


def main_loop():
    print_usage()
    cmd = ""
    while cmd.strip() not in ['q', 'Q']:
        print("> ")
        cmd = input()
        args = cmd.strip().split()
        if len(args) == 2:  # assuming it is, e.g. 10 USD
            rates.calc(args[0], args[1])
        elif '=' in cmd:
            rates.parseRate(cmd)
        else:
            print_usage()
    rates.save()


# ========  Execution  =============

if __name__ == "__main__":
    from rates import Rates
    rates = Rates(" USD/RUR=64.35 BTC/RUR=325960 USD/EUR=0.88 EUR/RUR=72.72")
    main_loop()