Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

Write tests for this function [code]

  1. User

    Write tests for this function

    def calculate_ema(data: tuple | list | np.ndarray, length: int) -> np.ndarray:
        """"
        Вычисляет экспоненциальную скользящую среднюю (EMA) заданной длины.
    
        Parameters:
            data (list, numpy.ndarray or tuple): Список или массив точек данных
            length (int): Количество периодов, которые следует учитывать при расчете EMA
    
        Returns:
            numpy.ndarray: Массив, содержащий значения EMA
    
        Raises:
            ValueError: If the length is greater than the length of the data
        """
    
        if length > len(data):
            raise ValueError("Length cannot be greater than the length of data")
    
        alpha = 2 / (length + 1)
        ema_values = [data[0]]
    
        for i in range(1, len(data)):
            ema_values.append((alpha * data[i]) + ((1 - alpha) * ema_values[i - 1]))
    
        return np.array(ema_values)
    
  2. Assistant

    Here are some tests for the calculate_ema function:

    1. Test for a valid list of data and length:
    data = [1, 2, 3, 4, 5]
    length = 3
    expected_output = np.array([1, 1.66666667, 2.55555556, 3.51851852, 4.50617284])
    
    assert np.array_equal(calculate_ema(data, length), expected_output)
    
    1. Test for a valid numpy.ndarray of data and length:
    import numpy as np
    
    data = np.array([1, 2, 3, 4, 5])
    length = 3
    expected_output = np.array([1, 1.66666667, 2.55555556, 3.51851852, 4.50617284])
    
    assert np.array_equal(calculate_ema(data, length), expected_output)
    
    1. Test for a valid tuple of data and length:
    data = (1, 2, 3, 4, 5)
    length = 3
    expected_output = np.array([1, 1.66666667, 2.55555556, 3.51851852, 4.50617284])
    
    assert np.array_equal(calculate_ema(data, length), expected_output)
    
    1. Test for length greater than the length of data:
    data = [1, 2, 3, 4, 5]
    length = 6
    
    try:
        calculate_ema(data, length)
        assert False  # This line should not be reached
    except ValueError:
        assert True  # The ValueError should be raised
    
    1. Test for an empty list of data:
    data = []
    length = 3
    
    try:
        calculate_ema(data, length)
        assert False  # This line should not be reached
    except ValueError:
        assert True  # The ValueError should be raised
    
    1. Test for a negative length:
    data = [1, 2, 3, 4, 5]
    length = -1
    
    try:
        calculate_ema(data, length)
        assert False  # This line should not be reached
    except ValueError:
        assert True  # The ValueError should be raised
    
  3. User

    Write a unittest for this function python

    def aggregate_trades_to_candlesticks(time_interval: str = "5T") -> pd.DataFrame:
        """
        Рассчитывает значение свечей на основе данные цены.
        Свечи должны включать значения открытия, максимума, минимума, закрытия.
        Parameters:
            time_interval (str): Временной интервал, на котором будет строиться выборка.
    
        Returns:
            pd.DataFrame: Таблица со значениями открытия, максимума, минимума, закрытия.
        """
    
        trades_df = pd.read_csv(Path("price", "prices.csv"), delimiter=',')
    
        trades_df["TS"] = pd.to_datetime(trades_df["TS"])
        trades_df.set_index("TS", inplace=True)
    
        resampled_df = trades_df.resample(time_interval).agg({"PRICE": "ohlc"})
    
        return resampled_df
    
  4. Assistant

    Here's an example of a unit test for the aggregate_trades_to_candlesticks function using the unittest module:

    import unittest
    import pandas as pd
    from pathlib import Path
    from datetime import datetime
    
    class TestAggregateTradesToCandlesticks(unittest.TestCase):
    
        def test_aggregate_trades_to_candlesticks(self):
            # Create a temporary test file with sample data
            sample_data = """
            TS,PRICE
            2022-01-01 09:00:00,10.0
            2022-01-01 09:01:00,12.0
            2022-01-01 09:02:00,8.0
            2022-01-01 09:03:00,11.0
            2022-01-01 09:04:00,9.0
            """
            with open("test_prices.csv", "w") as f:
                f.write(sample_data)
    
            # Call the function being tested
            expected_output = pd.DataFrame({
                "PRICE_OPEN": [10.0, 11.0],
                "PRICE_HIGH": [12.0, 11.0],
                "PRICE_LOW": [8.0, 9.0],
                "PRICE_CLOSE": [9.0, 9.0]
            }, index=[datetime(2022, 1, 1, 9, 0), datetime(2022, 1, 1, 9, 5)])
    
            result = aggregate_trades_to_candlesticks("5T")
    
            # Assert that the actual result matches the expected output
            pd.testing.assert_frame_equal(result, expected_output)
    
            # Remove the temporary test file
            Path("test_prices.csv").unlink()
    
    if __name__ == "__main__":
        unittest.main()
    

    In this unit test, we create a temporary test file called "test_prices.csv" with sample data using a context manager. We then call the aggregate_trades_to_candlesticks function with a predefined time interval of "5T" and compare the actual result with the expected output using pd.testing.assert_frame_equal. Finally, we remove the temporary test file to clean up after the test.