Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 1 addition & 18 deletions qiskit_finance/data_providers/random_data_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,11 @@
from typing import Optional, Union, List
import datetime
import logging

import pandas as pd
import numpy as np

from qiskit.exceptions import MissingOptionalLibraryError
from ._base_data_provider import BaseDataProvider

try:
import pandas as pd

_HAS_PANDAS = True
except ImportError:
_HAS_PANDAS = False

logger = logging.getLogger(__name__)


Expand All @@ -47,17 +39,8 @@ def __init__(
start: first data point
end: last data point precedes this date
seed: optional random seed

Raises:
MissingOptionalLibraryError: Pandas not installed
"""
super().__init__()
if not _HAS_PANDAS:
raise MissingOptionalLibraryError(
libname="Pandas",
name="RandomDataProvider",
pip_install="pip install pandas",
)
tickers = tickers if tickers is not None else ["TICKER1", "TICKER2"]
if isinstance(tickers, list):
self._tickers = tickers
Expand Down
18 changes: 1 addition & 17 deletions qiskit_finance/data_providers/yahoo_data_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,11 @@
from typing import Optional, Union, List
import datetime
import logging
import yfinance as yf

from qiskit.exceptions import MissingOptionalLibraryError
from ._base_data_provider import BaseDataProvider
from ..exceptions import QiskitFinanceError

try:
import yfinance as yf

_HAS_YFINANCE = True
except ImportError:
_HAS_YFINANCE = False

logger = logging.getLogger(__name__)


Expand All @@ -49,17 +42,8 @@ def __init__(
tickers: tickers
start: start time
end: end time

Raises:
MissingOptionalLibraryError: YFinance not installed
"""
super().__init__()
if not _HAS_YFINANCE:
raise MissingOptionalLibraryError(
libname="YFinance",
name="YahooDataProvider",
pip_install="pip install yfinance",
)
self._tickers = []
tickers = tickers if tickers is not None else []
if isinstance(tickers, list):
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
qiskit-terra>=0.17.0
qiskit-terra>=0.20.0
qiskit-optimization>=0.2.0
scipy>=1.4
numpy>=1.17
Expand Down
6 changes: 3 additions & 3 deletions test/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2021.
# (C) Copyright IBM 2018, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand All @@ -12,6 +12,6 @@

""" Finance test packages """

from .finance_test_case import QiskitFinanceTestCase, requires_extra_library
from .finance_test_case import QiskitFinanceTestCase

__all__ = ["QiskitFinanceTestCase", "requires_extra_library"]
__all__ = ["QiskitFinanceTestCase"]
11 changes: 3 additions & 8 deletions test/circuit/test_european_call_delta_objective.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

from qiskit.circuit.library import IntegerComparator
from qiskit.quantum_info import Operator
from qiskit.utils import QuantumInstance
from qiskit.utils import QuantumInstance, optionals
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit_finance.circuit.library import LogNormalDistribution

Expand Down Expand Up @@ -47,15 +47,10 @@ def test_circuit(self):

self.assertTrue(Operator(ecd).equiv(comparator))

@unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test")
def test_application(self):
"""Test an end-to-end application."""
try:
from qiskit import (
Aer,
) # pylint: disable=unused-import,import-outside-toplevel
except ImportError as ex: # pylint: disable=broad-except
self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'")
return
from qiskit import Aer

num_qubits = 3

Expand Down
13 changes: 4 additions & 9 deletions test/circuit/test_european_call_pricing_objective.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
# (C) Copyright IBM 2020, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand All @@ -17,7 +17,7 @@

import numpy as np

from qiskit.utils import algorithm_globals, QuantumInstance
from qiskit.utils import algorithm_globals, QuantumInstance, optionals
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.circuit.library import LinearAmplitudeFunction, TwoLocal
from qiskit.quantum_info import Operator
Expand Down Expand Up @@ -60,15 +60,10 @@ def test_ecev_circuit(self):

self.assertTrue(Operator(ecev).equiv(linear_function))

@unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test")
def test_application(self):
"""Test an end-to-end application."""
try:
from qiskit import (
Aer,
) # pylint: disable=unused-import,import-outside-toplevel
except ImportError as ex: # pylint: disable=broad-except
self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'")
return
from qiskit import Aer

bounds = np.array([0.0, 7.0])
num_qubits = 3
Expand Down
13 changes: 4 additions & 9 deletions test/circuit/test_fixed_income_pricing_objective.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020, 2021.
# (C) Copyright IBM 2020, 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
Expand All @@ -18,7 +18,7 @@
import numpy as np

from qiskit import QuantumCircuit
from qiskit.utils import QuantumInstance
from qiskit.utils import QuantumInstance, optionals
from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem
from qiskit.quantum_info import Operator
from qiskit_finance.circuit.library import NormalDistribution
Expand Down Expand Up @@ -50,15 +50,10 @@ def test_circuit(self):

self.assertTrue(Operator(circuit).equiv(expected))

@unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test")
def test_application(self):
"""Test an end-to-end application."""
try:
from qiskit import (
Aer,
) # pylint: disable=unused-import,import-outside-toplevel
except ImportError as ex: # pylint: disable=broad-except
self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'")
return
from qiskit import Aer

a_n = np.eye(2)
b = np.zeros(2)
Expand Down
9 changes: 1 addition & 8 deletions test/data_providers/test_data_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import warnings
import os
import datetime
from test import QiskitFinanceTestCase, requires_extra_library
from test import QiskitFinanceTestCase
from ddt import ddt, data, unpack
import numpy as np
from qiskit_finance import QiskitFinanceError
Expand Down Expand Up @@ -50,7 +50,6 @@ def tearDown(self):
warnings.filterwarnings(action="default", message="unclosed", category=ResourceWarning)
warnings.filterwarnings(action="default", module="urllib3", category=DeprecationWarning)

@requires_extra_library
def test_random_wrong_use(self):
"""Random wrong use test"""
rnd = RandomDataProvider(seed=1)
Expand All @@ -73,7 +72,6 @@ def test_random_wrong_use(self):
with self.subTest("test WikipediaDataProvider get_similarity_matrix"):
self.assertRaises(QiskitFinanceError, wiki.get_similarity_matrix)

@requires_extra_library
def test_yahoo_wrong_use(self):
"""Yahoo! wrong use test"""
yahoo = YahooDataProvider(
Expand All @@ -87,7 +85,6 @@ def test_yahoo_wrong_use(self):
with self.subTest("test YahooDataProvider get_similarity_matrix"):
self.assertRaises(QiskitFinanceError, yahoo.get_similarity_matrix)

@requires_extra_library
def test_random(self):
"""random test"""
similarity = np.array([[1.00000000e00, 6.2284804e-04], [6.2284804e-04, 1.00000000e00]])
Expand All @@ -99,7 +96,6 @@ def test_random(self):
with self.subTest("test RandomDataProvider get_similarity_matrix"):
np.testing.assert_array_almost_equal(rnd.get_similarity_matrix(), similarity, decimal=3)

@requires_extra_library
def test_random_divide_0(self):
"""Random divide by 0 test"""
# This will create data with some 0 values, it should not throw
Expand All @@ -121,7 +117,6 @@ def test_random_divide_0(self):
with self.subTest("test get_period_return_covariance_matrix is numpy array"):
self.assertIsInstance(sigma_value, np.ndarray)

@requires_extra_library
def test_wikipedia(self):
"""wikipedia test"""
try:
Expand Down Expand Up @@ -165,7 +160,6 @@ def test_nasdaq(self):
except QiskitFinanceError as ex:
self.skipTest(f"Test of DataOnDemandProvider skipped {str(ex)}")

@requires_extra_library
def test_exchangedata(self):
"""exchange data test"""
try:
Expand Down Expand Up @@ -197,7 +191,6 @@ def test_exchangedata(self):
["AEO", 7.0, [[1.0]]],
)
@unpack
@requires_extra_library
def test_yahoo(self, tickers, covariance, similarity):
"""Yahoo data test"""
yahoo = YahooDataProvider(
Expand Down
19 changes: 0 additions & 19 deletions test/finance_test_case.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import os
import unittest
import time
from qiskit.exceptions import MissingOptionalLibraryError

# disable deprecation warnings that can cause log output overflow
# pylint: disable=unused-argument
Expand All @@ -34,24 +33,6 @@ def _noop(*args, **kargs):
# warnings.warn = _noop


def requires_extra_library(test_item):
"""Decorator that skips test if an extra library is not available
Args:
test_item (callable): function to be decorated.
Returns:
callable: the decorated function.
"""

def wrapper(self, *args):
try:
test_item(self, *args)
except MissingOptionalLibraryError as ex:
self.skipTest(str(ex))
return wrapper

return wrapper


class QiskitFinanceTestCase(unittest.TestCase, ABC):
"""Finance Test Case"""

Expand Down