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
Assistant
To write a unittest for the given function, you can use the unittest module in Python. Here's an example of a unittest for the aggregate_trades_to_candlesticks function:
python
User
Write unit tests for dataframe
Assistant
User
Write unit tests for dataframe
Assistant
import unittest
import pandas as pd
from pathlib import Path
class TestCandlestickAggregation(unittest.TestCase):
def test_aggregate_trades_to_candlesticks(self):
time_interval = "5T"
# Create a test dataset
test_data = pd.DataFrame({
"TS": ["2021-01-01 00:00:00", "2021-01-01 00:01:00", "2021-01-01 00:02:00", "2021-01-01 00:03:00"],
"PRICE": [10, 15, 12, 18]
})
test_data["TS"] = pd.to_datetime(test_data["TS"])
test_data.set_index("TS", inplace=True)
# Save the test dataset to a CSV file
test_data.to_csv(Path("price", "prices.csv"), index=True)
# Call the function to be tested
result = aggregate_trades_to_candlesticks(time_interval)
# Define the expected result
expected_result = pd.DataFrame({
"PRICE_open": [10],
"PRICE_high": [15],
"PRICE_low": [10],
"PRICE_close": [12]
}, index=pd.to_datetime(["2021-01-01 00:00:00"]))
# Compare the actual result with the expected result
self.assertTrue(expected_result.equals(result))
if __name__ == "__main__":
unittest.main()
In this unittest, we create a test dataset with sample data and save it to a CSV file named "prices.csv" using the to_csv method of the pandas library. Then, we call the aggregate_trades_to_candlesticks function with the test parameters. Finally, we compare the actual result with the expected result using the equals method of the pandas library, and the assertTrue method of the unittest.TestCase class.
To write unit tests for the pd.DataFrame returned by the aggregate_trades_to_candlesticks function, you can use the unittest module and the pandas library. Here's an example of how you can write unit tests for the dataframe:
python
import unittest
import pandas as pd
from pathlib import Path
class TestCandlestickAggregation(unittest.TestCase):
def setUp(self):
# Create a sample dataframe for testing
self.trades_df = pd.DataFrame({
"TS": ["2021-01-01 00:00:00", "2021-01-01 00:01:00", "2021-01-01 00:02:00",
"2021-01-01 00:03:00"],
"PRICE": [10, 15, 12, 18]
})
self.trades_df["TS"] = pd.to_datetime(self.trades_df["TS"])
self.trades_df.set_index("TS", inplace=True)
# Save the sample dataframe to a CSV file
self.trades_df.to_csv(Path("price", "prices.csv"), index=True)
def tearDown(self):
# Remove the CSV file after testing
Path("price", "prices.csv").unlink(missing_ok=True)
def test_dataframe_columns(self):
time_interval = "5T"
# Call the function to be tested
result = aggregate_trades_to_candlesticks(time_interval)
# Check if the dataframe has the expected columns
expected_columns = ["PRICE_open", "PRICE_high", "PRICE_low", "PRICE_close"]
self.assertEqual(list(result.columns), expected_columns)
def test_dataframe_index(self):
time_interval = "5T"
# Call the function to be tested
result = aggregate_trades_to_candlesticks(time_interval)
# Check if the dataframe has the expected index
expected_index = pd.to_datetime(["2021-01-01 00:00:00"])
self.assertTrue(expected_index.equals(result.index))
def test_dataframe_values(self):
time_interval = "5T"
# Call the function to be tested
result = aggregate_trades_to_candlesticks(time_interval)
# Check if the dataframe values match the expected values
expected_values = [[10, 15, 10, 12]]
self.assertTrue(expected_values == result.values.tolist())
if __name__ == "__main__":
unittest.main()
In these unit tests, we use the setUp method to create a sample dataframe and save it to a CSV file before each test case. We use the tearDown method to remove the CSV file after each test case.
The test_dataframe_columns method checks if the dataframe has the expected columns. The test_dataframe_index method checks if the dataframe has the expected index. The test_dataframe_values method checks if the dataframe values match the expected values. We use assertions like self.assertEqual and self.assertTrue to compare the actual dataframe properties/values with the expected properties/values.
Sure! Here's an example of unit tests for the dataframe returned by the aggregate_trades_to_candlesticks function:
python
import unittest
import pandas as pd
from pathlib import Path
class TestCandlestickAggregation(unittest.TestCase):
def setUp(self):
# Create a sample dataframe for testing
self.trades_df = pd.DataFrame({
"TS": ["2021-01-01 00:00:00", "2021-01-01 00:01:00", "2021-01-01 00:02:00",
"2021-01-01 00:03:00"],
"PRICE": [10, 15, 12, 18]
})
self.trades_df["TS"] = pd.to_datetime(self.trades_df["TS"])
self.trades_df.set_index("TS", inplace=True)
# Save the sample dataframe to a CSV file
self.trades_df.to_csv(Path("price", "prices.csv"), index=True)
def tearDown(self):
# Remove the CSV file after testing
Path("price", "prices.csv").unlink(missing_ok=True)
def test_dataframe_columns(self):
time_interval = "5T"
# Call the function to be tested
result = aggregate_trades_to_candlesticks(time_interval)
# Check if the dataframe has the expected columns
expected_columns = ["PRICE_open", "PRICE_high", "PRICE_low", "PRICE_close"]
self.assertEqual(list(result.columns), expected_columns)
def test_dataframe_index(self):
time_interval = "5T"
# Call the function to be tested
result = aggregate_trades_to_candlesticks(time_interval)
# Check if the dataframe has the expected index
expected_index = pd.to_datetime(["2021-01-01 00:00:00"])
self.assertTrue(expected_index.equals(result.index))
def test_dataframe_values(self):
time_interval = "5T"
# Call the function to be tested
result = aggregate_trades_to_candlesticks(time_interval)
# Check if the dataframe values match the expected values
expected_values = [[10, 15, 10, 12]]
self.assertTrue(expected_values == result.values.tolist())
if __name__ == "__main__":
unittest.main()
In these unit tests, the setUp method is used to create a sample dataframe and save it to a CSV file before each test case. The tearDown method is used to remove the CSV file after each test case.
The test_dataframe_columns method asserts that the dataframe has the expected columns. The test_dataframe_index method asserts that the dataframe has the expected index. The test_dataframe_values method asserts that the dataframe values match the expected values.
You can run these unit tests by executing python -m unittest test_file.py in the command line, where test_file.py is the name of the Python file where you have written these unit tests.