Compare commits
14 Commits
find_close
...
master
Author | SHA1 | Date | |
---|---|---|---|
173fba0f03 | |||
a4ecd38b97 | |||
3e5875b873 | |||
2f50894b46 | |||
|
06be27d46c | ||
c453ff20e5 | |||
a455cdfc65 | |||
f317a93bfe | |||
|
14afb1400a | ||
0bab00f455 | |||
56e8017de7 | |||
7108fa2a56 | |||
6cf56ddf11 | |||
3a5ca91234 |
34
README.md
34
README.md
@ -1,22 +1,28 @@
|
||||
# PyFacts
|
||||
|
||||
PyFacts stands for Python library for Financial analysis and computations on time series. It is a library which makes it simple to work with time series data.
|
||||
|
||||
Most libraries, and languages like SQL, work with rows. Operations are performed by rows and not by dates. For instance, to calculate 1-year rolling returns in SQL, you are forced to use either a lag of 365/252 rows, leading to an approximation, or slow and cumbersome joins. PyFacts solves this by allowing you to work with dates and time intervals. Hence, to calculate 1-year returns, you will be specifying a lag of 1-year and the library will do the grunt work of finding the most appropriate observations to calculate these returns on.
|
||||
|
||||
## The problem
|
||||
|
||||
Libraries and languages usually don't allow comparison based on dates. Calculating month on month or year on year returns are always cumbersome as users are forced to rely on row lags. However, data always have inconsistencies, especially financial data. Markets don't work on weekends, there are off days, data doesn't get released on a few days a year, data availability is patchy when dealing with 40-year old data. All these problems are exacerbated when you are forced to make calculations using lag.
|
||||
|
||||
## The Solution
|
||||
|
||||
PyFacts aims to simplify things by allowing you to:
|
||||
* Compare time-series data based on dates and time-period-based lag
|
||||
* Easy way to work around missing dates by taking the closest data points
|
||||
* Completing series with missing data points using forward fill and backward fill
|
||||
* Use friendly dates everywhere written as a simple string
|
||||
|
||||
- Compare time-series data based on dates and time-period-based lag
|
||||
- Easy way to work around missing dates by taking the closest data points
|
||||
- Completing series with missing data points using forward fill and backward fill
|
||||
- Use friendly dates everywhere written as a simple string
|
||||
|
||||
## Creating a time series
|
||||
|
||||
Time series data can be created from a dictionary, a list of lists/tuples/dicts, or by reading a csv file.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
>>> import pyfacts as pft
|
||||
|
||||
@ -33,6 +39,7 @@ Example:
|
||||
```
|
||||
|
||||
### Sample usage
|
||||
|
||||
```
|
||||
>>> ts.calculate_returns(as_on='2021-04-01', return_period_unit='months', return_period_value=3, annual_compounded_returns=False)
|
||||
(datetime.datetime(2021, 4, 1, 0, 0), 0.6)
|
||||
@ -42,21 +49,24 @@ Example:
|
||||
```
|
||||
|
||||
### Working with dates
|
||||
|
||||
With PyFacts, you never have to go into the hassle of creating datetime objects for your time series. PyFacts will parse any date passed to it as string. The default format is ISO format, i.e., YYYY-MM-DD. However, you can use your preferred format simply by specifying it in the options in datetime library compatible format, after importing the library. For example, to use DD-MM-YYY format:
|
||||
|
||||
```
|
||||
>>> import pyfacts as pft
|
||||
>>> pft.PyfactsOptions.date_format = '%d-%m-%Y'
|
||||
```
|
||||
|
||||
Now the library will automatically parse all dates as DD-MM-YYYY
|
||||
|
||||
If you happen to have any one situation where you need to use a different format, all methods accept a date_format parameter to override the default.
|
||||
|
||||
|
||||
### Working with multiple time series
|
||||
|
||||
While working with time series data, you will often need to perform calculations on the data. PyFacts supports all kinds of mathematical operations on time series.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
>>> import pyfacts as pft
|
||||
|
||||
@ -83,6 +93,7 @@ TimeSeries([(datetime.datetime(2022, 1, 1, 0, 0), 0.1),
|
||||
Mathematical operations can also be done between time series as long as they have the same dates.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
>>> import pyfacts as pft
|
||||
|
||||
@ -110,6 +121,7 @@ TimeSeries([(datetime.datetime(2022, 1, 1, 0, 0), 1.0),
|
||||
However, if the dates are not in sync, PyFacts provides convenience methods for syncronising dates.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
>>> import pyfacts as pft
|
||||
|
||||
@ -146,6 +158,7 @@ TimeSeries([(datetime.datetime(2022, 1, 1, 0, 0), 20.0),
|
||||
Even if you need to perform calculations on data with different frequencies, PyFacts will let you easily handle this with the expand and shrink methods.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
>>> data = [
|
||||
... ("2022-01-01", 10),
|
||||
@ -176,6 +189,7 @@ TimeSeries([(datetime.datetime(2022, 1, 1, 0, 0), 10.0),
|
||||
If you want to shorten the timeframe of the data with an aggregation function, the transform method will help you out. Currently it supports sum and mean.
|
||||
|
||||
Example:
|
||||
|
||||
```
|
||||
>>> data = [
|
||||
... ("2022-01-01", 10),
|
||||
@ -208,11 +222,11 @@ TimeSeries([(datetime.datetime(2022, 1, 1, 0, 0), 12.0),
|
||||
(datetime.datetime(2022, 10, 1, 0, 0), 30.0)], frequency='Q')
|
||||
```
|
||||
|
||||
|
||||
## To-do
|
||||
|
||||
### Core features
|
||||
- [x] Add __setitem__
|
||||
|
||||
- [x] Add **setitem**
|
||||
- [ ] Create emtpy TimeSeries object
|
||||
- [x] Read from CSV
|
||||
- [ ] Write to CSV
|
||||
@ -220,18 +234,20 @@ TimeSeries([(datetime.datetime(2022, 1, 1, 0, 0), 12.0),
|
||||
- [x] Convert to list of tuples
|
||||
|
||||
### pyfacts features
|
||||
|
||||
- [x] Sync two TimeSeries
|
||||
- [x] Average rolling return
|
||||
- [x] Sharpe ratio
|
||||
- [x] Jensen's Alpha
|
||||
- [x] Beta
|
||||
- [ ] Sortino ratio
|
||||
- [x] Sortino ratio
|
||||
- [x] Correlation & R-squared
|
||||
- [ ] Treynor ratio
|
||||
- [x] Max drawdown
|
||||
- [ ] Moving average
|
||||
|
||||
### Pending implementation
|
||||
|
||||
- [x] Use limit parameter in ffill and bfill
|
||||
- [x] Implementation of ffill and bfill may be incorrect inside expand, check and correct
|
||||
- [ ] Implement interpolation in expand
|
||||
- [ ] Implement interpolation in expand
|
||||
|
@ -2,3 +2,26 @@ from .core import *
|
||||
from .pyfacts import *
|
||||
from .statistics import *
|
||||
from .utils import *
|
||||
|
||||
__author__ = "Gourav Kumar"
|
||||
__email__ = "gouravkr@outlook.in"
|
||||
__version__ = "0.0.1"
|
||||
|
||||
|
||||
__doc__ = """
|
||||
PyFacts stands for Python library for Financial analysis and computations on time series.
|
||||
It is a library which makes it simple to work with time series data.
|
||||
|
||||
Most libraries, and languages like SQL, work with rows. Operations are performed by rows
|
||||
and not by dates. For instance, to calculate 1-year rolling returns in SQL, you are forced
|
||||
to use either a lag of 365/252 rows, leading to an approximation, or slow and cumbersome
|
||||
joins. PyFacts solves this by allowing you to work with dates and time intervals. Hence,
|
||||
to calculate 1-year returns, you will be specifying a lag of 1-year and the library will
|
||||
do the grunt work of finding the most appropriate observations to calculate these returns on.
|
||||
|
||||
PyFacts aims to simplify things by allowing you to:
|
||||
* Compare time-series data based on dates and time-period-based lag
|
||||
* Easy way to work around missing dates by taking the closest data points
|
||||
* Completing series with missing data points using forward fill and backward fill
|
||||
* Use friendly dates everywhere written as a simple string
|
||||
"""
|
||||
|
@ -76,29 +76,28 @@ def create_date_series(
|
||||
if eomonth and frequency.days < AllFrequencies.M.days:
|
||||
raise ValueError(f"eomonth cannot be set to True if frequency is higher than {AllFrequencies.M.name}")
|
||||
|
||||
if ensure_coverage:
|
||||
if frequency.days == 1 and skip_weekends and end_date.weekday() > 4:
|
||||
extend_by_days = 7 - end_date.weekday()
|
||||
end_date += relativedelta(days=extend_by_days)
|
||||
|
||||
# TODO: Add code to ensure coverage for other frequencies as well
|
||||
|
||||
datediff = (end_date - start_date).days / frequency.days + 1
|
||||
dates = []
|
||||
|
||||
for i in range(0, int(datediff)):
|
||||
diff = {frequency.freq_type: frequency.value * i}
|
||||
counter = 0
|
||||
while counter < 100000:
|
||||
diff = {frequency.freq_type: frequency.value * counter}
|
||||
date = start_date + relativedelta(**diff)
|
||||
|
||||
if eomonth:
|
||||
replacement = {"month": date.month + 1} if date.month < 12 else {"year": date.year + 1}
|
||||
date = date.replace(day=1).replace(**replacement) - relativedelta(days=1)
|
||||
date += relativedelta(months=1, day=1, days=-1)
|
||||
|
||||
if date <= end_date:
|
||||
if frequency.days > 1 or not skip_weekends:
|
||||
dates.append(date)
|
||||
elif date.weekday() < 5:
|
||||
dates.append(date)
|
||||
if date > end_date:
|
||||
if not ensure_coverage:
|
||||
break
|
||||
elif dates[-1] >= end_date:
|
||||
break
|
||||
|
||||
counter += 1
|
||||
if frequency.days > 1 or not skip_weekends:
|
||||
dates.append(date)
|
||||
elif date.weekday() < 5:
|
||||
dates.append(date)
|
||||
else:
|
||||
raise ValueError("Cannot generate a series containing more than 100000 dates")
|
||||
|
||||
return Series(dates, dtype="date")
|
||||
|
||||
@ -568,6 +567,7 @@ class TimeSeries(TimeSeriesCore):
|
||||
Parameters
|
||||
----------
|
||||
kwargs: parameters to be passed to the calculate_rolling_returns() function
|
||||
Refer TimeSeries.calculate_rolling_returns() method for more details
|
||||
|
||||
Returns
|
||||
-------
|
||||
@ -805,7 +805,12 @@ class TimeSeries(TimeSeriesCore):
|
||||
return statistics.mean(self.values)
|
||||
|
||||
def transform(
|
||||
self, to_frequency: Literal["W", "M", "Q", "H", "Y"], method: Literal["sum", "mean"], eomonth: bool = False
|
||||
self,
|
||||
to_frequency: Literal["W", "M", "Q", "H", "Y"],
|
||||
method: Literal["sum", "mean"],
|
||||
eomonth: bool = False,
|
||||
ensure_coverage: bool = True,
|
||||
anchor_date=Literal["start", "end"],
|
||||
) -> TimeSeries:
|
||||
"""Transform a time series object into a lower frequency object with an aggregation function.
|
||||
|
||||
@ -845,28 +850,33 @@ class TimeSeries(TimeSeriesCore):
|
||||
|
||||
dates = create_date_series(
|
||||
self.start_date,
|
||||
self.end_date
|
||||
+ datetime.timedelta(to_frequency.days), # need extra date at the end for calculation of last value
|
||||
self.end_date, # + relativedelta(days=to_frequency.days),
|
||||
to_frequency.symbol,
|
||||
ensure_coverage=True,
|
||||
ensure_coverage=ensure_coverage,
|
||||
eomonth=eomonth,
|
||||
)
|
||||
prev_date = dates[0]
|
||||
# prev_date = dates[0]
|
||||
|
||||
new_ts_dict = {}
|
||||
for date in dates[1:]:
|
||||
cur_data = self[(self.dates >= prev_date) & (self.dates < date)]
|
||||
for idx, date in enumerate(dates):
|
||||
if idx == 0:
|
||||
cur_data = self[self.dates <= date]
|
||||
else:
|
||||
cur_data = self[(self.dates <= date) & (self.dates > dates[idx - 1])]
|
||||
if method == "sum":
|
||||
value = sum(cur_data.values)
|
||||
elif method == "mean":
|
||||
value = cur_data.mean()
|
||||
|
||||
new_ts_dict.update({prev_date: value})
|
||||
prev_date = date
|
||||
new_ts_dict.update({date: value})
|
||||
# prev_date = date
|
||||
|
||||
return self.__class__(new_ts_dict, to_frequency.symbol)
|
||||
|
||||
|
||||
def _preprocess_csv(file_path: str | pathlib.Path, delimiter: str = ",", encoding: str = "utf-8") -> List[list]:
|
||||
def _preprocess_csv(
|
||||
file_path: str | pathlib.Path, delimiter: str = ",", encoding: str = "utf-8", **kwargs
|
||||
) -> List[list]:
|
||||
"""Preprocess csv data"""
|
||||
|
||||
if isinstance(file_path, str):
|
||||
@ -876,7 +886,7 @@ def _preprocess_csv(file_path: str | pathlib.Path, delimiter: str = ",", encodin
|
||||
raise ValueError("File not found. Check the file path")
|
||||
|
||||
with open(file_path, "r", encoding=encoding) as file:
|
||||
reader: csv.reader = csv.reader(file, delimiter=delimiter)
|
||||
reader: csv.reader = csv.reader(file, delimiter=delimiter, **kwargs)
|
||||
csv_data: list = list(reader)
|
||||
|
||||
csv_data = [i for i in csv_data if i] # remove blank rows
|
||||
@ -897,8 +907,51 @@ def read_csv(
|
||||
nrows: int = -1,
|
||||
delimiter: str = ",",
|
||||
encoding: str = "utf-8",
|
||||
**kwargs,
|
||||
) -> TimeSeries:
|
||||
"""Reads Time Series data directly from a CSV file"""
|
||||
"""Reads Time Series data directly from a CSV file
|
||||
|
||||
Parameters
|
||||
----------
|
||||
csv_file_pah:
|
||||
path of the csv file to be read.
|
||||
|
||||
frequency:
|
||||
frequency of the time series data.
|
||||
|
||||
date_format:
|
||||
date format, specified as datetime compatible string
|
||||
|
||||
col_names:
|
||||
specify the column headers to be read.
|
||||
this parameter will allow you to read two columns from a CSV file which may have more columns.
|
||||
this parameter overrides col_index parameter.
|
||||
|
||||
dol_index:
|
||||
specify the column numbers to be read.
|
||||
this parameter will allow you to read two columns from a CSV file which may have more columns.
|
||||
if neither names nor index is specified, the first two columns from the csv file will be read,
|
||||
with the first being treated as date.
|
||||
|
||||
has_header:
|
||||
specify whether the file has a header row.
|
||||
if true, the header row will be ignored while creating the time series data.
|
||||
|
||||
skip_rows:
|
||||
the number of rows after the header which should be skipped.
|
||||
|
||||
nrows:
|
||||
the number of rows to be read from the csv file.
|
||||
|
||||
delimiter:
|
||||
specify the delimeter used in the csv file.
|
||||
|
||||
encoding:
|
||||
specify the encoding of the csv file.
|
||||
|
||||
kwargs:
|
||||
other keyword arguments to be passed on the csv.reader()
|
||||
"""
|
||||
|
||||
data = _preprocess_csv(csv_file_path, delimiter, encoding)
|
||||
|
||||
|
@ -7,7 +7,7 @@ from typing import Literal
|
||||
|
||||
from pyfacts.core import date_parser
|
||||
|
||||
from .pyfacts import TimeSeries
|
||||
from .pyfacts import TimeSeries, create_date_series
|
||||
from .utils import _interval_to_years, _preprocess_from_to_date, covariance
|
||||
|
||||
# from dateutil.relativedelta import relativedelta
|
||||
@ -587,3 +587,35 @@ def sortino_ratio(
|
||||
|
||||
sortino_ratio_value = excess_returns / sd
|
||||
return sortino_ratio_value
|
||||
|
||||
|
||||
@date_parser(3, 4)
|
||||
def moving_average(
|
||||
time_series_data: TimeSeries,
|
||||
moving_average_period_unit: Literal["years", "months", "days"],
|
||||
moving_average_period_value: int,
|
||||
from_date: str | datetime.datetime = None,
|
||||
to_date: str | datetime.datetime = None,
|
||||
as_on_match: str = "closest",
|
||||
prior_match: str = "closest",
|
||||
closest: Literal["previous", "next"] = "previous",
|
||||
date_format: str = None,
|
||||
) -> TimeSeries:
|
||||
|
||||
from_date, to_date = _preprocess_from_to_date(
|
||||
from_date,
|
||||
to_date,
|
||||
time_series_data,
|
||||
False,
|
||||
return_period_unit=moving_average_period_unit,
|
||||
return_period_value=moving_average_period_value,
|
||||
as_on_match=as_on_match,
|
||||
prior_match=prior_match,
|
||||
closest=closest,
|
||||
)
|
||||
|
||||
dates = create_date_series(from_date, to_date, time_series_data.frequency.symbol)
|
||||
|
||||
for date in dates:
|
||||
start_date = date - datetime.timedelta(**{moving_average_period_unit: moving_average_period_value})
|
||||
time_series_data[start_date:date]
|
||||
|
@ -1,6 +1,7 @@
|
||||
attrs==21.4.0
|
||||
black==22.1.0
|
||||
click==8.1.3
|
||||
python-dateutil==2.8.2
|
||||
flake8==4.0.1
|
||||
iniconfig==1.1.1
|
||||
isort==5.10.1
|
||||
|
3
setup.py
3
setup.py
@ -2,9 +2,10 @@ from setuptools import find_packages, setup
|
||||
|
||||
license = open("LICENSE").read().strip()
|
||||
|
||||
|
||||
setup(
|
||||
name="pyfacts",
|
||||
version=open("VERSION").read().strip(),
|
||||
version="0.0.1",
|
||||
license=license,
|
||||
author="Gourav Kumar",
|
||||
author_email="gouravkr@outlook.in",
|
||||
|
@ -3,10 +3,11 @@ import math
|
||||
import random
|
||||
from typing import List
|
||||
|
||||
import pyfacts as pft
|
||||
import pytest
|
||||
from dateutil.relativedelta import relativedelta
|
||||
|
||||
import pyfacts as pft
|
||||
|
||||
|
||||
def conf_add(n1, n2):
|
||||
return n1 + n2
|
||||
@ -95,7 +96,9 @@ def sample_data_generator(
|
||||
)
|
||||
}
|
||||
end_date = start_date + relativedelta(**timedelta_dict)
|
||||
dates = pft.create_date_series(start_date, end_date, frequency.symbol, skip_weekends=skip_weekends, eomonth=eomonth)
|
||||
dates = pft.create_date_series(
|
||||
start_date, end_date, frequency.symbol, skip_weekends=skip_weekends, eomonth=eomonth, ensure_coverage=False
|
||||
)
|
||||
if dates_as_string:
|
||||
dates = [dt.strftime("%Y-%m-%d") for dt in dates]
|
||||
values = create_prices(1000, mu, sigma, num)
|
||||
|
@ -1,6 +1,7 @@
|
||||
import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from pyfacts import (
|
||||
AllFrequencies,
|
||||
Frequency,
|
||||
@ -29,7 +30,7 @@ class TestDateSeries:
|
||||
def test_monthly(self):
|
||||
start_date = datetime.datetime(2020, 1, 1)
|
||||
end_date = datetime.datetime(2020, 12, 31)
|
||||
d = create_date_series(start_date, end_date, frequency="M")
|
||||
d = create_date_series(start_date, end_date, frequency="M", ensure_coverage=False)
|
||||
assert len(d) == 12
|
||||
|
||||
d = create_date_series(start_date, end_date, frequency="M", eomonth=True)
|
||||
@ -326,7 +327,7 @@ class TestExpand:
|
||||
ts_data = create_test_data(AllFrequencies.M, num=6)
|
||||
ts = TimeSeries(ts_data, "M")
|
||||
expanded_ts = ts.expand("W", "ffill")
|
||||
assert len(expanded_ts) == 22
|
||||
assert len(expanded_ts) == 23
|
||||
assert expanded_ts.frequency.name == "weekly"
|
||||
assert expanded_ts.iloc[0][1] == expanded_ts.iloc[1][1]
|
||||
|
||||
@ -340,8 +341,23 @@ class TestExpand:
|
||||
|
||||
|
||||
class TestShrink:
|
||||
# TODO
|
||||
pass
|
||||
def test_daily_to_smaller(self, create_test_data):
|
||||
ts_data = create_test_data(AllFrequencies.D, num=1000)
|
||||
ts = TimeSeries(ts_data, "D")
|
||||
shrunk_ts_w = ts.shrink("W", "ffill")
|
||||
shrunk_ts_m = ts.shrink("M", "ffill")
|
||||
assert len(shrunk_ts_w) == 144
|
||||
assert len(shrunk_ts_m) == 34
|
||||
|
||||
def test_weekly_to_smaller(self, create_test_data):
|
||||
ts_data = create_test_data(AllFrequencies.W, num=300)
|
||||
ts = TimeSeries(ts_data, "W")
|
||||
tsm = ts.shrink("M", "ffill")
|
||||
assert len(tsm) == 70
|
||||
tsmeo = ts.shrink("M", "ffill", eomonth=True)
|
||||
assert len(tsmeo) == 69
|
||||
with pytest.raises(ValueError):
|
||||
ts.shrink("D", "ffill")
|
||||
|
||||
|
||||
class TestMeanReturns:
|
||||
@ -358,29 +374,29 @@ class TestTransform:
|
||||
def test_daily_to_weekly(self, create_test_data):
|
||||
ts_data = create_test_data(AllFrequencies.D, num=782, skip_weekends=True)
|
||||
ts = TimeSeries(ts_data, "D")
|
||||
tst = ts.transform("W", "mean")
|
||||
tst = ts.transform("W", "mean", ensure_coverage=False)
|
||||
assert isinstance(tst, TimeSeries)
|
||||
assert len(tst) == 157
|
||||
assert "2017-01-30" in tst
|
||||
assert tst.iloc[4] == (datetime.datetime(2017, 1, 30), 1021.19)
|
||||
assert tst.iloc[4] == (datetime.datetime(2017, 1, 30), 1020.082)
|
||||
|
||||
def test_daily_to_monthly(self, create_test_data):
|
||||
ts_data = create_test_data(AllFrequencies.D, num=782, skip_weekends=False)
|
||||
ts = TimeSeries(ts_data, "D")
|
||||
tst = ts.transform("M", "mean")
|
||||
assert isinstance(tst, TimeSeries)
|
||||
assert len(tst) == 26
|
||||
assert len(tst) == 27
|
||||
assert "2018-01-01" in tst
|
||||
assert round(tst.iloc[12][1], 2) == 1146.1
|
||||
assert round(tst.iloc[12][1], 2) == 1146.91
|
||||
|
||||
def test_daily_to_yearly(self, create_test_data):
|
||||
ts_data = create_test_data(AllFrequencies.D, num=782, skip_weekends=True)
|
||||
ts = TimeSeries(ts_data, "D")
|
||||
tst = ts.transform("Y", "mean")
|
||||
assert isinstance(tst, TimeSeries)
|
||||
assert len(tst) == 3
|
||||
assert len(tst) == 4
|
||||
assert "2019-01-02" in tst
|
||||
assert tst.iloc[2] == (datetime.datetime(2019, 1, 2), 1238.5195)
|
||||
assert tst.iloc[2] == (datetime.datetime(2019, 1, 2), 1157.2835632183908)
|
||||
|
||||
def test_weekly_to_monthly(self, create_test_data):
|
||||
ts_data = create_test_data(AllFrequencies.W, num=261)
|
||||
@ -388,22 +404,22 @@ class TestTransform:
|
||||
tst = ts.transform("M", "mean")
|
||||
assert isinstance(tst, TimeSeries)
|
||||
assert "2017-01-01" in tst
|
||||
assert tst.iloc[0] == (datetime.datetime(2017, 1, 1), 1007.33)
|
||||
assert tst.iloc[1] == (datetime.datetime(2017, 2, 1), 1008.405)
|
||||
|
||||
def test_weekly_to_qty(self, create_test_data):
|
||||
ts_data = create_test_data(AllFrequencies.W, num=261)
|
||||
ts = TimeSeries(ts_data, "W")
|
||||
tst = ts.transform("Q", "mean")
|
||||
assert len(tst) == 20
|
||||
assert len(tst) == 21
|
||||
assert "2018-01-01" in tst
|
||||
assert round(tst.iloc[4][1], 2) == 1054.72
|
||||
assert round(tst.iloc[4][1], 2) == 1032.01
|
||||
|
||||
def test_weekly_to_yearly(self, create_test_data):
|
||||
ts_data = create_test_data(AllFrequencies.W, num=261)
|
||||
ts = TimeSeries(ts_data, "W")
|
||||
tst = ts.transform("Y", "mean")
|
||||
assert "2019-01-01" in tst
|
||||
assert round(tst.iloc[2][1], 2) == 1054.50
|
||||
assert round(tst.iloc[2][1], 2) == 1053.70
|
||||
with pytest.raises(ValueError):
|
||||
ts.transform("D", "mean")
|
||||
|
||||
@ -411,9 +427,9 @@ class TestTransform:
|
||||
ts_data = create_test_data(AllFrequencies.M, num=36)
|
||||
ts = TimeSeries(ts_data, "M")
|
||||
tst = ts.transform("Q", "mean")
|
||||
assert len(tst) == 12
|
||||
assert len(tst) == 13
|
||||
assert "2018-10-01" in tst
|
||||
assert tst.iloc[7] == (datetime.datetime(2018, 10, 1), 1021.19)
|
||||
assert tst.iloc[7] == (datetime.datetime(2018, 10, 1), 1022.6466666666666)
|
||||
with pytest.raises(ValueError):
|
||||
ts.transform("M", "sum")
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user