diff --git a/.gitattributes b/.gitattributes
index 67e523680c5b508c690d044ccc117962991e7ca1..641f0852a2f62586f97250bea23f906a175a8d38 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -144,3 +144,5 @@ tasks/tasksmith-87860368c397/tests/source/tests/pdfs/issue-982-example.pdf filte
tasks/tasksmith-87860368c397/tests/source/tests/pdfs/pdffill-demo.pdf filter=lfs diff=lfs merge=lfs -text
tasks/tasksmith-87860368c397/tests/source/tests/pdfs/pr-136-example.pdf filter=lfs diff=lfs merge=lfs -text
tasks/tasksmith-87860368c397/tests/source/tests/pdfs/table-curves-example.pdf filter=lfs diff=lfs merge=lfs -text
+tasks/tasksmith-ca08ab4caec6/environment/source/etc/NYSE-Historical-Closings.pdf filter=lfs diff=lfs merge=lfs -text
+tasks/tasksmith-ca08ab4caec6/tests/source/etc/NYSE-Historical-Closings.pdf filter=lfs diff=lfs merge=lfs -text
diff --git a/tasks/tasksmith-a7e859277e7a/environment/source/pyproject.toml b/tasks/tasksmith-a7e859277e7a/environment/source/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..6dedf1e64e01e4fd18e2d3852d86eecab1de031a
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/environment/source/pyproject.toml
@@ -0,0 +1,64 @@
+[build-system]
+requires = ["poetry-core"]
+build-backend = "poetry.core.masonry.api"
+
+
+[tool.poetry]
+name = "numpy-financial"
+version = "2.0.0"
+description = "Simple financial functions"
+license = "BSD-3-Clause"
+authors = ["Travis E. Oliphant et al."]
+maintainers = ["Numpy Financial Developers "]
+readme = "README.md"
+homepage = "https://numpy.org/numpy-financial/latest/"
+repository = "https://github.com/numpy/numpy-financial"
+documentation = "https://numpy.org/numpy-financial/latest/#functions"
+classifiers = [
+ "Development Status :: 5 - Production/Stable",
+ "Intended Audience :: Developers",
+ "Intended Audience :: Financial and Insurance Industry",
+ "License :: OSI Approved :: BSD License",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3 :: Only",
+ "Topic :: Software Development",
+ "Topic :: Office/Business :: Financial :: Accounting",
+ "Topic :: Office/Business :: Financial :: Investment",
+ "Topic :: Office/Business :: Financial :: Spreadsheet",
+ "Operating System :: Microsoft :: Windows",
+ "Operating System :: POSIX",
+ "Operating System :: Unix",
+ "Operating System :: MacOS",
+]
+packages = [{include = "numpy_financial"}]
+
+[tool.poetry.dependencies]
+python = "^3.10"
+numpy = "^1.23"
+numba = "^0.59.1"
+
+[tool.poetry.group.test.dependencies]
+pytest = "^8.0"
+hypothesis = {extras = ["numpy"], version = "^6.99.11"}
+pytest-xdist = {extras = ["psutil"], version = "^3.5.0"}
+
+
+[tool.poetry.group.docs.dependencies]
+sphinx = "^7.0"
+numpydoc = "^1.5"
+pydata-sphinx-theme = "^0.14.3"
+myst-parser = "^2.0.0"
+
+
+
+[tool.poetry.group.lint.dependencies]
+ruff = "^0.3"
+
+
+[tool.poetry.group.bench.dependencies]
+asv = "^0.6"
+
diff --git a/tasks/tasksmith-a7e859277e7a/instruction.md b/tasks/tasksmith-a7e859277e7a/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..c3a4d60d3ad3062a80907596498e0583bcefd2ed
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/instruction.md
@@ -0,0 +1,25 @@
+Rework `npf.npv(rate, values)` to support broadcasting over multiple rates and cashflow series.
+
+**New behavior:**
+
+- When `rate` is a 1-D array of length *R* and `values` is a 2-D array of shape *(C, T)*, `npv` must return an array of shape *(R, C)* where entry `[i, j]` is the NPV of cashflow row `j` discounted at `rates[i]`.
+- When either argument is a scalar / 1-D cashflow (single series), the result should be squeezed: a scalar when only one rate and one cashflow, a 1-D array otherwise.
+- A `rate` whose array representation has `ndim > 1` (e.g. a 2-D list or a 3-D array) must raise `ValueError`.
+- A `values` input whose array representation has `ndim > 2` (e.g. a 3-D list or array) must raise `ValueError`.
+- When `rate` is exactly `-1` (integer or float), the function must return `nan` instead of raising an error.
+
+**Preserved behavior:**
+`npv(scalar_rate, 1d_cashflow)` continues to return a scalar with the same formula:
+`sum(values[t] / (1 + rate)**t for t in range(T))`.
+
+**Example:**
+```python
+rates = [0.00, 0.05, 0.10]
+cashflows = [[-4_000, 500, 800], [-5_000, 600, 900]]
+npf.npv(rates, cashflows)
+# array([[-2700. , -3500. ],
+# [-2798.19, -3612.24],
+# [-2884.3 , -3710.74]])
+```
+
+Work in `/workspace`. Submit your fix in Python source files under `numpy_financial`, `benchmarks/benchmarks.py`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files.
diff --git a/tasks/tasksmith-a7e859277e7a/solution/reference/benchmarks/benchmarks.py b/tasks/tasksmith-a7e859277e7a/solution/reference/benchmarks/benchmarks.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d074f3b01721715958d884431d5c46a9213119b
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/solution/reference/benchmarks/benchmarks.py
@@ -0,0 +1,31 @@
+import numpy as np
+
+import numpy_financial as npf
+
+
+class Npv2D:
+
+ param_names = ["n_cashflows", "cashflow_lengths", "rates_lengths"]
+ params = [
+ (1, 10, 100),
+ (1, 10, 100),
+ (1, 10, 100),
+ ]
+
+ def __init__(self):
+ self.rates = None
+ self.cashflows = None
+
+ def setup(self, n_cashflows, cashflow_lengths, rates_lengths):
+ rng = np.random.default_rng(0)
+ cf_shape = (n_cashflows, cashflow_lengths)
+ self.cashflows = rng.standard_normal(cf_shape)
+ self.rates = rng.standard_normal(rates_lengths)
+
+ def time_for_loop(self, n_cashflows, cashflow_lengths, rates_lengths):
+ for rate in self.rates:
+ for cashflow in self.cashflows:
+ npf.npv(rate, cashflow)
+
+ def time_broadcast(self, n_cashflows, cashflow_lengths, rates_lengths):
+ npf.npv(self.rates, self.cashflows)
diff --git a/tasks/tasksmith-a7e859277e7a/solution/reference/numpy_financial/_financial.py b/tasks/tasksmith-a7e859277e7a/solution/reference/numpy_financial/_financial.py
new file mode 100644
index 0000000000000000000000000000000000000000..61d3723d620d09839f3c7f3dc70c32650529e626
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/solution/reference/numpy_financial/_financial.py
@@ -0,0 +1,1041 @@
+"""Some simple financial calculations.
+
+patterned after spreadsheet computations.
+
+There is some complexity in each function
+so that the functions behave like ufuncs with
+broadcasting and being able to be called with scalars
+or arrays (or other sequences).
+
+Functions support the :class:`decimal.Decimal` type unless
+otherwise stated.
+"""
+
+from decimal import Decimal
+
+import numba as nb
+import numpy as np
+
+__all__ = ['fv', 'pmt', 'nper', 'ipmt', 'ppmt', 'pv', 'rate',
+ 'irr', 'npv', 'mirr',
+ 'NoRealSolutionError', 'IterationsExceededError']
+
+_when_to_num = {'end': 0, 'begin': 1,
+ 'e': 0, 'b': 1,
+ 0: 0, 1: 1,
+ 'beginning': 1,
+ 'start': 1,
+ 'finish': 0}
+
+
+class NoRealSolutionError(Exception):
+ """No real solution to the problem."""
+
+
+class IterationsExceededError(Exception):
+ """Maximum number of iterations reached."""
+
+
+def _get_output_array_shape(*arrays):
+ return tuple(array.shape[0] for array in arrays)
+
+
+def _ufunc_like(array):
+ try:
+ # If size of array is one, return scalar
+ return array.item()
+ except ValueError:
+ # Otherwise, return entire array
+ return array.squeeze()
+
+
+def _convert_when(when):
+ # Test to see if when has already been converted to ndarray
+ # This will happen if one function calls another, for example ppmt
+ if isinstance(when, np.ndarray):
+ return when
+ try:
+ return _when_to_num[when]
+ except (KeyError, TypeError):
+ return [_when_to_num[x] for x in when]
+
+
+def fv(rate, nper, pmt, pv, when='end'):
+ """Compute the future value.
+
+ Given:
+ * a present value, `pv`
+ * an interest `rate` compounded once per period, of which
+ there are
+ * `nper` total
+ * a (fixed) payment, `pmt`, paid either
+ * at the beginning (`when` = {'begin', 1}) or the end
+ (`when` = {'end', 0}) of each period
+
+ Return:
+ the value at the end of the `nper` periods
+
+ Parameters
+ ----------
+ rate : scalar or array_like of shape(M, )
+ Rate of interest as decimal (not per cent) per period
+ nper : scalar or array_like of shape(M, )
+ Number of compounding periods
+ pmt : scalar or array_like of shape(M, )
+ Payment
+ pv : scalar or array_like of shape(M, )
+ Present value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
+ When payments are due ('begin' (1) or 'end' (0)).
+ Defaults to {'end', 0}.
+
+ Returns
+ -------
+ out : ndarray
+ Future values. If all input is scalar, returns a scalar float. If
+ any input is array_like, returns future values for each input element.
+ If multiple inputs are array_like, they all must have the same shape.
+
+ Notes
+ -----
+ The future value is computed by solving the equation::
+
+ fv +
+ pv*(1+rate)**nper +
+ pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
+
+ or, when ``rate == 0``::
+
+ fv + pv + pmt * nper == 0
+
+ References
+ ----------
+ .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May).
+ Open Document Format for Office Applications (OpenDocument)v1.2,
+ Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version,
+ Pre-Draft 12. Organization for the Advancement of Structured Information
+ Standards (OASIS). Billerica, MA, USA. [ODT Document].
+ Available:
+ http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula
+ OpenDocument-formula-20090508.odt
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import numpy_financial as npf
+
+ What is the future value after 10 years of saving $100 now, with
+ an additional monthly savings of $100. Assume the interest rate is
+ 5% (annually) compounded monthly?
+
+ >>> npf.fv(0.05/12, 10*12, -100, -100)
+ 15692.92889433575
+
+ By convention, the negative sign represents cash flow out (i.e. money not
+ available today). Thus, saving $100 a month at 5% annual interest leads
+ to $15,692.93 available to spend in 10 years.
+
+ If any input is array_like, returns an array of equal shape. Let's
+ compare different interest rates from the example above.
+
+ >>> a = np.array((0.05, 0.06, 0.07))/12
+ >>> npf.fv(a, 10*12, -100, -100)
+ array([15692.92889434, 16569.87435405, 17509.44688102])
+
+ """
+ when = _convert_when(when)
+ rate, nper, pmt, pv, when = np.broadcast_arrays(rate, nper, pmt, pv, when)
+
+ fv_array = np.empty_like(rate)
+ zero = rate == 0
+ nonzero = ~zero
+
+ fv_array[zero] = -(pv[zero] + pmt[zero] * nper[zero])
+
+ rate_nonzero = rate[nonzero]
+ temp = (1 + rate_nonzero) ** nper[nonzero]
+ fv_array[nonzero] = (
+ - pv[nonzero] * temp
+ - pmt[nonzero] * (1 + rate_nonzero * when[nonzero]) / rate_nonzero
+ * (temp - 1)
+ )
+
+ if np.ndim(fv_array) == 0:
+ # Follow the ufunc convention of returning scalars for scalar
+ # and 0d array inputs.
+ return fv_array.item(0)
+ return fv_array
+
+
+def pmt(rate, nper, pv, fv=0, when='end'):
+ """Compute the payment against loan principal plus interest.
+
+ Given:
+ * a present value, `pv` (e.g., an amount borrowed)
+ * a future value, `fv` (e.g., 0)
+ * an interest `rate` compounded once per period, of which
+ there are
+ * `nper` total
+ * and (optional) specification of whether payment is made
+ at the beginning (`when` = {'begin', 1}) or the end
+ (`when` = {'end', 0}) of each period
+
+ Return:
+ the (fixed) periodic payment.
+
+ Parameters
+ ----------
+ rate : array_like
+ Rate of interest (per period)
+ nper : array_like
+ Number of compounding periods
+ pv : array_like
+ Present value
+ fv : array_like, optional
+ Future value (default = 0)
+ when : {{'begin', 1}, {'end', 0}}, {string, int}
+ When payments are due ('begin' (1) or 'end' (0))
+
+ Returns
+ -------
+ out : ndarray
+ Payment against loan plus interest. If all input is scalar, returns a
+ scalar float. If any input is array_like, returns payment for each
+ input element. If multiple inputs are array_like, they all must have
+ the same shape.
+
+ Notes
+ -----
+ The payment is computed by solving the equation::
+
+ fv +
+ pv*(1 + rate)**nper +
+ pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
+
+ or, when ``rate == 0``::
+
+ fv + pv + pmt * nper == 0
+
+ for ``pmt``.
+
+ Note that computing a monthly mortgage payment is only
+ one use for this function. For example, pmt returns the
+ periodic deposit one must make to achieve a specified
+ future balance given an initial deposit, a fixed,
+ periodically compounded interest rate, and the total
+ number of periods.
+
+ References
+ ----------
+ .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May).
+ Open Document Format for Office Applications (OpenDocument)v1.2,
+ Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version,
+ Pre-Draft 12. Organization for the Advancement of Structured Information
+ Standards (OASIS). Billerica, MA, USA. [ODT Document].
+ Available:
+ http://www.oasis-open.org/committees/documents.php
+ ?wg_abbrev=office-formulaOpenDocument-formula-20090508.odt
+
+ Examples
+ --------
+ >>> import numpy_financial as npf
+
+ What is the monthly payment needed to pay off a $200,000 loan in 15
+ years at an annual interest rate of 7.5%?
+
+ >>> npf.pmt(0.075/12, 12*15, 200000)
+ -1854.0247200054619
+
+ In order to pay-off (i.e., have a future-value of 0) the $200,000 obtained
+ today, a monthly payment of $1,854.02 would be required. Note that this
+ example illustrates usage of `fv` having a default value of 0.
+
+ """
+ when = _convert_when(when)
+ (rate, nper, pv, fv, when) = map(np.array, [rate, nper, pv, fv, when])
+ temp = (1 + rate) ** nper
+ mask = (rate == 0)
+ masked_rate = np.where(mask, 1, rate)
+ fact = np.where(mask != 0, nper,
+ (1 + masked_rate * when) * (temp - 1) / masked_rate)
+ return -(fv + pv * temp) / fact
+
+
+def nper(rate, pmt, pv, fv=0, when='end'):
+ """Compute the number of periodic payments.
+
+ :class:`decimal.Decimal` type is not supported.
+
+ Parameters
+ ----------
+ rate : array_like
+ Rate of interest (per period)
+ pmt : array_like
+ Payment
+ pv : array_like
+ Present value
+ fv : array_like, optional
+ Future value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
+ When payments are due ('begin' (1) or 'end' (0))
+
+ Notes
+ -----
+ The number of periods ``nper`` is computed by solving the equation::
+
+ fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate*((1+rate)**nper-1) = 0
+
+ but if ``rate = 0`` then::
+
+ fv + pv + pmt*nper = 0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import numpy_financial as npf
+
+ If you only had $150/month to pay towards the loan, how long would it take
+ to pay-off a loan of $8,000 at 7% annual interest?
+
+ >>> print(np.round(npf.nper(0.07/12, -150, 8000), 5))
+ 64.07335
+
+ So, over 64 months would be required to pay off the loan.
+
+ The same analysis could be done with several different interest rates
+ and/or payments and/or total amounts to produce an entire table.
+
+ >>> npf.nper(*(np.ogrid[0.07/12: 0.08/12: 0.01/12,
+ ... -150 : -99 : 50 ,
+ ... 8000 : 9001 : 1000]))
+ array([[[ 64.07334877, 74.06368256],
+ [108.07548412, 127.99022654]],
+
+ [[ 66.12443902, 76.87897353],
+ [114.70165583, 137.90124779]]])
+ """
+ when = _convert_when(when)
+ rate, pmt, pv, fv, when = np.broadcast_arrays(rate, pmt, pv, fv, when)
+ nper_array = np.empty_like(rate, dtype=np.float64)
+
+ zero = rate == 0
+ nonzero = ~zero
+
+ with np.errstate(divide='ignore'):
+ # Infinite numbers of payments are okay, so ignore the
+ # potential divide by zero.
+ nper_array[zero] = -(fv[zero] + pv[zero]) / pmt[zero]
+
+ nonzero_rate = rate[nonzero]
+ z = pmt[nonzero] * (1 + nonzero_rate * when[nonzero]) / nonzero_rate
+ nper_array[nonzero] = (
+ np.log((-fv[nonzero] + z) / (pv[nonzero] + z))
+ / np.log(1 + nonzero_rate)
+ )
+
+ return nper_array
+
+
+def _value_like(arr, value):
+ entry = arr.item(0)
+ if isinstance(entry, Decimal):
+ return Decimal(value)
+ return np.array(value, dtype=arr.dtype).item(0)
+
+
+def ipmt(rate, per, nper, pv, fv=0, when='end'):
+ """Compute the interest portion of a payment.
+
+ Parameters
+ ----------
+ rate : scalar or array_like of shape(M, )
+ Rate of interest as decimal (not per cent) per period
+ per : scalar or array_like of shape(M, )
+ Interest paid against the loan changes during the life or the loan.
+ The `per` is the payment period to calculate the interest amount.
+ nper : scalar or array_like of shape(M, )
+ Number of compounding periods
+ pv : scalar or array_like of shape(M, )
+ Present value
+ fv : scalar or array_like of shape(M, ), optional
+ Future value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
+ When payments are due ('begin' (1) or 'end' (0)).
+ Defaults to {'end', 0}.
+
+ Returns
+ -------
+ out : ndarray
+ Interest portion of payment. If all input is scalar, returns a scalar
+ float. If any input is array_like, returns interest payment for each
+ input element. If multiple inputs are array_like, they all must have
+ the same shape.
+
+ See Also
+ --------
+ ppmt, pmt, pv
+
+ Notes
+ -----
+ The total payment is made up of payment against principal plus interest.
+
+ ``pmt = ppmt + ipmt``
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import numpy_financial as npf
+
+ What is the amortization schedule for a 1 year loan of $2500 at
+ 8.24% interest per year compounded monthly?
+
+ >>> principal = 2500.00
+
+ The 'per' variable represents the periods of the loan. Remember that
+ financial equations start the period count at 1!
+
+ >>> per = np.arange(1*12) + 1
+ >>> ipmt = npf.ipmt(0.0824/12, per, 1*12, principal)
+ >>> ppmt = npf.ppmt(0.0824/12, per, 1*12, principal)
+
+ Each element of the sum of the 'ipmt' and 'ppmt' arrays should equal
+ 'pmt'.
+
+ >>> pmt = npf.pmt(0.0824/12, 1*12, principal)
+ >>> np.allclose(ipmt + ppmt, pmt)
+ True
+
+ >>> fmt = '{0:2d} {1:8.2f} {2:8.2f} {3:8.2f}'
+ >>> for payment in per:
+ ... index = payment - 1
+ ... principal = principal + ppmt[index]
+ ... print(fmt.format(payment, ppmt[index], ipmt[index], principal))
+ 1 -200.58 -17.17 2299.42
+ 2 -201.96 -15.79 2097.46
+ 3 -203.35 -14.40 1894.11
+ 4 -204.74 -13.01 1689.37
+ 5 -206.15 -11.60 1483.22
+ 6 -207.56 -10.18 1275.66
+ 7 -208.99 -8.76 1066.67
+ 8 -210.42 -7.32 856.25
+ 9 -211.87 -5.88 644.38
+ 10 -213.32 -4.42 431.05
+ 11 -214.79 -2.96 216.26
+ 12 -216.26 -1.49 -0.00
+
+ >>> interestpd = np.sum(ipmt)
+ >>> np.round(interestpd, 2)
+ -112.98
+
+ """
+ when = _convert_when(when)
+ rate, per, nper, pv, fv, when = np.broadcast_arrays(rate, per, nper,
+ pv, fv, when)
+
+ total_pmt = pmt(rate, nper, pv, fv, when)
+ ipmt_array = np.array(_rbl(rate, per, total_pmt, pv, when) * rate)
+
+ # Payments start at the first period, so payments before that
+ # don't make any sense.
+ ipmt_array[per < 1] = _value_like(ipmt_array, np.nan)
+ # If payments occur at the beginning of a period and this is the
+ # first period, then no interest has accrued.
+ per1_and_begin = (when == 1) & (per == 1)
+ ipmt_array[per1_and_begin] = _value_like(ipmt_array, 0)
+ # If paying at the beginning we need to discount by one period.
+ per_gt_1_and_begin = (when == 1) & (per > 1)
+ ipmt_array[per_gt_1_and_begin] = (
+ ipmt_array[per_gt_1_and_begin] / (1 + rate[per_gt_1_and_begin])
+ )
+
+ if np.ndim(ipmt_array) == 0:
+ # Follow the ufunc convention of returning scalars for scalar
+ # and 0d array inputs.
+ return ipmt_array.item(0)
+ return ipmt_array
+
+
+def _rbl(rate, per, pmt, pv, when):
+ """Remaining balance on loan.
+
+ This function is here to simply have a different name for the 'fv'
+ function to not interfere with the 'fv' keyword argument within the 'ipmt'
+ function. It is the 'remaining balance on loan' which might be useful as
+ it's own function, but is easily calculated with the 'fv' function.
+ """
+ return fv(rate, (per - 1), pmt, pv, when)
+
+
+def ppmt(rate, per, nper, pv, fv=0, when='end'):
+ """Compute the payment against loan principle.
+
+ Parameters
+ ----------
+ rate : array_like
+ Rate of interest (per period)
+ per : array_like, int
+ Amount paid against the loan changes. The `per` is the period of
+ interest.
+ nper : array_like
+ Number of compounding periods
+ pv : array_like
+ Present value
+ fv : array_like, optional
+ Future value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}
+ When payments are due ('begin' (1) or 'end' (0))
+
+ See Also
+ --------
+ pmt, pv, ipmt
+
+ """
+ total = pmt(rate, nper, pv, fv, when)
+ return total - ipmt(rate, per, nper, pv, fv, when)
+
+
+def pv(rate, nper, pmt, fv=0, when='end'):
+ """Compute the present value.
+
+ Given:
+ * a future value, `fv`
+ * an interest `rate` compounded once per period, of which
+ there are
+ * `nper` total
+ * a (fixed) payment, `pmt`, paid either
+ * at the beginning (`when` = {'begin', 1}) or the end
+ (`when` = {'end', 0}) of each period
+
+ Return:
+ the value now
+
+ Parameters
+ ----------
+ rate : array_like
+ Rate of interest (per period)
+ nper : array_like
+ Number of compounding periods
+ pmt : array_like
+ Payment
+ fv : array_like, optional
+ Future value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
+ When payments are due ('begin' (1) or 'end' (0))
+
+ Returns
+ -------
+ out : ndarray, float
+ Present value of a series of payments or investments.
+
+ Notes
+ -----
+ The present value is computed by solving the equation::
+
+ fv +
+ pv*(1 + rate)**nper +
+ pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) = 0
+
+ or, when ``rate = 0``::
+
+ fv + pv + pmt * nper = 0
+
+ for `pv`, which is then returned.
+
+ References
+ ----------
+ .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May).
+ Open Document Format for Office Applications (OpenDocument)v1.2,
+ Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version,
+ Pre-Draft 12. Organization for the Advancement of Structured Information
+ Standards (OASIS). Billerica, MA, USA. [ODT Document].
+ Available:
+ http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula
+ OpenDocument-formula-20090508.odt
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import numpy_financial as npf
+
+ What is the present value (e.g., the initial investment)
+ of an investment that needs to total $15692.93
+ after 10 years of saving $100 every month? Assume the
+ interest rate is 5% (annually) compounded monthly.
+
+ >>> npf.pv(0.05/12, 10*12, -100, 15692.93)
+ -100.00067131625819
+
+ By convention, the negative sign represents cash flow out
+ (i.e., money not available today). Thus, to end up with
+ $15,692.93 in 10 years saving $100 a month at 5% annual
+ interest, one's initial deposit should also be $100.
+
+ If any input is array_like, ``pv`` returns an array of equal shape.
+ Let's compare different interest rates in the example above:
+
+ >>> a = np.array((0.05, 0.04, 0.03))/12
+ >>> npf.pv(a, 10*12, -100, 15692.93)
+ array([ -100.00067132, -649.26771385, -1273.78633713])
+
+ So, to end up with the same $15692.93 under the same $100 per month
+ "savings plan," for annual interest rates of 4% and 3%, one would
+ need initial investments of $649.27 and $1273.79, respectively.
+
+ """
+ when = _convert_when(when)
+ (rate, nper, pmt, fv, when) = map(np.asarray, [rate, nper, pmt, fv, when])
+ temp = (1 + rate) ** nper
+ fact = np.where(rate == 0, nper, (1 + rate * when) * (temp - 1) / rate)
+ return -(fv + pmt * fact) / temp
+
+
+# Computed with Sage
+# (y + (r + 1)^n*x + p*((r + 1)^n - 1)*(r*w + 1)/r)/(n*(r + 1)^(n - 1)*x -
+# p*((r + 1)^n - 1)*(r*w + 1)/r^2 + n*p*(r + 1)^(n - 1)*(r*w + 1)/r +
+# p*((r + 1)^n - 1)*w/r)
+
+
+def _g_div_gp(r, n, p, x, y, w):
+ # Evaluate g(r_n)/g'(r_n), where g =
+ # fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1)
+ t1 = (r + 1) ** n
+ t2 = (r + 1) ** (n - 1)
+ g = y + t1 * x + p * (t1 - 1) * (r * w + 1) / r
+ gp = (n * t2 * x
+ - p * (t1 - 1) * (r * w + 1) / (r ** 2)
+ + n * p * t2 * (r * w + 1) / r
+ + p * (t1 - 1) * w / r)
+ return g / gp
+
+
+# Use Newton's iteration until the change is less than 1e-6
+# for all values or a maximum of 100 iterations is reached.
+# Newton's rule is
+# r_{n+1} = r_{n} - g(r_n)/g'(r_n)
+# where
+# g(r) is the formula
+# g'(r) is the derivative with respect to r.
+def rate(
+ nper,
+ pmt,
+ pv,
+ fv,
+ when='end',
+ guess=None,
+ tol=None,
+ maxiter=100,
+ *,
+ raise_exceptions=False):
+ """Compute the rate of interest per period.
+
+ Parameters
+ ----------
+ nper : array_like
+ Number of compounding periods
+ pmt : array_like
+ Payment
+ pv : array_like
+ Present value
+ fv : array_like
+ Future value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
+ When payments are due ('begin' (1) or 'end' (0))
+ guess : Number, optional
+ Starting guess for solving the rate of interest, default 0.1
+ tol : Number, optional
+ Required tolerance for the solution, default 1e-6
+ maxiter : int, optional
+ Maximum iterations in finding the solution
+ raise_exceptions: bool, optional
+ Flag to raise an exception when at least one of the rates
+ cannot be computed due to having reached the maximum number of
+ iterations (IterationsExceededException). Set to False as default,
+ thus returning NaNs for those rates.
+
+ Notes
+ -----
+ The rate of interest is computed by iteratively solving the
+ (non-linear) equation::
+
+ fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) = 0
+
+ for ``rate``.
+
+ References
+ ----------
+ Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document
+ Format for Office Applications (OpenDocument)v1.2, Part 2: Recalculated
+ Formula (OpenFormula) Format - Annotated Version, Pre-Draft 12.
+ Organization for the Advancement of Structured Information Standards
+ (OASIS). Billerica, MA, USA. [ODT Document]. Available:
+ http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula
+ OpenDocument-formula-20090508.odt
+
+ """
+ when = _convert_when(when)
+ default_type = Decimal if isinstance(pmt, Decimal) else float
+
+ # Handle casting defaults to Decimal if/when pmt is a Decimal and
+ # guess and/or tol are not given default values
+ if guess is None:
+ guess = default_type('0.1')
+
+ if tol is None:
+ tol = default_type('1e-6')
+
+ (nper, pmt, pv, fv, when) = map(np.asarray, [nper, pmt, pv, fv, when])
+
+ rn = guess
+ iterator = 0
+ close = False
+ while (iterator < maxiter) and not np.all(close):
+ rnp1 = rn - _g_div_gp(rn, nper, pmt, pv, fv, when)
+ diff = abs(rnp1 - rn)
+ close = diff < tol
+ iterator += 1
+ rn = rnp1
+
+ if not np.all(close):
+ if np.isscalar(rn):
+ if raise_exceptions:
+ raise IterationsExceededError('Maximum number of iterations exceeded.')
+ return default_type(np.nan)
+ else:
+ # Return nan's in array of the same shape as rn
+ # where the solution is not close to tol.
+ if raise_exceptions:
+ raise IterationsExceededError(f'Maximum iterations exceeded in '
+ f'{len(close) - close.sum()} rate(s).')
+ rn[~close] = np.nan
+ return rn
+
+
+def irr(values, *, guess=None, tol=1e-12, maxiter=100, raise_exceptions=False):
+ r"""Return the Internal Rate of Return (IRR).
+
+ This is the "average" periodically compounded rate of return
+ that gives a net present value of 0.0; for a more complete explanation,
+ see Notes below.
+
+ :class:`decimal.Decimal` type is not supported.
+
+ Parameters
+ ----------
+ values : array_like, shape(N,)
+ Input cash flows per time period. By convention, net "deposits"
+ are negative and net "withdrawals" are positive. Thus, for
+ example, at least the first element of `values`, which represents
+ the initial investment, will typically be negative.
+ guess : float, optional
+ Initial guess of the IRR for the iterative solver. If no guess is
+ given an heuristic is used to estimate the guess through the ratio of
+ positive to negative cash lows
+ tol : float, optional
+ Required tolerance to accept solution. Default is 1e-12.
+ maxiter : int, optional
+ Maximum iterations to perform in finding a solution. Default is 100.
+ raise_exceptions: bool, optional
+ Flag to raise an exception when the irr cannot be computed due to
+ either having all cashflows of the same sign (NoRealSolutionException) or
+ having reached the maximum number of iterations (IterationsExceededException).
+ Set to False as default, thus returning NaNs in the two previous
+ cases.
+
+ Returns
+ -------
+ out : float
+ Internal Rate of Return for periodic input values.
+
+ Notes
+ -----
+ The IRR is perhaps best understood through an example (illustrated
+ using np.irr in the Examples section below). Suppose one invests 100
+ units and then makes the following withdrawals at regular (fixed)
+ intervals: 39, 59, 55, 20. Assuming the ending value is 0, one's 100
+ unit investment yields 173 units; however, due to the combination of
+ compounding and the periodic withdrawals, the "average" rate of return
+ is neither simply 0.73/4 nor (1.73)^0.25-1. Rather, it is the solution
+ (for :math:`r`) of the equation:
+
+ .. math:: -100 + \\frac{39}{1+r} + \\frac{59}{(1+r)^2}
+ + \\frac{55}{(1+r)^3} + \\frac{20}{(1+r)^4} = 0
+
+ In general, for `values` :math:`= [v_0, v_1, ... v_M]`,
+ irr is the solution of the equation: [G]_
+
+ .. math:: \\sum_{t=0}^M{\\frac{v_t}{(1+irr)^{t}}} = 0
+
+ References
+ ----------
+ .. [G] L. J. Gitman, "Principles of Managerial Finance, Brief," 3rd ed.,
+ Addison-Wesley, 2003, pg. 348.
+
+ Examples
+ --------
+ >>> import numpy_financial as npf
+
+ >>> round(npf.irr([-100, 39, 59, 55, 20]), 5)
+ 0.28095
+ >>> round(npf.irr([-100, 0, 0, 74]), 5)
+ -0.0955
+ >>> round(npf.irr([-100, 100, 0, -7]), 5)
+ -0.0833
+ >>> round(npf.irr([-100, 100, 0, 7]), 5)
+ 0.06206
+ >>> round(npf.irr([-5, 10.5, 1, -8, 1]), 5)
+ 0.0886
+
+ """
+ values = np.atleast_1d(values)
+ if values.ndim != 1:
+ raise ValueError("Cashflows must be a rank-1 array")
+
+ # If all values are of the same sign no solution exists
+ # we don't perform any further calculations and exit early
+ same_sign = np.all(values > 0) if values[0] > 0 else np.all(values < 0)
+ if same_sign:
+ if raise_exceptions:
+ raise NoRealSolutionError('No real solution exists for IRR since all '
+ 'cashflows are of the same sign.')
+ return np.nan
+
+ # If no value is passed for `guess`, then make a heuristic estimate
+ if guess is None:
+ positive_cashflow = values > 0
+ inflow = values.sum(where=positive_cashflow)
+ outflow = -values.sum(where=~positive_cashflow)
+ guess = inflow / outflow - 1
+
+ # We aim to solve eirr such that NPV is exactly zero. This can be framed as
+ # simply finding the closest root of a polynomial to a given initial guess
+ # as follows:
+ # V0 V1 V2 V3
+ # NPV = ---------- + ---------- + ---------- + ---------- + ... = 0
+ # (1+eirr)^0 (1+eirr)^1 (1+eirr)^2 (1+eirr)^3
+ #
+ # by letting g = (1+eirr), we substitute to get
+ #
+ # NPV = V0 * 1/g^0 + V1 * 1/g^1 + V2 * 1/x^2 + V3 * 1/g^3 + ... = 0
+ #
+ # Multiplying by g^N this becomes
+ #
+ # V0 * g^N + V1 * g^{N-1} + V2 * g^{N-2} + V3 * g^{N-3} + ... = 0
+ #
+ # which we solve using Newton-Raphson and then reverse out the solution
+ # as eirr = g - 1 (if we are close enough to a solution)
+ npv_ = np.polynomial.Polynomial(values[::-1])
+ d_npv = npv_.deriv()
+ g = 1 + guess
+
+ for _ in range(maxiter):
+ delta = npv_(g) / d_npv(g)
+ if abs(delta) < tol:
+ return g - 1
+ g -= delta
+
+ if raise_exceptions:
+ raise IterationsExceededError('Maximum number of iterations exceeded.')
+
+ return np.nan
+
+
+@nb.njit
+def _npv_native(rates, values, out):
+ for i in range(rates.shape[0]):
+ for j in range(values.shape[0]):
+ acc = 0.0
+ for t in range(values.shape[1]):
+ if rates[i] == -1.0:
+ acc = np.nan
+ break
+ else:
+ acc += values[j, t] / ((1.0 + rates[i]) ** t)
+ out[i, j] = acc
+
+
+def npv(rate, values):
+ r"""Return the NPV (Net Present Value) of a cash flow series.
+
+ Parameters
+ ----------
+ rate : scalar or array_like shape(K, )
+ The discount rate.
+ values : array_like, shape(M, ) or shape(M, N)
+ The values of the time series of cash flows. The (fixed) time
+ interval between cash flow "events" must be the same as that for
+ which `rate` is given (i.e., if `rate` is per year, then precisely
+ a year is understood to elapse between each cash flow event). By
+ convention, investments or "deposits" are negative, income or
+ "withdrawals" are positive; `values` must begin with the initial
+ investment, thus `values[0]` will typically be negative.
+
+ Returns
+ -------
+ out : float or array shape(K, M)
+ The NPV of the input cash flow series `values` at the discount
+ `rate`. `out` follows the ufunc convention of returning scalars
+ instead of single element arrays.
+
+ Warnings
+ --------
+ ``npv`` considers a series of cashflows starting in the present (t = 0).
+ NPV can also be defined with a series of future cashflows, paid at the
+ end, rather than the start, of each period. If future cashflows are used,
+ the first cashflow `values[0]` must be zeroed and added to the net
+ present value of the future cashflows. This is demonstrated in the
+ examples.
+
+ Notes
+ -----
+ Returns the result of: [G]_
+
+ .. math :: \\sum_{t=0}^{M-1}{\\frac{values_t}{(1+rate)^{t}}}
+
+ References
+ ----------
+ .. [G] L. J. Gitman, "Principles of Managerial Finance, Brief," 3rd ed.,
+ Addison-Wesley, 2003, pg. 346.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import numpy_financial as npf
+
+ Consider a potential project with an initial investment of $40 000 and
+ projected cashflows of $5 000, $8 000, $12 000 and $30 000 at the end of
+ each period discounted at a rate of 8% per period. To find the project's
+ net present value:
+
+ >>> rate, cashflows = 0.08, [-40_000, 5_000, 8_000, 12_000, 30_000]
+ >>> np.round(npf.npv(rate, cashflows), 5)
+ 3065.22267
+
+ It may be preferable to split the projected cashflow into an initial
+ investment and expected future cashflows. In this case, the value of
+ the initial cashflow is zero and the initial investment is later added
+ to the future cashflows net present value:
+
+ >>> initial_cashflow = cashflows[0]
+ >>> cashflows[0] = 0
+ >>> np.round(npf.npv(rate, cashflows) + initial_cashflow, 5)
+ 3065.22267
+
+ The NPV calculation may be applied to several ``rates`` and ``cashflows``
+ simulatneously. This produces an array of shape ``(len(rates), len(cashflows))``.
+ >>> rates = [0.00, 0.05, 0.10]
+ >>> cashflows = [[-4_000, 500, 800], [-5_000, 600, 900]]
+ >>> npf.npv(rates, cashflows).round(2)
+ array([[-2700. , -3500. ],
+ [-2798.19, -3612.24],
+ [-2884.3 , -3710.74]])
+
+ """
+ values_inner = np.atleast_2d(values)
+ rate_inner = np.atleast_1d(rate)
+
+ if rate_inner.ndim != 1:
+ msg = "invalid shape for rates. Rate must be either a scalar or 1d array"
+ raise ValueError(msg)
+
+ if values_inner.ndim != 2:
+ msg = "invalid shape for values. Values must be either a 1d or 2d array"
+ raise ValueError(msg)
+
+ output_shape = _get_output_array_shape(rate_inner, values_inner)
+ out = np.empty(output_shape)
+ _npv_native(rate_inner, values_inner, out)
+ return _ufunc_like(out)
+
+
+def mirr(values, finance_rate, reinvest_rate, *, raise_exceptions=False):
+ r"""
+ Return the Modified Internal Rate of Return (MIRR).
+
+ MIRR is a financial metric that takes into account both the cost of
+ the investment and the return on reinvested cash flows. It is useful
+ for evaluating the profitability of an investment with multiple cash
+ inflows and outflows.
+
+ Parameters
+ ----------
+ values : array_like
+ Cash flows, where the first value is considered a sunk cost at time zero.
+ It must contain at least one positive and one negative value.
+ finance_rate : scalar
+ Interest rate paid on the cash flows.
+ reinvest_rate : scalar
+ Interest rate received on the cash flows upon reinvestment.
+ raise_exceptions: bool, optional
+ Flag to raise an exception when the MIRR cannot be computed due to
+ having all cash flows of the same sign (NoRealSolutionException).
+ Set to False as default,thus returning NaNs in the previous case.
+
+ Returns
+ -------
+ out : float
+ Modified internal rate of return
+
+ Notes
+ -----
+ The MIRR formula is as follows:
+
+ .. math::
+
+ MIRR =
+ \\left( \\frac{{FV_{positive}}}{{PV_{negative}}} \\right)^{\\frac{{1}}{{n-1}}}
+ * (1+r) - 1
+
+ where:
+ - \(FV_{positive}\) is the future value of positive cash flows,
+ - \(PV_{negative}\) is the present value of negative cash flows,
+ - \(n\) is the number of periods.
+ - \(r\) is the reinvestment rate.
+
+ Examples
+ --------
+ >>> import numpy_financial as npf
+
+ Consider a project with an initial investment of -$100
+ and projected cash flows of $50, -$60, and $70 at the end of each period.
+ The project has a finance rate of 10% and a reinvestment rate of 12%.
+
+ >>> npf.mirr([-100, 50, -60, 70], 0.10, 0.12)
+ -0.03909366594356467
+
+ Now, let's consider the scenario where all cash flows are negative.
+
+ >>> npf.mirr([-100, -50, -60, -70], 0.10, 0.12)
+ nan
+
+ Finally, let's explore the situation where all cash flows are positive,
+ and the `raise_exceptions` parameter is set to True.
+
+ >>> npf.mirr([
+ ... 100, 50, 60, 70],
+ ... 0.10, 0.12,
+ ... raise_exceptions=True
+ ... ) #doctest: +NORMALIZE_WHITESPACE
+ Traceback (most recent call last):
+ ...
+ numpy_financial._financial.NoRealSolutionError:
+ No real solution exists for MIRR since all cashflows are of the same sign.
+ """
+ values = np.asarray(values)
+ n = values.size
+
+ # Without this explicit cast the 1/(n - 1) computation below
+ # becomes a float, which causes TypeError when using Decimal
+ # values.
+ if isinstance(finance_rate, Decimal):
+ n = Decimal(n)
+
+ pos = values > 0
+ neg = values < 0
+ if not (pos.any() and neg.any()):
+ if raise_exceptions:
+ raise NoRealSolutionError('No real solution exists for MIRR since'
+ ' all cashflows are of the same sign.')
+ return np.nan
+ numer = np.abs(npv(reinvest_rate, values * pos))
+ denom = np.abs(npv(finance_rate, values * neg))
+ return (numer / denom) ** (1 / (n - 1)) * (1 + reinvest_rate) - 1
diff --git a/tasks/tasksmith-a7e859277e7a/solution/solve.sh b/tasks/tasksmith-a7e859277e7a/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2a03b1dcfb1e7734b54badf26e71a070bb354e98
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/sh
+set -eu
+mkdir -p -- /workspace/benchmarks
+cp /solution/reference/benchmarks/benchmarks.py /workspace/benchmarks/benchmarks.py
+mkdir -p -- /workspace/numpy_financial
+cp /solution/reference/numpy_financial/_financial.py /workspace/numpy_financial/_financial.py
diff --git a/tasks/tasksmith-a7e859277e7a/task.toml b/tasks/tasksmith-a7e859277e7a/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..40f940287f0c906a9b273b9c738e4a1da50266ea
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/task.toml
@@ -0,0 +1,226 @@
+schema_version = "1.3"
+
+[task]
+name = "repo2rlenv/tasksmith-a7e859277e7a"
+
+[metadata.repo2env]
+recipe = "tasksmith"
+recipe_version = "1"
+source_url = "https://github.com/numpy/numpy-financial/pull/108"
+source_head = "6b54195dadf216a7cb0e90238bdc4be042b06b1c"
+source_base = "68960080799bad56c7c563497048051f97717f30"
+workspace_strategy = "head_minus_source_patch"
+source_diff_sha256 = "484414d0104267015b5bc89907d8cfe83ef316867ed2f0ac5958bf730a7fcdad"
+acceptance_profile = "practical-generation-v1"
+upstream_test_policy = "retain"
+reward_kinds = [
+ "test_execution",
+]
+quality_status = "exported"
+fail_to_pass_count = 9
+pass_to_pass_count = 3
+tracked_files = [
+ "environment/Dockerfile",
+ "environment/source/.github/CODE_OF_CONDUCT.md",
+ "environment/source/.github/ISSUE_TEMPLATE/bug-report.yml",
+ "environment/source/.github/ISSUE_TEMPLATE/config.yml",
+ "environment/source/.github/ISSUE_TEMPLATE/documentation.yml",
+ "environment/source/.github/ISSUE_TEMPLATE/feature-request.yml",
+ "environment/source/.github/workflows/lint.yml",
+ "environment/source/.github/workflows/publish_docs_to_pages.yml",
+ "environment/source/.github/workflows/pythonpackage.yml",
+ "environment/source/Dockerfile",
+ "environment/source/LICENSE.txt",
+ "environment/source/README.md",
+ "environment/source/benchmarks/__init__.py",
+ "environment/source/benchmarks/benchmarks.py",
+ "environment/source/doc/Makefile",
+ "environment/source/doc/make.bat",
+ "environment/source/doc/source/_static/numpy_financial_favicon.png",
+ "environment/source/doc/source/_static/numpy_financial_logov.svg",
+ "environment/source/doc/source/conf.py",
+ "environment/source/doc/source/dev/building_with_poetry.md",
+ "environment/source/doc/source/dev/getting_the_code.md",
+ "environment/source/doc/source/dev/running_the_benchmarks.md",
+ "environment/source/doc/source/fv.rst",
+ "environment/source/doc/source/generate_rst_function_files.py",
+ "environment/source/doc/source/index.rst",
+ "environment/source/doc/source/ipmt.rst",
+ "environment/source/doc/source/irr.rst",
+ "environment/source/doc/source/mirr.rst",
+ "environment/source/doc/source/nper.rst",
+ "environment/source/doc/source/npv.rst",
+ "environment/source/doc/source/pmt.rst",
+ "environment/source/doc/source/ppmt.rst",
+ "environment/source/doc/source/pv.rst",
+ "environment/source/doc/source/rate.rst",
+ "environment/source/doc/source/release-notes.rst",
+ "environment/source/docweb/README.txt",
+ "environment/source/docweb/css/home.css",
+ "environment/source/docweb/images/numpy_financial_favicon.png",
+ "environment/source/docweb/images/numpy_financial_logoh.svg",
+ "environment/source/docweb/index.html",
+ "environment/source/numpy_financial/__init__.py",
+ "environment/source/numpy_financial/_financial.py",
+ "environment/source/pyproject.toml",
+ "solution/reference/benchmarks/benchmarks.py",
+ "solution/reference/numpy_financial/_financial.py",
+ "solution/solve.sh",
+ "tests/Dockerfile",
+ "tests/contract.json",
+ "tests/grade.py",
+ "tests/source/.github/CODE_OF_CONDUCT.md",
+ "tests/source/.github/ISSUE_TEMPLATE/bug-report.yml",
+ "tests/source/.github/ISSUE_TEMPLATE/config.yml",
+ "tests/source/.github/ISSUE_TEMPLATE/documentation.yml",
+ "tests/source/.github/ISSUE_TEMPLATE/feature-request.yml",
+ "tests/source/.github/workflows/lint.yml",
+ "tests/source/.github/workflows/publish_docs_to_pages.yml",
+ "tests/source/.github/workflows/pythonpackage.yml",
+ "tests/source/.gitignore",
+ "tests/source/Dockerfile",
+ "tests/source/LICENSE.txt",
+ "tests/source/README.md",
+ "tests/source/asv.conf.json",
+ "tests/source/benchmarks/__init__.py",
+ "tests/source/benchmarks/benchmarks.py",
+ "tests/source/doc/Makefile",
+ "tests/source/doc/make.bat",
+ "tests/source/doc/source/_static/numpy_financial_favicon.png",
+ "tests/source/doc/source/_static/numpy_financial_logov.svg",
+ "tests/source/doc/source/conf.py",
+ "tests/source/doc/source/dev/building_with_poetry.md",
+ "tests/source/doc/source/dev/getting_the_code.md",
+ "tests/source/doc/source/dev/running_the_benchmarks.md",
+ "tests/source/doc/source/fv.rst",
+ "tests/source/doc/source/generate_rst_function_files.py",
+ "tests/source/doc/source/index.rst",
+ "tests/source/doc/source/ipmt.rst",
+ "tests/source/doc/source/irr.rst",
+ "tests/source/doc/source/mirr.rst",
+ "tests/source/doc/source/nper.rst",
+ "tests/source/doc/source/npv.rst",
+ "tests/source/doc/source/pmt.rst",
+ "tests/source/doc/source/ppmt.rst",
+ "tests/source/doc/source/pv.rst",
+ "tests/source/doc/source/rate.rst",
+ "tests/source/doc/source/release-notes.rst",
+ "tests/source/docweb/README.txt",
+ "tests/source/docweb/css/home.css",
+ "tests/source/docweb/images/numpy_financial_favicon.png",
+ "tests/source/docweb/images/numpy_financial_logoh.svg",
+ "tests/source/docweb/index.html",
+ "tests/source/numpy_financial/__init__.py",
+ "tests/source/numpy_financial/_financial.py",
+ "tests/source/pyproject.toml",
+ "tests/source/tests/__init__.py",
+ "tests/source/tests/tasksmith_behavior.py",
+ "tests/source/tests/test_financial.py",
+ "tests/test.sh",
+ "tests/test_driver.py",
+ "tests/test_results.py",
+]
+executable_files = [
+ "solution/solve.sh",
+ "tests/test.sh",
+]
+bundle_hash = "sha256:5555bab1d34b5856c8d7248c1f7705f8b87d03c21f5ddd9aaa522e4b3cc98fe7"
+
+[metadata.repo2env.evaluation]
+schema_version = "1"
+status = "verified"
+stage = "complete"
+reason_codes = [
+ "quality_verified",
+]
+detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile."
+checked_at = "2026-11-20T08:51:20.293964Z"
+provenance = "unknown"
+subject_bundle_hash = "sha256:5555bab1d34b5856c8d7248c1f7705f8b87d03c21f5ddd9aaa522e4b3cc98fe7"
+profile = "evidence-review-v2"
+source_task_path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/abec33f28a9f/candidates/a7e859277e7a/quality/revisions/r0/tasksmith-a7e859277e7a"
+source_task_toml_sha256 = "e7d7e762aae6e7f50bf52ad35a3415d97b7b90173749755e7b9f013038b8918f"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "quality_result"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/abec33f28a9f/candidates/a7e859277e7a/quality/result.json"
+sha256 = "9c9daf5f84e1215481be46b3d906594d52a87c7c955091f8e1a1471189957fbf"
+subject_bundle_hash = "sha256:5555bab1d34b5856c8d7248c1f7705f8b87d03c21f5ddd9aaa522e4b3cc98fe7"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "baseline"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/abec33f28a9f/candidates/a7e859277e7a/quality/trials/r0-baseline/tsbatch-195cc094e760-abec33f28a9f-q-a7e85927-r0-baseline/tasksmith-a7e859277e7a__PhjDxM2/result.json"
+sha256 = "316ab4334889c85afcf1ce2cc2438d1aa78e5d30427286206369bfbd001ee0f4"
+subject_bundle_hash = "sha256:5555bab1d34b5856c8d7248c1f7705f8b87d03c21f5ddd9aaa522e4b3cc98fe7"
+harbor_task_checksum = "23d7489f6910f577e46d7b27371c8fed06f8138172cc75315b03e6f2a086ed21"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "oracle"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/abec33f28a9f/candidates/a7e859277e7a/quality/trials/r0-oracle/tsbatch-195cc094e760-abec33f28a9f-q-a7e85927-r0-oracle/tasksmith-a7e859277e7a__b3oEZJF/result.json"
+sha256 = "28b08ef41fe31d18c572fc389d4cfd62c5697e3c4d9ab7acb8df461193a02380"
+subject_bundle_hash = "sha256:5555bab1d34b5856c8d7248c1f7705f8b87d03c21f5ddd9aaa522e4b3cc98fe7"
+harbor_task_checksum = "23d7489f6910f577e46d7b27371c8fed06f8138172cc75315b03e6f2a086ed21"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "probe"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/abec33f28a9f/candidates/a7e859277e7a/quality/trials/r0-probe0/tsbatch-195cc094e760-abec33f28a9f-q-a7e85927-r0-probe0/tasksmith-a7e859277e7a__XA3QBFN/result.json"
+sha256 = "465fe1b6f8885bb3ec3f569b793c6f807cfd9c57049bb2c064b0c3ae5346d6cf"
+subject_bundle_hash = "sha256:17e651606673a8cbcd967907d56b5ecf6b13343c1cbe64ec93f361a3e87568fa"
+harbor_task_checksum = "f36345ed8cf96a20703e4e72fe4f49b948dbae0d8d9d83ee5e3bcc6393a6789d"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "probe"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/abec33f28a9f/candidates/a7e859277e7a/quality/trials/r0-probe1/tsbatch-195cc094e760-abec33f28a9f-q-a7e85927-r0-probe1/tasksmith-a7e859277e7a__DyGRRoP/result.json"
+sha256 = "a668473c46dcbf0412e4a274ca80301f995c4c0d37b5e5ea2b0a891c8194ecef"
+subject_bundle_hash = "sha256:02e509deecac50d60168c13cb2195a966ed5bda9303aeb8d3a0dc94300964571"
+harbor_task_checksum = "baacfaffd5bab7a849cb8f2c5fdb3ded6f8bf708058171b3568d1e094924634e"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "rollout"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/abec33f28a9f/candidates/a7e859277e7a/quality/trials/r0-rollout/tsbatch-195cc094e760-abec33f28a9f-q-a7e85927-r0-rollout/tasksmith-a7e859277e7a__RyeHJuX/result.json"
+sha256 = "0439947b3add72f8781322759173cee583335a01d336c78d683f2df3631ed05f"
+subject_bundle_hash = "sha256:5555bab1d34b5856c8d7248c1f7705f8b87d03c21f5ddd9aaa522e4b3cc98fe7"
+harbor_task_checksum = "23d7489f6910f577e46d7b27371c8fed06f8138172cc75315b03e6f2a086ed21"
+
+[metadata.repo2env.quality_requirements]
+probe_focus = [
+ "general",
+]
+
+[environment]
+cpus = 1
+memory_mb = 2048
+build_timeout_sec = 600
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 600
+user = "learner"
+network_mode = "no-network"
+
+[verifier]
+timeout_sec = 210
+user = "root"
+network_mode = "no-network"
+environment_mode = "separate"
+
+[verifier.environment]
+network_mode = "no-network"
+cpus = 2
+memory_mb = 2048
+
+[[artifacts]]
+source = "/workspace/numpy_financial"
+exclude = [
+ "__pycache__",
+ "*.pyc",
+ ".pytest_cache",
+]
+
+[[artifacts]]
+source = "/workspace/benchmarks/benchmarks.py"
+exclude = [
+ "__pycache__",
+ "*.pyc",
+ ".pytest_cache",
+]
diff --git a/tasks/tasksmith-a7e859277e7a/tests/Dockerfile b/tasks/tasksmith-a7e859277e7a/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..9ca8b252a009717099a16d26197878703c31af2d
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/Dockerfile
@@ -0,0 +1,10 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir poetry-core==1.9.1 numba==0.68.1 llvmlite==0.50.0 numpy==2.5.5 pytest==8.3.5 'hypothesis[numpy]==6.99.11' 'pytest-xdist[psutil]==3.5.0'
+COPY source /workspace
+RUN python -m pip install --no-cache-dir -e .
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
+RUN useradd -m -u 1001 grader
+COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/
+RUN chmod 755 /tests && chmod 644 /tests/*
diff --git a/tasks/tasksmith-a7e859277e7a/tests/contract.json b/tasks/tasksmith-a7e859277e7a/tests/contract.json
new file mode 100644
index 0000000000000000000000000000000000000000..12a3e1ff4235538bd533a05cb1590bed69f08847
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/contract.json
@@ -0,0 +1 @@
+{"expected_passes": ["tests.tasksmith_behavior::test_npv_broadcasting_shape_and_values", "tests.tasksmith_behavior::test_npv_multiple_rates_single_cashflow_returns_1d", "tests.test_financial.TestNpv::test_fuzz", "tests.test_financial.TestNpv::test_invalid_cashflows_shape[cf0]", "tests.test_financial.TestNpv::test_invalid_cashflows_shape[cf1]", "tests.test_financial.TestNpv::test_invalid_rates_shape[rates0]", "tests.test_financial.TestNpv::test_invalid_rates_shape[rates1]", "tests.test_financial.TestNpv::test_rate_of_negative_one_returns_nan[-1.0]", "tests.test_financial.TestNpv::test_rate_of_negative_one_returns_nan[-1]", "tests.tasksmith_behavior::test_npv_scalar_rate_1d_cashflow_returns_scalar", "tests.tasksmith_behavior::test_npv_single_rate_multiple_cashflows_returns_1d", "tests.test_financial.TestNpv::test_npv"], "immutable_assets": {}, "optional_files": [], "pytest_args": [], "submitted_files": ["benchmarks/benchmarks.py", "numpy_financial/__init__.py", "numpy_financial/_financial.py"], "submitted_roots": ["numpy_financial"], "test_paths": ["tests/test_financial.py::TestNpv", "tests/tasksmith_behavior.py"], "timeout_sec": 180}
\ No newline at end of file
diff --git a/tasks/tasksmith-a7e859277e7a/tests/grade.py b/tasks/tasksmith-a7e859277e7a/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..a803a55bfcc142c8279645ea59cea90b2a90918a
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/grade.py
@@ -0,0 +1,196 @@
+"""Standalone trusted entry point; copied into each separate verifier image.
+
+No Repo2RLEnv installation is needed to grade an exported task. Submitted Python
+runs as an unprivileged user; this parent owns the result parser and reward file.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import os
+import signal
+import stat
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+
+def child_environment(temporary: str) -> dict[str, str]:
+ """Preserve prepared runtime assets without inheriting controller credentials."""
+ return {
+ **{
+ key: os.environ[key]
+ for key in (
+ "LD_LIBRARY_PATH",
+ "CUDA_VISIBLE_DEVICES",
+ "NVIDIA_VISIBLE_DEVICES",
+ "NVIDIA_DRIVER_CAPABILITIES",
+ "NCCL_SOCKET_IFNAME",
+ "GLOO_SOCKET_IFNAME",
+ "HF_HOME",
+ "HF_HUB_CACHE",
+ "HF_HUB_OFFLINE",
+ "TRANSFORMERS_OFFLINE",
+ "HF_DATASETS_OFFLINE",
+ )
+ if key in os.environ
+ },
+ "PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin",
+ "HOME": temporary,
+ "PYTHONDONTWRITEBYTECODE": "1",
+ "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
+ }
+
+
+def validate_submission(workspace: Path, contract: dict) -> None:
+ """Validate private staging and remove inert backups before importing Python."""
+ submitted = set(contract["submitted_files"])
+ backups: set[str] = set()
+ optional = submitted & set(contract.get("optional_files", []))
+ paths = submitted - optional
+ for relative in optional:
+ path = workspace / relative
+ if any(component.is_symlink() for component in (path, *path.parents)):
+ raise ValueError("Submitted source contains a symlink")
+ # Added standalone modules may be absent in the baseline. If supplied,
+ # apply the same regular-file and size checks as every required module.
+ if path.exists():
+ paths.add(relative)
+ roots = contract.get("submitted_roots", [])
+ immutable = contract.get("immutable_assets", {})
+ paths.update(immutable)
+ for relative in roots:
+ root = workspace / relative
+ if root.is_symlink() or not root.is_dir():
+ raise ValueError("Submitted source root is missing or linked")
+ for path in root.rglob("*"):
+ if path.is_symlink():
+ raise ValueError("Submitted source contains a symlink")
+ if path.is_dir():
+ continue
+ name = path.relative_to(workspace).as_posix()
+ if path.suffix != ".py" and name not in immutable:
+ if name not in submitted and path.name.endswith((".py.bak", ".py~")):
+ backups.add(name)
+ else:
+ raise ValueError("Only Python source files may be added")
+ paths.add(name)
+ for relative in sorted(paths):
+ path = workspace / relative
+ for component in (path, *path.parents):
+ if component.is_symlink():
+ raise ValueError("Submitted source contains a symlink")
+ if (
+ not path.is_file()
+ or not stat.S_ISREG(path.stat().st_mode)
+ or path.stat().st_size > 8 * 1024 * 1024
+ ):
+ raise ValueError("Submitted source is not a bounded regular file")
+ if (
+ relative in immutable
+ and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative]
+ ):
+ raise ValueError("Non-Python source assets must remain unchanged")
+ if relative not in backups:
+ # os.chown doesn't exist on Windows. This module only ever runs for
+ # real inside the Linux verifier container (every other path here
+ # is an absolute container path); the guard exists so the tests
+ # that call validate_submission() directly can run on a Windows
+ # host without touching real container-only ownership semantics.
+ if sys.platform != "win32":
+ os.chown(path, 0, 0)
+ path.chmod(0o644)
+ # Only the verifier's collected copy is cleaned. The learner workspace and
+ # archived submission retain their bytes. Validate every path first so a
+ # backup cannot bypass linked, oversized, required, or immutable file checks.
+ for relative in sorted(backups):
+ (workspace / relative).unlink()
+
+
+def main() -> None:
+ directory = Path("/tests")
+ parser_spec = importlib.util.spec_from_file_location(
+ "test_results", directory / "test_results.py"
+ )
+ parser = importlib.util.module_from_spec(parser_spec)
+ sys.modules[parser_spec.name] = parser
+ parser_spec.loader.exec_module(parser)
+ contract = json.loads((directory / "contract.json").read_text())
+ logs = Path("/logs/verifier")
+ logs.mkdir(parents=True, exist_ok=True)
+ logs.chmod(0o755)
+ reward = logs / "reward.txt"
+ reward.write_text("0\n")
+ reward.chmod(0o644)
+ try:
+ validate_submission(Path("/workspace"), contract)
+ except (ValueError, OSError) as exc:
+ (logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)}))
+ return
+ with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary:
+ working = Path(temporary)
+ if sys.platform != "win32": # os.chown doesn't exist on Windows; see above
+ os.chown(working, 1001, 1001)
+ working.chmod(0o700)
+ report = working / "results.xml"
+ command = [
+ sys.executable,
+ "-I",
+ "/tests/test_driver.py",
+ *contract["test_paths"],
+ *contract.get("pytest_args", []),
+ "-q",
+ "--tb=short",
+ "-p",
+ "no:cacheprovider",
+ f"--junitxml={report}",
+ ]
+ with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr:
+ process = subprocess.Popen(
+ command,
+ cwd="/workspace",
+ stdout=stdout,
+ stderr=stderr,
+ user=1001,
+ group=1001,
+ extra_groups=[],
+ start_new_session=True,
+ env=child_environment(temporary),
+ )
+ try:
+ code = process.wait(timeout=contract["timeout_sec"])
+ finally:
+ # Terminate descendants too: they must not keep modifying the
+ # child-owned report while the trusted parent checks it.
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024:
+ (logs / "result.json").write_text(
+ json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"})
+ )
+ return
+ text = report.read_text()
+ (logs / "results.xml").write_text(text)
+ try:
+ parsed = parser.parse_junit(text, returncode=code)
+ except ValueError as exc:
+ (logs / "result.json").write_text(
+ json.dumps({"passed": False, "returncode": code, "reason": str(exc)})
+ )
+ return
+ expected = set(contract["expected_passes"])
+ passed = code == 0 and bool(expected) and parsed.passed == expected
+ (logs / "result.json").write_text(
+ json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses})
+ )
+ reward.write_text("1\n" if passed else "0\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/.github/CODE_OF_CONDUCT.md b/tasks/tasksmith-a7e859277e7a/tests/source/.github/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000000000000000000000000000000000..73c5e17e1838b8c4a2b8ee34548b3f793d7e603e
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/.github/CODE_OF_CONDUCT.md
@@ -0,0 +1,9 @@
+All NumPy-Financial participants are expected to honor the NumPy Code of Conduct.
+
+This code of conduct applies to all spaces managed by the NumPy project, including all public and private mailing lists, issue trackers, wikis, blogs, Twitter, and any other communication channel used by our community. The NumPy project does not organise in-person events, however events related to our community should have a code of conduct similar in spirit to this one.
+
+This code of conduct should be honored by everyone who participates in the NumPy community formally or informally, or claims any affiliation with the project, in any project-related activities and especially when representing the project, in any role.
+
+This code is not exhaustive or complete. It serves to distill our common understanding of a collaborative, shared environment and goals. Please try to follow this code in spirit as much as in letter, to create a friendly and productive environment that enriches the surrounding community.
+
+To view the full Code of Conduct, please see: https://numpy.org/code-of-conduct/
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml b/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml
new file mode 100644
index 0000000000000000000000000000000000000000..84472be69ae18a2ae6a80a74171fd4596f0657dd
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml
@@ -0,0 +1,63 @@
+name: Bug report
+description: Report a bug. For security vulnerabilities see Report a security vulnerability in the templates.
+title: "BUG: "
+labels: [00 - Bug]
+
+body:
+- type: markdown
+ attributes:
+ value: >
+ Thank you for taking the time to file a bug report. Before creating a new
+ issue, please make sure to take a few minutes to check the issue tracker
+ for existing issues about the bug.
+
+- type: textarea
+ attributes:
+ label: "Describe the issue:"
+ validations:
+ required: true
+
+- type: textarea
+ attributes:
+ label: "Reproduce the code example:"
+ description: >
+ A short code example that reproduces the problem/missing feature. It
+ should be self-contained, i.e., can be copy-pasted into the Python
+ interpreter or run as-is via `python myproblem.py`.
+ placeholder: |
+ import numpy_financial as npf
+ << your code here >>
+ render: python
+ validations:
+ required: true
+
+- type: textarea
+ attributes:
+ label: "Error message:"
+ description: >
+ Please include full error message, if any.
+ If you are reporting a segfault please include a GDB traceback,
+ which you can generate by following
+ [these instructions](https://github.com/numpy/numpy/blob/main/doc/source/dev/development_environment.rst#debugging).
+ placeholder: |
+ << Full traceback starting from `Traceback: ...` >>
+ render: shell
+
+- type: textarea
+ attributes:
+ label: "Runtime information:"
+ description: >
+ Output from `import sys, numpy; print(numpy.__version__); print(sys.version)`
+ If you are running NumPy 1.24+, also show `print(numpy.show_runtime())`
+ validations:
+ required: true
+
+- type: textarea
+ attributes:
+ label: "Context for the issue:"
+ description: |
+ Please explain how this issue affects your work or why it should be prioritized.
+ placeholder: |
+ << your explanation here >>
+ validations:
+ required: false
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/config.yml b/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/config.yml
new file mode 100644
index 0000000000000000000000000000000000000000..adfff81bd004d4abf1341a3a90a1e9ed0920c7cb
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/config.yml
@@ -0,0 +1,7 @@
+contact_links:
+ - name: Question/Help/Support
+ url: https://numpy.org/gethelp/
+ about: "If you have a question, please look at the listed resources available on the website."
+ - name: Development-related matters
+ url: https://numpy.org/community/
+ about: "If you would like to discuss development-related matters or need help from the NumPy team, see our community's communication channels."
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/documentation.yml b/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/documentation.yml
new file mode 100644
index 0000000000000000000000000000000000000000..c5a8b8b56fcf55aa5d91d89d39e192f26729132b
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/documentation.yml
@@ -0,0 +1,23 @@
+name: Documentation
+description: Report an issue related to the NumPy-Financial documentation.
+title: "DOC: "
+labels: [04 - Documentation]
+
+body:
+- type: textarea
+ attributes:
+ label: "Issue with current documentation:"
+ description: >
+ Please make sure to leave a reference to the document/code you're
+ referring to. You can also check the development version of the
+ documentation and see if this issue has already been addressed at
+ https://numpy.org/devdocs.
+
+- type: textarea
+ attributes:
+ label: "Idea or request for content:"
+ description: >
+ Please describe as clearly as possible what topics you think are missing
+ from the current documentation. Make sure to check
+ https://github.com/numpy/numpy-tutorials and see if this issue might be
+ more appropriate there.
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml b/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml
new file mode 100644
index 0000000000000000000000000000000000000000..2d58845352b2c6716462caa89e0cca8fc46a8a33
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/.github/ISSUE_TEMPLATE/feature-request.yml
@@ -0,0 +1,22 @@
+name: Feature request
+description: Check instructions for submitting your idea on the mailing list first.
+title: "ENH: "
+
+body:
+- type: markdown
+ attributes:
+ value: >
+ If you're looking to request a new feature or change in functionality,
+ including adding or changing the meaning of arguments to an existing
+ function, please post your idea on the
+ [numpy-discussion mailing list](https://mail.python.org/mailman/listinfo/numpy-discussion)
+ to explain your reasoning in addition to opening an issue or pull request.
+ You can also check out our
+ [Contributor Guide](https://github.com/numpy/numpy/blob/main/doc/source/dev/index.rst)
+ if you need more information.
+
+- type: textarea
+ attributes:
+ label: "Proposed new feature or change:"
+ validations:
+ required: true
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/.github/workflows/lint.yml b/tasks/tasksmith-a7e859277e7a/tests/source/.github/workflows/lint.yml
new file mode 100644
index 0000000000000000000000000000000000000000..7ed2347287e29d3412b965b2a7ef2799f5a5c842
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/.github/workflows/lint.yml
@@ -0,0 +1,53 @@
+name: Lint
+
+on:
+ push:
+ branches:
+ - "*"
+ pull_request:
+ branches:
+ - main
+
+permissions:
+ contents: read # to fetch code (actions/checkout)
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
+ cancel-in-progress: true
+
+jobs:
+ test_lint:
+ name: Lint
+ # If using act to run CI locally the github object does not exist and the usual skipping should not be enforced
+ if: "github.repository == 'numpy/numpy-financial' || github.repository == ''"
+ runs-on: ubuntu-22.04
+ strategy:
+ matrix:
+ python-version: ['3.11']
+
+ steps:
+ - uses: actions/checkout@v3
+ with:
+ fetch-depth: 0
+ submodules: recursive
+
+ - name: Setup Python
+ uses: actions/setup-python@v4
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Install Python packages
+ run: |
+ python -m pip install --upgrade pip poetry
+ poetry env use ${{ matrix.python-version }}
+ poetry install --with=lint
+
+ - name: Lint with Ruff
+ run: |
+ set -euo pipefail
+ # Tell us what version we are using
+ poetry run ruff version
+ # Check the source file, ignore type annotations (ANN) for now.
+ poetry run ruff check numpy_financial/ --ignore F403 --select E,F,B,I
+ # Check the test and benchmark files
+ poetry run ruff check tests/ benchmarks/ --select E,F,B,I
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/.github/workflows/publish_docs_to_pages.yml b/tasks/tasksmith-a7e859277e7a/tests/source/.github/workflows/publish_docs_to_pages.yml
new file mode 100644
index 0000000000000000000000000000000000000000..d8fe8e0ddfba20655903476855d887a626c167ef
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/.github/workflows/publish_docs_to_pages.yml
@@ -0,0 +1,76 @@
+name: Publish docs to gh-pages
+
+on:
+ push:
+ branches:
+ - master
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v1
+ - uses: actions/setup-python@v1
+ with:
+ python-version: '3.7'
+ - name: Install dependencies
+ run: |
+ export DEBIAN_FRONTEND=noninteractive
+ sudo apt-get -q -y install dvipng texlive-latex-extra
+ python -m pip install --upgrade pip
+ pip install -r requirements.txt
+ pip install sphinx
+ pip install numpydoc
+ - name: Install numpy-financial
+ run: |
+ pip install .
+ - name: Build documentation with Sphinx
+ run: |
+ cd doc
+ make html
+ mv build/html /tmp
+ cd ..
+ - name: Deploy to gh-pages branch
+ env:
+ GH_ACTION_PAGES_DEPLOY_KEY: ${{ secrets.GH_ACTION_PAGES_DEPLOY_KEY }}
+ run: |
+ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ # Set up SSH key
+ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ mkdir -p ~/.ssh/
+ echo "$GH_ACTION_PAGES_DEPLOY_KEY" > ~/.ssh/id_rsa
+ chmod 600 ~/.ssh/id_rsa
+ ssh-keyscan github.com >> ~/.ssh/known_hosts
+ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ # Reconfigure the git remote to use SSH
+ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ git remote rm origin
+ git remote add origin git@github.com:numpy/numpy-financial.git
+ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ # Configure the git user
+ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ git config user.name "${GITHUB_ACTOR}"
+ git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
+ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ # Go to work on gh-pages...
+ # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ echo "Fetching gh-pages"
+ git fetch origin gh-pages
+ echo "Checking out gh-pages branch"
+ git checkout gh-pages
+ echo "Removing old dev documentation"
+ git clean -xdf .
+ cd dev
+ git rm -r '*'
+ cd ..
+ echo "Committing emptied dev directory"
+ git commit -m "Remove old dev documentation"
+ mkdir dev
+ cd dev
+ echo "Copying /tmp/html here"
+ cp -v -r /tmp/html/* .
+ echo "Adding new dev documentation"
+ git add -A .
+ git commit -m "Add new dev documentation"
+ echo "Pushing new documentation to origin"
+ git push -v origin gh-pages
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/.github/workflows/pythonpackage.yml b/tasks/tasksmith-a7e859277e7a/tests/source/.github/workflows/pythonpackage.yml
new file mode 100644
index 0000000000000000000000000000000000000000..e5b576cc03ea77b0662b2e47e3941506816ccac8
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/.github/workflows/pythonpackage.yml
@@ -0,0 +1,25 @@
+name: Python package
+
+on: [push, pull_request]
+
+jobs:
+ build:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ python-version: ["3.10", "3.11", "3.12"]
+ steps:
+ - uses: actions/checkout@v3
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v4
+ with:
+ python-version: ${{ matrix.python-version }}
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip poetry
+ poetry env use ${{ matrix.python-version }}
+ poetry install --with=test
+ - name: Test with pytest
+ run: |
+ poetry run pytest --doctest-modules
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/.gitignore b/tasks/tasksmith-a7e859277e7a/tests/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..e03204a679cb6ef6554c1814491adfa781db5524
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/.gitignore
@@ -0,0 +1,113 @@
+# Editor temporary/working/backup files #
+#########################################
+.#*
+[#]*#
+*~
+*$
+*.bak
+*.diff
+.idea/
+*.iml
+*.ipr
+*.iws
+*.org
+.project
+pmip
+*.rej
+.settings/
+.*.sw[nop]
+.sw[nop]
+*.tmp
+*.vim
+.vscode
+tags
+cscope.out
+# gnu global
+GPATH
+GRTAGS
+GSYMS
+GTAGS
+.cache
+
+# Compiled source #
+###################
+*.a
+*.com
+*.class
+*.dll
+*.exe
+*.o
+*.o.d
+*.py[ocd]
+*.so
+
+# Packages #
+############
+# it's better to unpack these files and commit the raw source
+# git has its own built in compression methods
+*.7z
+*.bz2
+*.bzip2
+*.dmg
+*.gz
+*.iso
+*.jar
+*.rar
+*.tar
+*.tbz2
+*.tgz
+*.zip
+
+# Python files #
+################
+# setup.py working directory
+build
+# sphinx build directory
+_build
+# setup.py dist directory
+dist
+doc/build
+doc/cdoc/build
+# Egg metadata
+*.egg-info
+# The shelf plugin uses this dir
+./.shelf
+MANIFEST
+.cache
+
+# Paver generated files #
+#########################
+/release
+
+# Logs and databases #
+######################
+*.log
+*.sql
+*.sqlite
+
+# Patches #
+###########
+*.patch
+*.diff
+
+# OS generated files #
+######################
+.DS_Store*
+.VolumeIcon.icns
+.fseventsd
+Icon?
+.gdb_history
+ehthumbs.db
+Thumbs.db
+.directory
+
+# pytest generated files #
+##########################
+/.pytest_cache
+
+# Poetry lock file #
+####################
+poetry.lock
+
+# Things specific to this project #
+###################################
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/Dockerfile b/tasks/tasksmith-a7e859277e7a/tests/source/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..0962562da3fc7054d5e236a0674b98732495c356
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/Dockerfile
@@ -0,0 +1,8 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir poetry-core==1.9.1 numba==0.68.1 llvmlite==0.50.0 numpy==2.5.5 pytest==8.3.5 'hypothesis[numpy]==6.99.11' 'pytest-xdist[psutil]==3.5.0'
+COPY . /workspace
+RUN python -m pip install --no-cache-dir -e .
+RUN rm -rf /workspace/.git /root/.cache/pip
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/LICENSE.txt b/tasks/tasksmith-a7e859277e7a/tests/source/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5eae3201a70c2be97770d15f669c23ac861a3aca
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/LICENSE.txt
@@ -0,0 +1,30 @@
+Copyright (c) 2005-2019, NumPy Developers.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided
+ with the distribution.
+
+ * Neither the name of the NumPy Developers nor the names of any
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/README.md b/tasks/tasksmith-a7e859277e7a/tests/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..de91eed7b594b1d3b8265623d09cb937fb51f6d8
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/README.md
@@ -0,0 +1,21 @@
+# NumPy Financial
+
+The `numpy-financial` package contains a collection of elementary financial
+functions.
+
+The [financial functions in NumPy](https://numpy.org/doc/1.17/reference/routines.financial.html)
+are deprecated and eventually will be removed from NumPy; see
+[NEP-32](https://numpy.org/neps/nep-0032-remove-financial-functions.html)
+for more information. This package is the replacement for the original
+NumPy financial functions.
+
+The source code for this package is available at https://github.com/numpy/numpy-financial.
+
+The importable name of the package is `numpy_financial`. The recommended
+alias is `npf`. For example,
+
+```
+>>> import numpy_financial as npf
+>>> npf.irr([-250000, 100000, 150000, 200000, 250000, 300000])
+0.5672303344358536
+```
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/asv.conf.json b/tasks/tasksmith-a7e859277e7a/tests/source/asv.conf.json
new file mode 100644
index 0000000000000000000000000000000000000000..e20ed9b1ef3e74bd2ecb4d89b09138cb1c0441a7
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/asv.conf.json
@@ -0,0 +1,193 @@
+{
+ // The version of the config file format. Do not change, unless
+ // you know what you are doing.
+ "version": 1,
+
+ // The name of the project being benchmarked
+ "project": "NumPy-Financial",
+
+ // The project's homepage
+ "project_url": "https://numpy.org/numpy-financial//",
+
+ // The URL or local path of the source code repository for the
+ // project being benchmarked
+ "repo": ".",
+
+ // The Python project's subdirectory in your repo. If missing or
+ // the empty string, the project is assumed to be located at the root
+ // of the repository.
+ // "repo_subdir": "",
+
+ // Customizable commands for building the project.
+ // See asv.conf.json documentation.
+ // To build the package using pyproject.toml (PEP518), uncomment the following lines
+ "build_command": [
+ "python -m pip install build",
+ "python -m build",
+ "PIP_NO_BUILD_ISOLATION=false python -mpip wheel --no-deps --no-index -w {build_cache_dir} {build_dir}"
+ ],
+ // To build the package using setuptools and a setup.py file, uncomment the following lines
+ // "build_command": [
+ // "python setup.py build",
+ // "PIP_NO_BUILD_ISOLATION=false python -mpip wheel --no-deps --no-index -w {build_cache_dir} {build_dir}"
+ // ],
+
+ // Customizable commands for installing and uninstalling the project.
+ // See asv.conf.json documentation.
+ // "install_command": ["in-dir={env_dir} python -mpip install {wheel_file}"],
+ // "uninstall_command": ["return-code=any python -mpip uninstall -y {project}"],
+
+ // List of branches to benchmark. If not provided, defaults to "master"
+ // (for git) or "default" (for mercurial).
+ "branches": ["main"],
+
+ // The DVCS being used. If not set, it will be automatically
+ // determined from "repo" by looking at the protocol in the URL
+ // (if remote), or by looking for special directories, such as
+ // ".git" (if local).
+ "dvcs": "git",
+
+ // The tool to use to create environments. May be "conda",
+ // "virtualenv", "mamba" (above 3.8)
+ // or other value depending on the plugins in use.
+ // If missing or the empty string, the tool will be automatically
+ // determined by looking for tools on the PATH environment
+ // variable.
+ "environment_type": "virtualenv",
+
+ // timeout in seconds for installing any dependencies in environment
+ // defaults to 10 min
+ //"install_timeout": 600,
+
+ // the base URL to show a commit for the project.
+ // "show_commit_url": "http://github.com/owner/project/commit/",
+
+ // The Pythons you'd like to test against. If not provided, defaults
+ // to the current version of Python used to run `asv`.
+ // "pythons": ["2.7", "3.8"],
+
+ // The list of conda channel names to be searched for benchmark
+ // dependency packages in the specified order
+ // "conda_channels": ["conda-forge", "defaults"],
+
+ // A conda environment file that is used for environment creation.
+ // "conda_environment_file": "environment.yml",
+
+ // The matrix of dependencies to test. Each key of the "req"
+ // requirements dictionary is the name of a package (in PyPI) and
+ // the values are version numbers. An empty list or empty string
+ // indicates to just test against the default (latest)
+ // version. null indicates that the package is to not be
+ // installed. If the package to be tested is only available from
+ // PyPi, and the 'environment_type' is conda, then you can preface
+ // the package name by 'pip+', and the package will be installed
+ // via pip (with all the conda available packages installed first,
+ // followed by the pip installed packages).
+ //
+ // The ``@env`` and ``@env_nobuild`` keys contain the matrix of
+ // environment variables to pass to build and benchmark commands.
+ // An environment will be created for every combination of the
+ // cartesian product of the "@env" variables in this matrix.
+ // Variables in "@env_nobuild" will be passed to every environment
+ // during the benchmark phase, but will not trigger creation of
+ // new environments. A value of ``null`` means that the variable
+ // will not be set for the current combination.
+ //
+ // "matrix": {
+ // "req": {
+ // "numpy": ["1.6", "1.7"],
+ // "six": ["", null], // test with and without six installed
+ // "pip+emcee": [""] // emcee is only available for install with pip.
+ // },
+ // "env": {"ENV_VAR_1": ["val1", "val2"]},
+ // "env_nobuild": {"ENV_VAR_2": ["val3", null]},
+ // },
+
+ // Combinations of libraries/python versions can be excluded/included
+ // from the set to test. Each entry is a dictionary containing additional
+ // key-value pairs to include/exclude.
+ //
+ // An exclude entry excludes entries where all values match. The
+ // values are regexps that should match the whole string.
+ //
+ // An include entry adds an environment. Only the packages listed
+ // are installed. The 'python' key is required. The exclude rules
+ // do not apply to includes.
+ //
+ // In addition to package names, the following keys are available:
+ //
+ // - python
+ // Python version, as in the *pythons* variable above.
+ // - environment_type
+ // Environment type, as above.
+ // - sys_platform
+ // Platform, as in sys.platform. Possible values for the common
+ // cases: 'linux2', 'win32', 'cygwin', 'darwin'.
+ // - req
+ // Required packages
+ // - env
+ // Environment variables
+ // - env_nobuild
+ // Non-build environment variables
+ //
+ // "exclude": [
+ // {"python": "3.2", "sys_platform": "win32"}, // skip py3.2 on windows
+ // {"environment_type": "conda", "req": {"six": null}}, // don't run without six on conda
+ // {"env": {"ENV_VAR_1": "val2"}}, // skip val2 for ENV_VAR_1
+ // ],
+ //
+ // "include": [
+ // // additional env for python2.7
+ // {"python": "2.7", "req": {"numpy": "1.8"}, "env_nobuild": {"FOO": "123"}},
+ // // additional env if run on windows+conda
+ // {"platform": "win32", "environment_type": "conda", "python": "2.7", "req": {"libpython": ""}},
+ // ],
+
+ // The directory (relative to the current directory) that benchmarks are
+ // stored in. If not provided, defaults to "benchmarks"
+ // "benchmark_dir": "benchmarks",
+
+ // The directory (relative to the current directory) to cache the Python
+ // environments in. If not provided, defaults to "env"
+ "env_dir": ".asv/env",
+
+ // The directory (relative to the current directory) that raw benchmark
+ // results are stored in. If not provided, defaults to "results".
+ "results_dir": ".asv/results",
+
+ // The directory (relative to the current directory) that the html tree
+ // should be written to. If not provided, defaults to "html".
+ "html_dir": ".asv/html",
+
+ // The number of characters to retain in the commit hashes.
+ // "hash_length": 8,
+
+ // `asv` will cache results of the recent builds in each
+ // environment, making them faster to install next time. This is
+ // the number of builds to keep, per environment.
+ // "build_cache_size": 2,
+
+ // The commits after which the regression search in `asv publish`
+ // should start looking for regressions. Dictionary whose keys are
+ // regexps matching to benchmark names, and values corresponding to
+ // the commit (exclusive) after which to start looking for
+ // regressions. The default is to start from the first commit
+ // with results. If the commit is `null`, regression detection is
+ // skipped for the matching benchmark.
+ //
+ // "regressions_first_commits": {
+ // "some_benchmark": "352cdf", // Consider regressions only after this commit
+ // "another_benchmark": null, // Skip regression detection altogether
+ // },
+
+ // The thresholds for relative change in results, after which `asv
+ // publish` starts reporting regressions. Dictionary of the same
+ // form as in ``regressions_first_commits``, with values
+ // indicating the thresholds. If multiple entries match, the
+ // maximum is taken. If no entry matches, the default is 5%.
+ //
+ // "regressions_thresholds": {
+ // "some_benchmark": 0.01, // Threshold of 1%
+ // "another_benchmark": 0.5, // Threshold of 50%
+ // },
+}
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/benchmarks/__init__.py b/tasks/tasksmith-a7e859277e7a/tests/source/benchmarks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/benchmarks/benchmarks.py b/tasks/tasksmith-a7e859277e7a/tests/source/benchmarks/benchmarks.py
new file mode 100644
index 0000000000000000000000000000000000000000..fffe5c66f65a41b638546d6a7f2b0a62a1e91fa2
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/benchmarks/benchmarks.py
@@ -0,0 +1,49 @@
+from decimal import Decimal
+
+import numpy as np
+
+import numpy_financial as npf
+
+
+def _to_decimal_array_1d(array):
+ return np.array([Decimal(x) for x in array.tolist()])
+
+
+def _to_decimal_array_2d(array):
+ decimals = [Decimal(x) for row in array.tolist() for x in row]
+ return np.array(decimals).reshape(array.shape)
+
+
+class Npv2D:
+
+ param_names = ["n_cashflows", "cashflow_lengths", "rates_lengths"]
+ params = [
+ (1, 10, 100),
+ (1, 10, 100),
+ (1, 10, 100),
+ ]
+
+ def __init__(self):
+ self.rates_decimal = None
+ self.rates = None
+ self.cashflows_decimal = None
+ self.cashflows = None
+
+ def setup(self, n_cashflows, cashflow_lengths, rates_lengths):
+ rng = np.random.default_rng(0)
+ cf_shape = (n_cashflows, cashflow_lengths)
+ self.cashflows = rng.standard_normal(cf_shape)
+ self.rates = rng.standard_normal(rates_lengths)
+ self.cashflows_decimal = _to_decimal_array_2d(self.cashflows)
+ self.rates_decimal = _to_decimal_array_1d(self.rates)
+
+ def time_for_loop(self, n_cashflows, cashflow_lengths, rates_lengths):
+ for rate in self.rates:
+ for cashflow in self.cashflows:
+ npf.npv(rate, cashflow)
+
+ def time_for_loop_decimal(self, n_cashflows, cashflow_lengths, rates_lengths):
+ for rate in self.rates_decimal:
+ for cashflow in self.cashflows_decimal:
+ npf.npv(rate, cashflow)
+
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/Makefile b/tasks/tasksmith-a7e859277e7a/tests/source/doc/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..d0c3cbf1020d5c292abdedf27627c6abe25e2293
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/Makefile
@@ -0,0 +1,20 @@
+# Minimal makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line, and also
+# from the environment for the first two.
+SPHINXOPTS ?=
+SPHINXBUILD ?= sphinx-build
+SOURCEDIR = source
+BUILDDIR = build
+
+# Put it first so that "make" without argument is like "make help".
+help:
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+
+.PHONY: help Makefile
+
+# Catch-all target: route all unknown targets to Sphinx using the new
+# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
+%: Makefile
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/make.bat b/tasks/tasksmith-a7e859277e7a/tests/source/doc/make.bat
new file mode 100644
index 0000000000000000000000000000000000000000..6247f7e231716482115f34084ac61030743e0715
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/make.bat
@@ -0,0 +1,35 @@
+@ECHO OFF
+
+pushd %~dp0
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+ set SPHINXBUILD=sphinx-build
+)
+set SOURCEDIR=source
+set BUILDDIR=build
+
+if "%1" == "" goto help
+
+%SPHINXBUILD% >NUL 2>NUL
+if errorlevel 9009 (
+ echo.
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
+ echo.installed, then set the SPHINXBUILD environment variable to point
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
+ echo.may add the Sphinx directory to PATH.
+ echo.
+ echo.If you don't have Sphinx installed, grab it from
+ echo.http://sphinx-doc.org/
+ exit /b 1
+)
+
+%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
+goto end
+
+:help
+%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
+
+:end
+popd
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/_static/numpy_financial_favicon.png b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/_static/numpy_financial_favicon.png
new file mode 100644
index 0000000000000000000000000000000000000000..14d7d7c5f7390761b6d53c76b835185cee0e029b
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/_static/numpy_financial_favicon.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:28f9fc915f503b23ec5f8c8fd088f608140cc457bff13fd0361ab7b1e48b1519
+size 170
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/_static/numpy_financial_logov.svg b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/_static/numpy_financial_logov.svg
new file mode 100644
index 0000000000000000000000000000000000000000..287607bc4e1adf25208943a6cfd970afcd90f5d1
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/_static/numpy_financial_logov.svg
@@ -0,0 +1,12 @@
+
+
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/conf.py b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0866a13a0d7394f12b958dff290d9bf5472d28a
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/conf.py
@@ -0,0 +1,67 @@
+# Configuration file for the Sphinx documentation builder.
+#
+# This file only contains a selection of the most common options. For a full
+# list see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+import numpy_financial
+
+# -- Path setup --------------------------------------------------------------
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#
+# import os
+# import sys
+# sys.path.insert(0, os.path.abspath('.'))
+
+
+# -- Project information -----------------------------------------------------
+
+project = 'numpy-financial'
+copyright = '2023, numpy-financial developers'
+author = 'numpy-financial developers'
+
+
+# -- General configuration ---------------------------------------------------
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = [
+ 'sphinx.ext.autodoc',
+ 'numpydoc',
+ 'sphinx.ext.mathjax',
+ 'myst_parser',
+]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+# This pattern also affects html_static_path and html_extra_path.
+exclude_patterns = []
+
+version = numpy_financial.__version__
+
+# -- Options for HTML output -------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+#
+html_theme = 'pydata_sphinx_theme'
+html_copy_source = False
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+html_logo = "_static/numpy_financial_logov.svg"
+html_favicon = "_static/numpy_financial_favicon.png"
+
+html_sidebars = {
+ '**': ['localtoc.html', 'searchbox.html'],
+}
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/dev/building_with_poetry.md b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/dev/building_with_poetry.md
new file mode 100644
index 0000000000000000000000000000000000000000..ffc17d2cb6cd7f2d5dc6b3afd69193a1d9310584
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/dev/building_with_poetry.md
@@ -0,0 +1,67 @@
+# Building with poetry
+
+## Installing poetry
+numpy-financial uses [poetry](https://python-poetry.org/) to manage
+dependencies, build wheels and sdists, and publish to PyPI this page documents
+how to work with poetry.
+
+To install poetry follow their [official guide](https://python-poetry.org/docs/#installing-with-the-official-installer)
+it is recommended to use the official installer for local development.
+
+To check your installation try to check the version of poetry:
+
+```shell
+poetry -V
+```
+
+## Setting up a virtual environment using poetry
+
+Once poetry is installed it is time to set up the virtual environment. To do
+this run:
+
+```shell
+poetry install
+```
+
+``poetry install`` looks for dependencies in the ``pyproject.toml`` file,
+resolves them to the most recent version and installs the dependencies
+in a virtual environment. It is now possible to launch an interactive REPL
+by running the following command:
+
+```shell
+poetry run python
+```
+
+## Running the test suite
+
+numpy-financial has an extensive test suite, which can be run with the
+following command:
+
+```shell
+poetry run pytest
+```
+
+## Building distributions
+
+It is possible to manually build distributions for numpy-financial using
+poetry. This is possible via the `build` command:
+
+```shell
+poetry build
+```
+
+The `build` command creates a `dist` directory containing a wheel and sdist
+file.
+
+
+## Publishing to PyPI
+
+poetry provides support to publish packages to PyPI. This is possible using
+the ``publish`` command:
+
+```shell
+poetry publish --build --username --password
+```
+
+Note that this builds the package before publishing it. You will need to
+provide the correct username and password for PyPI.
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/dev/getting_the_code.md b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/dev/getting_the_code.md
new file mode 100644
index 0000000000000000000000000000000000000000..7aa822a6d24311892bff27c4cf260e99230cd846
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/dev/getting_the_code.md
@@ -0,0 +1,43 @@
+# Getting the code
+
+This document explains how to get the source code for NumPy-Financial using Git.
+
+## Code Location
+
+NumPy-Financial is hosted on GitHub. The repository URL is https://github.com/numpy/numpy-financial.
+
+## Creating a fork
+
+To create a fork click the green "fork" button at the top right of the page. This creates a new repository on your
+GitHub profile. This will have the URL: https://github.com//numpy-financial.
+
+## Cloning the repository
+
+Now that you have forked the repository you will need to clone it. This copies the repository from GitHub to the local
+machine. To clone a repository enter the following commands in the terminal.
+
+```shell
+git clone https://github.com//numpy-financial.git
+```
+
+Hooray! You now have a working copy of NumPy-Financial.
+
+
+## Updating the code with other's changes
+
+From time to time you may want to pull down the latest code. Do this with:
+
+```shell
+git fetch
+```
+
+The `git fetch` command downloads commits, files and refs from a remote repo into your local repo.
+
+Then run:
+
+```shell
+git merge --ff-only
+```
+
+The `git merge` command is Git's way of putting independent branches back together. The `--ff-only` flag tells git to
+use `fast-forward` merges. This is preferable as fast-forward merge avoids creating merge commits.
\ No newline at end of file
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/dev/running_the_benchmarks.md b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/dev/running_the_benchmarks.md
new file mode 100644
index 0000000000000000000000000000000000000000..e15efe9a100e2eec9d5d89bef8587a2368f18c9d
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/dev/running_the_benchmarks.md
@@ -0,0 +1,55 @@
+# Running the benchmarks
+
+This document outlines how to setup and run the benchmarks using [asv](https://asv.readthedocs.io/en/v0.6.1/).
+
+## Installing asv
+
+`asv` can be installed with poetry via the `bench` group to install the bench group run:
+
+```shell
+poetry install --with=bench
+```
+
+This will install ``asv`` into your poetry environment.
+
+## Running the benchmarks
+
+To run the benchmarks with ``asv``, simply enter:
+
+```shell
+poetry run asv run
+```
+
+## Viewing the results
+
+There are two steps to viewing the results locally. The results need to be published and the launched in a local web browser.
+
+To publish the results use:
+
+```shell
+poetry run asv publish
+```
+
+And then to view the results:
+
+```shell
+poetry run asv preview
+```
+
+This will launch a local web browser from which you can view the results
+
+## Dry runs
+
+One common use case is to use ``asv`` in development, there are several useful flags that should be used:
+
+```shell
+poetry run asv --python=same --quick --dry-run
+```
+
+We are adding three flags, these flags are:
+
+1. `--python=same` uses the same environment as your development environment (saves time to avoid building environments)
+2. `--quick` only runs the benchmarks once
+3. `--dry-run` to not save the results of the benchmarks
+
+These can be useful for getting quick feedback during development, but should not be used as anything other than a rough guide.
\ No newline at end of file
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/fv.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/fv.rst
new file mode 100644
index 0000000000000000000000000000000000000000..269b814d7cfb677ad36ab4ca7cec7c676b3ab9a6
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/fv.rst
@@ -0,0 +1,8 @@
+fv
+==
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: fv
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/generate_rst_function_files.py b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/generate_rst_function_files.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b7801c418b28e4859637318ebf9a88c08f36350
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/generate_rst_function_files.py
@@ -0,0 +1,27 @@
+
+# This script was used to generate the rst function stubs
+# numpy_financial.fv.rst, numpy_financial.ipmt.rst, etc.
+# It requires that numpy_financial is already installed,
+# although it could just as easily use a hard-coded list
+# of function names.
+
+import numpy_financial as nf
+
+
+def generate_rst_function_files():
+ names = [name for name in dir(nf) if not name.startswith('_')]
+ for name in names:
+ with open(name + '.rst', 'w') as f:
+ f.write('''{name}
+{underline}
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: {name}
+'''.format(name=name, underline='='*len(name)))
+
+
+if __name__ == "__main__":
+ generate_rst_function_files()
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/index.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/index.rst
new file mode 100644
index 0000000000000000000000000000000000000000..93d67c2dc42e0c5aa67a90aaf98279e1b567a986
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/index.rst
@@ -0,0 +1,79 @@
+
+numpy-financial |version|
+=========================
+
+The `numpy-financial` package is a collection of elementary financial
+functions.
+
+The `financial functions in NumPy `_
+are deprecated and eventually will be removed from NumPy; see
+`NEP-32 `_
+for more information. This package is the replacement for the deprecated
+NumPy financial functions.
+
+The source code for this package is available at https://github.com/numpy/numpy-financial.
+
+The importable name of the package is `numpy_financial`. The recommended
+alias is `npf`. For example,
+
+>>> import numpy_financial as npf
+>>> npf.irr([-250000, 100000, 150000, 200000, 250000, 300000])
+0.5672303344358536
+
+
+Functions
+---------
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+ :maxdepth: 4
+
+.. autosummary::
+
+ fv
+ ipmt
+ irr
+ mirr
+ nper
+ npv
+ pmt
+ ppmt
+ pv
+ rate
+
+.. The following "hidden" toctree is a hack to prevent Sphinx warnings
+ about "document isn't included in any toctree"
+
+.. toctree::
+ :hidden:
+
+ fv
+ ipmt
+ irr
+ mirr
+ nper
+ npv
+ pmt
+ ppmt
+ pv
+ rate
+
+Development
+===========
+
+.. toctree::
+ :maxdepth: 1
+
+ dev/getting_the_code.md
+ dev/building_with_poetry.md
+ dev/running_the_benchmarks.md
+
+.. include:: release-notes.rst
+
+
+Index and Search
+================
+
+* :ref:`genindex`
+* :ref:`search`
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/ipmt.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/ipmt.rst
new file mode 100644
index 0000000000000000000000000000000000000000..f40beff18814641bd25b9b415d78d6859c134fde
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/ipmt.rst
@@ -0,0 +1,8 @@
+ipmt
+====
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: ipmt
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/irr.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/irr.rst
new file mode 100644
index 0000000000000000000000000000000000000000..8873dba40995b87d9da381b452a6049cbe1d2027
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/irr.rst
@@ -0,0 +1,8 @@
+irr
+===
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: irr
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/mirr.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/mirr.rst
new file mode 100644
index 0000000000000000000000000000000000000000..0e2977b9c7eb4988015f1297aa03e23e476f8c8e
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/mirr.rst
@@ -0,0 +1,8 @@
+mirr
+====
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: mirr
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/nper.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/nper.rst
new file mode 100644
index 0000000000000000000000000000000000000000..ad56e96d12a9270a6a9b89394a6d77b91b249984
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/nper.rst
@@ -0,0 +1,8 @@
+nper
+====
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: nper
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/npv.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/npv.rst
new file mode 100644
index 0000000000000000000000000000000000000000..70b9820800b1e86288d2786064f0253c11324bc6
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/npv.rst
@@ -0,0 +1,8 @@
+npv
+===
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: npv
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/pmt.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/pmt.rst
new file mode 100644
index 0000000000000000000000000000000000000000..20415138832e549d952236a09b026f4f2223f064
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/pmt.rst
@@ -0,0 +1,8 @@
+pmt
+===
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: pmt
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/ppmt.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/ppmt.rst
new file mode 100644
index 0000000000000000000000000000000000000000..8f72c2a76659f964bdae380270d932011aac3cd3
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/ppmt.rst
@@ -0,0 +1,8 @@
+ppmt
+====
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: ppmt
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/pv.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/pv.rst
new file mode 100644
index 0000000000000000000000000000000000000000..701e6f745c008dff1892fd51e15c087567447690
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/pv.rst
@@ -0,0 +1,8 @@
+pv
+==
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: pv
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/rate.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/rate.rst
new file mode 100644
index 0000000000000000000000000000000000000000..f79783345a9830a1275044415103ec0263d1cd36
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/rate.rst
@@ -0,0 +1,8 @@
+rate
+====
+
+.. currentmodule:: numpy_financial
+
+.. toctree::
+
+.. autofunction:: rate
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/release-notes.rst b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/release-notes.rst
new file mode 100644
index 0000000000000000000000000000000000000000..3e0683db5c48bb11bff2ecc83bcf59e0770bc69f
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/doc/source/release-notes.rst
@@ -0,0 +1,20 @@
+Release Notes
+-------------
+1.1.0
+~~~~~
+* **1.1.0 is not released yet.**
+
+1.0.0
+~~~~~
+* The transition of the source code from NumPy to this package is complete.
+
+0.2.0
+~~~~~
+* Removed the use of `numpy.core.overrides.array_function_dispatch` to create
+ wrappers of the financial functions.
+* Support NumPy versions back to 1.15.
+
+0.1.0
+~~~~~
+* This is the initial release of numpy-financial. The functions were
+ copied from NumPy 1.17.
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/docweb/README.txt b/tasks/tasksmith-a7e859277e7a/tests/source/docweb/README.txt
new file mode 100644
index 0000000000000000000000000000000000000000..40de9310382c2f03c69cbc12d448f2ef4eb54fe6
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/docweb/README.txt
@@ -0,0 +1,3 @@
+This directory contains the files for the top-level online documentation.
+If these files are changed, the changes must be copied over to the top directory
+of the gh-pages branch.
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/docweb/css/home.css b/tasks/tasksmith-a7e859277e7a/tests/source/docweb/css/home.css
new file mode 100644
index 0000000000000000000000000000000000000000..ba17741c165767b0602d3efbfb9c08ed44d58417
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/docweb/css/home.css
@@ -0,0 +1,128 @@
+
+body {
+ margin: auto;
+ padding-right: 1em;
+ padding-left: 1em;
+ max-width: 48em;
+ color: black;
+ font-family: sans-serif;
+ font-size: 100%;
+ line-height: 125%;
+ color: #333;
+}
+pre {
+ border: 1px dotted gray;
+ background-color: #E8E8E8;
+ color: #101010;
+ padding: 0.5em;
+}
+code {
+ font-family: monospace;
+ font-size: 130%;
+ font-weight: bold;
+}
+h1 a, h2 a, h3 a, h4 a, h5 a {
+ text-decoration: none;
+ color: #336699;
+}
+h1, h2, h3, h4, h5 {
+ font-family: sans-serif;
+ font-weight: bold;
+ color: #336699; }
+
+h1 {
+ font-size: 130%;
+}
+
+h2 {
+ font-size: 110%;
+ font-style: italic;
+}
+
+h3 {
+ font-size: 95%;
+ font-style: italic;
+}
+
+h4 {
+ font-size: 90%;
+ font-style: italic;
+}
+
+h5 {
+ font-size: 90%;
+ font-style: italic;
+}
+
+h1.title {
+ font-size: 200%;
+ font-weight: bold;
+ padding-top: 0.2em;
+ padding-bottom: 0.2em;
+ text-align: left;
+ border: none;
+}
+
+dt code {
+ font-weight: bold;
+}
+dd p {
+ margin-top: 0;
+}
+
+ul {
+ padding: 0px 0px 0px 16px;
+}
+
+ul li {
+ margin: 0px;
+ padding: 0px;
+}
+
+.link2 {
+ border: solid 1px #000;
+ border-radius: 3x;
+ -moz-border-radius: 3px;
+ -webkit-border-radius: 3px;
+ background-color: #FFF;
+ color: #336699;
+ text-decoration: none;
+ text-align: center;
+ width: 180px;
+ margin: 0px 0px 2px 0px;
+ padding: 2px 0 0px 0px;
+ display: inline-block;
+}
+.link2:hover { background-color: #FFF060; }
+
+aside h3 {
+ margin: 10px 0px 2px 0px;
+}
+
+/*
+ * Specific id styles.
+ */
+
+#logo {
+ border: solid 1px #000;
+ padding: 5px 5px 3px 5px;
+ background-color: #FFFFEA;
+}
+
+#asidelinks {
+ width: 25%;
+ float: right;
+ color: black;
+ background-color: #E8F4FF;
+ padding: 0px 10px 10px 10px;
+ border: solid 1px #000;
+ margin: 0em 0.75em 0em 0.5em;
+ box-shadow: 5px 8px 9px #b0b0b0;
+}
+
+#footer {
+ padding-top: 1em;
+ font-size: 70%;
+ color: gray;
+ text-align: center;
+}
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/docweb/images/numpy_financial_favicon.png b/tasks/tasksmith-a7e859277e7a/tests/source/docweb/images/numpy_financial_favicon.png
new file mode 100644
index 0000000000000000000000000000000000000000..14d7d7c5f7390761b6d53c76b835185cee0e029b
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/docweb/images/numpy_financial_favicon.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:28f9fc915f503b23ec5f8c8fd088f608140cc457bff13fd0361ab7b1e48b1519
+size 170
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/docweb/images/numpy_financial_logoh.svg b/tasks/tasksmith-a7e859277e7a/tests/source/docweb/images/numpy_financial_logoh.svg
new file mode 100644
index 0000000000000000000000000000000000000000..0eb55d5e27372f0b0e28c3ac85dd36ad65a49406
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/docweb/images/numpy_financial_logoh.svg
@@ -0,0 +1,11 @@
+
+
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/docweb/index.html b/tasks/tasksmith-a7e859277e7a/tests/source/docweb/index.html
new file mode 100644
index 0000000000000000000000000000000000000000..9ea5367ae47d90dc9d38177e32943f7320bafce4
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/docweb/index.html
@@ -0,0 +1,105 @@
+
+
+
+
+
+ numpy-financial
+
+
+
+
+ numpy-financial
+
+
+
+
+
+
+
+The numpy-financial Python package is a collection of elementary
+financial functions. These functions were copied to this package
+from version 1.17 of NumPy.
+
+
The financial functions in NumPy
+are deprecated and eventually will be removed from NumPy; see
+NEP-32
+for more information. This package is the replacement for the deprecated
+NumPy financial functions.
+
+
+
Installation
+
+The package is available on PyPI, and may be installed
+with pip:
+
+
+ $ pip install numpy-financial
+
+
+The package requires NumPy version 1.15 or later.
+
+
+
Using numpy_financial
+
+The importable name of the package is numpy_financial.
+The recommended alias is npf. For example,
+
For code that uses the numpy namespace like this
+
+ import numpy as np
+
+ x = np.array([-250000, 100000, 150000, 200000, 250000, 300000])
+ r = np.irr(x)
+
+the import statement for the numpy-financial package must be added,
+and the calls of the financial functions must be changed to use
+the npf namespace:
+
+ import numpy as np
+ import numpy_financial as npf
+
+ x = np.array([-250000, 100000, 150000, 200000, 250000, 300000])
+ r = npf.irr(x)
+
+
+
+
+
+
+
+
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/numpy_financial/__init__.py b/tasks/tasksmith-a7e859277e7a/tests/source/numpy_financial/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e2b39e23611a0312fe0bc72cde1a1a4a1777562
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/numpy_financial/__init__.py
@@ -0,0 +1,9 @@
+"""__init__ file.
+
+This file allows us to import the public functions from NumPy-Financial and
+tells us the version we are using.
+"""
+
+__version__ = "1.1.0.dev0"
+
+from ._financial import *
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/numpy_financial/_financial.py b/tasks/tasksmith-a7e859277e7a/tests/source/numpy_financial/_financial.py
new file mode 100644
index 0000000000000000000000000000000000000000..a24ec5222514ecd5742c1ac0749668c5db4ce8d2
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/numpy_financial/_financial.py
@@ -0,0 +1,998 @@
+"""Some simple financial calculations.
+
+patterned after spreadsheet computations.
+
+There is some complexity in each function
+so that the functions behave like ufuncs with
+broadcasting and being able to be called with scalars
+or arrays (or other sequences).
+
+Functions support the :class:`decimal.Decimal` type unless
+otherwise stated.
+"""
+
+from decimal import Decimal
+
+import numpy as np
+
+__all__ = ['fv', 'pmt', 'nper', 'ipmt', 'ppmt', 'pv', 'rate',
+ 'irr', 'npv', 'mirr',
+ 'NoRealSolutionError', 'IterationsExceededError']
+
+_when_to_num = {'end': 0, 'begin': 1,
+ 'e': 0, 'b': 1,
+ 0: 0, 1: 1,
+ 'beginning': 1,
+ 'start': 1,
+ 'finish': 0}
+
+
+class NoRealSolutionError(Exception):
+ """No real solution to the problem."""
+
+
+class IterationsExceededError(Exception):
+ """Maximum number of iterations reached."""
+
+
+def _convert_when(when):
+ # Test to see if when has already been converted to ndarray
+ # This will happen if one function calls another, for example ppmt
+ if isinstance(when, np.ndarray):
+ return when
+ try:
+ return _when_to_num[when]
+ except (KeyError, TypeError):
+ return [_when_to_num[x] for x in when]
+
+
+def fv(rate, nper, pmt, pv, when='end'):
+ """Compute the future value.
+
+ Given:
+ * a present value, `pv`
+ * an interest `rate` compounded once per period, of which
+ there are
+ * `nper` total
+ * a (fixed) payment, `pmt`, paid either
+ * at the beginning (`when` = {'begin', 1}) or the end
+ (`when` = {'end', 0}) of each period
+
+ Return:
+ the value at the end of the `nper` periods
+
+ Parameters
+ ----------
+ rate : scalar or array_like of shape(M, )
+ Rate of interest as decimal (not per cent) per period
+ nper : scalar or array_like of shape(M, )
+ Number of compounding periods
+ pmt : scalar or array_like of shape(M, )
+ Payment
+ pv : scalar or array_like of shape(M, )
+ Present value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
+ When payments are due ('begin' (1) or 'end' (0)).
+ Defaults to {'end', 0}.
+
+ Returns
+ -------
+ out : ndarray
+ Future values. If all input is scalar, returns a scalar float. If
+ any input is array_like, returns future values for each input element.
+ If multiple inputs are array_like, they all must have the same shape.
+
+ Notes
+ -----
+ The future value is computed by solving the equation::
+
+ fv +
+ pv*(1+rate)**nper +
+ pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
+
+ or, when ``rate == 0``::
+
+ fv + pv + pmt * nper == 0
+
+ References
+ ----------
+ .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May).
+ Open Document Format for Office Applications (OpenDocument)v1.2,
+ Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version,
+ Pre-Draft 12. Organization for the Advancement of Structured Information
+ Standards (OASIS). Billerica, MA, USA. [ODT Document].
+ Available:
+ http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula
+ OpenDocument-formula-20090508.odt
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import numpy_financial as npf
+
+ What is the future value after 10 years of saving $100 now, with
+ an additional monthly savings of $100. Assume the interest rate is
+ 5% (annually) compounded monthly?
+
+ >>> npf.fv(0.05/12, 10*12, -100, -100)
+ 15692.92889433575
+
+ By convention, the negative sign represents cash flow out (i.e. money not
+ available today). Thus, saving $100 a month at 5% annual interest leads
+ to $15,692.93 available to spend in 10 years.
+
+ If any input is array_like, returns an array of equal shape. Let's
+ compare different interest rates from the example above.
+
+ >>> a = np.array((0.05, 0.06, 0.07))/12
+ >>> npf.fv(a, 10*12, -100, -100)
+ array([15692.92889434, 16569.87435405, 17509.44688102])
+
+ """
+ when = _convert_when(when)
+ rate, nper, pmt, pv, when = np.broadcast_arrays(rate, nper, pmt, pv, when)
+
+ fv_array = np.empty_like(rate)
+ zero = rate == 0
+ nonzero = ~zero
+
+ fv_array[zero] = -(pv[zero] + pmt[zero] * nper[zero])
+
+ rate_nonzero = rate[nonzero]
+ temp = (1 + rate_nonzero) ** nper[nonzero]
+ fv_array[nonzero] = (
+ - pv[nonzero] * temp
+ - pmt[nonzero] * (1 + rate_nonzero * when[nonzero]) / rate_nonzero
+ * (temp - 1)
+ )
+
+ if np.ndim(fv_array) == 0:
+ # Follow the ufunc convention of returning scalars for scalar
+ # and 0d array inputs.
+ return fv_array.item(0)
+ return fv_array
+
+
+def pmt(rate, nper, pv, fv=0, when='end'):
+ """Compute the payment against loan principal plus interest.
+
+ Given:
+ * a present value, `pv` (e.g., an amount borrowed)
+ * a future value, `fv` (e.g., 0)
+ * an interest `rate` compounded once per period, of which
+ there are
+ * `nper` total
+ * and (optional) specification of whether payment is made
+ at the beginning (`when` = {'begin', 1}) or the end
+ (`when` = {'end', 0}) of each period
+
+ Return:
+ the (fixed) periodic payment.
+
+ Parameters
+ ----------
+ rate : array_like
+ Rate of interest (per period)
+ nper : array_like
+ Number of compounding periods
+ pv : array_like
+ Present value
+ fv : array_like, optional
+ Future value (default = 0)
+ when : {{'begin', 1}, {'end', 0}}, {string, int}
+ When payments are due ('begin' (1) or 'end' (0))
+
+ Returns
+ -------
+ out : ndarray
+ Payment against loan plus interest. If all input is scalar, returns a
+ scalar float. If any input is array_like, returns payment for each
+ input element. If multiple inputs are array_like, they all must have
+ the same shape.
+
+ Notes
+ -----
+ The payment is computed by solving the equation::
+
+ fv +
+ pv*(1 + rate)**nper +
+ pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) == 0
+
+ or, when ``rate == 0``::
+
+ fv + pv + pmt * nper == 0
+
+ for ``pmt``.
+
+ Note that computing a monthly mortgage payment is only
+ one use for this function. For example, pmt returns the
+ periodic deposit one must make to achieve a specified
+ future balance given an initial deposit, a fixed,
+ periodically compounded interest rate, and the total
+ number of periods.
+
+ References
+ ----------
+ .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May).
+ Open Document Format for Office Applications (OpenDocument)v1.2,
+ Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version,
+ Pre-Draft 12. Organization for the Advancement of Structured Information
+ Standards (OASIS). Billerica, MA, USA. [ODT Document].
+ Available:
+ http://www.oasis-open.org/committees/documents.php
+ ?wg_abbrev=office-formulaOpenDocument-formula-20090508.odt
+
+ Examples
+ --------
+ >>> import numpy_financial as npf
+
+ What is the monthly payment needed to pay off a $200,000 loan in 15
+ years at an annual interest rate of 7.5%?
+
+ >>> npf.pmt(0.075/12, 12*15, 200000)
+ -1854.0247200054619
+
+ In order to pay-off (i.e., have a future-value of 0) the $200,000 obtained
+ today, a monthly payment of $1,854.02 would be required. Note that this
+ example illustrates usage of `fv` having a default value of 0.
+
+ """
+ when = _convert_when(when)
+ (rate, nper, pv, fv, when) = map(np.array, [rate, nper, pv, fv, when])
+ temp = (1 + rate) ** nper
+ mask = (rate == 0)
+ masked_rate = np.where(mask, 1, rate)
+ fact = np.where(mask != 0, nper,
+ (1 + masked_rate * when) * (temp - 1) / masked_rate)
+ return -(fv + pv * temp) / fact
+
+
+def nper(rate, pmt, pv, fv=0, when='end'):
+ """Compute the number of periodic payments.
+
+ :class:`decimal.Decimal` type is not supported.
+
+ Parameters
+ ----------
+ rate : array_like
+ Rate of interest (per period)
+ pmt : array_like
+ Payment
+ pv : array_like
+ Present value
+ fv : array_like, optional
+ Future value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
+ When payments are due ('begin' (1) or 'end' (0))
+
+ Notes
+ -----
+ The number of periods ``nper`` is computed by solving the equation::
+
+ fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate*((1+rate)**nper-1) = 0
+
+ but if ``rate = 0`` then::
+
+ fv + pv + pmt*nper = 0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import numpy_financial as npf
+
+ If you only had $150/month to pay towards the loan, how long would it take
+ to pay-off a loan of $8,000 at 7% annual interest?
+
+ >>> print(np.round(npf.nper(0.07/12, -150, 8000), 5))
+ 64.07335
+
+ So, over 64 months would be required to pay off the loan.
+
+ The same analysis could be done with several different interest rates
+ and/or payments and/or total amounts to produce an entire table.
+
+ >>> npf.nper(*(np.ogrid[0.07/12: 0.08/12: 0.01/12,
+ ... -150 : -99 : 50 ,
+ ... 8000 : 9001 : 1000]))
+ array([[[ 64.07334877, 74.06368256],
+ [108.07548412, 127.99022654]],
+
+ [[ 66.12443902, 76.87897353],
+ [114.70165583, 137.90124779]]])
+ """
+ when = _convert_when(when)
+ rate, pmt, pv, fv, when = np.broadcast_arrays(rate, pmt, pv, fv, when)
+ nper_array = np.empty_like(rate, dtype=np.float64)
+
+ zero = rate == 0
+ nonzero = ~zero
+
+ with np.errstate(divide='ignore'):
+ # Infinite numbers of payments are okay, so ignore the
+ # potential divide by zero.
+ nper_array[zero] = -(fv[zero] + pv[zero]) / pmt[zero]
+
+ nonzero_rate = rate[nonzero]
+ z = pmt[nonzero] * (1 + nonzero_rate * when[nonzero]) / nonzero_rate
+ nper_array[nonzero] = (
+ np.log((-fv[nonzero] + z) / (pv[nonzero] + z))
+ / np.log(1 + nonzero_rate)
+ )
+
+ return nper_array
+
+
+def _value_like(arr, value):
+ entry = arr.item(0)
+ if isinstance(entry, Decimal):
+ return Decimal(value)
+ return np.array(value, dtype=arr.dtype).item(0)
+
+
+def ipmt(rate, per, nper, pv, fv=0, when='end'):
+ """Compute the interest portion of a payment.
+
+ Parameters
+ ----------
+ rate : scalar or array_like of shape(M, )
+ Rate of interest as decimal (not per cent) per period
+ per : scalar or array_like of shape(M, )
+ Interest paid against the loan changes during the life or the loan.
+ The `per` is the payment period to calculate the interest amount.
+ nper : scalar or array_like of shape(M, )
+ Number of compounding periods
+ pv : scalar or array_like of shape(M, )
+ Present value
+ fv : scalar or array_like of shape(M, ), optional
+ Future value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
+ When payments are due ('begin' (1) or 'end' (0)).
+ Defaults to {'end', 0}.
+
+ Returns
+ -------
+ out : ndarray
+ Interest portion of payment. If all input is scalar, returns a scalar
+ float. If any input is array_like, returns interest payment for each
+ input element. If multiple inputs are array_like, they all must have
+ the same shape.
+
+ See Also
+ --------
+ ppmt, pmt, pv
+
+ Notes
+ -----
+ The total payment is made up of payment against principal plus interest.
+
+ ``pmt = ppmt + ipmt``
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import numpy_financial as npf
+
+ What is the amortization schedule for a 1 year loan of $2500 at
+ 8.24% interest per year compounded monthly?
+
+ >>> principal = 2500.00
+
+ The 'per' variable represents the periods of the loan. Remember that
+ financial equations start the period count at 1!
+
+ >>> per = np.arange(1*12) + 1
+ >>> ipmt = npf.ipmt(0.0824/12, per, 1*12, principal)
+ >>> ppmt = npf.ppmt(0.0824/12, per, 1*12, principal)
+
+ Each element of the sum of the 'ipmt' and 'ppmt' arrays should equal
+ 'pmt'.
+
+ >>> pmt = npf.pmt(0.0824/12, 1*12, principal)
+ >>> np.allclose(ipmt + ppmt, pmt)
+ True
+
+ >>> fmt = '{0:2d} {1:8.2f} {2:8.2f} {3:8.2f}'
+ >>> for payment in per:
+ ... index = payment - 1
+ ... principal = principal + ppmt[index]
+ ... print(fmt.format(payment, ppmt[index], ipmt[index], principal))
+ 1 -200.58 -17.17 2299.42
+ 2 -201.96 -15.79 2097.46
+ 3 -203.35 -14.40 1894.11
+ 4 -204.74 -13.01 1689.37
+ 5 -206.15 -11.60 1483.22
+ 6 -207.56 -10.18 1275.66
+ 7 -208.99 -8.76 1066.67
+ 8 -210.42 -7.32 856.25
+ 9 -211.87 -5.88 644.38
+ 10 -213.32 -4.42 431.05
+ 11 -214.79 -2.96 216.26
+ 12 -216.26 -1.49 -0.00
+
+ >>> interestpd = np.sum(ipmt)
+ >>> np.round(interestpd, 2)
+ -112.98
+
+ """
+ when = _convert_when(when)
+ rate, per, nper, pv, fv, when = np.broadcast_arrays(rate, per, nper,
+ pv, fv, when)
+
+ total_pmt = pmt(rate, nper, pv, fv, when)
+ ipmt_array = np.array(_rbl(rate, per, total_pmt, pv, when) * rate)
+
+ # Payments start at the first period, so payments before that
+ # don't make any sense.
+ ipmt_array[per < 1] = _value_like(ipmt_array, np.nan)
+ # If payments occur at the beginning of a period and this is the
+ # first period, then no interest has accrued.
+ per1_and_begin = (when == 1) & (per == 1)
+ ipmt_array[per1_and_begin] = _value_like(ipmt_array, 0)
+ # If paying at the beginning we need to discount by one period.
+ per_gt_1_and_begin = (when == 1) & (per > 1)
+ ipmt_array[per_gt_1_and_begin] = (
+ ipmt_array[per_gt_1_and_begin] / (1 + rate[per_gt_1_and_begin])
+ )
+
+ if np.ndim(ipmt_array) == 0:
+ # Follow the ufunc convention of returning scalars for scalar
+ # and 0d array inputs.
+ return ipmt_array.item(0)
+ return ipmt_array
+
+
+def _rbl(rate, per, pmt, pv, when):
+ """Remaining balance on loan.
+
+ This function is here to simply have a different name for the 'fv'
+ function to not interfere with the 'fv' keyword argument within the 'ipmt'
+ function. It is the 'remaining balance on loan' which might be useful as
+ it's own function, but is easily calculated with the 'fv' function.
+ """
+ return fv(rate, (per - 1), pmt, pv, when)
+
+
+def ppmt(rate, per, nper, pv, fv=0, when='end'):
+ """Compute the payment against loan principle.
+
+ Parameters
+ ----------
+ rate : array_like
+ Rate of interest (per period)
+ per : array_like, int
+ Amount paid against the loan changes. The `per` is the period of
+ interest.
+ nper : array_like
+ Number of compounding periods
+ pv : array_like
+ Present value
+ fv : array_like, optional
+ Future value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}
+ When payments are due ('begin' (1) or 'end' (0))
+
+ See Also
+ --------
+ pmt, pv, ipmt
+
+ """
+ total = pmt(rate, nper, pv, fv, when)
+ return total - ipmt(rate, per, nper, pv, fv, when)
+
+
+def pv(rate, nper, pmt, fv=0, when='end'):
+ """Compute the present value.
+
+ Given:
+ * a future value, `fv`
+ * an interest `rate` compounded once per period, of which
+ there are
+ * `nper` total
+ * a (fixed) payment, `pmt`, paid either
+ * at the beginning (`when` = {'begin', 1}) or the end
+ (`when` = {'end', 0}) of each period
+
+ Return:
+ the value now
+
+ Parameters
+ ----------
+ rate : array_like
+ Rate of interest (per period)
+ nper : array_like
+ Number of compounding periods
+ pmt : array_like
+ Payment
+ fv : array_like, optional
+ Future value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
+ When payments are due ('begin' (1) or 'end' (0))
+
+ Returns
+ -------
+ out : ndarray, float
+ Present value of a series of payments or investments.
+
+ Notes
+ -----
+ The present value is computed by solving the equation::
+
+ fv +
+ pv*(1 + rate)**nper +
+ pmt*(1 + rate*when)/rate*((1 + rate)**nper - 1) = 0
+
+ or, when ``rate = 0``::
+
+ fv + pv + pmt * nper = 0
+
+ for `pv`, which is then returned.
+
+ References
+ ----------
+ .. [WRW] Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May).
+ Open Document Format for Office Applications (OpenDocument)v1.2,
+ Part 2: Recalculated Formula (OpenFormula) Format - Annotated Version,
+ Pre-Draft 12. Organization for the Advancement of Structured Information
+ Standards (OASIS). Billerica, MA, USA. [ODT Document].
+ Available:
+ http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula
+ OpenDocument-formula-20090508.odt
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import numpy_financial as npf
+
+ What is the present value (e.g., the initial investment)
+ of an investment that needs to total $15692.93
+ after 10 years of saving $100 every month? Assume the
+ interest rate is 5% (annually) compounded monthly.
+
+ >>> npf.pv(0.05/12, 10*12, -100, 15692.93)
+ -100.00067131625819
+
+ By convention, the negative sign represents cash flow out
+ (i.e., money not available today). Thus, to end up with
+ $15,692.93 in 10 years saving $100 a month at 5% annual
+ interest, one's initial deposit should also be $100.
+
+ If any input is array_like, ``pv`` returns an array of equal shape.
+ Let's compare different interest rates in the example above:
+
+ >>> a = np.array((0.05, 0.04, 0.03))/12
+ >>> npf.pv(a, 10*12, -100, 15692.93)
+ array([ -100.00067132, -649.26771385, -1273.78633713])
+
+ So, to end up with the same $15692.93 under the same $100 per month
+ "savings plan," for annual interest rates of 4% and 3%, one would
+ need initial investments of $649.27 and $1273.79, respectively.
+
+ """
+ when = _convert_when(when)
+ (rate, nper, pmt, fv, when) = map(np.asarray, [rate, nper, pmt, fv, when])
+ temp = (1 + rate) ** nper
+ fact = np.where(rate == 0, nper, (1 + rate * when) * (temp - 1) / rate)
+ return -(fv + pmt * fact) / temp
+
+
+# Computed with Sage
+# (y + (r + 1)^n*x + p*((r + 1)^n - 1)*(r*w + 1)/r)/(n*(r + 1)^(n - 1)*x -
+# p*((r + 1)^n - 1)*(r*w + 1)/r^2 + n*p*(r + 1)^(n - 1)*(r*w + 1)/r +
+# p*((r + 1)^n - 1)*w/r)
+
+
+def _g_div_gp(r, n, p, x, y, w):
+ # Evaluate g(r_n)/g'(r_n), where g =
+ # fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1)
+ t1 = (r + 1) ** n
+ t2 = (r + 1) ** (n - 1)
+ g = y + t1 * x + p * (t1 - 1) * (r * w + 1) / r
+ gp = (n * t2 * x
+ - p * (t1 - 1) * (r * w + 1) / (r ** 2)
+ + n * p * t2 * (r * w + 1) / r
+ + p * (t1 - 1) * w / r)
+ return g / gp
+
+
+# Use Newton's iteration until the change is less than 1e-6
+# for all values or a maximum of 100 iterations is reached.
+# Newton's rule is
+# r_{n+1} = r_{n} - g(r_n)/g'(r_n)
+# where
+# g(r) is the formula
+# g'(r) is the derivative with respect to r.
+def rate(
+ nper,
+ pmt,
+ pv,
+ fv,
+ when='end',
+ guess=None,
+ tol=None,
+ maxiter=100,
+ *,
+ raise_exceptions=False):
+ """Compute the rate of interest per period.
+
+ Parameters
+ ----------
+ nper : array_like
+ Number of compounding periods
+ pmt : array_like
+ Payment
+ pv : array_like
+ Present value
+ fv : array_like
+ Future value
+ when : {{'begin', 1}, {'end', 0}}, {string, int}, optional
+ When payments are due ('begin' (1) or 'end' (0))
+ guess : Number, optional
+ Starting guess for solving the rate of interest, default 0.1
+ tol : Number, optional
+ Required tolerance for the solution, default 1e-6
+ maxiter : int, optional
+ Maximum iterations in finding the solution
+ raise_exceptions: bool, optional
+ Flag to raise an exception when at least one of the rates
+ cannot be computed due to having reached the maximum number of
+ iterations (IterationsExceededException). Set to False as default,
+ thus returning NaNs for those rates.
+
+ Notes
+ -----
+ The rate of interest is computed by iteratively solving the
+ (non-linear) equation::
+
+ fv + pv*(1+rate)**nper + pmt*(1+rate*when)/rate * ((1+rate)**nper - 1) = 0
+
+ for ``rate``.
+
+ References
+ ----------
+ Wheeler, D. A., E. Rathke, and R. Weir (Eds.) (2009, May). Open Document
+ Format for Office Applications (OpenDocument)v1.2, Part 2: Recalculated
+ Formula (OpenFormula) Format - Annotated Version, Pre-Draft 12.
+ Organization for the Advancement of Structured Information Standards
+ (OASIS). Billerica, MA, USA. [ODT Document]. Available:
+ http://www.oasis-open.org/committees/documents.php?wg_abbrev=office-formula
+ OpenDocument-formula-20090508.odt
+
+ """
+ when = _convert_when(when)
+ default_type = Decimal if isinstance(pmt, Decimal) else float
+
+ # Handle casting defaults to Decimal if/when pmt is a Decimal and
+ # guess and/or tol are not given default values
+ if guess is None:
+ guess = default_type('0.1')
+
+ if tol is None:
+ tol = default_type('1e-6')
+
+ (nper, pmt, pv, fv, when) = map(np.asarray, [nper, pmt, pv, fv, when])
+
+ rn = guess
+ iterator = 0
+ close = False
+ while (iterator < maxiter) and not np.all(close):
+ rnp1 = rn - _g_div_gp(rn, nper, pmt, pv, fv, when)
+ diff = abs(rnp1 - rn)
+ close = diff < tol
+ iterator += 1
+ rn = rnp1
+
+ if not np.all(close):
+ if np.isscalar(rn):
+ if raise_exceptions:
+ raise IterationsExceededError('Maximum number of iterations exceeded.')
+ return default_type(np.nan)
+ else:
+ # Return nan's in array of the same shape as rn
+ # where the solution is not close to tol.
+ if raise_exceptions:
+ raise IterationsExceededError(f'Maximum iterations exceeded in '
+ f'{len(close) - close.sum()} rate(s).')
+ rn[~close] = np.nan
+ return rn
+
+
+def irr(values, *, guess=None, tol=1e-12, maxiter=100, raise_exceptions=False):
+ r"""Return the Internal Rate of Return (IRR).
+
+ This is the "average" periodically compounded rate of return
+ that gives a net present value of 0.0; for a more complete explanation,
+ see Notes below.
+
+ :class:`decimal.Decimal` type is not supported.
+
+ Parameters
+ ----------
+ values : array_like, shape(N,)
+ Input cash flows per time period. By convention, net "deposits"
+ are negative and net "withdrawals" are positive. Thus, for
+ example, at least the first element of `values`, which represents
+ the initial investment, will typically be negative.
+ guess : float, optional
+ Initial guess of the IRR for the iterative solver. If no guess is
+ given an heuristic is used to estimate the guess through the ratio of
+ positive to negative cash lows
+ tol : float, optional
+ Required tolerance to accept solution. Default is 1e-12.
+ maxiter : int, optional
+ Maximum iterations to perform in finding a solution. Default is 100.
+ raise_exceptions: bool, optional
+ Flag to raise an exception when the irr cannot be computed due to
+ either having all cashflows of the same sign (NoRealSolutionException) or
+ having reached the maximum number of iterations (IterationsExceededException).
+ Set to False as default, thus returning NaNs in the two previous
+ cases.
+
+ Returns
+ -------
+ out : float
+ Internal Rate of Return for periodic input values.
+
+ Notes
+ -----
+ The IRR is perhaps best understood through an example (illustrated
+ using np.irr in the Examples section below). Suppose one invests 100
+ units and then makes the following withdrawals at regular (fixed)
+ intervals: 39, 59, 55, 20. Assuming the ending value is 0, one's 100
+ unit investment yields 173 units; however, due to the combination of
+ compounding and the periodic withdrawals, the "average" rate of return
+ is neither simply 0.73/4 nor (1.73)^0.25-1. Rather, it is the solution
+ (for :math:`r`) of the equation:
+
+ .. math:: -100 + \\frac{39}{1+r} + \\frac{59}{(1+r)^2}
+ + \\frac{55}{(1+r)^3} + \\frac{20}{(1+r)^4} = 0
+
+ In general, for `values` :math:`= [v_0, v_1, ... v_M]`,
+ irr is the solution of the equation: [G]_
+
+ .. math:: \\sum_{t=0}^M{\\frac{v_t}{(1+irr)^{t}}} = 0
+
+ References
+ ----------
+ .. [G] L. J. Gitman, "Principles of Managerial Finance, Brief," 3rd ed.,
+ Addison-Wesley, 2003, pg. 348.
+
+ Examples
+ --------
+ >>> import numpy_financial as npf
+
+ >>> round(npf.irr([-100, 39, 59, 55, 20]), 5)
+ 0.28095
+ >>> round(npf.irr([-100, 0, 0, 74]), 5)
+ -0.0955
+ >>> round(npf.irr([-100, 100, 0, -7]), 5)
+ -0.0833
+ >>> round(npf.irr([-100, 100, 0, 7]), 5)
+ 0.06206
+ >>> round(npf.irr([-5, 10.5, 1, -8, 1]), 5)
+ 0.0886
+
+ """
+ values = np.atleast_1d(values)
+ if values.ndim != 1:
+ raise ValueError("Cashflows must be a rank-1 array")
+
+ # If all values are of the same sign no solution exists
+ # we don't perform any further calculations and exit early
+ same_sign = np.all(values > 0) if values[0] > 0 else np.all(values < 0)
+ if same_sign:
+ if raise_exceptions:
+ raise NoRealSolutionError('No real solution exists for IRR since all '
+ 'cashflows are of the same sign.')
+ return np.nan
+
+ # If no value is passed for `guess`, then make a heuristic estimate
+ if guess is None:
+ positive_cashflow = values > 0
+ inflow = values.sum(where=positive_cashflow)
+ outflow = -values.sum(where=~positive_cashflow)
+ guess = inflow / outflow - 1
+
+ # We aim to solve eirr such that NPV is exactly zero. This can be framed as
+ # simply finding the closest root of a polynomial to a given initial guess
+ # as follows:
+ # V0 V1 V2 V3
+ # NPV = ---------- + ---------- + ---------- + ---------- + ... = 0
+ # (1+eirr)^0 (1+eirr)^1 (1+eirr)^2 (1+eirr)^3
+ #
+ # by letting g = (1+eirr), we substitute to get
+ #
+ # NPV = V0 * 1/g^0 + V1 * 1/g^1 + V2 * 1/x^2 + V3 * 1/g^3 + ... = 0
+ #
+ # Multiplying by g^N this becomes
+ #
+ # V0 * g^N + V1 * g^{N-1} + V2 * g^{N-2} + V3 * g^{N-3} + ... = 0
+ #
+ # which we solve using Newton-Raphson and then reverse out the solution
+ # as eirr = g - 1 (if we are close enough to a solution)
+ npv_ = np.polynomial.Polynomial(values[::-1])
+ d_npv = npv_.deriv()
+ g = 1 + guess
+
+ for _ in range(maxiter):
+ delta = npv_(g) / d_npv(g)
+ if abs(delta) < tol:
+ return g - 1
+ g -= delta
+
+ if raise_exceptions:
+ raise IterationsExceededError('Maximum number of iterations exceeded.')
+
+ return np.nan
+
+
+def npv(rate, values):
+ r"""Return the NPV (Net Present Value) of a cash flow series.
+
+ Parameters
+ ----------
+ rate : scalar or array_like shape(K, )
+ The discount rate.
+ values : array_like, shape(M, ) or shape(M, N)
+ The values of the time series of cash flows. The (fixed) time
+ interval between cash flow "events" must be the same as that for
+ which `rate` is given (i.e., if `rate` is per year, then precisely
+ a year is understood to elapse between each cash flow event). By
+ convention, investments or "deposits" are negative, income or
+ "withdrawals" are positive; `values` must begin with the initial
+ investment, thus `values[0]` will typically be negative.
+
+ Returns
+ -------
+ out : float or array shape(K, M)
+ The NPV of the input cash flow series `values` at the discount
+ `rate`. `out` follows the ufunc convention of returning scalars
+ instead of single element arrays.
+
+ Warnings
+ --------
+ ``npv`` considers a series of cashflows starting in the present (t = 0).
+ NPV can also be defined with a series of future cashflows, paid at the
+ end, rather than the start, of each period. If future cashflows are used,
+ the first cashflow `values[0]` must be zeroed and added to the net
+ present value of the future cashflows. This is demonstrated in the
+ examples.
+
+ Notes
+ -----
+ Returns the result of: [G]_
+
+ .. math :: \\sum_{t=0}^{M-1}{\\frac{values_t}{(1+rate)^{t}}}
+
+ References
+ ----------
+ .. [G] L. J. Gitman, "Principles of Managerial Finance, Brief," 3rd ed.,
+ Addison-Wesley, 2003, pg. 346.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import numpy_financial as npf
+
+ Consider a potential project with an initial investment of $40 000 and
+ projected cashflows of $5 000, $8 000, $12 000 and $30 000 at the end of
+ each period discounted at a rate of 8% per period. To find the project's
+ net present value:
+
+ >>> rate, cashflows = 0.08, [-40_000, 5_000, 8_000, 12_000, 30_000]
+ >>> np.round(npf.npv(rate, cashflows), 5)
+ 3065.22267
+
+ It may be preferable to split the projected cashflow into an initial
+ investment and expected future cashflows. In this case, the value of
+ the initial cashflow is zero and the initial investment is later added
+ to the future cashflows net present value:
+
+ >>> initial_cashflow = cashflows[0]
+ >>> cashflows[0] = 0
+ >>> np.round(npf.npv(rate, cashflows) + initial_cashflow, 5)
+ 3065.22267
+
+ """
+ values = np.atleast_2d(values)
+ timestep_array = np.arange(0, values.shape[1])
+ npv = (values / (1 + rate) ** timestep_array).sum(axis=1)
+ try:
+ # If size of array is one, return scalar
+ return npv.item()
+ except ValueError:
+ # Otherwise, return entire array
+ return npv
+
+
+def mirr(values, finance_rate, reinvest_rate, *, raise_exceptions=False):
+ r"""
+ Return the Modified Internal Rate of Return (MIRR).
+
+ MIRR is a financial metric that takes into account both the cost of
+ the investment and the return on reinvested cash flows. It is useful
+ for evaluating the profitability of an investment with multiple cash
+ inflows and outflows.
+
+ Parameters
+ ----------
+ values : array_like
+ Cash flows, where the first value is considered a sunk cost at time zero.
+ It must contain at least one positive and one negative value.
+ finance_rate : scalar
+ Interest rate paid on the cash flows.
+ reinvest_rate : scalar
+ Interest rate received on the cash flows upon reinvestment.
+ raise_exceptions: bool, optional
+ Flag to raise an exception when the MIRR cannot be computed due to
+ having all cash flows of the same sign (NoRealSolutionException).
+ Set to False as default,thus returning NaNs in the previous case.
+
+ Returns
+ -------
+ out : float
+ Modified internal rate of return
+
+ Notes
+ -----
+ The MIRR formula is as follows:
+
+ .. math::
+
+ MIRR =
+ \\left( \\frac{{FV_{positive}}}{{PV_{negative}}} \\right)^{\\frac{{1}}{{n-1}}}
+ * (1+r) - 1
+
+ where:
+ - \(FV_{positive}\) is the future value of positive cash flows,
+ - \(PV_{negative}\) is the present value of negative cash flows,
+ - \(n\) is the number of periods.
+ - \(r\) is the reinvestment rate.
+
+ Examples
+ --------
+ >>> import numpy_financial as npf
+
+ Consider a project with an initial investment of -$100
+ and projected cash flows of $50, -$60, and $70 at the end of each period.
+ The project has a finance rate of 10% and a reinvestment rate of 12%.
+
+ >>> npf.mirr([-100, 50, -60, 70], 0.10, 0.12)
+ -0.03909366594356467
+
+ Now, let's consider the scenario where all cash flows are negative.
+
+ >>> npf.mirr([-100, -50, -60, -70], 0.10, 0.12)
+ nan
+
+ Finally, let's explore the situation where all cash flows are positive,
+ and the `raise_exceptions` parameter is set to True.
+
+ >>> npf.mirr([
+ ... 100, 50, 60, 70],
+ ... 0.10, 0.12,
+ ... raise_exceptions=True
+ ... ) #doctest: +NORMALIZE_WHITESPACE
+ Traceback (most recent call last):
+ ...
+ numpy_financial._financial.NoRealSolutionError:
+ No real solution exists for MIRR since all cashflows are of the same sign.
+ """
+ values = np.asarray(values)
+ n = values.size
+
+ # Without this explicit cast the 1/(n - 1) computation below
+ # becomes a float, which causes TypeError when using Decimal
+ # values.
+ if isinstance(finance_rate, Decimal):
+ n = Decimal(n)
+
+ pos = values > 0
+ neg = values < 0
+ if not (pos.any() and neg.any()):
+ if raise_exceptions:
+ raise NoRealSolutionError('No real solution exists for MIRR since'
+ ' all cashflows are of the same sign.')
+ return np.nan
+ numer = np.abs(npv(reinvest_rate, values * pos))
+ denom = np.abs(npv(finance_rate, values * neg))
+ return (numer / denom) ** (1 / (n - 1)) * (1 + reinvest_rate) - 1
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/pyproject.toml b/tasks/tasksmith-a7e859277e7a/tests/source/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..6dedf1e64e01e4fd18e2d3852d86eecab1de031a
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/pyproject.toml
@@ -0,0 +1,64 @@
+[build-system]
+requires = ["poetry-core"]
+build-backend = "poetry.core.masonry.api"
+
+
+[tool.poetry]
+name = "numpy-financial"
+version = "2.0.0"
+description = "Simple financial functions"
+license = "BSD-3-Clause"
+authors = ["Travis E. Oliphant et al."]
+maintainers = ["Numpy Financial Developers "]
+readme = "README.md"
+homepage = "https://numpy.org/numpy-financial/latest/"
+repository = "https://github.com/numpy/numpy-financial"
+documentation = "https://numpy.org/numpy-financial/latest/#functions"
+classifiers = [
+ "Development Status :: 5 - Production/Stable",
+ "Intended Audience :: Developers",
+ "Intended Audience :: Financial and Insurance Industry",
+ "License :: OSI Approved :: BSD License",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3 :: Only",
+ "Topic :: Software Development",
+ "Topic :: Office/Business :: Financial :: Accounting",
+ "Topic :: Office/Business :: Financial :: Investment",
+ "Topic :: Office/Business :: Financial :: Spreadsheet",
+ "Operating System :: Microsoft :: Windows",
+ "Operating System :: POSIX",
+ "Operating System :: Unix",
+ "Operating System :: MacOS",
+]
+packages = [{include = "numpy_financial"}]
+
+[tool.poetry.dependencies]
+python = "^3.10"
+numpy = "^1.23"
+numba = "^0.59.1"
+
+[tool.poetry.group.test.dependencies]
+pytest = "^8.0"
+hypothesis = {extras = ["numpy"], version = "^6.99.11"}
+pytest-xdist = {extras = ["psutil"], version = "^3.5.0"}
+
+
+[tool.poetry.group.docs.dependencies]
+sphinx = "^7.0"
+numpydoc = "^1.5"
+pydata-sphinx-theme = "^0.14.3"
+myst-parser = "^2.0.0"
+
+
+
+[tool.poetry.group.lint.dependencies]
+ruff = "^0.3"
+
+
+[tool.poetry.group.bench.dependencies]
+asv = "^0.6"
+
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/tests/__init__.py b/tasks/tasksmith-a7e859277e7a/tests/source/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/tests/tasksmith_behavior.py b/tasks/tasksmith-a7e859277e7a/tests/source/tests/tasksmith_behavior.py
new file mode 100644
index 0000000000000000000000000000000000000000..f68327599417eb3f23767a7396314e6a5cffff5b
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/tests/tasksmith_behavior.py
@@ -0,0 +1,46 @@
+import numpy
+import numpy_financial as npf
+import pytest
+
+
+def test_npv_broadcasting_shape_and_values():
+ """Multiple rates x multiple cashflows produce (n_rates, n_cashflows) array with correct values."""
+ rates = [0.00, 0.05, 0.10]
+ cashflows = [[-4_000, 500, 800], [-5_000, 600, 900]]
+ result = npf.npv(rates, cashflows)
+ assert result.shape == (3, 2)
+ expected = numpy.array([
+ [-2700.0, -3500.0],
+ [-2798.19, -3612.24],
+ [-2884.3, -3710.74],
+ ])
+ numpy.testing.assert_allclose(result, expected, rtol=1e-3)
+
+
+def test_npv_single_rate_multiple_cashflows_returns_1d():
+ """Scalar rate with 2-D cashflows returns a 1-D array of length n_cashflows."""
+ cashflows = [[-4_000, 500, 800], [-5_000, 600, 900]]
+ result = npf.npv(0.05, cashflows)
+ assert result.ndim == 1
+ assert result.shape == (2,)
+ numpy.testing.assert_allclose(result[0], npf.npv(0.05, [-4_000, 500, 800]), rtol=1e-5)
+ numpy.testing.assert_allclose(result[1], npf.npv(0.05, [-5_000, 600, 900]), rtol=1e-5)
+
+
+def test_npv_multiple_rates_single_cashflow_returns_1d():
+ """1-D rates with a single 1-D cashflow returns a 1-D array of length n_rates."""
+ rates = [0.0, 0.05, 0.10]
+ cashflow = [-1000, 500, 600]
+ result = npf.npv(rates, cashflow)
+ assert result.ndim == 1
+ assert result.shape == (3,)
+ for i, r in enumerate(rates):
+ numpy.testing.assert_allclose(result[i], npf.npv(r, cashflow), rtol=1e-5)
+
+
+def test_npv_scalar_rate_1d_cashflow_returns_scalar():
+ """Existing behavior: scalar rate + 1-D cashflow returns a Python scalar."""
+ result = npf.npv(0.05, [-15000.0, 1500.0, 2500.0, 3500.0, 4500.0, 6000.0])
+ # Must be a scalar (not an ndarray)
+ assert numpy.ndim(result) == 0
+ numpy.testing.assert_allclose(result, 122.89, rtol=1e-2)
diff --git a/tasks/tasksmith-a7e859277e7a/tests/source/tests/test_financial.py b/tasks/tasksmith-a7e859277e7a/tests/source/tests/test_financial.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d8ecec29fd2646fd53e0cb16566fcdaff9a910f
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/source/tests/test_financial.py
@@ -0,0 +1,871 @@
+import math
+from decimal import Decimal
+
+import hypothesis.extra.numpy as npst
+import hypothesis.strategies as st
+
+# Don't use 'import numpy as np', to avoid accidentally testing
+# the versions in numpy instead of numpy_financial.
+import numpy
+import pytest
+from hypothesis import given, settings
+from numpy.testing import (
+ assert_,
+ assert_allclose,
+ assert_equal,
+ assert_raises,
+)
+
+import numpy_financial as npf
+
+
+def float_dtype():
+ return npst.floating_dtypes(sizes=[32, 64], endianness="<")
+
+
+def int_dtype():
+ return npst.integer_dtypes(sizes=[32, 64], endianness="<")
+
+
+def uint_dtype():
+ return npst.unsigned_integer_dtypes(sizes=[32, 64], endianness="<")
+
+
+real_scalar_dtypes = st.one_of(float_dtype(), int_dtype(), uint_dtype())
+
+
+cashflow_array_strategy = npst.arrays(
+ dtype=real_scalar_dtypes,
+ shape=npst.array_shapes(min_dims=1, max_dims=2, min_side=0, max_side=25),
+)
+cashflow_list_strategy = cashflow_array_strategy.map(lambda x: x.tolist())
+
+cashflow_array_like_strategy = st.one_of(
+ cashflow_array_strategy,
+ cashflow_list_strategy,
+)
+
+short_scalar_array = npst.arrays(
+ dtype=real_scalar_dtypes,
+ shape=npst.array_shapes(min_dims=0, max_dims=1, min_side=0, max_side=5),
+)
+
+
+def assert_decimal_close(actual, expected, tol=Decimal("1e-7")):
+ # Check if both actual and expected are iterable (like arrays)
+ if hasattr(actual, "__iter__") and hasattr(expected, "__iter__"):
+ for a, e in zip(actual, expected):
+ assert abs(a - e) <= tol
+ else:
+ # For single value comparisons
+ assert abs(actual - expected) <= tol
+
+
+class TestFinancial(object):
+ def test_when(self):
+ # begin
+ assert_equal(
+ npf.rate(10, 20, -3500, 10000, 1), npf.rate(10, 20, -3500, 10000, "begin")
+ )
+ # end
+ assert_equal(
+ npf.rate(10, 20, -3500, 10000), npf.rate(10, 20, -3500, 10000, "end")
+ )
+ assert_equal(
+ npf.rate(10, 20, -3500, 10000, 0), npf.rate(10, 20, -3500, 10000, "end")
+ )
+
+ # begin
+ assert_equal(npf.pv(0.07, 20, 12000, 0, 1), npf.pv(0.07, 20, 12000, 0, "begin"))
+ # end
+ assert_equal(npf.pv(0.07, 20, 12000, 0), npf.pv(0.07, 20, 12000, 0, "end"))
+ assert_equal(npf.pv(0.07, 20, 12000, 0, 0), npf.pv(0.07, 20, 12000, 0, "end"))
+
+ # begin
+ assert_equal(
+ npf.pmt(0.08 / 12, 5 * 12, 15000.0, 0, 1),
+ npf.pmt(0.08 / 12, 5 * 12, 15000.0, 0, "begin"),
+ )
+ # end
+ assert_equal(
+ npf.pmt(0.08 / 12, 5 * 12, 15000.0, 0),
+ npf.pmt(0.08 / 12, 5 * 12, 15000.0, 0, "end"),
+ )
+ assert_equal(
+ npf.pmt(0.08 / 12, 5 * 12, 15000.0, 0, 0),
+ npf.pmt(0.08 / 12, 5 * 12, 15000.0, 0, "end"),
+ )
+
+ # begin
+ assert_equal(
+ npf.nper(0.075, -2000, 0, 100000.0, 1),
+ npf.nper(0.075, -2000, 0, 100000.0, "begin"),
+ )
+ # end
+ assert_equal(
+ npf.nper(0.075, -2000, 0, 100000.0),
+ npf.nper(0.075, -2000, 0, 100000.0, "end"),
+ )
+ assert_equal(
+ npf.nper(0.075, -2000, 0, 100000.0, 0),
+ npf.nper(0.075, -2000, 0, 100000.0, "end"),
+ )
+
+ def test_decimal_with_when(self):
+ """
+ Test that decimals are still supported if the when argument is passed
+ """
+ # begin
+ assert_equal(
+ npf.rate(
+ Decimal("10"),
+ Decimal("20"),
+ Decimal("-3500"),
+ Decimal("10000"),
+ Decimal("1"),
+ ),
+ npf.rate(
+ Decimal("10"),
+ Decimal("20"),
+ Decimal("-3500"),
+ Decimal("10000"),
+ "begin",
+ ),
+ )
+ # end
+ assert_equal(
+ npf.rate(Decimal("10"), Decimal("20"), Decimal("-3500"), Decimal("10000")),
+ npf.rate(
+ Decimal("10"), Decimal("20"), Decimal("-3500"), Decimal("10000"), "end"
+ ),
+ )
+ assert_equal(
+ npf.rate(
+ Decimal("10"),
+ Decimal("20"),
+ Decimal("-3500"),
+ Decimal("10000"),
+ Decimal("0"),
+ ),
+ npf.rate(
+ Decimal("10"), Decimal("20"), Decimal("-3500"), Decimal("10000"), "end"
+ ),
+ )
+
+ # begin
+ assert_equal(
+ npf.pv(
+ Decimal("0.07"),
+ Decimal("20"),
+ Decimal("12000"),
+ Decimal("0"),
+ Decimal("1"),
+ ),
+ npf.pv(
+ Decimal("0.07"), Decimal("20"), Decimal("12000"), Decimal("0"), "begin"
+ ),
+ )
+ # end
+ assert_equal(
+ npf.pv(Decimal("0.07"), Decimal("20"), Decimal("12000"), Decimal("0")),
+ npf.pv(
+ Decimal("0.07"), Decimal("20"), Decimal("12000"), Decimal("0"), "end"
+ ),
+ )
+ assert_equal(
+ npf.pv(
+ Decimal("0.07"),
+ Decimal("20"),
+ Decimal("12000"),
+ Decimal("0"),
+ Decimal("0"),
+ ),
+ npf.pv(
+ Decimal("0.07"), Decimal("20"), Decimal("12000"), Decimal("0"), "end"
+ ),
+ )
+
+
+class TestPV:
+ def test_pv(self):
+ assert_allclose(npf.pv(0.07, 20, 12000, 0), -127128.17, rtol=1e-2)
+
+ def test_pv_decimal(self):
+ assert_equal(
+ npf.pv(Decimal("0.07"), Decimal("20"), Decimal("12000"), Decimal("0")),
+ Decimal("-127128.1709461939327295222005"),
+ )
+
+
+class TestRate:
+ def test_rate(self):
+ assert_allclose(npf.rate(10, 0, -3500, 10000), 0.1107, rtol=1e-4)
+
+ @pytest.mark.parametrize("number_type", [Decimal, float])
+ @pytest.mark.parametrize("when", [0, 1, "end", "begin"])
+ def test_rate_with_infeasible_solution(self, number_type, when):
+ """
+ Test when no feasible rate can be found.
+
+ Rate will return NaN, if the Newton Raphson method cannot find a
+ feasible rate within the required tolerance or number of iterations.
+ This can occur if both `pmt` and `pv` have the same sign, as it is
+ impossible to repay a loan by making further withdrawls.
+ """
+ result = npf.rate(
+ number_type(12.0),
+ number_type(400.0),
+ number_type(10000.0),
+ number_type(5000.0),
+ when=when,
+ )
+ is_nan = Decimal.is_nan if number_type == Decimal else numpy.isnan
+ assert is_nan(result)
+
+ def test_rate_decimal(self):
+ rate = npf.rate(Decimal("10"), Decimal("0"), Decimal("-3500"), Decimal("10000"))
+ assert_equal(Decimal("0.1106908537142689284704528100"), rate)
+
+ def test_gh48(self):
+ """
+ Test the correct result is returned with only infeasible solutions
+ converted to nan.
+ """
+ des = [-0.39920185, -0.02305873, -0.41818459, 0.26513414, numpy.nan]
+ nper = 2
+ pmt = 0
+ pv = [-593.06, -4725.38, -662.05, -428.78, -13.65]
+ fv = [214.07, 4509.97, 224.11, 686.29, -329.67]
+ actual = npf.rate(nper, pmt, pv, fv)
+ assert_allclose(actual, des)
+
+ def test_rate_maximum_iterations_exception_scalar(self):
+ # Test that if the maximum number of iterations is reached,
+ # then npf.rate returns IterationsExceededException
+ # when raise_exceptions is set to True.
+ assert_raises(
+ npf.IterationsExceededError,
+ npf.rate,
+ Decimal(12.0),
+ Decimal(400.0),
+ Decimal(10000.0),
+ Decimal(5000.0),
+ raise_exceptions=True,
+ )
+
+ def test_rate_maximum_iterations_exception_array(self):
+ # Test that if the maximum number of iterations is reached in at least
+ # one rate, then npf.rate returns IterationsExceededException
+ # when raise_exceptions is set to True.
+ nper = 2
+ pmt = 0
+ pv = [-593.06, -4725.38, -662.05, -428.78, -13.65]
+ fv = [214.07, 4509.97, 224.11, 686.29, -329.67]
+ assert_raises(
+ npf.IterationsExceededError,
+ npf.rate,
+ nper,
+ pmt,
+ pv,
+ fv,
+ raise_exceptions=True,
+ )
+
+
+class TestNpv:
+ def test_npv(self):
+ assert_allclose(
+ npf.npv(0.05, [-15000.0, 1500.0, 2500.0, 3500.0, 4500.0, 6000.0]),
+ 122.89,
+ rtol=1e-2,
+ )
+
+ @given(rates=short_scalar_array, values=cashflow_array_strategy)
+ @settings(deadline=None)
+ def test_fuzz(self, rates, values):
+ npf.npv(rates, values)
+
+ @pytest.mark.parametrize("rates", ([[1, 2, 3]], numpy.empty(shape=(1, 1, 1))))
+ def test_invalid_rates_shape(self, rates):
+ cashflows = [1, 2, 3]
+ with pytest.raises(ValueError):
+ npf.npv(rates, cashflows)
+
+ @pytest.mark.parametrize("cf", ([[[1, 2, 3]]], numpy.empty(shape=(1, 1, 1))))
+ def test_invalid_cashflows_shape(self, cf):
+ rates = [1, 2, 3]
+ with pytest.raises(ValueError):
+ npf.npv(rates, cf)
+
+ @pytest.mark.parametrize("rate", (-1, -1.0))
+ def test_rate_of_negative_one_returns_nan(self, rate):
+ cashflow = numpy.arange(5)
+ assert numpy.isnan(npf.npv(rate, cashflow))
+
+
+class TestPmt:
+ def test_pmt_simple(self):
+ res = npf.pmt(0.08 / 12, 5 * 12, 15000)
+ tgt = -304.145914
+ assert_allclose(res, tgt)
+
+ def test_pmt_zero_rate(self):
+ # Test the edge case where rate == 0.0
+ res = npf.pmt(0.0, 5 * 12, 15000)
+ tgt = -250.0
+ assert_allclose(res, tgt)
+
+ def test_pmt_broadcast(self):
+ # Test the case where we use broadcast and
+ # the arguments passed in are arrays.
+ res = npf.pmt([[0.0, 0.8], [0.3, 0.8]], [12, 3], [2000, 20000])
+ tgt = numpy.array([[-166.66667, -19311.258], [-626.90814, -19311.258]])
+ assert_allclose(res, tgt)
+
+ def test_pmt_decimal_simple(self):
+ res = npf.pmt(Decimal("0.08") / Decimal("12"), 5 * 12, 15000)
+ tgt = Decimal("-304.1459143262052370338701494")
+ assert_equal(res, tgt)
+
+ def test_pmt_decimal_zero_rate(self):
+ # Test the edge case where rate == 0.0
+ res = npf.pmt(Decimal("0"), Decimal("60"), Decimal("15000"))
+ tgt = -250
+ assert_equal(res, tgt)
+
+ def test_pmt_decimal_broadcast(self):
+ # Test the case where we use broadcast and
+ # the arguments passed in are arrays.
+ res = npf.pmt(
+ [[Decimal("0"), Decimal("0.8")], [Decimal("0.3"), Decimal("0.8")]],
+ [Decimal("12"), Decimal("3")],
+ [Decimal("2000"), Decimal("20000")],
+ )
+ tgt = numpy.array(
+ [
+ [
+ Decimal("-166.6666666666666666666666667"),
+ Decimal("-19311.25827814569536423841060"),
+ ],
+ [
+ Decimal("-626.9081401700757748402586600"),
+ Decimal("-19311.25827814569536423841060"),
+ ],
+ ]
+ )
+
+ # Cannot use the `assert_allclose` because it uses isfinite under
+ # the covers which does not support the Decimal type
+ # See issue: https://github.com/numpy/numpy/issues/9954
+ assert_equal(res[0][0], tgt[0][0])
+ assert_equal(res[0][1], tgt[0][1])
+ assert_equal(res[1][0], tgt[1][0])
+ assert_equal(res[1][1], tgt[1][1])
+
+
+class TestMirr:
+ @pytest.mark.parametrize(
+ "values,finance_rate,reinvest_rate,expected",
+ [
+ (
+ [-4500, -800, 800, 800, 600, 600, 800, 800, 700, 3000],
+ 0.08,
+ 0.055,
+ 0.0666,
+ ),
+ ([-120000, 39000, 30000, 21000, 37000, 46000], 0.10, 0.12, 0.126094),
+ ([100, 200, -50, 300, -200], 0.05, 0.06, 0.3428),
+ ([39000, 30000, 21000, 37000, 46000], 0.10, 0.12, None),
+ ],
+ )
+ def test_mirr(self, values, finance_rate, reinvest_rate, expected):
+ result = npf.mirr(values, finance_rate, reinvest_rate)
+
+ if expected:
+ decimal_part_len = len(str(expected).split(".")[1])
+ difference = 10**-decimal_part_len
+ assert_allclose(result, expected, atol=difference)
+ else:
+ assert_(numpy.isnan(result))
+
+ def test_mirr_no_real_solution_exception(self):
+ # Test that if there is no solution because all the cashflows
+ # have the same sign, then npf.mirr returns NoRealSolutionException
+ # when raise_exceptions is set to True.
+ val = [39000, 30000, 21000, 37000, 46000]
+
+ with pytest.raises(npf.NoRealSolutionError):
+ npf.mirr(val, 0.10, 0.12, raise_exceptions=True)
+
+
+class TestNper:
+ def test_basic_values(self):
+ assert_allclose(
+ npf.nper([0, 0.075], -2000, 0, 100000),
+ [50, 21.544944], # Computed using Google Sheet's NPER
+ rtol=1e-5,
+ )
+
+ def test_gh_18(self):
+ with numpy.errstate(divide="raise"):
+ assert_allclose(
+ npf.nper(0.1, 0, -500, 1500),
+ 11.52670461, # Computed using Google Sheet's NPER
+ )
+
+ def test_infinite_payments(self):
+ with numpy.errstate(divide="raise"):
+ result = npf.nper(0, -0.0, 1000)
+ assert_(result == numpy.inf)
+
+ def test_no_interest(self):
+ assert_(npf.nper(0, -100, 1000) == 10)
+
+ def test_broadcast(self):
+ assert_allclose(
+ npf.nper(0.075, -2000, 0, 100000.0, [0, 1]), [21.5449442, 20.76156441], 4
+ )
+
+
+class TestPpmt:
+ def test_float(self):
+ assert_allclose(npf.ppmt(0.1 / 12, 1, 60, 55000), -710.25, rtol=1e-4)
+
+ def test_decimal(self):
+ result = npf.ppmt(
+ Decimal("0.1") / Decimal("12"),
+ Decimal("1"),
+ Decimal("60"),
+ Decimal("55000"),
+ )
+ assert_equal(
+ result,
+ Decimal("-710.2541257864217612489830917"),
+ )
+
+ @pytest.mark.parametrize("when", [1, "begin"])
+ def test_when_is_begin(self, when):
+ assert_allclose(
+ npf.ppmt(0.1 / 12, 1, 60, 55000, 0, when),
+ -1158.929712, # Computed using Google Sheet's PPMT
+ rtol=1e-9,
+ )
+
+ @pytest.mark.parametrize("when", [None, 0, "end"])
+ def test_when_is_end(self, when):
+ args = (0.1 / 12, 1, 60, 55000, 0)
+ result = npf.ppmt(*args) if when is None else npf.ppmt(*args, when)
+ assert_allclose(
+ result,
+ -710.254126, # Computed using Google Sheet's PPMT
+ rtol=1e-9,
+ )
+
+ @pytest.mark.parametrize("when", [Decimal("1"), "begin"])
+ def test_when_is_begin_decimal(self, when):
+ result = npf.ppmt(
+ Decimal("0.08") / Decimal("12"),
+ Decimal("1"),
+ Decimal("60"),
+ Decimal("15000."),
+ Decimal("0"),
+ when,
+ )
+ assert_decimal_close(
+ result,
+ Decimal("-302.131703"), # Computed using Google Sheet's PPMT
+ tol=1e-5,
+ )
+
+ @pytest.mark.parametrize("when", [None, Decimal("0"), "end"])
+ def test_when_is_end_decimal(self, when):
+ args = (
+ Decimal("0.08") / Decimal("12"),
+ Decimal("1"),
+ Decimal("60"),
+ Decimal("15000."),
+ Decimal("0"),
+ )
+ result = npf.ppmt(*args) if when is None else npf.ppmt(*args, when)
+ assert_decimal_close(
+ result,
+ Decimal("-204.145914"), # Computed using Google Sheet's PPMT
+ tol=1e-5,
+ )
+
+ @pytest.mark.parametrize(
+ "args",
+ [
+ (0.1 / 12, 0, 60, 15000),
+ (Decimal("0.012"), Decimal("0"), Decimal("60"), Decimal("15000")),
+ ],
+ )
+ def test_invalid_per(self, args):
+ # Note that math.isnan() handles Decimal NaN correctly.
+ assert math.isnan(npf.ppmt(*args))
+
+ @pytest.mark.parametrize(
+ "when, desired",
+ [
+ (
+ None,
+ [-75.62318601, -76.25337923, -76.88882405, -77.52956425],
+ ),
+ (
+ [0, 1, "end", "begin"],
+ [-75.62318601, -75.62318601, -76.88882405, -76.88882405],
+ ),
+ ],
+ )
+ def test_broadcast(self, when, desired):
+ args = (0.1 / 12, numpy.arange(1, 5), 24, 2000, 0)
+ result = npf.ppmt(*args) if when is None else npf.ppmt(*args, when)
+ assert_allclose(result, desired, rtol=1e-5)
+
+ @pytest.mark.parametrize(
+ "when, desired",
+ [
+ (
+ None,
+ [
+ Decimal("-75.62318601"),
+ Decimal("-76.25337923"),
+ Decimal("-76.88882405"),
+ Decimal("-77.52956425"),
+ ],
+ ),
+ (
+ [Decimal("0"), Decimal("1"), "end", "begin"],
+ [
+ Decimal("-75.62318601"),
+ Decimal("-75.62318601"),
+ Decimal("-76.88882405"),
+ Decimal("-76.88882405"),
+ ],
+ ),
+ ],
+ )
+ def test_broadcast_decimal(self, when, desired):
+ args = (
+ Decimal("0.1") / Decimal("12"),
+ numpy.arange(1, 5),
+ Decimal("24"),
+ Decimal("2000"),
+ Decimal("0"),
+ )
+ result = npf.ppmt(*args) if when is None else npf.ppmt(*args, when)
+ assert_decimal_close(result, desired, tol=1e-8)
+
+
+class TestIpmt:
+ def test_float(self):
+ assert_allclose(
+ npf.ipmt(0.1 / 12, 1, 24, 2000),
+ -16.666667, # Computed using Google Sheet's IPMT
+ rtol=1e-6,
+ )
+
+ def test_decimal(self):
+ result = npf.ipmt(Decimal("0.1") / Decimal("12"), 1, 24, 2000)
+ assert result == Decimal("-16.66666666666666666666666667")
+
+ @pytest.mark.parametrize("when", [1, "begin"])
+ def test_when_is_begin(self, when):
+ assert npf.ipmt(0.1 / 12, 1, 24, 2000, 0, when) == 0
+
+ @pytest.mark.parametrize("when", [None, 0, "end"])
+ def test_when_is_end(self, when):
+ if when is None:
+ result = npf.ipmt(0.1 / 12, 1, 24, 2000)
+ else:
+ result = npf.ipmt(0.1 / 12, 1, 24, 2000, 0, when)
+ assert_allclose(result, -16.666667, rtol=1e-6)
+
+ @pytest.mark.parametrize("when", [Decimal("1"), "begin"])
+ def test_when_is_begin_decimal(self, when):
+ result = npf.ipmt(
+ Decimal("0.1") / Decimal("12"),
+ Decimal("1"),
+ Decimal("24"),
+ Decimal("2000"),
+ Decimal("0"),
+ when,
+ )
+ assert result == 0
+
+ @pytest.mark.parametrize("when", [None, Decimal("0"), "end"])
+ def test_when_is_end_decimal(self, when):
+ # Computed using Google Sheet's IPMT
+ desired = Decimal("-16.666667")
+ args = (
+ Decimal("0.1") / Decimal("12"),
+ Decimal("1"),
+ Decimal("24"),
+ Decimal("2000"),
+ Decimal("0"),
+ )
+ result = npf.ipmt(*args) if when is None else npf.ipmt(*args, when)
+ assert_decimal_close(result, desired, tol=1e-5)
+
+ @pytest.mark.parametrize(
+ "per, desired",
+ [
+ (0, numpy.nan),
+ (1, 0),
+ (2, -594.107158),
+ (3, -592.971592),
+ ],
+ )
+ def test_gh_17(self, per, desired):
+ # All desired results computed using Google Sheet's IPMT
+ rate = 0.001988079518355057
+ result = npf.ipmt(rate, per, 360, 300000, when="begin")
+ if numpy.isnan(desired):
+ assert numpy.isnan(result)
+ else:
+ assert_allclose(result, desired, rtol=1e-6)
+
+ def test_broadcasting(self):
+ desired = [numpy.nan, -16.66666667, -16.03647345, -15.40102862, -14.76028842]
+ assert_allclose(
+ npf.ipmt(0.1 / 12, numpy.arange(5), 24, 2000),
+ desired,
+ rtol=1e-6,
+ )
+
+ def test_decimal_broadcasting(self):
+ desired = [
+ Decimal("-16.66666667"),
+ Decimal("-16.03647345"),
+ Decimal("-15.40102862"),
+ Decimal("-14.76028842"),
+ ]
+ result = npf.ipmt(
+ Decimal("0.1") / Decimal("12"),
+ list(range(1, 5)),
+ Decimal("24"),
+ Decimal("2000"),
+ )
+ assert_decimal_close(result, desired, tol=1e-4)
+
+ def test_0d_inputs(self):
+ args = (0.1 / 12, 1, 24, 2000)
+ # Scalar inputs should return a scalar.
+ assert numpy.isscalar(npf.ipmt(*args))
+ args = (numpy.array(args[0]),) + args[1:]
+ # 0d array inputs should return a scalar.
+ assert numpy.isscalar(npf.ipmt(*args))
+
+
+class TestFv:
+ def test_float(self):
+ assert_allclose(
+ npf.fv(0.075, 20, -2000, 0, 0),
+ 86609.362673042924,
+ rtol=1e-10,
+ )
+
+ def test_decimal(self):
+ assert_decimal_close(
+ npf.fv(Decimal("0.075"), Decimal("20"), Decimal("-2000"), 0, 0),
+ Decimal("86609.36267304300040536731624"),
+ tol=1e-10,
+ )
+
+ @pytest.mark.parametrize("when", [1, "begin"])
+ def test_when_is_begin_float(self, when):
+ assert_allclose(
+ npf.fv(0.075, 20, -2000, 0, when),
+ 93105.064874, # Computed using Google Sheet's FV
+ rtol=1e-10,
+ )
+
+ @pytest.mark.parametrize("when", [Decimal("1"), "begin"])
+ def test_when_is_begin_decimal(self, when):
+ result = npf.fv(
+ Decimal("0.075"),
+ Decimal("20"),
+ Decimal("-2000"),
+ Decimal("0"),
+ when,
+ )
+ assert_decimal_close(result, Decimal("93105.064874"), tol=5)
+
+ @pytest.mark.parametrize("when", [None, 0, "end"])
+ def test_when_is_end_float(self, when):
+ args = (0.075, 20, -2000, 0)
+ result = npf.fv(*args) if when is None else npf.fv(*args, when)
+ assert_allclose(
+ result,
+ 86609.362673, # Computed using Google Sheet's FV
+ rtol=1e-10,
+ )
+
+ @pytest.mark.parametrize("when", [None, Decimal("0"), "end"])
+ def test_when_is_end_decimal(self, when):
+ args = (
+ Decimal("0.075"),
+ Decimal("20"),
+ Decimal("-2000"),
+ Decimal("0"),
+ )
+ result = npf.fv(*args) if when is None else npf.fv(*args, when)
+ assert_decimal_close(result, Decimal("86609.362673"), tol=5)
+
+ def test_broadcast(self):
+ result = npf.fv([[0.1], [0.2]], 5, 100, 0, [0, 1])
+ # All values computed using Google Sheet's FV
+ desired = [[-610.510000, -671.561000], [-744.160000, -892.992000]]
+ assert_allclose(result, desired, rtol=1e-10)
+
+ def test_some_rates_zero(self):
+ # Check that the logical indexing is working correctly.
+ assert_allclose(
+ npf.fv([0, 0.1], 5, 100, 0),
+ [-500, -610.51], # Computed using Google Sheet's FV
+ rtol=1e-10,
+ )
+
+
+class TestIrr:
+ def test_npv_irr_congruence(self):
+ # IRR is defined as the rate required for the present value of
+ # a series of cashflows to be zero, so we should have
+ #
+ # NPV(IRR(x), x) = 0.
+ cashflows = numpy.array([-40000, 5000, 8000, 12000, 30000])
+ assert_allclose(
+ npf.npv(npf.irr(cashflows), cashflows),
+ 0,
+ atol=1e-10,
+ rtol=0,
+ )
+
+ @pytest.mark.parametrize(
+ "v, desired",
+ [
+ ([-150000, 15000, 25000, 35000, 45000, 60000], 0.0524),
+ ([-100, 0, 0, 74], -0.0955),
+ ([-100, 39, 59, 55, 20], 0.28095),
+ ([-100, 100, 0, -7], -0.0833),
+ ([-100, 100, 0, 7], 0.06206),
+ ([-5, 10.5, 1, -8, 1], 0.0886),
+ ],
+ )
+ def test_basic_values(self, v, desired):
+ assert_allclose(npf.irr(v), desired, rtol=1e-2)
+
+ def test_trailing_zeros(self):
+ assert_allclose(
+ npf.irr([-5, 10.5, 1, -8, 1, 0, 0, 0]),
+ 0.0886,
+ rtol=1e-2,
+ )
+
+ @pytest.mark.parametrize(
+ "v",
+ [
+ (1, 2, 3),
+ (-1, -2, -3),
+ ],
+ )
+ def test_numpy_gh_6744(self, v):
+ # Test that if there is no solution then npf.irr returns nan.
+ assert numpy.isnan(npf.irr(v))
+
+ def test_gh_15(self):
+ v = [
+ -3000.0,
+ 2.3926932267015667e-07,
+ 4.1672087103345505e-16,
+ 5.3965110036378706e-25,
+ 5.1962551071806174e-34,
+ 3.7202955645436402e-43,
+ 1.9804961711632469e-52,
+ 7.8393517651814181e-62,
+ 2.3072565113911438e-71,
+ 5.0491839233308912e-81,
+ 8.2159177668499263e-91,
+ 9.9403244366963527e-101,
+ 8.942410813633967e-111,
+ 5.9816122646481191e-121,
+ 2.9750309031844241e-131,
+ 1.1002067043497954e-141,
+ 3.0252876563518021e-152,
+ 6.1854121948207909e-163,
+ 9.4032980015353301e-174,
+ 1.0629218520017728e-184,
+ 8.9337141847171845e-196,
+ 5.5830607698467935e-207,
+ 2.5943122036622652e-218,
+ 8.9635842466507006e-230,
+ 2.3027710094332358e-241,
+ 4.3987510596745562e-253,
+ 6.2476630372575209e-265,
+ 6.598046841695288e-277,
+ 5.1811095266842017e-289,
+ 3.0250999925830644e-301,
+ 1.3133070599585015e-313,
+ ]
+ result = npf.irr(v)
+ assert numpy.isfinite(result)
+ # Very rough approximation taken from the issue.
+ desired = -0.9999999990596069
+ assert_allclose(result, desired, rtol=1e-9)
+
+ def test_gh_39(self):
+ cashflows = numpy.array(
+ [
+ -217500.0,
+ -217500.0,
+ 108466.80462450592,
+ 101129.96439328062,
+ 93793.12416205535,
+ 86456.28393083003,
+ 79119.44369960476,
+ 71782.60346837944,
+ 64445.76323715414,
+ 57108.92300592884,
+ 49772.08277470355,
+ 42435.24254347826,
+ 35098.40231225296,
+ 27761.56208102766,
+ 20424.721849802358,
+ 13087.88161857707,
+ 5751.041387351768,
+ -1585.7988438735192,
+ -8922.639075098821,
+ -16259.479306324123,
+ -23596.31953754941,
+ -30933.159768774713,
+ -38270.0,
+ -45606.8402312253,
+ -52943.680462450604,
+ -60280.520693675906,
+ -67617.36092490121,
+ ]
+ )
+ assert_allclose(npf.irr(cashflows), 0.12)
+
+ def test_gh_44(self):
+ # "true" value as calculated by Google sheets
+ cf = [-1678.87, 771.96, 1814.05, 3520.30, 3552.95, 3584.99, 4789.91, -1]
+ assert_allclose(npf.irr(cf), 1.00426, rtol=1e-4)
+
+ def test_irr_no_real_solution_exception(self):
+ # Test that if there is no solution because all the cashflows
+ # have the same sign, then npf.irr returns NoRealSolutionException
+ # when raise_exceptions is set to True.
+ cashflows = numpy.array([40000, 5000, 8000, 12000, 30000])
+
+ with pytest.raises(npf.NoRealSolutionError):
+ npf.irr(cashflows, raise_exceptions=True)
+
+ def test_irr_maximum_iterations_exception(self):
+ # Test that if the maximum number of iterations is reached,
+ # then npf.irr returns IterationsExceededException
+ # when raise_exceptions is set to True.
+ cashflows = numpy.array([-40000, 5000, 8000, 12000, 30000])
+
+ with pytest.raises(npf.IterationsExceededError):
+ npf.irr(cashflows, maxiter=1, raise_exceptions=True)
diff --git a/tasks/tasksmith-a7e859277e7a/tests/test.sh b/tasks/tasksmith-a7e859277e7a/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..80254c0fc64954034729dff8cdf6a0745fe24aa2
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+set -eu
+exec /usr/local/bin/python -B -I -S /tests/grade.py
diff --git a/tasks/tasksmith-a7e859277e7a/tests/test_driver.py b/tasks/tasksmith-a7e859277e7a/tests/test_driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0b8bb331c4499e300b92f0e022ff6a723a4a562
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/test_driver.py
@@ -0,0 +1,41 @@
+"""Private pytest entry point with a bounded framework-tampering check.
+
+The host still owns reward parsing. This guard detects replacement or in-place
+editing of unittest assertions, a demonstrated attack against repository tests.
+It does not claim to isolate arbitrary test and solution code in one interpreter.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+
+
+def run(arguments: list[str]) -> int:
+ import pytest
+
+ # Capture before pytest imports any repository modules. Retain code objects
+ # too: an attacker can mutate function.__code__ without replacing a method.
+ original = {
+ name: (value, getattr(value, "__code__", None))
+ for name, value in vars(unittest.TestCase).items()
+ if name.startswith("assert") and callable(value)
+ }
+ case = unittest.TestCase
+ # The harness supplies selectors and reporting explicitly. Repository addopts
+ # often enable optional coverage/report plugins that are intentionally not
+ # auto-loaded in this isolated verifier; they are not test dependencies.
+ code = int(pytest.main(["-o", "addopts=", *arguments]))
+ changed = []
+ for name, (method, implementation) in original.items():
+ current = getattr(case, name, None)
+ if current is not method or getattr(current, "__code__", None) is not implementation:
+ changed.append(name)
+ if unittest.TestCase is not case or changed:
+ sys.stderr.write("Verifier framework was modified: " + ", ".join(changed) + "\n")
+ return 254
+ return code
+
+
+if __name__ == "__main__":
+ raise SystemExit(run(sys.argv[1:]))
diff --git a/tasks/tasksmith-a7e859277e7a/tests/test_results.py b/tasks/tasksmith-a7e859277e7a/tests/test_results.py
new file mode 100644
index 0000000000000000000000000000000000000000..05ce2c730e38e02bad44f2344e88e5f1cb02cb8d
--- /dev/null
+++ b/tasks/tasksmith-a7e859277e7a/tests/test_results.py
@@ -0,0 +1,65 @@
+"""Strict test evidence used by repository recipes and their exported verifiers."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from xml.etree import ElementTree
+
+
+@dataclass(frozen=True)
+class TestResults:
+ __test__ = False
+ statuses: dict[str, str]
+ returncode: int
+
+ @property
+ def passed(self) -> set[str]:
+ return {name for name, status in self.statuses.items() if status == "passed"}
+
+
+def parse_junit(text: str, *, returncode: int) -> TestResults:
+ if " dict[str, list[str]]:
+ if healthy.returncode != 0 or not healthy.passed:
+ raise ValueError("Reference must execute successfully with passing tests")
+ if healthy.statuses.keys() != defective.statuses.keys():
+ raise ValueError("Mutation changed test collection; contrast is not comparable")
+ failing = sorted(
+ name for name in healthy.passed if defective.statuses[name] in {"failed", "error"}
+ )
+ if not failing or defective.returncode != 1:
+ raise ValueError("No intended fail-to-pass contrast")
+ return {"FAIL_TO_PASS": failing, "PASS_TO_PASS": sorted(healthy.passed - set(failing))}
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/Dockerfile b/tasks/tasksmith-a9cb6b87c28d/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..8d808eea89f6fcd68b6398cfc8b7168bd7cd7323
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/Dockerfile
@@ -0,0 +1,9 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir setuptools==84.2.1 ply==3.11 python-dateutil==2.9.0.post0 six==1.16.0 pytest==9.0.3
+COPY source /workspace
+RUN python -m pip install --no-cache-dir --no-deps -e .
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
+RUN apt-get update && apt-get install -y --no-install-recommends tmux && rm -rf /var/lib/apt/lists/*
+RUN useradd -m learner && chown -R learner:learner /workspace
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/.gitattributes b/tasks/tasksmith-a9cb6b87c28d/environment/source/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..d958a5de51d19738f7aa76832cae7e77ce47bcfc
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/.gitattributes
@@ -0,0 +1,22 @@
+* text=auto
+* text eol=lf
+
+# Source files
+# ============
+*.pxd text diff=python eol=lf
+*.py text diff=python eol=lf
+*.py3 text diff=python eol=lf
+*.pyw text diff=python eol=lf
+*.pyx text diff=python eol=lf
+*.md text eol=lf
+*.txt text eol=lf
+*.yml text eol=lf
+
+# Binary files
+# ============
+*.db binary
+*.p binary
+*.pkl binary
+*.pyc binary
+*.pyd binary
+*.pyo binary
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/.gitignore b/tasks/tasksmith-a9cb6b87c28d/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..9e1907b0170e1ebb529c185094d17b7e45aa4db2
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/.gitignore
@@ -0,0 +1,100 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+pip-wheel-metadata/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+.hypothesis/
+.pytest_cache/
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+.python-version
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# ply
+*.dbg
+*.out
+*.tab
+*parsetab.py
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/Dockerfile b/tasks/tasksmith-a9cb6b87c28d/environment/source/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f2f520314cb79b146aafd3b39c29a3c545d36506
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/Dockerfile
@@ -0,0 +1,8 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir setuptools==84.2.1 ply==3.11 python-dateutil==2.9.0.post0 six==1.16.0 pytest==9.0.3
+COPY . /workspace
+RUN python -m pip install --no-cache-dir --no-deps -e .
+RUN rm -rf /workspace/.git /root/.cache/pip
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/LICENSE b/tasks/tasksmith-a9cb6b87c28d/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..784067a36810e86f20841e6469cf51822ec62ba7
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/LICENSE
@@ -0,0 +1,21 @@
+(The MIT License)
+
+Copyright (c) AidHound
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/README.md b/tasks/tasksmith-a9cb6b87c28d/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..4b8d9b0eb2b388e19817cf0867843683b38b55c3
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/README.md
@@ -0,0 +1,71 @@
+# hotxlfp
+
+[](https://app.travis-ci.com/github/aidhound/hotxlfp) [](https://codecov.io/gh/aidhound/hotxlfp)
+
+hotxlfp intends to be a python version of the javascript [handsontable excel formula parser](https://github.com/handsontable/formula-parser) differences are acceptable to make it more pythonic or the function implementations more correct.
+
+# Install
+
+You can install using pip
+
+ pip install hotxlfp
+
+# Usage
+
+## Create a Parser
+
+ import hotxlfp
+ p = hotxlfp.Parser()
+
+## Parse excel formulas
+
+ p.parse('SUM(1,2,3)') # returns {'result': 6, 'error': None}
+
+It's also fine to use semi-colons as separators (they're used by excel depending on your locale)
+
+ p.parse('SUM(1;2;3)') # returns {'result': 6, 'error': None}
+
+## Custom functions
+
+Say you have a function called triple:
+
+ def triple(x):
+ return x*3
+
+You can teach the parser to use it with set_function
+
+ p.set_function('TRIPLE', triple)
+ p.parse('TRIPLE(2)') # returns {'result': 6, 'error': None}
+
+## Variables
+
+You can also set variables that you can then use in your formulas
+
+ p.set_variable('foo', 33)
+ p.parse('foo/3') # returns {'result': 11.0, 'error': None}
+
+# Contributing
+
+Fork the project
+
+## Installing Dependencies
+
+Depends on ply and python-dateutil.
+
+To install dependencies automatically using pip run:
+
+ pip install -r requirements.txt
+
+## Testing
+
+ python setup.py test
+
+## Coverage
+
+ coverage run --source hotxlfp setup.py test
+
+## Update SUPPORTED_FORMULAS.md
+
+Inside the project directory run:
+
+ python -m "scripts.update_supported_formulas"
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/PKG-INFO b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/PKG-INFO
new file mode 100644
index 0000000000000000000000000000000000000000..e8fa15068e9110a0df1f135def1e26e5203ddbfd
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/PKG-INFO
@@ -0,0 +1,174 @@
+Metadata-Version: 2.4
+Name: hotxlfp
+Version: 0.0.16
+Home-page: https://github.com/aidhound/hotxlfp
+Download-URL: https://github.com/aidhound/hotxlfp/archive/0.0.16.tar.gz
+Author: Leonel Câmara
+Author-email: leonelcamara@gmail.com
+License: MIT
+Keywords: excel,formula,parser
+Classifier: Development Status :: 3 - Alpha
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: ply
+Requires-Dist: python-dateutil
+Dynamic: author
+Dynamic: author-email
+Dynamic: classifier
+Dynamic: description
+Dynamic: description-content-type
+Dynamic: download-url
+Dynamic: home-page
+Dynamic: keywords
+Dynamic: license
+Dynamic: license-file
+Dynamic: requires-dist
+
+# hotxlfp
+
+
+
+
+
+hotxlfp intends to be a python version of the javascript [handsontable excel formula parser](https://github.com/handsontable/formula-parser) differences are acceptable to make it more pythonic or the function implementations more correct.
+
+
+
+# Install
+
+
+
+You can install using pip
+
+
+
+ pip install hotxlfp
+
+
+
+# Usage
+
+
+
+## Create a Parser
+
+
+
+ import hotxlfp
+
+ p = hotxlfp.Parser()
+
+
+
+## Parse excel formulas
+
+
+
+ p.parse('SUM(1,2,3)') # returns {'result': 6, 'error': None}
+
+
+
+It's also fine to use semi-colons as separators (they're used by excel depending on your locale)
+
+
+
+ p.parse('SUM(1;2;3)') # returns {'result': 6, 'error': None}
+
+
+
+## Custom functions
+
+
+
+Say you have a function called triple:
+
+
+
+ def triple(x):
+
+ return x*3
+
+
+
+You can teach the parser to use it with set_function
+
+
+
+ p.set_function('TRIPLE', triple)
+
+ p.parse('TRIPLE(2)') # returns {'result': 6, 'error': None}
+
+
+
+## Variables
+
+
+
+You can also set variables that you can then use in your formulas
+
+
+
+ p.set_variable('foo', 33)
+
+ p.parse('foo/3') # returns {'result': 11.0, 'error': None}
+
+
+
+# Contributing
+
+
+
+Fork the project
+
+
+
+## Installing Dependencies
+
+
+
+Depends on ply and python-dateutil.
+
+
+
+To install dependencies automatically using pip run:
+
+
+
+ pip install -r requirements.txt
+
+
+
+## Testing
+
+
+
+ python setup.py test
+
+
+
+## Coverage
+
+
+
+ coverage run --source hotxlfp setup.py test
+
+
+
+## Update SUPPORTED_FORMULAS.md
+
+
+
+Inside the project directory run:
+
+
+
+ python -m "scripts.update_supported_formulas"
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/SOURCES.txt b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/SOURCES.txt
new file mode 100644
index 0000000000000000000000000000000000000000..2ae76ed658f493ff63b967f4b6ba46a772c9692a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/SOURCES.txt
@@ -0,0 +1,50 @@
+LICENSE
+README.md
+setup.py
+hotxlfp/__init__.py
+hotxlfp/parser.py
+hotxlfp/tinyemitter.py
+hotxlfp.egg-info/PKG-INFO
+hotxlfp.egg-info/SOURCES.txt
+hotxlfp.egg-info/dependency_links.txt
+hotxlfp.egg-info/requires.txt
+hotxlfp.egg-info/top_level.txt
+hotxlfp/_compat/__init__.py
+hotxlfp/_compat/py3/__init__.py
+hotxlfp/_compat/py3/statistics.py
+hotxlfp/formulas/__init__.py
+hotxlfp/formulas/dateandtime.py
+hotxlfp/formulas/engineering.py
+hotxlfp/formulas/error.py
+hotxlfp/formulas/financial.py
+hotxlfp/formulas/information.py
+hotxlfp/formulas/logic.py
+hotxlfp/formulas/lookupandreference.py
+hotxlfp/formulas/mathtrig.py
+hotxlfp/formulas/operators.py
+hotxlfp/formulas/statistical.py
+hotxlfp/formulas/text.py
+hotxlfp/formulas/utils.py
+hotxlfp/grammarparser/__init__.py
+hotxlfp/grammarparser/lexer.py
+hotxlfp/grammarparser/parser.py
+hotxlfp/helper/__init__.py
+hotxlfp/helper/cell.py
+hotxlfp/helper/number.py
+tests/test_dateandtime.py
+tests/test_engineering.py
+tests/test_error.py
+tests/test_financial.py
+tests/test_helper.py
+tests/test_information.py
+tests/test_lexer.py
+tests/test_logic.py
+tests/test_lookupandreference.py
+tests/test_mathtrig.py
+tests/test_operators.py
+tests/test_parser.py
+tests/test_statistical.py
+tests/test_text.py
+tests/test_tinyemitter.py
+tests/test_tinyexcel.py
+tests/test_vars.py
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/dependency_links.txt b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/dependency_links.txt
new file mode 100644
index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/requires.txt b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/requires.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7b5737b809e138abf31ea4e428a167277dfd312a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/requires.txt
@@ -0,0 +1,2 @@
+ply
+python-dateutil
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/top_level.txt b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0de34161ab7e8edaefb08c848207ba687efdcc55
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp.egg-info/top_level.txt
@@ -0,0 +1 @@
+hotxlfp
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/__init__.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a3855a18ab02d153f7aade1197db525b6246c4f
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/__init__.py
@@ -0,0 +1 @@
+from .parser import Parser
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/_compat/__init__.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/_compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ed03b4f947c2749b7e351b25b5fc40939561b01
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/_compat/__init__.py
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+import sys
+
+PY2 = sys.version_info[0] == 2
+
+if PY2:
+ from .py3 import statistics
+ number_types = (int, long, float, complex)
+ integer_types = (int, long)
+ string_types = (str, unicode)
+else:
+ import statistics
+ number_types = (int, float, complex)
+ integer_types = (int,)
+ string_types = (str,)
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/_compat/py3/__init__.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/_compat/py3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/_compat/py3/statistics.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/_compat/py3/statistics.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4b7688bbfd11a5df86965f5318cb7818f05d4e2
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/_compat/py3/statistics.py
@@ -0,0 +1,975 @@
+# -*- coding: utf-8 -*-
+# This was literally copied from python 3 source and made compatible with py2
+# See: https://github.com/python/cpython/blob/master/LICENSE
+"""
+Basic statistics module.
+
+This module provides functions for calculating statistics of data, including
+averages, variance, and standard deviation.
+
+Calculating averages
+--------------------
+
+================== =============================================
+Function Description
+================== =============================================
+mean Arithmetic mean (average) of data.
+geometric_mean Geometric mean of data.
+harmonic_mean Harmonic mean of data.
+median Median (middle value) of data.
+median_low Low median of data.
+median_high High median of data.
+median_grouped Median, or 50th percentile, of grouped data.
+mode Mode (most common value) of data.
+multimode List of modes (most common values of data).
+================== =============================================
+
+Calculate the arithmetic mean ("the average") of data:
+
+>>> mean([-1.0, 2.5, 3.25, 5.75])
+2.625
+
+
+Calculate the standard median of discrete data:
+
+>>> median([2, 3, 4, 5])
+3.5
+
+
+Calculate the median, or 50th percentile, of data grouped into class intervals
+centred on the data values provided. E.g. if your data points are rounded to
+the nearest whole number:
+
+>>> median_grouped([2, 2, 3, 3, 3, 4]) #doctest: +ELLIPSIS
+2.8333333333...
+
+This should be interpreted in this way: you have two data points in the class
+interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in
+the class interval 3.5-4.5. The median of these data points is 2.8333...
+
+
+Calculating variability or spread
+---------------------------------
+
+================== =============================================
+Function Description
+================== =============================================
+pvariance Population variance of data.
+variance Sample variance of data.
+pstdev Population standard deviation of data.
+stdev Sample standard deviation of data.
+================== =============================================
+
+Calculate the standard deviation of sample data:
+
+>>> stdev([2.5, 3.25, 5.5, 11.25, 11.75]) #doctest: +ELLIPSIS
+4.38961843444...
+
+If you have previously calculated the mean, you can pass it as the optional
+second argument to the four "spread" functions to avoid recalculating it:
+
+>>> data = [1, 2, 2, 4, 4, 4, 5, 6]
+>>> mu = mean(data)
+>>> pvariance(data, mu)
+2.5
+
+
+Exceptions
+----------
+
+A single exception is defined: StatisticsError is a subclass of ValueError.
+
+"""
+from __future__ import division
+
+__all__ = [ 'StatisticsError', 'NormalDist',
+ 'pstdev', 'pvariance', 'stdev', 'variance',
+ 'median', 'median_low', 'median_high', 'median_grouped',
+ 'mean', 'mode', 'multimode', 'harmonic_mean', 'fmean',
+ 'geometric_mean',
+ ]
+
+import math
+import numbers
+import random
+
+from fractions import Fraction
+from decimal import Decimal
+from itertools import groupby
+from bisect import bisect_left, bisect_right
+from math import hypot, sqrt, fabs, exp, erf, log, fsum
+from operator import itemgetter
+from collections import Counter
+
+tau = 6.283185307179586
+# === Exceptions ===
+
+class StatisticsError(ValueError):
+ pass
+
+
+# === Private utilities ===
+
+def _sum(data, start=0):
+ """_sum(data [, start]) -> (type, sum, count)
+
+ Return a high-precision sum of the given numeric data as a fraction,
+ together with the type to be converted to and the count of items.
+
+ If optional argument ``start`` is given, it is added to the total.
+ If ``data`` is empty, ``start`` (defaulting to 0) is returned.
+
+
+ Examples
+ --------
+
+ >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75)
+ (, Fraction(11, 1), 5)
+
+ Some sources of round-off error will be avoided:
+
+ # Built-in sum returns zero.
+ >>> _sum([1e50, 1, -1e50] * 1000)
+ (, Fraction(1000, 1), 3000)
+
+ Fractions and Decimals are also supported:
+
+ >>> from fractions import Fraction as F
+ >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)])
+ (, Fraction(63, 20), 4)
+
+ >>> from decimal import Decimal as D
+ >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")]
+ >>> _sum(data)
+ (, Fraction(6963, 10000), 4)
+
+ Mixed types are currently treated as an error, except that int is
+ allowed.
+ """
+ count = 0
+ n, d = _exact_ratio(start)
+ partials = {d: n}
+ partials_get = partials.get
+ T = _coerce(int, type(start))
+ for typ, values in groupby(data, type):
+ T = _coerce(T, typ) # or raise TypeError
+ for n,d in map(_exact_ratio, values):
+ count += 1
+ partials[d] = partials_get(d, 0) + n
+ if None in partials:
+ # The sum will be a NAN or INF. We can ignore all the finite
+ # partials, and just look at this special one.
+ total = partials[None]
+ assert not _isfinite(total)
+ else:
+ # Sum all the partial sums using builtin sum.
+ # FIXME is this faster if we sum them in order of the denominator?
+ total = sum(Fraction(n, d) for d, n in sorted(partials.items()))
+ return (T, total, count)
+
+
+def _isfinite(x):
+ try:
+ return x.is_finite() # Likely a Decimal.
+ except AttributeError:
+ return math.isfinite(x) # Coerces to float first.
+
+
+def _coerce(T, S):
+ """Coerce types T and S to a common type, or raise TypeError.
+
+ Coercion rules are currently an implementation detail. See the CoerceTest
+ test class in test_statistics for details.
+ """
+ # See http://bugs.python.org/issue24068.
+ assert T is not bool, "initial type T is bool"
+ # If the types are the same, no need to coerce anything. Put this
+ # first, so that the usual case (no coercion needed) happens as soon
+ # as possible.
+ if T is S: return T
+ # Mixed int & other coerce to the other type.
+ if S is int or S is bool: return T
+ if T is int: return S
+ # If one is a (strict) subclass of the other, coerce to the subclass.
+ if issubclass(S, T): return S
+ if issubclass(T, S): return T
+ # Ints coerce to the other type.
+ if issubclass(T, int): return S
+ if issubclass(S, int): return T
+ # Mixed fraction & float coerces to float (or float subclass).
+ if issubclass(T, Fraction) and issubclass(S, float):
+ return S
+ if issubclass(T, float) and issubclass(S, Fraction):
+ return T
+ # Any other combination is disallowed.
+ msg = "don't know how to coerce %s and %s"
+ raise TypeError(msg % (T.__name__, S.__name__))
+
+
+def _exact_ratio(x):
+ """Return Real number x to exact (numerator, denominator) pair.
+
+ >>> _exact_ratio(0.25)
+ (1, 4)
+
+ x is expected to be an int, Fraction, Decimal or float.
+ """
+ try:
+ # Optimise the common case of floats. We expect that the most often
+ # used numeric type will be builtin floats, so try to make this as
+ # fast as possible.
+ if type(x) is float or type(x) is Decimal:
+ return x.as_integer_ratio()
+ try:
+ # x may be an int, Fraction, or Integral ABC.
+ return (x.numerator, x.denominator)
+ except AttributeError:
+ try:
+ # x may be a float or Decimal subclass.
+ return x.as_integer_ratio()
+ except AttributeError:
+ # Just give up?
+ pass
+ except (OverflowError, ValueError):
+ # float NAN or INF.
+ assert not _isfinite(x)
+ return (x, None)
+ msg = "can't convert type '{}' to numerator/denominator"
+ raise TypeError(msg.format(type(x).__name__))
+
+
+def _convert(value, T):
+ """Convert value to given numeric type T."""
+ if type(value) is T:
+ # This covers the cases where T is Fraction, or where value is
+ # a NAN or INF (Decimal or float).
+ return value
+ if issubclass(T, int) and value.denominator != 1:
+ T = float
+ try:
+ # FIXME: what do we do if this overflows?
+ return T(value)
+ except TypeError:
+ if issubclass(T, Decimal):
+ return T(value.numerator)/T(value.denominator)
+ else:
+ raise
+
+
+def _find_lteq(a, x):
+ 'Locate the leftmost value exactly equal to x'
+ i = bisect_left(a, x)
+ if i != len(a) and a[i] == x:
+ return i
+ raise ValueError
+
+
+def _find_rteq(a, l, x):
+ 'Locate the rightmost value exactly equal to x'
+ i = bisect_right(a, x, lo=l)
+ if i != (len(a)+1) and a[i-1] == x:
+ return i-1
+ raise ValueError
+
+
+def _fail_neg(values, errmsg='negative value'):
+ """Iterate over values, failing if any are less than zero."""
+ for x in values:
+ if x < 0:
+ raise StatisticsError(errmsg)
+ yield x
+
+
+# === Measures of central tendency (averages) ===
+
+def mean(data):
+ """Return the sample arithmetic mean of data.
+
+ >>> mean([1, 2, 3, 4, 4])
+ 2.8
+
+ >>> from fractions import Fraction as F
+ >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
+ Fraction(13, 21)
+
+ >>> from decimal import Decimal as D
+ >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
+ Decimal('0.5625')
+
+ If ``data`` is empty, StatisticsError will be raised.
+ """
+ if iter(data) is data:
+ data = list(data)
+ n = len(data)
+ if n < 1:
+ raise StatisticsError('mean requires at least one data point')
+ T, total, count = _sum(data)
+ assert count == n
+ return _convert(total/n, T)
+
+def fmean(data):
+ """ Convert data to floats and compute the arithmetic mean.
+
+ This runs faster than the mean() function and it always returns a float.
+ The result is highly accurate but not as perfect as mean().
+ If the input dataset is empty, it raises a StatisticsError.
+
+ >>> fmean([3.5, 4.0, 5.25])
+ 4.25
+
+ """
+ try:
+ n = len(data)
+ except TypeError:
+ # Handle iterators that do not define __len__().
+ ndic = {'n': 0} # this was just n = 0
+ def count(x): # and in this function we had nonlocal n
+ ndic['n'] += 1
+ return x
+ total = fsum(map(count, data))
+ n = ndic['n']
+ else:
+ total = fsum(data)
+ try:
+ return total / n
+ except ZeroDivisionError:
+ raise StatisticsError('fmean requires at least one data point')
+
+def geometric_mean(data):
+ """Convert data to floats and compute the geometric mean.
+
+ Raises a StatisticsError if the input dataset is empty,
+ if it contains a zero, or if it contains a negative value.
+
+ No special efforts are made to achieve exact results.
+ (However, this may change in the future.)
+
+ >>> round(geometric_mean([54, 24, 36]), 9)
+ 36.0
+ """
+ try:
+ return exp(fmean(map(log, data)))
+ except ValueError:
+ raise StatisticsError('geometric mean requires a non-empty dataset '
+ ' containing positive numbers')
+
+def harmonic_mean(data):
+ """Return the harmonic mean of data.
+
+ The harmonic mean, sometimes called the subcontrary mean, is the
+ reciprocal of the arithmetic mean of the reciprocals of the data,
+ and is often appropriate when averaging quantities which are rates
+ or ratios, for example speeds. Example:
+
+ Suppose an investor purchases an equal value of shares in each of
+ three companies, with P/E (price/earning) ratios of 2.5, 3 and 10.
+ What is the average P/E ratio for the investor's portfolio?
+
+ >>> harmonic_mean([2.5, 3, 10]) # For an equal investment portfolio.
+ 3.6
+
+ Using the arithmetic mean would give an average of about 5.167, which
+ is too high.
+
+ If ``data`` is empty, or any element is less than zero,
+ ``harmonic_mean`` will raise ``StatisticsError``.
+ """
+ # For a justification for using harmonic mean for P/E ratios, see
+ # http://fixthepitch.pellucid.com/comps-analysis-the-missing-harmony-of-summary-statistics/
+ # http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2621087
+ if iter(data) is data:
+ data = list(data)
+ errmsg = 'harmonic mean does not support negative values'
+ n = len(data)
+ if n < 1:
+ raise StatisticsError('harmonic_mean requires at least one data point')
+ elif n == 1:
+ x = data[0]
+ if isinstance(x, (numbers.Real, Decimal)):
+ if x < 0:
+ raise StatisticsError(errmsg)
+ return x
+ else:
+ raise TypeError('unsupported type')
+ try:
+ T, total, count = _sum(1/x for x in _fail_neg(data, errmsg))
+ except ZeroDivisionError:
+ return 0
+ assert count == n
+ return _convert(n/total, T)
+
+
+# FIXME: investigate ways to calculate medians without sorting? Quickselect?
+def median(data):
+ """Return the median (middle value) of numeric data.
+
+ When the number of data points is odd, return the middle data point.
+ When the number of data points is even, the median is interpolated by
+ taking the average of the two middle values:
+
+ >>> median([1, 3, 5])
+ 3
+ >>> median([1, 3, 5, 7])
+ 4.0
+
+ """
+ data = sorted(data)
+ n = len(data)
+ if n == 0:
+ raise StatisticsError("no median for empty data")
+ if n%2 == 1:
+ return data[n//2]
+ else:
+ i = n//2
+ return (data[i - 1] + data[i])/2
+
+
+def median_low(data):
+ """Return the low median of numeric data.
+
+ When the number of data points is odd, the middle value is returned.
+ When it is even, the smaller of the two middle values is returned.
+
+ >>> median_low([1, 3, 5])
+ 3
+ >>> median_low([1, 3, 5, 7])
+ 3
+
+ """
+ data = sorted(data)
+ n = len(data)
+ if n == 0:
+ raise StatisticsError("no median for empty data")
+ if n%2 == 1:
+ return data[n//2]
+ else:
+ return data[n//2 - 1]
+
+
+def median_high(data):
+ """Return the high median of data.
+
+ When the number of data points is odd, the middle value is returned.
+ When it is even, the larger of the two middle values is returned.
+
+ >>> median_high([1, 3, 5])
+ 3
+ >>> median_high([1, 3, 5, 7])
+ 5
+
+ """
+ data = sorted(data)
+ n = len(data)
+ if n == 0:
+ raise StatisticsError("no median for empty data")
+ return data[n//2]
+
+
+def median_grouped(data, interval=1):
+ """Return the 50th percentile (median) of grouped continuous data.
+
+ >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
+ 3.7
+ >>> median_grouped([52, 52, 53, 54])
+ 52.5
+
+ This calculates the median as the 50th percentile, and should be
+ used when your data is continuous and grouped. In the above example,
+ the values 1, 2, 3, etc. actually represent the midpoint of classes
+ 0.5-1.5, 1.5-2.5, 2.5-3.5, etc. The middle value falls somewhere in
+ class 3.5-4.5, and interpolation is used to estimate it.
+
+ Optional argument ``interval`` represents the class interval, and
+ defaults to 1. Changing the class interval naturally will change the
+ interpolated 50th percentile value:
+
+ >>> median_grouped([1, 3, 3, 5, 7], interval=1)
+ 3.25
+ >>> median_grouped([1, 3, 3, 5, 7], interval=2)
+ 3.5
+
+ This function does not check whether the data points are at least
+ ``interval`` apart.
+ """
+ data = sorted(data)
+ n = len(data)
+ if n == 0:
+ raise StatisticsError("no median for empty data")
+ elif n == 1:
+ return data[0]
+ # Find the value at the midpoint. Remember this corresponds to the
+ # centre of the class interval.
+ x = data[n//2]
+ for obj in (x, interval):
+ if isinstance(obj, (str, bytes)):
+ raise TypeError('expected number but got %r' % obj)
+ try:
+ L = x - interval/2 # The lower limit of the median interval.
+ except TypeError:
+ # Mixed type. For now we just coerce to float.
+ L = float(x) - float(interval)/2
+
+ # Uses bisection search to search for x in data with log(n) time complexity
+ # Find the position of leftmost occurrence of x in data
+ l1 = _find_lteq(data, x)
+ # Find the position of rightmost occurrence of x in data[l1...len(data)]
+ # Assuming always l1 <= l2
+ l2 = _find_rteq(data, l1, x)
+ cf = l1
+ f = l2 - l1 + 1
+ return L + interval*(n/2 - cf)/f
+
+
+def mode(data):
+ """Return the most common data point from discrete or nominal data.
+
+ ``mode`` assumes discrete data, and returns a single value. This is the
+ standard treatment of the mode as commonly taught in schools:
+
+ >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
+ 3
+
+ This also works with nominal (non-numeric) data:
+
+ >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
+ 'red'
+
+ If there are multiple modes, return the first one encountered.
+
+ >>> mode(['red', 'red', 'green', 'blue', 'blue'])
+ 'red'
+
+ If *data* is empty, ``mode``, raises StatisticsError.
+
+ """
+ data = iter(data)
+ try:
+ return Counter(data).most_common(1)[0][0]
+ except IndexError:
+ raise StatisticsError('no mode for empty data')
+
+
+def multimode(data):
+ """ Return a list of the most frequently occurring values.
+
+ Will return more than one result if there are multiple modes
+ or an empty list if *data* is empty.
+
+ >>> multimode('aabbbbbbbbcc')
+ ['b']
+ >>> multimode('aabbbbccddddeeffffgg')
+ ['b', 'd', 'f']
+ >>> multimode('')
+ []
+
+ """
+ counts = Counter(iter(data)).most_common()
+ maxcount, mode_items = next(groupby(counts, key=itemgetter(1)), (0, []))
+ return list(map(itemgetter(0), mode_items))
+
+
+# === Measures of spread ===
+
+# See http://mathworld.wolfram.com/Variance.html
+# http://mathworld.wolfram.com/SampleVariance.html
+# http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
+#
+# Under no circumstances use the so-called "computational formula for
+# variance", as that is only suitable for hand calculations with a small
+# amount of low-precision data. It has terrible numeric properties.
+#
+# See a comparison of three computational methods here:
+# http://www.johndcook.com/blog/2008/09/26/comparing-three-methods-of-computing-standard-deviation/
+
+def _ss(data, c=None):
+ """Return sum of square deviations of sequence data.
+
+ If ``c`` is None, the mean is calculated in one pass, and the deviations
+ from the mean are calculated in a second pass. Otherwise, deviations are
+ calculated from ``c`` as given. Use the second case with care, as it can
+ lead to garbage results.
+ """
+ if c is None:
+ c = mean(data)
+ T, total, count = _sum((x-c)**2 for x in data)
+ # The following sum should mathematically equal zero, but due to rounding
+ # error may not.
+ U, total2, count2 = _sum((x-c) for x in data)
+ assert T == U and count == count2
+ total -= total2**2/len(data)
+ assert not total < 0, 'negative sum of square deviations: %f' % total
+ return (T, total)
+
+
+def variance(data, xbar=None):
+ """Return the sample variance of data.
+
+ data should be an iterable of Real-valued numbers, with at least two
+ values. The optional argument xbar, if given, should be the mean of
+ the data. If it is missing or None, the mean is automatically calculated.
+
+ Use this function when your data is a sample from a population. To
+ calculate the variance from the entire population, see ``pvariance``.
+
+ Examples:
+
+ >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
+ >>> variance(data)
+ 1.3720238095238095
+
+ If you have already calculated the mean of your data, you can pass it as
+ the optional second argument ``xbar`` to avoid recalculating it:
+
+ >>> m = mean(data)
+ >>> variance(data, m)
+ 1.3720238095238095
+
+ This function does not check that ``xbar`` is actually the mean of
+ ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
+ impossible results.
+
+ Decimals and Fractions are supported:
+
+ >>> from decimal import Decimal as D
+ >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
+ Decimal('31.01875')
+
+ >>> from fractions import Fraction as F
+ >>> variance([F(1, 6), F(1, 2), F(5, 3)])
+ Fraction(67, 108)
+
+ """
+ if iter(data) is data:
+ data = list(data)
+ n = len(data)
+ if n < 2:
+ raise StatisticsError('variance requires at least two data points')
+ T, ss = _ss(data, xbar)
+ return _convert(ss/(n-1), T)
+
+
+def pvariance(data, mu=None):
+ """Return the population variance of ``data``.
+
+ data should be an iterable of Real-valued numbers, with at least one
+ value. The optional argument mu, if given, should be the mean of
+ the data. If it is missing or None, the mean is automatically calculated.
+
+ Use this function to calculate the variance from the entire population.
+ To estimate the variance from a sample, the ``variance`` function is
+ usually a better choice.
+
+ Examples:
+
+ >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
+ >>> pvariance(data)
+ 1.25
+
+ If you have already calculated the mean of the data, you can pass it as
+ the optional second argument to avoid recalculating it:
+
+ >>> mu = mean(data)
+ >>> pvariance(data, mu)
+ 1.25
+
+ This function does not check that ``mu`` is actually the mean of ``data``.
+ Giving arbitrary values for ``mu`` may lead to invalid or impossible
+ results.
+
+ Decimals and Fractions are supported:
+
+ >>> from decimal import Decimal as D
+ >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
+ Decimal('24.815')
+
+ >>> from fractions import Fraction as F
+ >>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
+ Fraction(13, 72)
+
+ """
+ if iter(data) is data:
+ data = list(data)
+ n = len(data)
+ if n < 1:
+ raise StatisticsError('pvariance requires at least one data point')
+ T, ss = _ss(data, mu)
+ return _convert(ss/n, T)
+
+
+def stdev(data, xbar=None):
+ """Return the square root of the sample variance.
+
+ See ``variance`` for arguments and other details.
+
+ >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
+ 1.0810874155219827
+
+ """
+ var = variance(data, xbar)
+ try:
+ return var.sqrt()
+ except AttributeError:
+ return math.sqrt(var)
+
+
+def pstdev(data, mu=None):
+ """Return the square root of the population variance.
+
+ See ``pvariance`` for arguments and other details.
+
+ >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
+ 0.986893273527251
+
+ """
+ var = pvariance(data, mu)
+ try:
+ return var.sqrt()
+ except AttributeError:
+ return math.sqrt(var)
+
+## Normal Distribution #####################################################
+
+class NormalDist:
+ 'Normal distribution of a random variable'
+ # https://en.wikipedia.org/wiki/Normal_distribution
+ # https://en.wikipedia.org/wiki/Variance#Properties
+
+ __slots__ = {'mu': 'Arithmetic mean of a normal distribution',
+ 'sigma': 'Standard deviation of a normal distribution'}
+
+ def __init__(self, mu=0.0, sigma=1.0):
+ 'NormalDist where mu is the mean and sigma is the standard deviation.'
+ if sigma < 0.0:
+ raise StatisticsError('sigma must be non-negative')
+ self.mu = mu
+ self.sigma = sigma
+
+ @classmethod
+ def from_samples(cls, data):
+ 'Make a normal distribution instance from sample data.'
+ if not isinstance(data, (list, tuple)):
+ data = list(data)
+ xbar = fmean(data)
+ return cls(xbar, stdev(data, xbar))
+
+ def samples(self, n, seed=None):
+ 'Generate *n* samples for a given mean and standard deviation.'
+ gauss = random.gauss if seed is None else random.Random(seed).gauss
+ mu, sigma = self.mu, self.sigma
+ return [gauss(mu, sigma) for i in range(n)]
+
+ def pdf(self, x):
+ 'Probability density function. P(x <= X < x+dx) / dx'
+ variance = self.sigma ** 2.0
+ if not variance:
+ raise StatisticsError('pdf() not defined when sigma is zero')
+ return exp((x - self.mu)**2.0 / (-2.0*variance)) / sqrt(tau * variance)
+
+ def cdf(self, x):
+ 'Cumulative distribution function. P(X <= x)'
+ if not self.sigma:
+ raise StatisticsError('cdf() not defined when sigma is zero')
+ return 0.5 * (1.0 + erf((x - self.mu) / (self.sigma * sqrt(2.0))))
+
+ def inv_cdf(self, p):
+ '''Inverse cumulative distribution function. x : P(X <= x) = p
+
+ Finds the value of the random variable such that the probability of the
+ variable being less than or equal to that value equals the given probability.
+
+ This function is also called the percent point function or quantile function.
+ '''
+ if (p <= 0.0 or p >= 1.0):
+ raise StatisticsError('p must be in the range 0.0 < p < 1.0')
+ if self.sigma <= 0.0:
+ raise StatisticsError('cdf() not defined when sigma at or below zero')
+
+ # There is no closed-form solution to the inverse CDF for the normal
+ # distribution, so we use a rational approximation instead:
+ # Wichura, M.J. (1988). "Algorithm AS241: The Percentage Points of the
+ # Normal Distribution". Applied Statistics. Blackwell Publishing. 37
+ # (3): 477–484. doi:10.2307/2347330. JSTOR 2347330.
+
+ q = p - 0.5
+ if fabs(q) <= 0.425:
+ r = 0.180625 - q * q
+ num = (((((((2.5090809287301226727e+3 * r +
+ 3.3430575583588128105e+4) * r +
+ 6.7265770927008700853e+4) * r +
+ 4.5921953931549871457e+4) * r +
+ 1.3731693765509461125e+4) * r +
+ 1.9715909503065514427e+3) * r +
+ 1.3314166789178437745e+2) * r +
+ 3.3871328727963666080e+0) * q
+ den = (((((((5.2264952788528545610e+3 * r +
+ 2.8729085735721942674e+4) * r +
+ 3.9307895800092710610e+4) * r +
+ 2.1213794301586595867e+4) * r +
+ 5.3941960214247511077e+3) * r +
+ 6.8718700749205790830e+2) * r +
+ 4.2313330701600911252e+1) * r +
+ 1.0)
+ x = num / den
+ return self.mu + (x * self.sigma)
+ r = p if q <= 0.0 else 1.0 - p
+ r = sqrt(-log(r))
+ if r <= 5.0:
+ r = r - 1.6
+ num = (((((((7.74545014278341407640e-4 * r +
+ 2.27238449892691845833e-2) * r +
+ 2.41780725177450611770e-1) * r +
+ 1.27045825245236838258e+0) * r +
+ 3.64784832476320460504e+0) * r +
+ 5.76949722146069140550e+0) * r +
+ 4.63033784615654529590e+0) * r +
+ 1.42343711074968357734e+0)
+ den = (((((((1.05075007164441684324e-9 * r +
+ 5.47593808499534494600e-4) * r +
+ 1.51986665636164571966e-2) * r +
+ 1.48103976427480074590e-1) * r +
+ 6.89767334985100004550e-1) * r +
+ 1.67638483018380384940e+0) * r +
+ 2.05319162663775882187e+0) * r +
+ 1.0)
+ else:
+ r = r - 5.0
+ num = (((((((2.01033439929228813265e-7 * r +
+ 2.71155556874348757815e-5) * r +
+ 1.24266094738807843860e-3) * r +
+ 2.65321895265761230930e-2) * r +
+ 2.96560571828504891230e-1) * r +
+ 1.78482653991729133580e+0) * r +
+ 5.46378491116411436990e+0) * r +
+ 6.65790464350110377720e+0)
+ den = (((((((2.04426310338993978564e-15 * r +
+ 1.42151175831644588870e-7) * r +
+ 1.84631831751005468180e-5) * r +
+ 7.86869131145613259100e-4) * r +
+ 1.48753612908506148525e-2) * r +
+ 1.36929880922735805310e-1) * r +
+ 5.99832206555887937690e-1) * r +
+ 1.0)
+ x = num / den
+ if q < 0.0:
+ x = -x
+ return self.mu + (x * self.sigma)
+
+ def overlap(self, other):
+ '''Compute the overlapping coefficient (OVL) between two normal distributions.
+
+ Measures the agreement between two normal probability distributions.
+ Returns a value between 0.0 and 1.0 giving the overlapping area in
+ the two underlying probability density functions.
+
+ >>> N1 = NormalDist(2.4, 1.6)
+ >>> N2 = NormalDist(3.2, 2.0)
+ >>> N1.overlap(N2)
+ 0.8035050657330205
+ '''
+ # See: "The overlapping coefficient as a measure of agreement between
+ # probability distributions and point estimation of the overlap of two
+ # normal densities" -- Henry F. Inman and Edwin L. Bradley Jr
+ # http://dx.doi.org/10.1080/03610928908830127
+ if not isinstance(other, NormalDist):
+ raise TypeError('Expected another NormalDist instance')
+ X, Y = self, other
+ if (Y.sigma, Y.mu) < (X.sigma, X.mu): # sort to assure commutativity
+ X, Y = Y, X
+ X_var, Y_var = X.variance, Y.variance
+ if not X_var or not Y_var:
+ raise StatisticsError('overlap() not defined when sigma is zero')
+ dv = Y_var - X_var
+ dm = fabs(Y.mu - X.mu)
+ if not dv:
+ return 1.0 - erf(dm / (2.0 * X.sigma * sqrt(2.0)))
+ a = X.mu * Y_var - Y.mu * X_var
+ b = X.sigma * Y.sigma * sqrt(dm**2.0 + dv * log(Y_var / X_var))
+ x1 = (a + b) / dv
+ x2 = (a - b) / dv
+ return 1.0 - (fabs(Y.cdf(x1) - X.cdf(x1)) + fabs(Y.cdf(x2) - X.cdf(x2)))
+
+ @property
+ def mean(self):
+ 'Arithmetic mean of the normal distribution.'
+ return self.mu
+
+ @property
+ def stdev(self):
+ 'Standard deviation of the normal distribution.'
+ return self.sigma
+
+ @property
+ def variance(self):
+ 'Square of the standard deviation.'
+ return self.sigma ** 2.0
+
+ def __add__(x1, x2):
+ '''Add a constant or another NormalDist instance.
+
+ If *other* is a constant, translate mu by the constant,
+ leaving sigma unchanged.
+
+ If *other* is a NormalDist, add both the means and the variances.
+ Mathematically, this works only if the two distributions are
+ independent or if they are jointly normally distributed.
+ '''
+ if isinstance(x2, NormalDist):
+ return NormalDist(x1.mu + x2.mu, hypot(x1.sigma, x2.sigma))
+ return NormalDist(x1.mu + x2, x1.sigma)
+
+ def __sub__(x1, x2):
+ '''Subtract a constant or another NormalDist instance.
+
+ If *other* is a constant, translate by the constant mu,
+ leaving sigma unchanged.
+
+ If *other* is a NormalDist, subtract the means and add the variances.
+ Mathematically, this works only if the two distributions are
+ independent or if they are jointly normally distributed.
+ '''
+ if isinstance(x2, NormalDist):
+ return NormalDist(x1.mu - x2.mu, hypot(x1.sigma, x2.sigma))
+ return NormalDist(x1.mu - x2, x1.sigma)
+
+ def __mul__(x1, x2):
+ '''Multiply both mu and sigma by a constant.
+
+ Used for rescaling, perhaps to change measurement units.
+ Sigma is scaled with the absolute value of the constant.
+ '''
+ return NormalDist(x1.mu * x2, x1.sigma * fabs(x2))
+
+ def __truediv__(x1, x2):
+ '''Divide both mu and sigma by a constant.
+
+ Used for rescaling, perhaps to change measurement units.
+ Sigma is scaled with the absolute value of the constant.
+ '''
+ return NormalDist(x1.mu / x2, x1.sigma / fabs(x2))
+
+ def __pos__(x1):
+ 'Return a copy of the instance.'
+ return NormalDist(x1.mu, x1.sigma)
+
+ def __neg__(x1):
+ 'Negates mu while keeping sigma the same.'
+ return NormalDist(-x1.mu, x1.sigma)
+
+ __radd__ = __add__
+
+ def __rsub__(x1, x2):
+ 'Subtract a NormalDist from a constant or another NormalDist.'
+ return -(x1 - x2)
+
+ __rmul__ = __mul__
+
+ def __eq__(x1, x2):
+ 'Two NormalDist objects are equal if their mu and sigma are both equal.'
+ if not isinstance(x2, NormalDist):
+ return NotImplemented
+ return (x1.mu, x2.sigma) == (x2.mu, x2.sigma)
+
+ def __repr__(self):
+ return '(%(name)s)(mu=%(mu)s, sigma=%(sigma)s)' % {'name':type(self).__name__, 'sigma': repr(self.sigma), 'mu': repr(self.mu)}
+
+
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/__init__.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..169bc396dadfa3bb6f3d0c29facb161c7357f4d5
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/__init__.py
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+
+
+class Dispatcher(object):
+
+ def __init__(self):
+ self._registry_ = {}
+
+ def register_for(self, *fnames):
+ def wrap(dispatch_fn):
+ for fname in fnames:
+ self._registry_[fname] = dispatch_fn
+ return dispatch_fn
+ return wrap
+
+ def get_for(self, fname):
+ try:
+ return self._registry_[fname]
+ except KeyError:
+ raise SyntaxError('Function not found for %s' % fname)
+
+ def __iter__(self):
+ return iter(registry.values())
+
+
+dispatcher = Dispatcher()
+
+
+def get_for(fname):
+ return dispatcher.get_for(fname)
+
+
+def supported():
+ """ Get a list of supported formulas """
+ return sorted(dispatcher._registry_.keys())
+
+
+def is_supported(fname):
+ return fname in dispatcher._registry_
+
+
+from . import error
+from . import information
+from . import logic
+from . import statistical
+from . import mathtrig
+from . import text
+from . import dateandtime
+from . import engineering
+from . import financial
+from . import lookupandreference
+
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/dateandtime.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/dateandtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..02fa8d489bef3fd544c07d217ba6ea566b57a89a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/dateandtime.py
@@ -0,0 +1,173 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/date-time.js
+"""
+from . import dispatcher
+from . import error
+from . import utils
+import datetime
+import calendar
+
+
+@dispatcher.register_for('DATE')
+def DATE(year, month, day):
+ year = utils.parse_number(year)
+ month = utils.parse_number(month)
+ day = utils.parse_number(day)
+ if utils.any_is_error((year, month, day)):
+ return error.VALUE
+ if year < 1900:
+ year += 1900
+ return datetime.datetime(year, month, day)
+
+
+@dispatcher.register_for('DATEVALUE')
+def DATEVALUE(date):
+ return utils.serialize_date(date)
+
+
+@dispatcher.register_for('YEAR')
+def YEAR(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.year
+
+
+@dispatcher.register_for('MONTH')
+def MONTH(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.month
+
+
+@dispatcher.register_for('DAY')
+def DAY(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.day
+
+
+@dispatcher.register_for('HOUR')
+def HOUR(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.hour
+
+
+@dispatcher.register_for('MINUTE')
+def MINUTE(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.minute
+
+
+@dispatcher.register_for('SECOND')
+def SECOND(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.second
+
+
+@dispatcher.register_for('TODAY')
+def TODAY():
+ today = datetime.date.today()
+ return datetime.datetime(today.year, today.month, today.day)
+
+
+@dispatcher.register_for('DAYS')
+def DAYS(end_date, start_date):
+ end_date = utils.parse_date(end_date)
+ start_date = utils.parse_date(start_date)
+ if utils.any_is_error((end_date, start_date)):
+ return error.VALUE
+ return utils.serialize_date(end_date) - utils.serialize_date(start_date)
+
+
+@dispatcher.register_for('NOW')
+def NOW():
+ return datetime.datetime.now()
+
+
+@dispatcher.register_for('DATEDIF')
+def DATEDIF(start_date, end_date, unit):
+ start_date = utils.parse_date(start_date)
+ end_date = utils.parse_date(end_date)
+ if utils.any_is_error((start_date, end_date)):
+ return error.NUM
+ if type(unit) != str:
+ return error.NAME
+ unit = unit.lower()
+ if start_date == end_date:
+ return 0
+ if start_date < end_date:
+ if unit == 'y':
+ return end_date.year - start_date.year - (1 if (end_date.month < start_date.month or (end_date.month == start_date.month and end_date.day < start_date.day)) else 0)
+ if unit == 'm':
+ return (end_date.year - start_date.year) * 12 + end_date.month - start_date.month - (1 if end_date.day < start_date.day else 0)
+ if unit == 'd':
+ return int(utils.serialize_date(end_date) - utils.serialize_date(start_date))
+ if unit == 'md':
+ start_day = start_date.day
+ end_day = end_date.day
+ if end_day >= start_day:
+ return end_day - start_day
+ else:
+ prev_month = end_date.month - 1
+ prev_month_days = 30 if prev_month in {4, 6, 9, 11} else 31 if prev_month != 2 else 29 if calendar.isleap(end_date.year) else 28
+ return prev_month_days - start_day + end_day
+ if unit == 'ym':
+ start_month = start_date.month
+ end_month = end_date.month
+ year_diff = end_date.year - start_date.year
+ month_diff = (year_diff * 12 + end_month - start_month)
+ if end_date.day < start_date.day:
+ month_diff -= 1
+ return int(month_diff % 12)
+ if unit == 'yd':
+ start_date_end_year = datetime.datetime(end_date.year, start_date.month, start_date.day)
+ if start_date_end_year > end_date:
+ start_date_end_year = datetime.datetime(end_date.year - 1, start_date.month, start_date.day)
+ return int(utils.serialize_date(end_date) - utils.serialize_date(start_date_end_year))
+ return error.NUM
+
+
+@dispatcher.register_for('EDATE')
+def EDATE(start_date, month):
+ if start_date == None:
+ default_date = True
+ start_date = datetime.datetime(1900, 1, 1)
+ else:
+ default_date = False
+ start_date = utils.parse_date(start_date)
+ if month == None:
+ return start_date
+ month= int(month)
+ year = start_date.year + (month // 12)
+ month = start_date.month + (month % 12)
+ if month > 12:
+ month -= 12
+ year += 1
+ elif month < 1:
+ month += 12
+ year -= 1
+ if default_date:
+ month -= 1
+ if month == 2:
+ day = 29 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else 28
+ elif month in {4, 6, 9, 11}:
+ day = 30
+ else:
+ day = 31
+ else:
+ day = start_date.day
+ day = min(day, [31, 29 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1])
+ if year > 9999 or year < 1900:
+ return error.NUM
+ return datetime.datetime(year, month, day)
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/engineering.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/engineering.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd0027793edb5c7a97e6b2986feceac41e44ec4e
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/engineering.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+from __future__ import division
+from . import dispatcher
+from . import error
+from . import utils
+from .utils import DEFAULT
+
+
+@dispatcher.register_for('HEX2DEC')
+def HEX2DEC(hex):
+ try:
+ dec = int(hex, 16)
+ return (dec - 1099511627776) if (dec >= 549755813888) else dec
+ except ValueError:
+ return error.VALUE
+
+
+@dispatcher.register_for('DEC2HEX')
+def DEC2HEX(dec, places=DEFAULT):
+ dec = utils.parse_number(dec)
+ if isinstance(dec, error.XLError):
+ return dec
+ if places is not DEFAULT:
+ places = utils.parse_number(places)
+ if isinstance(places, error.XLError):
+ return places
+ if places < 0:
+ return error.NUM
+ if dec < 0:
+ places = DEFAULT
+ dec = dec + 1099511627776
+ try:
+ result = (hex(dec)[2:])
+ if result[-1] == 'L':
+ result = result[:-1]
+ if places is not DEFAULT:
+ if len(result) > places:
+ return error.NUM
+ result = result.rjust(places, '0')
+ return result.upper()
+ except ValueError:
+ return error.VALUE
+
+
+@dispatcher.register_for('COMPLEX')
+def COMPLEX(real, imaginary):
+ real = utils.parse_number(real)
+ imaginary = utils.parse_number(imaginary)
+ if utils.any_is_error((real, imaginary)):
+ return error.VALUE
+ return complex(real, imaginary)
+
+
+@dispatcher.register_for('DELTA')
+def DELTA(number1, number2):
+ number1 = utils.parse_number(number1)
+ number2 = utils.parse_number(number2)
+ if utils.any_is_error((number1, number2)):
+ return error.VALUE
+ return 1 if number1 == number2 else 0
+
+
+@dispatcher.register_for('IMAGINARY')
+def IMAGINARY(compl):
+ compl = utils.parse_complex(compl)
+ if isinstance(compl, error.XLError):
+ return compl
+ return int(compl.imag)
+
+@dispatcher.register_for('IMREAL')
+def IMREAL(compl):
+ compl = utils.parse_complex(compl)
+ if isinstance(compl, error.XLError):
+ return compl
+ return int(compl.real)
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/error.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/error.py
new file mode 100644
index 0000000000000000000000000000000000000000..17fa37d602b057f6c242c65d08ab59a461894f1a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/error.py
@@ -0,0 +1,32 @@
+# -*- coding: utf-8 -*-
+"""
+Defines Excel errors as python exceptions
+"""
+
+class XLError(RuntimeError):
+ pass
+
+ERROR = XLError('#ERROR!')
+DIV_ZERO = XLError('#DIV/0!')
+NAME = XLError('#NAME?')
+NOT_AVAILABLE = XLError('#N/A')
+NULL = XLError('#NULL!')
+NUM = XLError('#NUM!')
+REF = XLError('#REF!')
+VALUE = XLError('#VALUE!')
+DATA = XLError('#GETTING_DATA')
+
+
+def from_message(message):
+ errdict = {
+ '#ERROR!': ERROR,
+ '#DIV/0!': DIV_ZERO,
+ '#NAME?': NAME,
+ '#N/A': NOT_AVAILABLE,
+ '#NULL!': NULL,
+ '#NUM!': NUM,
+ '#REF!': REF,
+ '#VALUE!': VALUE,
+ '#GETTING_DATA': DATA
+ }
+ return errdict.get(str(message), ERROR)
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/financial.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/financial.py
new file mode 100644
index 0000000000000000000000000000000000000000..fced0ea2849d39dbacf81e76e26b9ecd2f5d4b0e
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/financial.py
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+from __future__ import division
+from . import dispatcher
+from . import error
+from . import utils
+
+
+@dispatcher.register_for('PV')
+def PV(rate, periods, payment, future=None, type=None):
+ if future is None:
+ future = 0
+ if type is None:
+ type = 0
+ rate = utils.parse_number(rate)
+ periods = utils.parse_number(periods)
+ payment = utils.parse_number(payment)
+ future = utils.parse_number(future)
+ type = utils.parse_number(type)
+ if utils.any_is_error((rate, periods, payment, future, type)):
+ return error.VALUE
+ # Return present value
+ if rate == 0:
+ return -payment * periods - future
+ else:
+ rate_exp_periods = (1 + rate)**periods
+ return (((1 - rate_exp_periods) / rate) * payment * (1 + rate * type) - future) / rate_exp_periods
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/information.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/information.py
new file mode 100644
index 0000000000000000000000000000000000000000..56dd4c4f175a81b4885838e56e40c0027538b546
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/information.py
@@ -0,0 +1,103 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/information.js
+"""
+
+from . import dispatcher
+from . import error
+from . import utils
+from .._compat import number_types, string_types
+import datetime
+
+
+@dispatcher.register_for('ERROR.TYPE')
+def ERROR_TYPE(error_val):
+ errdict = {
+ error.NULL: 1,
+ error.DIV_ZERO: 2,
+ error.VALUE: 3,
+ error.REF: 4,
+ error.NAME: 5,
+ error.NUM: 6,
+ error.NOT_AVAILABLE: 7,
+ error.DATA: 8
+ }
+ return errdict.get(error_val, error.NOT_AVAILABLE)
+
+
+@dispatcher.register_for('ISBLANK')
+def ISBLANK(value):
+ return value is None
+
+
+@dispatcher.register_for('ISERR')
+def ISERR(value):
+ return isinstance(value, error.XLError) and value != error.NOT_AVAILABLE
+
+
+@dispatcher.register_for('ISERROR')
+def ISERROR(value):
+ return isinstance(value, error.XLError)
+
+
+@dispatcher.register_for('ISEVEN')
+def ISEVEN(number):
+ if not isinstance(number, number_types):
+ return error.VALUE
+ return (int(number) & 1) == 0
+
+
+@dispatcher.register_for('ISODD')
+def ISODD(number):
+ if not isinstance(number, number_types):
+ return error.VALUE
+ return (int(number) & 1)
+
+
+@dispatcher.register_for('ISTEXT')
+def ISTEXT(value):
+ return isinstance(value, string_types)
+
+
+@dispatcher.register_for('ISNUMBER')
+def ISNUMBER(value):
+ return (not isinstance(value, bool)) and isinstance(value, number_types)
+
+
+@dispatcher.register_for('ISLOGICAL')
+def ISLOGICAL(value):
+ return isinstance(value, bool)
+
+
+@dispatcher.register_for('ISNA')
+def ISNA(value):
+ return value == error.NOT_AVAILABLE
+
+
+@dispatcher.register_for('N')
+def N(value):
+ if isinstance(value, (error.XLError, number_types)):
+ return value
+ if isinstance(value, datetime.datetime):
+ return utils.serialize_date(value)
+ if value is True:
+ return 1
+ return 0
+
+
+@dispatcher.register_for('NA')
+def NA():
+ return error.NOT_AVAILABLE
+
+
+@dispatcher.register_for('ISNONTEXT')
+def ISNONTEXT(value):
+ return not isinstance(value, string_types)
+
+
+@dispatcher.register_for('T')
+def T(value):
+ if isinstance(value, (error.XLError, string_types)):
+ return value
+ return ''
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/logic.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/logic.py
new file mode 100644
index 0000000000000000000000000000000000000000..e573bab2363cb4a4df554ed700c5283908d6668e
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/logic.py
@@ -0,0 +1,81 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/logical.js
+"""
+from . import dispatcher
+from . import error
+from . import utils
+
+
+@dispatcher.register_for('AND')
+def AND(*args):
+ args = utils.iflatten(args)
+ return all(args)
+
+
+@dispatcher.register_for('IF')
+def IF(test, then, otherwise):
+ return then if test else otherwise
+
+
+@dispatcher.register_for('IFERROR')
+def IFERROR(value, value_if_error):
+ return value if not isinstance(value, error.XLError) else value_if_error
+
+
+@dispatcher.register_for('IFNA')
+def IFNA(value, value_if_na):
+ return value if value != error.NOT_AVAILABLE else value_if_na
+
+
+@dispatcher.register_for('NOT')
+def NOT(boolean):
+ return not boolean
+
+
+@dispatcher.register_for('XOR')
+def XOR(*args):
+ args = utils.iflatten(args)
+ result = sum(bool(a) for a in args)
+ return bool(result & 1)
+
+
+@dispatcher.register_for('OR')
+def OR(*args):
+ args = utils.iflatten(args)
+ return any(args)
+
+
+@dispatcher.register_for('SWITCH')
+def SWITCH(target_value, *args):
+ if len(args) <= 1:
+ return error.NOT_AVAILABLE
+ argc = len(args)
+ default_clause = utils.DEFAULT if (argc % 2 == 0) else args[-1]
+ for i in range(0, argc, 2):
+ if target_value == args[i]:
+ return args[i + 1]
+ if default_clause is not utils.DEFAULT:
+ return default_clause
+ return error.NOT_AVAILABLE
+
+
+@dispatcher.register_for('IFS')
+def IFS(*args):
+ for pair in zip(args[::2], args[1::2]):
+ if pair[0]:
+ return pair[1]
+ return error.NOT_AVAILABLE
+
+
+# Compatibility functions
+
+@dispatcher.register_for('TRUE')
+def TRUE():
+ return True
+
+
+@dispatcher.register_for('FALSE')
+def FALSE():
+ return False
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/lookupandreference.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/lookupandreference.py
new file mode 100644
index 0000000000000000000000000000000000000000..a699bf3f407a03671a2b0821e433feaa52c3c0c9
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/lookupandreference.py
@@ -0,0 +1,112 @@
+# -*- coding: utf-8 -*-
+import fnmatch
+from . import dispatcher
+from . import error
+from . import utils
+from .utils import DEFAULT
+from .._compat import string_types
+
+
+@dispatcher.register_for('CHOOSE')
+def CHOOSE(*args):
+ if (len(args) < 2):
+ return error.NOT_AVAILABLE
+
+ index = args[0]
+ if (index < 1 or index > 254):
+ return error.VALUE
+
+ if (len(args) < index + 1):
+ return error.VALUE
+
+ return args[index]
+
+
+@dispatcher.register_for('MATCH')
+def MATCH(lookup_value, lookup_array, match_type=1):
+ if not lookup_value and not lookup_array:
+ return error.NOT_AVAILABLE
+
+ if not isinstance(lookup_array, list):
+ return error.NOT_AVAILABLE
+
+ if match_type not in (-1, 0, 1):
+ return error.NOT_AVAILABLE
+
+ index = None
+ index_value = None
+ for idx in range(len(lookup_array)):
+ if match_type == 1:
+ if lookup_array[idx] == lookup_value:
+ return idx + 1
+ elif lookup_array[idx] < lookup_value:
+ if not index_value:
+ index = idx + 1
+ index_value = lookup_array[idx]
+ elif lookup_array[idx] > index_value:
+ index = idx + 1
+ index_value = lookup_array[idx]
+ elif match_type == 0:
+ if isinstance(lookup_value, string_types):
+ if fnmatch.fnmatch(lookup_array[idx].lower(), lookup_value.lower()):
+ return idx + 1
+ else:
+ if lookup_array[idx] == lookup_value:
+ return idx + 1
+ elif match_type == -1:
+ if lookup_array[idx] == lookup_value:
+ return idx + 1
+ elif lookup_array[idx] > lookup_value:
+ if not index_value:
+ index = idx + 1
+ index_value = lookup_array[idx]
+ elif lookup_array[idx] < index_value:
+ index = idx + 1
+ index_value = lookup_array[idx]
+
+ return index if index else error.NOT_AVAILABLE
+
+
+@dispatcher.register_for('INDEX')
+def INDEX(arr, row_num=DEFAULT, column_num=DEFAULT, area_num=DEFAULT):
+ if row_num is None:
+ row_num = DEFAULT
+ if column_num is None:
+ column_num = DEFAULT
+
+ if arr is None or (row_num is DEFAULT and column_num is DEFAULT):
+ return error.VALUE
+
+ if not isinstance(arr, list):
+ arr = [[arr]]
+
+ bidimensional = isinstance(arr[0], list)
+
+ if row_num is not DEFAULT:
+ row_num = utils.parse_number(row_num)
+ if isinstance(row_num, error.XLError):
+ return row_num
+
+ if column_num is not DEFAULT:
+ column_num = utils.parse_number(column_num)
+ if isinstance(column_num, error.XLError):
+ return column_num
+ try:
+ if row_num is DEFAULT:
+ if bidimensional:
+ return [row[column_num - 1] for row in arr]
+ else:
+ return arr[column_num - 1]
+ if column_num is DEFAULT:
+ return arr[row_num - 1]
+ if row_num == 0 and column_num == 0:
+ return arr
+ if row_num == 0:
+ return [row[column_num - 1] for row in arr]
+ if column_num == 0:
+ return arr[row_num - 1]
+ if not bidimensional and column_num == 1:
+ return arr[row_num -1]
+ return arr[row_num - 1][column_num - 1]
+ except (IndexError, TypeError):
+ return error.REF
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/mathtrig.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/mathtrig.py
new file mode 100644
index 0000000000000000000000000000000000000000..49c4a0e596e22705f7e9ce2a5943ff4247561d7d
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/mathtrig.py
@@ -0,0 +1,547 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/math-trig.js
+"""
+from __future__ import division
+import math
+import random
+import re
+from functools import reduce
+import operator
+import collections
+from . import dispatcher
+from . import error
+from . import utils
+from .utils import DEFAULT
+from ..helper.number import to_number
+
+
+@dispatcher.register_for('ABS')
+def ABS(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return abs(number)
+
+
+@dispatcher.register_for('ACOS')
+def ACOS(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.acos(number)
+
+
+@dispatcher.register_for('ACOSH')
+def ACOSH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.log(number + math.sqrt(number * number - 1))
+
+
+@dispatcher.register_for('ACOT')
+def ACOT(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.atan(1 / number)
+
+
+@dispatcher.register_for('ACOTH')
+def ACOTH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return 0.5 * math.log((number + 1) / (number - 1))
+
+
+@dispatcher.register_for('SIN')
+def SIN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.sin(number)
+
+
+@dispatcher.register_for('SINH')
+def SINH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.sinh(number)
+
+
+@dispatcher.register_for('ASIN')
+def ASIN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.asin(number)
+
+
+@dispatcher.register_for('ASINH')
+def ASINH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.asinh(number)
+
+
+@dispatcher.register_for('COS')
+def COS(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.cos(number)
+
+
+@dispatcher.register_for('COSH')
+def COSH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.cosh(number)
+
+
+@dispatcher.register_for('COT')
+def COT(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.cos(number)/math.sin(number)
+
+
+@dispatcher.register_for('TAN')
+def TAN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.tan(number)
+
+
+@dispatcher.register_for('TANH')
+def TANH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.tanh(number)
+
+
+@dispatcher.register_for('ATAN')
+def ATAN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.atan(number)
+
+
+@dispatcher.register_for('ATAN2')
+def ATAN2(x_num, y_num):
+ x_num = utils.parse_number(x_num)
+ if isinstance(x_num, error.XLError):
+ return x_num
+ y_num = utils.parse_number(y_num)
+ if isinstance(y_num, error.XLError):
+ return y_num
+ if y_num == 0:
+ return error.DIV_ZERO
+ return math.atan2(y_num, x_num)
+
+
+@dispatcher.register_for('ATANH')
+def ATANH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.atanh(number)
+
+
+@dispatcher.register_for('SQRT')
+def SQRT(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.sqrt(number)
+
+
+@dispatcher.register_for('EXP')
+def EXP(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.e**number
+
+
+@dispatcher.register_for('LN')
+def LN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.log(number)
+
+
+@dispatcher.register_for('LOG')
+def LOG(number, base=10):
+ number = utils.parse_number(number)
+ base = utils.parse_number(base)
+ if utils.any_is_error((number, base)):
+ return error.VALUE
+ return math.log(number, base)
+
+
+@dispatcher.register_for('LOG10')
+def LOG10(number):
+ return LOG(number, 10)
+
+
+@dispatcher.register_for('PI')
+def PI():
+ return math.pi
+
+
+@dispatcher.register_for('ROUND')
+def ROUND(number, digits):
+ number = utils.parse_number(number)
+ digits = utils.parse_number(digits)
+ if utils.any_is_error((number, digits)):
+ return error.VALUE
+ return round(number, digits)
+
+
+@dispatcher.register_for('ROUNDUP')
+def ROUNDUP(number, digits):
+ number = utils.parse_number(number)
+ digits = utils.parse_number(digits)
+ if utils.any_is_error((number, digits)):
+ return error.VALUE
+ sign = 1 if number > 0 else -1
+ return sign * (math.ceil(abs(number) * 10**digits)) / 10**digits
+
+
+@dispatcher.register_for('ROUNDDOWN')
+def ROUNDDOWN(number, digits):
+ number = utils.parse_number(number)
+ digits = utils.parse_number(digits)
+ if utils.any_is_error((number, digits)):
+ return error.VALUE
+ sign = 1 if number > 0 else -1
+ return sign * (math.floor(abs(number) * 10**digits)) / 10**digits
+
+
+@dispatcher.register_for('SUM')
+def SUM(*args):
+ return sum(utils.inumbers(args, try_parse=True))
+
+
+@dispatcher.register_for('SUMIF')
+def SUMIF(args, criteria):
+ predicate = utils.parse_criteria(criteria)
+ return sum(a for a in utils.iflatten(args) if predicate(a))
+
+
+@dispatcher.register_for('CEILING', 'CEILING.MATH', 'CEILING.PRECISE')
+def CEILING(number, significance=1):
+ number = utils.parse_number(number)
+ significance = utils.parse_number(significance)
+
+ if utils.any_is_error((number, significance)):
+ return error.VALUE
+ if significance == 0:
+ return 0
+
+ positive_significance = significance > 0
+ significance = abs(significance)
+ if number >= 0:
+ return math.ceil(number / significance) * significance
+ else:
+ if positive_significance:
+ return -1 * math.floor(abs(number) / significance) * significance
+ else:
+ return -1 * math.ceil(abs(number) / significance) * significance
+
+
+@dispatcher.register_for('FLOOR', 'FLOOR.MATH', 'FLOOR.PRECISE')
+def FLOOR(number, significance=1):
+ number = utils.parse_number(number)
+ significance = utils.parse_number(significance)
+
+ if utils.any_is_error((number, significance)):
+ return error.VALUE
+ if significance == 0:
+ return 0
+ if number > 0 and not significance > 0:
+ return error.NUM
+
+ abs_significance = abs(significance)
+ if number >= 0:
+ return math.floor(number / abs_significance) * abs_significance
+ else:
+ func = math.floor
+ if significance > 0:
+ func = math.ceil
+ return -1 * func(abs(number) / abs_significance) * abs_significance
+
+
+@dispatcher.register_for('POWER')
+def POWER(number, power):
+ number = utils.parse_number(number)
+ power = utils.parse_number(power)
+ if utils.any_is_error((number, power)):
+ return error.VALUE
+ result = number**power
+ if math.isnan(result):
+ return error.NUM
+ return result
+
+
+@dispatcher.register_for('QUOTIENT')
+def QUOTIENT(numerator, denominator):
+ numerator = utils.parse_number(numerator)
+ denominator = utils.parse_number(denominator)
+ if utils.any_is_error((numerator, denominator)):
+ return error.VALUE
+ if denominator == 0:
+ return error.DIV_ZERO
+ return int(numerator / denominator)
+
+
+@dispatcher.register_for('MOD')
+def MOD(numerator, denominator):
+ numerator = utils.parse_number(numerator)
+ denominator = utils.parse_number(denominator)
+ if isinstance(numerator, error.XLError):
+ return numerator
+ if isinstance(denominator, error.XLError):
+ return denominator
+ if denominator == 0:
+ return error.DIV_ZERO
+ modulus = abs(numerator % denominator)
+ return modulus if denominator > 0 else -modulus
+
+
+@dispatcher.register_for('RADIANS')
+def RADIANS(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return number * math.pi / 180
+
+
+@dispatcher.register_for('DEGREES')
+def DEGREES(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return number * 180 / math.pi
+
+
+@dispatcher.register_for('PRODUCT')
+def PRODUCT(*args):
+ return reduce(operator.mul, utils.inumbers(args))
+
+
+@dispatcher.register_for('ODD')
+def ODD(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ tmp = math.ceil(abs(number))
+ tmp = tmp if (tmp % 2) == 1 else tmp + 1
+ return tmp if number > 0 else -tmp
+
+
+@dispatcher.register_for('EVEN')
+def EVEN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ tmp = math.ceil(abs(number))
+ tmp = tmp if (tmp % 2) == 0 else tmp + 1
+ return tmp if number > 0 else -tmp
+
+
+@dispatcher.register_for('DECIMAL')
+def DECIMAL(text, base):
+ text = str(text)
+ base = utils.parse_number(base)
+ if isinstance(base, error.XLError):
+ return base
+ try:
+ dec = int(text, base)
+ return (dec - 1099511627776) if (dec >= 549755813888) else dec
+ except ValueError:
+ return error.VALUE
+
+
+@dispatcher.register_for('BASE')
+def BASE(value, base, places=DEFAULT):
+ value = utils.parse_number(value)
+ if isinstance(value, error.XLError):
+ return value
+ base = utils.parse_number(base)
+ if isinstance(base, error.XLError):
+ return base
+ if places is not DEFAULT:
+ places = utils.parse_number(places)
+ if isinstance(places, error.XLError):
+ return places
+ if places < 0:
+ return error.NUM
+ if value == 0:
+ return '0'
+ digits = []
+ while value:
+ digits.append(int(value % base))
+ value //= base
+ result = ''.join(str(n) for n in digits[::-1])
+ if places is not DEFAULT:
+ if len(result) > places:
+ return error.NUM
+ result = result.rjust(places, '0')
+ return result
+
+
+@dispatcher.register_for('FACT')
+def FACT(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ if number < 0:
+ return error.NUM
+ return math.factorial(int(number))
+
+
+@dispatcher.register_for('FACTDOUBLE')
+def FACTDOUBLE(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ if number < 0:
+ return error.NUM
+ number = int(number)
+ if number in (0, 1):
+ return 1
+ return reduce(operator.mul, range(number, 1, -2))
+
+
+@dispatcher.register_for('ROMAN')
+def ROMAN(number, form=0):
+ number = utils.parse_number(number)
+ form = utils.parse_number(form)
+ if form is True:
+ form = 0
+ elif form is False:
+ form = 4
+
+ if utils.any_is_error((number, form)):
+ return error.VALUE
+
+ if not (0 < number < 4000 and 0 <= form <= 4):
+ return error.VALUE # number must be between 1 and 3999
+
+ def numerals(compress):
+ numeral_map = ((1000, 'M'), (500, 'D'), (100, 'C'), (50, 'L'), (10, 'X'), (5, 'V'), (1, 'I'))
+ for i, (arabic, roman) in enumerate(numeral_map, 1):
+ yield arabic, roman
+ # Then we make a list where we try to create new mappings
+ # subtracting the subsequent fixed roman numeral values from our current one
+ # and prepending their roman numerals to ours, up to compress times.
+ # The more mappings we have the more compressed the representation will be.
+ inbetweeners = collections.deque()
+ for smaller_arabic, smaller_roman in numeral_map[i:]:
+ smaller_arabic = arabic - smaller_arabic
+ if (smaller_arabic, smaller_roman) not in numeral_map:
+ inbetweeners.appendleft((smaller_arabic, smaller_roman + roman))
+ if len(inbetweeners) == compress:
+ break
+ for el in inbetweeners:
+ yield el
+
+ result = ''
+ for arabic_digit, roman_numeral in numerals(form + 1):
+ if not number:
+ break
+ count = int(number / arabic_digit)
+ result += roman_numeral * count
+ number -= arabic_digit * count
+ return result
+
+
+@dispatcher.register_for('ARABIC')
+def ARABIC(text):
+ text = str(text).upper()
+ roman_numeral_regex = '^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$'
+
+ if re.search(roman_numeral_regex, text) is None:
+ return error.VALUE
+
+ numeral_map = {
+ 'M': 1000,
+ 'CM': 900,
+ 'D': 500,
+ 'CD': 400,
+ 'C': 100,
+ 'XC': 90,
+ 'L': 50,
+ 'XL': 40,
+ 'X': 10,
+ 'IX': 9,
+ 'V': 5,
+ 'IV': 4,
+ 'I': 1
+ }
+ result = 0
+ return sum(numeral_map[match.group()] for match in re.finditer('[MDLV]|C[MD]?|X[CL]?|I[XV]?', text))
+
+
+@dispatcher.register_for('RAND')
+def RAND():
+ return random.random()
+
+
+@dispatcher.register_for('RANDBETWEEN')
+def RANDBETWEEN(bottom, top):
+ bottom = utils.parse_number(bottom)
+ top = utils.parse_number(top)
+
+ if utils.any_is_error((bottom, top)):
+ return error.VALUE
+
+ return random.randint(int(bottom), int(top))
+
+
+@dispatcher.register_for('INT')
+def INT(number):
+ if not isinstance(number, (int, float)):
+ return error.VALUE
+ if number >= 0:
+ return int(number)
+ elif int(number) > number:
+ return int(number)-1
+ else:
+ return int(number)
+
+
+@dispatcher.register_for('SUMIFS')
+def SUMIFS(sum_args, *criteria):
+ if len(criteria) % 2 != 0:
+ return error.ERROR
+ range_and_preds = list(zip(criteria[::2], (utils.parse_criteria(criterion) for criterion in criteria[1::2])))
+ b = 0
+ for i, a in enumerate(sum_args):
+ if all(pred(criteria_range[i]) for criteria_range,pred in range_and_preds):
+ b += a
+ return b
+
+
+@dispatcher.register_for('SIGN')
+def SIGN(number):
+ if not isinstance(number, (int, float)):
+ return error.VALUE
+ if number == 0:
+ return 0
+ if number > 0:
+ return 1
+ return -1
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/operators.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/operators.py
new file mode 100644
index 0000000000000000000000000000000000000000..10ef145a8e733b2456b3a12a4ba2dd215768126a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/operators.py
@@ -0,0 +1,396 @@
+# -*- coding: utf-8 -*-
+from __future__ import division
+import datetime
+from . import error
+from ..helper.number import to_number
+from .utils import OPERATOR_DICT, serialize_date, parse_date, date_1900
+from .._compat import number_types, string_types
+
+
+NoneType = type(None)
+
+
+class ExcelComparator(object):
+
+ def __init__(self, value):
+ self.value = value
+ if isinstance(value, datetime.datetime):
+ self.value = serialize_date(value)
+
+ def convert_other(self, other):
+ if other is None:
+ if isinstance(self.value, bool):
+ other = False
+ elif isinstance(self.value, number_types):
+ other = type(self.value)(0) # so it's the same number type
+ elif isinstance(self.value, string_types):
+ other = ''
+ elif isinstance(other, datetime.datetime):
+ other = serialize_date(other)
+ return other
+
+ def __lt__(self, other):
+ if self.value is None:
+ if other is None:
+ return False
+ else:
+ return ExcelComparator(other).__gt__(self.value)
+ if type(self.value) != type(other):
+ other = self.convert_other(other)
+ if type(self.value) != type(other) and not (isinstance(self.value, number_types) and isinstance(other, number_types)):
+ # if the type is still different
+ if isinstance(self.value, bool):
+ return False # bool is the biggest in XL
+ if isinstance(self.value, string_types):
+ if isinstance(other, bool):
+ return True
+ if isinstance(other, number_types):
+ return False
+ if isinstance(self.value, number_types):
+ return True
+ return self.value < other
+
+ def __gt__(self, other):
+ if self.value is None:
+ if other is None:
+ return False
+ return ExcelComparator(other).__lt__(self.value)
+ if type(self.value) != type(other):
+ other = self.convert_other(other)
+ if type(self.value) != type(other) and not (isinstance(self.value, number_types) and isinstance(other, number_types)):
+ if isinstance(self.value, bool):
+ return True # bool is the biggest in XL
+ if isinstance(self.value, string_types):
+ if isinstance(other, bool):
+ return False
+ if isinstance(other, number_types):
+ return True
+ if isinstance(self.value, number_types):
+ return False
+ return self.value > other
+
+ def __eq__(self, other):
+ if self.value is None:
+ if other is None:
+ return True
+ return ExcelComparator(other).__eq__(self.value)
+ if type(self.value) != type(other):
+ other = self.convert_other(other)
+ return self.value == other
+
+ def __ge__(self, other):
+ return self.__gt__(other) or self.__eq__(other)
+
+ def __le__(self, other):
+ return self.__lt__(other) or self.__eq__(other)
+
+
+class ExcelArrayOps(object):
+
+ def __init__(self, arr):
+ self.arr = arr
+
+ def adapt_value(self, value):
+ if isinstance(value, list) and len(value) == 1:
+ value = value[0]
+ if not isinstance(value, list):
+ value = [value for i in range(len(self.arr))]
+ return value
+
+ def __add__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('+', a, b) for a, b in zip(self.arr, value)]
+
+ __radd__ = __add__
+
+ def __sub__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('-', a, b) for a, b in zip(self.arr, value)]
+
+ def __rsub__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('-', b, a) for a, b in zip(self.arr, value)]
+
+ def __mul__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('*', a, b) for a, b in zip(self.arr, value)]
+
+ __rmul__ = __mul__
+
+ def __truediv__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('/', a, b) for a, b in zip(self.arr, value)]
+
+ def __rtruediv__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('/', b, a) for a, b in zip(self.arr, value)]
+
+
+def value_and_type(value):
+ if isinstance(value, number_types):
+ return (value, number_types)
+ if isinstance(value, datetime.datetime):
+ return (value, datetime.datetime)
+ if isinstance(value, string_types):
+ value = to_number(value)
+ if isinstance(value, number_types):
+ return value_and_type(value)
+ try_date = parse_date(value)
+ if isinstance(try_date, error.XLError):
+ return (value, string_types)
+ return value_and_type(try_date)
+ if isinstance(value, NoneType):
+ return (value, NoneType)
+ if isinstance(value, error.XLError):
+ return (value, error.XLError)
+ return (error.VALUE, error.XLError)
+
+
+# see https://support.office.com/en-ie/article/data-types-in-data-models-e2388f62-6122-4e2b-bcad-053e3da9ba90#__toc319430523
+IMPLICIT_DATA_TYPE_CONVERSIONS = {
+ '+': {
+ # left operand
+ number_types: {
+ # right operand
+ datetime.datetime: {
+ # conversion
+ 'left': None,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': None,
+ 'right': None
+ },
+ NoneType: {
+ 'left': None,
+ 'right': lambda x: 0
+ }
+ },
+ datetime.datetime: {
+ datetime.datetime: {
+ 'left': serialize_date,
+ 'right': serialize_date
+ },
+ number_types: {
+ 'left': serialize_date,
+ 'right': None,
+ 'result': parse_date
+ },
+ NoneType: {
+ 'left': serialize_date,
+ 'right': lambda x: 0,
+ 'result': parse_date
+ }
+ },
+ NoneType: {
+ datetime.datetime: {
+ 'left': lambda x: 0,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': lambda x: 0,
+ 'right': None
+ },
+ NoneType: {
+ 'left': lambda x: 0,
+ 'right': lambda x: 0
+ }
+ },
+ },
+ '-': {
+ number_types: {
+ datetime.datetime: {
+ 'left': None,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': None,
+ 'right': None
+ },
+ NoneType: {
+ 'left': None,
+ 'right': lambda x: 0
+ }
+ },
+ datetime.datetime: {
+ datetime.datetime: {
+ 'left': serialize_date,
+ 'right': serialize_date
+ },
+ number_types: {
+ 'left': serialize_date,
+ 'right': None,
+ 'result': parse_date
+ },
+ NoneType: {
+ 'left': serialize_date,
+ 'right': lambda x: 0,
+ 'result': parse_date
+ }
+ },
+ NoneType: {
+ datetime.datetime: {
+ 'left': lambda x: 0,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': lambda x: 0,
+ 'right': None
+ },
+ NoneType: {
+ 'left': lambda x: 0,
+ 'right': lambda x: 0
+ }
+ }
+ },
+ '*': {
+ number_types: {
+ datetime.datetime: {
+ 'left': None,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': None,
+ 'right': None
+ },
+ NoneType: {
+ 'left': None,
+ 'right': lambda x: 0
+ }
+ },
+ datetime.datetime: {
+ datetime.datetime: {
+ 'left': serialize_date,
+ 'right': serialize_date
+ },
+ number_types: {
+ 'left': serialize_date,
+ 'right': None,
+ 'result': parse_date
+ },
+ NoneType: {
+ 'left': serialize_date,
+ 'right': lambda x: 0,
+ 'result': parse_date
+ }
+ },
+ NoneType: {
+ datetime.datetime: {
+ 'left': lambda x: 0,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': lambda x: 0,
+ 'right': None
+ },
+ NoneType: {
+ 'left': lambda x: 0,
+ 'right': lambda x: 0
+ }
+ }
+ },
+ '/': {
+ number_types: {
+ datetime.datetime: {
+ 'left': None,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': None,
+ 'right': None
+ },
+ NoneType: {
+ 'left': None,
+ 'right': lambda x: 0
+ }
+
+ },
+ datetime.datetime: {
+ datetime.datetime: {
+ 'left': serialize_date,
+ 'right': serialize_date
+ },
+ number_types: {
+ 'left': serialize_date,
+ 'right': None,
+ 'result': parse_date
+ },
+ NoneType: {
+ 'left': serialize_date,
+ 'right': lambda x: 0
+ }
+ },
+ NoneType: {
+ datetime.datetime: {
+ 'left': lambda x: 0,
+ 'right': serialize_date
+ },
+ number_types: {
+ 'left': lambda x: 0,
+ 'right': None
+ },
+ NoneType: {
+ 'left': lambda x: 0,
+ 'right': lambda x: 0
+ }
+ }
+ }
+}
+
+
+def evaluate_arithmetic(op, lval, rval):
+ if isinstance(lval, error.XLError):
+ return lval
+ if isinstance(rval, error.XLError):
+ return rval
+ if isinstance(lval, list):
+ return OPERATOR_DICT[op](ExcelArrayOps(lval), rval)
+ if isinstance(rval, list):
+ return OPERATOR_DICT[op](lval, ExcelArrayOps(rval))
+
+ lval, ltype = value_and_type(lval)
+ rval, rtype = value_and_type(rval)
+ conversions = IMPLICIT_DATA_TYPE_CONVERSIONS[op]
+
+ if ltype not in conversions:
+ return error.VALUE
+ if rtype not in conversions[ltype]:
+ return error.VALUE
+
+ lconv = conversions[ltype][rtype]['left']
+ if lconv is not None:
+ lval = lconv(lval)
+ rconv = conversions[ltype][rtype]['right']
+ if rconv is not None:
+ rval = rconv(rval)
+
+ try:
+ result = OPERATOR_DICT[op](lval, rval)
+ if 'result' in conversions[ltype][rtype]:
+ result = conversions[ltype][rtype]['result'](result)
+ return result
+ except ZeroDivisionError:
+ return error.DIV_ZERO
+
+
+def evaluate_logic(op, lval, rval):
+ return OPERATOR_DICT[op](ExcelComparator(lval), rval)
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/statistical.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/statistical.py
new file mode 100644
index 0000000000000000000000000000000000000000..77eb226ec439e472b39016509ac727df988d9bf5
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/statistical.py
@@ -0,0 +1,201 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/statistical.js
+"""
+from __future__ import division
+from . import dispatcher
+from . import error
+from . import utils
+from .._compat import number_types, statistics
+from ..helper.number import to_number
+
+
+@dispatcher.register_for('AVERAGE')
+def AVERAGE(*args):
+ return statistics.mean(utils.inumbers(args, try_parse=True))
+
+
+@dispatcher.register_for('AVEDEV')
+def AVEDEV(*args):
+ args = utils.flatten(args)
+ average = AVERAGE(*args)
+ return sum(abs(arg - average) for arg in utils.iflatten(args)) / len(args)
+
+
+@dispatcher.register_for('AVERAGEA')
+def AVERAGEA(*args):
+ return statistics.mean(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('AVERAGEIF')
+def AVERAGEIF(args, criteria, average_range=None):
+ average_range = average_range or args
+ args = utils.flatten(args)
+ average_range = utils.iparse_number_array(utils.flatten(average_range))
+ if isinstance(average_range, error.XLError):
+ return average_range
+ average_range = list(average_range)
+ average_count = 0
+ result = 0
+ predicate = utils.parse_criteria(criteria)
+
+ for i, arg_i in enumerate(args):
+ if (predicate(args[i])):
+ result += average_range[i]
+ average_count += 1
+ return result / average_count
+
+
+@dispatcher.register_for('COUNT')
+def COUNT(*args):
+ return len(utils.flatten(args))
+
+
+@dispatcher.register_for('COUNTA')
+def COUNTA(*args):
+ return sum(1 for a in utils.iflatten(args) if (a is not None and a != ''))
+
+
+@dispatcher.register_for('COUNTBLANK')
+def COUNTBLANK(*args):
+ return sum(1 for a in utils.iflatten(args) if (a is None or a == ''))
+
+
+@dispatcher.register_for('COUNTIF')
+def COUNTIF(args, criteria):
+ predicate = utils.parse_criteria(criteria)
+ return sum(1 for a in utils.iflatten(args) if predicate(a))
+
+
+@dispatcher.register_for('MAX')
+def MAX(*args):
+ return max(utils.inumbers(args))
+
+
+@dispatcher.register_for('MAXA')
+def MAXA(*args):
+ return max(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('MEDIAN')
+def MEDIAN(*args):
+ return statistics.median(utils.inumbers(args, try_parse=True))
+
+
+@dispatcher.register_for('MIN')
+def MIN(*args):
+ return min(utils.inumbers(args))
+
+
+@dispatcher.register_for('MINA')
+def MINA(*args):
+ return min(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('MODE', 'MODE.SNGL')
+def MODE(*args):
+ return statistics.mode(utils.inumbers(args, try_parse=True))
+
+
+@dispatcher.register_for('VAR', 'VAR.S')
+def VAR(*args):
+ return statistics.variance(utils.inumbers(args))
+
+
+@dispatcher.register_for('VAR.P', 'VARP')
+def VAR_P(*args):
+ return statistics.pvariance(utils.inumbers(args))
+
+
+@dispatcher.register_for('VARA')
+def VARA(*args):
+ return statistics.variance(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('STDEV', 'STDEV.S')
+def STDEV(*args):
+ return statistics.stdev(utils.inumbers(args))
+
+
+@dispatcher.register_for('STDEV.P', 'STDEVP')
+def STDEV_P(*args):
+ return statistics.pstdev(utils.inumbers(args))
+
+
+@dispatcher.register_for('STDEVA')
+def STDEVA(*args):
+ return statistics.stdev(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('STDEVPA')
+def STDEVPA(*args):
+ return statistics.pstdev(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('HARMEAN')
+def HARMEAN(*args):
+ return statistics.harmonic_mean(utils.inumbers(args))
+
+
+@dispatcher.register_for('GEOMEAN')
+def GEOMEAN(*args):
+ return statistics.geometric_mean(utils.inumbers(args))
+
+
+@dispatcher.register_for('AVERAGEIFS')
+def AVERAGEIFS(average_range, *criteria):
+ if len(criteria) % 2 != 0:
+ return error.ERROR
+ range_and_preds = list(zip(criteria[::2], (utils.parse_criteria(criterion) for criterion in criteria[1::2])))
+ sum_value = 0
+ count_value = 0
+ for i, a in enumerate(average_range):
+ if all(pred(criteria_range[i]) for criteria_range, pred in range_and_preds):
+ sum_value += a
+ count_value += 1
+ if count_value == 0:
+ return error.DIV0
+ return sum_value / count_value
+
+
+@dispatcher.register_for('MAXIFS')
+def MAXIFS(sum_args, *criteria):
+ if len(criteria) % 2 != 0:
+ return error.ERROR
+ range_and_preds = list(zip(criteria[::2], (utils.parse_criteria(criterion) for criterion in criteria[1::2])))
+ b = 0
+ for i, a in enumerate(sum_args):
+ if all(pred(criteria_range[i]) for criteria_range,pred in range_and_preds):
+ if a > b:
+ b = a
+ return b
+
+
+@dispatcher.register_for('SLOPE')
+def SLOPE(*yx):
+ if len(yx) % 2 != 0:
+ return error.DIV_ZERO
+
+ midpoint = len(yx) // 2
+ ys = yx[:midpoint]
+ xs = yx[midpoint:]
+
+ if len(ys) != len(xs) or len(ys) == 0 or len(xs) == 0:
+ return error.DIV_ZERO
+
+ ys = list(ys)
+ xs = list(xs)
+
+ n = len(ys)
+ sum_x = sum(xs)
+ sum_y = sum(ys)
+ sum_x_sq = sum(x ** 2 for x in xs)
+ sum_xy = sum(x * y for x, y in zip(xs, ys))
+
+ denominator = (n * sum_x_sq) - (sum_x ** 2)
+ if denominator == 0:
+ return error.DIV_ZERO
+
+ slope = ((n * sum_xy) - (sum_x * sum_y)) / denominator
+ return slope
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/text.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/text.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aa4a0e23ac6d5548956c6a5b6d4ae7c2814dcaa
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/text.py
@@ -0,0 +1,122 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/math-trig.js
+"""
+from __future__ import division
+import math
+from functools import reduce
+import operator
+from . import dispatcher
+from . import error
+from . import utils
+from .utils import DEFAULT
+from ..helper.number import to_number
+from .._compat import string_types
+
+
+@dispatcher.register_for('CHAR')
+def CHAR(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return chr(number)
+
+
+@dispatcher.register_for('CODE')
+def CODE(char):
+ return ord(char)
+
+
+@dispatcher.register_for('CLEAN')
+def CLEAN(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return ''.join(c for c in text if ord(c) > 31)
+
+
+@dispatcher.register_for('CONCAT', 'CONCATENATE')
+def CONCATENATE(*args):
+ return ''.join(utils.iflatten(args))
+
+
+@dispatcher.register_for('LEN')
+def LEN(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ return 0
+ if not isinstance(text, string_types):
+ text = str(text)
+ return len(text)
+
+
+@dispatcher.register_for('LOWER')
+def LOWER(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return text.lower()
+
+
+@dispatcher.register_for('UPPER')
+def UPPER(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return text.upper()
+
+
+@dispatcher.register_for('PROPER')
+def PROPER(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return text.title()
+
+
+@dispatcher.register_for('SUBSTITUTE')
+def SUBSTITUTE(text, old_text, new_text, instance_num=DEFAULT):
+ if instance_num is not DEFAULT:
+ instance_num = utils.parse_number(instance_num)
+ if isinstance(instance_num, error.XLError):
+ return instance_num
+ if instance_num <= 0:
+ return error.VALUE
+ if not text or not old_text or not new_text:
+ return text
+ if instance_num is DEFAULT:
+ return text.replace(old_text, new_text)
+ else:
+ len_old = len(old_text)
+ ocurrences = 0
+ for i in range(len(text) - len_old + 1):
+ if text[i:i + len_old] == old_text:
+ ocurrences += 1
+ if ocurrences == instance_num:
+ return text[0:i] + new_text + text[i + len_old:]
+ return text
+
+
+@dispatcher.register_for('TEXTJOIN')
+def TEXTJOIN(delimiter, ignore_empty, *args):
+ if not isinstance(delimiter, string_types):
+ return error.VALUE
+ if ignore_empty:
+ gen = (words for words in utils.iflatten(args) if words is not None)
+ else:
+ gen = (words if words is not None else '' for words in utils.iflatten(args))
+ return delimiter.join(gen)
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/utils.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c71421016bc330733cf18b64c2fd88f4124083e
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/formulas/utils.py
@@ -0,0 +1,160 @@
+# -*- coding: utf-8 -*-
+from __future__ import division
+import re
+import fnmatch
+import itertools
+from .._compat import number_types, string_types
+from ..helper.number import to_number
+import operator
+from . import error
+import datetime
+import time
+from dateutil.parser import parse as to_date
+
+DEFAULT = lambda: 0
+
+OPERATOR_DICT = {
+ '+': operator.add,
+ '-': operator.sub,
+ '*': operator.mul,
+ '/': operator.truediv,
+ '>': operator.gt,
+ '<': operator.lt,
+ '<>': operator.ne,
+ '=': operator.eq,
+ '>=': operator.ge,
+ '<=': operator.le,
+}
+
+REGEX_CRITERIA = re.compile(r'(?P[\<\>\=]*)(?P.+)', re.UNICODE)
+
+
+def iflatten(iterable):
+ if not isinstance(iterable, (list, tuple)):
+ yield iterable
+ return
+ remainder = iter(iterable)
+ while True:
+ try:
+ first = next(remainder)
+ except StopIteration:
+ return
+ if isinstance(first, (list, tuple)):
+ remainder = itertools.chain(first, remainder)
+ else:
+ yield first
+
+
+def flatten(l):
+ return list(iflatten(l))
+
+
+def inumbers(l, try_parse=False, text_is_zero=False):
+ """ only the numbers """
+ for el in iflatten(l):
+ if isinstance(el, error.XLError):
+ raise el
+ if try_parse:
+ el = to_number(el)
+ if isinstance(el, number_types):
+ yield el
+ elif text_is_zero and isinstance(el, string_types):
+ yield 0
+
+
+def numbers(l, try_parse=False, text_is_zero=False):
+ return list(inumbers(l, try_parse=try_parse, text_is_zero=text_is_zero))
+
+
+def parse_number(string):
+ num = to_number(string)
+ if isinstance(num, number_types):
+ return num
+ if isinstance(num, error.XLError):
+ return num
+ return error.VALUE
+
+def parse_complex(string):
+ if string is None:
+ return 0
+ if isinstance(string, complex):
+ return string
+ if isinstance(string, error.XLError):
+ return string
+ try:
+ return complex(string.replace('i', 'j').replace(' ', ''))
+ except ValueError:
+ return error.NUM
+
+def iparse_number_array_aux(arr):
+ for el in arr:
+ yield parse_number(el)
+
+
+def iparse_number_array(arr):
+ if not arr:
+ return error.VALUE
+ return iparse_number_array_aux(arr)
+
+
+def parse_criteria(criteria):
+ match = REGEX_CRITERIA.match(criteria)
+ op = match.group('op')
+ val = match.group('val')
+ if op:
+ val = to_number(val)
+ op = OPERATOR_DICT[op]
+ return lambda a: op(a, val)
+ else:
+ if any(c in val for c in ('?', '*')):
+ # Then use fnmatch
+ return lambda a: fnmatch.fnmatch(val, a)
+ else:
+ return lambda a: a == to_number(val)
+
+
+def any_is_error(iterable):
+ return any(isinstance(el, error.XLError) for el in iterable)
+
+
+date_1900 = datetime.datetime(1900, 1, 1)
+epoch = datetime.datetime(1970, 1, 1)
+
+
+def epoch_seconds(date):
+ return (date - epoch).total_seconds()
+
+
+def parse_date(date):
+ if isinstance(date, error.XLError):
+ return date
+ if isinstance(date, datetime.datetime):
+ return date
+ date = to_number(date)
+ if isinstance(date, number_types):
+ if date < 0:
+ return error.NUM
+ if date < 1:
+ return date_1900
+ if date <= 60:
+ return epoch + datetime.timedelta(seconds=(epoch_seconds(date_1900) + (date - 1) * 86400))
+ return epoch + datetime.timedelta(seconds=(epoch_seconds(date_1900) + (date - 2) * 86400))
+ if isinstance(date, string_types):
+ try:
+ return to_date(date)
+ except ValueError:
+ pass
+ return error.VALUE
+
+
+def serialize_date(date):
+ date = parse_date(date)
+ if not isinstance(date, datetime.datetime):
+ return error.VALUE
+ if date == date_1900:
+ return 0
+ date = epoch_seconds(date) * 1000
+ d1900 = epoch_seconds(date_1900) * 1000
+ if date <= -2203891200000:
+ return (date - d1900) / 86400000 + 1
+ return (date - d1900) / 86400000 + 2
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/grammarparser/__init__.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/grammarparser/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/grammarparser/lexer.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/grammarparser/lexer.py
new file mode 100644
index 0000000000000000000000000000000000000000..8506f997c24c1000a57e7b7f408b85f69be824a5
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/grammarparser/lexer.py
@@ -0,0 +1,230 @@
+# -*- coding: utf-8 -*-
+import ply.lex as lex
+from ..formulas import error
+
+tokens = (
+ 'WHITESPACE',
+ 'STRING',
+ 'FUNCTION',
+ 'XLERROR',
+ 'ABSOLUTE_CELL',
+ 'MIXED_CELL',
+ 'RELATIVE_CELL',
+ 'VARIABLE',
+ 'NUMBER',
+ 'LBRACKET',
+ 'RBRACKET',
+ 'AMP',
+ 'SINGLESPACE',
+ 'DECIMAL',
+ 'COLON',
+ 'SEMICOLON',
+ 'COMMA',
+ 'BACKSLASH',
+ 'MULT',
+ 'DIV',
+ 'MINUS',
+ 'PLUS',
+ 'CARET',
+ 'LPAREN',
+ 'RPAREN',
+ 'GREATER',
+ 'LESS',
+ 'GREATEREQ',
+ 'LESSEQ',
+ 'NOTEQUAL',
+ 'QUOTATION',
+ 'APOSTROPHE',
+ 'EXCLAMATION',
+ 'EQUAL',
+ 'PERCENT',
+ 'HASH'
+)
+
+
+def t_WHITESPACE(t):
+ r'\s+'
+ pass # Ignore whitespace
+
+
+def t_STRING(t):
+ r'"(\\["]|[^"])*"|\'(\\[\']|[^\'])*\''
+ return t
+
+
+def t_FUNCTION(t):
+ r'([A-Za-z]{1,}[A-Za-z_0-9\.]+(?=[(]))|([A-Za-z\.]+(?=[(]))'
+ return t
+
+
+def t_XLERROR(t):
+ r'\#[A-Z0-9\/]+(\!|\?)?'
+ return t
+
+
+def t_ABSOLUTE_CELL(t):
+ r'\$[A-Za-z]+\$[0-9]+'
+ return t
+
+
+def t_MIXED_CELL(t):
+ r'(\$[A-Za-z]+[0-9]+)|([A-Za-z]+\$[0-9]+)'
+ return t
+
+
+def t_RELATIVE_CELL(t):
+ r'[A-Za-z]+[0-9]+'
+ return t
+
+
+def t_VARIABLE(t):
+ r'([A-Za-z]{1,}[A-Za-z_0-9]+)|([A-Za-z_]+)'
+ return t
+
+
+def t_NUMBER(t):
+ r'[0-9]+'
+ return t
+
+
+def t_LBRACKET(t):
+ r'\{'
+ return t
+
+
+def t_RBRACKET(t):
+ r'\}'
+ return t
+
+
+def t_AMP(t):
+ r'\&'
+ return t
+
+
+def t_SINGLESPACE(t):
+ r'\ '
+ return t
+
+
+def t_DECIMAL(t):
+ r'\.'
+ return t
+
+
+def t_COLON(t):
+ r'\:'
+ return t
+
+
+def t_SEMICOLON(t):
+ r'\;'
+ return t
+
+
+def t_COMMA(t):
+ r'\,'
+ return t
+
+
+def t_BACKSLASH(t):
+ r'\\'
+ return t
+
+
+def t_MULT(t):
+ r'\*'
+ return t
+
+
+def t_DIV(t):
+ r'\/'
+ return t
+
+
+def t_MINUS(t):
+ r'\-'
+ return t
+
+
+def t_PLUS(t):
+ r'\+'
+ return t
+
+
+def t_CARET(t):
+ r'\^'
+ return t
+
+
+def t_LPAREN(t):
+ r'\('
+ return t
+
+
+def t_RPAREN(t):
+ r'\)'
+ return t
+
+
+def t_NOTEQUAL(t):
+ r'\<\>'
+ return t
+
+
+def t_GREATEREQ(t):
+ r'\>\='
+ return t
+
+
+def t_LESSEQ(t):
+ r'\<\='
+ return t
+
+
+def t_GREATER(t):
+ r'\>'
+ return t
+
+
+def t_LESS(t):
+ r'\<'
+ return t
+
+
+def t_QUOTATION(t):
+ r'\"'
+ return t
+
+
+def t_APOSTROPHE(t):
+ r'\''
+ return t
+
+
+def t_EXCLAMATION(t):
+ r'\!'
+ return t
+
+
+def t_EQUAL(t):
+ r'\='
+ return t
+
+
+def t_PERCENT(t):
+ r'\%'
+ return t
+
+
+def t_HASH(t):
+ r'\#'
+ return t
+
+
+def t_error(t):
+ raise error.NAME
+
+
+def build():
+ return lex.lex()
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/grammarparser/parser.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/grammarparser/parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..5af280f0258592eedcbd7ba62befdd1a22c1f323
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/grammarparser/parser.py
@@ -0,0 +1,293 @@
+# -*- coding: utf-8 -*-
+from __future__ import division
+from __future__ import print_function
+import ply.yacc as yacc
+import ply.lex as lex
+from . import lexer
+from ..helper.number import to_number
+from .._compat import PY2, number_types, string_types
+from ..formulas import error, operators
+import math
+
+
+class Parser(object):
+ """
+ Base class for a lexer/parser that has the rules defined as methods
+ """
+ tokens = lexer.tokens
+ precedence = (
+ ('left', 'EQUAL'),
+ ('left', 'LESSEQ', 'GREATEREQ', 'NOTEQUAL'),
+ ('left', 'GREATER', 'LESS'),
+ ('left', 'PLUS', 'MINUS'),
+ ('left', 'MULT', 'DIV'),
+ ('left', 'CARET'),
+ ('left', 'AMP'),
+ ('left', 'PERCENT'),
+ ('left', 'UMINUS')
+ )
+
+ def __init__(self, debug=False, call_function=None, call_variable=None, call_cell_value=None, call_range_value=None, throw_error=None):
+ self.debug = debug
+ self.call_function = call_function
+ self.call_variable = call_variable
+ self.call_cell_value = call_cell_value
+ self.call_range_value = call_range_value
+ self.throw_error = throw_error
+ self.names = {}
+ try:
+ modname = os.path.split(os.path.splitext(__file__)[0])[
+ 1] + "_" + self.__class__.__name__
+ except:
+ modname = "parser" + "_" + self.__class__.__name__
+ self.debugfile = modname + ".dbg"
+ self.tabmodule = modname + "_" + "parsetab"
+
+ # Build the lexer and parser
+ self.lex = lex.lex(module=lexer, debug=self.debug)
+ self.yacc = yacc.yacc(module=self,
+ debug=self.debug,
+ debugfile=self.debugfile,
+ tabmodule=self.tabmodule)
+
+ def parse(self, input):
+ return self.yacc.parse(input)
+
+ def run(self):
+ while 1:
+ try:
+ s = raw_input('=')
+ except EOFError:
+ break
+ if not s:
+ continue
+ print(self.parse(s))
+
+
+class FormulaParser(Parser):
+
+ def p_expressions(self, p):
+ 'expressions : expression'
+ p[0] = p[1]
+
+ def p_expression_arithmetic_operator(self, p):
+ """
+ expression : expression PLUS expression
+ | expression MINUS expression
+ | expression MULT expression
+ | expression DIV expression
+ | expression AMP expression
+ """
+ if p[2] == '&':
+ p[0] = str(p[1]) + str(p[3])
+ else:
+ p[0] = operators.evaluate_arithmetic(p[2], p[1], p[3])
+
+ def p_expression_logical_operator(self, p):
+ """
+ expression : expression GREATER expression
+ | expression LESS expression
+ | expression GREATEREQ expression
+ | expression LESSEQ expression
+ | expression EQUAL expression
+ | expression NOTEQUAL expression
+ """
+ p[0] = operators.evaluate_logic(p[2], p[1], p[3])
+
+ def p_expression_uminus(self, p):
+ 'expression : MINUS expression %prec UMINUS'
+ p[0] = -p[2]
+
+ def p_expression_number(self, p):
+ """
+ expression : NUMBER
+ | DECIMAL NUMBER
+ | NUMBER DECIMAL NUMBER
+ | NUMBER CARET NUMBER
+ | NUMBER PERCENT
+ """
+ if len(p) == 2:
+ p[0] = to_number(p[1])
+ elif p[1] == '.':
+ p[0] = to_number('0.' + p[2])
+ elif p[2] == '.':
+ p[0] = to_number(p[1] + '.' + p[3])
+ elif p[2] == '^':
+ p[0] = to_number(p[1])**to_number(p[3])
+ elif p[2] == '%':
+ p[0] = to_number(p[1]) * 0.01
+
+ def p_expression_string(self, p):
+ """
+ expression : STRING
+ """
+ p[0] = p[1][1:-1]
+
+ def p_expression_function(self, p):
+ """
+ expression : FUNCTION LPAREN RPAREN
+ """
+ p[0] = self.call_function(p[1])
+
+ def p_expression_wargs(self, p):
+ """
+ expression : FUNCTION LPAREN expseqcomma RPAREN
+ | FUNCTION LPAREN expseqsemicolon RPAREN
+ | FUNCTION LPAREN expseqbackslash RPAREN
+ """
+ p[0] = self.call_function(p[1], p[3])
+
+ def p_expression_array(self, p):
+ """
+ expression : array
+ """
+ p[0] = p[1]
+
+ def p_array(self, p):
+ """
+ array : LBRACKET expseqsemicolon RBRACKET
+ | LBRACKET expseqcomma RBRACKET
+ | LBRACKET expseqbackslash RBRACKET
+ """
+ p[0] = p[2]
+
+ def p_expseq_semicolon(self, p):
+ """
+ expseqsemicolon : expression
+ | SEMICOLON SEMICOLON
+ | SEMICOLON expseqsemicolon
+ | expseqsemicolon SEMICOLON
+ | expseqsemicolon SEMICOLON expression
+ | expseqsemicolon SEMICOLON SEMICOLON expression
+ | expseqcomma SEMICOLON expseqcomma
+ | expseqbackslash SEMICOLON expseqbackslash
+ """
+ if len(p) == 2:
+ p[0] = [p[1]]
+ elif len(p) == 3:
+ if p[1] == ';' and p[2] == ';':
+ p[0] = [None, None, None]
+ elif p[1] == ';':
+ p[0] = [None] + p[2]
+ else:
+ p[0] = p[1] + [None]
+ elif p[2] == ';':
+ if p[3] == ';':
+ p[0] = p[1] + [None, p[4]]
+ else:
+ if str(p.slice[1]) in ('expseqcomma', 'expseqbackslash'):
+ p[0] = [p[1]] + [p[3]]
+ else:
+ p[0] = p[1] + [p[3]]
+
+ def p_expseq_comma(self, p):
+ """
+ expseqcomma : expression
+ | COMMA COMMA
+ | COMMA expseqcomma
+ | expseqcomma COMMA
+ | expseqcomma COMMA expression
+ | expseqcomma COMMA COMMA expression
+ """
+ if len(p) == 2: # expression
+ p[0] = [p[1]]
+ elif len(p) == 3:
+ if p[1] == ',' and p[2] == ',':
+ p[0] = [None, None, None]
+ elif p[1] == ',':
+ p[0] = [None] + p[2]
+ else:
+ p[0] = p[1] + [None]
+ elif p[2] == ',':
+ # expseqcomma COMMA COMMA expression
+ if p[3] == ',': # e.g. an empty function argument
+ p[0] = p[1] + [None, p[4]]
+ else:
+ p[0] = p[1] + [p[3]]
+
+ def p_expseq_backslash(self, p):
+ """
+ expseqbackslash : expression
+ | BACKSLASH BACKSLASH
+ | BACKSLASH expseqbackslash
+ | expseqbackslash BACKSLASH
+ | expseqbackslash BACKSLASH expression
+ | expseqbackslash BACKSLASH BACKSLASH expression
+ """
+ if len(p) == 2:
+ p[0] = [p[1]]
+ elif len(p) == 3:
+ if p[1] == '\\' and p[2] == '\\':
+ p[0] = [None, None, None]
+ elif p[1] == '\\':
+ p[0] = [None] + p[2]
+ else:
+ p[0] = p[1] + [None]
+ elif p[2] == '\\':
+ if p[3] == '\\':
+ p[0] = p[1] + [None, p[4]]
+ else:
+ p[0] = p[1] + [p[3]]
+
+ def p_xlerror(self, p):
+ """
+ expression : XLERROR
+ """
+ p[0] = self.throw_error(p[1])
+
+ def p_error(self, p):
+ """
+ SyntaxError
+ """
+ p[0] = self.throw_error(error.ERROR)
+
+ def p_expression_paren(self, p):
+ """
+ expression : LPAREN expression RPAREN
+ """
+ p[0] = p[2]
+
+ def p_expression_varseq(self, p):
+ """
+ expression : variable_sequence
+ """
+ p[0] = self.call_variable(p[1][0])
+
+ def p_variable(self, p):
+ """
+ variable_sequence : VARIABLE
+ """
+ p[0] = [p[1]]
+
+ def p_variable_seq(self, p):
+ """
+ variable_sequence : variable_sequence DECIMAL VARIABLE
+ """
+ p[0] = p[1] if isinstance(p[1], list) else [p[1]]
+ p[0].append(p[3])
+
+ def p_expression_cell(self, p):
+ """
+ expression : cell
+ """
+ p[0] = p[1]
+
+ def p_cell(self, p):
+ """
+ cell : ABSOLUTE_CELL
+ | RELATIVE_CELL
+ | MIXED_CELL
+ | ABSOLUTE_CELL COLON ABSOLUTE_CELL
+ | ABSOLUTE_CELL COLON RELATIVE_CELL
+ | ABSOLUTE_CELL COLON MIXED_CELL
+ | RELATIVE_CELL COLON ABSOLUTE_CELL
+ | RELATIVE_CELL COLON RELATIVE_CELL
+ | RELATIVE_CELL COLON MIXED_CELL
+ | MIXED_CELL COLON ABSOLUTE_CELL
+ | MIXED_CELL COLON RELATIVE_CELL
+ | MIXED_CELL COLON MIXED_CELL
+ """
+ if len(p) == 2:
+ p[0] = self.call_cell_value(p[1])
+ else:
+ p[0] = self.call_range_value(p[1], p[3])
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/helper/__init__.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/helper/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd655037edb91087d68fc3c90524acd5cd50b739
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/helper/__init__.py
@@ -0,0 +1 @@
+from . import number
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/helper/cell.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/helper/cell.py
new file mode 100644
index 0000000000000000000000000000000000000000..f318eb146248d22bdb69467bbff9ff6d090e5554
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/helper/cell.py
@@ -0,0 +1,102 @@
+# -*- coding: utf-8 -*-
+import re
+import math
+from collections import namedtuple
+from .._compat import integer_types, string_types
+
+
+def row_label_to_index(label):
+ try:
+ result = int(label)
+ except ValueError:
+ result = label
+ if isinstance(result, integer_types):
+ return max(result - 1, -1)
+ else:
+ return -1
+
+
+def row_index_to_label(row):
+ if row >= 0:
+ return str(row + 1)
+ return ''
+
+COLUMN_LABEL_BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+COLUMN_LABEL_BASE_LENGTH = len(COLUMN_LABEL_BASE)
+
+
+def column_label_to_index(label):
+ result = 0
+ if isinstance(label, string_types):
+ label = label.upper()
+ for i, j in zip(range(len(label)), range(len(label) - 1, -1, -1)):
+ result += (COLUMN_LABEL_BASE_LENGTH**j) * (COLUMN_LABEL_BASE.find(label[i]) + 1)
+ return result - 1
+
+
+def column_index_to_label(column):
+ result = ''
+ while column >= 0:
+ column = int(column)
+ result = chr((column % COLUMN_LABEL_BASE_LENGTH) + 97) + result
+ column = math.floor(column // COLUMN_LABEL_BASE_LENGTH) - 1
+
+ return result.upper()
+
+
+LABEL_EXTRACT_REGEXP = re.compile(r'^([$])?([A-Za-z]+)([$])?([0-9]+)$')
+
+ParsedLabel = namedtuple('ParsedLabel', ['index', 'label', 'is_absolute'])
+
+
+class Cell(object):
+ __slots__ = ('label', 'row', 'col')
+
+ def __init__(self, label=None, row=None, col=None):
+ self.label = label
+ self.row = row
+ self.col = col
+
+ def __getitem__(self, idx):
+ # Allowing you to do stuff like row, coll = mycell
+ if idx == 0:
+ return self.row
+ if idx == 1:
+ return self.col
+ raise IndexError
+
+ def __repr__(self):
+ return 'Cell(label=%(label)s, row=%(row)s, col=%(col)s)' % {'label': self.label,'row': self.row, 'col': self.col}
+
+
+def extract_label(label):
+ """
+ Extract cell coordinates.
+
+ @param label cell coordinates (e.g. 'A1', '$B6', '$N$98').
+ @returns Returns an list of objects.
+ """
+ match = LABEL_EXTRACT_REGEXP.match(label)
+ if (not isinstance(label, string_types)) or (match is None):
+ return []
+ label = label.upper()
+ column_abs, column, row_abs, row = match.groups()
+
+ return [
+ ParsedLabel(
+ index=row_label_to_index(row),
+ label=row,
+ is_absolute=row_abs == '$'
+ ),
+ ParsedLabel(
+ index=column_label_to_index(column),
+ label=column,
+ is_absolute=column_abs == '$',
+ )
+ ]
+
+
+def to_label(row, column):
+ row_label = ('$' if row.is_absolute else '') + row_index_to_label(row.index)
+ column_label = ('$' if column.is_absolute else '') + column_index_to_label(column.index)
+ return column_label + row_label
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/helper/number.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/helper/number.py
new file mode 100644
index 0000000000000000000000000000000000000000..561a37c68afd8284d23a3bd5d98e3d981428d955
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/helper/number.py
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+from .._compat import number_types, string_types
+
+def to_number(number):
+ if isinstance(number, number_types):
+ return number
+ if isinstance(number, string_types):
+ try:
+ return int(number)
+ except ValueError:
+ try:
+ return float(number)
+ except ValueError:
+ pass
+ if isinstance(number, bool):
+ return 1 if number else 0
+ return number
+
+def invert_number(number):
+ return -1 * to_number(number)
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/parser.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fa3c7b02243b978fc165aa48ebe3c7e5d881fb0
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/parser.py
@@ -0,0 +1,135 @@
+# -*- coding: utf-8 -*-
+from .tinyemitter import Emitter
+from . import formulas
+from .formulas import error as formulaserror
+from .grammarparser.parser import FormulaParser
+from .helper.cell import extract_label, to_label, Cell
+import traceback
+
+
+class Parser(Emitter):
+
+ def __init__(self, debug=False):
+ super(Parser, self).__init__()
+ self.variables = {'TRUE': True, 'FALSE': False, 'NULL': None}
+ self.functions = {}
+ self.debug = debug
+ self.parser = FormulaParser(call_function=self.call_function,
+ call_variable=self.call_variable,
+ call_cell_value=self.call_cell_value,
+ call_range_value=self.call_range_value,
+ throw_error=self._throw_error
+ )
+
+ def parse(self, expression):
+ result = None
+ error = None
+ try:
+ if expression == '':
+ result = ''
+ else:
+ result = self.parser.parse(expression)
+ except Exception as e:
+ if self.debug:
+ traceback.print_exc()
+ error = str(formulaserror.from_message(e))
+
+ if isinstance(result, formulaserror.XLError):
+ error = str(result)
+ result = None
+ return {'result': result, 'error': error}
+
+ def set_function(self, name, f):
+ self.functions[name] = f
+ return self
+
+ def get_function(self, name):
+ return self.functions[name]
+
+ def call_function(self, name, args=None):
+ if args is None:
+ args = []
+
+ fn = self.functions.get(name)
+ result = {'value': None} # get around 2.7 not having nonlocal
+ if fn is None:
+ fn = formulas.get_for(name)
+ if fn is None:
+ raise formulaserror.NAME
+ result['value'] = fn(*args)
+
+ def valsetter(new_value):
+ if new_value is not None:
+ result['value'] = new_value
+
+ self.emit('callFunction', name, args, valsetter)
+ return result['value']
+
+ def set_variable(self, name, v):
+ self.variables[name] = v
+ return self
+
+ def get_variable(self, name):
+ return self.variables[name]
+
+ def call_variable(self, name):
+ not_found = lambda : 0
+ value = self.variables.get(name, not_found)
+ result = {'value': value} # get around 2.7 not having nonlocal
+
+ def valsetter(new_value):
+ if new_value is not None:
+ result['value'] = new_value
+ self.emit('callVariable', name, valsetter)
+ if result['value'] is not_found:
+ raise formulaserror.NAME
+ return result['value']
+
+ def call_cell_value(self, label):
+ label = label.upper()
+ row, col = extract_label(label)
+ result = {'value': None} # get around 2.7 not having nonlocal
+
+ def valsetter(new_value):
+ if new_value is not None:
+ result['value'] = new_value
+
+ self.emit('callCellValue', Cell(label, row, col), valsetter)
+ return result['value']
+
+ def call_range_value(self, start_label, end_label):
+ if start_label is None or end_label is None:
+ return []
+ start_label = start_label.upper()
+ end_label = end_label.upper()
+
+ start_row, start_col = extract_label(start_label)
+ end_row, end_col = extract_label(end_label)
+ start_cell = Cell(start_label)
+ end_cell = Cell(end_label)
+
+ if start_row.index <= end_row.index:
+ start_cell.row = start_row
+ end_cell.row = end_row
+ else:
+ end_cell.row = start_row
+ start_cell.row = end_row
+
+ if start_col.index <= end_col.index:
+ start_cell.col = start_col
+ end_cell.col = end_col
+ else:
+ end_cell.col = start_col
+ start_cell.col = end_col
+
+ result = {'value': None} # get around 2.7 not having nonlocal
+
+ def valsetter(new_value):
+ if new_value is not None:
+ result['value'] = new_value
+
+ self.emit('callRangeValue', start_cell, end_cell, valsetter)
+ return result['value']
+
+ def _throw_error(self, error_name):
+ raise formulaserror.from_message(error_name)
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/tinyemitter.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/tinyemitter.py
new file mode 100644
index 0000000000000000000000000000000000000000..342e20f953de5eca4c5fbe9daa5c35237a39c8bc
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/hotxlfp/tinyemitter.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+"""
+A python version of tiny-emitter
+https://github.com/scottcorgan/tiny-emitter
+"""
+from collections import defaultdict, namedtuple
+
+
+Listener = namedtuple('Listener', ['fn', 'ctx'])
+
+
+class Emitter(object):
+
+ def __init__(self):
+ self._e = defaultdict(list)
+
+ def on(self, name, callback, ctx=None):
+ if ctx is None:
+ ctx = {}
+ self._e[name].append(Listener(fn=callback, ctx=ctx))
+ return self
+
+ def once(self, name, callback, ctx=None):
+ if ctx is None:
+ ctx = {}
+ def onetime_listener(*args, **ctx):
+ self.off(name, onetime_listener)
+ callback(*args, **ctx)
+ onetime_listener._ = callback
+ return self.on(name, onetime_listener, ctx)
+
+ def emit(self, name, *args):
+ listeners = self._e[name][:]
+ for listener in listeners:
+ listener.fn(*args, **listener.ctx)
+ return self
+
+ def off(self, name, callback=None):
+ events = self._e[name]
+ live_events = []
+ if events and callback:
+ for event in events:
+ if event.fn != callback and ((not hasattr(event.fn, '_')) or event.fn._ != callback):
+ live_events.append(event)
+
+ if live_events:
+ self._e[name] = live_events
+ else:
+ del self._e[name]
+ return self
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/requirements.txt b/tasks/tasksmith-a9cb6b87c28d/environment/source/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7b5737b809e138abf31ea4e428a167277dfd312a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/requirements.txt
@@ -0,0 +1,2 @@
+ply
+python-dateutil
diff --git a/tasks/tasksmith-a9cb6b87c28d/environment/source/setup.py b/tasks/tasksmith-a9cb6b87c28d/environment/source/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..223e5b4c3a454e79509c758bc268a27ded432b60
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/environment/source/setup.py
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+from io import open
+from setuptools import setup
+
+setup(
+ name='hotxlfp',
+ version='0.0.16',
+ packages=['hotxlfp', 'hotxlfp._compat', 'hotxlfp._compat.py3', 'hotxlfp.helper', 'hotxlfp.formulas', 'hotxlfp.grammarparser'],
+ license='MIT',
+ test_suite='tests',
+ author='Leonel Câmara',
+ author_email='leonelcamara@gmail.com',
+ url='https://github.com/aidhound/hotxlfp',
+ download_url='https://github.com/aidhound/hotxlfp/archive/0.0.16.tar.gz',
+ keywords=['excel', 'formula', 'parser'],
+ install_requires=['ply', 'python-dateutil'],
+ long_description='\n'.join(l for l in open('README.md', encoding="utf-8").readlines() if not l.startswith('[!')),
+ long_description_content_type='text/markdown',
+ classifiers=[
+ 'Development Status :: 3 - Alpha',
+ 'Intended Audience :: Developers',
+ 'License :: OSI Approved :: MIT License',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.9',
+ 'Programming Language :: Python :: 3.10',
+ 'Programming Language :: Python :: 3.11'
+ ]
+)
+
+
diff --git a/tasks/tasksmith-a9cb6b87c28d/instruction.md b/tasks/tasksmith-a9cb6b87c28d/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..d09bca1601a1faa5919b4a7bdd39c97aaba54e23
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/instruction.md
@@ -0,0 +1,22 @@
+Add a `TEXT` formula to the hotxlfp formula library. `TEXT(value, format_text)` converts a value to a formatted string using an Excel-style format string. It must be callable via `Parser().parse('TEXT(...)')`.
+
+**Non-string `format_text`** must return `error.NAME`.
+
+**Date/datetime values** are formatted using Excel date format tokens:
+- Year: `yyyy`/`yyy` → 4-digit, `yy` → 2-digit
+- Month: `mmmmm` → first letter of month name, `mmmm` → full name, `mmm` → 3-letter abbrev, `mm` → zero-padded number, `m` → bare number. When `h` or `hh` appears in the format, `mm`/`m` refer to minutes instead.
+- Day: `dddd` → full weekday, `ddd` → 3-letter, `dd` → zero-padded, `d` → bare number
+- Combined formats like `"dd-mm-yyy"` → `"03-04-2004"`, `"dddd, mmmm dd"` → `"Saturday, April 03"`
+
+**Numeric values** (int or float):
+- Prefix/suffix: non-pattern characters before/after the numeric pattern are preserved, e.g. `"$#,##0"` → `"$100"`, `"#,##0€"` → `"100€"`
+- Thousands separator: a `,` in the format enables grouping, e.g. `TEXT(100, "$#,##0")` → `"$100"`
+- Percentage: `%` in the format multiplies by 100 and appends `%`, e.g. `TEXT(0.85, "0%")` → `"85%"`
+- Decimal places: determined by the count of `0`/`#` digits after `.`, e.g. `TEXT(3.141592654, "0.000")` → `"3.142"`, `TEXT(8.9, "#.000")` → `"8.900"`, `TEXT(.631, "0.#")` → `"0.6"`
+- Rounding (no decimal): `TEXT(0.5, "0")` → `"1"`, `TEXT(0.4, "0")` → `"0"`, `TEXT(0.85, "0")` → `"1"`
+- Scientific notation: `"0.0E+00"` → `"2.5E+10"` for 25000000000
+- Fraction: `"???/???"` → exact fraction, e.g. `TEXT(100.25, "???/???")` → `"401/4"`; `"# ???/???"` → mixed number, e.g. `TEXT(5.25, "# ???/???")` → `"5 1/4"`
+
+**Non-numeric, non-date values** return `format_text` unchanged.
+
+Work in `/workspace`. Submit your fix in Python source files under `hotxlfp`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files.
diff --git a/tasks/tasksmith-a9cb6b87c28d/solution/reference/hotxlfp/formulas/text.py b/tasks/tasksmith-a9cb6b87c28d/solution/reference/hotxlfp/formulas/text.py
new file mode 100644
index 0000000000000000000000000000000000000000..baecebb7b2f848bf12af3697bab69e1feaa27dc9
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/solution/reference/hotxlfp/formulas/text.py
@@ -0,0 +1,207 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/math-trig.js
+"""
+from __future__ import division
+import math
+from functools import reduce
+import operator
+from . import dispatcher
+from . import error
+from . import utils
+from .utils import DEFAULT
+from ..helper.number import to_number
+from .._compat import string_types
+
+
+@dispatcher.register_for('CHAR')
+def CHAR(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return chr(number)
+
+
+@dispatcher.register_for('CODE')
+def CODE(char):
+ return ord(char)
+
+
+@dispatcher.register_for('CLEAN')
+def CLEAN(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return ''.join(c for c in text if ord(c) > 31)
+
+
+@dispatcher.register_for('CONCAT', 'CONCATENATE')
+def CONCATENATE(*args):
+ return ''.join(utils.iflatten(args))
+
+
+@dispatcher.register_for('LEN')
+def LEN(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ return 0
+ if not isinstance(text, string_types):
+ text = str(text)
+ return len(text)
+
+
+@dispatcher.register_for('LOWER')
+def LOWER(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return text.lower()
+
+
+@dispatcher.register_for('UPPER')
+def UPPER(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return text.upper()
+
+
+@dispatcher.register_for('PROPER')
+def PROPER(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return text.title()
+
+
+@dispatcher.register_for('SUBSTITUTE')
+def SUBSTITUTE(text, old_text, new_text, instance_num=DEFAULT):
+ if instance_num is not DEFAULT:
+ instance_num = utils.parse_number(instance_num)
+ if isinstance(instance_num, error.XLError):
+ return instance_num
+ if instance_num <= 0:
+ return error.VALUE
+ if not text or not old_text or not new_text:
+ return text
+ if instance_num is DEFAULT:
+ return text.replace(old_text, new_text)
+ else:
+ len_old = len(old_text)
+ ocurrences = 0
+ for i in range(len(text) - len_old + 1):
+ if text[i:i + len_old] == old_text:
+ ocurrences += 1
+ if ocurrences == instance_num:
+ return text[0:i] + new_text + text[i + len_old:]
+ return text
+
+
+@dispatcher.register_for('TEXTJOIN')
+def TEXTJOIN(delimiter, ignore_empty, *args):
+ if not isinstance(delimiter, string_types):
+ return error.VALUE
+ if ignore_empty:
+ gen = (words for words in utils.iflatten(args) if words is not None)
+ else:
+ gen = (words if words is not None else '' for words in utils.iflatten(args))
+ return delimiter.join(gen)
+
+import datetime
+import re
+from fractions import Fraction
+@dispatcher.register_for('TEXT')
+def TEXT(value, format_text):
+ if not isinstance(format_text, string_types):
+ return error.NAME
+ if isinstance(value, (datetime.datetime, datetime.date)):
+ value = datetime.datetime(year=value.year, month=value.month, day=value.day)
+
+ if 'h' in format_text or 'hh' in format_text:
+ format_text = re.sub(r'\bmm\b', '%M', format_text)
+ format_text = re.sub(r'\bm\b', str(value.minute), format_text)
+ else:
+ format_text = re.sub(r'\bmm\b', f"{value.month:02}", format_text)
+ format_text = re.sub(r'\bm\b', str(value.month), format_text)
+
+ format_mapping = {
+ "yyyy": "%Y", "yyy": "%Y", "yy": "%y",
+ "mmmmm": value.strftime('%B')[0], "mmmm": "%B", "mmm": "%b",
+ "dddd": "%A","ddd": "%a","dd": f"{value.day:02}", "d": str(value.day),
+ "hh": "%H", "h": str(value.hour or 12), "ss": "%S", "s": str(value.second or 12),
+ "am/pm": "%p", "a/p": value.strftime("%p")[0].lower()
+ }
+
+ for k, v in format_mapping.items():
+ format_text = re.sub(rf"\b{k}\b", v, format_text)
+
+ return value.strftime(format_text)
+
+ if isinstance(value, (int, float)):
+ prefix = re.match(r'^[^\d#0,]*', format_text).group()
+ suffix = re.search(r'[^\d#0,%]*$', format_text).group()
+
+ numeric_format = format_text[len(prefix):-len(suffix) if suffix else None]
+
+ is_percentage = '%' in numeric_format
+ if is_percentage:
+ value *= 100
+ numeric_format = numeric_format.replace('%', '')
+
+ numeric_format = numeric_format.replace(',', '')
+
+ if '.' in numeric_format:
+ num_decimal_places = len(numeric_format.split('.')[1].replace('#', '0'))
+ formatted_value = f"{value:.{num_decimal_places}f}"
+ else:
+ if value - int(value) >= 0.5:
+ formatted_value = str(math.ceil(value))
+ else:
+ formatted_value = str(math.floor(value))
+
+ if ',' in format_text:
+ parts = formatted_value.split('.')
+ parts[0] = '{:,}'.format(int(parts[0]))
+ formatted_value = '.'.join(parts)
+
+
+ if 'E' in numeric_format:
+ coefficient_format, exponent_format = numeric_format.split('E')
+
+ if '.' in coefficient_format:
+ num_decimal_places = len(coefficient_format.split('.')[1].replace('#', '0'))
+ formatted_value = f"{value:.{num_decimal_places}e}"
+ else:
+ formatted_value = f"{value:.0e}"
+
+ if '+' in exponent_format:
+ formatted_value = formatted_value.replace('e+', 'E+')
+ else:
+ formatted_value = formatted_value.replace('e', 'E')
+
+ return formatted_value
+
+ if '???/???' in format_text and '#' not in format_text:
+ frac_value = Fraction(value).limit_denominator()
+ return f"{frac_value.numerator}/{frac_value.denominator}"
+ elif '# ???/???' in format_text:
+ frac_value = (Fraction(value).limit_denominator()) - int(value)
+ return f"{int(value)} {frac_value.numerator}/{frac_value.denominator}"
+
+ return f"{prefix}{formatted_value}{suffix}" + ('%' if is_percentage else '')
+ else:
+ return format_text
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/solution/solve.sh b/tasks/tasksmith-a9cb6b87c28d/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..720d6b14171cc38504bcadcec830760fbb890ae0
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/solution/solve.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+set -eu
+mkdir -p -- /workspace/hotxlfp/formulas
+cp /solution/reference/hotxlfp/formulas/text.py /workspace/hotxlfp/formulas/text.py
diff --git a/tasks/tasksmith-a9cb6b87c28d/task.toml b/tasks/tasksmith-a9cb6b87c28d/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..edafed9513f7c4c525aade5c37a229dfca7711ec
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/task.toml
@@ -0,0 +1,229 @@
+schema_version = "1.3"
+
+[task]
+name = "repo2rlenv/tasksmith-a9cb6b87c28d"
+
+[metadata.repo2env]
+recipe = "tasksmith"
+recipe_version = "1"
+source_url = "https://github.com/aidhound/hotxlfp/pull/14"
+source_head = "3376ec579fbbc6a7280dec3a88ba0454fdc343ee"
+source_base = "4912e9c2218d70bc091ffb7d458dd762c264d4f2"
+workspace_strategy = "head_minus_source_patch"
+source_diff_sha256 = "2f68c20140d7d7aa7e2ced13cfad578d4b3ae9f00e06ebb534da3d9d615d1a84"
+acceptance_profile = "practical-generation-v1"
+upstream_test_policy = "retain"
+reward_kinds = [
+ "test_execution",
+]
+quality_status = "exported"
+fail_to_pass_count = 1
+pass_to_pass_count = 1
+tracked_files = [
+ "environment/Dockerfile",
+ "environment/source/.gitattributes",
+ "environment/source/.gitignore",
+ "environment/source/Dockerfile",
+ "environment/source/LICENSE",
+ "environment/source/README.md",
+ "environment/source/hotxlfp.egg-info/PKG-INFO",
+ "environment/source/hotxlfp.egg-info/SOURCES.txt",
+ "environment/source/hotxlfp.egg-info/dependency_links.txt",
+ "environment/source/hotxlfp.egg-info/requires.txt",
+ "environment/source/hotxlfp.egg-info/top_level.txt",
+ "environment/source/hotxlfp/__init__.py",
+ "environment/source/hotxlfp/_compat/__init__.py",
+ "environment/source/hotxlfp/_compat/py3/__init__.py",
+ "environment/source/hotxlfp/_compat/py3/statistics.py",
+ "environment/source/hotxlfp/formulas/__init__.py",
+ "environment/source/hotxlfp/formulas/dateandtime.py",
+ "environment/source/hotxlfp/formulas/engineering.py",
+ "environment/source/hotxlfp/formulas/error.py",
+ "environment/source/hotxlfp/formulas/financial.py",
+ "environment/source/hotxlfp/formulas/information.py",
+ "environment/source/hotxlfp/formulas/logic.py",
+ "environment/source/hotxlfp/formulas/lookupandreference.py",
+ "environment/source/hotxlfp/formulas/mathtrig.py",
+ "environment/source/hotxlfp/formulas/operators.py",
+ "environment/source/hotxlfp/formulas/statistical.py",
+ "environment/source/hotxlfp/formulas/text.py",
+ "environment/source/hotxlfp/formulas/utils.py",
+ "environment/source/hotxlfp/grammarparser/__init__.py",
+ "environment/source/hotxlfp/grammarparser/lexer.py",
+ "environment/source/hotxlfp/grammarparser/parser.py",
+ "environment/source/hotxlfp/helper/__init__.py",
+ "environment/source/hotxlfp/helper/cell.py",
+ "environment/source/hotxlfp/helper/number.py",
+ "environment/source/hotxlfp/parser.py",
+ "environment/source/hotxlfp/tinyemitter.py",
+ "environment/source/requirements.txt",
+ "environment/source/setup.py",
+ "solution/reference/hotxlfp/formulas/text.py",
+ "solution/solve.sh",
+ "tests/Dockerfile",
+ "tests/contract.json",
+ "tests/grade.py",
+ "tests/source/.coveragerc",
+ "tests/source/.gitattributes",
+ "tests/source/.gitignore",
+ "tests/source/.travis.yml",
+ "tests/source/Dockerfile",
+ "tests/source/LICENSE",
+ "tests/source/README.md",
+ "tests/source/SUPPORTED_FORMULAS.md",
+ "tests/source/changelog.md",
+ "tests/source/create_new_pip_version.md",
+ "tests/source/hotxlfp.egg-info/PKG-INFO",
+ "tests/source/hotxlfp.egg-info/SOURCES.txt",
+ "tests/source/hotxlfp.egg-info/dependency_links.txt",
+ "tests/source/hotxlfp.egg-info/requires.txt",
+ "tests/source/hotxlfp.egg-info/top_level.txt",
+ "tests/source/hotxlfp/__init__.py",
+ "tests/source/hotxlfp/_compat/__init__.py",
+ "tests/source/hotxlfp/_compat/py3/__init__.py",
+ "tests/source/hotxlfp/_compat/py3/statistics.py",
+ "tests/source/hotxlfp/formulas/__init__.py",
+ "tests/source/hotxlfp/formulas/dateandtime.py",
+ "tests/source/hotxlfp/formulas/engineering.py",
+ "tests/source/hotxlfp/formulas/error.py",
+ "tests/source/hotxlfp/formulas/financial.py",
+ "tests/source/hotxlfp/formulas/information.py",
+ "tests/source/hotxlfp/formulas/logic.py",
+ "tests/source/hotxlfp/formulas/lookupandreference.py",
+ "tests/source/hotxlfp/formulas/mathtrig.py",
+ "tests/source/hotxlfp/formulas/operators.py",
+ "tests/source/hotxlfp/formulas/statistical.py",
+ "tests/source/hotxlfp/formulas/text.py",
+ "tests/source/hotxlfp/formulas/utils.py",
+ "tests/source/hotxlfp/grammarparser/__init__.py",
+ "tests/source/hotxlfp/grammarparser/lexer.py",
+ "tests/source/hotxlfp/grammarparser/parser.py",
+ "tests/source/hotxlfp/helper/__init__.py",
+ "tests/source/hotxlfp/helper/cell.py",
+ "tests/source/hotxlfp/helper/number.py",
+ "tests/source/hotxlfp/parser.py",
+ "tests/source/hotxlfp/tinyemitter.py",
+ "tests/source/requirements.txt",
+ "tests/source/scripts/__init__.py",
+ "tests/source/scripts/allformulas.txt",
+ "tests/source/scripts/update_supported_formulas.py",
+ "tests/source/setup.py",
+ "tests/source/tests/__init__.py",
+ "tests/source/tests/test_dateandtime.py",
+ "tests/source/tests/test_engineering.py",
+ "tests/source/tests/test_error.py",
+ "tests/source/tests/test_financial.py",
+ "tests/source/tests/test_helper.py",
+ "tests/source/tests/test_information.py",
+ "tests/source/tests/test_lexer.py",
+ "tests/source/tests/test_logic.py",
+ "tests/source/tests/test_lookupandreference.py",
+ "tests/source/tests/test_mathtrig.py",
+ "tests/source/tests/test_operators.py",
+ "tests/source/tests/test_parser.py",
+ "tests/source/tests/test_statistical.py",
+ "tests/source/tests/test_text.py",
+ "tests/source/tests/test_tinyemitter.py",
+ "tests/source/tests/test_tinyexcel.py",
+ "tests/source/tests/test_vars.py",
+ "tests/test.sh",
+ "tests/test_driver.py",
+ "tests/test_results.py",
+]
+executable_files = [
+ "solution/solve.sh",
+ "tests/test.sh",
+]
+bundle_hash = "sha256:6655f19b6385b41a90f8b7037f7e9d0335a58bbb4361398540c9dbdf191c70e7"
+
+[metadata.repo2env.evaluation]
+schema_version = "1"
+status = "verified"
+stage = "complete"
+reason_codes = [
+ "quality_verified",
+]
+detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile."
+checked_at = "2026-11-20T09:18:36.176952Z"
+provenance = "unknown"
+subject_bundle_hash = "sha256:6655f19b6385b41a90f8b7037f7e9d0335a58bbb4361398540c9dbdf191c70e7"
+profile = "evidence-review-v2"
+source_task_path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/291ecbfea35b/candidates/a9cb6b87c28d/quality/revisions/r0/tasksmith-a9cb6b87c28d"
+source_task_toml_sha256 = "a4b709d6e29a90c2fa514d3b3e8a0ba7d863b82ed6fe150f8d221eee0a916f7d"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "quality_result"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/291ecbfea35b/candidates/a9cb6b87c28d/quality/result.json"
+sha256 = "73ba977fd14b1a6e2d21bdcc21b7232825a2e782a69b06dfc85d0082189025f2"
+subject_bundle_hash = "sha256:6655f19b6385b41a90f8b7037f7e9d0335a58bbb4361398540c9dbdf191c70e7"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "baseline"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/291ecbfea35b/candidates/a9cb6b87c28d/quality/trials/r0-baseline/tsbatch-195cc094e760-291ecbfea35b-q-a9cb6b87-r0-baseline/tasksmith-a9cb6b87c28d__ArncDip/result.json"
+sha256 = "48c78f67aa7368bc43e4e5abc6579a1941fdfa1589c2c2ea7a60e191d05fedd3"
+subject_bundle_hash = "sha256:6655f19b6385b41a90f8b7037f7e9d0335a58bbb4361398540c9dbdf191c70e7"
+harbor_task_checksum = "90e93fefd2e4004af251dbabf2b46f82d18b66317c204b429c00bdfd83be1603"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "oracle"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/291ecbfea35b/candidates/a9cb6b87c28d/quality/trials/r0-oracle/tsbatch-195cc094e760-291ecbfea35b-q-a9cb6b87-r0-oracle/tasksmith-a9cb6b87c28d__xF5a98H/result.json"
+sha256 = "901551516eecb75690b04d49c9635e8c92ca2950fda60e1300339cbdf5d9a14c"
+subject_bundle_hash = "sha256:6655f19b6385b41a90f8b7037f7e9d0335a58bbb4361398540c9dbdf191c70e7"
+harbor_task_checksum = "90e93fefd2e4004af251dbabf2b46f82d18b66317c204b429c00bdfd83be1603"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "probe"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/291ecbfea35b/candidates/a9cb6b87c28d/quality/trials/r0-probe0/tsbatch-195cc094e760-291ecbfea35b-q-a9cb6b87-r0-probe0/tasksmith-a9cb6b87c28d__xWYYUqJ/result.json"
+sha256 = "96c4ccbc98c1b9ea7ee874cf4b5603ad35f3393e7bc96bde5564a04f8662e5e9"
+subject_bundle_hash = "sha256:7aec988c23eed1d99f62dbf8bd2371597bad0b80a2189cb2778b89cfe2444269"
+harbor_task_checksum = "4c2a0c43d23f3115608a6037f04f92066c3442ee70a9c5e57415e6bce40319e8"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "probe"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/291ecbfea35b/candidates/a9cb6b87c28d/quality/trials/r0-probe1/tsbatch-195cc094e760-291ecbfea35b-q-a9cb6b87-r0-probe1/tasksmith-a9cb6b87c28d__qsuZ6ZS/result.json"
+sha256 = "4fe68f9ce12114ef1f793d2907fd980e9d26c65f9025d66d6d58219826d72f8d"
+subject_bundle_hash = "sha256:1d028518278e6fe748c3132ef13b7863ee9c6653ec628f84ef21cefec54be1ed"
+harbor_task_checksum = "b9e239590cd220ce6331088194ec2f4eb51c24fd5edc151b18e6c64ed382d946"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "rollout"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/291ecbfea35b/candidates/a9cb6b87c28d/quality/trials/r0-rollout/tsbatch-195cc094e760-291ecbfea35b-q-a9cb6b87-r0-rollout/tasksmith-a9cb6b87c28d__RNGvrJe/result.json"
+sha256 = "99066cad429938fa6fd18e007efd94eafcc19893dcc18cb2fda1b787dcad76e6"
+subject_bundle_hash = "sha256:6655f19b6385b41a90f8b7037f7e9d0335a58bbb4361398540c9dbdf191c70e7"
+harbor_task_checksum = "90e93fefd2e4004af251dbabf2b46f82d18b66317c204b429c00bdfd83be1603"
+
+[metadata.repo2env.quality_requirements]
+probe_focus = [
+ "general",
+]
+
+[environment]
+docker_image = "ghcr.io/younesbelkada/hat@sha256:15c02715d3f612f1b80e1e9681a8b6ca5bca98b468cdf1a0bfd4c843312c958e"
+cpus = 1
+memory_mb = 2048
+build_timeout_sec = 600
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 600
+user = "learner"
+network_mode = "no-network"
+
+[verifier]
+timeout_sec = 90
+user = "root"
+network_mode = "no-network"
+environment_mode = "separate"
+
+[verifier.environment]
+network_mode = "no-network"
+cpus = 1
+memory_mb = 512
+
+[[artifacts]]
+source = "/workspace/hotxlfp"
+exclude = [
+ "__pycache__",
+ "*.pyc",
+ ".pytest_cache",
+]
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/Dockerfile b/tasks/tasksmith-a9cb6b87c28d/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..10afcad2d5ee9e3dfe2b35f97252bf6af42303b4
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/Dockerfile
@@ -0,0 +1,10 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir setuptools==84.2.1 ply==3.11 python-dateutil==2.9.0.post0 six==1.16.0 pytest==9.0.3
+COPY source /workspace
+RUN python -m pip install --no-cache-dir --no-deps -e .
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
+RUN useradd -m -u 1001 grader
+COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/
+RUN chmod 755 /tests && chmod 644 /tests/*
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/contract.json b/tasks/tasksmith-a9cb6b87c28d/tests/contract.json
new file mode 100644
index 0000000000000000000000000000000000000000..d5d1ff7b6578676660f6a83c1e71bdb1fbdbb0f2
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/contract.json
@@ -0,0 +1 @@
+{"expected_passes": ["tests.test_text.TestText::test_text", "tests.test_text.TestText::test_textjoin"], "immutable_assets": {}, "optional_files": [], "pytest_args": [], "submitted_files": ["hotxlfp/__init__.py", "hotxlfp/_compat/__init__.py", "hotxlfp/_compat/py3/__init__.py", "hotxlfp/_compat/py3/statistics.py", "hotxlfp/formulas/__init__.py", "hotxlfp/formulas/dateandtime.py", "hotxlfp/formulas/engineering.py", "hotxlfp/formulas/error.py", "hotxlfp/formulas/financial.py", "hotxlfp/formulas/information.py", "hotxlfp/formulas/logic.py", "hotxlfp/formulas/lookupandreference.py", "hotxlfp/formulas/mathtrig.py", "hotxlfp/formulas/operators.py", "hotxlfp/formulas/statistical.py", "hotxlfp/formulas/text.py", "hotxlfp/formulas/utils.py", "hotxlfp/grammarparser/__init__.py", "hotxlfp/grammarparser/lexer.py", "hotxlfp/grammarparser/parser.py", "hotxlfp/helper/__init__.py", "hotxlfp/helper/cell.py", "hotxlfp/helper/number.py", "hotxlfp/parser.py", "hotxlfp/tinyemitter.py"], "submitted_roots": ["hotxlfp"], "test_paths": ["tests/test_text.py::TestText::test_text", "tests/test_text.py::TestText::test_textjoin"], "timeout_sec": 60}
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/grade.py b/tasks/tasksmith-a9cb6b87c28d/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..a803a55bfcc142c8279645ea59cea90b2a90918a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/grade.py
@@ -0,0 +1,196 @@
+"""Standalone trusted entry point; copied into each separate verifier image.
+
+No Repo2RLEnv installation is needed to grade an exported task. Submitted Python
+runs as an unprivileged user; this parent owns the result parser and reward file.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import os
+import signal
+import stat
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+
+def child_environment(temporary: str) -> dict[str, str]:
+ """Preserve prepared runtime assets without inheriting controller credentials."""
+ return {
+ **{
+ key: os.environ[key]
+ for key in (
+ "LD_LIBRARY_PATH",
+ "CUDA_VISIBLE_DEVICES",
+ "NVIDIA_VISIBLE_DEVICES",
+ "NVIDIA_DRIVER_CAPABILITIES",
+ "NCCL_SOCKET_IFNAME",
+ "GLOO_SOCKET_IFNAME",
+ "HF_HOME",
+ "HF_HUB_CACHE",
+ "HF_HUB_OFFLINE",
+ "TRANSFORMERS_OFFLINE",
+ "HF_DATASETS_OFFLINE",
+ )
+ if key in os.environ
+ },
+ "PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin",
+ "HOME": temporary,
+ "PYTHONDONTWRITEBYTECODE": "1",
+ "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
+ }
+
+
+def validate_submission(workspace: Path, contract: dict) -> None:
+ """Validate private staging and remove inert backups before importing Python."""
+ submitted = set(contract["submitted_files"])
+ backups: set[str] = set()
+ optional = submitted & set(contract.get("optional_files", []))
+ paths = submitted - optional
+ for relative in optional:
+ path = workspace / relative
+ if any(component.is_symlink() for component in (path, *path.parents)):
+ raise ValueError("Submitted source contains a symlink")
+ # Added standalone modules may be absent in the baseline. If supplied,
+ # apply the same regular-file and size checks as every required module.
+ if path.exists():
+ paths.add(relative)
+ roots = contract.get("submitted_roots", [])
+ immutable = contract.get("immutable_assets", {})
+ paths.update(immutable)
+ for relative in roots:
+ root = workspace / relative
+ if root.is_symlink() or not root.is_dir():
+ raise ValueError("Submitted source root is missing or linked")
+ for path in root.rglob("*"):
+ if path.is_symlink():
+ raise ValueError("Submitted source contains a symlink")
+ if path.is_dir():
+ continue
+ name = path.relative_to(workspace).as_posix()
+ if path.suffix != ".py" and name not in immutable:
+ if name not in submitted and path.name.endswith((".py.bak", ".py~")):
+ backups.add(name)
+ else:
+ raise ValueError("Only Python source files may be added")
+ paths.add(name)
+ for relative in sorted(paths):
+ path = workspace / relative
+ for component in (path, *path.parents):
+ if component.is_symlink():
+ raise ValueError("Submitted source contains a symlink")
+ if (
+ not path.is_file()
+ or not stat.S_ISREG(path.stat().st_mode)
+ or path.stat().st_size > 8 * 1024 * 1024
+ ):
+ raise ValueError("Submitted source is not a bounded regular file")
+ if (
+ relative in immutable
+ and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative]
+ ):
+ raise ValueError("Non-Python source assets must remain unchanged")
+ if relative not in backups:
+ # os.chown doesn't exist on Windows. This module only ever runs for
+ # real inside the Linux verifier container (every other path here
+ # is an absolute container path); the guard exists so the tests
+ # that call validate_submission() directly can run on a Windows
+ # host without touching real container-only ownership semantics.
+ if sys.platform != "win32":
+ os.chown(path, 0, 0)
+ path.chmod(0o644)
+ # Only the verifier's collected copy is cleaned. The learner workspace and
+ # archived submission retain their bytes. Validate every path first so a
+ # backup cannot bypass linked, oversized, required, or immutable file checks.
+ for relative in sorted(backups):
+ (workspace / relative).unlink()
+
+
+def main() -> None:
+ directory = Path("/tests")
+ parser_spec = importlib.util.spec_from_file_location(
+ "test_results", directory / "test_results.py"
+ )
+ parser = importlib.util.module_from_spec(parser_spec)
+ sys.modules[parser_spec.name] = parser
+ parser_spec.loader.exec_module(parser)
+ contract = json.loads((directory / "contract.json").read_text())
+ logs = Path("/logs/verifier")
+ logs.mkdir(parents=True, exist_ok=True)
+ logs.chmod(0o755)
+ reward = logs / "reward.txt"
+ reward.write_text("0\n")
+ reward.chmod(0o644)
+ try:
+ validate_submission(Path("/workspace"), contract)
+ except (ValueError, OSError) as exc:
+ (logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)}))
+ return
+ with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary:
+ working = Path(temporary)
+ if sys.platform != "win32": # os.chown doesn't exist on Windows; see above
+ os.chown(working, 1001, 1001)
+ working.chmod(0o700)
+ report = working / "results.xml"
+ command = [
+ sys.executable,
+ "-I",
+ "/tests/test_driver.py",
+ *contract["test_paths"],
+ *contract.get("pytest_args", []),
+ "-q",
+ "--tb=short",
+ "-p",
+ "no:cacheprovider",
+ f"--junitxml={report}",
+ ]
+ with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr:
+ process = subprocess.Popen(
+ command,
+ cwd="/workspace",
+ stdout=stdout,
+ stderr=stderr,
+ user=1001,
+ group=1001,
+ extra_groups=[],
+ start_new_session=True,
+ env=child_environment(temporary),
+ )
+ try:
+ code = process.wait(timeout=contract["timeout_sec"])
+ finally:
+ # Terminate descendants too: they must not keep modifying the
+ # child-owned report while the trusted parent checks it.
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024:
+ (logs / "result.json").write_text(
+ json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"})
+ )
+ return
+ text = report.read_text()
+ (logs / "results.xml").write_text(text)
+ try:
+ parsed = parser.parse_junit(text, returncode=code)
+ except ValueError as exc:
+ (logs / "result.json").write_text(
+ json.dumps({"passed": False, "returncode": code, "reason": str(exc)})
+ )
+ return
+ expected = set(contract["expected_passes"])
+ passed = code == 0 and bool(expected) and parsed.passed == expected
+ (logs / "result.json").write_text(
+ json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses})
+ )
+ reward.write_text("1\n" if passed else "0\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/.coveragerc b/tasks/tasksmith-a9cb6b87c28d/tests/source/.coveragerc
new file mode 100644
index 0000000000000000000000000000000000000000..e5449d05947a7f13efaa6909c1e034f3fe271b1f
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/.coveragerc
@@ -0,0 +1,4 @@
+[run]
+omit =
+ ./hotxlfp/_compat/*
+ ./hotxlfp/grammarparser/parser_FormulaParser_parsetab.py
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/.gitattributes b/tasks/tasksmith-a9cb6b87c28d/tests/source/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..d958a5de51d19738f7aa76832cae7e77ce47bcfc
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/.gitattributes
@@ -0,0 +1,22 @@
+* text=auto
+* text eol=lf
+
+# Source files
+# ============
+*.pxd text diff=python eol=lf
+*.py text diff=python eol=lf
+*.py3 text diff=python eol=lf
+*.pyw text diff=python eol=lf
+*.pyx text diff=python eol=lf
+*.md text eol=lf
+*.txt text eol=lf
+*.yml text eol=lf
+
+# Binary files
+# ============
+*.db binary
+*.p binary
+*.pkl binary
+*.pyc binary
+*.pyd binary
+*.pyo binary
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/.gitignore b/tasks/tasksmith-a9cb6b87c28d/tests/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..9e1907b0170e1ebb529c185094d17b7e45aa4db2
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/.gitignore
@@ -0,0 +1,100 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+pip-wheel-metadata/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+.hypothesis/
+.pytest_cache/
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+.python-version
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# ply
+*.dbg
+*.out
+*.tab
+*parsetab.py
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/.travis.yml b/tasks/tasksmith-a9cb6b87c28d/tests/source/.travis.yml
new file mode 100644
index 0000000000000000000000000000000000000000..399b84662940ae6f00ec93608a3b280682fb7864
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/.travis.yml
@@ -0,0 +1,18 @@
+dist: xenial
+language: python
+python:
+ - "2.7"
+ - "3.6"
+ - "3.7"
+
+install:
+ - pip install -r requirements.txt
+ - pip install coverage
+ - pip install codecov
+
+script:
+ - coverage run --source hotxlfp setup.py test
+
+after_success:
+ - coverage combine
+ - codecov
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/Dockerfile b/tasks/tasksmith-a9cb6b87c28d/tests/source/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f2f520314cb79b146aafd3b39c29a3c545d36506
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/Dockerfile
@@ -0,0 +1,8 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir setuptools==84.2.1 ply==3.11 python-dateutil==2.9.0.post0 six==1.16.0 pytest==9.0.3
+COPY . /workspace
+RUN python -m pip install --no-cache-dir --no-deps -e .
+RUN rm -rf /workspace/.git /root/.cache/pip
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/LICENSE b/tasks/tasksmith-a9cb6b87c28d/tests/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..784067a36810e86f20841e6469cf51822ec62ba7
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/LICENSE
@@ -0,0 +1,21 @@
+(The MIT License)
+
+Copyright (c) AidHound
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/README.md b/tasks/tasksmith-a9cb6b87c28d/tests/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..4b8d9b0eb2b388e19817cf0867843683b38b55c3
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/README.md
@@ -0,0 +1,71 @@
+# hotxlfp
+
+[](https://app.travis-ci.com/github/aidhound/hotxlfp) [](https://codecov.io/gh/aidhound/hotxlfp)
+
+hotxlfp intends to be a python version of the javascript [handsontable excel formula parser](https://github.com/handsontable/formula-parser) differences are acceptable to make it more pythonic or the function implementations more correct.
+
+# Install
+
+You can install using pip
+
+ pip install hotxlfp
+
+# Usage
+
+## Create a Parser
+
+ import hotxlfp
+ p = hotxlfp.Parser()
+
+## Parse excel formulas
+
+ p.parse('SUM(1,2,3)') # returns {'result': 6, 'error': None}
+
+It's also fine to use semi-colons as separators (they're used by excel depending on your locale)
+
+ p.parse('SUM(1;2;3)') # returns {'result': 6, 'error': None}
+
+## Custom functions
+
+Say you have a function called triple:
+
+ def triple(x):
+ return x*3
+
+You can teach the parser to use it with set_function
+
+ p.set_function('TRIPLE', triple)
+ p.parse('TRIPLE(2)') # returns {'result': 6, 'error': None}
+
+## Variables
+
+You can also set variables that you can then use in your formulas
+
+ p.set_variable('foo', 33)
+ p.parse('foo/3') # returns {'result': 11.0, 'error': None}
+
+# Contributing
+
+Fork the project
+
+## Installing Dependencies
+
+Depends on ply and python-dateutil.
+
+To install dependencies automatically using pip run:
+
+ pip install -r requirements.txt
+
+## Testing
+
+ python setup.py test
+
+## Coverage
+
+ coverage run --source hotxlfp setup.py test
+
+## Update SUPPORTED_FORMULAS.md
+
+Inside the project directory run:
+
+ python -m "scripts.update_supported_formulas"
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/SUPPORTED_FORMULAS.md b/tasks/tasksmith-a9cb6b87c28d/tests/source/SUPPORTED_FORMULAS.md
new file mode 100644
index 0000000000000000000000000000000000000000..b2fe4158dbc1a7c25f3b452d1a8a98935db76a83
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/SUPPORTED_FORMULAS.md
@@ -0,0 +1,488 @@
+# Supported Formulas - 144
+
+* ABS
+* ACOS
+* ACOSH
+* ACOT
+* ACOTH
+* AND
+* ARABIC
+* ASIN
+* ASINH
+* ATAN
+* ATAN2
+* ATANH
+* AVEDEV
+* AVERAGE
+* AVERAGEA
+* AVERAGEIF
+* AVERAGEIFS
+* BASE
+* CEILING
+* CEILING.MATH
+* CEILING.PRECISE
+* CHAR
+* CHOOSE
+* CLEAN
+* CODE
+* COMPLEX
+* CONCAT
+* CONCATENATE
+* COS
+* COSH
+* COT
+* COUNT
+* COUNTA
+* COUNTBLANK
+* COUNTIF
+* DATE
+* DATEDIF
+* DATEVALUE
+* DAY
+* DAYS
+* DEC2HEX
+* DECIMAL
+* DEGREES
+* DELTA
+* EDATE
+* ERROR.TYPE
+* EVEN
+* EXP
+* FACT
+* FACTDOUBLE
+* FALSE
+* FLOOR
+* FLOOR.MATH
+* FLOOR.PRECISE
+* GEOMEAN
+* HARMEAN
+* HEX2DEC
+* HOUR
+* IF
+* IFERROR
+* IFNA
+* IFS
+* IMAGINARY
+* IMREAL
+* INDEX
+* INT
+* ISBLANK
+* ISERR
+* ISERROR
+* ISEVEN
+* ISLOGICAL
+* ISNA
+* ISNONTEXT
+* ISNUMBER
+* ISODD
+* ISTEXT
+* LEN
+* LN
+* LOG
+* LOG10
+* LOWER
+* MATCH
+* MAX
+* MAXA
+* MAXIFS
+* MEDIAN
+* MIN
+* MINA
+* MINUTE
+* MOD
+* MODE
+* MODE.SNGL
+* MONTH
+* N
+* NA
+* NOT
+* NOW
+* ODD
+* OR
+* PI
+* POWER
+* PRODUCT
+* PROPER
+* PV
+* QUOTIENT
+* RADIANS
+* RAND
+* RANDBETWEEN
+* ROMAN
+* ROUND
+* ROUNDDOWN
+* ROUNDUP
+* SECOND
+* SIGN
+* SIN
+* SINH
+* SLOPE
+* SQRT
+* STDEV
+* STDEV.P
+* STDEV.S
+* STDEVA
+* STDEVP
+* STDEVPA
+* SUBSTITUTE
+* SUM
+* SUMIF
+* SUMIFS
+* SWITCH
+* T
+* TAN
+* TANH
+* TEXT
+* TEXTJOIN
+* TODAY
+* TRUE
+* UPPER
+* VAR
+* VAR.P
+* VAR.S
+* VARA
+* VARP
+* XOR
+* YEAR
+
+
+# Not Yet Supported Formulas - 338
+
+* ACCRINT
+* ACCRINTM
+* ADDRESS
+* AGGREGATE
+* AMORDEGRC
+* AMORLINC
+* AREAS
+* ARRAYTOTEXT
+* ASC
+* BAHTTEXT
+* BESSELI
+* BESSELJ
+* BESSELK
+* BESSELY
+* BETA.DIST
+* BETA.INV
+* BETADIST
+* BETAINV
+* BIN2DEC
+* BIN2HEX
+* BIN2OCT
+* BINOM.DIST
+* BINOM.DIST.RANGE
+* BINOM.INV
+* BINOMDIST
+* BITAND
+* BITLSHIFT
+* BITOR
+* BITRSHIFT
+* BITXOR
+* CALL
+* CELL
+* CHIDIST
+* CHIINV
+* CHISQ.DIST
+* CHISQ.DIST.RT
+* CHISQ.INV
+* CHISQ.INV.RT
+* CHISQ.TEST
+* CHITEST
+* COLUMN
+* COLUMNS
+* COMBIN
+* COMBINA
+* CONFIDENCE
+* CONFIDENCE.NORM
+* CONFIDENCE.T
+* CONVERT
+* CORREL
+* COTH
+* COUNTIFS
+* COUPDAYBS
+* COUPDAYS
+* COUPDAYSNC
+* COUPNCD
+* COUPNUM
+* COUPPCD
+* COVAR
+* COVARIANCE.P
+* COVARIANCE.S
+* CRITBINOM
+* CSC
+* CSCH
+* CUBEKPIMEMBER
+* CUBEMEMBER
+* CUBEMEMBERPROPERTY
+* CUBERANKEDMEMBER
+* CUBESET
+* CUBESETCOUNT
+* CUBEVALUE
+* CUMIPMT
+* CUMPRINC
+* DAVERAGE
+* DAYS360
+* DB
+* DBCS
+* DCOUNT
+* DCOUNTA
+* DDB
+* DEC2BIN
+* DEC2OCT
+* DEVSQ
+* DGET
+* DISC
+* DMAX
+* DMIN
+* DOLLAR
+* DOLLARDE
+* DOLLARFR
+* DPRODUCT
+* DSTDEV
+* DSTDEVP
+* DSUM
+* DURATION
+* DVAR
+* DVARP
+* EFFECT
+* ENCODEURL
+* EOMONTH
+* ERF
+* ERF.PRECISE
+* ERFC
+* ERFC.PRECISE
+* EUROCONVERT
+* EXACT
+* EXPON.DIST
+* EXPONDIST
+* F.DIST
+* F.DIST.RT
+* F.INV
+* F.INV.RT
+* F.TEST
+* FDIST
+* FILTER
+* FILTERXML
+* FIND, FINDBs
+* FINV
+* FISHER
+* FISHERINV
+* FIXED
+* FORECAST
+* FORECAST.ETS
+* FORECAST.ETS.CONFINT
+* FORECAST.ETS.SEASONALITY
+* FORECAST.ETS.STAT
+* FORECAST.LINEAR
+* FORMULATEXT
+* FREQUENCY
+* FTEST
+* FV
+* FVSCHEDULE
+* GAMMA
+* GAMMA.DIST
+* GAMMA.INV
+* GAMMADIST
+* GAMMAINV
+* GAMMALN
+* GAMMALN.PRECISE
+* GAUSS
+* GCD
+* GESTEP
+* GETPIVOTDATA
+* GROWTH
+* HEX2BIN
+* HEX2OCT
+* HLOOKUP
+* HYPERLINK
+* HYPGEOM.DIST
+* HYPGEOMDIST
+* IMABS
+* IMARGUMENT
+* IMCONJUGATE
+* IMCOS
+* IMCOSH
+* IMCOT
+* IMCSC
+* IMCSCH
+* IMDIV
+* IMEXP
+* IMLN
+* IMLOG10
+* IMLOG2
+* IMPOWER
+* IMPRODUCT
+* IMSEC
+* IMSECH
+* IMSIN
+* IMSINH
+* IMSQRT
+* IMSUB
+* IMSUM
+* IMTAN
+* INDIRECT
+* INFO
+* INTERCEPT
+* INTRATE
+* IPMT
+* IRR
+* ISFORMULA
+* ISO.CEILING
+* ISOWEEKNUM
+* ISPMT
+* ISREF
+* JIS
+* KURT
+* LARGE
+* LCM
+* LEFT, LEFTBs
+* LEN, LENBs
+* LET
+* LINEST
+* LOGEST
+* LOGINV
+* LOGNORM.DIST
+* LOGNORM.INV
+* LOGNORMDIST
+* LOOKUP
+* MDETERM
+* MDURATION
+* MID, MIDBs
+* MINIFS
+* MINVERSE
+* MIRR
+* MMULT
+* MODE.MULT
+* MROUND
+* MULTINOMIAL
+* MUNIT
+* NEGBINOM.DIST
+* NEGBINOMDIST
+* NETWORKDAYS
+* NETWORKDAYS.INTL
+* NOMINAL
+* NORM.DIST
+* NORM.INV
+* NORM.S.DIST
+* NORM.S.INV
+* NORMDIST
+* NORMINV
+* NORMSDIST
+* NORMSINV
+* NPER
+* NPV
+* NUMBERVALUE
+* OCT2BIN
+* OCT2DEC
+* OCT2HEX
+* ODDFPRICE
+* ODDFYIELD
+* ODDLPRICE
+* ODDLYIELD
+* OFFSET
+* PDURATION
+* PEARSON
+* PERCENTILE
+* PERCENTILE.EXC
+* PERCENTILE.INC
+* PERCENTRANK
+* PERCENTRANK.EXC
+* PERCENTRANK.INC
+* PERMUT
+* PERMUTATIONA
+* PHI
+* PHONETIC
+* PMT
+* POISSON
+* POISSON.DIST
+* PPMT
+* PRICE
+* PRICEDISC
+* PRICEMAT
+* PROB
+* QUARTILE
+* QUARTILE.EXC
+* QUARTILE.INC
+* RANDARRAY
+* RANK
+* RANK.AVG
+* RANK.EQ
+* RATE
+* RECEIVED
+* REGISTER.ID
+* REPLACE, REPLACEBs
+* REPT
+* RIGHT, RIGHTBs
+* ROW
+* ROWS
+* RRI
+* RSQ
+* RTD
+* SEARCH, SEARCHBs
+* SEC
+* SECH
+* SEQUENCE
+* SERIESSUM
+* SHEET
+* SHEETS
+* SKEW
+* SKEW.P
+* SLN
+* SMALL
+* SORT
+* SORTBY
+* SQRTPI
+* STANDARDIZE
+* STEYX
+* SUBTOTAL
+* SUMPRODUCT
+* SUMSQ
+* SUMX2MY2
+* SUMX2PY2
+* SUMXMY2
+* SYD
+* T.DIST
+* T.DIST.2T
+* T.DIST.RT
+* T.INV
+* T.INV.2T
+* T.TEST
+* TBILLEQ
+* TBILLPRICE
+* TBILLYIELD
+* TDIST
+* TIME
+* TIMEVALUE
+* TINV
+* TRANSPOSE
+* TREND
+* TRIM
+* TRIMMEAN
+* TRUNC
+* TTEST
+* TYPE
+* UNICHAR
+* UNICODE
+* UNIQUE
+* VALUE
+* VALUETOTEXT
+* VARPA
+* VDB
+* VLOOKUP
+* WEBSERVICE
+* WEEKDAY
+* WEEKNUM
+* WEIBULL
+* WEIBULL.DIST
+* WORKDAY
+* WORKDAY.INTL
+* XIRR
+* XLOOKUP
+* XMATCH
+* XNPV
+* YEARFRAC
+* YIELD
+* YIELDDISC
+* YIELDMAT
+* Z.TEST
+* ZTEST
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/changelog.md b/tasks/tasksmith-a9cb6b87c28d/tests/source/changelog.md
new file mode 100644
index 0000000000000000000000000000000000000000..eaa0861dfc47d7ed5a136f48ba91a0e956b03dcb
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/changelog.md
@@ -0,0 +1,78 @@
+# hotxlfp changelog
+
+## 0.0.16
+
+* Fixed SWITCH formula returning N/A when the default value was "falsy" (like 0)
+
+This release also brings a bunch of new supported formulas (Thanks Rodrigo Patrão)
+
+* Support for SIGN function
+* Support for SLOPE function
+* Support for MAXIFS function
+* Support for AVERAGEIFS
+* Support for SUMIFS function
+* Support for INT function
+* Support for EDATE fuction
+* Support for DATEDIF
+* Support for NOW function
+* Support for T, IMAGINARY and IMREAL
+
+## 0.0.15
+
+* Fixed bugs in FLOOR function.
+* Fixed bugs in ATAN2
+
+## 0.0.14
+
+* Fixed using a parser within a parser.
+
+## 0.0.13
+
+* Fixed comparison between floats and integers giving inverted results
+* Fixed decimals without a leading zero resulting in an error.
+
+## 0.0.12
+
+* Fix a bug where formulas using criteria like COUNTIF would not match correctly if the criteria had characters like ',' or ')'
+
+## 0.0.11
+
+* Support for RAND, RANDBETWEEN, DAYS, ISNONTEXT and COT
+
+## 0.0.10
+
+* Support for FACT, FACTDOUBLE, ARABIC, ROMAN and TODAY
+* Fixed bugs where the result was not an error when it should
+
+## 0.0.9
+
+* Fixed bug with undefined variables not returning a #NAME? error
+
+## 0.0.8
+
+* Fix bug with accented charactes in criteria
+
+## 0.0.7
+
+* Fixed a bug with criteria evaluation in formulas such as COUNTIF
+
+## 0.0.6
+
+* bidimensional arrays are now supported in some cases
+* INDEX is now supported
+* TEXTJOIN is now supported
+* SUBSTITUTE is now supported
+* LEN is now supported
+
+## 0.0.5
+
+* DECIMAL is now supported
+* BASE is now supported
+* ISLOGICAL is now supported
+* ISNUMBER is now supported
+* DATEVALUE is now supported
+* Much better implicit type conversion in operators
+
+## 0.0.4
+
+First version that actually works if you install using pip
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/create_new_pip_version.md b/tasks/tasksmith-a9cb6b87c28d/tests/source/create_new_pip_version.md
new file mode 100644
index 0000000000000000000000000000000000000000..618261c88c53f8d235d44721205b2e641c5ed44c
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/create_new_pip_version.md
@@ -0,0 +1,29 @@
+Send new version to pip
+
+# Make sure tests pass
+
+python setup.py test
+
+# Update supported formulas
+
+python -m "scripts.update_supported_formulas"
+
+# Edit
+
+setup.py - bump the version and download url
+changelog.md - put the change you made there
+
+# Create the release in github
+
+push everything to master
+
+Go to
+https://github.com/aidhound/hotxlfp/releases
+
+Press draft a new release
+
+# Upload to pypi
+
+python setup.py sdist bdist_wheel
+
+twine upload dist/*
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/PKG-INFO b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/PKG-INFO
new file mode 100644
index 0000000000000000000000000000000000000000..e8fa15068e9110a0df1f135def1e26e5203ddbfd
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/PKG-INFO
@@ -0,0 +1,174 @@
+Metadata-Version: 2.4
+Name: hotxlfp
+Version: 0.0.16
+Home-page: https://github.com/aidhound/hotxlfp
+Download-URL: https://github.com/aidhound/hotxlfp/archive/0.0.16.tar.gz
+Author: Leonel Câmara
+Author-email: leonelcamara@gmail.com
+License: MIT
+Keywords: excel,formula,parser
+Classifier: Development Status :: 3 - Alpha
+Classifier: Intended Audience :: Developers
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3.6
+Classifier: Programming Language :: Python :: 3.7
+Classifier: Programming Language :: Python :: 3.8
+Classifier: Programming Language :: Python :: 3.9
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Description-Content-Type: text/markdown
+License-File: LICENSE
+Requires-Dist: ply
+Requires-Dist: python-dateutil
+Dynamic: author
+Dynamic: author-email
+Dynamic: classifier
+Dynamic: description
+Dynamic: description-content-type
+Dynamic: download-url
+Dynamic: home-page
+Dynamic: keywords
+Dynamic: license
+Dynamic: license-file
+Dynamic: requires-dist
+
+# hotxlfp
+
+
+
+
+
+hotxlfp intends to be a python version of the javascript [handsontable excel formula parser](https://github.com/handsontable/formula-parser) differences are acceptable to make it more pythonic or the function implementations more correct.
+
+
+
+# Install
+
+
+
+You can install using pip
+
+
+
+ pip install hotxlfp
+
+
+
+# Usage
+
+
+
+## Create a Parser
+
+
+
+ import hotxlfp
+
+ p = hotxlfp.Parser()
+
+
+
+## Parse excel formulas
+
+
+
+ p.parse('SUM(1,2,3)') # returns {'result': 6, 'error': None}
+
+
+
+It's also fine to use semi-colons as separators (they're used by excel depending on your locale)
+
+
+
+ p.parse('SUM(1;2;3)') # returns {'result': 6, 'error': None}
+
+
+
+## Custom functions
+
+
+
+Say you have a function called triple:
+
+
+
+ def triple(x):
+
+ return x*3
+
+
+
+You can teach the parser to use it with set_function
+
+
+
+ p.set_function('TRIPLE', triple)
+
+ p.parse('TRIPLE(2)') # returns {'result': 6, 'error': None}
+
+
+
+## Variables
+
+
+
+You can also set variables that you can then use in your formulas
+
+
+
+ p.set_variable('foo', 33)
+
+ p.parse('foo/3') # returns {'result': 11.0, 'error': None}
+
+
+
+# Contributing
+
+
+
+Fork the project
+
+
+
+## Installing Dependencies
+
+
+
+Depends on ply and python-dateutil.
+
+
+
+To install dependencies automatically using pip run:
+
+
+
+ pip install -r requirements.txt
+
+
+
+## Testing
+
+
+
+ python setup.py test
+
+
+
+## Coverage
+
+
+
+ coverage run --source hotxlfp setup.py test
+
+
+
+## Update SUPPORTED_FORMULAS.md
+
+
+
+Inside the project directory run:
+
+
+
+ python -m "scripts.update_supported_formulas"
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/SOURCES.txt b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/SOURCES.txt
new file mode 100644
index 0000000000000000000000000000000000000000..2ae76ed658f493ff63b967f4b6ba46a772c9692a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/SOURCES.txt
@@ -0,0 +1,50 @@
+LICENSE
+README.md
+setup.py
+hotxlfp/__init__.py
+hotxlfp/parser.py
+hotxlfp/tinyemitter.py
+hotxlfp.egg-info/PKG-INFO
+hotxlfp.egg-info/SOURCES.txt
+hotxlfp.egg-info/dependency_links.txt
+hotxlfp.egg-info/requires.txt
+hotxlfp.egg-info/top_level.txt
+hotxlfp/_compat/__init__.py
+hotxlfp/_compat/py3/__init__.py
+hotxlfp/_compat/py3/statistics.py
+hotxlfp/formulas/__init__.py
+hotxlfp/formulas/dateandtime.py
+hotxlfp/formulas/engineering.py
+hotxlfp/formulas/error.py
+hotxlfp/formulas/financial.py
+hotxlfp/formulas/information.py
+hotxlfp/formulas/logic.py
+hotxlfp/formulas/lookupandreference.py
+hotxlfp/formulas/mathtrig.py
+hotxlfp/formulas/operators.py
+hotxlfp/formulas/statistical.py
+hotxlfp/formulas/text.py
+hotxlfp/formulas/utils.py
+hotxlfp/grammarparser/__init__.py
+hotxlfp/grammarparser/lexer.py
+hotxlfp/grammarparser/parser.py
+hotxlfp/helper/__init__.py
+hotxlfp/helper/cell.py
+hotxlfp/helper/number.py
+tests/test_dateandtime.py
+tests/test_engineering.py
+tests/test_error.py
+tests/test_financial.py
+tests/test_helper.py
+tests/test_information.py
+tests/test_lexer.py
+tests/test_logic.py
+tests/test_lookupandreference.py
+tests/test_mathtrig.py
+tests/test_operators.py
+tests/test_parser.py
+tests/test_statistical.py
+tests/test_text.py
+tests/test_tinyemitter.py
+tests/test_tinyexcel.py
+tests/test_vars.py
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/dependency_links.txt b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/dependency_links.txt
new file mode 100644
index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/requires.txt b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/requires.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7b5737b809e138abf31ea4e428a167277dfd312a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/requires.txt
@@ -0,0 +1,2 @@
+ply
+python-dateutil
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/top_level.txt b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..0de34161ab7e8edaefb08c848207ba687efdcc55
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp.egg-info/top_level.txt
@@ -0,0 +1 @@
+hotxlfp
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/__init__.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a3855a18ab02d153f7aade1197db525b6246c4f
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/__init__.py
@@ -0,0 +1 @@
+from .parser import Parser
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/_compat/__init__.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/_compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ed03b4f947c2749b7e351b25b5fc40939561b01
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/_compat/__init__.py
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+import sys
+
+PY2 = sys.version_info[0] == 2
+
+if PY2:
+ from .py3 import statistics
+ number_types = (int, long, float, complex)
+ integer_types = (int, long)
+ string_types = (str, unicode)
+else:
+ import statistics
+ number_types = (int, float, complex)
+ integer_types = (int,)
+ string_types = (str,)
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/_compat/py3/__init__.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/_compat/py3/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/_compat/py3/statistics.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/_compat/py3/statistics.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4b7688bbfd11a5df86965f5318cb7818f05d4e2
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/_compat/py3/statistics.py
@@ -0,0 +1,975 @@
+# -*- coding: utf-8 -*-
+# This was literally copied from python 3 source and made compatible with py2
+# See: https://github.com/python/cpython/blob/master/LICENSE
+"""
+Basic statistics module.
+
+This module provides functions for calculating statistics of data, including
+averages, variance, and standard deviation.
+
+Calculating averages
+--------------------
+
+================== =============================================
+Function Description
+================== =============================================
+mean Arithmetic mean (average) of data.
+geometric_mean Geometric mean of data.
+harmonic_mean Harmonic mean of data.
+median Median (middle value) of data.
+median_low Low median of data.
+median_high High median of data.
+median_grouped Median, or 50th percentile, of grouped data.
+mode Mode (most common value) of data.
+multimode List of modes (most common values of data).
+================== =============================================
+
+Calculate the arithmetic mean ("the average") of data:
+
+>>> mean([-1.0, 2.5, 3.25, 5.75])
+2.625
+
+
+Calculate the standard median of discrete data:
+
+>>> median([2, 3, 4, 5])
+3.5
+
+
+Calculate the median, or 50th percentile, of data grouped into class intervals
+centred on the data values provided. E.g. if your data points are rounded to
+the nearest whole number:
+
+>>> median_grouped([2, 2, 3, 3, 3, 4]) #doctest: +ELLIPSIS
+2.8333333333...
+
+This should be interpreted in this way: you have two data points in the class
+interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in
+the class interval 3.5-4.5. The median of these data points is 2.8333...
+
+
+Calculating variability or spread
+---------------------------------
+
+================== =============================================
+Function Description
+================== =============================================
+pvariance Population variance of data.
+variance Sample variance of data.
+pstdev Population standard deviation of data.
+stdev Sample standard deviation of data.
+================== =============================================
+
+Calculate the standard deviation of sample data:
+
+>>> stdev([2.5, 3.25, 5.5, 11.25, 11.75]) #doctest: +ELLIPSIS
+4.38961843444...
+
+If you have previously calculated the mean, you can pass it as the optional
+second argument to the four "spread" functions to avoid recalculating it:
+
+>>> data = [1, 2, 2, 4, 4, 4, 5, 6]
+>>> mu = mean(data)
+>>> pvariance(data, mu)
+2.5
+
+
+Exceptions
+----------
+
+A single exception is defined: StatisticsError is a subclass of ValueError.
+
+"""
+from __future__ import division
+
+__all__ = [ 'StatisticsError', 'NormalDist',
+ 'pstdev', 'pvariance', 'stdev', 'variance',
+ 'median', 'median_low', 'median_high', 'median_grouped',
+ 'mean', 'mode', 'multimode', 'harmonic_mean', 'fmean',
+ 'geometric_mean',
+ ]
+
+import math
+import numbers
+import random
+
+from fractions import Fraction
+from decimal import Decimal
+from itertools import groupby
+from bisect import bisect_left, bisect_right
+from math import hypot, sqrt, fabs, exp, erf, log, fsum
+from operator import itemgetter
+from collections import Counter
+
+tau = 6.283185307179586
+# === Exceptions ===
+
+class StatisticsError(ValueError):
+ pass
+
+
+# === Private utilities ===
+
+def _sum(data, start=0):
+ """_sum(data [, start]) -> (type, sum, count)
+
+ Return a high-precision sum of the given numeric data as a fraction,
+ together with the type to be converted to and the count of items.
+
+ If optional argument ``start`` is given, it is added to the total.
+ If ``data`` is empty, ``start`` (defaulting to 0) is returned.
+
+
+ Examples
+ --------
+
+ >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75)
+ (, Fraction(11, 1), 5)
+
+ Some sources of round-off error will be avoided:
+
+ # Built-in sum returns zero.
+ >>> _sum([1e50, 1, -1e50] * 1000)
+ (, Fraction(1000, 1), 3000)
+
+ Fractions and Decimals are also supported:
+
+ >>> from fractions import Fraction as F
+ >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)])
+ (, Fraction(63, 20), 4)
+
+ >>> from decimal import Decimal as D
+ >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")]
+ >>> _sum(data)
+ (, Fraction(6963, 10000), 4)
+
+ Mixed types are currently treated as an error, except that int is
+ allowed.
+ """
+ count = 0
+ n, d = _exact_ratio(start)
+ partials = {d: n}
+ partials_get = partials.get
+ T = _coerce(int, type(start))
+ for typ, values in groupby(data, type):
+ T = _coerce(T, typ) # or raise TypeError
+ for n,d in map(_exact_ratio, values):
+ count += 1
+ partials[d] = partials_get(d, 0) + n
+ if None in partials:
+ # The sum will be a NAN or INF. We can ignore all the finite
+ # partials, and just look at this special one.
+ total = partials[None]
+ assert not _isfinite(total)
+ else:
+ # Sum all the partial sums using builtin sum.
+ # FIXME is this faster if we sum them in order of the denominator?
+ total = sum(Fraction(n, d) for d, n in sorted(partials.items()))
+ return (T, total, count)
+
+
+def _isfinite(x):
+ try:
+ return x.is_finite() # Likely a Decimal.
+ except AttributeError:
+ return math.isfinite(x) # Coerces to float first.
+
+
+def _coerce(T, S):
+ """Coerce types T and S to a common type, or raise TypeError.
+
+ Coercion rules are currently an implementation detail. See the CoerceTest
+ test class in test_statistics for details.
+ """
+ # See http://bugs.python.org/issue24068.
+ assert T is not bool, "initial type T is bool"
+ # If the types are the same, no need to coerce anything. Put this
+ # first, so that the usual case (no coercion needed) happens as soon
+ # as possible.
+ if T is S: return T
+ # Mixed int & other coerce to the other type.
+ if S is int or S is bool: return T
+ if T is int: return S
+ # If one is a (strict) subclass of the other, coerce to the subclass.
+ if issubclass(S, T): return S
+ if issubclass(T, S): return T
+ # Ints coerce to the other type.
+ if issubclass(T, int): return S
+ if issubclass(S, int): return T
+ # Mixed fraction & float coerces to float (or float subclass).
+ if issubclass(T, Fraction) and issubclass(S, float):
+ return S
+ if issubclass(T, float) and issubclass(S, Fraction):
+ return T
+ # Any other combination is disallowed.
+ msg = "don't know how to coerce %s and %s"
+ raise TypeError(msg % (T.__name__, S.__name__))
+
+
+def _exact_ratio(x):
+ """Return Real number x to exact (numerator, denominator) pair.
+
+ >>> _exact_ratio(0.25)
+ (1, 4)
+
+ x is expected to be an int, Fraction, Decimal or float.
+ """
+ try:
+ # Optimise the common case of floats. We expect that the most often
+ # used numeric type will be builtin floats, so try to make this as
+ # fast as possible.
+ if type(x) is float or type(x) is Decimal:
+ return x.as_integer_ratio()
+ try:
+ # x may be an int, Fraction, or Integral ABC.
+ return (x.numerator, x.denominator)
+ except AttributeError:
+ try:
+ # x may be a float or Decimal subclass.
+ return x.as_integer_ratio()
+ except AttributeError:
+ # Just give up?
+ pass
+ except (OverflowError, ValueError):
+ # float NAN or INF.
+ assert not _isfinite(x)
+ return (x, None)
+ msg = "can't convert type '{}' to numerator/denominator"
+ raise TypeError(msg.format(type(x).__name__))
+
+
+def _convert(value, T):
+ """Convert value to given numeric type T."""
+ if type(value) is T:
+ # This covers the cases where T is Fraction, or where value is
+ # a NAN or INF (Decimal or float).
+ return value
+ if issubclass(T, int) and value.denominator != 1:
+ T = float
+ try:
+ # FIXME: what do we do if this overflows?
+ return T(value)
+ except TypeError:
+ if issubclass(T, Decimal):
+ return T(value.numerator)/T(value.denominator)
+ else:
+ raise
+
+
+def _find_lteq(a, x):
+ 'Locate the leftmost value exactly equal to x'
+ i = bisect_left(a, x)
+ if i != len(a) and a[i] == x:
+ return i
+ raise ValueError
+
+
+def _find_rteq(a, l, x):
+ 'Locate the rightmost value exactly equal to x'
+ i = bisect_right(a, x, lo=l)
+ if i != (len(a)+1) and a[i-1] == x:
+ return i-1
+ raise ValueError
+
+
+def _fail_neg(values, errmsg='negative value'):
+ """Iterate over values, failing if any are less than zero."""
+ for x in values:
+ if x < 0:
+ raise StatisticsError(errmsg)
+ yield x
+
+
+# === Measures of central tendency (averages) ===
+
+def mean(data):
+ """Return the sample arithmetic mean of data.
+
+ >>> mean([1, 2, 3, 4, 4])
+ 2.8
+
+ >>> from fractions import Fraction as F
+ >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
+ Fraction(13, 21)
+
+ >>> from decimal import Decimal as D
+ >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
+ Decimal('0.5625')
+
+ If ``data`` is empty, StatisticsError will be raised.
+ """
+ if iter(data) is data:
+ data = list(data)
+ n = len(data)
+ if n < 1:
+ raise StatisticsError('mean requires at least one data point')
+ T, total, count = _sum(data)
+ assert count == n
+ return _convert(total/n, T)
+
+def fmean(data):
+ """ Convert data to floats and compute the arithmetic mean.
+
+ This runs faster than the mean() function and it always returns a float.
+ The result is highly accurate but not as perfect as mean().
+ If the input dataset is empty, it raises a StatisticsError.
+
+ >>> fmean([3.5, 4.0, 5.25])
+ 4.25
+
+ """
+ try:
+ n = len(data)
+ except TypeError:
+ # Handle iterators that do not define __len__().
+ ndic = {'n': 0} # this was just n = 0
+ def count(x): # and in this function we had nonlocal n
+ ndic['n'] += 1
+ return x
+ total = fsum(map(count, data))
+ n = ndic['n']
+ else:
+ total = fsum(data)
+ try:
+ return total / n
+ except ZeroDivisionError:
+ raise StatisticsError('fmean requires at least one data point')
+
+def geometric_mean(data):
+ """Convert data to floats and compute the geometric mean.
+
+ Raises a StatisticsError if the input dataset is empty,
+ if it contains a zero, or if it contains a negative value.
+
+ No special efforts are made to achieve exact results.
+ (However, this may change in the future.)
+
+ >>> round(geometric_mean([54, 24, 36]), 9)
+ 36.0
+ """
+ try:
+ return exp(fmean(map(log, data)))
+ except ValueError:
+ raise StatisticsError('geometric mean requires a non-empty dataset '
+ ' containing positive numbers')
+
+def harmonic_mean(data):
+ """Return the harmonic mean of data.
+
+ The harmonic mean, sometimes called the subcontrary mean, is the
+ reciprocal of the arithmetic mean of the reciprocals of the data,
+ and is often appropriate when averaging quantities which are rates
+ or ratios, for example speeds. Example:
+
+ Suppose an investor purchases an equal value of shares in each of
+ three companies, with P/E (price/earning) ratios of 2.5, 3 and 10.
+ What is the average P/E ratio for the investor's portfolio?
+
+ >>> harmonic_mean([2.5, 3, 10]) # For an equal investment portfolio.
+ 3.6
+
+ Using the arithmetic mean would give an average of about 5.167, which
+ is too high.
+
+ If ``data`` is empty, or any element is less than zero,
+ ``harmonic_mean`` will raise ``StatisticsError``.
+ """
+ # For a justification for using harmonic mean for P/E ratios, see
+ # http://fixthepitch.pellucid.com/comps-analysis-the-missing-harmony-of-summary-statistics/
+ # http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2621087
+ if iter(data) is data:
+ data = list(data)
+ errmsg = 'harmonic mean does not support negative values'
+ n = len(data)
+ if n < 1:
+ raise StatisticsError('harmonic_mean requires at least one data point')
+ elif n == 1:
+ x = data[0]
+ if isinstance(x, (numbers.Real, Decimal)):
+ if x < 0:
+ raise StatisticsError(errmsg)
+ return x
+ else:
+ raise TypeError('unsupported type')
+ try:
+ T, total, count = _sum(1/x for x in _fail_neg(data, errmsg))
+ except ZeroDivisionError:
+ return 0
+ assert count == n
+ return _convert(n/total, T)
+
+
+# FIXME: investigate ways to calculate medians without sorting? Quickselect?
+def median(data):
+ """Return the median (middle value) of numeric data.
+
+ When the number of data points is odd, return the middle data point.
+ When the number of data points is even, the median is interpolated by
+ taking the average of the two middle values:
+
+ >>> median([1, 3, 5])
+ 3
+ >>> median([1, 3, 5, 7])
+ 4.0
+
+ """
+ data = sorted(data)
+ n = len(data)
+ if n == 0:
+ raise StatisticsError("no median for empty data")
+ if n%2 == 1:
+ return data[n//2]
+ else:
+ i = n//2
+ return (data[i - 1] + data[i])/2
+
+
+def median_low(data):
+ """Return the low median of numeric data.
+
+ When the number of data points is odd, the middle value is returned.
+ When it is even, the smaller of the two middle values is returned.
+
+ >>> median_low([1, 3, 5])
+ 3
+ >>> median_low([1, 3, 5, 7])
+ 3
+
+ """
+ data = sorted(data)
+ n = len(data)
+ if n == 0:
+ raise StatisticsError("no median for empty data")
+ if n%2 == 1:
+ return data[n//2]
+ else:
+ return data[n//2 - 1]
+
+
+def median_high(data):
+ """Return the high median of data.
+
+ When the number of data points is odd, the middle value is returned.
+ When it is even, the larger of the two middle values is returned.
+
+ >>> median_high([1, 3, 5])
+ 3
+ >>> median_high([1, 3, 5, 7])
+ 5
+
+ """
+ data = sorted(data)
+ n = len(data)
+ if n == 0:
+ raise StatisticsError("no median for empty data")
+ return data[n//2]
+
+
+def median_grouped(data, interval=1):
+ """Return the 50th percentile (median) of grouped continuous data.
+
+ >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
+ 3.7
+ >>> median_grouped([52, 52, 53, 54])
+ 52.5
+
+ This calculates the median as the 50th percentile, and should be
+ used when your data is continuous and grouped. In the above example,
+ the values 1, 2, 3, etc. actually represent the midpoint of classes
+ 0.5-1.5, 1.5-2.5, 2.5-3.5, etc. The middle value falls somewhere in
+ class 3.5-4.5, and interpolation is used to estimate it.
+
+ Optional argument ``interval`` represents the class interval, and
+ defaults to 1. Changing the class interval naturally will change the
+ interpolated 50th percentile value:
+
+ >>> median_grouped([1, 3, 3, 5, 7], interval=1)
+ 3.25
+ >>> median_grouped([1, 3, 3, 5, 7], interval=2)
+ 3.5
+
+ This function does not check whether the data points are at least
+ ``interval`` apart.
+ """
+ data = sorted(data)
+ n = len(data)
+ if n == 0:
+ raise StatisticsError("no median for empty data")
+ elif n == 1:
+ return data[0]
+ # Find the value at the midpoint. Remember this corresponds to the
+ # centre of the class interval.
+ x = data[n//2]
+ for obj in (x, interval):
+ if isinstance(obj, (str, bytes)):
+ raise TypeError('expected number but got %r' % obj)
+ try:
+ L = x - interval/2 # The lower limit of the median interval.
+ except TypeError:
+ # Mixed type. For now we just coerce to float.
+ L = float(x) - float(interval)/2
+
+ # Uses bisection search to search for x in data with log(n) time complexity
+ # Find the position of leftmost occurrence of x in data
+ l1 = _find_lteq(data, x)
+ # Find the position of rightmost occurrence of x in data[l1...len(data)]
+ # Assuming always l1 <= l2
+ l2 = _find_rteq(data, l1, x)
+ cf = l1
+ f = l2 - l1 + 1
+ return L + interval*(n/2 - cf)/f
+
+
+def mode(data):
+ """Return the most common data point from discrete or nominal data.
+
+ ``mode`` assumes discrete data, and returns a single value. This is the
+ standard treatment of the mode as commonly taught in schools:
+
+ >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
+ 3
+
+ This also works with nominal (non-numeric) data:
+
+ >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
+ 'red'
+
+ If there are multiple modes, return the first one encountered.
+
+ >>> mode(['red', 'red', 'green', 'blue', 'blue'])
+ 'red'
+
+ If *data* is empty, ``mode``, raises StatisticsError.
+
+ """
+ data = iter(data)
+ try:
+ return Counter(data).most_common(1)[0][0]
+ except IndexError:
+ raise StatisticsError('no mode for empty data')
+
+
+def multimode(data):
+ """ Return a list of the most frequently occurring values.
+
+ Will return more than one result if there are multiple modes
+ or an empty list if *data* is empty.
+
+ >>> multimode('aabbbbbbbbcc')
+ ['b']
+ >>> multimode('aabbbbccddddeeffffgg')
+ ['b', 'd', 'f']
+ >>> multimode('')
+ []
+
+ """
+ counts = Counter(iter(data)).most_common()
+ maxcount, mode_items = next(groupby(counts, key=itemgetter(1)), (0, []))
+ return list(map(itemgetter(0), mode_items))
+
+
+# === Measures of spread ===
+
+# See http://mathworld.wolfram.com/Variance.html
+# http://mathworld.wolfram.com/SampleVariance.html
+# http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
+#
+# Under no circumstances use the so-called "computational formula for
+# variance", as that is only suitable for hand calculations with a small
+# amount of low-precision data. It has terrible numeric properties.
+#
+# See a comparison of three computational methods here:
+# http://www.johndcook.com/blog/2008/09/26/comparing-three-methods-of-computing-standard-deviation/
+
+def _ss(data, c=None):
+ """Return sum of square deviations of sequence data.
+
+ If ``c`` is None, the mean is calculated in one pass, and the deviations
+ from the mean are calculated in a second pass. Otherwise, deviations are
+ calculated from ``c`` as given. Use the second case with care, as it can
+ lead to garbage results.
+ """
+ if c is None:
+ c = mean(data)
+ T, total, count = _sum((x-c)**2 for x in data)
+ # The following sum should mathematically equal zero, but due to rounding
+ # error may not.
+ U, total2, count2 = _sum((x-c) for x in data)
+ assert T == U and count == count2
+ total -= total2**2/len(data)
+ assert not total < 0, 'negative sum of square deviations: %f' % total
+ return (T, total)
+
+
+def variance(data, xbar=None):
+ """Return the sample variance of data.
+
+ data should be an iterable of Real-valued numbers, with at least two
+ values. The optional argument xbar, if given, should be the mean of
+ the data. If it is missing or None, the mean is automatically calculated.
+
+ Use this function when your data is a sample from a population. To
+ calculate the variance from the entire population, see ``pvariance``.
+
+ Examples:
+
+ >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
+ >>> variance(data)
+ 1.3720238095238095
+
+ If you have already calculated the mean of your data, you can pass it as
+ the optional second argument ``xbar`` to avoid recalculating it:
+
+ >>> m = mean(data)
+ >>> variance(data, m)
+ 1.3720238095238095
+
+ This function does not check that ``xbar`` is actually the mean of
+ ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
+ impossible results.
+
+ Decimals and Fractions are supported:
+
+ >>> from decimal import Decimal as D
+ >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
+ Decimal('31.01875')
+
+ >>> from fractions import Fraction as F
+ >>> variance([F(1, 6), F(1, 2), F(5, 3)])
+ Fraction(67, 108)
+
+ """
+ if iter(data) is data:
+ data = list(data)
+ n = len(data)
+ if n < 2:
+ raise StatisticsError('variance requires at least two data points')
+ T, ss = _ss(data, xbar)
+ return _convert(ss/(n-1), T)
+
+
+def pvariance(data, mu=None):
+ """Return the population variance of ``data``.
+
+ data should be an iterable of Real-valued numbers, with at least one
+ value. The optional argument mu, if given, should be the mean of
+ the data. If it is missing or None, the mean is automatically calculated.
+
+ Use this function to calculate the variance from the entire population.
+ To estimate the variance from a sample, the ``variance`` function is
+ usually a better choice.
+
+ Examples:
+
+ >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
+ >>> pvariance(data)
+ 1.25
+
+ If you have already calculated the mean of the data, you can pass it as
+ the optional second argument to avoid recalculating it:
+
+ >>> mu = mean(data)
+ >>> pvariance(data, mu)
+ 1.25
+
+ This function does not check that ``mu`` is actually the mean of ``data``.
+ Giving arbitrary values for ``mu`` may lead to invalid or impossible
+ results.
+
+ Decimals and Fractions are supported:
+
+ >>> from decimal import Decimal as D
+ >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
+ Decimal('24.815')
+
+ >>> from fractions import Fraction as F
+ >>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
+ Fraction(13, 72)
+
+ """
+ if iter(data) is data:
+ data = list(data)
+ n = len(data)
+ if n < 1:
+ raise StatisticsError('pvariance requires at least one data point')
+ T, ss = _ss(data, mu)
+ return _convert(ss/n, T)
+
+
+def stdev(data, xbar=None):
+ """Return the square root of the sample variance.
+
+ See ``variance`` for arguments and other details.
+
+ >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
+ 1.0810874155219827
+
+ """
+ var = variance(data, xbar)
+ try:
+ return var.sqrt()
+ except AttributeError:
+ return math.sqrt(var)
+
+
+def pstdev(data, mu=None):
+ """Return the square root of the population variance.
+
+ See ``pvariance`` for arguments and other details.
+
+ >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
+ 0.986893273527251
+
+ """
+ var = pvariance(data, mu)
+ try:
+ return var.sqrt()
+ except AttributeError:
+ return math.sqrt(var)
+
+## Normal Distribution #####################################################
+
+class NormalDist:
+ 'Normal distribution of a random variable'
+ # https://en.wikipedia.org/wiki/Normal_distribution
+ # https://en.wikipedia.org/wiki/Variance#Properties
+
+ __slots__ = {'mu': 'Arithmetic mean of a normal distribution',
+ 'sigma': 'Standard deviation of a normal distribution'}
+
+ def __init__(self, mu=0.0, sigma=1.0):
+ 'NormalDist where mu is the mean and sigma is the standard deviation.'
+ if sigma < 0.0:
+ raise StatisticsError('sigma must be non-negative')
+ self.mu = mu
+ self.sigma = sigma
+
+ @classmethod
+ def from_samples(cls, data):
+ 'Make a normal distribution instance from sample data.'
+ if not isinstance(data, (list, tuple)):
+ data = list(data)
+ xbar = fmean(data)
+ return cls(xbar, stdev(data, xbar))
+
+ def samples(self, n, seed=None):
+ 'Generate *n* samples for a given mean and standard deviation.'
+ gauss = random.gauss if seed is None else random.Random(seed).gauss
+ mu, sigma = self.mu, self.sigma
+ return [gauss(mu, sigma) for i in range(n)]
+
+ def pdf(self, x):
+ 'Probability density function. P(x <= X < x+dx) / dx'
+ variance = self.sigma ** 2.0
+ if not variance:
+ raise StatisticsError('pdf() not defined when sigma is zero')
+ return exp((x - self.mu)**2.0 / (-2.0*variance)) / sqrt(tau * variance)
+
+ def cdf(self, x):
+ 'Cumulative distribution function. P(X <= x)'
+ if not self.sigma:
+ raise StatisticsError('cdf() not defined when sigma is zero')
+ return 0.5 * (1.0 + erf((x - self.mu) / (self.sigma * sqrt(2.0))))
+
+ def inv_cdf(self, p):
+ '''Inverse cumulative distribution function. x : P(X <= x) = p
+
+ Finds the value of the random variable such that the probability of the
+ variable being less than or equal to that value equals the given probability.
+
+ This function is also called the percent point function or quantile function.
+ '''
+ if (p <= 0.0 or p >= 1.0):
+ raise StatisticsError('p must be in the range 0.0 < p < 1.0')
+ if self.sigma <= 0.0:
+ raise StatisticsError('cdf() not defined when sigma at or below zero')
+
+ # There is no closed-form solution to the inverse CDF for the normal
+ # distribution, so we use a rational approximation instead:
+ # Wichura, M.J. (1988). "Algorithm AS241: The Percentage Points of the
+ # Normal Distribution". Applied Statistics. Blackwell Publishing. 37
+ # (3): 477–484. doi:10.2307/2347330. JSTOR 2347330.
+
+ q = p - 0.5
+ if fabs(q) <= 0.425:
+ r = 0.180625 - q * q
+ num = (((((((2.5090809287301226727e+3 * r +
+ 3.3430575583588128105e+4) * r +
+ 6.7265770927008700853e+4) * r +
+ 4.5921953931549871457e+4) * r +
+ 1.3731693765509461125e+4) * r +
+ 1.9715909503065514427e+3) * r +
+ 1.3314166789178437745e+2) * r +
+ 3.3871328727963666080e+0) * q
+ den = (((((((5.2264952788528545610e+3 * r +
+ 2.8729085735721942674e+4) * r +
+ 3.9307895800092710610e+4) * r +
+ 2.1213794301586595867e+4) * r +
+ 5.3941960214247511077e+3) * r +
+ 6.8718700749205790830e+2) * r +
+ 4.2313330701600911252e+1) * r +
+ 1.0)
+ x = num / den
+ return self.mu + (x * self.sigma)
+ r = p if q <= 0.0 else 1.0 - p
+ r = sqrt(-log(r))
+ if r <= 5.0:
+ r = r - 1.6
+ num = (((((((7.74545014278341407640e-4 * r +
+ 2.27238449892691845833e-2) * r +
+ 2.41780725177450611770e-1) * r +
+ 1.27045825245236838258e+0) * r +
+ 3.64784832476320460504e+0) * r +
+ 5.76949722146069140550e+0) * r +
+ 4.63033784615654529590e+0) * r +
+ 1.42343711074968357734e+0)
+ den = (((((((1.05075007164441684324e-9 * r +
+ 5.47593808499534494600e-4) * r +
+ 1.51986665636164571966e-2) * r +
+ 1.48103976427480074590e-1) * r +
+ 6.89767334985100004550e-1) * r +
+ 1.67638483018380384940e+0) * r +
+ 2.05319162663775882187e+0) * r +
+ 1.0)
+ else:
+ r = r - 5.0
+ num = (((((((2.01033439929228813265e-7 * r +
+ 2.71155556874348757815e-5) * r +
+ 1.24266094738807843860e-3) * r +
+ 2.65321895265761230930e-2) * r +
+ 2.96560571828504891230e-1) * r +
+ 1.78482653991729133580e+0) * r +
+ 5.46378491116411436990e+0) * r +
+ 6.65790464350110377720e+0)
+ den = (((((((2.04426310338993978564e-15 * r +
+ 1.42151175831644588870e-7) * r +
+ 1.84631831751005468180e-5) * r +
+ 7.86869131145613259100e-4) * r +
+ 1.48753612908506148525e-2) * r +
+ 1.36929880922735805310e-1) * r +
+ 5.99832206555887937690e-1) * r +
+ 1.0)
+ x = num / den
+ if q < 0.0:
+ x = -x
+ return self.mu + (x * self.sigma)
+
+ def overlap(self, other):
+ '''Compute the overlapping coefficient (OVL) between two normal distributions.
+
+ Measures the agreement between two normal probability distributions.
+ Returns a value between 0.0 and 1.0 giving the overlapping area in
+ the two underlying probability density functions.
+
+ >>> N1 = NormalDist(2.4, 1.6)
+ >>> N2 = NormalDist(3.2, 2.0)
+ >>> N1.overlap(N2)
+ 0.8035050657330205
+ '''
+ # See: "The overlapping coefficient as a measure of agreement between
+ # probability distributions and point estimation of the overlap of two
+ # normal densities" -- Henry F. Inman and Edwin L. Bradley Jr
+ # http://dx.doi.org/10.1080/03610928908830127
+ if not isinstance(other, NormalDist):
+ raise TypeError('Expected another NormalDist instance')
+ X, Y = self, other
+ if (Y.sigma, Y.mu) < (X.sigma, X.mu): # sort to assure commutativity
+ X, Y = Y, X
+ X_var, Y_var = X.variance, Y.variance
+ if not X_var or not Y_var:
+ raise StatisticsError('overlap() not defined when sigma is zero')
+ dv = Y_var - X_var
+ dm = fabs(Y.mu - X.mu)
+ if not dv:
+ return 1.0 - erf(dm / (2.0 * X.sigma * sqrt(2.0)))
+ a = X.mu * Y_var - Y.mu * X_var
+ b = X.sigma * Y.sigma * sqrt(dm**2.0 + dv * log(Y_var / X_var))
+ x1 = (a + b) / dv
+ x2 = (a - b) / dv
+ return 1.0 - (fabs(Y.cdf(x1) - X.cdf(x1)) + fabs(Y.cdf(x2) - X.cdf(x2)))
+
+ @property
+ def mean(self):
+ 'Arithmetic mean of the normal distribution.'
+ return self.mu
+
+ @property
+ def stdev(self):
+ 'Standard deviation of the normal distribution.'
+ return self.sigma
+
+ @property
+ def variance(self):
+ 'Square of the standard deviation.'
+ return self.sigma ** 2.0
+
+ def __add__(x1, x2):
+ '''Add a constant or another NormalDist instance.
+
+ If *other* is a constant, translate mu by the constant,
+ leaving sigma unchanged.
+
+ If *other* is a NormalDist, add both the means and the variances.
+ Mathematically, this works only if the two distributions are
+ independent or if they are jointly normally distributed.
+ '''
+ if isinstance(x2, NormalDist):
+ return NormalDist(x1.mu + x2.mu, hypot(x1.sigma, x2.sigma))
+ return NormalDist(x1.mu + x2, x1.sigma)
+
+ def __sub__(x1, x2):
+ '''Subtract a constant or another NormalDist instance.
+
+ If *other* is a constant, translate by the constant mu,
+ leaving sigma unchanged.
+
+ If *other* is a NormalDist, subtract the means and add the variances.
+ Mathematically, this works only if the two distributions are
+ independent or if they are jointly normally distributed.
+ '''
+ if isinstance(x2, NormalDist):
+ return NormalDist(x1.mu - x2.mu, hypot(x1.sigma, x2.sigma))
+ return NormalDist(x1.mu - x2, x1.sigma)
+
+ def __mul__(x1, x2):
+ '''Multiply both mu and sigma by a constant.
+
+ Used for rescaling, perhaps to change measurement units.
+ Sigma is scaled with the absolute value of the constant.
+ '''
+ return NormalDist(x1.mu * x2, x1.sigma * fabs(x2))
+
+ def __truediv__(x1, x2):
+ '''Divide both mu and sigma by a constant.
+
+ Used for rescaling, perhaps to change measurement units.
+ Sigma is scaled with the absolute value of the constant.
+ '''
+ return NormalDist(x1.mu / x2, x1.sigma / fabs(x2))
+
+ def __pos__(x1):
+ 'Return a copy of the instance.'
+ return NormalDist(x1.mu, x1.sigma)
+
+ def __neg__(x1):
+ 'Negates mu while keeping sigma the same.'
+ return NormalDist(-x1.mu, x1.sigma)
+
+ __radd__ = __add__
+
+ def __rsub__(x1, x2):
+ 'Subtract a NormalDist from a constant or another NormalDist.'
+ return -(x1 - x2)
+
+ __rmul__ = __mul__
+
+ def __eq__(x1, x2):
+ 'Two NormalDist objects are equal if their mu and sigma are both equal.'
+ if not isinstance(x2, NormalDist):
+ return NotImplemented
+ return (x1.mu, x2.sigma) == (x2.mu, x2.sigma)
+
+ def __repr__(self):
+ return '(%(name)s)(mu=%(mu)s, sigma=%(sigma)s)' % {'name':type(self).__name__, 'sigma': repr(self.sigma), 'mu': repr(self.mu)}
+
+
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/__init__.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..169bc396dadfa3bb6f3d0c29facb161c7357f4d5
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/__init__.py
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+
+
+class Dispatcher(object):
+
+ def __init__(self):
+ self._registry_ = {}
+
+ def register_for(self, *fnames):
+ def wrap(dispatch_fn):
+ for fname in fnames:
+ self._registry_[fname] = dispatch_fn
+ return dispatch_fn
+ return wrap
+
+ def get_for(self, fname):
+ try:
+ return self._registry_[fname]
+ except KeyError:
+ raise SyntaxError('Function not found for %s' % fname)
+
+ def __iter__(self):
+ return iter(registry.values())
+
+
+dispatcher = Dispatcher()
+
+
+def get_for(fname):
+ return dispatcher.get_for(fname)
+
+
+def supported():
+ """ Get a list of supported formulas """
+ return sorted(dispatcher._registry_.keys())
+
+
+def is_supported(fname):
+ return fname in dispatcher._registry_
+
+
+from . import error
+from . import information
+from . import logic
+from . import statistical
+from . import mathtrig
+from . import text
+from . import dateandtime
+from . import engineering
+from . import financial
+from . import lookupandreference
+
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/dateandtime.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/dateandtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..02fa8d489bef3fd544c07d217ba6ea566b57a89a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/dateandtime.py
@@ -0,0 +1,173 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/date-time.js
+"""
+from . import dispatcher
+from . import error
+from . import utils
+import datetime
+import calendar
+
+
+@dispatcher.register_for('DATE')
+def DATE(year, month, day):
+ year = utils.parse_number(year)
+ month = utils.parse_number(month)
+ day = utils.parse_number(day)
+ if utils.any_is_error((year, month, day)):
+ return error.VALUE
+ if year < 1900:
+ year += 1900
+ return datetime.datetime(year, month, day)
+
+
+@dispatcher.register_for('DATEVALUE')
+def DATEVALUE(date):
+ return utils.serialize_date(date)
+
+
+@dispatcher.register_for('YEAR')
+def YEAR(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.year
+
+
+@dispatcher.register_for('MONTH')
+def MONTH(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.month
+
+
+@dispatcher.register_for('DAY')
+def DAY(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.day
+
+
+@dispatcher.register_for('HOUR')
+def HOUR(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.hour
+
+
+@dispatcher.register_for('MINUTE')
+def MINUTE(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.minute
+
+
+@dispatcher.register_for('SECOND')
+def SECOND(serial_number):
+ serial_number = utils.parse_date(serial_number)
+ if isinstance(serial_number, error.XLError):
+ return serial_number
+ return serial_number.second
+
+
+@dispatcher.register_for('TODAY')
+def TODAY():
+ today = datetime.date.today()
+ return datetime.datetime(today.year, today.month, today.day)
+
+
+@dispatcher.register_for('DAYS')
+def DAYS(end_date, start_date):
+ end_date = utils.parse_date(end_date)
+ start_date = utils.parse_date(start_date)
+ if utils.any_is_error((end_date, start_date)):
+ return error.VALUE
+ return utils.serialize_date(end_date) - utils.serialize_date(start_date)
+
+
+@dispatcher.register_for('NOW')
+def NOW():
+ return datetime.datetime.now()
+
+
+@dispatcher.register_for('DATEDIF')
+def DATEDIF(start_date, end_date, unit):
+ start_date = utils.parse_date(start_date)
+ end_date = utils.parse_date(end_date)
+ if utils.any_is_error((start_date, end_date)):
+ return error.NUM
+ if type(unit) != str:
+ return error.NAME
+ unit = unit.lower()
+ if start_date == end_date:
+ return 0
+ if start_date < end_date:
+ if unit == 'y':
+ return end_date.year - start_date.year - (1 if (end_date.month < start_date.month or (end_date.month == start_date.month and end_date.day < start_date.day)) else 0)
+ if unit == 'm':
+ return (end_date.year - start_date.year) * 12 + end_date.month - start_date.month - (1 if end_date.day < start_date.day else 0)
+ if unit == 'd':
+ return int(utils.serialize_date(end_date) - utils.serialize_date(start_date))
+ if unit == 'md':
+ start_day = start_date.day
+ end_day = end_date.day
+ if end_day >= start_day:
+ return end_day - start_day
+ else:
+ prev_month = end_date.month - 1
+ prev_month_days = 30 if prev_month in {4, 6, 9, 11} else 31 if prev_month != 2 else 29 if calendar.isleap(end_date.year) else 28
+ return prev_month_days - start_day + end_day
+ if unit == 'ym':
+ start_month = start_date.month
+ end_month = end_date.month
+ year_diff = end_date.year - start_date.year
+ month_diff = (year_diff * 12 + end_month - start_month)
+ if end_date.day < start_date.day:
+ month_diff -= 1
+ return int(month_diff % 12)
+ if unit == 'yd':
+ start_date_end_year = datetime.datetime(end_date.year, start_date.month, start_date.day)
+ if start_date_end_year > end_date:
+ start_date_end_year = datetime.datetime(end_date.year - 1, start_date.month, start_date.day)
+ return int(utils.serialize_date(end_date) - utils.serialize_date(start_date_end_year))
+ return error.NUM
+
+
+@dispatcher.register_for('EDATE')
+def EDATE(start_date, month):
+ if start_date == None:
+ default_date = True
+ start_date = datetime.datetime(1900, 1, 1)
+ else:
+ default_date = False
+ start_date = utils.parse_date(start_date)
+ if month == None:
+ return start_date
+ month= int(month)
+ year = start_date.year + (month // 12)
+ month = start_date.month + (month % 12)
+ if month > 12:
+ month -= 12
+ year += 1
+ elif month < 1:
+ month += 12
+ year -= 1
+ if default_date:
+ month -= 1
+ if month == 2:
+ day = 29 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else 28
+ elif month in {4, 6, 9, 11}:
+ day = 30
+ else:
+ day = 31
+ else:
+ day = start_date.day
+ day = min(day, [31, 29 if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1])
+ if year > 9999 or year < 1900:
+ return error.NUM
+ return datetime.datetime(year, month, day)
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/engineering.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/engineering.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd0027793edb5c7a97e6b2986feceac41e44ec4e
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/engineering.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+from __future__ import division
+from . import dispatcher
+from . import error
+from . import utils
+from .utils import DEFAULT
+
+
+@dispatcher.register_for('HEX2DEC')
+def HEX2DEC(hex):
+ try:
+ dec = int(hex, 16)
+ return (dec - 1099511627776) if (dec >= 549755813888) else dec
+ except ValueError:
+ return error.VALUE
+
+
+@dispatcher.register_for('DEC2HEX')
+def DEC2HEX(dec, places=DEFAULT):
+ dec = utils.parse_number(dec)
+ if isinstance(dec, error.XLError):
+ return dec
+ if places is not DEFAULT:
+ places = utils.parse_number(places)
+ if isinstance(places, error.XLError):
+ return places
+ if places < 0:
+ return error.NUM
+ if dec < 0:
+ places = DEFAULT
+ dec = dec + 1099511627776
+ try:
+ result = (hex(dec)[2:])
+ if result[-1] == 'L':
+ result = result[:-1]
+ if places is not DEFAULT:
+ if len(result) > places:
+ return error.NUM
+ result = result.rjust(places, '0')
+ return result.upper()
+ except ValueError:
+ return error.VALUE
+
+
+@dispatcher.register_for('COMPLEX')
+def COMPLEX(real, imaginary):
+ real = utils.parse_number(real)
+ imaginary = utils.parse_number(imaginary)
+ if utils.any_is_error((real, imaginary)):
+ return error.VALUE
+ return complex(real, imaginary)
+
+
+@dispatcher.register_for('DELTA')
+def DELTA(number1, number2):
+ number1 = utils.parse_number(number1)
+ number2 = utils.parse_number(number2)
+ if utils.any_is_error((number1, number2)):
+ return error.VALUE
+ return 1 if number1 == number2 else 0
+
+
+@dispatcher.register_for('IMAGINARY')
+def IMAGINARY(compl):
+ compl = utils.parse_complex(compl)
+ if isinstance(compl, error.XLError):
+ return compl
+ return int(compl.imag)
+
+@dispatcher.register_for('IMREAL')
+def IMREAL(compl):
+ compl = utils.parse_complex(compl)
+ if isinstance(compl, error.XLError):
+ return compl
+ return int(compl.real)
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/error.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/error.py
new file mode 100644
index 0000000000000000000000000000000000000000..17fa37d602b057f6c242c65d08ab59a461894f1a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/error.py
@@ -0,0 +1,32 @@
+# -*- coding: utf-8 -*-
+"""
+Defines Excel errors as python exceptions
+"""
+
+class XLError(RuntimeError):
+ pass
+
+ERROR = XLError('#ERROR!')
+DIV_ZERO = XLError('#DIV/0!')
+NAME = XLError('#NAME?')
+NOT_AVAILABLE = XLError('#N/A')
+NULL = XLError('#NULL!')
+NUM = XLError('#NUM!')
+REF = XLError('#REF!')
+VALUE = XLError('#VALUE!')
+DATA = XLError('#GETTING_DATA')
+
+
+def from_message(message):
+ errdict = {
+ '#ERROR!': ERROR,
+ '#DIV/0!': DIV_ZERO,
+ '#NAME?': NAME,
+ '#N/A': NOT_AVAILABLE,
+ '#NULL!': NULL,
+ '#NUM!': NUM,
+ '#REF!': REF,
+ '#VALUE!': VALUE,
+ '#GETTING_DATA': DATA
+ }
+ return errdict.get(str(message), ERROR)
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/financial.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/financial.py
new file mode 100644
index 0000000000000000000000000000000000000000..fced0ea2849d39dbacf81e76e26b9ecd2f5d4b0e
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/financial.py
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+from __future__ import division
+from . import dispatcher
+from . import error
+from . import utils
+
+
+@dispatcher.register_for('PV')
+def PV(rate, periods, payment, future=None, type=None):
+ if future is None:
+ future = 0
+ if type is None:
+ type = 0
+ rate = utils.parse_number(rate)
+ periods = utils.parse_number(periods)
+ payment = utils.parse_number(payment)
+ future = utils.parse_number(future)
+ type = utils.parse_number(type)
+ if utils.any_is_error((rate, periods, payment, future, type)):
+ return error.VALUE
+ # Return present value
+ if rate == 0:
+ return -payment * periods - future
+ else:
+ rate_exp_periods = (1 + rate)**periods
+ return (((1 - rate_exp_periods) / rate) * payment * (1 + rate * type) - future) / rate_exp_periods
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/information.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/information.py
new file mode 100644
index 0000000000000000000000000000000000000000..56dd4c4f175a81b4885838e56e40c0027538b546
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/information.py
@@ -0,0 +1,103 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/information.js
+"""
+
+from . import dispatcher
+from . import error
+from . import utils
+from .._compat import number_types, string_types
+import datetime
+
+
+@dispatcher.register_for('ERROR.TYPE')
+def ERROR_TYPE(error_val):
+ errdict = {
+ error.NULL: 1,
+ error.DIV_ZERO: 2,
+ error.VALUE: 3,
+ error.REF: 4,
+ error.NAME: 5,
+ error.NUM: 6,
+ error.NOT_AVAILABLE: 7,
+ error.DATA: 8
+ }
+ return errdict.get(error_val, error.NOT_AVAILABLE)
+
+
+@dispatcher.register_for('ISBLANK')
+def ISBLANK(value):
+ return value is None
+
+
+@dispatcher.register_for('ISERR')
+def ISERR(value):
+ return isinstance(value, error.XLError) and value != error.NOT_AVAILABLE
+
+
+@dispatcher.register_for('ISERROR')
+def ISERROR(value):
+ return isinstance(value, error.XLError)
+
+
+@dispatcher.register_for('ISEVEN')
+def ISEVEN(number):
+ if not isinstance(number, number_types):
+ return error.VALUE
+ return (int(number) & 1) == 0
+
+
+@dispatcher.register_for('ISODD')
+def ISODD(number):
+ if not isinstance(number, number_types):
+ return error.VALUE
+ return (int(number) & 1)
+
+
+@dispatcher.register_for('ISTEXT')
+def ISTEXT(value):
+ return isinstance(value, string_types)
+
+
+@dispatcher.register_for('ISNUMBER')
+def ISNUMBER(value):
+ return (not isinstance(value, bool)) and isinstance(value, number_types)
+
+
+@dispatcher.register_for('ISLOGICAL')
+def ISLOGICAL(value):
+ return isinstance(value, bool)
+
+
+@dispatcher.register_for('ISNA')
+def ISNA(value):
+ return value == error.NOT_AVAILABLE
+
+
+@dispatcher.register_for('N')
+def N(value):
+ if isinstance(value, (error.XLError, number_types)):
+ return value
+ if isinstance(value, datetime.datetime):
+ return utils.serialize_date(value)
+ if value is True:
+ return 1
+ return 0
+
+
+@dispatcher.register_for('NA')
+def NA():
+ return error.NOT_AVAILABLE
+
+
+@dispatcher.register_for('ISNONTEXT')
+def ISNONTEXT(value):
+ return not isinstance(value, string_types)
+
+
+@dispatcher.register_for('T')
+def T(value):
+ if isinstance(value, (error.XLError, string_types)):
+ return value
+ return ''
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/logic.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/logic.py
new file mode 100644
index 0000000000000000000000000000000000000000..e573bab2363cb4a4df554ed700c5283908d6668e
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/logic.py
@@ -0,0 +1,81 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/logical.js
+"""
+from . import dispatcher
+from . import error
+from . import utils
+
+
+@dispatcher.register_for('AND')
+def AND(*args):
+ args = utils.iflatten(args)
+ return all(args)
+
+
+@dispatcher.register_for('IF')
+def IF(test, then, otherwise):
+ return then if test else otherwise
+
+
+@dispatcher.register_for('IFERROR')
+def IFERROR(value, value_if_error):
+ return value if not isinstance(value, error.XLError) else value_if_error
+
+
+@dispatcher.register_for('IFNA')
+def IFNA(value, value_if_na):
+ return value if value != error.NOT_AVAILABLE else value_if_na
+
+
+@dispatcher.register_for('NOT')
+def NOT(boolean):
+ return not boolean
+
+
+@dispatcher.register_for('XOR')
+def XOR(*args):
+ args = utils.iflatten(args)
+ result = sum(bool(a) for a in args)
+ return bool(result & 1)
+
+
+@dispatcher.register_for('OR')
+def OR(*args):
+ args = utils.iflatten(args)
+ return any(args)
+
+
+@dispatcher.register_for('SWITCH')
+def SWITCH(target_value, *args):
+ if len(args) <= 1:
+ return error.NOT_AVAILABLE
+ argc = len(args)
+ default_clause = utils.DEFAULT if (argc % 2 == 0) else args[-1]
+ for i in range(0, argc, 2):
+ if target_value == args[i]:
+ return args[i + 1]
+ if default_clause is not utils.DEFAULT:
+ return default_clause
+ return error.NOT_AVAILABLE
+
+
+@dispatcher.register_for('IFS')
+def IFS(*args):
+ for pair in zip(args[::2], args[1::2]):
+ if pair[0]:
+ return pair[1]
+ return error.NOT_AVAILABLE
+
+
+# Compatibility functions
+
+@dispatcher.register_for('TRUE')
+def TRUE():
+ return True
+
+
+@dispatcher.register_for('FALSE')
+def FALSE():
+ return False
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/lookupandreference.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/lookupandreference.py
new file mode 100644
index 0000000000000000000000000000000000000000..a699bf3f407a03671a2b0821e433feaa52c3c0c9
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/lookupandreference.py
@@ -0,0 +1,112 @@
+# -*- coding: utf-8 -*-
+import fnmatch
+from . import dispatcher
+from . import error
+from . import utils
+from .utils import DEFAULT
+from .._compat import string_types
+
+
+@dispatcher.register_for('CHOOSE')
+def CHOOSE(*args):
+ if (len(args) < 2):
+ return error.NOT_AVAILABLE
+
+ index = args[0]
+ if (index < 1 or index > 254):
+ return error.VALUE
+
+ if (len(args) < index + 1):
+ return error.VALUE
+
+ return args[index]
+
+
+@dispatcher.register_for('MATCH')
+def MATCH(lookup_value, lookup_array, match_type=1):
+ if not lookup_value and not lookup_array:
+ return error.NOT_AVAILABLE
+
+ if not isinstance(lookup_array, list):
+ return error.NOT_AVAILABLE
+
+ if match_type not in (-1, 0, 1):
+ return error.NOT_AVAILABLE
+
+ index = None
+ index_value = None
+ for idx in range(len(lookup_array)):
+ if match_type == 1:
+ if lookup_array[idx] == lookup_value:
+ return idx + 1
+ elif lookup_array[idx] < lookup_value:
+ if not index_value:
+ index = idx + 1
+ index_value = lookup_array[idx]
+ elif lookup_array[idx] > index_value:
+ index = idx + 1
+ index_value = lookup_array[idx]
+ elif match_type == 0:
+ if isinstance(lookup_value, string_types):
+ if fnmatch.fnmatch(lookup_array[idx].lower(), lookup_value.lower()):
+ return idx + 1
+ else:
+ if lookup_array[idx] == lookup_value:
+ return idx + 1
+ elif match_type == -1:
+ if lookup_array[idx] == lookup_value:
+ return idx + 1
+ elif lookup_array[idx] > lookup_value:
+ if not index_value:
+ index = idx + 1
+ index_value = lookup_array[idx]
+ elif lookup_array[idx] < index_value:
+ index = idx + 1
+ index_value = lookup_array[idx]
+
+ return index if index else error.NOT_AVAILABLE
+
+
+@dispatcher.register_for('INDEX')
+def INDEX(arr, row_num=DEFAULT, column_num=DEFAULT, area_num=DEFAULT):
+ if row_num is None:
+ row_num = DEFAULT
+ if column_num is None:
+ column_num = DEFAULT
+
+ if arr is None or (row_num is DEFAULT and column_num is DEFAULT):
+ return error.VALUE
+
+ if not isinstance(arr, list):
+ arr = [[arr]]
+
+ bidimensional = isinstance(arr[0], list)
+
+ if row_num is not DEFAULT:
+ row_num = utils.parse_number(row_num)
+ if isinstance(row_num, error.XLError):
+ return row_num
+
+ if column_num is not DEFAULT:
+ column_num = utils.parse_number(column_num)
+ if isinstance(column_num, error.XLError):
+ return column_num
+ try:
+ if row_num is DEFAULT:
+ if bidimensional:
+ return [row[column_num - 1] for row in arr]
+ else:
+ return arr[column_num - 1]
+ if column_num is DEFAULT:
+ return arr[row_num - 1]
+ if row_num == 0 and column_num == 0:
+ return arr
+ if row_num == 0:
+ return [row[column_num - 1] for row in arr]
+ if column_num == 0:
+ return arr[row_num - 1]
+ if not bidimensional and column_num == 1:
+ return arr[row_num -1]
+ return arr[row_num - 1][column_num - 1]
+ except (IndexError, TypeError):
+ return error.REF
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/mathtrig.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/mathtrig.py
new file mode 100644
index 0000000000000000000000000000000000000000..49c4a0e596e22705f7e9ce2a5943ff4247561d7d
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/mathtrig.py
@@ -0,0 +1,547 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/math-trig.js
+"""
+from __future__ import division
+import math
+import random
+import re
+from functools import reduce
+import operator
+import collections
+from . import dispatcher
+from . import error
+from . import utils
+from .utils import DEFAULT
+from ..helper.number import to_number
+
+
+@dispatcher.register_for('ABS')
+def ABS(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return abs(number)
+
+
+@dispatcher.register_for('ACOS')
+def ACOS(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.acos(number)
+
+
+@dispatcher.register_for('ACOSH')
+def ACOSH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.log(number + math.sqrt(number * number - 1))
+
+
+@dispatcher.register_for('ACOT')
+def ACOT(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.atan(1 / number)
+
+
+@dispatcher.register_for('ACOTH')
+def ACOTH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return 0.5 * math.log((number + 1) / (number - 1))
+
+
+@dispatcher.register_for('SIN')
+def SIN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.sin(number)
+
+
+@dispatcher.register_for('SINH')
+def SINH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.sinh(number)
+
+
+@dispatcher.register_for('ASIN')
+def ASIN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.asin(number)
+
+
+@dispatcher.register_for('ASINH')
+def ASINH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.asinh(number)
+
+
+@dispatcher.register_for('COS')
+def COS(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.cos(number)
+
+
+@dispatcher.register_for('COSH')
+def COSH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.cosh(number)
+
+
+@dispatcher.register_for('COT')
+def COT(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.cos(number)/math.sin(number)
+
+
+@dispatcher.register_for('TAN')
+def TAN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.tan(number)
+
+
+@dispatcher.register_for('TANH')
+def TANH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.tanh(number)
+
+
+@dispatcher.register_for('ATAN')
+def ATAN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.atan(number)
+
+
+@dispatcher.register_for('ATAN2')
+def ATAN2(x_num, y_num):
+ x_num = utils.parse_number(x_num)
+ if isinstance(x_num, error.XLError):
+ return x_num
+ y_num = utils.parse_number(y_num)
+ if isinstance(y_num, error.XLError):
+ return y_num
+ if y_num == 0:
+ return error.DIV_ZERO
+ return math.atan2(y_num, x_num)
+
+
+@dispatcher.register_for('ATANH')
+def ATANH(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.atanh(number)
+
+
+@dispatcher.register_for('SQRT')
+def SQRT(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.sqrt(number)
+
+
+@dispatcher.register_for('EXP')
+def EXP(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.e**number
+
+
+@dispatcher.register_for('LN')
+def LN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return math.log(number)
+
+
+@dispatcher.register_for('LOG')
+def LOG(number, base=10):
+ number = utils.parse_number(number)
+ base = utils.parse_number(base)
+ if utils.any_is_error((number, base)):
+ return error.VALUE
+ return math.log(number, base)
+
+
+@dispatcher.register_for('LOG10')
+def LOG10(number):
+ return LOG(number, 10)
+
+
+@dispatcher.register_for('PI')
+def PI():
+ return math.pi
+
+
+@dispatcher.register_for('ROUND')
+def ROUND(number, digits):
+ number = utils.parse_number(number)
+ digits = utils.parse_number(digits)
+ if utils.any_is_error((number, digits)):
+ return error.VALUE
+ return round(number, digits)
+
+
+@dispatcher.register_for('ROUNDUP')
+def ROUNDUP(number, digits):
+ number = utils.parse_number(number)
+ digits = utils.parse_number(digits)
+ if utils.any_is_error((number, digits)):
+ return error.VALUE
+ sign = 1 if number > 0 else -1
+ return sign * (math.ceil(abs(number) * 10**digits)) / 10**digits
+
+
+@dispatcher.register_for('ROUNDDOWN')
+def ROUNDDOWN(number, digits):
+ number = utils.parse_number(number)
+ digits = utils.parse_number(digits)
+ if utils.any_is_error((number, digits)):
+ return error.VALUE
+ sign = 1 if number > 0 else -1
+ return sign * (math.floor(abs(number) * 10**digits)) / 10**digits
+
+
+@dispatcher.register_for('SUM')
+def SUM(*args):
+ return sum(utils.inumbers(args, try_parse=True))
+
+
+@dispatcher.register_for('SUMIF')
+def SUMIF(args, criteria):
+ predicate = utils.parse_criteria(criteria)
+ return sum(a for a in utils.iflatten(args) if predicate(a))
+
+
+@dispatcher.register_for('CEILING', 'CEILING.MATH', 'CEILING.PRECISE')
+def CEILING(number, significance=1):
+ number = utils.parse_number(number)
+ significance = utils.parse_number(significance)
+
+ if utils.any_is_error((number, significance)):
+ return error.VALUE
+ if significance == 0:
+ return 0
+
+ positive_significance = significance > 0
+ significance = abs(significance)
+ if number >= 0:
+ return math.ceil(number / significance) * significance
+ else:
+ if positive_significance:
+ return -1 * math.floor(abs(number) / significance) * significance
+ else:
+ return -1 * math.ceil(abs(number) / significance) * significance
+
+
+@dispatcher.register_for('FLOOR', 'FLOOR.MATH', 'FLOOR.PRECISE')
+def FLOOR(number, significance=1):
+ number = utils.parse_number(number)
+ significance = utils.parse_number(significance)
+
+ if utils.any_is_error((number, significance)):
+ return error.VALUE
+ if significance == 0:
+ return 0
+ if number > 0 and not significance > 0:
+ return error.NUM
+
+ abs_significance = abs(significance)
+ if number >= 0:
+ return math.floor(number / abs_significance) * abs_significance
+ else:
+ func = math.floor
+ if significance > 0:
+ func = math.ceil
+ return -1 * func(abs(number) / abs_significance) * abs_significance
+
+
+@dispatcher.register_for('POWER')
+def POWER(number, power):
+ number = utils.parse_number(number)
+ power = utils.parse_number(power)
+ if utils.any_is_error((number, power)):
+ return error.VALUE
+ result = number**power
+ if math.isnan(result):
+ return error.NUM
+ return result
+
+
+@dispatcher.register_for('QUOTIENT')
+def QUOTIENT(numerator, denominator):
+ numerator = utils.parse_number(numerator)
+ denominator = utils.parse_number(denominator)
+ if utils.any_is_error((numerator, denominator)):
+ return error.VALUE
+ if denominator == 0:
+ return error.DIV_ZERO
+ return int(numerator / denominator)
+
+
+@dispatcher.register_for('MOD')
+def MOD(numerator, denominator):
+ numerator = utils.parse_number(numerator)
+ denominator = utils.parse_number(denominator)
+ if isinstance(numerator, error.XLError):
+ return numerator
+ if isinstance(denominator, error.XLError):
+ return denominator
+ if denominator == 0:
+ return error.DIV_ZERO
+ modulus = abs(numerator % denominator)
+ return modulus if denominator > 0 else -modulus
+
+
+@dispatcher.register_for('RADIANS')
+def RADIANS(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return number * math.pi / 180
+
+
+@dispatcher.register_for('DEGREES')
+def DEGREES(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return number * 180 / math.pi
+
+
+@dispatcher.register_for('PRODUCT')
+def PRODUCT(*args):
+ return reduce(operator.mul, utils.inumbers(args))
+
+
+@dispatcher.register_for('ODD')
+def ODD(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ tmp = math.ceil(abs(number))
+ tmp = tmp if (tmp % 2) == 1 else tmp + 1
+ return tmp if number > 0 else -tmp
+
+
+@dispatcher.register_for('EVEN')
+def EVEN(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ tmp = math.ceil(abs(number))
+ tmp = tmp if (tmp % 2) == 0 else tmp + 1
+ return tmp if number > 0 else -tmp
+
+
+@dispatcher.register_for('DECIMAL')
+def DECIMAL(text, base):
+ text = str(text)
+ base = utils.parse_number(base)
+ if isinstance(base, error.XLError):
+ return base
+ try:
+ dec = int(text, base)
+ return (dec - 1099511627776) if (dec >= 549755813888) else dec
+ except ValueError:
+ return error.VALUE
+
+
+@dispatcher.register_for('BASE')
+def BASE(value, base, places=DEFAULT):
+ value = utils.parse_number(value)
+ if isinstance(value, error.XLError):
+ return value
+ base = utils.parse_number(base)
+ if isinstance(base, error.XLError):
+ return base
+ if places is not DEFAULT:
+ places = utils.parse_number(places)
+ if isinstance(places, error.XLError):
+ return places
+ if places < 0:
+ return error.NUM
+ if value == 0:
+ return '0'
+ digits = []
+ while value:
+ digits.append(int(value % base))
+ value //= base
+ result = ''.join(str(n) for n in digits[::-1])
+ if places is not DEFAULT:
+ if len(result) > places:
+ return error.NUM
+ result = result.rjust(places, '0')
+ return result
+
+
+@dispatcher.register_for('FACT')
+def FACT(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ if number < 0:
+ return error.NUM
+ return math.factorial(int(number))
+
+
+@dispatcher.register_for('FACTDOUBLE')
+def FACTDOUBLE(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ if number < 0:
+ return error.NUM
+ number = int(number)
+ if number in (0, 1):
+ return 1
+ return reduce(operator.mul, range(number, 1, -2))
+
+
+@dispatcher.register_for('ROMAN')
+def ROMAN(number, form=0):
+ number = utils.parse_number(number)
+ form = utils.parse_number(form)
+ if form is True:
+ form = 0
+ elif form is False:
+ form = 4
+
+ if utils.any_is_error((number, form)):
+ return error.VALUE
+
+ if not (0 < number < 4000 and 0 <= form <= 4):
+ return error.VALUE # number must be between 1 and 3999
+
+ def numerals(compress):
+ numeral_map = ((1000, 'M'), (500, 'D'), (100, 'C'), (50, 'L'), (10, 'X'), (5, 'V'), (1, 'I'))
+ for i, (arabic, roman) in enumerate(numeral_map, 1):
+ yield arabic, roman
+ # Then we make a list where we try to create new mappings
+ # subtracting the subsequent fixed roman numeral values from our current one
+ # and prepending their roman numerals to ours, up to compress times.
+ # The more mappings we have the more compressed the representation will be.
+ inbetweeners = collections.deque()
+ for smaller_arabic, smaller_roman in numeral_map[i:]:
+ smaller_arabic = arabic - smaller_arabic
+ if (smaller_arabic, smaller_roman) not in numeral_map:
+ inbetweeners.appendleft((smaller_arabic, smaller_roman + roman))
+ if len(inbetweeners) == compress:
+ break
+ for el in inbetweeners:
+ yield el
+
+ result = ''
+ for arabic_digit, roman_numeral in numerals(form + 1):
+ if not number:
+ break
+ count = int(number / arabic_digit)
+ result += roman_numeral * count
+ number -= arabic_digit * count
+ return result
+
+
+@dispatcher.register_for('ARABIC')
+def ARABIC(text):
+ text = str(text).upper()
+ roman_numeral_regex = '^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$'
+
+ if re.search(roman_numeral_regex, text) is None:
+ return error.VALUE
+
+ numeral_map = {
+ 'M': 1000,
+ 'CM': 900,
+ 'D': 500,
+ 'CD': 400,
+ 'C': 100,
+ 'XC': 90,
+ 'L': 50,
+ 'XL': 40,
+ 'X': 10,
+ 'IX': 9,
+ 'V': 5,
+ 'IV': 4,
+ 'I': 1
+ }
+ result = 0
+ return sum(numeral_map[match.group()] for match in re.finditer('[MDLV]|C[MD]?|X[CL]?|I[XV]?', text))
+
+
+@dispatcher.register_for('RAND')
+def RAND():
+ return random.random()
+
+
+@dispatcher.register_for('RANDBETWEEN')
+def RANDBETWEEN(bottom, top):
+ bottom = utils.parse_number(bottom)
+ top = utils.parse_number(top)
+
+ if utils.any_is_error((bottom, top)):
+ return error.VALUE
+
+ return random.randint(int(bottom), int(top))
+
+
+@dispatcher.register_for('INT')
+def INT(number):
+ if not isinstance(number, (int, float)):
+ return error.VALUE
+ if number >= 0:
+ return int(number)
+ elif int(number) > number:
+ return int(number)-1
+ else:
+ return int(number)
+
+
+@dispatcher.register_for('SUMIFS')
+def SUMIFS(sum_args, *criteria):
+ if len(criteria) % 2 != 0:
+ return error.ERROR
+ range_and_preds = list(zip(criteria[::2], (utils.parse_criteria(criterion) for criterion in criteria[1::2])))
+ b = 0
+ for i, a in enumerate(sum_args):
+ if all(pred(criteria_range[i]) for criteria_range,pred in range_and_preds):
+ b += a
+ return b
+
+
+@dispatcher.register_for('SIGN')
+def SIGN(number):
+ if not isinstance(number, (int, float)):
+ return error.VALUE
+ if number == 0:
+ return 0
+ if number > 0:
+ return 1
+ return -1
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/operators.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/operators.py
new file mode 100644
index 0000000000000000000000000000000000000000..10ef145a8e733b2456b3a12a4ba2dd215768126a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/operators.py
@@ -0,0 +1,396 @@
+# -*- coding: utf-8 -*-
+from __future__ import division
+import datetime
+from . import error
+from ..helper.number import to_number
+from .utils import OPERATOR_DICT, serialize_date, parse_date, date_1900
+from .._compat import number_types, string_types
+
+
+NoneType = type(None)
+
+
+class ExcelComparator(object):
+
+ def __init__(self, value):
+ self.value = value
+ if isinstance(value, datetime.datetime):
+ self.value = serialize_date(value)
+
+ def convert_other(self, other):
+ if other is None:
+ if isinstance(self.value, bool):
+ other = False
+ elif isinstance(self.value, number_types):
+ other = type(self.value)(0) # so it's the same number type
+ elif isinstance(self.value, string_types):
+ other = ''
+ elif isinstance(other, datetime.datetime):
+ other = serialize_date(other)
+ return other
+
+ def __lt__(self, other):
+ if self.value is None:
+ if other is None:
+ return False
+ else:
+ return ExcelComparator(other).__gt__(self.value)
+ if type(self.value) != type(other):
+ other = self.convert_other(other)
+ if type(self.value) != type(other) and not (isinstance(self.value, number_types) and isinstance(other, number_types)):
+ # if the type is still different
+ if isinstance(self.value, bool):
+ return False # bool is the biggest in XL
+ if isinstance(self.value, string_types):
+ if isinstance(other, bool):
+ return True
+ if isinstance(other, number_types):
+ return False
+ if isinstance(self.value, number_types):
+ return True
+ return self.value < other
+
+ def __gt__(self, other):
+ if self.value is None:
+ if other is None:
+ return False
+ return ExcelComparator(other).__lt__(self.value)
+ if type(self.value) != type(other):
+ other = self.convert_other(other)
+ if type(self.value) != type(other) and not (isinstance(self.value, number_types) and isinstance(other, number_types)):
+ if isinstance(self.value, bool):
+ return True # bool is the biggest in XL
+ if isinstance(self.value, string_types):
+ if isinstance(other, bool):
+ return False
+ if isinstance(other, number_types):
+ return True
+ if isinstance(self.value, number_types):
+ return False
+ return self.value > other
+
+ def __eq__(self, other):
+ if self.value is None:
+ if other is None:
+ return True
+ return ExcelComparator(other).__eq__(self.value)
+ if type(self.value) != type(other):
+ other = self.convert_other(other)
+ return self.value == other
+
+ def __ge__(self, other):
+ return self.__gt__(other) or self.__eq__(other)
+
+ def __le__(self, other):
+ return self.__lt__(other) or self.__eq__(other)
+
+
+class ExcelArrayOps(object):
+
+ def __init__(self, arr):
+ self.arr = arr
+
+ def adapt_value(self, value):
+ if isinstance(value, list) and len(value) == 1:
+ value = value[0]
+ if not isinstance(value, list):
+ value = [value for i in range(len(self.arr))]
+ return value
+
+ def __add__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('+', a, b) for a, b in zip(self.arr, value)]
+
+ __radd__ = __add__
+
+ def __sub__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('-', a, b) for a, b in zip(self.arr, value)]
+
+ def __rsub__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('-', b, a) for a, b in zip(self.arr, value)]
+
+ def __mul__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('*', a, b) for a, b in zip(self.arr, value)]
+
+ __rmul__ = __mul__
+
+ def __truediv__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('/', a, b) for a, b in zip(self.arr, value)]
+
+ def __rtruediv__(self, value):
+ value = self.adapt_value(value)
+ if len(value) != len(self.arr):
+ return error.VALUE
+ return [evaluate_arithmetic('/', b, a) for a, b in zip(self.arr, value)]
+
+
+def value_and_type(value):
+ if isinstance(value, number_types):
+ return (value, number_types)
+ if isinstance(value, datetime.datetime):
+ return (value, datetime.datetime)
+ if isinstance(value, string_types):
+ value = to_number(value)
+ if isinstance(value, number_types):
+ return value_and_type(value)
+ try_date = parse_date(value)
+ if isinstance(try_date, error.XLError):
+ return (value, string_types)
+ return value_and_type(try_date)
+ if isinstance(value, NoneType):
+ return (value, NoneType)
+ if isinstance(value, error.XLError):
+ return (value, error.XLError)
+ return (error.VALUE, error.XLError)
+
+
+# see https://support.office.com/en-ie/article/data-types-in-data-models-e2388f62-6122-4e2b-bcad-053e3da9ba90#__toc319430523
+IMPLICIT_DATA_TYPE_CONVERSIONS = {
+ '+': {
+ # left operand
+ number_types: {
+ # right operand
+ datetime.datetime: {
+ # conversion
+ 'left': None,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': None,
+ 'right': None
+ },
+ NoneType: {
+ 'left': None,
+ 'right': lambda x: 0
+ }
+ },
+ datetime.datetime: {
+ datetime.datetime: {
+ 'left': serialize_date,
+ 'right': serialize_date
+ },
+ number_types: {
+ 'left': serialize_date,
+ 'right': None,
+ 'result': parse_date
+ },
+ NoneType: {
+ 'left': serialize_date,
+ 'right': lambda x: 0,
+ 'result': parse_date
+ }
+ },
+ NoneType: {
+ datetime.datetime: {
+ 'left': lambda x: 0,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': lambda x: 0,
+ 'right': None
+ },
+ NoneType: {
+ 'left': lambda x: 0,
+ 'right': lambda x: 0
+ }
+ },
+ },
+ '-': {
+ number_types: {
+ datetime.datetime: {
+ 'left': None,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': None,
+ 'right': None
+ },
+ NoneType: {
+ 'left': None,
+ 'right': lambda x: 0
+ }
+ },
+ datetime.datetime: {
+ datetime.datetime: {
+ 'left': serialize_date,
+ 'right': serialize_date
+ },
+ number_types: {
+ 'left': serialize_date,
+ 'right': None,
+ 'result': parse_date
+ },
+ NoneType: {
+ 'left': serialize_date,
+ 'right': lambda x: 0,
+ 'result': parse_date
+ }
+ },
+ NoneType: {
+ datetime.datetime: {
+ 'left': lambda x: 0,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': lambda x: 0,
+ 'right': None
+ },
+ NoneType: {
+ 'left': lambda x: 0,
+ 'right': lambda x: 0
+ }
+ }
+ },
+ '*': {
+ number_types: {
+ datetime.datetime: {
+ 'left': None,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': None,
+ 'right': None
+ },
+ NoneType: {
+ 'left': None,
+ 'right': lambda x: 0
+ }
+ },
+ datetime.datetime: {
+ datetime.datetime: {
+ 'left': serialize_date,
+ 'right': serialize_date
+ },
+ number_types: {
+ 'left': serialize_date,
+ 'right': None,
+ 'result': parse_date
+ },
+ NoneType: {
+ 'left': serialize_date,
+ 'right': lambda x: 0,
+ 'result': parse_date
+ }
+ },
+ NoneType: {
+ datetime.datetime: {
+ 'left': lambda x: 0,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': lambda x: 0,
+ 'right': None
+ },
+ NoneType: {
+ 'left': lambda x: 0,
+ 'right': lambda x: 0
+ }
+ }
+ },
+ '/': {
+ number_types: {
+ datetime.datetime: {
+ 'left': None,
+ 'right': serialize_date,
+ 'result': parse_date
+ },
+ number_types: {
+ 'left': None,
+ 'right': None
+ },
+ NoneType: {
+ 'left': None,
+ 'right': lambda x: 0
+ }
+
+ },
+ datetime.datetime: {
+ datetime.datetime: {
+ 'left': serialize_date,
+ 'right': serialize_date
+ },
+ number_types: {
+ 'left': serialize_date,
+ 'right': None,
+ 'result': parse_date
+ },
+ NoneType: {
+ 'left': serialize_date,
+ 'right': lambda x: 0
+ }
+ },
+ NoneType: {
+ datetime.datetime: {
+ 'left': lambda x: 0,
+ 'right': serialize_date
+ },
+ number_types: {
+ 'left': lambda x: 0,
+ 'right': None
+ },
+ NoneType: {
+ 'left': lambda x: 0,
+ 'right': lambda x: 0
+ }
+ }
+ }
+}
+
+
+def evaluate_arithmetic(op, lval, rval):
+ if isinstance(lval, error.XLError):
+ return lval
+ if isinstance(rval, error.XLError):
+ return rval
+ if isinstance(lval, list):
+ return OPERATOR_DICT[op](ExcelArrayOps(lval), rval)
+ if isinstance(rval, list):
+ return OPERATOR_DICT[op](lval, ExcelArrayOps(rval))
+
+ lval, ltype = value_and_type(lval)
+ rval, rtype = value_and_type(rval)
+ conversions = IMPLICIT_DATA_TYPE_CONVERSIONS[op]
+
+ if ltype not in conversions:
+ return error.VALUE
+ if rtype not in conversions[ltype]:
+ return error.VALUE
+
+ lconv = conversions[ltype][rtype]['left']
+ if lconv is not None:
+ lval = lconv(lval)
+ rconv = conversions[ltype][rtype]['right']
+ if rconv is not None:
+ rval = rconv(rval)
+
+ try:
+ result = OPERATOR_DICT[op](lval, rval)
+ if 'result' in conversions[ltype][rtype]:
+ result = conversions[ltype][rtype]['result'](result)
+ return result
+ except ZeroDivisionError:
+ return error.DIV_ZERO
+
+
+def evaluate_logic(op, lval, rval):
+ return OPERATOR_DICT[op](ExcelComparator(lval), rval)
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/statistical.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/statistical.py
new file mode 100644
index 0000000000000000000000000000000000000000..77eb226ec439e472b39016509ac727df988d9bf5
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/statistical.py
@@ -0,0 +1,201 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/statistical.js
+"""
+from __future__ import division
+from . import dispatcher
+from . import error
+from . import utils
+from .._compat import number_types, statistics
+from ..helper.number import to_number
+
+
+@dispatcher.register_for('AVERAGE')
+def AVERAGE(*args):
+ return statistics.mean(utils.inumbers(args, try_parse=True))
+
+
+@dispatcher.register_for('AVEDEV')
+def AVEDEV(*args):
+ args = utils.flatten(args)
+ average = AVERAGE(*args)
+ return sum(abs(arg - average) for arg in utils.iflatten(args)) / len(args)
+
+
+@dispatcher.register_for('AVERAGEA')
+def AVERAGEA(*args):
+ return statistics.mean(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('AVERAGEIF')
+def AVERAGEIF(args, criteria, average_range=None):
+ average_range = average_range or args
+ args = utils.flatten(args)
+ average_range = utils.iparse_number_array(utils.flatten(average_range))
+ if isinstance(average_range, error.XLError):
+ return average_range
+ average_range = list(average_range)
+ average_count = 0
+ result = 0
+ predicate = utils.parse_criteria(criteria)
+
+ for i, arg_i in enumerate(args):
+ if (predicate(args[i])):
+ result += average_range[i]
+ average_count += 1
+ return result / average_count
+
+
+@dispatcher.register_for('COUNT')
+def COUNT(*args):
+ return len(utils.flatten(args))
+
+
+@dispatcher.register_for('COUNTA')
+def COUNTA(*args):
+ return sum(1 for a in utils.iflatten(args) if (a is not None and a != ''))
+
+
+@dispatcher.register_for('COUNTBLANK')
+def COUNTBLANK(*args):
+ return sum(1 for a in utils.iflatten(args) if (a is None or a == ''))
+
+
+@dispatcher.register_for('COUNTIF')
+def COUNTIF(args, criteria):
+ predicate = utils.parse_criteria(criteria)
+ return sum(1 for a in utils.iflatten(args) if predicate(a))
+
+
+@dispatcher.register_for('MAX')
+def MAX(*args):
+ return max(utils.inumbers(args))
+
+
+@dispatcher.register_for('MAXA')
+def MAXA(*args):
+ return max(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('MEDIAN')
+def MEDIAN(*args):
+ return statistics.median(utils.inumbers(args, try_parse=True))
+
+
+@dispatcher.register_for('MIN')
+def MIN(*args):
+ return min(utils.inumbers(args))
+
+
+@dispatcher.register_for('MINA')
+def MINA(*args):
+ return min(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('MODE', 'MODE.SNGL')
+def MODE(*args):
+ return statistics.mode(utils.inumbers(args, try_parse=True))
+
+
+@dispatcher.register_for('VAR', 'VAR.S')
+def VAR(*args):
+ return statistics.variance(utils.inumbers(args))
+
+
+@dispatcher.register_for('VAR.P', 'VARP')
+def VAR_P(*args):
+ return statistics.pvariance(utils.inumbers(args))
+
+
+@dispatcher.register_for('VARA')
+def VARA(*args):
+ return statistics.variance(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('STDEV', 'STDEV.S')
+def STDEV(*args):
+ return statistics.stdev(utils.inumbers(args))
+
+
+@dispatcher.register_for('STDEV.P', 'STDEVP')
+def STDEV_P(*args):
+ return statistics.pstdev(utils.inumbers(args))
+
+
+@dispatcher.register_for('STDEVA')
+def STDEVA(*args):
+ return statistics.stdev(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('STDEVPA')
+def STDEVPA(*args):
+ return statistics.pstdev(utils.inumbers(args, try_parse=True, text_is_zero=True))
+
+
+@dispatcher.register_for('HARMEAN')
+def HARMEAN(*args):
+ return statistics.harmonic_mean(utils.inumbers(args))
+
+
+@dispatcher.register_for('GEOMEAN')
+def GEOMEAN(*args):
+ return statistics.geometric_mean(utils.inumbers(args))
+
+
+@dispatcher.register_for('AVERAGEIFS')
+def AVERAGEIFS(average_range, *criteria):
+ if len(criteria) % 2 != 0:
+ return error.ERROR
+ range_and_preds = list(zip(criteria[::2], (utils.parse_criteria(criterion) for criterion in criteria[1::2])))
+ sum_value = 0
+ count_value = 0
+ for i, a in enumerate(average_range):
+ if all(pred(criteria_range[i]) for criteria_range, pred in range_and_preds):
+ sum_value += a
+ count_value += 1
+ if count_value == 0:
+ return error.DIV0
+ return sum_value / count_value
+
+
+@dispatcher.register_for('MAXIFS')
+def MAXIFS(sum_args, *criteria):
+ if len(criteria) % 2 != 0:
+ return error.ERROR
+ range_and_preds = list(zip(criteria[::2], (utils.parse_criteria(criterion) for criterion in criteria[1::2])))
+ b = 0
+ for i, a in enumerate(sum_args):
+ if all(pred(criteria_range[i]) for criteria_range,pred in range_and_preds):
+ if a > b:
+ b = a
+ return b
+
+
+@dispatcher.register_for('SLOPE')
+def SLOPE(*yx):
+ if len(yx) % 2 != 0:
+ return error.DIV_ZERO
+
+ midpoint = len(yx) // 2
+ ys = yx[:midpoint]
+ xs = yx[midpoint:]
+
+ if len(ys) != len(xs) or len(ys) == 0 or len(xs) == 0:
+ return error.DIV_ZERO
+
+ ys = list(ys)
+ xs = list(xs)
+
+ n = len(ys)
+ sum_x = sum(xs)
+ sum_y = sum(ys)
+ sum_x_sq = sum(x ** 2 for x in xs)
+ sum_xy = sum(x * y for x, y in zip(xs, ys))
+
+ denominator = (n * sum_x_sq) - (sum_x ** 2)
+ if denominator == 0:
+ return error.DIV_ZERO
+
+ slope = ((n * sum_xy) - (sum_x * sum_y)) / denominator
+ return slope
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/text.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/text.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aa4a0e23ac6d5548956c6a5b6d4ae7c2814dcaa
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/text.py
@@ -0,0 +1,122 @@
+# -*- coding: utf-8 -*-
+"""
+inspired by:
+https://github.com/sutoiku/formula.js/blob/master/lib/math-trig.js
+"""
+from __future__ import division
+import math
+from functools import reduce
+import operator
+from . import dispatcher
+from . import error
+from . import utils
+from .utils import DEFAULT
+from ..helper.number import to_number
+from .._compat import string_types
+
+
+@dispatcher.register_for('CHAR')
+def CHAR(number):
+ number = utils.parse_number(number)
+ if isinstance(number, error.XLError):
+ return number
+ return chr(number)
+
+
+@dispatcher.register_for('CODE')
+def CODE(char):
+ return ord(char)
+
+
+@dispatcher.register_for('CLEAN')
+def CLEAN(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return ''.join(c for c in text if ord(c) > 31)
+
+
+@dispatcher.register_for('CONCAT', 'CONCATENATE')
+def CONCATENATE(*args):
+ return ''.join(utils.iflatten(args))
+
+
+@dispatcher.register_for('LEN')
+def LEN(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ return 0
+ if not isinstance(text, string_types):
+ text = str(text)
+ return len(text)
+
+
+@dispatcher.register_for('LOWER')
+def LOWER(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return text.lower()
+
+
+@dispatcher.register_for('UPPER')
+def UPPER(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return text.upper()
+
+
+@dispatcher.register_for('PROPER')
+def PROPER(text):
+ if isinstance(text, error.XLError):
+ return text
+ if text is None:
+ text = ''
+ if not isinstance(text, string_types):
+ text = str(text)
+ return text.title()
+
+
+@dispatcher.register_for('SUBSTITUTE')
+def SUBSTITUTE(text, old_text, new_text, instance_num=DEFAULT):
+ if instance_num is not DEFAULT:
+ instance_num = utils.parse_number(instance_num)
+ if isinstance(instance_num, error.XLError):
+ return instance_num
+ if instance_num <= 0:
+ return error.VALUE
+ if not text or not old_text or not new_text:
+ return text
+ if instance_num is DEFAULT:
+ return text.replace(old_text, new_text)
+ else:
+ len_old = len(old_text)
+ ocurrences = 0
+ for i in range(len(text) - len_old + 1):
+ if text[i:i + len_old] == old_text:
+ ocurrences += 1
+ if ocurrences == instance_num:
+ return text[0:i] + new_text + text[i + len_old:]
+ return text
+
+
+@dispatcher.register_for('TEXTJOIN')
+def TEXTJOIN(delimiter, ignore_empty, *args):
+ if not isinstance(delimiter, string_types):
+ return error.VALUE
+ if ignore_empty:
+ gen = (words for words in utils.iflatten(args) if words is not None)
+ else:
+ gen = (words if words is not None else '' for words in utils.iflatten(args))
+ return delimiter.join(gen)
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/utils.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c71421016bc330733cf18b64c2fd88f4124083e
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/formulas/utils.py
@@ -0,0 +1,160 @@
+# -*- coding: utf-8 -*-
+from __future__ import division
+import re
+import fnmatch
+import itertools
+from .._compat import number_types, string_types
+from ..helper.number import to_number
+import operator
+from . import error
+import datetime
+import time
+from dateutil.parser import parse as to_date
+
+DEFAULT = lambda: 0
+
+OPERATOR_DICT = {
+ '+': operator.add,
+ '-': operator.sub,
+ '*': operator.mul,
+ '/': operator.truediv,
+ '>': operator.gt,
+ '<': operator.lt,
+ '<>': operator.ne,
+ '=': operator.eq,
+ '>=': operator.ge,
+ '<=': operator.le,
+}
+
+REGEX_CRITERIA = re.compile(r'(?P[\<\>\=]*)(?P.+)', re.UNICODE)
+
+
+def iflatten(iterable):
+ if not isinstance(iterable, (list, tuple)):
+ yield iterable
+ return
+ remainder = iter(iterable)
+ while True:
+ try:
+ first = next(remainder)
+ except StopIteration:
+ return
+ if isinstance(first, (list, tuple)):
+ remainder = itertools.chain(first, remainder)
+ else:
+ yield first
+
+
+def flatten(l):
+ return list(iflatten(l))
+
+
+def inumbers(l, try_parse=False, text_is_zero=False):
+ """ only the numbers """
+ for el in iflatten(l):
+ if isinstance(el, error.XLError):
+ raise el
+ if try_parse:
+ el = to_number(el)
+ if isinstance(el, number_types):
+ yield el
+ elif text_is_zero and isinstance(el, string_types):
+ yield 0
+
+
+def numbers(l, try_parse=False, text_is_zero=False):
+ return list(inumbers(l, try_parse=try_parse, text_is_zero=text_is_zero))
+
+
+def parse_number(string):
+ num = to_number(string)
+ if isinstance(num, number_types):
+ return num
+ if isinstance(num, error.XLError):
+ return num
+ return error.VALUE
+
+def parse_complex(string):
+ if string is None:
+ return 0
+ if isinstance(string, complex):
+ return string
+ if isinstance(string, error.XLError):
+ return string
+ try:
+ return complex(string.replace('i', 'j').replace(' ', ''))
+ except ValueError:
+ return error.NUM
+
+def iparse_number_array_aux(arr):
+ for el in arr:
+ yield parse_number(el)
+
+
+def iparse_number_array(arr):
+ if not arr:
+ return error.VALUE
+ return iparse_number_array_aux(arr)
+
+
+def parse_criteria(criteria):
+ match = REGEX_CRITERIA.match(criteria)
+ op = match.group('op')
+ val = match.group('val')
+ if op:
+ val = to_number(val)
+ op = OPERATOR_DICT[op]
+ return lambda a: op(a, val)
+ else:
+ if any(c in val for c in ('?', '*')):
+ # Then use fnmatch
+ return lambda a: fnmatch.fnmatch(val, a)
+ else:
+ return lambda a: a == to_number(val)
+
+
+def any_is_error(iterable):
+ return any(isinstance(el, error.XLError) for el in iterable)
+
+
+date_1900 = datetime.datetime(1900, 1, 1)
+epoch = datetime.datetime(1970, 1, 1)
+
+
+def epoch_seconds(date):
+ return (date - epoch).total_seconds()
+
+
+def parse_date(date):
+ if isinstance(date, error.XLError):
+ return date
+ if isinstance(date, datetime.datetime):
+ return date
+ date = to_number(date)
+ if isinstance(date, number_types):
+ if date < 0:
+ return error.NUM
+ if date < 1:
+ return date_1900
+ if date <= 60:
+ return epoch + datetime.timedelta(seconds=(epoch_seconds(date_1900) + (date - 1) * 86400))
+ return epoch + datetime.timedelta(seconds=(epoch_seconds(date_1900) + (date - 2) * 86400))
+ if isinstance(date, string_types):
+ try:
+ return to_date(date)
+ except ValueError:
+ pass
+ return error.VALUE
+
+
+def serialize_date(date):
+ date = parse_date(date)
+ if not isinstance(date, datetime.datetime):
+ return error.VALUE
+ if date == date_1900:
+ return 0
+ date = epoch_seconds(date) * 1000
+ d1900 = epoch_seconds(date_1900) * 1000
+ if date <= -2203891200000:
+ return (date - d1900) / 86400000 + 1
+ return (date - d1900) / 86400000 + 2
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/grammarparser/__init__.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/grammarparser/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/grammarparser/lexer.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/grammarparser/lexer.py
new file mode 100644
index 0000000000000000000000000000000000000000..8506f997c24c1000a57e7b7f408b85f69be824a5
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/grammarparser/lexer.py
@@ -0,0 +1,230 @@
+# -*- coding: utf-8 -*-
+import ply.lex as lex
+from ..formulas import error
+
+tokens = (
+ 'WHITESPACE',
+ 'STRING',
+ 'FUNCTION',
+ 'XLERROR',
+ 'ABSOLUTE_CELL',
+ 'MIXED_CELL',
+ 'RELATIVE_CELL',
+ 'VARIABLE',
+ 'NUMBER',
+ 'LBRACKET',
+ 'RBRACKET',
+ 'AMP',
+ 'SINGLESPACE',
+ 'DECIMAL',
+ 'COLON',
+ 'SEMICOLON',
+ 'COMMA',
+ 'BACKSLASH',
+ 'MULT',
+ 'DIV',
+ 'MINUS',
+ 'PLUS',
+ 'CARET',
+ 'LPAREN',
+ 'RPAREN',
+ 'GREATER',
+ 'LESS',
+ 'GREATEREQ',
+ 'LESSEQ',
+ 'NOTEQUAL',
+ 'QUOTATION',
+ 'APOSTROPHE',
+ 'EXCLAMATION',
+ 'EQUAL',
+ 'PERCENT',
+ 'HASH'
+)
+
+
+def t_WHITESPACE(t):
+ r'\s+'
+ pass # Ignore whitespace
+
+
+def t_STRING(t):
+ r'"(\\["]|[^"])*"|\'(\\[\']|[^\'])*\''
+ return t
+
+
+def t_FUNCTION(t):
+ r'([A-Za-z]{1,}[A-Za-z_0-9\.]+(?=[(]))|([A-Za-z\.]+(?=[(]))'
+ return t
+
+
+def t_XLERROR(t):
+ r'\#[A-Z0-9\/]+(\!|\?)?'
+ return t
+
+
+def t_ABSOLUTE_CELL(t):
+ r'\$[A-Za-z]+\$[0-9]+'
+ return t
+
+
+def t_MIXED_CELL(t):
+ r'(\$[A-Za-z]+[0-9]+)|([A-Za-z]+\$[0-9]+)'
+ return t
+
+
+def t_RELATIVE_CELL(t):
+ r'[A-Za-z]+[0-9]+'
+ return t
+
+
+def t_VARIABLE(t):
+ r'([A-Za-z]{1,}[A-Za-z_0-9]+)|([A-Za-z_]+)'
+ return t
+
+
+def t_NUMBER(t):
+ r'[0-9]+'
+ return t
+
+
+def t_LBRACKET(t):
+ r'\{'
+ return t
+
+
+def t_RBRACKET(t):
+ r'\}'
+ return t
+
+
+def t_AMP(t):
+ r'\&'
+ return t
+
+
+def t_SINGLESPACE(t):
+ r'\ '
+ return t
+
+
+def t_DECIMAL(t):
+ r'\.'
+ return t
+
+
+def t_COLON(t):
+ r'\:'
+ return t
+
+
+def t_SEMICOLON(t):
+ r'\;'
+ return t
+
+
+def t_COMMA(t):
+ r'\,'
+ return t
+
+
+def t_BACKSLASH(t):
+ r'\\'
+ return t
+
+
+def t_MULT(t):
+ r'\*'
+ return t
+
+
+def t_DIV(t):
+ r'\/'
+ return t
+
+
+def t_MINUS(t):
+ r'\-'
+ return t
+
+
+def t_PLUS(t):
+ r'\+'
+ return t
+
+
+def t_CARET(t):
+ r'\^'
+ return t
+
+
+def t_LPAREN(t):
+ r'\('
+ return t
+
+
+def t_RPAREN(t):
+ r'\)'
+ return t
+
+
+def t_NOTEQUAL(t):
+ r'\<\>'
+ return t
+
+
+def t_GREATEREQ(t):
+ r'\>\='
+ return t
+
+
+def t_LESSEQ(t):
+ r'\<\='
+ return t
+
+
+def t_GREATER(t):
+ r'\>'
+ return t
+
+
+def t_LESS(t):
+ r'\<'
+ return t
+
+
+def t_QUOTATION(t):
+ r'\"'
+ return t
+
+
+def t_APOSTROPHE(t):
+ r'\''
+ return t
+
+
+def t_EXCLAMATION(t):
+ r'\!'
+ return t
+
+
+def t_EQUAL(t):
+ r'\='
+ return t
+
+
+def t_PERCENT(t):
+ r'\%'
+ return t
+
+
+def t_HASH(t):
+ r'\#'
+ return t
+
+
+def t_error(t):
+ raise error.NAME
+
+
+def build():
+ return lex.lex()
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/grammarparser/parser.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/grammarparser/parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..5af280f0258592eedcbd7ba62befdd1a22c1f323
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/grammarparser/parser.py
@@ -0,0 +1,293 @@
+# -*- coding: utf-8 -*-
+from __future__ import division
+from __future__ import print_function
+import ply.yacc as yacc
+import ply.lex as lex
+from . import lexer
+from ..helper.number import to_number
+from .._compat import PY2, number_types, string_types
+from ..formulas import error, operators
+import math
+
+
+class Parser(object):
+ """
+ Base class for a lexer/parser that has the rules defined as methods
+ """
+ tokens = lexer.tokens
+ precedence = (
+ ('left', 'EQUAL'),
+ ('left', 'LESSEQ', 'GREATEREQ', 'NOTEQUAL'),
+ ('left', 'GREATER', 'LESS'),
+ ('left', 'PLUS', 'MINUS'),
+ ('left', 'MULT', 'DIV'),
+ ('left', 'CARET'),
+ ('left', 'AMP'),
+ ('left', 'PERCENT'),
+ ('left', 'UMINUS')
+ )
+
+ def __init__(self, debug=False, call_function=None, call_variable=None, call_cell_value=None, call_range_value=None, throw_error=None):
+ self.debug = debug
+ self.call_function = call_function
+ self.call_variable = call_variable
+ self.call_cell_value = call_cell_value
+ self.call_range_value = call_range_value
+ self.throw_error = throw_error
+ self.names = {}
+ try:
+ modname = os.path.split(os.path.splitext(__file__)[0])[
+ 1] + "_" + self.__class__.__name__
+ except:
+ modname = "parser" + "_" + self.__class__.__name__
+ self.debugfile = modname + ".dbg"
+ self.tabmodule = modname + "_" + "parsetab"
+
+ # Build the lexer and parser
+ self.lex = lex.lex(module=lexer, debug=self.debug)
+ self.yacc = yacc.yacc(module=self,
+ debug=self.debug,
+ debugfile=self.debugfile,
+ tabmodule=self.tabmodule)
+
+ def parse(self, input):
+ return self.yacc.parse(input)
+
+ def run(self):
+ while 1:
+ try:
+ s = raw_input('=')
+ except EOFError:
+ break
+ if not s:
+ continue
+ print(self.parse(s))
+
+
+class FormulaParser(Parser):
+
+ def p_expressions(self, p):
+ 'expressions : expression'
+ p[0] = p[1]
+
+ def p_expression_arithmetic_operator(self, p):
+ """
+ expression : expression PLUS expression
+ | expression MINUS expression
+ | expression MULT expression
+ | expression DIV expression
+ | expression AMP expression
+ """
+ if p[2] == '&':
+ p[0] = str(p[1]) + str(p[3])
+ else:
+ p[0] = operators.evaluate_arithmetic(p[2], p[1], p[3])
+
+ def p_expression_logical_operator(self, p):
+ """
+ expression : expression GREATER expression
+ | expression LESS expression
+ | expression GREATEREQ expression
+ | expression LESSEQ expression
+ | expression EQUAL expression
+ | expression NOTEQUAL expression
+ """
+ p[0] = operators.evaluate_logic(p[2], p[1], p[3])
+
+ def p_expression_uminus(self, p):
+ 'expression : MINUS expression %prec UMINUS'
+ p[0] = -p[2]
+
+ def p_expression_number(self, p):
+ """
+ expression : NUMBER
+ | DECIMAL NUMBER
+ | NUMBER DECIMAL NUMBER
+ | NUMBER CARET NUMBER
+ | NUMBER PERCENT
+ """
+ if len(p) == 2:
+ p[0] = to_number(p[1])
+ elif p[1] == '.':
+ p[0] = to_number('0.' + p[2])
+ elif p[2] == '.':
+ p[0] = to_number(p[1] + '.' + p[3])
+ elif p[2] == '^':
+ p[0] = to_number(p[1])**to_number(p[3])
+ elif p[2] == '%':
+ p[0] = to_number(p[1]) * 0.01
+
+ def p_expression_string(self, p):
+ """
+ expression : STRING
+ """
+ p[0] = p[1][1:-1]
+
+ def p_expression_function(self, p):
+ """
+ expression : FUNCTION LPAREN RPAREN
+ """
+ p[0] = self.call_function(p[1])
+
+ def p_expression_wargs(self, p):
+ """
+ expression : FUNCTION LPAREN expseqcomma RPAREN
+ | FUNCTION LPAREN expseqsemicolon RPAREN
+ | FUNCTION LPAREN expseqbackslash RPAREN
+ """
+ p[0] = self.call_function(p[1], p[3])
+
+ def p_expression_array(self, p):
+ """
+ expression : array
+ """
+ p[0] = p[1]
+
+ def p_array(self, p):
+ """
+ array : LBRACKET expseqsemicolon RBRACKET
+ | LBRACKET expseqcomma RBRACKET
+ | LBRACKET expseqbackslash RBRACKET
+ """
+ p[0] = p[2]
+
+ def p_expseq_semicolon(self, p):
+ """
+ expseqsemicolon : expression
+ | SEMICOLON SEMICOLON
+ | SEMICOLON expseqsemicolon
+ | expseqsemicolon SEMICOLON
+ | expseqsemicolon SEMICOLON expression
+ | expseqsemicolon SEMICOLON SEMICOLON expression
+ | expseqcomma SEMICOLON expseqcomma
+ | expseqbackslash SEMICOLON expseqbackslash
+ """
+ if len(p) == 2:
+ p[0] = [p[1]]
+ elif len(p) == 3:
+ if p[1] == ';' and p[2] == ';':
+ p[0] = [None, None, None]
+ elif p[1] == ';':
+ p[0] = [None] + p[2]
+ else:
+ p[0] = p[1] + [None]
+ elif p[2] == ';':
+ if p[3] == ';':
+ p[0] = p[1] + [None, p[4]]
+ else:
+ if str(p.slice[1]) in ('expseqcomma', 'expseqbackslash'):
+ p[0] = [p[1]] + [p[3]]
+ else:
+ p[0] = p[1] + [p[3]]
+
+ def p_expseq_comma(self, p):
+ """
+ expseqcomma : expression
+ | COMMA COMMA
+ | COMMA expseqcomma
+ | expseqcomma COMMA
+ | expseqcomma COMMA expression
+ | expseqcomma COMMA COMMA expression
+ """
+ if len(p) == 2: # expression
+ p[0] = [p[1]]
+ elif len(p) == 3:
+ if p[1] == ',' and p[2] == ',':
+ p[0] = [None, None, None]
+ elif p[1] == ',':
+ p[0] = [None] + p[2]
+ else:
+ p[0] = p[1] + [None]
+ elif p[2] == ',':
+ # expseqcomma COMMA COMMA expression
+ if p[3] == ',': # e.g. an empty function argument
+ p[0] = p[1] + [None, p[4]]
+ else:
+ p[0] = p[1] + [p[3]]
+
+ def p_expseq_backslash(self, p):
+ """
+ expseqbackslash : expression
+ | BACKSLASH BACKSLASH
+ | BACKSLASH expseqbackslash
+ | expseqbackslash BACKSLASH
+ | expseqbackslash BACKSLASH expression
+ | expseqbackslash BACKSLASH BACKSLASH expression
+ """
+ if len(p) == 2:
+ p[0] = [p[1]]
+ elif len(p) == 3:
+ if p[1] == '\\' and p[2] == '\\':
+ p[0] = [None, None, None]
+ elif p[1] == '\\':
+ p[0] = [None] + p[2]
+ else:
+ p[0] = p[1] + [None]
+ elif p[2] == '\\':
+ if p[3] == '\\':
+ p[0] = p[1] + [None, p[4]]
+ else:
+ p[0] = p[1] + [p[3]]
+
+ def p_xlerror(self, p):
+ """
+ expression : XLERROR
+ """
+ p[0] = self.throw_error(p[1])
+
+ def p_error(self, p):
+ """
+ SyntaxError
+ """
+ p[0] = self.throw_error(error.ERROR)
+
+ def p_expression_paren(self, p):
+ """
+ expression : LPAREN expression RPAREN
+ """
+ p[0] = p[2]
+
+ def p_expression_varseq(self, p):
+ """
+ expression : variable_sequence
+ """
+ p[0] = self.call_variable(p[1][0])
+
+ def p_variable(self, p):
+ """
+ variable_sequence : VARIABLE
+ """
+ p[0] = [p[1]]
+
+ def p_variable_seq(self, p):
+ """
+ variable_sequence : variable_sequence DECIMAL VARIABLE
+ """
+ p[0] = p[1] if isinstance(p[1], list) else [p[1]]
+ p[0].append(p[3])
+
+ def p_expression_cell(self, p):
+ """
+ expression : cell
+ """
+ p[0] = p[1]
+
+ def p_cell(self, p):
+ """
+ cell : ABSOLUTE_CELL
+ | RELATIVE_CELL
+ | MIXED_CELL
+ | ABSOLUTE_CELL COLON ABSOLUTE_CELL
+ | ABSOLUTE_CELL COLON RELATIVE_CELL
+ | ABSOLUTE_CELL COLON MIXED_CELL
+ | RELATIVE_CELL COLON ABSOLUTE_CELL
+ | RELATIVE_CELL COLON RELATIVE_CELL
+ | RELATIVE_CELL COLON MIXED_CELL
+ | MIXED_CELL COLON ABSOLUTE_CELL
+ | MIXED_CELL COLON RELATIVE_CELL
+ | MIXED_CELL COLON MIXED_CELL
+ """
+ if len(p) == 2:
+ p[0] = self.call_cell_value(p[1])
+ else:
+ p[0] = self.call_range_value(p[1], p[3])
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/helper/__init__.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/helper/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd655037edb91087d68fc3c90524acd5cd50b739
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/helper/__init__.py
@@ -0,0 +1 @@
+from . import number
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/helper/cell.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/helper/cell.py
new file mode 100644
index 0000000000000000000000000000000000000000..f318eb146248d22bdb69467bbff9ff6d090e5554
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/helper/cell.py
@@ -0,0 +1,102 @@
+# -*- coding: utf-8 -*-
+import re
+import math
+from collections import namedtuple
+from .._compat import integer_types, string_types
+
+
+def row_label_to_index(label):
+ try:
+ result = int(label)
+ except ValueError:
+ result = label
+ if isinstance(result, integer_types):
+ return max(result - 1, -1)
+ else:
+ return -1
+
+
+def row_index_to_label(row):
+ if row >= 0:
+ return str(row + 1)
+ return ''
+
+COLUMN_LABEL_BASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
+COLUMN_LABEL_BASE_LENGTH = len(COLUMN_LABEL_BASE)
+
+
+def column_label_to_index(label):
+ result = 0
+ if isinstance(label, string_types):
+ label = label.upper()
+ for i, j in zip(range(len(label)), range(len(label) - 1, -1, -1)):
+ result += (COLUMN_LABEL_BASE_LENGTH**j) * (COLUMN_LABEL_BASE.find(label[i]) + 1)
+ return result - 1
+
+
+def column_index_to_label(column):
+ result = ''
+ while column >= 0:
+ column = int(column)
+ result = chr((column % COLUMN_LABEL_BASE_LENGTH) + 97) + result
+ column = math.floor(column // COLUMN_LABEL_BASE_LENGTH) - 1
+
+ return result.upper()
+
+
+LABEL_EXTRACT_REGEXP = re.compile(r'^([$])?([A-Za-z]+)([$])?([0-9]+)$')
+
+ParsedLabel = namedtuple('ParsedLabel', ['index', 'label', 'is_absolute'])
+
+
+class Cell(object):
+ __slots__ = ('label', 'row', 'col')
+
+ def __init__(self, label=None, row=None, col=None):
+ self.label = label
+ self.row = row
+ self.col = col
+
+ def __getitem__(self, idx):
+ # Allowing you to do stuff like row, coll = mycell
+ if idx == 0:
+ return self.row
+ if idx == 1:
+ return self.col
+ raise IndexError
+
+ def __repr__(self):
+ return 'Cell(label=%(label)s, row=%(row)s, col=%(col)s)' % {'label': self.label,'row': self.row, 'col': self.col}
+
+
+def extract_label(label):
+ """
+ Extract cell coordinates.
+
+ @param label cell coordinates (e.g. 'A1', '$B6', '$N$98').
+ @returns Returns an list of objects.
+ """
+ match = LABEL_EXTRACT_REGEXP.match(label)
+ if (not isinstance(label, string_types)) or (match is None):
+ return []
+ label = label.upper()
+ column_abs, column, row_abs, row = match.groups()
+
+ return [
+ ParsedLabel(
+ index=row_label_to_index(row),
+ label=row,
+ is_absolute=row_abs == '$'
+ ),
+ ParsedLabel(
+ index=column_label_to_index(column),
+ label=column,
+ is_absolute=column_abs == '$',
+ )
+ ]
+
+
+def to_label(row, column):
+ row_label = ('$' if row.is_absolute else '') + row_index_to_label(row.index)
+ column_label = ('$' if column.is_absolute else '') + column_index_to_label(column.index)
+ return column_label + row_label
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/helper/number.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/helper/number.py
new file mode 100644
index 0000000000000000000000000000000000000000..561a37c68afd8284d23a3bd5d98e3d981428d955
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/helper/number.py
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+from .._compat import number_types, string_types
+
+def to_number(number):
+ if isinstance(number, number_types):
+ return number
+ if isinstance(number, string_types):
+ try:
+ return int(number)
+ except ValueError:
+ try:
+ return float(number)
+ except ValueError:
+ pass
+ if isinstance(number, bool):
+ return 1 if number else 0
+ return number
+
+def invert_number(number):
+ return -1 * to_number(number)
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/parser.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fa3c7b02243b978fc165aa48ebe3c7e5d881fb0
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/parser.py
@@ -0,0 +1,135 @@
+# -*- coding: utf-8 -*-
+from .tinyemitter import Emitter
+from . import formulas
+from .formulas import error as formulaserror
+from .grammarparser.parser import FormulaParser
+from .helper.cell import extract_label, to_label, Cell
+import traceback
+
+
+class Parser(Emitter):
+
+ def __init__(self, debug=False):
+ super(Parser, self).__init__()
+ self.variables = {'TRUE': True, 'FALSE': False, 'NULL': None}
+ self.functions = {}
+ self.debug = debug
+ self.parser = FormulaParser(call_function=self.call_function,
+ call_variable=self.call_variable,
+ call_cell_value=self.call_cell_value,
+ call_range_value=self.call_range_value,
+ throw_error=self._throw_error
+ )
+
+ def parse(self, expression):
+ result = None
+ error = None
+ try:
+ if expression == '':
+ result = ''
+ else:
+ result = self.parser.parse(expression)
+ except Exception as e:
+ if self.debug:
+ traceback.print_exc()
+ error = str(formulaserror.from_message(e))
+
+ if isinstance(result, formulaserror.XLError):
+ error = str(result)
+ result = None
+ return {'result': result, 'error': error}
+
+ def set_function(self, name, f):
+ self.functions[name] = f
+ return self
+
+ def get_function(self, name):
+ return self.functions[name]
+
+ def call_function(self, name, args=None):
+ if args is None:
+ args = []
+
+ fn = self.functions.get(name)
+ result = {'value': None} # get around 2.7 not having nonlocal
+ if fn is None:
+ fn = formulas.get_for(name)
+ if fn is None:
+ raise formulaserror.NAME
+ result['value'] = fn(*args)
+
+ def valsetter(new_value):
+ if new_value is not None:
+ result['value'] = new_value
+
+ self.emit('callFunction', name, args, valsetter)
+ return result['value']
+
+ def set_variable(self, name, v):
+ self.variables[name] = v
+ return self
+
+ def get_variable(self, name):
+ return self.variables[name]
+
+ def call_variable(self, name):
+ not_found = lambda : 0
+ value = self.variables.get(name, not_found)
+ result = {'value': value} # get around 2.7 not having nonlocal
+
+ def valsetter(new_value):
+ if new_value is not None:
+ result['value'] = new_value
+ self.emit('callVariable', name, valsetter)
+ if result['value'] is not_found:
+ raise formulaserror.NAME
+ return result['value']
+
+ def call_cell_value(self, label):
+ label = label.upper()
+ row, col = extract_label(label)
+ result = {'value': None} # get around 2.7 not having nonlocal
+
+ def valsetter(new_value):
+ if new_value is not None:
+ result['value'] = new_value
+
+ self.emit('callCellValue', Cell(label, row, col), valsetter)
+ return result['value']
+
+ def call_range_value(self, start_label, end_label):
+ if start_label is None or end_label is None:
+ return []
+ start_label = start_label.upper()
+ end_label = end_label.upper()
+
+ start_row, start_col = extract_label(start_label)
+ end_row, end_col = extract_label(end_label)
+ start_cell = Cell(start_label)
+ end_cell = Cell(end_label)
+
+ if start_row.index <= end_row.index:
+ start_cell.row = start_row
+ end_cell.row = end_row
+ else:
+ end_cell.row = start_row
+ start_cell.row = end_row
+
+ if start_col.index <= end_col.index:
+ start_cell.col = start_col
+ end_cell.col = end_col
+ else:
+ end_cell.col = start_col
+ start_cell.col = end_col
+
+ result = {'value': None} # get around 2.7 not having nonlocal
+
+ def valsetter(new_value):
+ if new_value is not None:
+ result['value'] = new_value
+
+ self.emit('callRangeValue', start_cell, end_cell, valsetter)
+ return result['value']
+
+ def _throw_error(self, error_name):
+ raise formulaserror.from_message(error_name)
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/tinyemitter.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/tinyemitter.py
new file mode 100644
index 0000000000000000000000000000000000000000..342e20f953de5eca4c5fbe9daa5c35237a39c8bc
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/hotxlfp/tinyemitter.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+"""
+A python version of tiny-emitter
+https://github.com/scottcorgan/tiny-emitter
+"""
+from collections import defaultdict, namedtuple
+
+
+Listener = namedtuple('Listener', ['fn', 'ctx'])
+
+
+class Emitter(object):
+
+ def __init__(self):
+ self._e = defaultdict(list)
+
+ def on(self, name, callback, ctx=None):
+ if ctx is None:
+ ctx = {}
+ self._e[name].append(Listener(fn=callback, ctx=ctx))
+ return self
+
+ def once(self, name, callback, ctx=None):
+ if ctx is None:
+ ctx = {}
+ def onetime_listener(*args, **ctx):
+ self.off(name, onetime_listener)
+ callback(*args, **ctx)
+ onetime_listener._ = callback
+ return self.on(name, onetime_listener, ctx)
+
+ def emit(self, name, *args):
+ listeners = self._e[name][:]
+ for listener in listeners:
+ listener.fn(*args, **listener.ctx)
+ return self
+
+ def off(self, name, callback=None):
+ events = self._e[name]
+ live_events = []
+ if events and callback:
+ for event in events:
+ if event.fn != callback and ((not hasattr(event.fn, '_')) or event.fn._ != callback):
+ live_events.append(event)
+
+ if live_events:
+ self._e[name] = live_events
+ else:
+ del self._e[name]
+ return self
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/requirements.txt b/tasks/tasksmith-a9cb6b87c28d/tests/source/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7b5737b809e138abf31ea4e428a167277dfd312a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/requirements.txt
@@ -0,0 +1,2 @@
+ply
+python-dateutil
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/scripts/__init__.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/scripts/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/scripts/allformulas.txt b/tasks/tasksmith-a9cb6b87c28d/tests/source/scripts/allformulas.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b88923acbdfbcbff9aad7602df2307533575a951
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/scripts/allformulas.txt
@@ -0,0 +1,481 @@
+ABS
+ACCRINT
+ACCRINTM
+ACOS
+ACOSH
+ACOT
+ACOTH
+ADDRESS
+AGGREGATE
+AMORDEGRC
+AMORLINC
+AND
+ARABIC
+AREAS
+ARRAYTOTEXT
+ASC
+ASIN
+ASINH
+ATAN
+ATAN2
+ATANH
+AVEDEV
+AVERAGE
+AVERAGEA
+AVERAGEIF
+AVERAGEIFS
+BAHTTEXT
+BASE
+BESSELI
+BESSELJ
+BESSELK
+BESSELY
+BETA.DIST
+BETA.INV
+BETADIST
+BETAINV
+BIN2DEC
+BIN2HEX
+BIN2OCT
+BINOM.DIST
+BINOM.DIST.RANGE
+BINOM.INV
+BINOMDIST
+BITAND
+BITLSHIFT
+BITOR
+BITRSHIFT
+BITXOR
+CALL
+CEILING
+CEILING.MATH
+CEILING.PRECISE
+CELL
+CHAR
+CHIDIST
+CHIINV
+CHISQ.DIST
+CHISQ.DIST.RT
+CHISQ.INV
+CHISQ.INV.RT
+CHISQ.TEST
+CHITEST
+CHOOSE
+CLEAN
+CODE
+COLUMN
+COLUMNS
+COMBIN
+COMBINA
+COMPLEX
+CONCAT
+CONCATENATE
+CONFIDENCE
+CONFIDENCE.NORM
+CONFIDENCE.T
+CONVERT
+CORREL
+COS
+COSH
+COT
+COTH
+COUNT
+COUNTA
+COUNTBLANK
+COUNTIF
+COUNTIFS
+COUPDAYBS
+COUPDAYS
+COUPDAYSNC
+COUPNCD
+COUPNUM
+COUPPCD
+COVAR
+COVARIANCE.P
+COVARIANCE.S
+CRITBINOM
+CSC
+CSCH
+CUBEKPIMEMBER
+CUBEMEMBER
+CUBEMEMBERPROPERTY
+CUBERANKEDMEMBER
+CUBESET
+CUBESETCOUNT
+CUBEVALUE
+CUMIPMT
+CUMPRINC
+DATE
+DATEDIF
+DATEVALUE
+DAVERAGE
+DAY
+DAYS
+DAYS360
+DB
+DBCS
+DCOUNT
+DCOUNTA
+DDB
+DEC2BIN
+DEC2HEX
+DEC2OCT
+DECIMAL
+DEGREES
+DELTA
+DEVSQ
+DGET
+DISC
+DMAX
+DMIN
+DOLLAR
+DOLLARDE
+DOLLARFR
+DPRODUCT
+DSTDEV
+DSTDEVP
+DSUM
+DURATION
+DVAR
+DVARP
+EDATE
+EFFECT
+ENCODEURL
+EOMONTH
+ERF
+ERF.PRECISE
+ERFC
+ERFC.PRECISE
+ERROR.TYPE
+EUROCONVERT
+EVEN
+EXACT
+EXP
+EXPON.DIST
+EXPONDIST
+F.DIST
+F.DIST.RT
+F.INV
+F.INV.RT
+F.TEST
+FACT
+FACTDOUBLE
+FALSE
+FDIST
+FILTER
+FILTERXML
+FIND, FINDBs
+FINV
+FISHER
+FISHERINV
+FIXED
+FLOOR
+FLOOR.MATH
+FLOOR.PRECISE
+FORECAST
+FORECAST.ETS
+FORECAST.ETS.CONFINT
+FORECAST.ETS.SEASONALITY
+FORECAST.ETS.STAT
+FORECAST.LINEAR
+FORMULATEXT
+FREQUENCY
+FTEST
+FV
+FVSCHEDULE
+GAMMA
+GAMMA.DIST
+GAMMA.INV
+GAMMADIST
+GAMMAINV
+GAMMALN
+GAMMALN.PRECISE
+GAUSS
+GCD
+GEOMEAN
+GESTEP
+GETPIVOTDATA
+GROWTH
+HARMEAN
+HEX2BIN
+HEX2DEC
+HEX2OCT
+HLOOKUP
+HOUR
+HYPERLINK
+HYPGEOM.DIST
+HYPGEOMDIST
+IF
+IFERROR
+IFNA
+IFS
+IMABS
+IMAGINARY
+IMARGUMENT
+IMCONJUGATE
+IMCOS
+IMCOSH
+IMCOT
+IMCSC
+IMCSCH
+IMDIV
+IMEXP
+IMLN
+IMLOG10
+IMLOG2
+IMPOWER
+IMPRODUCT
+IMREAL
+IMSEC
+IMSECH
+IMSIN
+IMSINH
+IMSQRT
+IMSUB
+IMSUM
+IMTAN
+INDEX
+INDIRECT
+INFO
+INT
+INTERCEPT
+INTRATE
+IPMT
+IRR
+ISBLANK
+ISERR
+ISERROR
+ISEVEN
+ISFORMULA
+ISLOGICAL
+ISNA
+ISNONTEXT
+ISNUMBER
+ISO.CEILING
+ISODD
+ISOWEEKNUM
+ISPMT
+ISREF
+ISTEXT
+JIS
+KURT
+LARGE
+LCM
+LEFT, LEFTBs
+LEN, LENBs
+LET
+LINEST
+LN
+LOG
+LOG10
+LOGEST
+LOGINV
+LOGNORM.DIST
+LOGNORM.INV
+LOGNORMDIST
+LOOKUP
+LOWER
+MATCH
+MAX
+MAXA
+MAXIFS
+MDETERM
+MDURATION
+MEDIAN
+MID, MIDBs
+MIN
+MINA
+MINIFS
+MINUTE
+MINVERSE
+MIRR
+MMULT
+MOD
+MODE
+MODE.MULT
+MODE.SNGL
+MONTH
+MROUND
+MULTINOMIAL
+MUNIT
+N
+NA
+NEGBINOM.DIST
+NEGBINOMDIST
+NETWORKDAYS
+NETWORKDAYS.INTL
+NOMINAL
+NORM.DIST
+NORM.INV
+NORM.S.DIST
+NORM.S.INV
+NORMDIST
+NORMINV
+NORMSDIST
+NORMSINV
+NOT
+NOW
+NPER
+NPV
+NUMBERVALUE
+OCT2BIN
+OCT2DEC
+OCT2HEX
+ODD
+ODDFPRICE
+ODDFYIELD
+ODDLPRICE
+ODDLYIELD
+OFFSET
+OR
+PDURATION
+PEARSON
+PERCENTILE
+PERCENTILE.EXC
+PERCENTILE.INC
+PERCENTRANK
+PERCENTRANK.EXC
+PERCENTRANK.INC
+PERMUT
+PERMUTATIONA
+PHI
+PHONETIC
+PI
+PMT
+POISSON
+POISSON.DIST
+POWER
+PPMT
+PRICE
+PRICEDISC
+PRICEMAT
+PROB
+PRODUCT
+PROPER
+PV
+QUARTILE
+QUARTILE.EXC
+QUARTILE.INC
+QUOTIENT
+RADIANS
+RAND
+RANDARRAY
+RANDBETWEEN
+RANK
+RANK.AVG
+RANK.EQ
+RATE
+RECEIVED
+REGISTER.ID
+REPLACE, REPLACEBs
+REPT
+RIGHT, RIGHTBs
+ROMAN
+ROUND
+ROUNDDOWN
+ROUNDUP
+ROW
+ROWS
+RRI
+RSQ
+RTD
+SEARCH, SEARCHBs
+SEC
+SECH
+SECOND
+SEQUENCE
+SERIESSUM
+SHEET
+SHEETS
+SIGN
+SIN
+SINH
+SKEW
+SKEW.P
+SLN
+SLOPE
+SMALL
+SORT
+SORTBY
+SQRT
+SQRTPI
+STANDARDIZE
+STDEV
+STDEV.P
+STDEV.S
+STDEVA
+STDEVP
+STDEVPA
+STEYX
+SUBSTITUTE
+SUBTOTAL
+SUM
+SUMIF
+SUMIFS
+SUMPRODUCT
+SUMSQ
+SUMX2MY2
+SUMX2PY2
+SUMXMY2
+SWITCH
+SYD
+T
+T.DIST
+T.DIST.2T
+T.DIST.RT
+T.INV
+T.INV.2T
+T.TEST
+TAN
+TANH
+TBILLEQ
+TBILLPRICE
+TBILLYIELD
+TDIST
+TEXT
+TEXTJOIN
+TIME
+TIMEVALUE
+TINV
+TODAY
+TRANSPOSE
+TREND
+TRIM
+TRIMMEAN
+TRUE
+TRUNC
+TTEST
+TYPE
+UNICHAR
+UNICODE
+UNIQUE
+UPPER
+VALUE
+VALUETOTEXT
+VAR
+VAR.P
+VAR.S
+VARA
+VARP
+VARPA
+VDB
+VLOOKUP
+WEBSERVICE
+WEEKDAY
+WEEKNUM
+WEIBULL
+WEIBULL.DIST
+WORKDAY
+WORKDAY.INTL
+XIRR
+XLOOKUP
+XMATCH
+XNPV
+XOR
+YEAR
+YEARFRAC
+YIELD
+YIELDDISC
+YIELDMAT
+Z.TEST
+ZTEST
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/scripts/update_supported_formulas.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/scripts/update_supported_formulas.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a6051c3d9fd4e8dc2fa1af878f84494b5ab793a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/scripts/update_supported_formulas.py
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+"""
+Run from root directory
+python -m "scripts.update_supported_formulas"
+"""
+from hotxlfp import formulas
+import os
+from io import open
+path = os.path.dirname(__file__)
+allpath = os.path.join(path, 'allformulas.txt')
+fpath = os.path.join(path, os.pardir, 'SUPPORTED_FORMULAS.md')
+
+
+functions_to_support = []
+with open(allpath, 'r', encoding='utf-8', newline='\n') as f:
+ functions_to_support = (l.strip() for l in f.readlines())
+
+with open(fpath, 'w', encoding='utf-8', newline='\n') as f:
+ supported = formulas.supported()
+ f.write(u'# Supported Formulas - %d\n\n' % len(supported))
+ for formula in supported:
+ f.write(u'* ' + formula + u'\n')
+ supported = set(supported)
+ unsupported = [fn for fn in functions_to_support if fn not in supported]
+ f.write(u'\n\n# Not Yet Supported Formulas - %d\n\n' % len(unsupported))
+ for formula in unsupported:
+ f.write(u'* ' + formula + u'\n')
+
+
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/setup.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..223e5b4c3a454e79509c758bc268a27ded432b60
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/setup.py
@@ -0,0 +1,33 @@
+# -*- coding: utf-8 -*-
+from io import open
+from setuptools import setup
+
+setup(
+ name='hotxlfp',
+ version='0.0.16',
+ packages=['hotxlfp', 'hotxlfp._compat', 'hotxlfp._compat.py3', 'hotxlfp.helper', 'hotxlfp.formulas', 'hotxlfp.grammarparser'],
+ license='MIT',
+ test_suite='tests',
+ author='Leonel Câmara',
+ author_email='leonelcamara@gmail.com',
+ url='https://github.com/aidhound/hotxlfp',
+ download_url='https://github.com/aidhound/hotxlfp/archive/0.0.16.tar.gz',
+ keywords=['excel', 'formula', 'parser'],
+ install_requires=['ply', 'python-dateutil'],
+ long_description='\n'.join(l for l in open('README.md', encoding="utf-8").readlines() if not l.startswith('[!')),
+ long_description_content_type='text/markdown',
+ classifiers=[
+ 'Development Status :: 3 - Alpha',
+ 'Intended Audience :: Developers',
+ 'License :: OSI Approved :: MIT License',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.9',
+ 'Programming Language :: Python :: 3.10',
+ 'Programming Language :: Python :: 3.11'
+ ]
+)
+
+
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/__init__.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_dateandtime.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_dateandtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5cb2231df1629c32e26dc89db562ecab0a8019b
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_dateandtime.py
@@ -0,0 +1,191 @@
+# -*- coding: utf-8 -*-
+import unittest
+import math
+from hotxlfp import Parser
+import datetime
+
+
+class TestDateAndTime(unittest.TestCase):
+
+ def test_date(self):
+ p = Parser(debug=True)
+ ret = p.parse('DATE(2020;10;12)')
+ self.assertEqual(ret['result'], datetime.datetime(2020, 10, 12))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DATE(95;10;12)')
+ self.assertEqual(ret['result'], datetime.datetime(1995, 10, 12))
+ self.assertEqual(ret['error'], None)
+
+ def test_datevalue(self):
+ p = Parser(debug=True)
+ ret = p.parse('DATEVALUE("8/22/2011")')
+ self.assertEqual(ret['result'], 40777)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DATEVALUE("22-MAY-2011")')
+ self.assertEqual(ret['result'], 40685)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DATEVALUE("2011/02/23")')
+ self.assertEqual(ret['result'], 40597)
+ self.assertEqual(ret['error'], None)
+
+ def test_year(self):
+ p = Parser(debug=True)
+ ret = p.parse('YEAR("2020-10-12 10:04:11")')
+ self.assertEqual(ret['result'], 2020)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('YEAR(41193)') # 2012-10-11 in serial
+ self.assertEqual(ret['result'], 2012)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('YEAR(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_month(self):
+ p = Parser(debug=True)
+ ret = p.parse('MONTH("2020-10-12 10:04:11")')
+ self.assertEqual(ret['result'], 10)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MONTH(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_day(self):
+ p = Parser(debug=True)
+ ret = p.parse('DAY("2020-10-12 10:04:11")')
+ self.assertEqual(ret['result'], 12)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DAY(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_hour(self):
+ p = Parser(debug=True)
+ ret = p.parse('HOUR("10:04:11")')
+ self.assertEqual(ret['result'], 10)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('HOUR(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_minute(self):
+ p = Parser(debug=True)
+ ret = p.parse('MINUTE("10:04:11")')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MINUTE(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_second(self):
+ p = Parser(debug=True)
+ ret = p.parse('SECOND("10:04:11")')
+ self.assertEqual(ret['result'], 11)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SECOND(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_today(self):
+ today = datetime.date.today()
+ today_datetime = datetime.datetime(today.year, today.month, today.day)
+ p = Parser(debug=True)
+ ret = p.parse('YEAR(TODAY())')
+ self.assertEqual(ret['result'], today.year)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MONTH(TODAY())')
+ self.assertEqual(ret['result'], today.month)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DAY(TODAY())')
+ self.assertEqual(ret['result'], today.day)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('HOUR(TODAY())')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MINUTE(TODAY())')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SECOND(TODAY())')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+
+ def test_days(self):
+ p = Parser(debug=True)
+ ret = p.parse('DAYS("3/15/11","2/1/11")')
+ self.assertEqual(ret['result'], 42)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DAYS("foo","2/1/11")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('DAYS(TODAY(),TODAY()-1)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+
+ def test_now(self):
+ p = Parser(debug=True)
+ now = datetime.datetime.now()
+ ret = p.parse('NOW()')
+ self.assertEqual(ret['result'], now)
+ ret = p.parse('YEAR(NOW())')
+ self.assertEqual(ret['result'], now.year)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MONTH(NOW())')
+ self.assertEqual(ret['result'], now.month)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DAY(NOW())')
+ self.assertEqual(ret['result'], now.day)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('HOUR(NOW())')
+ self.assertEqual(ret['result'], now.hour)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MINUTE(NOW())')
+ self.assertEqual(ret['result'], now.minute)
+ self.assertEqual(ret['error'], None)
+
+ def test_datedif(self):
+ p = Parser(debug=True)
+ ret = p.parse('DATEDIF(DATE(2019,10,6), DATE(2020,10,5), "Y")')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DATEDIF(DATE(2019,10,6), DATE(2020,10,5), "m")')
+ self.assertEqual(ret['result'], 11)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DATEDIF(DATE(2019,10,6), DATE(2020,10,5), "d")')
+ self.assertEqual(ret['result'], 365)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DATEDIF(DATE(2019,1,20), DATE(2019,3,10), "md")')
+ self.assertEqual(ret['result'], 18)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DATEDIF(DATE(2019,10,6), DATE(2020,10,5), "ym")')
+ self.assertEqual(ret['result'], 11)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DATEDIF(DATE(2019,10,4), DATE(2020,10,5), "yd")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+
+
+ def test_edate(self):
+ p = Parser(debug=True)
+ ret = p.parse('EDATE(DATE(2019,10,6), -1437)')
+ self.assertEqual(ret['result'], datetime.datetime(1900, 1, 6))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EDATE(DATE(2019,10,6), -1)')
+ self.assertEqual(ret['result'], datetime.datetime(2019, 9, 6))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EDATE(DATE(2019,10,6), 12)')
+ self.assertEqual(ret['result'], datetime.datetime(2020, 10, 6))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EDATE(DATE(2019,10,6), -12)')
+ self.assertEqual(ret['result'], datetime.datetime(2018, 10, 6))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EDATE(, 4)')
+ self.assertEqual(ret['result'], datetime.datetime(1900, 4, 30))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EDATE(DATE(2019,10,6), )')
+ self.assertEqual(ret['result'], datetime.datetime(2019,10,6))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EDATE(0,0)')
+ self.assertEqual(ret['result'], datetime.datetime(1900, 1, 1))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EDATE(DATE(1999,7,8), 404)')
+ self.assertEqual(ret['result'], datetime.datetime(2033, 3, 8))
+ self.assertEqual(ret['error'], None)
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_engineering.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_engineering.py
new file mode 100644
index 0000000000000000000000000000000000000000..aefbed3d320cb8f6c0b1e1ab9993e81fbf820f9a
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_engineering.py
@@ -0,0 +1,114 @@
+# -*- coding: utf-8 -*-
+import unittest
+import math
+from hotxlfp import Parser
+
+
+class TestEngineering(unittest.TestCase):
+
+ def test_hex2dec(self):
+ p = Parser(debug=True)
+ ret = p.parse('HEX2DEC("A5")')
+ self.assertEqual(ret['result'], 165)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('HEX2DEC("FFFFFFFF5B")')
+ self.assertEqual(ret['result'], -165)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('HEX2DEC("3DA408B9")')
+ self.assertEqual(ret['result'], 1034160313)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('HEX2DEC("ZZZ")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+
+ def test_dec2hex(self):
+ p = Parser(debug=True)
+ ret = p.parse('DEC2HEX(100, 4)')
+ self.assertEqual(ret['result'], '0064')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DEC2HEX(-54)')
+ self.assertEqual(ret['result'], 'FFFFFFFFCA')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DEC2HEX(28)')
+ self.assertEqual(ret['result'], '1C')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DEC2HEX(64,1)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#NUM!')
+
+ def test_delta(self):
+ p = Parser(debug=True)
+ ret = p.parse('DELTA(5, 4)')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DELTA(5, 5)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DELTA(0.5, 0)')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+
+ def test_complex(self):
+ p = Parser(debug=True)
+ ret = p.parse('COMPLEX(3, 5)')
+ self.assertEqual(ret['result'], complex(3, 5))
+ self.assertEqual(ret['error'], None)
+
+
+ def test_imaginary(self):
+ p = Parser(debug=True)
+ ret = p.parse('IMAGINARY("i")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMAGINARY("1")')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMAGINARY("4i")')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMAGINARY(COMPLEX(2,3))')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMAGINARY(COMPLEX(2,0))')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMAGINARY("2+4i")')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMAGINARY("5-2i")')
+ self.assertEqual(ret['result'], -2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMAGINARY("-5-2i")')
+ self.assertEqual(ret['result'], -2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMAGINARY(B1)')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+
+
+ def test_imreal(self):
+ p = Parser(debug=True)
+ ret = p.parse('IMREAL("i")')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMREAL("1")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMREAL("4i")')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMREAL(COMPLEX(2,3))')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMREAL(COMPLEX(0,3))')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMREAL("2+4i")')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMREAL("5-2i")')
+ self.assertEqual(ret['result'], 5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IMREAL("-5-2i")')
+ self.assertEqual(ret['result'], -5)
+ self.assertEqual(ret['error'], None)
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_error.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b8aca041684d2f44595089faf6427936dbc33bd
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_error.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+import unittest
+from hotxlfp import Parser
+
+
+class TestError(unittest.TestCase):
+ """ Stuff that should cause errors """
+
+ def test_div_zero(self):
+ p = Parser()
+ ret = p.parse('2/0')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('SUM(2/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('SUM(1; 2/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('SUM(2/0; 1)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+
+ def test_wrong_syntax(self):
+ p = Parser()
+ ret = p.parse('2(6+2)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#ERROR!')
+ ret = p.parse('2:5')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#ERROR!')
+
+
+ def test_error_imaginary(self):
+ p = Parser()
+ ret = p.parse('IMAGINARY(#ERROR!)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#ERROR!')
+ ret = p.parse('IMAGINARY(2/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('IMAGINARY("")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#NUM!')
+ ret = p.parse('IMAGINARY(#N/A)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#N/A')
+
+ def test_error_real(self):
+ p = Parser()
+ ret = p.parse('IMREAL(#ERROR!)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#ERROR!')
+ ret = p.parse('IMREAL(2/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('IMREAL("")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#NUM!')
+ ret = p.parse('IMREAL(#N/A)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#N/A')
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_financial.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_financial.py
new file mode 100644
index 0000000000000000000000000000000000000000..4248d3a37af685c51a44fe2ba2f6ea096905b184
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_financial.py
@@ -0,0 +1,21 @@
+# -*- coding: utf-8 -*-
+import unittest
+import math
+from hotxlfp import Parser
+
+
+class TestFinancial(unittest.TestCase):
+
+ def test_pv(self):
+ p = Parser(debug=True)
+ ret = p.parse('PV(8%/12, 12*20, 500,,0)')
+ self.assertEqual(round(ret['result'], 2), -59777.15)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('PV(8%/12, 12*20, 500)')
+ self.assertEqual(round(ret['result'], 2), -59777.15)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('PV(1/0, 12*20, 500)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('PV(0, 12*20, 500)')
+ self.assertEqual(ret['result'], -120000)
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_helper.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..08d2c2cdee5bd36c65cf8760f96a22880b04086b
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_helper.py
@@ -0,0 +1,69 @@
+# -*- coding: utf-8 -*-
+
+import unittest
+from hotxlfp.helper import cell, number
+
+
+class TestHelper(unittest.TestCase):
+
+ def test_row_index_to_label(self):
+ res = cell.row_index_to_label(0)
+ self.assertEqual(res, '1')
+ res = cell.row_index_to_label(26)
+ self.assertEqual(res, '27')
+ res = cell.row_index_to_label(51)
+ self.assertEqual(res, '52')
+
+ def test_row_label_to_index(self):
+ res = cell.row_label_to_index('0')
+ self.assertEqual(res, -1)
+ res = cell.row_label_to_index('A')
+ self.assertEqual(res, -1)
+ res = cell.row_label_to_index('1')
+ self.assertEqual(res, 0)
+ res = cell.row_label_to_index('27')
+ self.assertEqual(res, 26)
+ res = cell.row_label_to_index('50')
+ self.assertEqual(res, 49)
+
+ def test_column_index_to_label(self):
+ res = cell.column_index_to_label(0)
+ self.assertEqual(res, 'A')
+ res = cell.column_index_to_label(26)
+ self.assertEqual(res, 'AA')
+ res = cell.column_index_to_label(51)
+ self.assertEqual(res, 'AZ')
+
+ def test_column_label_to_index(self):
+ res = cell.column_label_to_index('')
+ self.assertEqual(res, -1)
+ res = cell.column_label_to_index('A')
+ self.assertEqual(res, 0)
+ res = cell.column_label_to_index('AA')
+ self.assertEqual(res, 26)
+ res = cell.column_label_to_index('AZ')
+ self.assertEqual(res, 51)
+
+ def test_extract_label(self):
+ res = cell.extract_label('A1')
+ self.assertEqual(res[0].index, 0)
+ self.assertEqual(res[0].label, '1')
+ self.assertEqual(res[0].is_absolute, False)
+ self.assertEqual(res[1].index, 0)
+ self.assertEqual(res[1].label, 'A')
+ self.assertEqual(res[1].is_absolute, False)
+ res = cell.extract_label('$N$98')
+ self.assertEqual(res[0].index, 97)
+ self.assertEqual(res[0].label, '98')
+ self.assertEqual(res[0].is_absolute, True)
+ self.assertEqual(res[1].index, 13)
+ self.assertEqual(res[1].label, 'N')
+ self.assertEqual(res[1].is_absolute, True)
+
+ def test_to_label(self):
+ res = cell.to_label(cell.ParsedLabel(index=0, label='1', is_absolute=False),
+ cell.ParsedLabel(index=0, label='A', is_absolute=False))
+ self.assertEqual(res, 'A1')
+ res = cell.to_label(cell.ParsedLabel(index=97, label='98', is_absolute=True),
+ cell.ParsedLabel(index=13, label='N', is_absolute=True))
+ self.assertEqual(res, '$N$98')
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_information.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_information.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bd18680669758b098bb6d0fbf68974350f0806e
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_information.py
@@ -0,0 +1,189 @@
+# -*- coding: utf-8 -*-
+
+import unittest
+from hotxlfp import Parser
+
+
+class TestStatistical(unittest.TestCase):
+
+ def test_error_type(self):
+ p = Parser(debug=True)
+ ret = p.parse('ERROR.TYPE(1/0)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+
+ def test_iserr(self):
+ p = Parser(debug=True)
+ ret = p.parse('ISERR(1/0)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+
+ def test_iserror(self):
+ p = Parser(debug=True)
+ ret = p.parse('ISERROR(1/0)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ p = Parser(debug=True)
+ ret = p.parse('ISERROR(1/2)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+
+ def test_iseven(self):
+ p = Parser(debug=True)
+ ret = p.parse('ISEVEN(1)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISEVEN(-1)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISEVEN(2)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISEVEN(-2)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISEVEN(1000)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISEVEN("A")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('ISEVEN(2.21)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+
+ def test_isodd(self):
+ p = Parser(debug=True)
+ ret = p.parse('ISODD(1)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISODD(-1)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISODD(2)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISODD(-2)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISODD(1000)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISODD("A")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('ISODD(2.21)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+
+ def test_istext(self):
+ p = Parser(debug=True)
+ ret = p.parse('ISTEXT("foo")')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISTEXT(NA())')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISTEXT(1)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+
+ def test_isnumber(self):
+ p = Parser(debug=True)
+ ret = p.parse('ISNUMBER("foo")')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISNUMBER(TRUE)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISNUMBER(NA())')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISNUMBER(1)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+
+ def test_islogical(self):
+ p = Parser(debug=True)
+ ret = p.parse('ISLOGICAL("foo")')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISLOGICAL(TRUE)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISLOGICAL(NA())')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISLOGICAL(1)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+
+ def test_isna(self):
+ p = Parser(debug=True)
+ ret = p.parse('ISNA(NA())')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISNA(1/0)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+
+ def test_isnontext(self):
+ p = Parser(debug=True)
+ ret = p.parse('ISNONTEXT("foo")')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISNONTEXT(NA())')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ISNONTEXT(1)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+
+ def test_n(self):
+ p = Parser(debug=True)
+ ret = p.parse('N(1)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('N(TODAY())')
+ ret2 = p.parse('DATEVALUE(TODAY())')
+ self.assertEqual(ret['result'], ret2['result'])
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('N("1024")')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('N("foo")')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('N(TRUE())')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('N(FALSE())')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+
+ def test_t(self):
+ p = Parser(debug=True)
+ ret = p.parse('T(100)')
+ self.assertEqual(ret['result'], '')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('T(TODAY())')
+ self.assertEqual(ret['result'], '')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('T("1024")')
+ self.assertEqual(ret['result'], "1024")
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('T("foo")')
+ self.assertEqual(ret['result'], "foo")
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('T(TRUE())')
+ self.assertEqual(ret['result'], '')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('T(FALSE())')
+ self.assertEqual(ret['result'], '')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('T(10%)')
+ self.assertEqual(ret['result'], '')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('T("FOO")')
+ self.assertEqual(ret['result'], "FOO")
+ self.assertEqual(ret['error'], None)
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_lexer.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_lexer.py
new file mode 100644
index 0000000000000000000000000000000000000000..491ec7e7af1806e0776c31f2b3f5590987543826
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_lexer.py
@@ -0,0 +1,13 @@
+# -*- coding: utf-8 -*-
+import unittest
+from hotxlfp.grammarparser import lexer
+
+
+class TestLexer(unittest.TestCase):
+
+ def test_function(self):
+ lex = lexer.build()
+ lex.input('ACOTH("foo")')
+ expected_token_types = ['FUNCTION', 'LPAREN', 'STRING', 'RPAREN']
+ for i, t in enumerate(lex):
+ self.assertEqual(t.type, expected_token_types[i])
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_logic.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_logic.py
new file mode 100644
index 0000000000000000000000000000000000000000..67e4f82ea768063096d238fb40f017f5661466ac
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_logic.py
@@ -0,0 +1,126 @@
+# -*- coding: utf-8 -*-
+import unittest
+from hotxlfp import Parser
+
+
+class TestLogic(unittest.TestCase):
+
+ def test_and(self):
+ p = Parser(debug=True)
+ ret = p.parse('AND(TRUE,TRUE, FALSE)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('AND(TRUE,TRUE, TRUE)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('AND(FALSE)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('AND(TRUE)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+
+ def test_if(self):
+ p = Parser(debug=True)
+ ret = p.parse('IF(TRUE,1,3)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IF(FALSE,1,3)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IF(,,)=0')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IF(,,)=""')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IF(,,)=B3')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+
+ def test_iferror(self):
+ p = Parser(debug=True)
+ ret = p.parse('IFERROR(1/0,1)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IFERROR("notme",1)')
+ self.assertEqual(ret['result'], "notme")
+ self.assertEqual(ret['error'], None)
+
+ def test_ifna(self):
+ p = Parser(debug=True)
+ ret = p.parse('IFNA(1/0,1)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('IFNA(NA(),1)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IFNA(2,1)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+
+ def test_ifs(self):
+ p = Parser(debug=True)
+ ret = p.parse('IFS(1=2,2,2=2,3)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IFS(1=2,2,2=3,3, TRUE,4)')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('IFS(1=2,2,2=3,3, FALSE,4)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#N/A')
+
+ def test_switch(self):
+ p = Parser(debug=True)
+ ret = p.parse('SWITCH(2,2,"lele",3, "lili")')
+ self.assertEqual(ret['result'], 'lele')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SWITCH(4,2,"lele",3, "lili")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#N/A')
+ ret = p.parse('SWITCH(4,2,"lele",3, "lili","default")')
+ self.assertEqual(ret['result'], 'default')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SWITCH(4,2,"lele",3, "lili", 0)')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SWITCH(1)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#N/A')
+
+ def test_not(self):
+ p = Parser(debug=True)
+ ret = p.parse('NOT(TRUE())')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('NOT(FALSE())')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+
+ def test_or(self):
+ p = Parser(debug=True)
+ ret = p.parse('OR(TRUE,TRUE, FALSE)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('OR(TRUE,TRUE, TRUE)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('OR(FALSE)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('OR(TRUE)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+
+ def test_xor(self):
+ p = Parser(debug=True)
+ ret = p.parse('XOR(3>0,2<9)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('XOR(3>12,4>6)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('XOR(3>12,4>2)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_lookupandreference.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_lookupandreference.py
new file mode 100644
index 0000000000000000000000000000000000000000..d69efad5699ca5f2e16765b97ed8461d662e69d7
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_lookupandreference.py
@@ -0,0 +1,87 @@
+# -*- coding: utf-8 -*-
+import unittest
+from hotxlfp import Parser
+
+
+class TestLookupAndReference(unittest.TestCase):
+
+ def test_choose(self):
+ p = Parser(debug=True)
+ ret = p.parse('CHOOSE(1,1,3)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CHOOSE(2,1,3)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CHOOSE(255,1,3)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('CHOOSE(3,1,3)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('CHOOSE(1)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#N/A')
+
+ def test_match(self):
+ p = Parser(debug=True)
+ ret = p.parse('MATCH(39,{25,38,40,41},1)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MATCH("f?o",{"eee","aaa","foa","foo"},0)')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MATCH(39,{25,38,40,41},-1)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+
+ def test_index(self):
+ p = Parser(debug=True)
+ ret = p.parse('INDEX({25,38,40,41},1)')
+ self.assertEqual(ret['result'], 25)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INDEX({1\\2\\3\\4;5\\6\\7\\8};2;1)')
+ self.assertEqual(ret['result'], 5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INDEX({1;2;3;4};2;2)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#REF!')
+ ret = p.parse('INDEX({1;2;3;4})')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('INDEX({1,2,3;4,5,6};;2)')
+ self.assertEqual(ret['result'], [2, 5])
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INDEX({1,2,3},,2)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUM(INDEX({1,2,3;4,5,6};0;2))')
+ self.assertEqual(ret['result'], 7)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INDEX({1;2;3};2;)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INDEX({1,2,3},2,)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INDEX({1;2;3};;1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('INDEX({1;2;3};1/0;)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('INDEX(1,1,1)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INDEX(1,1,2)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#REF!')
+ ret = p.parse('SUM(INDEX({1,2,3},0,0))')
+ self.assertEqual(ret['result'], 6)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INDEX({1}*2,1,1)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INDEX({1,2}*2,1,1)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_mathtrig.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_mathtrig.py
new file mode 100644
index 0000000000000000000000000000000000000000..206bd3cfdbe4e18506fb86783fa021356b8ed088
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_mathtrig.py
@@ -0,0 +1,615 @@
+# -*- coding: utf-8 -*-
+import unittest
+import math
+from hotxlfp import Parser
+
+
+class TestMathTrig(unittest.TestCase):
+
+ def test_abs(self):
+ p = Parser(debug=True)
+ ret = p.parse('ABS(1)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ABS(-1)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ABS("a")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+
+ def test_acos(self):
+ p = Parser(debug=True)
+ ret = p.parse('ACOS(-0.5)')
+ self.assertTrue(str(ret['result']).startswith('2.094395102'))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ACOS(-0.5)*180/PI()')
+ self.assertTrue(str(ret['result']).startswith('120.0'))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ACOS(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_acosh(self):
+ p = Parser(debug=True)
+ ret = p.parse('ACOSH(1)')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ACOSH(10)')
+ self.assertTrue(str(ret['result']).startswith('2.9932228'))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ACOSH(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_acot(self):
+ p = Parser(debug=True)
+ ret = p.parse('ACOT(2)')
+ self.assertTrue(str(ret['result']).startswith('0.4636'))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ACOT(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_acoth(self):
+ p = Parser(debug=True)
+ ret = p.parse('ACOTH(6)')
+ self.assertTrue(str(ret['result']).startswith('0.168'))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ACOTH(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_sin(self):
+ p = Parser(debug=True)
+ ret = p.parse('SIN(PI()/2)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SIN(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_sinh(self):
+ p = Parser(debug=True)
+ ret = p.parse('2.868*SINH(0.0342*1.03)')
+ self.assertAlmostEqual(ret['result'], 0.1010491, places=7)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SINH(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_asin(self):
+ p = Parser(debug=True)
+ ret = p.parse('ASIN(-0.5)')
+ self.assertAlmostEqual(ret['result'], -0.523598776, places=9)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ASIN(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_asinh(self):
+ p = Parser(debug=True)
+ ret = p.parse('ASINH(-2.5)')
+ self.assertAlmostEqual(ret['result'], -1.647231146, places=9)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ASINH(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_cos(self):
+ p = Parser(debug=True)
+ ret = p.parse('COS(0)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('COS(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_cosh(self):
+ p = Parser(debug=True)
+ ret = p.parse('COSH(4)')
+ self.assertAlmostEqual(ret['result'], 27.308233, places=6)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('COSH(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_cot(self):
+ p = Parser(debug=True)
+ ret = p.parse('COT(30)')
+ self.assertAlmostEqual(ret['result'], -0.156, places=3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('COT(45)')
+ self.assertAlmostEqual(ret['result'], 0.617, places=3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('COT(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_tan(self):
+ p = Parser(debug=True)
+ ret = p.parse('TAN(45*PI()/180)')
+ self.assertAlmostEqual(ret['result'], 1, places=9)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TAN(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_tanh(self):
+ p = Parser(debug=True)
+ ret = p.parse('TANH(0.5)')
+ self.assertAlmostEqual(ret['result'], 0.462117, places=6)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TANH(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_atan(self):
+ p = Parser(debug=True)
+ ret = p.parse('ATAN(1)*180/PI()')
+ self.assertEqual(ret['result'], 45)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ATAN(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_atan2(self):
+ p = Parser(debug=True)
+ ret = p.parse('ATAN2(1, 1)')
+ self.assertAlmostEqual(ret['result'], 0.785398163, places=9)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ATAN2(1, 0.8)')
+ self.assertAlmostEqual(ret['result'], 0.674740942, places=9)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ATAN2(0, 0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_atanh(self):
+ p = Parser(debug=True)
+ ret = p.parse('ATANH(0.76159416)')
+ self.assertAlmostEqual(ret['result'], 1.00000001, places=9)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ATANH(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_sqrt(self):
+ p = Parser(debug=True)
+ ret = p.parse('SQRT(16)')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SQRT(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_round(self):
+ p = Parser(debug=True)
+ ret = p.parse('ROUND(23.7825, 2)')
+ self.assertEqual(ret['result'], 23.78)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ROUND(23.789, 2)')
+ self.assertEqual(ret['result'], 23.79)
+ self.assertEqual(ret['error'], None)
+
+ def test_roundup(self):
+ p = Parser(debug=True)
+ ret = p.parse('ROUNDUP(23.7825, 2)')
+ self.assertEqual(ret['result'], 23.79)
+ self.assertEqual(ret['error'], None)
+
+ def test_rounddown(self):
+ p = Parser(debug=True)
+ ret = p.parse('ROUNDDOWN(23.7895, 2)')
+ self.assertEqual(ret['result'], 23.78)
+ self.assertEqual(ret['error'], None)
+
+ def test_ln(self):
+ p = Parser(debug=True)
+ ret = p.parse('LN(EXP(1))')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LN(EXP(3))')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+
+ def test_log(self):
+ p = Parser(debug=True)
+ ret = p.parse('LOG(10)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LOG(8, 2)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+
+ def test_log10(self):
+ p = Parser(debug=True)
+ ret = p.parse('LOG10(10)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LOG10(100000)')
+ self.assertEqual(ret['result'], 5)
+ self.assertEqual(ret['error'], None)
+
+ def test_sum(self):
+ p = Parser(debug=True)
+ ret = p.parse('SUM(10)')
+ self.assertEqual(ret['result'], 10)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUM(1;2)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUM(1;2;"aa")')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUM(1;2;{4;5};"aa")')
+ self.assertEqual(ret['result'], 12)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUM(,,,)')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUM(TRUE,,"2")')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+
+ def test_sumif(self):
+ p = Parser(debug=True)
+ ret = p.parse('SUMIF({1;4;5}, ">0")')
+ self.assertEqual(ret['result'], 10)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUMIF({1;4;5}, ">1")')
+ self.assertEqual(ret['result'], 9)
+ self.assertEqual(ret['error'], None)
+
+ def test_ceiling(self):
+ p = Parser(debug=True)
+ ret = p.parse('CEILING(2.5, 1)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CEILING(-2.5, -2)')
+ self.assertEqual(ret['result'], -4)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CEILING(-2.5, 2)')
+ self.assertEqual(ret['result'], -2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CEILING(1.5, 0.1)')
+ self.assertEqual(ret['result'], 1.5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CEILING(0.234, 0.01)')
+ self.assertEqual(ret['result'], 0.24)
+ self.assertEqual(ret['error'], None)
+
+ def test_floor(self):
+ p = Parser(debug=True)
+ ret = p.parse('FLOOR(3.7,2)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FLOOR(-2.5,-2)')
+ self.assertEqual(ret['result'], -2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FLOOR(2.5,-2)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#NUM!')
+ ret = p.parse('FLOOR(1.58,0.1)')
+ self.assertEqual(ret['result'], 1.5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FLOOR(0.234,0.01)')
+ self.assertEqual(ret['result'], 0.23)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FLOOR(-5.6; 1)')
+ self.assertEqual(ret['result'], -6)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FLOOR(-5.6; -1)')
+ self.assertEqual(ret['result'], -5)
+ self.assertEqual(ret['error'], None)
+
+
+ def test_quotient(self):
+ p = Parser(debug=True)
+ ret = p.parse('QUOTIENT(5, 2)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('QUOTIENT(4.5, 3.1)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('QUOTIENT(-10, 3)')
+ self.assertEqual(ret['result'], -3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('QUOTIENT(3, 0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_mod(self):
+ p = Parser(debug=True)
+ ret = p.parse('MOD(3, 2)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MOD(-3, 2)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MOD(3, -2)')
+ self.assertEqual(ret['result'], -1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MOD(-3, -2)')
+ self.assertEqual(ret['result'], -1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MOD(1/0, 1)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('MOD(1, 1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('MOD(3, 0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_radians(self):
+ p = Parser(debug=True)
+ ret = p.parse('RADIANS(270)')
+ self.assertTrue(str(ret['result']).startswith('4.7123'))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('RADIANS(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_degrees(self):
+ p = Parser(debug=True)
+ ret = p.parse('DEGREES(PI())')
+ self.assertEqual(ret['result'], 180)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DEGREES(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_power(self):
+ p = Parser(debug=True)
+ ret = p.parse('POWER(5,2)')
+ self.assertEqual(ret['result'], 25)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('POWER(98.6,3.2)')
+ self.assertTrue(str(ret['result']).startswith('2401077.222'))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('POWER(4,5/4)')
+ self.assertTrue(str(ret['result']).startswith('5.656854249'))
+ self.assertEqual(ret['error'], None)
+
+ def test_product(self):
+ p = Parser(debug=True)
+ ret = p.parse('PRODUCT(10)')
+ self.assertEqual(ret['result'], 10)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('PRODUCT(1;2)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('PRODUCT(1;2;"aa")')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('PRODUCT(1;2;{4;5};"aa")')
+ self.assertEqual(ret['result'], 40)
+ self.assertEqual(ret['error'], None)
+
+ def test_odd(self):
+ p = Parser(debug=True)
+ ret = p.parse('ODD(1.5)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ODD(3)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ODD(2)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ODD(-1)')
+ self.assertEqual(ret['result'], -1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ODD(-2)')
+ self.assertEqual(ret['result'], -3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ODD(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_even(self):
+ p = Parser(debug=True)
+ ret = p.parse('EVEN(1.5)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EVEN(3)')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EVEN(2)')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EVEN(-1)')
+ self.assertEqual(ret['result'], -2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('EVEN(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_decimal(self):
+ p = Parser(debug=True)
+ ret = p.parse('DECIMAL("FF";16)')
+ self.assertEqual(ret['result'], 255)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DECIMAL(111;2)')
+ self.assertEqual(ret['result'], 7)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DECIMAL("zap";36)')
+ self.assertEqual(ret['result'], 45745)
+ self.assertEqual(ret['error'], None)
+
+ def test_base(self):
+ p = Parser(debug=True)
+ ret = p.parse('BASE(7,2)')
+ self.assertEqual(ret['result'], '111')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('BASE(100,16)')
+ self.assertEqual(ret['result'], '64')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('BASE(15,2,10)')
+ self.assertEqual(ret['result'], '0000001111')
+ self.assertEqual(ret['error'], None)
+
+ def test_fact(self):
+ p = Parser(debug=True)
+ ret = p.parse('FACT(5)')
+ self.assertEqual(ret['result'], 120)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FACT(1.9)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FACT(0)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FACT(-1)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#NUM!')
+ ret = p.parse('FACT(1)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+
+ def test_factdouble(self):
+ p = Parser(debug=True)
+ ret = p.parse('FACTDOUBLE(6)')
+ self.assertEqual(ret['result'], 48)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FACTDOUBLE(7)')
+ self.assertEqual(ret['result'], 105)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FACTDOUBLE(0)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FACTDOUBLE(1)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FACTDOUBLE(-10)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#NUM!')
+ ret = p.parse('FACTDOUBLE("foo")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+
+ def test_roman(self):
+ p = Parser(debug=True)
+ ret = p.parse('ROMAN(499,0)')
+ self.assertEqual(ret['result'], 'CDXCIX')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ROMAN(499,1)')
+ self.assertEqual(ret['result'], 'LDVLIV')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ROMAN(499,2)')
+ self.assertEqual(ret['result'], 'XDIX')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ROMAN(499,3)')
+ self.assertEqual(ret['result'], 'VDIV')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ROMAN(499,4)')
+ self.assertEqual(ret['result'], 'ID')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ROMAN(4000)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('ROMAN(499,TRUE())')
+ self.assertEqual(ret['result'], 'CDXCIX')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ROMAN(499,FALSE())')
+ self.assertEqual(ret['result'], 'ID')
+ self.assertEqual(ret['error'], None)
+
+ def test_arabic(self):
+ p = Parser(debug=True)
+ ret = p.parse('ARABIC("M")')
+ self.assertEqual(ret['result'], 1000)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ARABIC("LVII")')
+ self.assertEqual(ret['result'], 57)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ARABIC("mcmxii")')
+ self.assertEqual(ret['result'], 1912)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ARABIC(ROMAN(499))')
+ self.assertEqual(ret['result'], 499)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('ARABIC(ROMAN(499, 4))')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+
+ def test_rand(self):
+ p = Parser()
+ ret = p.parse('RAND(2)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#ERROR!')
+ for i in range(1000):
+ ret = p.parse('RAND()')
+ self.assertGreaterEqual(ret['result'], 0)
+ self.assertLessEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+
+ def test_randbetween(self):
+ p = Parser()
+ ret = p.parse('RANDBETWEEN(2)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#ERROR!')
+ ret = p.parse('RANDBETWEEN("a", 2)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('RANDBETWEEN(2, "a")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ for i in range(1000):
+ ret = p.parse('RANDBETWEEN(10; 100)')
+ self.assertGreaterEqual(ret['result'], 10)
+ self.assertLessEqual(ret['result'], 100)
+ self.assertEqual(ret['error'], None)
+
+ def test_int(self):
+ p = Parser()
+ ret = p.parse('INT(101.001)')
+ self.assertEqual(ret['result'], 101)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INT(99.99)')
+ self.assertEqual(ret['result'], 99)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INT(0)')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INT(-10.8)')
+ self.assertEqual(ret['result'], -11)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INT(-72.34)')
+ self.assertEqual(ret['result'], -73)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('INT(-72)')
+ self.assertEqual(ret['result'], -72)
+ self.assertEqual(ret['error'], None)
+
+ def test_sumifs(self):
+ p = Parser(debug=True)
+ ret = p.parse('SUMIFS({1;4;5;100}, {1;4;5;100},"<>200")')
+ self.assertEqual(ret['result'], 110)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUMIFS({1;4;5}, {3;5;9},"<7")')
+ self.assertEqual(ret['result'], 5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUMIFS({1;4;5}, ">1","<5")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#ERROR!')
+ ret = p.parse('SUMIFS({1;4;5;100}, {1;4;5;100},"<>200", {1;4;300;100},"<100", {2;-3;5;2},">1")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+
+ def test_sign(self):
+ p = Parser(debug=True)
+ ret = p.parse('SIGN(2)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SIGN(-2)')
+ self.assertEqual(ret['result'], -1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SIGN(0)')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SIGN("a")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_operators.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_operators.py
new file mode 100644
index 0000000000000000000000000000000000000000..6be99834e5c13dca52904fe84c668f45eec9bfca
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_operators.py
@@ -0,0 +1,660 @@
+# -*- coding: utf-8 -*-
+import unittest
+import datetime
+from hotxlfp import Parser
+
+
+class TestOperators(unittest.TestCase):
+
+ def test_plus(self):
+ p = Parser(debug=True)
+ ret = p.parse('1 + 1')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('1 + "lele"')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('1 + "2"')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+
+ def test_minus(self):
+ p = Parser(debug=True)
+ ret = p.parse('1 - 1')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('1 - "lele"')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+
+ def test_mult(self):
+ p = Parser(debug=True)
+ ret = p.parse('4*2')
+ self.assertEqual(ret['result'], 8)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('4*"lele"')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+
+ def test_div(self):
+ p = Parser(debug=True)
+ ret = p.parse('4/2')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('5/2')
+ self.assertEqual(ret['result'], 2.5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('4/"lele"')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('5/0')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_logic(self):
+ p = Parser(debug=True)
+ # Numbers
+ ret = p.parse('3 = 2')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('4 <> 2')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('3 > 2')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('2 < 3')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('3 >= 2')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('3 <= 2')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('3 < .4')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('3 < 0.4')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('3 > .4')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('3 > 0.4')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('3 >= 0.4')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('3 <= 0.4')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ # Strings
+ ret = p.parse('"3" = "2"')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('"4" <> "2"')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('"3" > "2"')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('"2" < "3"')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('"3" >= "2"')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('"3" <= "2"')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('""=0')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ # booleans are bigger than strings
+ ret = p.parse('FALSE>"true"')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TRUE>"true"')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('FALSE<"true"')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TRUE<"true"')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('"true"TRUE')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('"true">FALSE')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ # strings are bigger than numbers
+ ret = p.parse('"a" > 2')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('"a" < 2')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('"2">2')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('2<"2"')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('2>"2"')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ # strings are bigger than dates
+ ret = p.parse('"a">DATE(2019,11,20)')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('"1"B3')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('-1B3')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('DATE(1800,11,20)B3')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('B41')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('B3<1')
+ self.assertEqual(ret['result'], True)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('B3>""')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('B3>DATE(2000; 1; 2)')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('B3>TRUE')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('B3>FALSE')
+ self.assertEqual(ret['result'], False)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('B32")')
+ self.assertEqual(ret['result'], 3.5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('AVERAGEIF({1;2;3;4};">2";{4;3;2;1})')
+ self.assertEqual(ret['result'], 1.5)
+ self.assertEqual(ret['error'], None)
+
+ def test_count(self):
+ p = Parser(debug=True)
+ ret = p.parse('COUNT(1;"2")')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ # with an array
+ ret = p.parse('COUNT({1;2;3;4})')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+
+ def test_counta(self):
+ p = Parser(debug=True)
+ ret = p.parse('COUNTA(1;"2")')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ # with an array
+ ret = p.parse('COUNTA({1;2;3;""})')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('COUNTA(1;2;3;NULL)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+
+ def test_countblank(self):
+ p = Parser(debug=True)
+ ret = p.parse('COUNTBLANK(1;"2")')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('COUNTBLANK(1;2;3;"")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('COUNTBLANK(1;2;3;NULL)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ # with an array
+ ret = p.parse('COUNTBLANK({1;2;3;4})')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('COUNTBLANK({1;2;3;""})')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+
+ def test_countif(self):
+ p = Parser(debug=True)
+ ret = p.parse('COUNTIF({1;3};">2")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('COUNTIF({"foo";"bar"};"foo")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('COUNTIF({"foo bar";"baz"};"foo bar")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse(u'COUNTIF({"áà ãâä";"baz"}; "áà ãâä")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse(u'COUNTIF({"áà ã,â,ä";"baz"}; "áà ã,â,ä")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse(u'COUNTIF({"áà ã(â)ä";"baz"}; "áà ã(â)ä")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+
+ def test_max(self):
+ p = Parser(debug=True)
+ ret = p.parse('MAX({1;3};4)')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MAX({1;2;3})')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+
+ def test_min(self):
+ p = Parser(debug=True)
+ ret = p.parse('MIN({1;3};0)')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MIN({1;2;3})')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+
+ def test_var(self):
+ p = Parser(debug=True)
+ ret = p.parse('VAR.S({1345;1301;1368;1322;1310;1370;1318;1350;1303;1299})')
+ self.assertTrue(str(ret['result']).startswith('754.2'))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('VAR.P({1345;1301;1368;1322;1310;1370;1318;1350;1303;1299})')
+ self.assertEqual(ret['result'], 678.84)
+ self.assertEqual(ret['error'], None)
+
+ def test_stdev(self):
+ p = Parser(debug=True)
+ ret = p.parse('STDEV.S({1345;1301;1368;1322;1310;1370;1318;1350;1303;1299})')
+ self.assertTrue(str(ret['result']).startswith('27.46'))
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('STDEV.P({1345;1301;1368;1322;1310;1370;1318;1350;1303;1299})')
+ self.assertTrue(str(ret['result']).startswith('26.05'))
+ self.assertEqual(ret['error'], None)
+
+ def test_median(self):
+ p = Parser(debug=True)
+ ret = p.parse('MEDIAN({1;2;3;4;5;6})')
+ self.assertEqual(ret['result'], 3.5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MEDIAN({1;2;3;4;5})')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MEDIAN({1;2;3;4;5;"lala"})')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+
+ def test_mode(self):
+ p = Parser(debug=True)
+ ret = p.parse('MODE({5.6;4;4;3;2;4})')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+
+ def test_averagifs(self):
+ p = Parser(debug=True)
+ ret = p.parse('AVERAGEIFS({1;2;3;4};{1;2;3;4};">2")')
+ self.assertEqual(ret['result'], 3.5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('AVERAGEIFS({1;2;3;4};{4;3;2;1};">2")')
+ self.assertEqual(ret['result'], 1.5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('AVERAGEIFS({1;2;3;4};{4;3;2;1};">2";{1;2;3;4};"<> 3")')
+ self.assertEqual(ret['result'], 1.5)
+ self.assertEqual(ret['error'], None)
+
+ def test_maxifs(self):
+ p = Parser(debug=True)
+ ret = p.parse('MAXIFS({1;2;3;4};{1;2;3;4};">2")')
+ self.assertEqual(ret['result'], 4)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MAXIFS({1;2;3;4};{4;3;2;1};">2")')
+ self.assertEqual(ret['result'], 2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('MAXIFS({1;2;3;4};{4;3;2;1};">3";{1;2;3;4};"<>3")')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+
+ def test_slope(self):
+ p = Parser(debug=True)
+ ret = p.parse('SLOPE(1;2;3;4;1;2;3;4)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SLOPE(6,2,-2,-4,-6,-2,0,2,3,4)')
+ self.assertEqual(ret['result'], -2)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SLOPE(6,1,2,4)')
+ self.assertEqual(ret['result'], -2.5)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SLOPE(6,1)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_text.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fdbf07999e3021e0eb756870bb23999208ae8a4
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_text.py
@@ -0,0 +1,271 @@
+# -*- coding: utf-8 -*-
+import unittest
+import math
+from hotxlfp import Parser
+
+
+class TestText(unittest.TestCase):
+
+ def test_char(self):
+ p = Parser(debug=True)
+ ret = p.parse('CHAR(65)')
+ self.assertEqual(ret['result'], 'A')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CHAR(33)')
+ self.assertEqual(ret['result'], '!')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CHAR(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_code(self):
+ p = Parser(debug=True)
+ ret = p.parse('CODE("A")')
+ self.assertEqual(ret['result'], 65)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CODE("!")')
+ self.assertEqual(ret['result'], 33)
+ self.assertEqual(ret['error'], None)
+
+ def test_clean(self):
+ p = Parser(debug=True)
+ ret = p.parse('CLEAN(CHAR(9)&"Monthly report"&CHAR(10))')
+ self.assertEqual(ret['result'], 'Monthly report')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CLEAN(B3)')
+ self.assertEqual(ret['result'], '')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('CLEAN(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+ ret = p.parse('CLEAN(223)')
+ self.assertEqual(ret['result'], '223')
+ self.assertEqual(ret['error'], None)
+
+ def test_concatenate(self):
+ p = Parser(debug=True)
+ ret = p.parse('CONCAT("The"," ","sun"," ","will"," ","come"," ","up"," ","tomorrow.")')
+ self.assertEqual(ret['result'], 'The sun will come up tomorrow.')
+ self.assertEqual(ret['error'], None)
+
+ def test_len(self):
+ p = Parser(debug=True)
+ ret = p.parse('LEN("Phoenix, AZ")')
+ self.assertEqual(ret['result'], 11)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LEN(" One ")')
+ self.assertEqual(ret['result'], 11)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LEN(B3)')
+ self.assertEqual(ret['result'], 0)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LEN(3)')
+ self.assertEqual(ret['result'], 1)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LEN(223)')
+ self.assertEqual(ret['result'], 3)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LEN(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+
+ def test_lower(self):
+ p = Parser(debug=True)
+ ret = p.parse('LOWER("aBcDe")')
+ self.assertEqual(ret['result'], 'abcde')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LOWER(B3)')
+ self.assertEqual(ret['result'], '')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LOWER(223)')
+ self.assertEqual(ret['result'], '223')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('LOWER(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_upper(self):
+ p = Parser(debug=True)
+ ret = p.parse('UPPER("aBcDe")')
+ self.assertEqual(ret['result'], 'ABCDE')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('UPPER(B3)')
+ self.assertEqual(ret['result'], '')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('UPPER(223)')
+ self.assertEqual(ret['result'], '223')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('UPPER(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_proper(self):
+ p = Parser(debug=True)
+ ret = p.parse('PROPER("aBcDe")')
+ self.assertEqual(ret['result'], 'Abcde')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('PROPER("76budGet")')
+ self.assertEqual(ret['result'], '76Budget')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('PROPER(B3)')
+ self.assertEqual(ret['result'], '')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('PROPER(223)')
+ self.assertEqual(ret['result'], '223')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('PROPER(1/0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#DIV/0!')
+
+ def test_substitute(self):
+ p = Parser(debug=True)
+ ret = p.parse('SUBSTITUTE("ccc", "a", "b")')
+ self.assertEqual(ret['result'], 'ccc')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUBSTITUTE("ccc", "a", "b", 2)')
+ self.assertEqual(ret['result'], 'ccc')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUBSTITUTE("ola a todos e todas as meninas e os meninos", "a", "b")')
+ self.assertEqual(ret['result'], "olb b todos e todbs bs meninbs e os meninos")
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUBSTITUTE("ola a todos e todas as meninas e os meninos", "a", "b", 2)')
+ self.assertEqual(ret['result'], "ola b todos e todas as meninas e os meninos")
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUBSTITUTE("ola a todos e todas as meninas e os meninos", "a", "b", 0)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('SUBSTITUTE("ola a todos e todas as meninas e os meninos", "os", "a", 3)')
+ self.assertEqual(ret['result'], "ola a todos e todas as meninas e os menina")
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUBSTITUTE("ola a todos e todas as meninas e os meninos", "os", "a", 2)')
+ self.assertEqual(ret['result'], "ola a todos e todas as meninas e a meninos")
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUBSTITUTE("ola a todos e todas as meninas e os meninos", "a", "b", "a")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('SUBSTITUTE(, "a", "b", "a")')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+ ret = p.parse('SUBSTITUTE(;;)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('SUBSTITUTE(;;;)')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+
+ def test_textjoin(self):
+ p = Parser(debug=True)
+ ret = p.parse('TEXTJOIN(";", TRUE, {"1";"2";"3"})')
+ self.assertEqual(ret['result'], '1;2;3')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXTJOIN(";", TRUE, {"1",,"2","3"})')
+ self.assertEqual(ret['result'], '1;2;3')
+ ret = p.parse('TEXTJOIN(";", FALSE, {"1",,"2","3"})')
+ self.assertEqual(ret['result'], '1;;2;3')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXTJOIN(1, FALSE, {"1",,"2","3"})')
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#VALUE!')
+
+ def test_text(self):
+ p = Parser(debug=True)
+ ret = p.parse('TEXT(100.25,"???/???")')
+ self.assertEqual(ret['result'], '401/4')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2024,4,3),"yyyy")')
+ self.assertEqual(ret['result'], '2024')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"yy")')
+ self.assertEqual(ret['result'], '04')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"mmmmm")')
+ self.assertEqual(ret['result'], 'A')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"mmmm")')
+ self.assertEqual(ret['result'], 'April')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"mmm")')
+ self.assertEqual(ret['result'], 'Apr')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"mm")')
+ self.assertEqual(ret['result'], '04')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"m")')
+ self.assertEqual(ret['result'], '4')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"dddd")')
+ self.assertEqual(ret['result'], 'Saturday')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"ddd")')
+ self.assertEqual(ret['result'], 'Sat')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"dd")')
+ self.assertEqual(ret['result'], '03')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"d")')
+ self.assertEqual(ret['result'], '3')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"dd-mm-yyy")')
+ self.assertEqual(ret['result'], '03-04-2004')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"dddd, mmmm dd")')
+ self.assertEqual(ret['result'], 'Saturday, April 03')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"ddd, mmm d")')
+ self.assertEqual(ret['result'], 'Sat, Apr 3')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(DATE(2004,4,3),"mmmmm yy")')
+ self.assertEqual(ret['result'], 'A 04')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(100,"$#,##0")')
+ self.assertEqual(ret['result'], '$100')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(100,"#,##0€")')
+ self.assertEqual(ret['result'], '100€')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(0.85,"0%")')
+ self.assertEqual(ret['result'], '85%')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(0.85,"0")')
+ self.assertEqual(ret['result'], '1')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(0.5,"0")')
+ self.assertEqual(ret['result'], '1')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(0.4,"0")')
+ self.assertEqual(ret['result'], '0')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(3.141592654,"0.000")')
+ self.assertEqual(ret['result'], '3.142')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(25000000000,"0.0E+00")')
+ self.assertEqual(ret['result'], '2.5E+10')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(8.9,"#.000")')
+ self.assertEqual(ret['result'], '8.900')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(.631,"0.#")')
+ self.assertEqual(ret['result'], '0.6')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(1234.568,"#.0#")')
+ self.assertEqual(ret['result'], '1234.57')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(1234.59,"####.#")')
+ self.assertEqual(ret['result'], '1234.6')
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(8.9, "#.000")')
+ self.assertEqual(ret['result'], "8.900")
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(.631, "0.#")')
+ self.assertEqual(ret['result'], "0.6")
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(1234.568, "#.0#")')
+ self.assertEqual(ret['result'], "1234.57")
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(12, "#.0#")')
+ self.assertEqual(ret['result'], "12.00")
+ self.assertEqual(ret['error'], None)
+ ret = p.parse('TEXT(5.25, "# ???/???")')
+ self.assertEqual(ret['result'], "5 1/4")
+ self.assertEqual(ret['error'], None)
\ No newline at end of file
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_tinyemitter.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_tinyemitter.py
new file mode 100644
index 0000000000000000000000000000000000000000..c93435e642ae4de549928e6e0f2c10569c31ea08
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_tinyemitter.py
@@ -0,0 +1,109 @@
+# -*- coding: utf-8 -*-
+import unittest
+from hotxlfp.tinyemitter import Emitter
+
+
+class TestEmitter(unittest.TestCase):
+
+ def test_subscribes(self):
+ """ Subscribes to an event """
+ emitter = Emitter()
+ emitter.on('test', lambda: None)
+ self.assertEqual(len(emitter._e['test']), 1)
+
+ def test_subscribes_with_context(self):
+ """ Subscribes to an event and context is passed """
+ emitter = Emitter()
+ context = {'context_value': True}
+
+ def ctxfunc(context_value=None):
+ self.assertTrue(context_value)
+
+ emitter.on('test', ctxfunc, context)
+ emitter.emit('test')
+
+ def test_only_once(self):
+ """ Subscribes to an event only once"""
+ emitter = Emitter()
+
+ def callmeonce():
+ self.assertNotIn('test', emitter._e)
+
+ emitter.once('test', callmeonce)
+ emitter.emit('test')
+
+ def test_only_once_context(self):
+ """ Subscribing to an event only once keeps context """
+ emitter = Emitter()
+ context = {'context_value': True}
+
+ def callmeonce(context_value=None):
+ self.assertTrue(context_value)
+ self.assertNotIn('test', emitter._e)
+
+ emitter.once('test', callmeonce, context)
+ emitter.emit('test')
+
+ def test_emit(self):
+ """ Emits an event """
+ emitter = Emitter()
+ function_called = {'value': False}
+
+ def wasicalled():
+ function_called['value'] = True
+
+ emitter.on('test', wasicalled)
+ emitter.emit('test')
+ self.assertTrue(function_called['value'])
+
+ def test_args(self):
+ """ Passes all arguments to event listener """
+ emitter = Emitter()
+ function_called = {'value': False}
+
+ def twoargs(arg1, arg2):
+ self.assertEqual(arg1, 'arg1')
+ self.assertEqual(arg2, 'arg2')
+
+ emitter.on('test', twoargs)
+ emitter.emit('test', 'arg1', 'arg2')
+
+ def test_unsubscribe(self):
+ """ Unsubscribes all listeners for events with name """
+ emitter = Emitter()
+
+ def dontcallme(arg1, arg2):
+ self.fail('Called an unsubscribed function')
+
+ emitter.on('test', dontcallme)
+ emitter.off('test')
+ emitter.emit('test')
+
+ def test_unsubscribe_single(self):
+ """ Unsubscribes one listener for events with name """
+ emitter = Emitter()
+ function_called = {'value': False}
+
+ def dontcallme(arg1, arg2):
+ self.fail('Called an unsubscribed function')
+
+ def wasicalled():
+ function_called['value'] = True
+
+ emitter.on('test', dontcallme)
+ emitter.on('test', wasicalled)
+ emitter.off('test', dontcallme)
+ emitter.emit('test')
+ self.assertTrue(function_called['value'])
+
+ def test_remove_inside_event(self):
+ """ Removes an event inside another event """
+ emitter = Emitter()
+
+ def callme():
+ self.assertEqual(len(emitter._e['test']), 1, 'event is still in the list')
+ emitter.off('test')
+ self.assertNotIn('test', emitter._e)
+
+ emitter.on('test', callme)
+ emitter.emit('test')
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_tinyexcel.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_tinyexcel.py
new file mode 100644
index 0000000000000000000000000000000000000000..88909c5b4c2b296b07f96bd5ee24c5e308de3c7c
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_tinyexcel.py
@@ -0,0 +1,62 @@
+# -*- coding: utf-8 -*-
+import unittest
+from hotxlfp import Parser
+
+
+class TestTinyExcel(unittest.TestCase):
+
+ def test_tinyexcel(self):
+ # Our tiny excel table and functions to access it
+ table = [
+ [0, None, None, None],
+ [1, None, None, None],
+ [2, None, None, None],
+ [3, None, None, None],
+ [4, None, None, None]
+ ]
+
+ def cellvalue(cell, valsetter):
+ valsetter(table[cell.row.index][cell.col.index])
+
+ def rangevalue(start, end, valsetter):
+ result = []
+ for i in range(start.row.index, end.row.index + 1):
+ result.append(table[i][start.col.index: end.col.index + 1])
+ valsetter(result)
+
+ # Make and setup our parser
+ p = Parser(debug=True)
+ p.on('callCellValue', cellvalue)
+ p.on('callRangeValue', rangevalue)
+ # Check a cells is blank
+ res = p.parse('ISBLANK(B1)')
+ self.assertEqual(res['result'], True)
+ self.assertEqual(res['error'], None)
+ # Let's try getting a range
+ res = p.parse('A1:A5')
+ self.assertEqual(res['result'], [[0], [1], [2], [3], [4]])
+ self.assertEqual(res['error'], None)
+ # Now use a formula on it
+ res = p.parse('SUM(A1:A5)')
+ self.assertEqual(res['result'], 10)
+ self.assertEqual(res['error'], None)
+ res = p.parse('SUM(A5:A1)')
+ self.assertEqual(res['result'], 10)
+ self.assertEqual(res['error'], None)
+ # Now lets try a custom function
+
+ def triple(x):
+ return x * 3
+ p.set_function('TRIPLE', triple)
+ res = p.parse('TRIPLE(A4)')
+ self.assertEqual(res['result'], 9)
+ self.assertEqual(res['error'], None)
+ # And a custom variable
+ p.set_variable('x', 2)
+ res = p.parse('TRIPLE(x)')
+ self.assertEqual(res['result'], 6)
+ self.assertEqual(res['error'], None)
+
+ # Sanity check
+ self.assertEqual(p.get_function('TRIPLE'), triple)
+ self.assertEqual(p.get_variable('x'), 2)
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_vars.py b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_vars.py
new file mode 100644
index 0000000000000000000000000000000000000000..3032732d9c452ab0cc145875251282ab78fdffe3
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/source/tests/test_vars.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+import unittest
+from hotxlfp import Parser
+
+
+class TestVars(unittest.TestCase):
+
+ def test_undefined(self):
+ p = Parser()
+ ret = p.parse("MY_VAR")
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#NAME?')
+ ret = p.parse("MY_VAR + 5")
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#NAME?')
+ ret = p.parse("5 + MY_VAR")
+ self.assertEqual(ret['result'], None)
+ self.assertEqual(ret['error'], '#NAME?')
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/test.sh b/tasks/tasksmith-a9cb6b87c28d/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..80254c0fc64954034729dff8cdf6a0745fe24aa2
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+set -eu
+exec /usr/local/bin/python -B -I -S /tests/grade.py
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/test_driver.py b/tasks/tasksmith-a9cb6b87c28d/tests/test_driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0b8bb331c4499e300b92f0e022ff6a723a4a562
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/test_driver.py
@@ -0,0 +1,41 @@
+"""Private pytest entry point with a bounded framework-tampering check.
+
+The host still owns reward parsing. This guard detects replacement or in-place
+editing of unittest assertions, a demonstrated attack against repository tests.
+It does not claim to isolate arbitrary test and solution code in one interpreter.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+
+
+def run(arguments: list[str]) -> int:
+ import pytest
+
+ # Capture before pytest imports any repository modules. Retain code objects
+ # too: an attacker can mutate function.__code__ without replacing a method.
+ original = {
+ name: (value, getattr(value, "__code__", None))
+ for name, value in vars(unittest.TestCase).items()
+ if name.startswith("assert") and callable(value)
+ }
+ case = unittest.TestCase
+ # The harness supplies selectors and reporting explicitly. Repository addopts
+ # often enable optional coverage/report plugins that are intentionally not
+ # auto-loaded in this isolated verifier; they are not test dependencies.
+ code = int(pytest.main(["-o", "addopts=", *arguments]))
+ changed = []
+ for name, (method, implementation) in original.items():
+ current = getattr(case, name, None)
+ if current is not method or getattr(current, "__code__", None) is not implementation:
+ changed.append(name)
+ if unittest.TestCase is not case or changed:
+ sys.stderr.write("Verifier framework was modified: " + ", ".join(changed) + "\n")
+ return 254
+ return code
+
+
+if __name__ == "__main__":
+ raise SystemExit(run(sys.argv[1:]))
diff --git a/tasks/tasksmith-a9cb6b87c28d/tests/test_results.py b/tasks/tasksmith-a9cb6b87c28d/tests/test_results.py
new file mode 100644
index 0000000000000000000000000000000000000000..05ce2c730e38e02bad44f2344e88e5f1cb02cb8d
--- /dev/null
+++ b/tasks/tasksmith-a9cb6b87c28d/tests/test_results.py
@@ -0,0 +1,65 @@
+"""Strict test evidence used by repository recipes and their exported verifiers."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from xml.etree import ElementTree
+
+
+@dataclass(frozen=True)
+class TestResults:
+ __test__ = False
+ statuses: dict[str, str]
+ returncode: int
+
+ @property
+ def passed(self) -> set[str]:
+ return {name for name, status in self.statuses.items() if status == "passed"}
+
+
+def parse_junit(text: str, *, returncode: int) -> TestResults:
+ if " dict[str, list[str]]:
+ if healthy.returncode != 0 or not healthy.passed:
+ raise ValueError("Reference must execute successfully with passing tests")
+ if healthy.statuses.keys() != defective.statuses.keys():
+ raise ValueError("Mutation changed test collection; contrast is not comparable")
+ failing = sorted(
+ name for name in healthy.passed if defective.statuses[name] in {"failed", "error"}
+ )
+ if not failing or defective.returncode != 1:
+ raise ValueError("No intended fail-to-pass contrast")
+ return {"FAIL_TO_PASS": failing, "PASS_TO_PASS": sorted(healthy.passed - set(failing))}
diff --git a/tasks/tasksmith-ae872f5c3953/environment/Dockerfile b/tasks/tasksmith-ae872f5c3953/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..0efcbe81b826f272c536cfed4aba01d81dbd519d
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/Dockerfile
@@ -0,0 +1,9 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir hatchling==1.33.0 pytest==9.2.0 pytest-cov==7.1.0 coverage==7.17.3 pytest-mock==3.17.0 pytest-ordering==0.6
+COPY source /workspace
+RUN python -m pip install --no-cache-dir -e .
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
+RUN apt-get update && apt-get install -y --no-install-recommends tmux && rm -rf /var/lib/apt/lists/*
+RUN useradd -m learner && chown -R learner:learner /workspace
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/LICENSE.txt b/tasks/tasksmith-ae872f5c3953/environment/source/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/NOTICE.txt b/tasks/tasksmith-ae872f5c3953/environment/source/NOTICE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f94f7dee49f7d648eb2f4a2bb81882034fa8047d
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/NOTICE.txt
@@ -0,0 +1,13 @@
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/README.md b/tasks/tasksmith-ae872f5c3953/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..89e8459128a79e0f0ec30c6ee48b3b6d48203b2d
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/README.md
@@ -0,0 +1,482 @@
+[](https://pypi.org/project/mail-parser/)
+[](https://coveralls.io/github/SpamScope/mail-parser?branch=develop)
+[](https://pypistats.org/packages/mail-parser)
+
+
+
+# mail-parser
+
+mail-parser is a **production-grade, RFC-compliant email parsing library** that goes far beyond a
+simple wrapper for Python's [email module](https://docs.python.org/2/library/email.message.html).
+It transforms raw email messages into richly structured Python objects with unparalleled precision,
+making complex email processing accessible and reliable.
+
+As the **battle-tested foundation of [SpamScope](https://github.com/SpamScope/spamscope)**—a
+powerful email security and threat analysis platform—mail-parser has proven itself in demanding
+production environments where accuracy and security matter most.
+
+## Why Choose mail-parser?
+
+**🔒 Security-First Design**: Built specifically for email security analysis and digital forensics,
+mail-parser excels at detecting malformed structures, hidden content, and RFC non-compliance that
+could indicate malicious intent.
+
+**🎯 Comprehensive Parsing**: Extracts every component of an email—headers, bodies (plain text and
+HTML), attachments, metadata, routing information, and even subtle defects that other parsers miss.
+
+**🔍 Multi-Format Access**: Every parsed element is accessible in three formats (Python object, raw
+string, and JSON), enabling seamless integration with any workflow or downstream system.
+
+**🛡️ Defect Detection**: Identifies and categorizes RFC violations, malformed MIME boundaries, and
+structural anomalies that could hide malicious payloads or bypass security filters.
+
+**📧 Outlook Support**: Native handling of Microsoft Outlook .msg files alongside standard email
+formats, making it versatile for diverse email ecosystems.
+
+**⚡ Production-Ready**: Trusted by security professionals and developers worldwide, with extensive
+test coverage and proven reliability in high-stakes environments.
+
+Additionally, mail-parser provides full support for parsing Outlook email formats (.msg). To enable
+this functionality on Debian-based systems, simply install the required system package:
+
+```bash
+apt-get install libemail-outlook-message-perl
+```
+
+For further details about the package, you can run:
+
+```bash
+apt-cache show libemail-outlook-message-perl
+```
+
+mail-parser is fully compatible with Python 3, ensuring modern performance and reliability.
+
+# Apache 2 Open Source License
+
+mail-parser can be downloaded, used, and modified free of charge. It is available under the Apache 2 license.
+
+# Support the Future of mail-parser
+
+mail-parser is a **labor of love and commitment to the open-source community**. Thousands of
+developers and security professionals worldwide rely on this library for critical email processing
+and threat analysis. Your support directly fuels continued innovation and excellence.
+
+## Invest in Innovation
+
+Your contribution—no matter the size—makes a real difference. By supporting mail-parser, you enable us to:
+
+- **Advance Security Capabilities**: Develop cutting-edge detection mechanisms for emerging email
+ threats and attack vectors.
+- **Expand Format Support**: Add compatibility with new email formats and standards as they evolve.
+- **Enhance Performance**: Optimize parsing speed and memory efficiency for large-scale deployments.
+- **Maintain Excellence**: Ensure comprehensive testing, documentation, and bug-free releases that
+ you can trust in production.
+- **Foster Community**: Respond to issues, review contributions, and build a thriving ecosystem
+ around email security.
+- **Stay RFC-Compliant**: Keep pace with evolving email standards and specifications to ensure
+ maximum compatibility.
+
+Every donation, whether $5 or $500, directly funds development time and infrastructure costs. Join
+the community of supporters who believe in **accessible, reliable, and secure email parsing for
+everyone**.
+
+[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=VEPXYP745KJF2)
+
+Or contribute with Bitcoin:
+
+
+
+
+
+**Bitcoin Address:** `bc1qxhz3tghztpjqdt7atey68s344wvmugtl55tm32`
+
+Thank you for supporting the evolution of mail-parser!
+
+# mail-parser on Web
+
+Explore mail-parser on these platforms:
+
+- **[FreeBSD port](https://www.freshports.org/mail/py-mail-parser/)**
+- **[Arch User Repository](https://aur.archlinux.org/packages/mailparser/)**
+- **[REMnux](https://docs.remnux.org/discover-the-tools/analyze+documents/email+messages#mail-parser)**
+
+# Description
+
+mail-parser transforms raw email messages into comprehensive, RFC-compliant Python objects that
+faithfully mirror the structure defined by [IETF email protocol standards](https://www.iana.org/assignments/message-headers/message-headers.xhtml).
+Each property of the parsed object directly corresponds to standard RFC headers—"From", "To", "Cc",
+"Bcc", "Subject", and many more—providing intuitive, Pythonic access to every email component.
+
+## Core Parsing Capabilities
+
+The library extracts and structures every aspect of an email message:
+
+- **Multi-format Bodies**: Both plain text and HTML body content, cleanly separated and accessible.
+- **Complete Attachments**: Full metadata extraction including filename, content type, encoding,
+ content disposition, content-ID, charset, and base64-encoded payloads.
+- **Routing Intelligence**: Parsed "Received" headers revealing the complete email journey,
+ including hop-by-hop analysis with timestamps, delays, server information, and envelope data.
+- **Advanced Diagnostics**: Timestamp parsing with timezone detection, defect identification for
+ RFC non-compliance, and structural anomaly detection.
+- **Custom Headers**: Full support for non-standard and vendor-specific headers using intuitive
+ underscore substitution for hyphenated names.
+
+## Triple-Format Property Access
+
+Every parsed element offers **three distinct access patterns** for maximum flexibility:
+
+- **Native Python objects**: Structured, typed data ready for immediate programmatic use
+ (`mail.to`, `mail.date`, `mail.attachments`).
+- **Raw strings**: Original, unprocessed header content preserving exact formatting
+ (`mail.to_raw`, `mail.subject_raw`).
+- **JSON serialization**: Clean, standardized JSON representations for easy integration with APIs,
+ databases, or other tools (`mail.to_json`, `mail.headers_json`).
+
+This versatile architecture makes mail-parser exceptionally powerful for diverse use cases—from
+security analysis and forensics to email migration, compliance auditing, and automated processing
+pipelines.
+
+**Standard RFC Headers** (directly accessible as properties):
+
+- `bcc` - Blind carbon copy recipients
+- `cc` - Carbon copy recipients
+- `date` - Parsed timestamp with timezone support
+- `delivered_to` - Final delivery address
+- `from_` - Sender address (underscore used since `from` is a Python keyword)
+- `message_id` - Unique message identifier
+- `received` - Parsed routing chain with hop-by-hop details
+- `reply_to` - Reply-to address
+- `subject` - Email subject line
+- `to` - Primary recipients
+
+**Additional Parsed Components**:
+
+- `body` - Complete message body
+- `text_html` - HTML body parts (list)
+- `text_plain` - Plain text body parts (list)
+- `headers` - All headers as a structured object
+- `attachments` - Complete attachment metadata and payloads
+- `get_server_ipaddress()` - Reliable sender IP extraction with trust levels
+- `to_domains` - Extracted recipient domains for analysis
+- `timezone` - Detected timezone information
+- `defects` - RFC compliance issues for security analysis
+- `defects_categories` - Categorized defect types
+
+The `attachments` property returns a list of dictionaries, each containing comprehensive metadata:
+
+- `binary` - Boolean flag indicating binary content
+- `charset` - Character encoding of the attachment
+- `content_transfer_encoding` - Transfer encoding method (e.g., base64, quoted-printable)
+- `content-disposition` - Disposition type (attachment, inline, etc.)
+- `content-id` - Content identifier for referencing within HTML bodies
+- `filename` - Original filename of the attachment
+- `mail_content_type` - MIME content type
+- `payload` - Base64-encoded attachment data, ready for decoding or storage
+
+To access custom or vendor-specific headers, replace hyphens with underscores. For example, to
+access the `X-MSMail-Priority` header:
+
+```python
+mail.X_MSMail_Priority
+```
+
+The `received` header is intelligently parsed into individual hops, revealing the complete email
+routing path. Each hop contains structured fields:
+
+- `by` - Receiving mail server
+- `date` - Timestamp of receipt (original timezone)
+- `date_utc` - Normalized UTC timestamp
+- `delay` - Time elapsed between consecutive hops
+- `envelope_from` - SMTP envelope sender
+- `envelope_sender` - Alternative envelope sender field
+- `for` - Intended recipient
+- `from` - Sending mail server
+- `hop` - Sequential hop number
+- `with` - Protocol used for transmission (SMTP, ESMTP, etc.)
+
+> **Critical Security Feature**: mail-parser detects and reports structural defects in email
+> messages.
+
+The [defects](https://docs.python.org/3/library/email.message.html#email.message.Message.defects)
+property identifies RFC non-compliance issues that may indicate malformed or malicious emails—a
+crucial capability for security analysis and threat detection.
+
+**Multi-Format Property Access Pattern**:
+
+All parsed properties provide three access variants using intuitive suffixes:
+
+- `property_name` - Returns structured Python object
+- `property_name_json` - Returns JSON-serialized representation
+- `property_name_raw` - Returns original, unprocessed header string
+
+Example usage:
+
+```python
+mail.to # Python list of recipient objects
+mail.to_json # JSON string representation
+mail.to_raw # Original "To:" header string as it appears in the email
+```
+
+The command-line tool outputs parsed emails in JSON format by default for easy integration with
+other tools and pipelines.
+
+## Defects and Their Critical Role in Email Security
+
+Email structural defects are not merely technical curiosities—they represent **potential security
+vulnerabilities** that sophisticated attackers actively exploit to bypass spam filters, antivirus
+scanners, and email security gateways.
+
+### Real-World Threat Scenarios
+
+Malformed MIME boundaries, for example, can conceal illegitimate epilogue sections containing:
+
+- **Malware Payloads**: Executable files or scripts hidden in non-standard message parts
+- **Phishing Links**: Obfuscated URLs that bypass pattern-matching filters
+- **Command-and-Control Data**: Encoded instructions for compromised systems
+- **Data Exfiltration**: Steganographically hidden sensitive information
+
+### mail-parser's Security Advantage
+
+mail-parser was **specifically engineered for security analysis and digital forensics**, with defect
+detection as a core feature rather than an afterthought. The library captures and categorizes even
+subtle structural anomalies that other parsers silently ignore or mishandle.
+
+By leveraging mail-parser's defect detection, security teams can:
+
+- **Expose Hidden Content**: Discover deliberately obfuscated message parts that may contain
+ malicious payloads.
+- **Identify Attack Patterns**: Recognize non-standard formatting techniques used by threat actors
+ to evade detection.
+- **Enable Deep Forensics**: Conduct thorough structural analysis of suspicious emails during
+ incident response.
+- **Strengthen Defenses**: Build more resilient email security rules based on identified defect
+ patterns.
+- **Ensure Compliance**: Verify that outbound emails meet RFC standards to avoid delivery issues.
+
+This robust defect detection mechanism has made mail-parser the **trusted choice for security
+platforms like SpamScope**, where identifying malicious intent hidden in structural anomalies can
+mean the difference between a blocked threat and a successful attack.
+
+# Authors
+
+## Main Author
+
+**Fedele Mantuano**: [LinkedIn](https://www.linkedin.com/in/fmantuano/)
+
+# Installation
+
+mail-parser requires Python 3 and can be installed in seconds using pip. Follow these steps:
+
+## Quick Install
+
+1. Ensure Python 3 is installed on your system.
+1. Open your terminal or command prompt.
+1. Install mail-parser from PyPI:
+
+```bash
+pip install mail-parser
+```
+
+1. (Optional) Verify the installation:
+
+```bash
+pip show mail-parser
+```
+
+## Development Installation
+
+For contributors and developers who want to work with the source code, we recommend using `uv` for
+dependency management:
+
+```bash
+git clone https://github.com/SpamScope/mail-parser.git
+cd mail-parser
+uv sync
+```
+
+This setup installs all development and testing dependencies in an isolated virtual environment,
+ensuring a clean and reproducible development workflow.
+
+For comprehensive documentation about `uv`, visit the [official uv documentation](https://docs.astral.sh/uv/).
+
+# Usage in a Project
+
+## Basic Usage
+
+Import the `mailparser` module and use the convenient factory functions:
+
+```python
+import mailparser
+
+mail = mailparser.parse_from_bytes(byte_mail) # Parse from bytes object
+mail = mailparser.parse_from_file(f) # Parse from file path
+mail = mailparser.parse_from_file_msg(outlook_mail) # Parse Outlook .msg file
+mail = mailparser.parse_from_file_obj(fp) # Parse from file object
+mail = mailparser.parse_from_string(raw_mail) # Parse from string
+```
+
+## Accessing Parsed Components
+
+Once parsed, access all email components through intuitive properties:
+
+```python
+mail.attachments # List of all attachments with metadata
+mail.body # Complete message body
+mail.date # Parsed datetime object (UTC)
+mail.defects # List of RFC compliance defects
+mail.defects_categories # Categorized defect types
+mail.delivered_to # Delivery address
+mail.from_ # Sender information
+mail.get_server_ipaddress(trust="my_server_mail_trust") # Reliable sender IP
+mail.headers # All headers as structured object
+mail.mail # Fully tokenized mail object
+mail.message # Underlying email.message.Message object
+mail.message_as_string # Reconstructed message as string
+mail.message_id # Unique message identifier
+mail.received # Parsed routing information (hop-by-hop)
+mail.subject # Email subject
+mail.text_plain # Plain text body parts (list)
+mail.text_html # HTML body parts (list)
+mail.text_not_managed # Unprocessed text parts (check logs for subtypes)
+mail.to # Recipient information
+mail.to_domains # Extracted recipient domains
+mail.timezone # Timezone information (offset from UTC)
+mail.mail_partial # Partial mail object (main parts only)
+```
+
+## Saving Attachments to Disk
+
+Write all attachments to a specified directory:
+
+```python
+mail.write_attachments(base_path)
+```
+
+# Usage from Command Line
+
+After installing mail-parser with pip, you can use the `mailparser` command-line tool for quick
+email analysis, batch processing, or integration with shell scripts and pipelines.
+
+## Command-Line Options
+
+```text
+usage: mailparser [-h] (-f FILE | -s STRING | -k)
+ [-l {CRITICAL,ERROR,WARNING,INFO,DEBUG,NOTSET}] [-j] [-b]
+ [-a] [-r] [-t] [-dt] [-m] [-u] [-c] [-d] [-o]
+ [-i Trust mail server string] [-p] [-z] [-v]
+
+Wrapper for email Python Standard Library
+
+optional arguments:
+ -h, --help show this help message and exit
+ -f FILE, --file FILE Raw email file (default: None)
+ -s STRING, --string STRING
+ Raw email string (default: None)
+ -k, --stdin Enable parsing from stdin (default: False)
+ -l {CRITICAL,ERROR,WARNING,INFO,DEBUG,NOTSET}, --log-level {CRITICAL,ERROR,WARNING,INFO,DEBUG,NOTSET}
+ Set log level (default: WARNING)
+ -j, --json Show the JSON of parsed mail (default: False)
+ -b, --body Print the body of mail (default: False)
+ -a, --attachments Print the attachments of mail (default: False)
+ -r, --headers Print the headers of mail (default: False)
+ -t, --to Print the to of mail (default: False)
+ -dt, --delivered-to Print the delivered-to of mail (default: False)
+ -m, --from Print the from of mail (default: False)
+ -u, --subject Print the subject of mail (default: False)
+ -c, --receiveds Print all receiveds of mail (default: False)
+ -d, --defects Print the defects of mail (default: False)
+ -o, --outlook Analyze Outlook msg (default: False)
+ -i Trust mail server string, --senderip Trust mail server string
+ Extract a reliable sender IP address heuristically
+ (default: None)
+ -p, --mail-hash Print mail fingerprints without headers (default:
+ False)
+ -z, --attachments-hash
+ Print attachments with fingerprints (default: False)
+ -sa, --store-attachments
+ Store attachments on disk (default: False)
+ -ap ATTACHMENTS_PATH, --attachments-path ATTACHMENTS_PATH
+ Path where store attachments (default: /tmp)
+ -v, --version show program's version number and exit
+
+It takes as input a raw mail and generates a parsed object.
+```
+
+## Examples
+
+Parse an email file and output as formatted JSON:
+
+```shell
+mailparser -f example_mail -j
+```
+
+Extract only the subject and sender:
+
+```shell
+mailparser -f example_mail -u -m
+```
+
+Analyze an Outlook .msg file with defect detection:
+
+```shell
+mailparser -f email.msg -o -d -j
+```
+
+Parse from stdin (useful for pipelines):
+
+```shell
+cat raw_email.eml | mailparser -k -j
+```
+
+See the transformation from [raw email](https://gist.github.com/fedelemantuano/5dd702004c25a46b2bd60de21e67458e)
+to [beautifully parsed JSON output](https://gist.github.com/fedelemantuano/e958aa2813c898db9d2d09469db8e6f6).
+
+# Exception Hierarchy
+
+mail-parser uses a well-structured exception hierarchy for precise error handling:
+
+```text
+MailParserError: Base MailParser Exception
+|
+\── MailParserOutlookError: Raised with Outlook integration errors
+|
+\── MailParserEnvironmentError: Raised when the environment is not correct
+|
+\── MailParserOSError: Raised when there is an OS error
+|
+\── MailParserReceivedParsingError: Raised when a received header cannot be parsed
+```
+
+# Docker Deployment
+
+A pre-built Docker image is available for easy deployment and containerized workflows. Find the
+[official image on Docker Hub](https://hub.docker.com/r/fmantuano/spamscope-mail-parser/).
+
+## Quick Start with Docker
+
+After installing Docker, run the containerized mail-parser:
+
+```shell
+sudo docker run -it --rm -v ~/mails:/mails fmantuano/spamscope-mail-parser
+```
+
+This command mounts your local `~/mails` directory into the container at `/mails`, allowing
+mail-parser to access your email files. You can pass any command-line options supported by
+mail-parser.
+
+## Using Docker Compose
+
+For more complex setups, a `docker-compose.yml` file is included in the repository. Run it with:
+
+```shell
+sudo docker-compose up
+```
+
+The default configuration includes:
+
+- Read-only mount of your local `~/mails` directory to `/mails` in the container.
+- A test command demonstrating mail-parser functionality.
+
+Customize the `docker-compose.yml` file to adjust mount points, command-line options, or
+environment variables for your specific use case.
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/pyproject.toml b/tasks/tasksmith-ae872f5c3953/environment/source/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..ae9f180b844ca1a1658fb376c6d5543d7b2a196b
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/pyproject.toml
@@ -0,0 +1,103 @@
+[project]
+name = "mail-parser"
+dynamic = ["version"]
+description = "A tool that parses emails by enhancing the Python standard library, extracting all details into a comprehensive object."
+license = "Apache-2.0"
+readme = "README.md"
+requires-python = ">=3.9,<3.15"
+keywords = ["email", "mail", "parser", "security", "forensics", "threat detection", "phishing", "malware", "spam"]
+classifiers = [
+ "Natural Language :: English",
+ "Operating System :: Unix",
+ "Operating System :: MacOS",
+ "Operating System :: Microsoft :: Windows",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.9",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Programming Language :: Python :: 3.14",
+]
+authors = [
+ { name = "Fedele Mantuano", email = "mantuano.fedele@gmail.com" }
+]
+maintainers = [
+ { name = "Fedele Mantuano", email = "mantuano.fedele@gmail.com" }
+]
+dependencies = []
+
+[dependency-groups]
+dev = [
+ "build>=1.2.2.post1",
+ "hatch>=1.14.0",
+ "pre-commit>=4.0.1",
+ "ruff>=0.9.9",
+ "twine>=6.0.1",
+ "wheel>=0.45.1",
+]
+test = [
+ "coverage>=7.6.10",
+ "pytest>=8.3.4",
+ "pytest-cov>=6.0.0",
+ "pytest-mock>=3.14.0",
+ "pytest-ordering>=0.6",
+]
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.uv]
+default-groups = ["dev", "test"]
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/mailparser"]
+
+[tool.hatch.version]
+path = "src/mailparser/version.py"
+
+[project.scripts]
+mail-parser = "mailparser.__main__:main"
+
+[tool.pytest.ini_options]
+testpaths = "tests"
+markers = [
+ "integration: integration tests",
+]
+addopts = """
+--strict-markers
+--strict-config
+-ra
+--cov=src
+--cov=tests
+--cov-report=term
+--cov-branch
+--cov-report=xml
+--cov-report=html
+--junitxml=junit.xml
+--verbose
+"""
+
+[tool.ruff.lint]
+select = [
+ # pycodestyle
+ "E",
+ # pyflakes
+ "F",
+ # pyupgrade
+ # "UP",
+ # flask8-bugbear
+ # "B",
+ # flake8-simplify
+ # "SIM",
+ # isort
+ "I",
+ # flask8-bandit
+ # "S",
+ # flake8-pytest-style
+ # "PT",
+ # flake8-annotations
+ # "ANN",
+]
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/__init__.py b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..72b1ef7a1eca5bcc044aee089d082db5e86c2029
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/__init__.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+from mailparser.core import (
+ MailParser,
+ parse_from_bytes,
+ parse_from_file,
+ parse_from_file_msg,
+ parse_from_file_obj,
+ parse_from_string,
+)
+from mailparser.utils import get_header
+
+__all__ = [
+ "MailParser",
+ "parse_from_bytes",
+ "parse_from_file",
+ "parse_from_file_msg",
+ "parse_from_file_obj",
+ "parse_from_string",
+ "get_header",
+]
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/__main__.py b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2db45a47ed7f7aec816f835014f0eabbc89ae2a4
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/__main__.py
@@ -0,0 +1,346 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import argparse
+import logging
+import sys
+
+import mailparser
+from mailparser.exceptions import MailParserOutlookError
+from mailparser.utils import (
+ custom_log,
+ print_attachments,
+ print_mail_fingerprints,
+ safe_print,
+ write_attachments,
+)
+from mailparser.version import __version__
+
+log = logging.getLogger("mailparser")
+
+
+def get_args():
+ """
+ Get arguments from command line.
+ :return: argparse.ArgumentParser
+ :rtype: argparse.ArgumentParser
+ """
+ parser = argparse.ArgumentParser(
+ description="Wrapper for email Python Standard Library",
+ epilog="It takes as input a raw mail and generates a parsed object.",
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+
+ parsing_group = parser.add_mutually_exclusive_group(required=True)
+ parsing_group.add_argument("-f", "--file", dest="file", help="Raw email file")
+ parsing_group.add_argument("-s", "--string", dest="string", help="Raw email string")
+ parsing_group.add_argument(
+ "-k",
+ "--stdin",
+ dest="stdin",
+ action="store_true",
+ help="Enable parsing from stdin",
+ )
+
+ parser.add_argument(
+ "-l",
+ "--log-level",
+ dest="log_level",
+ default="WARNING",
+ choices=["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"],
+ help="Set log level",
+ )
+
+ parser.add_argument(
+ "-j",
+ "--json",
+ dest="json",
+ action="store_true",
+ help="Show the JSON of parsed mail",
+ )
+
+ parser.add_argument(
+ "-b", "--body", dest="body", action="store_true", help="Print the body of mail"
+ )
+
+ parser.add_argument(
+ "-a",
+ "--attachments",
+ dest="attachments",
+ action="store_true",
+ help="Print the attachments of mail",
+ )
+
+ parser.add_argument(
+ "-r",
+ "--headers",
+ dest="headers",
+ action="store_true",
+ help="Print the headers of mail",
+ )
+
+ parser.add_argument(
+ "-t", "--to", dest="to", action="store_true", help="Print the to of mail"
+ )
+
+ parser.add_argument(
+ "-dt",
+ "--delivered-to",
+ dest="delivered_to",
+ action="store_true",
+ help="Print the delivered-to of mail",
+ )
+
+ parser.add_argument(
+ "-m", "--from", dest="from_", action="store_true", help="Print the from of mail"
+ )
+
+ parser.add_argument(
+ "-u",
+ "--subject",
+ dest="subject",
+ action="store_true",
+ help="Print the subject of mail",
+ )
+
+ parser.add_argument(
+ "-c",
+ "--receiveds",
+ dest="receiveds",
+ action="store_true",
+ help="Print all receiveds of mail",
+ )
+
+ parser.add_argument(
+ "-d",
+ "--defects",
+ dest="defects",
+ action="store_true",
+ help="Print the defects of mail",
+ )
+
+ parser.add_argument(
+ "-o",
+ "--outlook",
+ dest="outlook",
+ action="store_true",
+ help="Analyze Outlook msg",
+ )
+
+ parser.add_argument(
+ "-i",
+ "--senderip",
+ dest="senderip",
+ metavar="Trust mail server string",
+ help="Extract a reliable sender IP address heuristically",
+ )
+
+ parser.add_argument(
+ "-p",
+ "--mail-hash",
+ dest="mail_hash",
+ action="store_true",
+ help="Print mail fingerprints without headers",
+ )
+
+ parser.add_argument(
+ "-z",
+ "--attachments-hash",
+ dest="attachments_hash",
+ action="store_true",
+ help="Print attachments with fingerprints",
+ )
+
+ parser.add_argument(
+ "-sa",
+ "--store-attachments",
+ dest="store_attachments",
+ action="store_true",
+ help="Store attachments on disk",
+ )
+
+ parser.add_argument(
+ "-ap",
+ "--attachments-path",
+ dest="attachments_path",
+ default="/tmp",
+ help="Path where store attachments",
+ )
+
+ parser.add_argument(
+ "-v", "--version", action="version", version=f"%(prog)s {__version__}"
+ )
+
+ return parser
+
+
+def main():
+ """
+ Main function.
+ """
+ args = get_args().parse_args()
+ log = custom_log(level=args.log_level, name="mailparser")
+
+ try:
+ parser = get_parser(args)
+ process_output(args, parser)
+ except Exception as e:
+ log.exception(f"An error occurred: {e}")
+ sys.exit(1)
+
+
+def get_parser(args):
+ """
+ Get the correct parser based on the input source.
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ :return: MailParser
+ :rtype: mailparser.core.MailParser
+ """
+ if args.file:
+ return parse_file(args)
+ elif args.string:
+ log.debug("Start analysis by string mail")
+ return mailparser.parse_from_string(args.string)
+ elif args.stdin:
+ return parse_stdin(args)
+ else:
+ raise ValueError("No input source provided")
+
+
+def parse_file(args):
+ """
+ Parse the file based on the arguments provided.
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ :return: MailParser
+ :rtype: mailparser.core.MailParser
+ """
+ log.debug("Start analysis by file mail")
+ if args.outlook:
+ log.debug("Start analysis by Outlook msg")
+ return mailparser.parse_from_file_msg(args.file)
+ else:
+ log.debug("Start analysis by raw mail")
+ return mailparser.parse_from_file(args.file)
+
+
+def parse_stdin(args):
+ """
+ Parse the stdin based on the arguments provided.
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ :return: MailParser
+ :rtype: mailparser.core.MailParser
+ """
+ log.debug("Start analysis by stdin mail")
+ if args.outlook:
+ raise MailParserOutlookError("You can't use stdin with msg Outlook")
+ return mailparser.parse_from_file_obj(sys.stdin)
+
+
+def process_output(args, parser):
+ """
+ Process the output based on the arguments provided.
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ :param parser: MailParser
+ :type parser: mailparser.core.MailParser
+ :param log: logger
+ :type log: logging.Logger
+ """
+ if args.json:
+ safe_print(parser.mail_json)
+
+ if args.body:
+ safe_print(parser.body)
+
+ if args.headers:
+ safe_print(parser.headers_json)
+
+ if args.to:
+ safe_print(parser.to_json)
+
+ if args.delivered_to:
+ safe_print(parser.delivered_to_json)
+
+ if args.from_:
+ safe_print(parser.from_json)
+
+ if args.subject:
+ safe_print(parser.subject)
+
+ if args.receiveds:
+ safe_print(parser.received_json)
+
+ if args.defects:
+ print_defects(parser)
+
+ if args.senderip:
+ print_sender_ip(parser, args)
+
+ if args.attachments or args.attachments_hash:
+ print_attachments_details(parser, args)
+
+ if args.mail_hash:
+ log.debug("Printing also mail fingerprints")
+ print_mail_fingerprints(parser.body.encode("utf-8"))
+
+ if args.store_attachments:
+ log.debug("Store attachments on disk")
+ write_attachments(parser.attachments, args.attachments_path)
+
+
+def print_defects(parser):
+ """
+ Print email defects.
+ :param parser: MailParser
+ :type parser: mailparser.core.MailParser
+ """
+ log.debug("Printing defects")
+ for defect in parser.defects_categories:
+ safe_print(defect)
+
+
+def print_sender_ip(parser, args):
+ """
+ Print sender IP address.
+ :param parser: MailParser
+ :type parser: mailparser.core.MailParser
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ """
+ log.debug("Printing sender IP")
+ sender_ip = parser.get_server_ipaddress(args.senderip)
+ safe_print(sender_ip if sender_ip else "Not Found")
+
+
+def print_attachments_details(parser, args):
+ """
+ Print attachments details.
+ :param parser: MailParser
+ :type parser: mailparser.core.MailParser
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ """
+ log.debug("Printing attachments details")
+ print_attachments(parser.attachments, args.attachments_hash)
+
+
+if __name__ == "__main__": # pragma: no cover
+ main()
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/const.py b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/const.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d172243828f9cc0d1f68a4f46c073ecccbde5ef
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/const.py
@@ -0,0 +1,101 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2018 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import re
+
+REGXIP = re.compile(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
+
+JUNK_PATTERN = r"[ \(\)\[\]\t\n]+"
+
+# Patterns for receiveds
+RECEIVED_PATTERNS = [
+ # FIXED: More restrictive 'from' clause
+ # Only matches 'from' at the beginning of the header (^) or after
+ # newline/whitespace to avoid matching within "for from "
+ # constructs which caused duplicate matches in IBM gateway headers
+ (
+ r"(?:(?:^|\n\s*)from\s+(?P.+?)(?:\s*[(]?"
+ r"envelope-from|\s*[(]?envelope-sender|\s+"
+ r"by|\s+with(?! cipher)|\s+id|\s+via|;))"
+ ),
+ # IMPROVED: More precise 'by' clause
+ # Modified to not consume 'with' clause, allowing proper separation
+ # of 'by' (server name) and 'with' (protocol) fields
+ (
+ r"(?:(?:^|\s)by\s+(?P[^\s]+(?:\s+[^\s]+)*?)"
+ r"(?:\s+with(?! cipher)|\s*[(]?envelope-from|\s*"
+ r"[(]?envelope-sender|\s+id|\s+for|\s+via|;))"
+ ),
+ # IMPROVED: 'with' clause with better boundary detection
+ (
+ r"(?:(?:^|\s)with(?! cipher)\s+(?P.+?)"
+ r"(?:\s*[(]?envelope-from|\s*[(]?"
+ r"envelope-sender|\s+id|\s+for|\s+via|;))"
+ ),
+ # IMPROVED: 'id' clause with cleaner boundaries
+ (
+ r"(?:(?:^|\s)id\s+(?P.+?)(?:\s*[(]?envelope-from|\s*"
+ r"[(]?envelope-sender|\s+for|\s+via|;))"
+ ),
+ # IMPROVED: 'for' clause - handles "for from " pattern
+ # Stops before 'from' keyword to prevent the 'from' pattern from
+ # matching the sender email in this construct
+ (
+ r"(?:(?:^|\s)for\s+(?P<[^>]+>|[^\s]+)"
+ r"(?:\s+from|\s*[(]?envelope-from|\s*[(]?"
+ r"envelope-sender|\s+via|;))"
+ ),
+ # IMPROVED: 'via' clause with better termination
+ (
+ r"(?:(?:^|\s)via\s+(?P.+?)(?:\s*[(]?"
+ r"envelope-from|\s*[(]?envelope-sender|;))"
+ ),
+ # assumes emails are always inside <>
+ r"(?:envelope-from\s+<(?P.+?)>)",
+ r"(?:envelope-sender\s+<(?P.+?)>)",
+ # datetime comes after ; at the end
+ r";\s*(?P.*)",
+ # sendgrid datetime
+ (
+ r"(?P\d{4}-\d{2}-\d{2} \d{2}:\d{2}:"
+ r"\d{2}\.\d{9} \+0000 UTC) m=\+\d+\.\d+"
+ ),
+]
+
+RECEIVED_COMPILED_LIST = [re.compile(i, re.I | re.DOTALL) for i in RECEIVED_PATTERNS]
+
+EPILOGUE_DEFECTS = {"StartBoundaryNotFoundDefect"}
+
+ADDRESSES_HEADERS = set(["bcc", "cc", "delivered-to", "from", "reply-to", "to"])
+
+# These parts are always returned
+OTHERS_PARTS = set(
+ [
+ "attachments",
+ "body",
+ "date",
+ "message-id",
+ "received",
+ "subject",
+ "timezone",
+ "to_domains",
+ "user-agent",
+ "x-mailer",
+ "x-original-to",
+ ]
+)
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/core.py b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5e865853725046fa4028b306e3458314fa5a71b
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/core.py
@@ -0,0 +1,759 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import base64
+import email
+import ipaddress
+import json
+import logging
+import os
+
+from mailparser.const import ADDRESSES_HEADERS, EPILOGUE_DEFECTS, REGXIP
+from mailparser.utils import (
+ convert_mail_date,
+ decode_header_part,
+ find_between,
+ get_header,
+ get_mail_keys,
+ get_to_domains,
+ msgconvert,
+ ported_open,
+ ported_string,
+ random_string,
+ receiveds_parsing,
+ write_attachments,
+)
+
+log = logging.getLogger(__name__)
+
+
+def parse_from_file_obj(fp):
+ """
+ Parsing email from a file-like object.
+
+ Args:
+ fp (file-like object): file-like object of raw email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_file_obj(fp)
+
+
+def parse_from_file(fp):
+ """
+ Parsing email from file.
+
+ Args:
+ fp (string): file path of raw email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_file(fp)
+
+
+def parse_from_file_msg(fp):
+ """
+ Parsing email from file Outlook msg.
+
+ Args:
+ fp (string): file path of raw Outlook email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_file_msg(fp)
+
+
+def parse_from_string(s):
+ """
+ Parsing email from string.
+
+ Args:
+ s (string): raw email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_string(s)
+
+
+def parse_from_bytes(bt):
+ """
+ Parsing email from bytes. Only for Python 3
+
+ Args:
+ bt (bytes-like object): raw email as bytes-like object
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_bytes(bt)
+
+
+class MailParser:
+ """
+ MailParser package provides a standard parser that understands
+ most email document structures like official email package.
+ MailParser handles the encoding of email and split the raw email for you.
+
+ Headers:
+ https://www.iana.org/assignments/message-headers/message-headers.xhtml
+ """
+
+ def __init__(self, message=None):
+ """
+ Init a new object from a message object structure.
+ """
+ self._message = message
+ log.debug("All headers of emails: {}".format(", ".join(message.keys())))
+ self.parse()
+
+ def __str__(self):
+ if self.message:
+ return self.subject
+ else:
+ return str()
+
+ @classmethod
+ def from_file_obj(cls, fp):
+ """
+ Init a new object from a file-like object.
+ Not for Outlook msg.
+
+ Args:
+ fp (file-like object): file-like object of raw email
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug("Parsing email from file object")
+ try:
+ fp.seek(0)
+ except OSError:
+ # When stdout is a TTY it's a character device
+ # and it's not seekable, you cannot seek in a TTY.
+ pass
+ finally:
+ s = fp.read()
+
+ return cls.from_string(s)
+
+ @classmethod
+ def from_file(cls, fp, is_outlook=False):
+ """
+ Init a new object from a file path.
+
+ Args:
+ fp (string): file path of raw email
+ is_outlook (boolean): if True is an Outlook email
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug(f"Parsing email from file {fp!r}")
+
+ with ported_open(fp) as f:
+ message = email.message_from_file(f)
+
+ if is_outlook:
+ log.debug(f"Removing temp converted Outlook email {fp!r}")
+ os.remove(fp)
+
+ return cls(message)
+
+ @classmethod
+ def from_file_msg(cls, fp):
+ """
+ Init a new object from a Outlook message file,
+ mime type: application/vnd.ms-outlook
+
+ Args:
+ fp (string): file path of raw Outlook email
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug("Parsing email from file Outlook")
+ f, _ = msgconvert(fp)
+ return cls.from_file(f, True)
+
+ @classmethod
+ def from_string(cls, s):
+ """
+ Init a new object from a string.
+
+ Args:
+ s (string): raw email
+
+ Returns:
+ Instance of MailParser
+ """
+
+ log.debug("Parsing email from string")
+ message = email.message_from_string(s)
+ return cls(message)
+
+ @classmethod
+ def from_bytes(cls, bt):
+ """
+ Init a new object from bytes.
+
+ Args:
+ bt (bytes-like object): raw email as bytes-like object
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug("Parsing email from bytes")
+ message = email.message_from_bytes(bt)
+ return cls(message)
+
+ def _reset(self):
+ """
+ Reset the state of mail object.
+ """
+ log.debug("Reset all variables")
+
+ self._attachments = []
+ self._text_plain = []
+ self._text_html = []
+ self._text_not_managed = []
+ self._defects = []
+ self._defects_categories = set()
+ self._has_defects = False
+
+ def _append_defects(self, part, part_content_type):
+ """
+ Add new defects and defects categories to object attributes.
+
+ The defects are a list of all the problems found
+ when parsing this message.
+
+ Args:
+ part (string): mail part
+ part_content_type (string): content type of part
+ """
+
+ part_defects = {}
+
+ for e in part.defects:
+ defects = f"{e.__class__.__name__}: {e.__doc__}"
+ self._defects_categories.add(e.__class__.__name__)
+ part_defects.setdefault(part_content_type, []).append(defects)
+ log.debug(f"Added defect {defects!r}")
+
+ # Tag mail with defect
+ if part_defects:
+ self._has_defects = True
+
+ # Save all defects
+ self._defects.append(part_defects)
+
+ def _make_mail(self, complete=True):
+ """
+ This method assigns the right values to all tokens of email.
+ Returns a parsed object
+
+ Keyword Arguments:
+ complete {bool} -- If True returns all mails parts
+ (default: {True})
+
+ Returns:
+ dict -- Parsed email object
+ """
+
+ mail = {}
+ keys = get_mail_keys(self.message, complete)
+
+ for i in keys:
+ log.debug(f"Getting header or part {i!r}")
+ value = getattr(self, i)
+ if value:
+ mail[i] = value
+
+ # add defects
+ mail["has_defects"] = self.has_defects
+ if self.has_defects:
+ mail["defects"] = self.defects
+ mail["defects_categories"] = list(self.defects_categories)
+
+ return mail
+
+ def parse(self):
+ """
+ This method parses the raw email and makes the tokens.
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+
+ if not self.message:
+ return self
+
+ # reset and start parsing
+ self._reset()
+ parts = [] # Normal parts plus defects
+
+ # walk all mail parts to search defects
+ for p in self.message.walk():
+ part_content_type = p.get_content_type()
+ self._append_defects(p, part_content_type)
+ parts.append(p)
+
+ # If defects are in epilogue defects get epilogue
+ if self.defects_categories & EPILOGUE_DEFECTS:
+ log.debug("Found defects in emails")
+ epilogue = find_between(
+ self.message.epilogue,
+ "{}".format("--" + self.message.get_boundary()),
+ "{}".format("--" + self.message.get_boundary() + "--"),
+ )
+
+ try:
+ p = email.message_from_string(epilogue)
+ parts.append(p)
+ except TypeError:
+ log.debug("Failed to get epilogue part for TypeError")
+ except Exception:
+ log.error("Failed to get epilogue part. Check raw mail.")
+
+ # walk all mail parts
+ for i, p in enumerate(parts):
+ if (
+ not p.is_multipart()
+ or ported_string(p.get_content_disposition()).lower() == "attachment"
+ ):
+ charset = p.get_content_charset("utf-8")
+ charset_raw = p.get_content_charset()
+ log.debug(f"Charset {charset!r} part {i!r}")
+ content_disposition = ported_string(p.get_content_disposition()).lower()
+ log.debug(f"content-disposition {content_disposition!r} part {i!r}")
+ content_id = ported_string(p.get("content-id"))
+ log.debug(f"content-id {content_id!r} part {i!r}")
+ content_subtype = ported_string(p.get_content_subtype())
+ log.debug(f"content subtype {content_subtype!r} part {i!r}")
+ filename = decode_header_part(p.get_filename())
+
+ is_attachment = False
+ if filename:
+ is_attachment = True
+ else:
+ if content_id and content_subtype not in ("html", "plain"):
+ is_attachment = True
+ filename = content_id
+ elif content_subtype in ("rtf"):
+ is_attachment = True
+ filename = f"{random_string()}.rtf"
+ elif content_disposition == "attachment":
+ is_attachment = True
+ filename = f"{random_string()}.txt"
+
+ # this is an attachment
+ if is_attachment:
+ log.debug(f"Email part {i!r} is an attachment")
+ log.debug(f"Filename {filename!r} part {i!r}")
+ binary = False
+ mail_content_type = ported_string(p.get_content_type())
+ log.debug(f"Mail content type {mail_content_type!r} part {i!r}")
+ transfer_encoding = ported_string(
+ p.get("content-transfer-encoding", "")
+ ).lower()
+ log.debug(f"Transfer encoding {transfer_encoding!r} part {i!r}")
+ content_disposition = ported_string(p.get("content-disposition"))
+ log.debug(f"content-disposition {content_disposition!r} part {i!r}")
+
+ if p.is_multipart():
+ payload = "".join(
+ [m.as_string() for m in p.get_payload(decode=False)]
+ )
+ binary = False
+ log.debug(f"Filename {filename!r} part {i!r} is multipart")
+ elif transfer_encoding == "base64" or (
+ transfer_encoding
+ == "quoted-\
+ printable"
+ and "application" in mail_content_type
+ ):
+ payload = p.get_payload(decode=False)
+ binary = True
+ log.debug(f"Filename {filename!r} part {i!r} is binary")
+ elif "uuencode" in transfer_encoding:
+ # Re-encode in base64
+ payload = base64.b64encode(p.get_payload(decode=True)).decode(
+ "ascii"
+ )
+ binary = True
+ transfer_encoding = "base64"
+ log.debug(
+ f"Filename {filename!r} part {i!r} is binary (uuencode"
+ " re-encoded to base64)"
+ )
+ else:
+ payload = ported_string(
+ p.get_payload(decode=True), encoding=charset
+ )
+ log.debug(f"Filename {filename!r} part {i!r} is not binary")
+
+ self._attachments.append(
+ {
+ "filename": filename,
+ "payload": payload,
+ "binary": binary,
+ "mail_content_type": mail_content_type,
+ "content-id": content_id,
+ "content-disposition": content_disposition,
+ "charset": charset_raw,
+ "content_transfer_encoding": transfer_encoding,
+ }
+ )
+
+ # this isn't an attachments
+ else:
+ log.debug(f"Email part {i!r} is not an attachment")
+
+ # Get the payload using get_payload method with decode=True
+ # As Python truly decodes only 'base64',
+ # 'quoted-printable', 'x-uuencode',
+ # 'uuencode', 'uue', 'x-uue'
+ # And for other encodings it breaks the characters so
+ # we need to decode them with encoding python is appying
+ # To maintain the characters
+ payload = p.get_payload(decode=True)
+ cte = p.get("Content-Transfer-Encoding")
+ if cte:
+ cte = cte.lower()
+
+ if not cte or cte in ["7bit", "8bit"]:
+ try:
+ payload = payload.decode("raw-unicode-escape")
+ except UnicodeDecodeError:
+ payload = ported_string(payload, encoding=charset)
+ else:
+ payload = ported_string(payload, encoding=charset)
+
+ if payload:
+ if p.get_content_subtype() == "html":
+ self._text_html.append(payload)
+ elif p.get_content_subtype() == "plain":
+ self._text_plain.append(payload)
+ else:
+ log.warning(
+ f"Email content {p.get_content_subtype()!r} not handled"
+ )
+ self._text_not_managed.append(payload)
+
+ # Parsed object mail with all parts
+ self._mail = self._make_mail()
+
+ # Parsed object mail with mains parts
+ self._mail_partial = self._make_mail(complete=False)
+
+ def get_server_ipaddress(self, trust):
+ """
+ Return the ip address of sender
+
+ Overview:
+ Extract a reliable sender IP address heuristically for each message.
+ Although the message format dictates a chain of relaying IP
+ addresses in each message, a malicious relay can easily alter that.
+ Therefore we cannot simply take the first IP in
+ the chain. Instead, our method is as follows.
+ First we trust the sender IP reported by our mail server in the
+ Received headers, and if the previous relay IP address is on our trust
+ list (e.g. other well-known mail services), we continue to
+ follow the previous Received line, till we reach the first unrecognized
+ IP address in the email header.
+
+ From article Characterizing Botnets from Email Spam Records:
+ Li Zhuang, J. D. Tygar
+
+ In our case we trust only our mail server with the trust string.
+
+ Args:
+ trust (string): String that identify our mail server
+
+ Returns:
+ string with the ip address
+ """
+ log.debug(f"Trust string is {trust!r}")
+
+ if not trust.strip():
+ return
+
+ received = self.message.get_all("received", [])
+
+ for i in received:
+ i = ported_string(i)
+ if trust in i:
+ log.debug(f"Trust string {trust!r} is in {i!r}")
+ ip_str = self._extract_ip(i)
+ if ip_str:
+ return ip_str
+
+ def _extract_ip(self, received_header):
+ """
+ Extract the IP address from the received header if it is not private.
+
+ Args:
+ received_header (string): The received header string
+
+ Returns:
+ string with the ip address or None
+ """
+ check = REGXIP.findall(received_header[0 : received_header.find("by")])
+ if check:
+ try:
+ ip_str = str(check[-1])
+ log.debug(f"Found sender IP {ip_str!r} in {received_header!r}")
+ ip = ipaddress.ip_address(ip_str)
+ except ValueError:
+ return None
+ else:
+ if not ip.is_private:
+ log.debug(f"IP {ip_str!r} not private")
+ return ip_str
+ return None
+
+ def write_attachments(self, base_path):
+ """This method writes the attachments of mail on disk
+
+ Arguments:
+ base_path {str} -- Base path where write the attachments
+ """
+ write_attachments(attachments=self.attachments, base_path=base_path)
+
+ def __getattr__(self, name):
+ name = name.strip("_").lower()
+ name_header = name.replace("_", "-")
+
+ # json headers
+ if name.endswith("_json"):
+ name = name[:-5]
+ return json.dumps(getattr(self, name), ensure_ascii=False)
+
+ # raw headers
+ elif name.endswith("_raw"):
+ name = name[:-4]
+ raw = self.message.get_all(name)
+ return json.dumps(raw, ensure_ascii=False)
+
+ # object headers
+ elif name_header in ADDRESSES_HEADERS:
+ h = decode_header_part(self.message.get(name_header, str()))
+ h_parsed = email.utils.getaddresses([h], strict=True)
+ return (
+ h_parsed
+ if h_parsed != [("", "")]
+ else email.utils.getaddresses([h], strict=False)
+ )
+
+ # others headers
+ else:
+ return get_header(self.message, name_header)
+
+ @property
+ def attachments(self):
+ """
+ Return a list of all attachments in the mail
+ """
+ return self._attachments
+
+ @property
+ def received(self):
+ """
+ Return a list of all received headers parsed
+ """
+ output = self.received_raw
+ return receiveds_parsing(output)
+
+ @property
+ def received_json(self):
+ """
+ Return a JSON of all received headers
+ """
+ return json.dumps(self.received, ensure_ascii=False, indent=2)
+
+ @property
+ def received_raw(self):
+ """
+ Return a list of all received headers in raw format
+ """
+ output = []
+ for i in self.message.get_all("received", []):
+ output.append(decode_header_part(i))
+ return output
+
+ @property
+ def body(self):
+ """
+ Return all text plain and text html parts of mail delimited from string
+ "--- mail_boundary ---"
+ """
+ return "\n--- mail_boundary ---\n".join(
+ self.text_plain + self.text_html + self.text_not_managed
+ )
+
+ @property
+ def headers(self) -> dict:
+ """
+ Return only the headers as Python object
+ """
+ all_headers = set(self.message.keys()) - set(["headers"])
+ return {i: getattr(self, i) for i in all_headers}
+
+ @property
+ def headers_json(self):
+ """
+ Return the JSON of headers
+ """
+ return json.dumps(self.headers, ensure_ascii=False, indent=2)
+
+ @property
+ def text_plain(self):
+ """
+ Return a list of all text plain parts of email.
+ """
+ return self._text_plain
+
+ @property
+ def text_html(self):
+ """
+ Return a list of all text html parts of email.
+ """
+ return self._text_html
+
+ @property
+ def text_not_managed(self):
+ """
+ Return a list of all text not managed of email.
+ """
+ return self._text_not_managed
+
+ @property
+ def date(self):
+ """
+ Return the mail date in datetime.datetime format and UTC.
+ """
+ date = self.message.get("date")
+ conv = None
+
+ try:
+ conv, _ = convert_mail_date(date)
+ except Exception:
+ pass
+ return conv
+
+ @property
+ def timezone(self):
+ """
+ Return timezone. Offset from UTC.
+ """
+ date = self.message.get("date")
+ timezone = 0
+
+ try:
+ _, timezone = convert_mail_date(date)
+ except Exception:
+ pass
+ return timezone
+
+ @property
+ def date_json(self):
+ """
+ Return the JSON of date
+ """
+ if self.date:
+ return json.dumps(self.date.isoformat(), ensure_ascii=False)
+
+ @property
+ def mail(self):
+ """
+ Return the Python object of mail parsed
+ """
+ return self._mail
+
+ @property
+ def mail_json(self):
+ """
+ Return the JSON of mail parsed
+ """
+ if self.mail.get("date"):
+ self._mail["date"] = self.date.isoformat()
+ return json.dumps(self.mail, ensure_ascii=False, indent=2)
+
+ @property
+ def mail_partial(self):
+ """
+ Return the Python object of mail parsed
+ with only the mains headers
+ """
+ return self._mail_partial
+
+ @property
+ def mail_partial_json(self):
+ """
+ Return the JSON of mail parsed partial
+ """
+ if self.mail_partial.get("date"):
+ self._mail_partial["date"] = self.date.isoformat()
+ return json.dumps(self.mail_partial, ensure_ascii=False, indent=2)
+
+ @property
+ def defects(self):
+ """
+ The defects property contains a list of
+ all the problems found when parsing this message.
+ """
+ return self._defects
+
+ @property
+ def defects_categories(self):
+ """
+ Return a set with only defects categories.
+ """
+ return self._defects_categories
+
+ @property
+ def has_defects(self):
+ """
+ Return a boolean: True if mail has defects.
+ """
+ return self._has_defects
+
+ @property
+ def message(self):
+ """
+ email.message.Message class.
+ """
+ return self._message
+
+ @property
+ def message_as_string(self):
+ """
+ Return the entire message flattened as a string.
+ """
+ return self.message.as_string()
+
+ @property
+ def to_domains(self):
+ """
+ Return all domain of 'to' and 'reply-to' email addresses
+ """
+ return get_to_domains(self.to, self.reply_to)
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/exceptions.py b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..143cba662f72ff4a3d6849b0dd7c2f4f646aa59f
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/exceptions.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2018 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+__all__ = (
+ "MailParserError",
+ "MailParserOutlookError",
+ "MailParserEnvironmentError",
+ "MailParserOSError",
+ "MailParserReceivedParsingError",
+)
+
+
+class MailParserError(Exception):
+ """
+ Base MailParser Exception
+ """
+
+ pass
+
+
+class MailParserOutlookError(MailParserError):
+ """
+ Raised when there is an error with Outlook integration
+ """
+
+ pass
+
+
+class MailParserEnvironmentError(MailParserError):
+ """
+ Raised when the environment is not correct
+ """
+
+ pass
+
+
+class MailParserOSError(MailParserError):
+ """
+ Raised when there is an OS error
+ """
+
+ pass
+
+
+class MailParserReceivedParsingError(MailParserError):
+ """
+ Raised when a received header cannot be parsed
+ """
+
+ pass
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/utils.py b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c73cd2c58cdcf1a9dfb31bd4d2feb6f29f9f6ab9
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/utils.py
@@ -0,0 +1,581 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import base64
+import datetime
+import email
+import functools
+import hashlib
+import json
+import logging
+import os
+import random
+import re
+import string
+import subprocess
+import sys
+import tempfile
+from collections import Counter, namedtuple
+from email.errors import HeaderParseError
+from email.header import decode_header
+from unicodedata import normalize
+
+from mailparser.const import (
+ ADDRESSES_HEADERS,
+ JUNK_PATTERN,
+ OTHERS_PARTS,
+ RECEIVED_COMPILED_LIST,
+)
+from mailparser.exceptions import MailParserOSError, MailParserReceivedParsingError
+
+log = logging.getLogger(__name__)
+
+
+def custom_log(level="WARNING", name=None): # pragma: no cover
+ """
+ This function returns a custom logger.
+ :param level: logging level
+ :type level: str
+ :param name: logger name
+ :type name: str
+ :return: logger
+ """
+ if name:
+ log = logging.getLogger(name)
+ else:
+ log = logging.getLogger()
+ log.setLevel(level)
+ ch = logging.StreamHandler(sys.stdout)
+ formatter = logging.Formatter(
+ "%(asctime)s | "
+ "%(name)s | "
+ "%(module)s | "
+ "%(funcName)s | "
+ "%(lineno)d | "
+ "%(levelname)s | "
+ "%(message)s"
+ )
+ ch.setFormatter(formatter)
+ log.addHandler(ch)
+ return log
+
+
+def sanitize(func):
+ """NFC is the normalization form recommended by W3C."""
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ return normalize("NFC", func(*args, **kwargs))
+
+ return wrapper
+
+
+@sanitize
+def ported_string(raw_data, encoding="utf-8", errors="ignore"):
+ """
+ Give as input raw data and output a str in Python 3.
+
+ Args:
+ raw_data: bytes or str to convert to str
+ encoding: string giving the name of an encoding
+ errors: specifies the treatment of characters
+ which are invalid in the input encoding
+
+ Returns:
+ str
+ """
+
+ if not raw_data:
+ return str()
+
+ if isinstance(raw_data, str):
+ return raw_data
+
+ # raw_data is bytes, decode it
+ try:
+ return str(raw_data, encoding)
+ except (LookupError, UnicodeDecodeError):
+ return str(raw_data, "utf-8", errors)
+
+
+def decode_header_part(header):
+ """
+ Given a raw header returns a decoded header
+
+ Args:
+ header (string): header to decode
+
+ Returns:
+ str
+ """
+ if not header:
+ return str()
+
+ output = str()
+
+ try:
+ for d, c in decode_header(header):
+ c = c if c else "utf-8"
+ output += ported_string(d, c, "ignore")
+
+ # Header parsing failed, when header has charset Shift_JIS
+ except (HeaderParseError, UnicodeError):
+ log.error(f"Failed decoding header part: {header}")
+ output += header
+
+ return output.strip()
+
+
+def ported_open(file_):
+ """Open a file with UTF-8 encoding and ignore errors.
+
+ Args:
+ file_: path to the file to open
+
+ Returns:
+ file object
+ """
+ return open(file_, encoding="utf-8", errors="ignore")
+
+
+def find_between(text, first_token, last_token):
+ try:
+ start = text.index(first_token) + len(first_token)
+ end = text.index(last_token, start)
+ return text[start:end].strip()
+ except ValueError:
+ return
+
+
+def fingerprints(data):
+ """
+ This function return the fingerprints of data.
+
+ Args:
+ data (string): raw data
+
+ Returns:
+ namedtuple: fingerprints md5, sha1, sha256, sha512
+ """
+
+ hashes = namedtuple("Hashes", "md5 sha1 sha256 sha512")
+
+ if not isinstance(data, bytes):
+ data = data.encode("utf-8")
+
+ # md5
+ md5 = hashlib.md5()
+ md5.update(data)
+ md5 = md5.hexdigest()
+
+ # sha1
+ sha1 = hashlib.sha1()
+ sha1.update(data)
+ sha1 = sha1.hexdigest()
+
+ # sha256
+ sha256 = hashlib.sha256()
+ sha256.update(data)
+ sha256 = sha256.hexdigest()
+
+ # sha512
+ sha512 = hashlib.sha512()
+ sha512.update(data)
+ sha512 = sha512.hexdigest()
+
+ return hashes(md5, sha1, sha256, sha512)
+
+
+def msgconvert(email):
+ """
+ Exec msgconvert tool, to convert msg Outlook
+ mail in eml mail format
+
+ Args:
+ email (string): file path of Outlook msg mail
+
+ Returns:
+ tuple with file path of mail converted and
+ standard output data (str)
+ """
+ log.debug("Started converting Outlook email")
+ temph, temp = tempfile.mkstemp(prefix="outlook_")
+ command = ["msgconvert", "--outfile", temp, email]
+
+ try:
+ out = subprocess.Popen(
+ command,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ )
+
+ except OSError as e:
+ message = f"Check if 'msgconvert' tool is installed / {e!r}"
+ log.exception(message)
+ raise MailParserOSError(message)
+
+ else:
+ stdoutdata, _ = out.communicate()
+ return temp, stdoutdata.decode("utf-8").strip()
+
+ finally:
+ os.close(temph)
+
+
+def parse_received(received):
+ """
+ Parse a single received header.
+ Return a dictionary of values by clause.
+
+ Arguments:
+ received {str} -- single received header
+
+ Raises:
+ MailParserReceivedParsingError -- Raised when a
+ received header cannot be parsed
+
+ Returns:
+ dict -- values by clause
+ """
+
+ values_by_clause = {}
+ for pattern in RECEIVED_COMPILED_LIST:
+ matches = [match for match in pattern.finditer(received)]
+
+ if len(matches) == 0:
+ # no matches for this clause, but it's ok! keep going!
+ log.debug("No matches found for %s in %s" % (pattern.pattern, received))
+ elif len(matches) > 1:
+ # uh, can't have more than one of each clause in a received.
+ # so either there's more than one or the current regex is wrong
+ msg = "More than one match found for %s in %s" % (pattern.pattern, received)
+ log.error(msg)
+ raise MailParserReceivedParsingError(msg)
+ else:
+ # otherwise we have one matching clause!
+ log.debug("Found one match for %s in %s" % (pattern.pattern, received))
+ match = matches[0].groupdict()
+ key = list(match.keys())[0]
+ value = list(match.values())[0]
+ values_by_clause[key] = value
+
+ if len(values_by_clause) == 0:
+ # we weren't able to match anything...
+ msg = "Unable to match any clauses in %s" % (received)
+
+ # Modification #1: Commenting the following log as
+ # this raised exception is caught above and then
+ # raw header is updated in response
+ # We dont want to get so many errors in our error
+ # logger as we are not even trying to parse the
+ # received headers
+ # Wanted to make it configurable via settiings,
+ # but this package does not depend on django and
+ # making configurable setting
+ # will make it django dependent,
+ # so better to keep it working with only python
+ # dependent and on any framework of python
+ # commenting it just for our use
+
+ # log.error(msg)
+
+ raise MailParserReceivedParsingError(msg)
+ return values_by_clause
+
+
+def receiveds_parsing(receiveds):
+ """
+ This function parses the receiveds headers.
+
+ Args:
+ receiveds (list): list of raw receiveds headers
+
+ Returns:
+ a list of parsed receiveds headers with first hop in first position
+ """
+
+ parsed = []
+ receiveds = [re.sub(JUNK_PATTERN, " ", i).strip() for i in receiveds]
+ n = len(receiveds)
+ log.debug(f"Nr. of receiveds. {n}")
+
+ for idx, received in enumerate(receiveds):
+ log.debug(f"Parsing received {idx + 1}/{n}")
+ log.debug(f"Try to parse {received!r}")
+ try:
+ # try to parse the current received header...
+ values_by_clause = parse_received(received)
+ except MailParserReceivedParsingError:
+ # if we can't, let's append the raw
+ parsed.append({"raw": received})
+ else:
+ # otherwise append the full values_by_clause dict
+ parsed.append(values_by_clause)
+
+ log.debug("len(receiveds) %s, len(parsed) %s" % (len(receiveds), len(parsed)))
+
+ if len(receiveds) != len(parsed):
+ # something really bad happened,
+ # so just return raw receiveds with hop indices
+ log.error(
+ "len(receiveds): %s, len(parsed): %s, receiveds: %s, \
+ parsed: %s"
+ % (len(receiveds), len(parsed), receiveds, parsed)
+ )
+ return receiveds_not_parsed(receiveds)
+
+ else:
+ # all's good! we have parsed or raw receiveds for each received header
+ return receiveds_format(parsed)
+
+
+def convert_mail_date(date):
+ """
+ Convert a mail date in a datetime object.
+ """
+ log.debug(f"Date to parse: {date!r}")
+ d = email.utils.parsedate_tz(date)
+ log.debug(f"Date parsed: {d!r}")
+ t = email.utils.mktime_tz(d)
+ log.debug(f"Date parsed in timestamp: {t!r}")
+ date_utc = datetime.datetime.fromtimestamp(t, datetime.timezone.utc)
+ timezone = d[9] / 3600.0 if d[9] else 0
+ timezone = f"{timezone:+.1f}"
+ log.debug(f"Calculated timezone: {timezone!r}")
+ return date_utc, timezone
+
+
+def receiveds_not_parsed(receiveds):
+ """
+ If receiveds are not parsed, makes a new structure with raw
+ field. It's useful to have the same structure of receiveds
+ parsed.
+
+ Args:
+ receiveds (list): list of raw receiveds headers
+
+ Returns:
+ a list of not parsed receiveds headers with first hop in first position
+ """
+ log.debug("Receiveds for this email are not parsed")
+
+ output = []
+ counter = Counter()
+
+ for i in receiveds[::-1]:
+ j = {"raw": i.strip()}
+ j["hop"] = counter["hop"] + 1
+ counter["hop"] += 1
+ output.append(j)
+
+ return output
+
+
+def receiveds_format(receiveds):
+ """
+ Given a list of receiveds hop, adds metadata and reformat
+ field values
+
+ Args:
+ receiveds (list): list of receiveds hops already formatted
+
+ Returns:
+ list of receiveds reformated and with new fields
+ """
+ log.debug("Receiveds for this email are parsed")
+
+ output = []
+ counter = Counter()
+
+ for i in receiveds[::-1]:
+ # Clean strings
+ j = {k: v.strip() for k, v in i.items() if v}
+
+ # Add hop
+ j["hop"] = counter["hop"] + 1
+
+ # Add UTC date
+ if i.get("date"):
+ # Modify date to manage strange header like:
+ # "for ; Tue, 7 Mar 2017 14:29:24 -0800",
+ i["date"] = i["date"].split(";")[-1]
+ try:
+ j["date_utc"], _ = convert_mail_date(i["date"])
+ except TypeError:
+ j["date_utc"] = None
+
+ # Add delay
+ size = len(output)
+ now = j.get("date_utc")
+
+ if size and now:
+ before = output[counter["hop"] - 1].get("date_utc")
+ if before:
+ j["delay"] = (now - before).total_seconds()
+ else:
+ j["delay"] = 0
+ else:
+ j["delay"] = 0
+
+ # append result
+ output.append(j)
+
+ # new hop
+ counter["hop"] += 1
+
+ for i in output:
+ if i.get("date_utc"):
+ i["date_utc"] = i["date_utc"].isoformat()
+ return output
+
+
+def get_to_domains(to=[], reply_to=[]):
+ domains = set()
+ for i in to + reply_to:
+ try:
+ domains.add(i[1].split("@")[-1].lower().strip())
+ except (KeyError, IndexError):
+ pass
+
+ return list(domains)
+
+
+def get_header(message, name):
+ """
+ Gets an email.message.Message and a header name and returns
+ the mail header decoded with the correct charset.
+
+ Args:
+ message (email.message.Message): email message object
+ name (string): header to get
+
+ Returns:
+ str if there is an header
+ list if there are more than one
+ """
+
+ headers = message.get_all(name)
+ log.debug(f"Getting header {name!r}: {headers!r}")
+ if headers:
+ headers = [decode_header_part(i) for i in headers]
+ if len(headers) == 1:
+ # in this case return a string
+ return headers[0].strip()
+ # in this case return a list
+ return headers
+ return str()
+
+
+def get_mail_keys(message, complete=True):
+ """
+ Given an email.message.Message, return a set with all email parts to get
+
+ Args:
+ message (email.message.Message): email message object
+ complete (bool): if True returns all email headers
+
+ Returns:
+ set with all email parts
+ """
+
+ if complete:
+ log.debug("Get all headers")
+ all_headers_keys = {i.lower() for i in message.keys()}
+ all_parts = ADDRESSES_HEADERS | OTHERS_PARTS | all_headers_keys
+ else:
+ log.debug("Get only mains headers")
+ all_parts = ADDRESSES_HEADERS | OTHERS_PARTS
+
+ log.debug("All parts to get: {}".format(", ".join(all_parts)))
+ return all_parts
+
+
+def safe_print(data): # pragma: no cover
+ try:
+ print(data)
+ except UnicodeEncodeError:
+ print(data.encode("utf-8"))
+
+
+def print_mail_fingerprints(data): # pragma: no cover
+ md5, sha1, sha256, sha512 = fingerprints(data)
+ print(f"md5:\t{md5}")
+ print(f"sha1:\t{sha1}")
+ print(f"sha256:\t{sha256}")
+ print(f"sha512:\t{sha512}")
+
+
+def print_attachments(attachments, flag_hash): # pragma: no cover
+ if flag_hash:
+ for i in attachments:
+ if i.get("content_transfer_encoding") == "base64":
+ payload = base64.b64decode(i["payload"])
+ else:
+ payload = i["payload"]
+
+ i["md5"], i["sha1"], i["sha256"], i["sha512"] = fingerprints(payload)
+
+ for i in attachments:
+ safe_print(json.dumps(i, ensure_ascii=False, indent=4))
+
+
+def write_attachments(attachments, base_path): # pragma: no cover
+ for a in attachments:
+ write_sample(
+ binary=a["binary"],
+ payload=a["payload"],
+ path=base_path,
+ filename=a["filename"],
+ )
+
+
+def write_sample(binary, payload, path, filename): # pragma: no cover
+ """
+ This function writes a sample on file system.
+
+ Args:
+ binary (bool): True if it's a binary file
+ payload: payload of sample, in base64 if it's a binary
+ path (string): path of file
+ filename (string): name of file
+ hash_ (string): file hash
+ """
+ if not os.path.exists(path):
+ os.makedirs(path)
+ sample = os.path.join(path, filename)
+
+ if binary:
+ with open(sample, "wb") as f:
+ f.write(base64.b64decode(payload))
+ else:
+ with open(sample, "w") as f:
+ f.write(payload)
+
+
+def random_string(string_length=10):
+ """Generate a random string of fixed length
+
+ Keyword Arguments:
+ string_length {int} -- String length (default: {10})
+
+ Returns:
+ str -- Random string
+ """
+ letters = string.ascii_lowercase
+ return "".join(random.choice(letters) for _ in range(string_length))
diff --git a/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/version.py b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdb9febd21372eaa7a89fcc338874320839b2cab
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/environment/source/src/mailparser/version.py
@@ -0,0 +1,19 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+__version__ = "4.1.4"
diff --git a/tasks/tasksmith-ae872f5c3953/instruction.md b/tasks/tasksmith-ae872f5c3953/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..e5f49fc45601cf291b6e70e47de2ab0f85e60eac
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/instruction.md
@@ -0,0 +1,25 @@
+In `mailparser`, address headers such as `From`, `To`, and `Cc` are returned as lists of `(display_name, email_address)` tuples. Fix two related bugs in this parsing logic:
+
+**Bug 1 – Comma in encoded display name causes incorrect splitting.**
+A `From` header like:
+```
+From: =?iso-8859-1?Q?Last=DFlName=2C_FirstName?=
+```
+should decode to a single address `("LastßlName, FirstName", "comma.name@example.com")`. Currently, decoding the encoded word first produces a string containing a bare comma, which the RFC 2822 address parser then uses as a field separator, incorrectly splitting into multiple addresses.
+
+**Bug 2 – Encoded display name identical to the email address should be suppressed.**
+When the decoded display name equals the email address string, the display name should be returned as an empty string `""`. For example:
+```
+From: =?UTF-8?B?bm90aWZpY2FjY2lvbi1jbGllbnRlc0BiYnZhLm14?=
+```
+The base64 payload decodes to `notificaccion-clientes@bbva.mx`, which equals the address, so the result must be `[("", "notificaccion-clientes@bbva.mx")]` — one tuple, not two.
+
+**Expected behavior for a header mixing simple and encoded addresses:**
+```
+Cc: simple@example.net, =?UTF-8?Q?John_=22Johnny=22_Doe?=
+```
+→ `[("", "simple@example.net"), ('John "Johnny" Doe', "john.doe@example.com")]`
+
+The fix must not regress any currently passing address-header tests.
+
+Work in `/workspace`. Submit your fix in Python source files under `src/mailparser`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files.
diff --git a/tasks/tasksmith-ae872f5c3953/solution/reference/src/mailparser/core.py b/tasks/tasksmith-ae872f5c3953/solution/reference/src/mailparser/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f07507d830782fb152b28795767d90a6e1ef691
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/solution/reference/src/mailparser/core.py
@@ -0,0 +1,768 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import base64
+import email
+import ipaddress
+import json
+import logging
+import os
+
+from mailparser.const import ADDRESSES_HEADERS, EPILOGUE_DEFECTS, REGXIP
+from mailparser.utils import (
+ convert_mail_date,
+ decode_header_part,
+ find_between,
+ get_header,
+ get_mail_keys,
+ get_to_domains,
+ msgconvert,
+ ported_open,
+ ported_string,
+ random_string,
+ receiveds_parsing,
+ write_attachments,
+)
+
+log = logging.getLogger(__name__)
+
+
+def parse_from_file_obj(fp):
+ """
+ Parsing email from a file-like object.
+
+ Args:
+ fp (file-like object): file-like object of raw email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_file_obj(fp)
+
+
+def parse_from_file(fp):
+ """
+ Parsing email from file.
+
+ Args:
+ fp (string): file path of raw email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_file(fp)
+
+
+def parse_from_file_msg(fp):
+ """
+ Parsing email from file Outlook msg.
+
+ Args:
+ fp (string): file path of raw Outlook email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_file_msg(fp)
+
+
+def parse_from_string(s):
+ """
+ Parsing email from string.
+
+ Args:
+ s (string): raw email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_string(s)
+
+
+def parse_from_bytes(bt):
+ """
+ Parsing email from bytes. Only for Python 3
+
+ Args:
+ bt (bytes-like object): raw email as bytes-like object
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_bytes(bt)
+
+
+class MailParser:
+ """
+ MailParser package provides a standard parser that understands
+ most email document structures like official email package.
+ MailParser handles the encoding of email and split the raw email for you.
+
+ Headers:
+ https://www.iana.org/assignments/message-headers/message-headers.xhtml
+ """
+
+ def __init__(self, message=None):
+ """
+ Init a new object from a message object structure.
+ """
+ self._message = message
+ log.debug("All headers of emails: {}".format(", ".join(message.keys())))
+ self.parse()
+
+ def __str__(self):
+ if self.message:
+ return self.subject
+ else:
+ return str()
+
+ @classmethod
+ def from_file_obj(cls, fp):
+ """
+ Init a new object from a file-like object.
+ Not for Outlook msg.
+
+ Args:
+ fp (file-like object): file-like object of raw email
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug("Parsing email from file object")
+ try:
+ fp.seek(0)
+ except OSError:
+ # When stdout is a TTY it's a character device
+ # and it's not seekable, you cannot seek in a TTY.
+ pass
+ finally:
+ s = fp.read()
+
+ return cls.from_string(s)
+
+ @classmethod
+ def from_file(cls, fp, is_outlook=False):
+ """
+ Init a new object from a file path.
+
+ Args:
+ fp (string): file path of raw email
+ is_outlook (boolean): if True is an Outlook email
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug(f"Parsing email from file {fp!r}")
+
+ with ported_open(fp) as f:
+ message = email.message_from_file(f)
+
+ if is_outlook:
+ log.debug(f"Removing temp converted Outlook email {fp!r}")
+ os.remove(fp)
+
+ return cls(message)
+
+ @classmethod
+ def from_file_msg(cls, fp):
+ """
+ Init a new object from a Outlook message file,
+ mime type: application/vnd.ms-outlook
+
+ Args:
+ fp (string): file path of raw Outlook email
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug("Parsing email from file Outlook")
+ f, _ = msgconvert(fp)
+ return cls.from_file(f, True)
+
+ @classmethod
+ def from_string(cls, s):
+ """
+ Init a new object from a string.
+
+ Args:
+ s (string): raw email
+
+ Returns:
+ Instance of MailParser
+ """
+
+ log.debug("Parsing email from string")
+ message = email.message_from_string(s)
+ return cls(message)
+
+ @classmethod
+ def from_bytes(cls, bt):
+ """
+ Init a new object from bytes.
+
+ Args:
+ bt (bytes-like object): raw email as bytes-like object
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug("Parsing email from bytes")
+ message = email.message_from_bytes(bt)
+ return cls(message)
+
+ def _reset(self):
+ """
+ Reset the state of mail object.
+ """
+ log.debug("Reset all variables")
+
+ self._attachments = []
+ self._text_plain = []
+ self._text_html = []
+ self._text_not_managed = []
+ self._defects = []
+ self._defects_categories = set()
+ self._has_defects = False
+
+ def _append_defects(self, part, part_content_type):
+ """
+ Add new defects and defects categories to object attributes.
+
+ The defects are a list of all the problems found
+ when parsing this message.
+
+ Args:
+ part (string): mail part
+ part_content_type (string): content type of part
+ """
+
+ part_defects = {}
+
+ for e in part.defects:
+ defects = f"{e.__class__.__name__}: {e.__doc__}"
+ self._defects_categories.add(e.__class__.__name__)
+ part_defects.setdefault(part_content_type, []).append(defects)
+ log.debug(f"Added defect {defects!r}")
+
+ # Tag mail with defect
+ if part_defects:
+ self._has_defects = True
+
+ # Save all defects
+ self._defects.append(part_defects)
+
+ def _make_mail(self, complete=True):
+ """
+ This method assigns the right values to all tokens of email.
+ Returns a parsed object
+
+ Keyword Arguments:
+ complete {bool} -- If True returns all mails parts
+ (default: {True})
+
+ Returns:
+ dict -- Parsed email object
+ """
+
+ mail = {}
+ keys = get_mail_keys(self.message, complete)
+
+ for i in keys:
+ log.debug(f"Getting header or part {i!r}")
+ value = getattr(self, i)
+ if value:
+ mail[i] = value
+
+ # add defects
+ mail["has_defects"] = self.has_defects
+ if self.has_defects:
+ mail["defects"] = self.defects
+ mail["defects_categories"] = list(self.defects_categories)
+
+ return mail
+
+ def parse(self):
+ """
+ This method parses the raw email and makes the tokens.
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+
+ if not self.message:
+ return self
+
+ # reset and start parsing
+ self._reset()
+ parts = [] # Normal parts plus defects
+
+ # walk all mail parts to search defects
+ for p in self.message.walk():
+ part_content_type = p.get_content_type()
+ self._append_defects(p, part_content_type)
+ parts.append(p)
+
+ # If defects are in epilogue defects get epilogue
+ if self.defects_categories & EPILOGUE_DEFECTS:
+ log.debug("Found defects in emails")
+ epilogue = find_between(
+ self.message.epilogue,
+ "{}".format("--" + self.message.get_boundary()),
+ "{}".format("--" + self.message.get_boundary() + "--"),
+ )
+
+ try:
+ p = email.message_from_string(epilogue)
+ parts.append(p)
+ except TypeError:
+ log.debug("Failed to get epilogue part for TypeError")
+ except Exception:
+ log.error("Failed to get epilogue part. Check raw mail.")
+
+ # walk all mail parts
+ for i, p in enumerate(parts):
+ if (
+ not p.is_multipart()
+ or ported_string(p.get_content_disposition()).lower() == "attachment"
+ ):
+ charset = p.get_content_charset("utf-8")
+ charset_raw = p.get_content_charset()
+ log.debug(f"Charset {charset!r} part {i!r}")
+ content_disposition = ported_string(p.get_content_disposition()).lower()
+ log.debug(f"content-disposition {content_disposition!r} part {i!r}")
+ content_id = ported_string(p.get("content-id"))
+ log.debug(f"content-id {content_id!r} part {i!r}")
+ content_subtype = ported_string(p.get_content_subtype())
+ log.debug(f"content subtype {content_subtype!r} part {i!r}")
+ filename = decode_header_part(p.get_filename())
+
+ is_attachment = False
+ if filename:
+ is_attachment = True
+ else:
+ if content_id and content_subtype not in ("html", "plain"):
+ is_attachment = True
+ filename = content_id
+ elif content_subtype in ("rtf"):
+ is_attachment = True
+ filename = f"{random_string()}.rtf"
+ elif content_disposition == "attachment":
+ is_attachment = True
+ filename = f"{random_string()}.txt"
+
+ # this is an attachment
+ if is_attachment:
+ log.debug(f"Email part {i!r} is an attachment")
+ log.debug(f"Filename {filename!r} part {i!r}")
+ binary = False
+ mail_content_type = ported_string(p.get_content_type())
+ log.debug(f"Mail content type {mail_content_type!r} part {i!r}")
+ transfer_encoding = ported_string(
+ p.get("content-transfer-encoding", "")
+ ).lower()
+ log.debug(f"Transfer encoding {transfer_encoding!r} part {i!r}")
+ content_disposition = ported_string(p.get("content-disposition"))
+ log.debug(f"content-disposition {content_disposition!r} part {i!r}")
+
+ if p.is_multipart():
+ payload = "".join(
+ [m.as_string() for m in p.get_payload(decode=False)]
+ )
+ binary = False
+ log.debug(f"Filename {filename!r} part {i!r} is multipart")
+ elif transfer_encoding == "base64" or (
+ transfer_encoding
+ == "quoted-\
+ printable"
+ and "application" in mail_content_type
+ ):
+ payload = p.get_payload(decode=False)
+ binary = True
+ log.debug(f"Filename {filename!r} part {i!r} is binary")
+ elif "uuencode" in transfer_encoding:
+ # Re-encode in base64
+ payload = base64.b64encode(p.get_payload(decode=True)).decode(
+ "ascii"
+ )
+ binary = True
+ transfer_encoding = "base64"
+ log.debug(
+ f"Filename {filename!r} part {i!r} is binary (uuencode"
+ " re-encoded to base64)"
+ )
+ else:
+ payload = ported_string(
+ p.get_payload(decode=True), encoding=charset
+ )
+ log.debug(f"Filename {filename!r} part {i!r} is not binary")
+
+ self._attachments.append(
+ {
+ "filename": filename,
+ "payload": payload,
+ "binary": binary,
+ "mail_content_type": mail_content_type,
+ "content-id": content_id,
+ "content-disposition": content_disposition,
+ "charset": charset_raw,
+ "content_transfer_encoding": transfer_encoding,
+ }
+ )
+
+ # this isn't an attachments
+ else:
+ log.debug(f"Email part {i!r} is not an attachment")
+
+ # Get the payload using get_payload method with decode=True
+ # As Python truly decodes only 'base64',
+ # 'quoted-printable', 'x-uuencode',
+ # 'uuencode', 'uue', 'x-uue'
+ # And for other encodings it breaks the characters so
+ # we need to decode them with encoding python is appying
+ # To maintain the characters
+ payload = p.get_payload(decode=True)
+ cte = p.get("Content-Transfer-Encoding")
+ if cte:
+ cte = cte.lower()
+
+ if not cte or cte in ["7bit", "8bit"]:
+ try:
+ payload = payload.decode("raw-unicode-escape")
+ except UnicodeDecodeError:
+ payload = ported_string(payload, encoding=charset)
+ else:
+ payload = ported_string(payload, encoding=charset)
+
+ if payload:
+ if p.get_content_subtype() == "html":
+ self._text_html.append(payload)
+ elif p.get_content_subtype() == "plain":
+ self._text_plain.append(payload)
+ else:
+ log.warning(
+ f"Email content {p.get_content_subtype()!r} not handled"
+ )
+ self._text_not_managed.append(payload)
+
+ # Parsed object mail with all parts
+ self._mail = self._make_mail()
+
+ # Parsed object mail with mains parts
+ self._mail_partial = self._make_mail(complete=False)
+
+ def get_server_ipaddress(self, trust):
+ """
+ Return the ip address of sender
+
+ Overview:
+ Extract a reliable sender IP address heuristically for each message.
+ Although the message format dictates a chain of relaying IP
+ addresses in each message, a malicious relay can easily alter that.
+ Therefore we cannot simply take the first IP in
+ the chain. Instead, our method is as follows.
+ First we trust the sender IP reported by our mail server in the
+ Received headers, and if the previous relay IP address is on our trust
+ list (e.g. other well-known mail services), we continue to
+ follow the previous Received line, till we reach the first unrecognized
+ IP address in the email header.
+
+ From article Characterizing Botnets from Email Spam Records:
+ Li Zhuang, J. D. Tygar
+
+ In our case we trust only our mail server with the trust string.
+
+ Args:
+ trust (string): String that identify our mail server
+
+ Returns:
+ string with the ip address
+ """
+ log.debug(f"Trust string is {trust!r}")
+
+ if not trust.strip():
+ return
+
+ received = self.message.get_all("received", [])
+
+ for i in received:
+ i = ported_string(i)
+ if trust in i:
+ log.debug(f"Trust string {trust!r} is in {i!r}")
+ ip_str = self._extract_ip(i)
+ if ip_str:
+ return ip_str
+
+ def _extract_ip(self, received_header):
+ """
+ Extract the IP address from the received header if it is not private.
+
+ Args:
+ received_header (string): The received header string
+
+ Returns:
+ string with the ip address or None
+ """
+ check = REGXIP.findall(received_header[0 : received_header.find("by")])
+ if check:
+ try:
+ ip_str = str(check[-1])
+ log.debug(f"Found sender IP {ip_str!r} in {received_header!r}")
+ ip = ipaddress.ip_address(ip_str)
+ except ValueError:
+ return None
+ else:
+ if not ip.is_private:
+ log.debug(f"IP {ip_str!r} not private")
+ return ip_str
+ return None
+
+ def write_attachments(self, base_path):
+ """This method writes the attachments of mail on disk
+
+ Arguments:
+ base_path {str} -- Base path where write the attachments
+ """
+ write_attachments(attachments=self.attachments, base_path=base_path)
+
+ def __getattr__(self, name):
+ name = name.strip("_").lower()
+ name_header = name.replace("_", "-")
+
+ # json headers
+ if name.endswith("_json"):
+ name = name[:-5]
+ return json.dumps(getattr(self, name), ensure_ascii=False)
+
+ # raw headers
+ elif name.endswith("_raw"):
+ name = name[:-4]
+ raw = self.message.get_all(name)
+ return json.dumps(raw, ensure_ascii=False)
+
+ # object headers
+ elif name_header in ADDRESSES_HEADERS:
+ raw_header = self.message.get(name_header, "")
+ # parse before decoding
+ parsed_addresses = email.utils.getaddresses([raw_header], strict=True)
+
+ # decoded addresses
+ return [
+ (
+ (
+ ""
+ if (decoded_name := decode_header_part(name)) == email_addr
+ else decoded_name
+ ),
+ email_addr,
+ )
+ for name, email_addr in parsed_addresses
+ ]
+
+ # others headers
+ else:
+ return get_header(self.message, name_header)
+
+ @property
+ def attachments(self):
+ """
+ Return a list of all attachments in the mail
+ """
+ return self._attachments
+
+ @property
+ def received(self):
+ """
+ Return a list of all received headers parsed
+ """
+ output = self.received_raw
+ return receiveds_parsing(output)
+
+ @property
+ def received_json(self):
+ """
+ Return a JSON of all received headers
+ """
+ return json.dumps(self.received, ensure_ascii=False, indent=2)
+
+ @property
+ def received_raw(self):
+ """
+ Return a list of all received headers in raw format
+ """
+ output = []
+ for i in self.message.get_all("received", []):
+ output.append(decode_header_part(i))
+ return output
+
+ @property
+ def body(self):
+ """
+ Return all text plain and text html parts of mail delimited from string
+ "--- mail_boundary ---"
+ """
+ return "\n--- mail_boundary ---\n".join(
+ self.text_plain + self.text_html + self.text_not_managed
+ )
+
+ @property
+ def headers(self) -> dict:
+ """
+ Return only the headers as Python object
+ """
+ all_headers = set(self.message.keys()) - set(["headers"])
+ return {i: getattr(self, i) for i in all_headers}
+
+ @property
+ def headers_json(self):
+ """
+ Return the JSON of headers
+ """
+ return json.dumps(self.headers, ensure_ascii=False, indent=2)
+
+ @property
+ def text_plain(self):
+ """
+ Return a list of all text plain parts of email.
+ """
+ return self._text_plain
+
+ @property
+ def text_html(self):
+ """
+ Return a list of all text html parts of email.
+ """
+ return self._text_html
+
+ @property
+ def text_not_managed(self):
+ """
+ Return a list of all text not managed of email.
+ """
+ return self._text_not_managed
+
+ @property
+ def date(self):
+ """
+ Return the mail date in datetime.datetime format and UTC.
+ """
+ date = self.message.get("date")
+ conv = None
+
+ try:
+ conv, _ = convert_mail_date(date)
+ except Exception:
+ pass
+ return conv
+
+ @property
+ def timezone(self):
+ """
+ Return timezone. Offset from UTC.
+ """
+ date = self.message.get("date")
+ timezone = 0
+
+ try:
+ _, timezone = convert_mail_date(date)
+ except Exception:
+ pass
+ return timezone
+
+ @property
+ def date_json(self):
+ """
+ Return the JSON of date
+ """
+ if self.date:
+ return json.dumps(self.date.isoformat(), ensure_ascii=False)
+
+ @property
+ def mail(self):
+ """
+ Return the Python object of mail parsed
+ """
+ return self._mail
+
+ @property
+ def mail_json(self):
+ """
+ Return the JSON of mail parsed
+ """
+ if self.mail.get("date"):
+ self._mail["date"] = self.date.isoformat()
+ return json.dumps(self.mail, ensure_ascii=False, indent=2)
+
+ @property
+ def mail_partial(self):
+ """
+ Return the Python object of mail parsed
+ with only the mains headers
+ """
+ return self._mail_partial
+
+ @property
+ def mail_partial_json(self):
+ """
+ Return the JSON of mail parsed partial
+ """
+ if self.mail_partial.get("date"):
+ self._mail_partial["date"] = self.date.isoformat()
+ return json.dumps(self.mail_partial, ensure_ascii=False, indent=2)
+
+ @property
+ def defects(self):
+ """
+ The defects property contains a list of
+ all the problems found when parsing this message.
+ """
+ return self._defects
+
+ @property
+ def defects_categories(self):
+ """
+ Return a set with only defects categories.
+ """
+ return self._defects_categories
+
+ @property
+ def has_defects(self):
+ """
+ Return a boolean: True if mail has defects.
+ """
+ return self._has_defects
+
+ @property
+ def message(self):
+ """
+ email.message.Message class.
+ """
+ return self._message
+
+ @property
+ def message_as_string(self):
+ """
+ Return the entire message flattened as a string.
+ """
+ return self.message.as_string()
+
+ @property
+ def to_domains(self):
+ """
+ Return all domain of 'to' and 'reply-to' email addresses
+ """
+ return get_to_domains(self.to, self.reply_to)
diff --git a/tasks/tasksmith-ae872f5c3953/solution/solve.sh b/tasks/tasksmith-ae872f5c3953/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..79a0affe1d2ef46db1ac72e0730ddf4181df8e67
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/solution/solve.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+set -eu
+mkdir -p -- /workspace/src/mailparser
+cp /solution/reference/src/mailparser/core.py /workspace/src/mailparser/core.py
diff --git a/tasks/tasksmith-ae872f5c3953/task.toml b/tasks/tasksmith-ae872f5c3953/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..c6fea397d04119785f17c51a7f6a263378191c59
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/task.toml
@@ -0,0 +1,131 @@
+schema_version = "1.3"
+
+[task]
+name = "repo2rlenv/tasksmith-ae872f5c3953"
+
+[metadata.repo2env]
+recipe = "tasksmith"
+recipe_version = "1"
+source_url = "https://github.com/SpamScope/mail-parser/pull/147"
+source_head = "ae027716b4cd0a3b6fa694f033a81dff3f5e33a7"
+source_base = "025f937e935ed3844597536d856db77cea7d4d59"
+workspace_strategy = "head_minus_source_patch"
+source_diff_sha256 = "af60b4e7c412e19b98a81406b4e72fb2fbc9dab0cc15e4237a0d6a14c83085aa"
+acceptance_profile = "practical-generation-v1"
+upstream_test_policy = "retain"
+reward_kinds = [
+ "test_execution",
+]
+quality_status = "exported"
+fail_to_pass_count = 5
+pass_to_pass_count = 1
+tracked_files = [
+ "environment/Dockerfile",
+ "environment/source/LICENSE.txt",
+ "environment/source/NOTICE.txt",
+ "environment/source/README.md",
+ "environment/source/pyproject.toml",
+ "environment/source/src/mailparser/__init__.py",
+ "environment/source/src/mailparser/__main__.py",
+ "environment/source/src/mailparser/const.py",
+ "environment/source/src/mailparser/core.py",
+ "environment/source/src/mailparser/exceptions.py",
+ "environment/source/src/mailparser/utils.py",
+ "environment/source/src/mailparser/version.py",
+ "solution/reference/src/mailparser/core.py",
+ "solution/solve.sh",
+ "tests/Dockerfile",
+ "tests/contract.json",
+ "tests/grade.py",
+ "tests/source/.github/FUNDING.yml",
+ "tests/source/.github/ISSUE_TEMPLATE/bug_report.md",
+ "tests/source/.github/ISSUE_TEMPLATE/feature_request.md",
+ "tests/source/.github/copilot-instructions.md",
+ "tests/source/.github/instructions/containerization-docker-best-practices.instructions.md",
+ "tests/source/.github/instructions/github-actions-ci-cd-best-practices.instructions.md",
+ "tests/source/.github/instructions/markdown.instructions.md",
+ "tests/source/.github/instructions/python.instructions.md",
+ "tests/source/.github/workflows/main.yml",
+ "tests/source/.gitignore",
+ "tests/source/.markdownlint.yaml",
+ "tests/source/.pre-commit-config.yaml",
+ "tests/source/Dockerfile",
+ "tests/source/LICENSE.txt",
+ "tests/source/Makefile",
+ "tests/source/NOTICE.txt",
+ "tests/source/README.md",
+ "tests/source/docker-compose.yml",
+ "tests/source/docs/images/Bitcoin SpamScope.jpg",
+ "tests/source/pyproject.toml",
+ "tests/source/src/mailparser/__init__.py",
+ "tests/source/src/mailparser/__main__.py",
+ "tests/source/src/mailparser/const.py",
+ "tests/source/src/mailparser/core.py",
+ "tests/source/src/mailparser/exceptions.py",
+ "tests/source/src/mailparser/utils.py",
+ "tests/source/src/mailparser/version.py",
+ "tests/source/tests/mails/mail_test_17",
+ "tests/source/tests/mails/mail_test_18",
+ "tests/source/tests/tasksmith_behavior.py",
+ "tests/source/tests/test_improved_received_patterns.py",
+ "tests/source/tests/test_mail_parser.py",
+ "tests/source/tests/test_main.py",
+ "tests/source/tests/test_utils.py",
+ "tests/source/uv.lock",
+ "tests/test.sh",
+ "tests/test_driver.py",
+ "tests/test_results.py",
+]
+executable_files = [
+ "solution/solve.sh",
+ "tests/test.sh",
+]
+bundle_hash = "sha256:2cb5ce9aeee3aacdd1509eacd2183f20fe260adceeec64b86c1088841ec1f275"
+
+[metadata.repo2env.evaluation]
+schema_version = "1"
+status = "unverified"
+stage = "generation"
+reason_codes = [
+ "task_changed",
+]
+detail = "Task content changed; validate this revision before acceptance."
+provenance = "unknown"
+subject_bundle_hash = "sha256:2cb5ce9aeee3aacdd1509eacd2183f20fe260adceeec64b86c1088841ec1f275"
+evidence = []
+
+[metadata.repo2env.quality_requirements]
+probe_focus = [
+ "general",
+]
+
+[environment]
+docker_image = "ghcr.io/younesbelkada/hat@sha256:0c6fa0c129088a40eccf9bf5bee0e0ae36d00dc244a8e53479834e754f8f715d"
+cpus = 1
+memory_mb = 2048
+build_timeout_sec = 600
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 600
+user = "learner"
+network_mode = "no-network"
+
+[verifier]
+timeout_sec = 90
+user = "root"
+network_mode = "no-network"
+environment_mode = "separate"
+
+[verifier.environment]
+network_mode = "no-network"
+cpus = 1
+memory_mb = 512
+
+[[artifacts]]
+source = "/workspace/src/mailparser"
+exclude = [
+ "__pycache__",
+ "*.pyc",
+ ".pytest_cache",
+]
diff --git a/tasks/tasksmith-ae872f5c3953/tests/Dockerfile b/tasks/tasksmith-ae872f5c3953/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..bbe17646ca0e8553e8c17bdbbcf0d4d7e4fc1d7a
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/Dockerfile
@@ -0,0 +1,10 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir hatchling==1.33.0 pytest==9.2.0 pytest-cov==7.1.0 coverage==7.17.3 pytest-mock==3.17.0 pytest-ordering==0.6
+COPY source /workspace
+RUN python -m pip install --no-cache-dir -e .
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
+RUN useradd -m -u 1001 grader
+COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/
+RUN chmod 755 /tests && chmod 644 /tests/*
diff --git a/tasks/tasksmith-ae872f5c3953/tests/contract.json b/tasks/tasksmith-ae872f5c3953/tests/contract.json
new file mode 100644
index 0000000000000000000000000000000000000000..c41f3dd5aa2a021e5211d670a8e2e158e4e8c6ff
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/contract.json
@@ -0,0 +1 @@
+{"expected_passes": ["tests.tasksmith_behavior::test_comma_in_encoded_display_name", "tests.tasksmith_behavior::test_encoded_name_equals_email_suppressed", "tests.tasksmith_behavior::test_mixed_cc_header", "tests.test_mail_parser.TestMailParser::test_comma_in_name", "tests.test_mail_parser.TestMailParser::test_issue_136", "tests.tasksmith_behavior::test_plain_address_header_unaffected"], "immutable_assets": {}, "optional_files": [], "pytest_args": [], "submitted_files": ["src/mailparser/__init__.py", "src/mailparser/__main__.py", "src/mailparser/const.py", "src/mailparser/core.py", "src/mailparser/exceptions.py", "src/mailparser/utils.py", "src/mailparser/version.py"], "submitted_roots": ["src/mailparser"], "test_paths": ["tests/test_mail_parser.py::TestMailParser::test_issue_136", "tests/test_mail_parser.py::TestMailParser::test_comma_in_name", "tests/tasksmith_behavior.py"], "timeout_sec": 60}
\ No newline at end of file
diff --git a/tasks/tasksmith-ae872f5c3953/tests/grade.py b/tasks/tasksmith-ae872f5c3953/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..a803a55bfcc142c8279645ea59cea90b2a90918a
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/grade.py
@@ -0,0 +1,196 @@
+"""Standalone trusted entry point; copied into each separate verifier image.
+
+No Repo2RLEnv installation is needed to grade an exported task. Submitted Python
+runs as an unprivileged user; this parent owns the result parser and reward file.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import os
+import signal
+import stat
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+
+def child_environment(temporary: str) -> dict[str, str]:
+ """Preserve prepared runtime assets without inheriting controller credentials."""
+ return {
+ **{
+ key: os.environ[key]
+ for key in (
+ "LD_LIBRARY_PATH",
+ "CUDA_VISIBLE_DEVICES",
+ "NVIDIA_VISIBLE_DEVICES",
+ "NVIDIA_DRIVER_CAPABILITIES",
+ "NCCL_SOCKET_IFNAME",
+ "GLOO_SOCKET_IFNAME",
+ "HF_HOME",
+ "HF_HUB_CACHE",
+ "HF_HUB_OFFLINE",
+ "TRANSFORMERS_OFFLINE",
+ "HF_DATASETS_OFFLINE",
+ )
+ if key in os.environ
+ },
+ "PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin",
+ "HOME": temporary,
+ "PYTHONDONTWRITEBYTECODE": "1",
+ "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
+ }
+
+
+def validate_submission(workspace: Path, contract: dict) -> None:
+ """Validate private staging and remove inert backups before importing Python."""
+ submitted = set(contract["submitted_files"])
+ backups: set[str] = set()
+ optional = submitted & set(contract.get("optional_files", []))
+ paths = submitted - optional
+ for relative in optional:
+ path = workspace / relative
+ if any(component.is_symlink() for component in (path, *path.parents)):
+ raise ValueError("Submitted source contains a symlink")
+ # Added standalone modules may be absent in the baseline. If supplied,
+ # apply the same regular-file and size checks as every required module.
+ if path.exists():
+ paths.add(relative)
+ roots = contract.get("submitted_roots", [])
+ immutable = contract.get("immutable_assets", {})
+ paths.update(immutable)
+ for relative in roots:
+ root = workspace / relative
+ if root.is_symlink() or not root.is_dir():
+ raise ValueError("Submitted source root is missing or linked")
+ for path in root.rglob("*"):
+ if path.is_symlink():
+ raise ValueError("Submitted source contains a symlink")
+ if path.is_dir():
+ continue
+ name = path.relative_to(workspace).as_posix()
+ if path.suffix != ".py" and name not in immutable:
+ if name not in submitted and path.name.endswith((".py.bak", ".py~")):
+ backups.add(name)
+ else:
+ raise ValueError("Only Python source files may be added")
+ paths.add(name)
+ for relative in sorted(paths):
+ path = workspace / relative
+ for component in (path, *path.parents):
+ if component.is_symlink():
+ raise ValueError("Submitted source contains a symlink")
+ if (
+ not path.is_file()
+ or not stat.S_ISREG(path.stat().st_mode)
+ or path.stat().st_size > 8 * 1024 * 1024
+ ):
+ raise ValueError("Submitted source is not a bounded regular file")
+ if (
+ relative in immutable
+ and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative]
+ ):
+ raise ValueError("Non-Python source assets must remain unchanged")
+ if relative not in backups:
+ # os.chown doesn't exist on Windows. This module only ever runs for
+ # real inside the Linux verifier container (every other path here
+ # is an absolute container path); the guard exists so the tests
+ # that call validate_submission() directly can run on a Windows
+ # host without touching real container-only ownership semantics.
+ if sys.platform != "win32":
+ os.chown(path, 0, 0)
+ path.chmod(0o644)
+ # Only the verifier's collected copy is cleaned. The learner workspace and
+ # archived submission retain their bytes. Validate every path first so a
+ # backup cannot bypass linked, oversized, required, or immutable file checks.
+ for relative in sorted(backups):
+ (workspace / relative).unlink()
+
+
+def main() -> None:
+ directory = Path("/tests")
+ parser_spec = importlib.util.spec_from_file_location(
+ "test_results", directory / "test_results.py"
+ )
+ parser = importlib.util.module_from_spec(parser_spec)
+ sys.modules[parser_spec.name] = parser
+ parser_spec.loader.exec_module(parser)
+ contract = json.loads((directory / "contract.json").read_text())
+ logs = Path("/logs/verifier")
+ logs.mkdir(parents=True, exist_ok=True)
+ logs.chmod(0o755)
+ reward = logs / "reward.txt"
+ reward.write_text("0\n")
+ reward.chmod(0o644)
+ try:
+ validate_submission(Path("/workspace"), contract)
+ except (ValueError, OSError) as exc:
+ (logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)}))
+ return
+ with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary:
+ working = Path(temporary)
+ if sys.platform != "win32": # os.chown doesn't exist on Windows; see above
+ os.chown(working, 1001, 1001)
+ working.chmod(0o700)
+ report = working / "results.xml"
+ command = [
+ sys.executable,
+ "-I",
+ "/tests/test_driver.py",
+ *contract["test_paths"],
+ *contract.get("pytest_args", []),
+ "-q",
+ "--tb=short",
+ "-p",
+ "no:cacheprovider",
+ f"--junitxml={report}",
+ ]
+ with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr:
+ process = subprocess.Popen(
+ command,
+ cwd="/workspace",
+ stdout=stdout,
+ stderr=stderr,
+ user=1001,
+ group=1001,
+ extra_groups=[],
+ start_new_session=True,
+ env=child_environment(temporary),
+ )
+ try:
+ code = process.wait(timeout=contract["timeout_sec"])
+ finally:
+ # Terminate descendants too: they must not keep modifying the
+ # child-owned report while the trusted parent checks it.
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024:
+ (logs / "result.json").write_text(
+ json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"})
+ )
+ return
+ text = report.read_text()
+ (logs / "results.xml").write_text(text)
+ try:
+ parsed = parser.parse_junit(text, returncode=code)
+ except ValueError as exc:
+ (logs / "result.json").write_text(
+ json.dumps({"passed": False, "returncode": code, "reason": str(exc)})
+ )
+ return
+ expected = set(contract["expected_passes"])
+ passed = code == 0 and bool(expected) and parsed.passed == expected
+ (logs / "result.json").write_text(
+ json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses})
+ )
+ reward.write_text("1\n" if passed else "0\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.github/FUNDING.yml b/tasks/tasksmith-ae872f5c3953/tests/source/.github/FUNDING.yml
new file mode 100644
index 0000000000000000000000000000000000000000..80a0a93bcca42b8e340ffec7238f1b41076e96be
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.github/FUNDING.yml
@@ -0,0 +1,3 @@
+# These are supported funding model platforms
+
+github: [fedelemantuano]
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.github/ISSUE_TEMPLATE/bug_report.md b/tasks/tasksmith-ae872f5c3953/tests/source/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 0000000000000000000000000000000000000000..ec400c369392e8cbce0df32f9e114031013c0083
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,33 @@
+---
+name: Bug report
+about: Create a report to help us improve
+
+---
+
+**Describe the bug**
+A clear and concise description of what the bug is.
+
+**To Reproduce**
+Steps to reproduce the behavior:
+
+1. `import mailparser`
+2. `mail = mailparser.parse_from_file(f)`
+3. '....'
+4. See error
+
+**Expected behavior**
+A clear and concise description of what you expected to happen.
+
+**Raw mail**
+The raw mail to reproduce the behavior.
+You can use a `gist` like [this](https://gist.github.com/fedelemantuano/5dd702004c25a46b2bd60de21e67458e).
+The issues without raw mail will be closed.
+
+**Environment:**
+
+- OS: [e.g. Linux, Windows]
+- Docker: [yes or no]
+- mail-parser version [e.g. 3.6.0]
+
+**Additional context**
+Add any other context about the problem here (e.g. stack traceback error).
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.github/ISSUE_TEMPLATE/feature_request.md b/tasks/tasksmith-ae872f5c3953/tests/source/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 0000000000000000000000000000000000000000..066b2d920a28db73b4ba3a0b35e6905eeeef5772
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,17 @@
+---
+name: Feature request
+about: Suggest an idea for this project
+
+---
+
+**Is your feature request related to a problem? Please describe.**
+A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
+
+**Describe the solution you'd like**
+A clear and concise description of what you want to happen.
+
+**Describe alternatives you've considered**
+A clear and concise description of any alternative solutions or features you've considered.
+
+**Additional context**
+Add any other context or screenshots about the feature request here.
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.github/copilot-instructions.md b/tasks/tasksmith-ae872f5c3953/tests/source/.github/copilot-instructions.md
new file mode 100644
index 0000000000000000000000000000000000000000..f84e7a8ba0b3aba1f41cc8e55742c524f58a6032
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.github/copilot-instructions.md
@@ -0,0 +1,226 @@
+# Copilot Instructions for mail-parser
+
+mail-parser is a **production-grade email parsing library** for Python that transforms raw email messages into
+structured Python objects. Originally built as the foundation for [SpamScope](https://github.com/SpamScope/spamscope),
+it excels at security analysis, forensics, and RFC-compliant email processing.
+
+## Core Architecture
+
+### Factory-Based API Pattern
+
+**Always use factory functions** instead of direct `MailParser()` instantiation:
+
+```python
+import mailparser
+mail = mailparser.parse_from_file(filepath) # Standard email files
+mail = mailparser.parse_from_string(raw_email) # Email as string
+mail = mailparser.parse_from_bytes(email_bytes) # Email as bytes
+mail = mailparser.parse_from_file_msg(msg_file) # Outlook .msg files
+```
+
+### Triple-Format Property Access
+
+Every parsed component offers **three access patterns** (`src/mailparser/core.py:550-570`):
+
+```python
+mail.subject # Python object (decoded string)
+mail.subject_raw # Raw header value (JSON list)
+mail.subject_json # JSON-serialized version
+```
+
+This pattern applies to all properties via `__getattr__` magic in `core.py`.
+
+### Property Naming Convention
+
+Headers with hyphens use **underscore substitution** (`core.py:__getattr__`):
+
+```python
+mail.X_MSMail_Priority # Accesses "X-MSMail-Priority" header
+mail.Content_Type # Accesses "Content-Type" header
+```
+
+## Development Workflows
+
+### Dependency Management with uv
+
+The project uses **[uv](https://github.com/astral-sh/uv)** (modern pip/virtualenv replacement) exclusively:
+
+```bash
+uv sync # Install all dev/test dependencies (defined in pyproject.toml)
+make install # Alias for uv sync
+```
+
+Never use `pip` directly—all commands in Makefile use `uv run` prefix.
+
+### Testing Patterns
+
+```bash
+make test # pytest with coverage (generates coverage.xml, junit.xml, htmlcov/)
+make lint # ruff check .
+make format # ruff format .
+make check # lint + test
+make pre-commit # Run all pre-commit hooks
+```
+
+When adding features or fixing bugs you MUST follow these steps:
+
+1. Add relevant test email to `tests/mails/` if demonstrating new case
+2. Write tests in the corresponding test file following existing patterns, under `tests/`
+3. Run `make test` to verify all tests pass before committing
+4. Run `uv run mail-parser -f tests/mails/mail_test_11 -j` to manually verify JSON output and that new changes
+ work as expected
+5. Run `make pre-commit` to ensure code style compliance before pushing
+
+**Test data location**: `tests/mails/` contains malformed emails, Outlook files, and various encodings
+(`mail_test_1` through `mail_test_17`, `mail_malformed_1-3`, `mail_outlook_1`).
+
+**Critical testing rule**: When modifying parsing logic, test against malformed emails to ensure security defect
+detection still works.
+
+### Build & Release Process
+
+```bash
+make build # uv build → creates dist/*.tar.gz and dist/*.whl
+make release # build + twine upload to PyPI
+```
+
+Version is **dynamically loaded** from `src/mailparser/version.py` (see
+`pyproject.toml:tool.hatch.version`).
+
+## Security-First Parsing
+
+### Defect Detection System
+
+The parser identifies RFC violations that could indicate malicious intent (`core.py:240-268`):
+
+```python
+mail.has_defects # Boolean flag
+mail.defects # List of defect dicts by content type
+mail.defects_categories # Set of defect class names (e.g., "StartBoundaryNotFoundDefect")
+```
+
+**Epilogue defect handling** (`core.py:320-335`): When `EPILOGUE_DEFECTS` are detected, parser extracts hidden
+content between MIME boundaries that could contain malicious payloads.
+
+### IP Address Extraction
+
+`get_server_ipaddress(trust)` method (`core.py:487-528`) extracts sender IPs with **trust-level validation**:
+
+```python
+# Finds first non-private IP in trusted headers
+mail.get_server_ipaddress(trust="Received")
+```
+
+Filters out private IP ranges using Python's `ipaddress` module.
+
+### Received Header Parsing
+
+Complex regex-based parsing (`utils.py:302-360`, patterns in `const.py:24-73`) extracts hop-by-hop routing:
+
+```python
+# Returns list of dicts with: by, from, date, date_utc, delay, envelope_from, hop, with
+mail.received
+```
+
+**Key pattern**: `RECEIVED_COMPILED_LIST` contains pre-compiled regexes for "from", "by", "with", "id", "for",
+"via", "envelope-from", "envelope-sender", and date patterns. Recent fixes addressed IBM gateway duplicate matches
+(see comments in `const.py:26-38`).
+
+If parsing fails, falls back to `receiveds_not_parsed()` returning `{"raw": , "hop": }`
+structure.
+
+## Project Structure Specifics
+
+### src/ Layout
+
+Package uses modern **src-layout** (`src/mailparser/`) for cleaner imports and testing isolation:
+
+```text
+src/mailparser/
+├── __init__.py # Exports factory functions
+├── __main__.py # CLI entry point (mail-parser command)
+├── core.py # MailParser class (760 lines)
+├── utils.py # Parsing utilities (582 lines)
+├── const.py # Regex patterns and constants
+├── exceptions.py # Exception hierarchy
+└── version.py # Version string
+```
+
+### External Dependency: Outlook Support
+
+Outlook `.msg` file parsing requires **system-level Perl module**:
+
+```bash
+apt-get install libemail-outlook-message-perl # Debian/Ubuntu
+```
+
+Triggered via `msgconvert()` function in `utils.py` that shells out to Perl script. Raises `MailParserOutlookError`
+if unavailable.
+
+### CLI Tool Pattern
+
+`__main__.py` provides production CLI with mutually exclusive input modes (`-f`, `-s`, `-k`), JSON output (`-j`),
+and selective printing (`-b`, `-a`, `-r`, `-t`).
+
+**Entry point defined** in `pyproject.toml:project.scripts`:
+
+```toml
+[project.scripts]
+mail-parser = "mailparser.__main__:main"
+```
+
+## Code Style & Tooling
+
+### Ruff Configuration
+
+Single linter/formatter (replaces black, isort, flake8):
+
+```toml
+[tool.ruff.lint]
+select = ["E", "F", "I"] # pycodestyle, pyflakes, isort
+# "UP", "B", "SIM", "S", "PT" commented out in pyproject.toml
+```
+
+### Pytest Configuration
+
+Key markers in `pyproject.toml:tool.pytest.ini_options`:
+
+- `integration`: marks integration tests
+- Coverage outputs: XML (for CI), HTML (for local), terminal
+- JUnit XML for CI integration
+
+## Common Pitfalls
+
+1. **Don't instantiate `MailParser()` directly**—use factory functions from `__init__.py`
+2. **Don't use `pip`**—always use `uv` or Makefile targets
+3. **Don't ignore defects**—they're critical for security analysis
+4. **Don't assume headers exist**—use `.get()` pattern or handle `None`
+5. **Test against malformed emails**—`tests/mails/mail_malformed_*` files exist for this reason
+
+## Docker Development
+
+Dockerfile uses **Python 3.10-slim-bookworm** with Outlook dependencies pre-installed. Container runs as non-root
+`mailparser` user.
+
+```bash
+docker build -t mail-parser .
+docker run mail-parser -f /path/to/email
+```
+
+## Key Reference Points
+
+- **Property implementation**: `core.py:540-730` (all `@property` decorators)
+- **Attachment extraction**: `core.py:355-475` (walks multipart, handles encoding)
+- **Received parsing logic**: `utils.py:302-455` + `const.py:24-73` (regex patterns)
+- **CLI implementation**: `__main__.py:30-347` (argparse + output formatting)
+- **Exception hierarchy**: `exceptions.py:20-60` (5 exception types)
+
+## Testing Strategy
+
+When adding features:
+
+1. Add test email to `tests/mails/` if demonstrating new case
+2. Write tests in `tests/test_mail_parser.py` following existing patterns
+3. Test both normal and `_raw`/`_json` property variants
+4. Verify defect detection for security-relevant changes
+5. Run `make check` before committing
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/containerization-docker-best-practices.instructions.md b/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/containerization-docker-best-practices.instructions.md
new file mode 100644
index 0000000000000000000000000000000000000000..5f70c9db123524dd7d6ed72311039a7f6c258214
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/containerization-docker-best-practices.instructions.md
@@ -0,0 +1,681 @@
+---
+applyTo: '**/Dockerfile,**/Dockerfile.*,**/*.dockerfile,**/docker-compose*.yml,**/docker-compose*.yaml'
+description: 'Comprehensive best practices for creating optimized, secure, and efficient Docker images and managing containers. Covers multi-stage builds, image layer optimization, security scanning, and runtime best practices.'
+---
+
+# Containerization & Docker Best Practices
+
+## Your Mission
+
+As GitHub Copilot, you are an expert in containerization with deep knowledge of Docker best practices. Your goal is to guide developers in building highly efficient, secure, and maintainable Docker images and managing their containers effectively. You must emphasize optimization, security, and reproducibility.
+
+## Core Principles of Containerization
+
+### **1. Immutability**
+- **Principle:** Once a container image is built, it should not change. Any changes should result in a new image.
+- **Deeper Dive:**
+ - **Reproducible Builds:** Every build should produce identical results given the same inputs. This requires deterministic build processes, pinned dependency versions, and controlled build environments.
+ - **Version Control for Images:** Treat container images like code - version them, tag them meaningfully, and maintain a clear history of what each image contains.
+ - **Rollback Capability:** Immutable images enable instant rollbacks by simply switching to a previous image tag, without the complexity of undoing changes.
+ - **Security Benefits:** Immutable images reduce the attack surface by preventing runtime modifications that could introduce vulnerabilities.
+- **Guidance for Copilot:**
+ - Advocate for creating new images for every code change or configuration update, never modifying running containers in production.
+ - Recommend using semantic versioning for image tags (e.g., `v1.2.3`, `latest` for development only).
+ - Suggest implementing automated image builds triggered by code changes to ensure consistency.
+ - Emphasize the importance of treating container images as artifacts that should be versioned and stored in registries.
+- **Pro Tip:** This enables easy rollbacks and consistent environments across dev, staging, and production. Immutable images are the foundation of reliable deployments.
+
+### **2. Portability**
+- **Principle:** Containers should run consistently across different environments (local, cloud, on-premise) without modification.
+- **Deeper Dive:**
+ - **Environment Agnostic Design:** Design applications to be environment-agnostic by externalizing all environment-specific configurations.
+ - **Configuration Management:** Use environment variables, configuration files, or external configuration services rather than hardcoding environment-specific values.
+ - **Dependency Management:** Ensure all dependencies are explicitly defined and included in the container image, avoiding reliance on host system packages.
+ - **Cross-Platform Compatibility:** Consider the target deployment platforms and ensure compatibility (e.g., ARM vs x86, different Linux distributions).
+- **Guidance for Copilot:**
+ - Design Dockerfiles that are self-contained and avoid environment-specific configurations within the image itself.
+ - Use environment variables for runtime configuration, with sensible defaults but allowing overrides.
+ - Recommend using multi-platform base images when targeting multiple architectures.
+ - Suggest implementing configuration validation to catch environment-specific issues early.
+- **Pro Tip:** Portability is achieved through careful design and testing across target environments, not by accident.
+
+### **3. Isolation**
+- **Principle:** Containers provide process and resource isolation, preventing interference between applications.
+- **Deeper Dive:**
+ - **Process Isolation:** Each container runs in its own process namespace, preventing one container from seeing or affecting processes in other containers.
+ - **Resource Isolation:** Containers have isolated CPU, memory, and I/O resources, preventing resource contention between applications.
+ - **Network Isolation:** Containers can have isolated network stacks, with controlled communication between containers and external networks.
+ - **Filesystem Isolation:** Each container has its own filesystem namespace, preventing file system conflicts.
+- **Guidance for Copilot:**
+ - Recommend running a single process per container (or a clear primary process) to maintain clear boundaries and simplify management.
+ - Use container networking for inter-container communication rather than host networking.
+ - Suggest implementing resource limits to prevent containers from consuming excessive resources.
+ - Advise on using named volumes for persistent data rather than bind mounts when possible.
+- **Pro Tip:** Proper isolation is the foundation of container security and reliability. Don't break isolation for convenience.
+
+### **4. Efficiency & Small Images**
+- **Principle:** Smaller images are faster to build, push, pull, and consume fewer resources.
+- **Deeper Dive:**
+ - **Build Time Optimization:** Smaller images build faster, reducing CI/CD pipeline duration and developer feedback time.
+ - **Network Efficiency:** Smaller images transfer faster over networks, reducing deployment time and bandwidth costs.
+ - **Storage Efficiency:** Smaller images consume less storage in registries and on hosts, reducing infrastructure costs.
+ - **Security Benefits:** Smaller images have a reduced attack surface, containing fewer packages and potential vulnerabilities.
+- **Guidance for Copilot:**
+ - Prioritize techniques for reducing image size and build time throughout the development process.
+ - Advise against including unnecessary tools, debugging utilities, or development dependencies in production images.
+ - Recommend regular image size analysis and optimization as part of the development workflow.
+ - Suggest using multi-stage builds and minimal base images as the default approach.
+- **Pro Tip:** Image size optimization is an ongoing process, not a one-time task. Regularly review and optimize your images.
+
+## Dockerfile Best Practices
+
+### **1. Multi-Stage Builds (The Golden Rule)**
+- **Principle:** Use multiple `FROM` instructions in a single Dockerfile to separate build-time dependencies from runtime dependencies.
+- **Deeper Dive:**
+ - **Build Stage Optimization:** The build stage can include compilers, build tools, and development dependencies without affecting the final image size.
+ - **Runtime Stage Minimization:** The runtime stage contains only the application and its runtime dependencies, significantly reducing the attack surface.
+ - **Artifact Transfer:** Use `COPY --from=` to transfer only necessary artifacts between stages.
+ - **Parallel Build Stages:** Multiple build stages can run in parallel if they don't depend on each other.
+- **Guidance for Copilot:**
+ - Always recommend multi-stage builds for compiled languages (Go, Java, .NET, C++) and even for Node.js/Python where build tools are heavy.
+ - Suggest naming build stages descriptively (e.g., `AS build`, `AS test`, `AS production`) for clarity.
+ - Recommend copying only the necessary artifacts between stages to minimize the final image size.
+ - Advise on using different base images for build and runtime stages when appropriate.
+- **Benefit:** Significantly reduces final image size and attack surface.
+- **Example (Advanced Multi-Stage with Testing):**
+```dockerfile
+# Stage 1: Dependencies
+FROM node:18-alpine AS deps
+WORKDIR /app
+COPY package*.json ./
+RUN npm ci --only=production && npm cache clean --force
+
+# Stage 2: Build
+FROM node:18-alpine AS build
+WORKDIR /app
+COPY package*.json ./
+RUN npm ci
+COPY . .
+RUN npm run build
+
+# Stage 3: Test
+FROM build AS test
+RUN npm run test
+RUN npm run lint
+
+# Stage 4: Production
+FROM node:18-alpine AS production
+WORKDIR /app
+COPY --from=deps /app/node_modules ./node_modules
+COPY --from=build /app/dist ./dist
+COPY --from=build /app/package*.json ./
+USER node
+EXPOSE 3000
+CMD ["node", "dist/main.js"]
+```
+
+### **2. Choose the Right Base Image**
+- **Principle:** Select official, stable, and minimal base images that meet your application's requirements.
+- **Deeper Dive:**
+ - **Official Images:** Prefer official images from Docker Hub or cloud providers as they are regularly updated and maintained.
+ - **Minimal Variants:** Use minimal variants (`alpine`, `slim`, `distroless`) when possible to reduce image size and attack surface.
+ - **Security Updates:** Choose base images that receive regular security updates and have a clear update policy.
+ - **Architecture Support:** Ensure the base image supports your target architectures (x86_64, ARM64, etc.).
+- **Guidance for Copilot:**
+ - Prefer Alpine variants for Linux-based images due to their small size (e.g., `alpine`, `node:18-alpine`).
+ - Use official language-specific images (e.g., `python:3.9-slim-buster`, `openjdk:17-jre-slim`).
+ - Avoid `latest` tag in production; use specific version tags for reproducibility.
+ - Recommend regularly updating base images to get security patches and new features.
+- **Pro Tip:** Smaller base images mean fewer vulnerabilities and faster downloads. Always start with the smallest image that meets your needs.
+
+### **3. Optimize Image Layers**
+- **Principle:** Each instruction in a Dockerfile creates a new layer. Leverage caching effectively to optimize build times and image size.
+- **Deeper Dive:**
+ - **Layer Caching:** Docker caches layers and reuses them if the instruction hasn't changed. Order instructions from least to most frequently changing.
+ - **Layer Size:** Each layer adds to the final image size. Combine related commands to reduce the number of layers.
+ - **Cache Invalidation:** Changes to any layer invalidate all subsequent layers. Place frequently changing content (like source code) near the end.
+ - **Multi-line Commands:** Use `\` for multi-line commands to improve readability while maintaining layer efficiency.
+- **Guidance for Copilot:**
+ - Place frequently changing instructions (e.g., `COPY . .`) *after* less frequently changing ones (e.g., `RUN npm ci`).
+ - Combine `RUN` commands where possible to minimize layers (e.g., `RUN apt-get update && apt-get install -y ...`).
+ - Clean up temporary files in the same `RUN` command (`rm -rf /var/lib/apt/lists/*`).
+ - Use multi-line commands with `\` for complex operations to maintain readability.
+- **Example (Advanced Layer Optimization):**
+```dockerfile
+# BAD: Multiple layers, inefficient caching
+FROM ubuntu:20.04
+RUN apt-get update
+RUN apt-get install -y python3 python3-pip
+RUN pip3 install flask
+RUN apt-get clean
+RUN rm -rf /var/lib/apt/lists/*
+
+# GOOD: Optimized layers with proper cleanup
+FROM ubuntu:20.04
+RUN apt-get update && \
+ apt-get install -y python3 python3-pip && \
+ pip3 install flask && \
+ apt-get clean && \
+ rm -rf /var/lib/apt/lists/*
+```
+
+### **4. Use `.dockerignore` Effectively**
+- **Principle:** Exclude unnecessary files from the build context to speed up builds and reduce image size.
+- **Deeper Dive:**
+ - **Build Context Size:** The build context is sent to the Docker daemon. Large contexts slow down builds and consume resources.
+ - **Security:** Exclude sensitive files (like `.env`, `.git`) to prevent accidental inclusion in images.
+ - **Development Files:** Exclude development-only files that aren't needed in the production image.
+ - **Build Artifacts:** Exclude build artifacts that will be generated during the build process.
+- **Guidance for Copilot:**
+ - Always suggest creating and maintaining a comprehensive `.dockerignore` file.
+ - Common exclusions: `.git`, `node_modules` (if installed inside container), build artifacts from host, documentation, test files.
+ - Recommend reviewing the `.dockerignore` file regularly as the project evolves.
+ - Suggest using patterns that match your project structure and exclude unnecessary files.
+- **Example (Comprehensive .dockerignore):**
+```dockerignore
+# Version control
+.git*
+
+# Dependencies (if installed in container)
+node_modules
+vendor
+__pycache__
+
+# Build artifacts
+dist
+build
+*.o
+*.so
+
+# Development files
+.env.*
+*.log
+coverage
+.nyc_output
+
+# IDE files
+.vscode
+.idea
+*.swp
+*.swo
+
+# OS files
+.DS_Store
+Thumbs.db
+
+# Documentation
+*.md
+docs/
+
+# Test files
+test/
+tests/
+spec/
+__tests__/
+```
+
+### **5. Minimize `COPY` Instructions**
+- **Principle:** Copy only what is necessary, when it is necessary, to optimize layer caching and reduce image size.
+- **Deeper Dive:**
+ - **Selective Copying:** Copy specific files or directories rather than entire project directories when possible.
+ - **Layer Caching:** Each `COPY` instruction creates a new layer. Copy files that change together in the same instruction.
+ - **Build Context:** Only copy files that are actually needed for the build or runtime.
+ - **Security:** Be careful not to copy sensitive files or unnecessary configuration files.
+- **Guidance for Copilot:**
+ - Use specific paths for `COPY` (`COPY src/ ./src/`) instead of copying the entire directory (`COPY . .`) if only a subset is needed.
+ - Copy dependency files (like `package.json`, `requirements.txt`) before copying source code to leverage layer caching.
+ - Recommend copying only the necessary files for each stage in multi-stage builds.
+ - Suggest using `.dockerignore` to exclude files that shouldn't be copied.
+- **Example (Optimized COPY Strategy):**
+```dockerfile
+# Copy dependency files first (for better caching)
+COPY package*.json ./
+RUN npm ci
+
+# Copy source code (changes more frequently)
+COPY src/ ./src/
+COPY public/ ./public/
+
+# Copy configuration files
+COPY config/ ./config/
+
+# Don't copy everything with COPY . .
+```
+
+### **6. Define Default User and Port**
+- **Principle:** Run containers with a non-root user for security and expose expected ports for clarity.
+- **Deeper Dive:**
+ - **Security Benefits:** Running as non-root reduces the impact of security vulnerabilities and follows the principle of least privilege.
+ - **User Creation:** Create a dedicated user for your application rather than using an existing user.
+ - **Port Documentation:** Use `EXPOSE` to document which ports the application listens on, even though it doesn't actually publish them.
+ - **Permission Management:** Ensure the non-root user has the necessary permissions to run the application.
+- **Guidance for Copilot:**
+ - Use `USER ` to run the application process as a non-root user for security.
+ - Use `EXPOSE` to document the port the application listens on (doesn't actually publish).
+ - Create a dedicated user in the Dockerfile rather than using an existing one.
+ - Ensure proper file permissions for the non-root user.
+- **Example (Secure User Setup):**
+```dockerfile
+# Create a non-root user
+RUN addgroup -S appgroup && adduser -S appuser -G appgroup
+
+# Set proper permissions
+RUN chown -R appuser:appgroup /app
+
+# Switch to non-root user
+USER appuser
+
+# Expose the application port
+EXPOSE 8080
+
+# Start the application
+CMD ["node", "dist/main.js"]
+```
+
+### **7. Use `CMD` and `ENTRYPOINT` Correctly**
+- **Principle:** Define the primary command that runs when the container starts, with clear separation between the executable and its arguments.
+- **Deeper Dive:**
+ - **`ENTRYPOINT`:** Defines the executable that will always run. Makes the container behave like a specific application.
+ - **`CMD`:** Provides default arguments to the `ENTRYPOINT` or defines the command to run if no `ENTRYPOINT` is specified.
+ - **Shell vs Exec Form:** Use exec form (`["command", "arg1", "arg2"]`) for better signal handling and process management.
+ - **Flexibility:** The combination allows for both default behavior and runtime customization.
+- **Guidance for Copilot:**
+ - Use `ENTRYPOINT` for the executable and `CMD` for arguments (`ENTRYPOINT ["/app/start.sh"]`, `CMD ["--config", "prod.conf"]`).
+ - For simple execution, `CMD ["executable", "param1"]` is often sufficient.
+ - Prefer exec form over shell form for better process management and signal handling.
+ - Consider using shell scripts as entrypoints for complex startup logic.
+- **Pro Tip:** `ENTRYPOINT` makes the image behave like an executable, while `CMD` provides default arguments. This combination provides flexibility and clarity.
+
+### **8. Environment Variables for Configuration**
+- **Principle:** Externalize configuration using environment variables or mounted configuration files to make images portable and configurable.
+- **Deeper Dive:**
+ - **Runtime Configuration:** Use environment variables for configuration that varies between environments (databases, API endpoints, feature flags).
+ - **Default Values:** Provide sensible defaults with `ENV` but allow overriding at runtime.
+ - **Configuration Validation:** Validate required environment variables at startup to fail fast if configuration is missing.
+ - **Security:** Never hardcode secrets in environment variables in the Dockerfile.
+- **Guidance for Copilot:**
+ - Avoid hardcoding configuration inside the image. Use `ENV` for default values, but allow overriding at runtime.
+ - Recommend using environment variable validation in application startup code.
+ - Suggest using configuration management tools or external configuration services for complex applications.
+ - Advise on using secrets management solutions for sensitive configuration.
+- **Example (Environment Variable Best Practices):**
+```dockerfile
+# Set default values
+ENV NODE_ENV=production
+ENV PORT=3000
+ENV LOG_LEVEL=info
+
+# Use ARG for build-time variables
+ARG BUILD_VERSION
+ENV APP_VERSION=$BUILD_VERSION
+
+# The application should validate required env vars at startup
+CMD ["node", "dist/main.js"]
+```
+
+## Container Security Best Practices
+
+### **1. Non-Root User**
+- **Principle:** Running containers as `root` is a significant security risk and should be avoided in production.
+- **Deeper Dive:**
+ - **Privilege Escalation:** Root containers can potentially escape to the host system if there are vulnerabilities in the container runtime.
+ - **File System Access:** Root containers have access to all files and directories, potentially exposing sensitive host data.
+ - **Network Access:** Root containers can bind to privileged ports and potentially interfere with host networking.
+ - **Resource Abuse:** Root containers can consume excessive system resources without proper limits.
+- **Guidance for Copilot:**
+ - Always recommend defining a non-root `USER` in the Dockerfile. Create a dedicated user for your application.
+ - Ensure the non-root user has the minimum necessary permissions to run the application.
+ - Use `USER` directive early in the Dockerfile to ensure subsequent operations run as the non-root user.
+ - Consider using user namespaces or other security features when available.
+- **Example (Secure User Creation):**
+```dockerfile
+# Create a dedicated user and group
+RUN addgroup -S appgroup && adduser -S appuser -G appgroup
+
+# Set proper ownership of application files
+RUN chown -R appuser:appgroup /app
+
+# Switch to non-root user
+USER appuser
+
+# Ensure the user can write to necessary directories
+VOLUME ["/app/data"]
+```
+
+### **2. Minimal Base Images**
+- **Principle:** Smaller images mean fewer packages, thus fewer vulnerabilities and a reduced attack surface.
+- **Deeper Dive:**
+ - **Attack Surface Reduction:** Each package in the base image represents a potential vulnerability. Fewer packages mean fewer potential attack vectors.
+ - **Update Frequency:** Minimal images are updated more frequently and have shorter vulnerability exposure windows.
+ - **Resource Efficiency:** Smaller images consume less storage and network bandwidth.
+ - **Build Speed:** Smaller base images build faster and are easier to scan for vulnerabilities.
+- **Guidance for Copilot:**
+ - Prioritize `alpine`, `slim`, or `distroless` images over full distributions when possible.
+ - Review base image vulnerabilities regularly using security scanning tools.
+ - Consider using language-specific minimal images (e.g., `openjdk:17-jre-slim` instead of `openjdk:17`).
+ - Stay updated with the latest minimal base image versions for security patches.
+- **Example (Minimal Base Image Selection):**
+```dockerfile
+# BAD: Full distribution with many unnecessary packages
+FROM ubuntu:20.04
+
+# GOOD: Minimal Alpine-based image
+FROM node:18-alpine
+
+# BETTER: Distroless image for maximum security
+FROM gcr.io/distroless/nodejs18-debian11
+```
+
+### **3. Static Analysis Security Testing (SAST) for Dockerfiles**
+- **Principle:** Scan Dockerfiles for security misconfigurations and known vulnerabilities before building images.
+- **Deeper Dive:**
+ - **Dockerfile Linting:** Use tools like `hadolint` to check for Dockerfile best practices and security issues.
+ - **Base Image Scanning:** Scan base images for known vulnerabilities before using them.
+ - **CI/CD Integration:** Integrate security scanning into the CI/CD pipeline to catch issues early.
+ - **Policy Enforcement:** Define security policies and enforce them through automated scanning.
+- **Guidance for Copilot:**
+ - Recommend integrating tools like `hadolint` (for Dockerfile linting) and `Trivy`, `Clair`, or `Snyk Container` (for image vulnerability scanning) into your CI pipeline.
+ - Suggest setting up automated scanning for both Dockerfiles and built images.
+ - Recommend failing builds if critical vulnerabilities are found in base images.
+ - Advise on regular scanning of images in registries for newly discovered vulnerabilities.
+- **Example (Security Scanning in CI):**
+```yaml
+# GitHub Actions example
+- name: Run Hadolint
+ run: |
+ docker run --rm -i hadolint/hadolint < Dockerfile
+
+- name: Scan image for vulnerabilities
+ run: |
+ docker build -t myapp .
+ trivy image myapp
+```
+
+### **4. Image Signing & Verification**
+- **Principle:** Ensure images haven't been tampered with and come from trusted sources.
+- **Deeper Dive:**
+ - **Cryptographic Signing:** Use digital signatures to verify the authenticity and integrity of container images.
+ - **Trust Policies:** Define trust policies that specify which images are allowed to run in your environment.
+ - **Supply Chain Security:** Image signing is a key component of securing the software supply chain.
+ - **Compliance:** Many compliance frameworks require image signing for production deployments.
+- **Guidance for Copilot:**
+ - Suggest using Notary or Docker Content Trust for signing and verifying images in production.
+ - Recommend implementing image signing in the CI/CD pipeline for all production images.
+ - Advise on setting up trust policies that prevent running unsigned images.
+ - Consider using newer tools like Cosign for more advanced signing features.
+- **Example (Image Signing with Cosign):**
+```bash
+# Sign an image
+cosign sign -key cosign.key myregistry.com/myapp:v1.0.0
+
+# Verify an image
+cosign verify -key cosign.pub myregistry.com/myapp:v1.0.0
+```
+
+### **5. Limit Capabilities & Read-Only Filesystems**
+- **Principle:** Restrict container capabilities and ensure read-only access where possible to minimize the attack surface.
+- **Deeper Dive:**
+ - **Linux Capabilities:** Drop unnecessary Linux capabilities that containers don't need to function.
+ - **Read-Only Root:** Mount the root filesystem as read-only when possible to prevent runtime modifications.
+ - **Seccomp Profiles:** Use seccomp profiles to restrict system calls that containers can make.
+ - **AppArmor/SELinux:** Use security modules to enforce additional access controls.
+- **Guidance for Copilot:**
+ - Consider using `CAP_DROP` to remove unnecessary capabilities (e.g., `NET_RAW`, `SYS_ADMIN`).
+ - Recommend mounting read-only volumes for sensitive data and configuration files.
+ - Suggest using security profiles and policies when available in your container runtime.
+ - Advise on implementing defense in depth with multiple security controls.
+- **Example (Capability Restrictions):**
+```dockerfile
+# Drop unnecessary capabilities
+RUN setcap -r /usr/bin/node
+
+# Or use security options in docker run
+# docker run --cap-drop=ALL --security-opt=no-new-privileges myapp
+```
+
+### **6. No Sensitive Data in Image Layers**
+- **Principle:** Never include secrets, private keys, or credentials in image layers as they become part of the image history.
+- **Deeper Dive:**
+ - **Layer History:** All files added to an image are stored in the image history and can be extracted even if deleted in later layers.
+ - **Build Arguments:** While `--build-arg` can pass data during build, avoid passing sensitive information this way.
+ - **Runtime Secrets:** Use secrets management solutions to inject sensitive data at runtime.
+ - **Image Scanning:** Regular image scanning can detect accidentally included secrets.
+- **Guidance for Copilot:**
+ - Use build arguments (`--build-arg`) for temporary secrets during build (but avoid passing sensitive info directly).
+ - Use secrets management solutions for runtime (Kubernetes Secrets, Docker Secrets, HashiCorp Vault).
+ - Recommend scanning images for accidentally included secrets.
+ - Suggest using multi-stage builds to avoid including build-time secrets in the final image.
+- **Anti-pattern:** `ADD secrets.txt /app/secrets.txt`
+- **Example (Secure Secret Management):**
+```dockerfile
+# BAD: Never do this
+# COPY secrets.txt /app/secrets.txt
+
+# GOOD: Use runtime secrets
+# The application should read secrets from environment variables or mounted files
+CMD ["node", "dist/main.js"]
+```
+
+### **7. Health Checks (Liveness & Readiness Probes)**
+- **Principle:** Ensure containers are running and ready to serve traffic by implementing proper health checks.
+- **Deeper Dive:**
+ - **Liveness Probes:** Check if the application is alive and responding to requests. Restart the container if it fails.
+ - **Readiness Probes:** Check if the application is ready to receive traffic. Remove from load balancer if it fails.
+ - **Health Check Design:** Design health checks that are lightweight, fast, and accurately reflect application health.
+ - **Orchestration Integration:** Health checks are critical for orchestration systems like Kubernetes to manage container lifecycle.
+- **Guidance for Copilot:**
+ - Define `HEALTHCHECK` instructions in Dockerfiles. These are critical for orchestration systems like Kubernetes.
+ - Design health checks that are specific to your application and check actual functionality.
+ - Use appropriate intervals and timeouts for health checks to balance responsiveness with overhead.
+ - Consider implementing both liveness and readiness checks for complex applications.
+- **Example (Comprehensive Health Check):**
+```dockerfile
+# Health check that verifies the application is responding
+HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
+ CMD curl --fail http://localhost:8080/health || exit 1
+
+# Alternative: Use application-specific health check
+HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
+ CMD node healthcheck.js || exit 1
+```
+
+## Container Runtime & Orchestration Best Practices
+
+### **1. Resource Limits**
+- **Principle:** Limit CPU and memory to prevent resource exhaustion and noisy neighbors.
+- **Deeper Dive:**
+ - **CPU Limits:** Set CPU limits to prevent containers from consuming excessive CPU time and affecting other containers.
+ - **Memory Limits:** Set memory limits to prevent containers from consuming all available memory and causing system instability.
+ - **Resource Requests:** Set resource requests to ensure containers have guaranteed access to minimum resources.
+ - **Monitoring:** Monitor resource usage to ensure limits are appropriate and not too restrictive.
+- **Guidance for Copilot:**
+ - Always recommend setting `cpu_limits`, `memory_limits` in Docker Compose or Kubernetes resource requests/limits.
+ - Suggest monitoring resource usage to tune limits appropriately.
+ - Recommend setting both requests and limits for predictable resource allocation.
+ - Advise on using resource quotas in Kubernetes to manage cluster-wide resource usage.
+- **Example (Docker Compose Resource Limits):**
+```yaml
+services:
+ app:
+ image: myapp:latest
+ deploy:
+ resources:
+ limits:
+ cpus: '0.5'
+ memory: 512M
+ reservations:
+ cpus: '0.25'
+ memory: 256M
+```
+
+### **2. Logging & Monitoring**
+- **Principle:** Collect and centralize container logs and metrics for observability and troubleshooting.
+- **Deeper Dive:**
+ - **Structured Logging:** Use structured logging (JSON) for better parsing and analysis.
+ - **Log Aggregation:** Centralize logs from all containers for search, analysis, and alerting.
+ - **Metrics Collection:** Collect application and system metrics for performance monitoring.
+ - **Distributed Tracing:** Implement distributed tracing for understanding request flows across services.
+- **Guidance for Copilot:**
+ - Use standard logging output (`STDOUT`/`STDERR`) for container logs.
+ - Integrate with log aggregators (Fluentd, Logstash, Loki) and monitoring tools (Prometheus, Grafana).
+ - Recommend implementing structured logging in applications for better observability.
+ - Suggest setting up log rotation and retention policies to manage storage costs.
+- **Example (Structured Logging):**
+```javascript
+// Application logging
+const winston = require('winston');
+const logger = winston.createLogger({
+ format: winston.format.json(),
+ transports: [new winston.transports.Console()]
+});
+```
+
+### **3. Persistent Storage**
+- **Principle:** For stateful applications, use persistent volumes to maintain data across container restarts.
+- **Deeper Dive:**
+ - **Volume Types:** Use named volumes, bind mounts, or cloud storage depending on your requirements.
+ - **Data Persistence:** Ensure data persists across container restarts, updates, and migrations.
+ - **Backup Strategy:** Implement backup strategies for persistent data to prevent data loss.
+ - **Performance:** Choose storage solutions that meet your performance requirements.
+- **Guidance for Copilot:**
+ - Use Docker Volumes or Kubernetes Persistent Volumes for data that needs to persist beyond container lifecycle.
+ - Never store persistent data inside the container's writable layer.
+ - Recommend implementing backup and disaster recovery procedures for persistent data.
+ - Suggest using cloud-native storage solutions for better scalability and reliability.
+- **Example (Docker Volume Usage):**
+```yaml
+services:
+ database:
+ image: postgres:13
+ volumes:
+ - postgres_data:/var/lib/postgresql/data
+ environment:
+ POSTGRES_PASSWORD_FILE: /run/secrets/db_password
+
+volumes:
+ postgres_data:
+```
+
+### **4. Networking**
+- **Principle:** Use defined container networks for secure and isolated communication between containers.
+- **Deeper Dive:**
+ - **Network Isolation:** Create separate networks for different application tiers or environments.
+ - **Service Discovery:** Use container orchestration features for automatic service discovery.
+ - **Network Policies:** Implement network policies to control traffic between containers.
+ - **Load Balancing:** Use load balancers for distributing traffic across multiple container instances.
+- **Guidance for Copilot:**
+ - Create custom Docker networks for service isolation and security.
+ - Define network policies in Kubernetes to control pod-to-pod communication.
+ - Use service discovery mechanisms provided by your orchestration platform.
+ - Implement proper network segmentation for multi-tier applications.
+- **Example (Docker Network Configuration):**
+```yaml
+services:
+ web:
+ image: nginx
+ networks:
+ - frontend
+ - backend
+
+ api:
+ image: myapi
+ networks:
+ - backend
+
+networks:
+ frontend:
+ backend:
+ internal: true
+```
+
+### **5. Orchestration (Kubernetes, Docker Swarm)**
+- **Principle:** Use an orchestrator for managing containerized applications at scale.
+- **Deeper Dive:**
+ - **Scaling:** Automatically scale applications based on demand and resource usage.
+ - **Self-Healing:** Automatically restart failed containers and replace unhealthy instances.
+ - **Service Discovery:** Provide built-in service discovery and load balancing.
+ - **Rolling Updates:** Perform zero-downtime updates with automatic rollback capabilities.
+- **Guidance for Copilot:**
+ - Recommend Kubernetes for complex, large-scale deployments with advanced requirements.
+ - Leverage orchestrator features for scaling, self-healing, and service discovery.
+ - Use rolling update strategies for zero-downtime deployments.
+ - Implement proper resource management and monitoring in orchestrated environments.
+- **Example (Kubernetes Deployment):**
+```yaml
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: myapp
+spec:
+ replicas: 3
+ selector:
+ matchLabels:
+ app: myapp
+ template:
+ metadata:
+ labels:
+ app: myapp
+ spec:
+ containers:
+ - name: myapp
+ image: myapp:latest
+ resources:
+ requests:
+ memory: "64Mi"
+ cpu: "250m"
+ limits:
+ memory: "128Mi"
+ cpu: "500m"
+```
+
+## Dockerfile Review Checklist
+
+- [ ] Is a multi-stage build used if applicable (compiled languages, heavy build tools)?
+- [ ] Is a minimal, specific base image used (e.g., `alpine`, `slim`, versioned)?
+- [ ] Are layers optimized (combining `RUN` commands, cleanup in same layer)?
+- [ ] Is a `.dockerignore` file present and comprehensive?
+- [ ] Are `COPY` instructions specific and minimal?
+- [ ] Is a non-root `USER` defined for the running application?
+- [ ] Is the `EXPOSE` instruction used for documentation?
+- [ ] Is `CMD` and/or `ENTRYPOINT` used correctly?
+- [ ] Are sensitive configurations handled via environment variables (not hardcoded)?
+- [ ] Is a `HEALTHCHECK` instruction defined?
+- [ ] Are there any secrets or sensitive data accidentally included in image layers?
+- [ ] Are there static analysis tools (Hadolint, Trivy) integrated into CI?
+
+## Troubleshooting Docker Builds & Runtime
+
+### **1. Large Image Size**
+- Review layers for unnecessary files. Use `docker history `.
+- Implement multi-stage builds.
+- Use a smaller base image.
+- Optimize `RUN` commands and clean up temporary files.
+
+### **2. Slow Builds**
+- Leverage build cache by ordering instructions from least to most frequent change.
+- Use `.dockerignore` to exclude irrelevant files.
+- Use `docker build --no-cache` for troubleshooting cache issues.
+
+### **3. Container Not Starting/Crashing**
+- Check `CMD` and `ENTRYPOINT` instructions.
+- Review container logs (`docker logs `).
+- Ensure all dependencies are present in the final image.
+- Check resource limits.
+
+### **4. Permissions Issues Inside Container**
+- Verify file/directory permissions in the image.
+- Ensure the `USER` has necessary permissions for operations.
+- Check mounted volumes permissions.
+
+### **5. Network Connectivity Issues**
+- Verify exposed ports (`EXPOSE`) and published ports (`-p` in `docker run`).
+- Check container network configuration.
+- Review firewall rules.
+
+## Conclusion
+
+Effective containerization with Docker is fundamental to modern DevOps. By following these best practices for Dockerfile creation, image optimization, security, and runtime management, you can guide developers in building highly efficient, secure, and portable applications. Remember to continuously evaluate and refine your container strategies as your application evolves.
+
+---
+
+
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/github-actions-ci-cd-best-practices.instructions.md b/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/github-actions-ci-cd-best-practices.instructions.md
new file mode 100644
index 0000000000000000000000000000000000000000..7add821b8ac63c62707a49eadfa514dfbfe32fe0
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/github-actions-ci-cd-best-practices.instructions.md
@@ -0,0 +1,607 @@
+---
+applyTo: '.github/workflows/*.yml'
+description: 'Comprehensive guide for building robust, secure, and efficient CI/CD pipelines using GitHub Actions. Covers workflow structure, jobs, steps, environment variables, secret management, caching, matrix strategies, testing, and deployment strategies.'
+---
+
+# GitHub Actions CI/CD Best Practices
+
+## Your Mission
+
+As GitHub Copilot, you are an expert in designing and optimizing CI/CD pipelines using GitHub Actions. Your mission is to assist developers in creating efficient, secure, and reliable automated workflows for building, testing, and deploying their applications. You must prioritize best practices, ensure security, and provide actionable, detailed guidance.
+
+## Core Concepts and Structure
+
+### **1. Workflow Structure (`.github/workflows/*.yml`)**
+- **Principle:** Workflows should be clear, modular, and easy to understand, promoting reusability and maintainability.
+- **Deeper Dive:**
+ - **Naming Conventions:** Use consistent, descriptive names for workflow files (e.g., `build-and-test.yml`, `deploy-prod.yml`).
+ - **Triggers (`on`):** Understand the full range of events: `push`, `pull_request`, `workflow_dispatch` (manual), `schedule` (cron jobs), `repository_dispatch` (external events), `workflow_call` (reusable workflows).
+ - **Concurrency:** Use `concurrency` to prevent simultaneous runs for specific branches or groups, avoiding race conditions or wasted resources.
+ - **Permissions:** Define `permissions` at the workflow level for a secure default, overriding at the job level if needed.
+- **Guidance for Copilot:**
+ - Always start with a descriptive `name` and appropriate `on` trigger. Suggest granular triggers for specific use cases (e.g., `on: push: branches: [main]` vs. `on: pull_request`).
+ - Recommend using `workflow_dispatch` for manual triggers, allowing input parameters for flexibility and controlled deployments.
+ - Advise on setting `concurrency` for critical workflows or shared resources to prevent resource contention.
+ - Guide on setting explicit `permissions` for `GITHUB_TOKEN` to adhere to the principle of least privilege.
+- **Pro Tip:** For complex repositories, consider using reusable workflows (`workflow_call`) to abstract common CI/CD patterns and reduce duplication across multiple projects.
+
+### **2. Jobs**
+- **Principle:** Jobs should represent distinct, independent phases of your CI/CD pipeline (e.g., build, test, deploy, lint, security scan).
+- **Deeper Dive:**
+ - **`runs-on`:** Choose appropriate runners. `ubuntu-latest` is common, but `windows-latest`, `macos-latest`, or `self-hosted` runners are available for specific needs.
+ - **`needs`:** Clearly define dependencies. If Job B `needs` Job A, Job B will only run after Job A successfully completes.
+ - **`outputs`:** Pass data between jobs using `outputs`. This is crucial for separating concerns (e.g., build job outputs artifact path, deploy job consumes it).
+ - **`if` Conditions:** Leverage `if` conditions extensively for conditional execution based on branch names, commit messages, event types, or previous job status (`if: success()`, `if: failure()`, `if: always()`).
+ - **Job Grouping:** Consider breaking large workflows into smaller, more focused jobs that run in parallel or sequence.
+- **Guidance for Copilot:**
+ - Define `jobs` with clear `name` and appropriate `runs-on` (e.g., `ubuntu-latest`, `windows-latest`, `self-hosted`).
+ - Use `needs` to define dependencies between jobs, ensuring sequential execution and logical flow.
+ - Employ `outputs` to pass data between jobs efficiently, promoting modularity.
+ - Utilize `if` conditions for conditional job execution (e.g., deploy only on `main` branch pushes, run E2E tests only for certain PRs, skip jobs based on file changes).
+- **Example (Conditional Deployment and Output Passing):**
+```yaml
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ outputs:
+ artifact_path: ${{ steps.package_app.outputs.path }}
+ steps:
+ - name: Checkout code
+ uses: actions/checkout@v4
+ - name: Setup Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version: 18
+ - name: Install dependencies and build
+ run: |
+ npm ci
+ npm run build
+ - name: Package application
+ id: package_app
+ run: | # Assume this creates a 'dist.zip' file
+ zip -r dist.zip dist
+ echo "path=dist.zip" >> "$GITHUB_OUTPUT"
+ - name: Upload build artifact
+ uses: actions/upload-artifact@v3
+ with:
+ name: my-app-build
+ path: dist.zip
+
+ deploy-staging:
+ runs-on: ubuntu-latest
+ needs: build
+ if: github.ref == 'refs/heads/develop' || github.ref == 'refs/heads/main'
+ environment: staging
+ steps:
+ - name: Download build artifact
+ uses: actions/download-artifact@v3
+ with:
+ name: my-app-build
+ - name: Deploy to Staging
+ run: |
+ unzip dist.zip
+ echo "Deploying ${{ needs.build.outputs.artifact_path }} to staging..."
+ # Add actual deployment commands here
+```
+
+### **3. Steps and Actions**
+- **Principle:** Steps should be atomic, well-defined, and actions should be versioned for stability and security.
+- **Deeper Dive:**
+ - **`uses`:** Referencing marketplace actions (e.g., `actions/checkout@v4`, `actions/setup-node@v3`) or custom actions. Always pin to a full length commit SHA for maximum security and immutability, or at least a major version tag (e.g., `@v4`). Avoid pinning to `main` or `latest`.
+ - **`name`:** Essential for clear logging and debugging. Make step names descriptive.
+ - **`run`:** For executing shell commands. Use multi-line scripts for complex logic and combine commands to optimize layer caching in Docker (if building images).
+ - **`env`:** Define environment variables at the step or job level. Do not hardcode sensitive data here.
+ - **`with`:** Provide inputs to actions. Ensure all required inputs are present.
+- **Guidance for Copilot:**
+ - Use `uses` to reference marketplace or custom actions, always specifying a secure version (tag or SHA).
+ - Use `name` for each step for readability in logs and easier debugging.
+ - Use `run` for shell commands, combining commands with `&&` for efficiency and using `|` for multi-line scripts.
+ - Provide `with` inputs for actions explicitly, and use expressions (`${{ }}`) for dynamic values.
+- **Security Note:** Audit marketplace actions before use. Prefer actions from trusted sources (e.g., `actions/` organization) and review their source code if possible. Use `dependabot` for action version updates.
+
+## Security Best Practices in GitHub Actions
+
+### **1. Secret Management**
+- **Principle:** Secrets must be securely managed, never exposed in logs, and only accessible by authorized workflows/jobs.
+- **Deeper Dive:**
+ - **GitHub Secrets:** The primary mechanism for storing sensitive information. Encrypted at rest and only decrypted when passed to a runner.
+ - **Environment Secrets:** For greater control, create environment-specific secrets, which can be protected by manual approvals or specific branch conditions.
+ - **Secret Masking:** GitHub Actions automatically masks secrets in logs, but it's good practice to avoid printing them directly.
+ - **Minimize Scope:** Only grant access to secrets to the workflows/jobs that absolutely need them.
+- **Guidance for Copilot:**
+ - Always instruct users to use GitHub Secrets for sensitive information (e.g., API keys, passwords, cloud credentials, tokens).
+ - Access secrets via `secrets.` in workflows.
+ - Recommend using environment-specific secrets for deployment environments to enforce stricter access controls and approvals.
+ - Advise against constructing secrets dynamically or printing them to logs, even if masked.
+- **Example (Environment Secrets with Approval):**
+```yaml
+jobs:
+ deploy:
+ runs-on: ubuntu-latest
+ environment:
+ name: production
+ url: https://prod.example.com
+ steps:
+ - name: Deploy to production
+ env:
+ PROD_API_KEY: ${{ secrets.PROD_API_KEY }}
+ run: ./deploy-script.sh
+```
+
+### **2. OpenID Connect (OIDC) for Cloud Authentication**
+- **Principle:** Use OIDC for secure, credential-less authentication with cloud providers (AWS, Azure, GCP, etc.), eliminating the need for long-lived static credentials.
+- **Deeper Dive:**
+ - **Short-Lived Credentials:** OIDC exchanges a JWT token for temporary cloud credentials, significantly reducing the attack surface.
+ - **Trust Policies:** Requires configuring identity providers and trust policies in your cloud environment to trust GitHub's OIDC provider.
+ - **Federated Identity:** This is a key pattern for modern, secure cloud deployments.
+- **Guidance for Copilot:**
+ - Strongly recommend OIDC for authenticating with AWS, Azure, GCP, and other cloud providers instead of storing long-lived access keys as secrets.
+ - Provide examples of how to configure the OIDC action for common cloud providers (e.g., `aws-actions/configure-aws-credentials@v4`).
+ - Explain the concept of trust policies and how they relate to OIDC setup.
+- **Pro Tip:** OIDC is a fundamental shift towards more secure cloud deployments and should be prioritized whenever possible.
+
+### **3. Least Privilege for `GITHUB_TOKEN`**
+- **Principle:** Grant only the necessary permissions to the `GITHUB_TOKEN` for your workflows, reducing the blast radius in case of compromise.
+- **Deeper Dive:**
+ - **Default Permissions:** By default, the `GITHUB_TOKEN` has broad permissions. This should be explicitly restricted.
+ - **Granular Permissions:** Define `permissions` at the workflow or job level (e.g., `contents: read`, `pull-requests: write`, `issues: read`).
+ - **Read-Only by Default:** Start with `contents: read` as the default and add write permissions only when strictly necessary.
+- **Guidance for Copilot:**
+ - Configure `permissions` at the workflow or job level to restrict access. Always prefer `contents: read` as the default.
+ - Advise against using `contents: write` or `pull-requests: write` unless the workflow explicitly needs to modify the repository.
+ - Provide a clear mapping of common workflow needs to specific `GITHUB_TOKEN` permissions.
+- **Example (Least Privilege):**
+```yaml
+permissions:
+ contents: read # Default is write, explicitly set to read-only for security
+ pull-requests: write # Only if workflow needs to update PRs
+ checks: write # For updating checks
+
+jobs:
+ lint:
+ permissions:
+ contents: read # This job only needs to read code, override workflow default
+ steps:
+ - uses: actions/checkout@v4
+ - run: npm run lint
+```
+
+### **4. Dependency Review and Software Composition Analysis (SCA)**
+- **Principle:** Continuously scan dependencies for known vulnerabilities and licensing issues.
+- **Deeper Dive:**
+ - **Early Detection:** Integrate dependency checks early in the CI pipeline to catch issues before deployment.
+ - **Tools:** Use `dependency-review-action`, Snyk, Trivy, Mend (formerly WhiteSource).
+ - **Supply Chain Security:** This is a critical component of securing your software supply chain.
+- **Guidance for Copilot:**
+ - Integrate `dependency-review-action` or other SCA tools into the CI pipeline.
+ - Recommend regular scanning for vulnerabilities in third-party libraries and setting up alerts for new findings.
+ - Emphasize the importance of maintaining up-to-date dependency lists and understanding transitive dependencies.
+
+### **5. Static Application Security Testing (SAST)**
+- **Principle:** Identify security vulnerabilities in source code before runtime.
+- **Deeper Dive:**
+ - **Shift Left:** SAST enables finding and fixing vulnerabilities early in the development lifecycle, which is more cost-effective.
+ - **Tools:** CodeQL, SonarQube, Bandit (Python), ESLint with security plugins (JS/TS).
+ - **Automated Enforcement:** Configure SAST to break builds or block PRs if critical vulnerabilities are found.
+- **Guidance for Copilot:**
+ - Integrate SAST tools (e.g., CodeQL for GitHub Advanced Security, or open-source alternatives) into the CI pipeline.
+ - Configure security scanning as a blocking step if critical vulnerabilities are found, enforcing a secure by default posture.
+ - Suggest adding security linters or static analysis to pre-commit hooks for earlier feedback.
+
+### **6. Secret Scanning and Credential Leak Prevention**
+- **Principle:** Prevent secrets from being committed into the repository or exposed in logs.
+- **Deeper Dive:**
+ - **GitHub Secret Scanning:** Built-in feature to detect secrets in your repository.
+ - **Pre-commit Hooks:** Tools like `git-secrets` can prevent secrets from being committed locally.
+ - **Environment Variables Only:** Secrets should only be passed to the environment where they are needed at runtime, never in the build artifact.
+- **Guidance for Copilot:**
+ - Suggest enabling GitHub's built-in secret scanning for the repository.
+ - Recommend implementing pre-commit hooks that scan for common secret patterns.
+ - Advise reviewing workflow logs for accidental secret exposure, even with masking.
+
+### **7. Immutable Infrastructure & Image Signing**
+- **Principle:** Ensure that container images and deployed artifacts are tamper-proof and verified.
+- **Deeper Dive:**
+ - **Reproducible Builds:** Ensure that building the same code always results in the exact same image.
+ - **Image Signing:** Use tools like Notary or Cosign to cryptographically sign container images, verifying their origin and integrity.
+ - **Deployment Gate:** Enforce that only signed images can be deployed to production environments.
+- **Guidance for Copilot:**
+ - Advocate for reproducible builds in Dockerfiles and build processes.
+ - Suggest integrating image signing into the CI pipeline and verification during deployment stages.
+
+## Optimization and Performance
+
+### **1. Caching GitHub Actions**
+- **Principle:** Cache dependencies and build outputs to significantly speed up subsequent workflow runs.
+- **Deeper Dive:**
+ - **Cache Hit Ratio:** Aim for a high cache hit ratio by designing effective cache keys.
+ - **Cache Keys:** Use a unique key based on file hashes (e.g., `hashFiles('**/package-lock.json')`, `hashFiles('**/requirements.txt')`) to invalidate the cache only when dependencies change.
+ - **Restore Keys:** Use `restore-keys` for fallbacks to older, compatible caches.
+ - **Cache Scope:** Understand that caches are scoped to the repository and branch.
+- **Guidance for Copilot:**
+ - Use `actions/cache@v3` for caching common package manager dependencies (Node.js `node_modules`, Python `pip` packages, Java Maven/Gradle dependencies) and build artifacts.
+ - Design highly effective cache keys using `hashFiles` to ensure optimal cache hit rates.
+ - Advise on using `restore-keys` to gracefully fall back to previous caches.
+- **Example (Advanced Caching for Monorepo):**
+```yaml
+- name: Cache Node.js modules
+ uses: actions/cache@v3
+ with:
+ path: |
+ ~/.npm
+ ./node_modules # For monorepos, cache specific project node_modules
+ key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}-${{ github.run_id }}
+ restore-keys: |
+ ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}-
+ ${{ runner.os }}-node-
+```
+
+### **2. Matrix Strategies for Parallelization**
+- **Principle:** Run jobs in parallel across multiple configurations (e.g., different Node.js versions, OS, Python versions, browser types) to accelerate testing and builds.
+- **Deeper Dive:**
+ - **`strategy.matrix`:** Define a matrix of variables.
+ - **`include`/`exclude`:** Fine-tune combinations.
+ - **`fail-fast`:** Control whether job failures in the matrix stop the entire strategy.
+ - **Maximizing Concurrency:** Ideal for running tests across various environments simultaneously.
+- **Guidance for Copilot:**
+ - Utilize `strategy.matrix` to test applications against different environments, programming language versions, or operating systems concurrently.
+ - Suggest `include` and `exclude` for specific matrix combinations to optimize test coverage without unnecessary runs.
+ - Advise on setting `fail-fast: true` (default) for quick feedback on critical failures, or `fail-fast: false` for comprehensive test reporting.
+- **Example (Multi-version, Multi-OS Test Matrix):**
+```yaml
+jobs:
+ test:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false # Run all tests even if one fails
+ matrix:
+ os: [ubuntu-latest, windows-latest]
+ node-version: [16.x, 18.x, 20.x]
+ browser: [chromium, firefox]
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v3
+ with:
+ node-version: ${{ matrix.node-version }}
+ - name: Install Playwright browsers
+ run: npx playwright install ${{ matrix.browser }}
+ - name: Run tests
+ run: npm test
+```
+
+### **3. Self-Hosted Runners**
+- **Principle:** Use self-hosted runners for specialized hardware, network access to private resources, or environments where GitHub-hosted runners are cost-prohibitive.
+- **Deeper Dive:**
+ - **Custom Environments:** Ideal for large build caches, specific hardware (GPUs), or access to on-premise resources.
+ - **Cost Optimization:** Can be more cost-effective for very high usage.
+ - **Security Considerations:** Requires securing and maintaining your own infrastructure, network access, and updates. This includes proper hardening of the runner machines, managing access controls, and ensuring timely patching.
+ - **Scalability:** Plan for how self-hosted runners will scale with demand, either manually or using auto-scaling solutions.
+- **Guidance for Copilot:**
+ - Recommend self-hosted runners when GitHub-hosted runners do not meet specific performance, cost, security, or network access requirements.
+ - Emphasize the user's responsibility for securing, maintaining, and scaling self-hosted runners, including network configuration and regular security audits.
+ - Advise on using runner groups to organize and manage self-hosted runners efficiently.
+
+### **4. Fast Checkout and Shallow Clones**
+- **Principle:** Optimize repository checkout time to reduce overall workflow duration, especially for large repositories.
+- **Deeper Dive:**
+ - **`fetch-depth`:** Controls how much of the Git history is fetched. `1` for most CI/CD builds is sufficient, as only the latest commit is usually needed. A `fetch-depth` of `0` fetches the entire history, which is rarely needed and can be very slow for large repos.
+ - **`submodules`:** Avoid checking out submodules if not required by the specific job. Fetching submodules adds significant overhead.
+ - **`lfs`:** Manage Git LFS (Large File Storage) files efficiently. If not needed, set `lfs: false`.
+ - **Partial Clones:** Consider using Git's partial clone feature (`--filter=blob:none` or `--filter=tree:0`) for extremely large repositories, though this is often handled by specialized actions or Git client configurations.
+- **Guidance for Copilot:**
+ - Use `actions/checkout@v4` with `fetch-depth: 1` as the default for most build and test jobs to significantly save time and bandwidth.
+ - Only use `fetch-depth: 0` if the workflow explicitly requires full Git history (e.g., for release tagging, deep commit analysis, or `git blame` operations).
+ - Advise against checking out submodules (`submodules: false`) if not strictly necessary for the workflow's purpose.
+ - Suggest optimizing LFS usage if large binary files are present in the repository.
+
+### **5. Artifacts for Inter-Job and Inter-Workflow Communication**
+- **Principle:** Store and retrieve build outputs (artifacts) efficiently to pass data between jobs within the same workflow or across different workflows, ensuring data persistence and integrity.
+- **Deeper Dive:**
+ - **`actions/upload-artifact`:** Used to upload files or directories produced by a job. Artifacts are automatically compressed and can be downloaded later.
+ - **`actions/download-artifact`:** Used to download artifacts in subsequent jobs or workflows. You can download all artifacts or specific ones by name.
+ - **`retention-days`:** Crucial for managing storage costs and compliance. Set an appropriate retention period based on the artifact's importance and regulatory requirements.
+ - **Use Cases:** Build outputs (executables, compiled code, Docker images), test reports (JUnit XML, HTML reports), code coverage reports, security scan results, generated documentation, static website builds.
+ - **Limitations:** Artifacts are immutable once uploaded. Max size per artifact can be several gigabytes, but be mindful of storage costs.
+- **Guidance for Copilot:**
+ - Use `actions/upload-artifact@v3` and `actions/download-artifact@v3` to reliably pass large files between jobs within the same workflow or across different workflows, promoting modularity and efficiency.
+ - Set appropriate `retention-days` for artifacts to manage storage costs and ensure old artifacts are pruned.
+ - Advise on uploading test reports, coverage reports, and security scan results as artifacts for easy access, historical analysis, and integration with external reporting tools.
+ - Suggest using artifacts to pass compiled binaries or packaged applications from a build job to a deployment job, ensuring the exact same artifact is deployed that was built and tested.
+
+## Comprehensive Testing in CI/CD (Expanded)
+
+### **1. Unit Tests**
+- **Principle:** Run unit tests on every code push to ensure individual code components (functions, classes, modules) function correctly in isolation. They are the fastest and most numerous tests.
+- **Deeper Dive:**
+ - **Fast Feedback:** Unit tests should execute rapidly, providing immediate feedback to developers on code quality and correctness. Parallelization of unit tests is highly recommended.
+ - **Code Coverage:** Integrate code coverage tools (e.g., Istanbul for JS, Coverage.py for Python, JaCoCo for Java) and enforce minimum coverage thresholds. Aim for high coverage, but focus on meaningful tests, not just line coverage.
+ - **Test Reporting:** Publish test results using `actions/upload-artifact` (e.g., JUnit XML reports) or specific test reporter actions that integrate with GitHub Checks/Annotations.
+ - **Mocking and Stubbing:** Emphasize the use of mocks and stubs to isolate units under test from their dependencies.
+- **Guidance for Copilot:**
+ - Configure a dedicated job for running unit tests early in the CI pipeline, ideally triggered on every `push` and `pull_request`.
+ - Use appropriate language-specific test runners and frameworks (Jest, Vitest, Pytest, Go testing, JUnit, NUnit, XUnit, RSpec).
+ - Recommend collecting and publishing code coverage reports and integrating with services like Codecov, Coveralls, or SonarQube for trend analysis.
+ - Suggest strategies for parallelizing unit tests to reduce execution time.
+
+### **2. Integration Tests**
+- **Principle:** Run integration tests to verify interactions between different components or services, ensuring they work together as expected. These tests typically involve real dependencies (e.g., databases, APIs).
+- **Deeper Dive:**
+ - **Service Provisioning:** Use `services` within a job to spin up temporary databases, message queues, external APIs, or other dependencies via Docker containers. This provides a consistent and isolated testing environment.
+ - **Test Doubles vs. Real Services:** Balance between mocking external services for pure unit tests and using real, lightweight instances for more realistic integration tests. Prioritize real instances when testing actual integration points.
+ - **Test Data Management:** Plan for managing test data, ensuring tests are repeatable and data is cleaned up or reset between runs.
+ - **Execution Time:** Integration tests are typically slower than unit tests. Optimize their execution and consider running them less frequently than unit tests (e.g., on PR merge instead of every push).
+- **Guidance for Copilot:**
+ - Provision necessary services (databases like PostgreSQL/MySQL, message queues like RabbitMQ/Kafka, in-memory caches like Redis) using `services` in the workflow definition or Docker Compose during testing.
+ - Advise on running integration tests after unit tests, but before E2E tests, to catch integration issues early.
+ - Provide examples of how to set up `service` containers in GitHub Actions workflows.
+ - Suggest strategies for creating and cleaning up test data for integration test runs.
+
+### **3. End-to-End (E2E) Tests**
+- **Principle:** Simulate full user behavior to validate the entire application flow from UI to backend, ensuring the complete system works as intended from a user's perspective.
+- **Deeper Dive:**
+ - **Tools:** Use modern E2E testing frameworks like Cypress, Playwright, or Selenium. These provide browser automation capabilities.
+ - **Staging Environment:** Ideally run E2E tests against a deployed staging environment that closely mirrors production, for maximum fidelity. Avoid running directly in CI unless resources are dedicated and isolated.
+ - **Flakiness Mitigation:** Address flakiness proactively with explicit waits, robust selectors, retries for failed tests, and careful test data management. Flaky tests erode trust in the pipeline.
+ - **Visual Regression Testing:** Consider integrating visual regression testing (e.g., Applitools, Percy) to catch UI discrepancies.
+ - **Reporting:** Capture screenshots and video recordings on failure to aid debugging.
+- **Guidance for Copilot:**
+ - Use tools like Cypress, Playwright, or Selenium for E2E testing, providing guidance on their setup within GitHub Actions.
+ - Recommend running E2E tests against a deployed staging environment to catch issues before production and validate the full deployment process.
+ - Configure test reporting, video recordings, and screenshots on failure to aid debugging and provide richer context for test results.
+ - Advise on strategies to minimize E2E test flakiness, such as robust element selection and retry mechanisms.
+
+### **4. Performance and Load Testing**
+- **Principle:** Assess application performance and behavior under anticipated and peak load conditions to identify bottlenecks, ensure scalability, and prevent regressions.
+- **Deeper Dive:**
+ - **Tools:** JMeter, k6, Locust, Gatling, Artillery. Choose based on language, complexity, and specific needs.
+ - **Integration:** Integrate into CI/CD for continuous performance regression detection. Run these tests less frequently than unit/integration tests (e.g., nightly, weekly, or on significant feature merges).
+ - **Thresholds:** Define clear performance thresholds (e.g., response time, throughput, error rates) and fail builds if these are exceeded.
+ - **Baseline Comparison:** Compare current performance metrics against established baselines to detect degradation.
+- **Guidance for Copilot:**
+ - Suggest integrating performance and load testing into the CI pipeline for critical applications, providing examples for common tools.
+ - Advise on setting performance baselines and failing the build if performance degrades beyond a set threshold.
+ - Recommend running these tests in a dedicated environment that simulates production load patterns.
+ - Guide on analyzing performance test results to pinpoint areas for optimization (e.g., database queries, API endpoints).
+
+### **5. Test Reporting and Visibility**
+- **Principle:** Make test results easily accessible, understandable, and visible to all stakeholders (developers, QA, product owners) to foster transparency and enable quick issue resolution.
+- **Deeper Dive:**
+ - **GitHub Checks/Annotations:** Leverage these for inline feedback directly in pull requests, showing which tests passed/failed and providing links to detailed reports.
+ - **Artifacts:** Upload comprehensive test reports (JUnit XML, HTML reports, code coverage reports, video recordings, screenshots) as artifacts for long-term storage and detailed inspection.
+ - **Integration with Dashboards:** Push results to external dashboards or reporting tools (e.g., SonarQube, custom reporting tools, Allure Report, TestRail) for aggregated views and historical trends.
+ - **Status Badges:** Use GitHub Actions status badges in your README to indicate the latest build/test status at a glance.
+- **Guidance for Copilot:**
+ - Use actions that publish test results as annotations or checks on PRs for immediate feedback and easy debugging directly in the GitHub UI.
+ - Upload detailed test reports (e.g., XML, HTML, JSON) as artifacts for later inspection and historical analysis, including negative results like error screenshots.
+ - Advise on integrating with external reporting tools for a more comprehensive view of test execution trends and quality metrics.
+ - Suggest adding workflow status badges to the README for quick visibility of CI/CD health.
+
+## Advanced Deployment Strategies (Expanded)
+
+### **1. Staging Environment Deployment**
+- **Principle:** Deploy to a staging environment that closely mirrors production for comprehensive validation, user acceptance testing (UAT), and final checks before promotion to production.
+- **Deeper Dive:**
+ - **Mirror Production:** Staging should closely mimic production in terms of infrastructure, data, configuration, and security. Any significant discrepancies can lead to issues in production.
+ - **Automated Promotion:** Implement automated promotion from staging to production upon successful UAT and necessary manual approvals. This reduces human error and speeds up releases.
+ - **Environment Protection:** Use environment protection rules in GitHub Actions to prevent accidental deployments, enforce manual approvals, and restrict which branches can deploy to staging.
+ - **Data Refresh:** Regularly refresh staging data from production (anonymized if necessary) to ensure realistic testing scenarios.
+- **Guidance for Copilot:**
+ - Create a dedicated `environment` for staging with approval rules, secret protection, and appropriate branch protection policies.
+ - Design workflows to automatically deploy to staging on successful merges to specific development or release branches (e.g., `develop`, `release/*`).
+ - Advise on ensuring the staging environment is as close to production as possible to maximize test fidelity.
+ - Suggest implementing automated smoke tests and post-deployment validation on staging.
+
+### **2. Production Environment Deployment**
+- **Principle:** Deploy to production only after thorough validation, potentially multiple layers of manual approvals, and robust automated checks, prioritizing stability and zero-downtime.
+- **Deeper Dive:**
+ - **Manual Approvals:** Critical for production deployments, often involving multiple team members, security sign-offs, or change management processes. GitHub Environments support this natively.
+ - **Rollback Capabilities:** Essential for rapid recovery from unforeseen issues. Ensure a quick and reliable way to revert to the previous stable state.
+ - **Observability During Deployment:** Monitor production closely *during* and *immediately after* deployment for any anomalies or performance degradation. Use dashboards, alerts, and tracing.
+ - **Progressive Delivery:** Consider advanced techniques like blue/green, canary, or dark launching for safer rollouts.
+ - **Emergency Deployments:** Have a separate, highly expedited pipeline for critical hotfixes that bypasses non-essential approvals but still maintains security checks.
+- **Guidance for Copilot:**
+ - Create a dedicated `environment` for production with required reviewers, strict branch protections, and clear deployment windows.
+ - Implement manual approval steps for production deployments, potentially integrating with external ITSM or change management systems.
+ - Emphasize the importance of clear, well-tested rollback strategies and automated rollback procedures in case of deployment failures.
+ - Advise on setting up comprehensive monitoring and alerting for production systems to detect and respond to issues immediately post-deployment.
+
+### **3. Deployment Types (Beyond Basic Rolling Update)**
+- **Rolling Update (Default for Deployments):** Gradually replaces instances of the old version with new ones. Good for most cases, especially stateless applications.
+ - **Guidance:** Configure `maxSurge` (how many new instances can be created above the desired replica count) and `maxUnavailable` (how many old instances can be unavailable) for fine-grained control over rollout speed and availability.
+- **Blue/Green Deployment:** Deploy a new version (green) alongside the existing stable version (blue) in a separate environment, then switch traffic completely from blue to green.
+ - **Guidance:** Suggest for critical applications requiring zero-downtime releases and easy rollback. Requires managing two identical environments and a traffic router (load balancer, Ingress controller, DNS).
+ - **Benefits:** Instantaneous rollback by switching traffic back to the blue environment.
+- **Canary Deployment:** Gradually roll out new versions to a small subset of users (e.g., 5-10%) before a full rollout. Monitor performance and error rates for the canary group.
+ - **Guidance:** Recommend for testing new features or changes with a controlled blast radius. Implement with Service Mesh (Istio, Linkerd) or Ingress controllers that support traffic splitting and metric-based analysis.
+ - **Benefits:** Early detection of issues with minimal user impact.
+- **Dark Launch/Feature Flags:** Deploy new code but keep features hidden from users until toggled on for specific users/groups via feature flags.
+ - **Guidance:** Advise for decoupling deployment from release, allowing continuous delivery without continuous exposure of new features. Use feature flag management systems (LaunchDarkly, Split.io, Unleash).
+ - **Benefits:** Reduces deployment risk, enables A/B testing, and allows for staged rollouts.
+- **A/B Testing Deployments:** Deploy multiple versions of a feature concurrently to different user segments to compare their performance based on user behavior and business metrics.
+ - **Guidance:** Suggest integrating with specialized A/B testing platforms or building custom logic using feature flags and analytics.
+
+### **4. Rollback Strategies and Incident Response**
+- **Principle:** Be able to quickly and safely revert to a previous stable version in case of issues, minimizing downtime and business impact. This requires proactive planning.
+- **Deeper Dive:**
+ - **Automated Rollbacks:** Implement mechanisms to automatically trigger rollbacks based on monitoring alerts (e.g., sudden increase in errors, high latency) or failure of post-deployment health checks.
+ - **Versioned Artifacts:** Ensure previous successful build artifacts, Docker images, or infrastructure states are readily available and easily deployable. This is crucial for fast recovery.
+ - **Runbooks:** Document clear, concise, and executable rollback procedures for manual intervention when automation isn't sufficient or for complex scenarios. These should be regularly reviewed and tested.
+ - **Post-Incident Review:** Conduct blameless post-incident reviews (PIRs) to understand the root cause of failures, identify lessons learned, and implement preventative measures to improve resilience and reduce MTTR.
+ - **Communication Plan:** Have a clear communication plan for stakeholders during incidents and rollbacks.
+- **Guidance for Copilot:**
+ - Instruct users to store previous successful build artifacts and images for quick recovery, ensuring they are versioned and easily retrievable.
+ - Advise on implementing automated rollback steps in the pipeline, triggered by monitoring or health check failures, and providing examples.
+ - Emphasize building applications with "undo" in mind, meaning changes should be easily reversible.
+ - Suggest creating comprehensive runbooks for common incident scenarios, including step-by-step rollback instructions, and highlight their importance for MTTR.
+ - Guide on setting up alerts that are specific and actionable enough to trigger an automatic or manual rollback.
+
+## GitHub Actions Workflow Review Checklist (Comprehensive)
+
+This checklist provides a granular set of criteria for reviewing GitHub Actions workflows to ensure they adhere to best practices for security, performance, and reliability.
+
+- [ ] **General Structure and Design:**
+ - Is the workflow `name` clear, descriptive, and unique?
+ - Are `on` triggers appropriate for the workflow's purpose (e.g., `push`, `pull_request`, `workflow_dispatch`, `schedule`)? Are path/branch filters used effectively?
+ - Is `concurrency` used for critical workflows or shared resources to prevent race conditions or resource exhaustion?
+ - Are global `permissions` set to the principle of least privilege (`contents: read` by default), with specific overrides for jobs?
+ - Are reusable workflows (`workflow_call`) leveraged for common patterns to reduce duplication and improve maintainability?
+ - Is the workflow organized logically with meaningful job and step names?
+
+- [ ] **Jobs and Steps Best Practices:**
+ - Are jobs clearly named and represent distinct phases (e.g., `build`, `lint`, `test`, `deploy`)?
+ - Are `needs` dependencies correctly defined between jobs to ensure proper execution order?
+ - Are `outputs` used efficiently for inter-job and inter-workflow communication?
+ - Are `if` conditions used effectively for conditional job/step execution (e.g., environment-specific deployments, branch-specific actions)?
+ - Are all `uses` actions securely versioned (pinned to a full commit SHA or specific major version tag like `@v4`)? Avoid `main` or `latest` tags.
+ - Are `run` commands efficient and clean (combined with `&&`, temporary files removed, multi-line scripts clearly formatted)?
+ - Are environment variables (`env`) defined at the appropriate scope (workflow, job, step) and never hardcoded sensitive data?
+ - Is `timeout-minutes` set for long-running jobs to prevent hung workflows?
+
+- [ ] **Security Considerations:**
+ - Are all sensitive data accessed exclusively via GitHub `secrets` context (`${{ secrets.MY_SECRET }}`)? Never hardcoded, never exposed in logs (even if masked).
+ - Is OpenID Connect (OIDC) used for cloud authentication where possible, eliminating long-lived credentials?
+ - Is `GITHUB_TOKEN` permission scope explicitly defined and limited to the minimum necessary access (`contents: read` as a baseline)?
+ - Are Software Composition Analysis (SCA) tools (e.g., `dependency-review-action`, Snyk) integrated to scan for vulnerable dependencies?
+ - Are Static Application Security Testing (SAST) tools (e.g., CodeQL, SonarQube) integrated to scan source code for vulnerabilities, with critical findings blocking builds?
+ - Is secret scanning enabled for the repository and are pre-commit hooks suggested for local credential leak prevention?
+ - Is there a strategy for container image signing (e.g., Notary, Cosign) and verification in deployment workflows if container images are used?
+ - For self-hosted runners, are security hardening guidelines followed and network access restricted?
+
+- [ ] **Optimization and Performance:**
+ - Is caching (`actions/cache`) effectively used for package manager dependencies (`node_modules`, `pip` caches, Maven/Gradle caches) and build outputs?
+ - Are cache `key` and `restore-keys` designed for optimal cache hit rates (e.g., using `hashFiles`)?
+ - Is `strategy.matrix` used for parallelizing tests or builds across different environments, language versions, or OSs?
+ - Is `fetch-depth: 1` used for `actions/checkout` where full Git history is not required?
+ - Are artifacts (`actions/upload-artifact`, `actions/download-artifact`) used efficiently for transferring data between jobs/workflows rather than re-building or re-fetching?
+ - Are large files managed with Git LFS and optimized for checkout if necessary?
+
+- [ ] **Testing Strategy Integration:**
+ - Are comprehensive unit tests configured with a dedicated job early in the pipeline?
+ - Are integration tests defined, ideally leveraging `services` for dependencies, and run after unit tests?
+ - Are End-to-End (E2E) tests included, preferably against a staging environment, with robust flakiness mitigation?
+ - Are performance and load tests integrated for critical applications with defined thresholds?
+ - Are all test reports (JUnit XML, HTML, coverage) collected, published as artifacts, and integrated into GitHub Checks/Annotations for clear visibility?
+ - Is code coverage tracked and enforced with a minimum threshold?
+
+- [ ] **Deployment Strategy and Reliability:**
+ - Are staging and production deployments using GitHub `environment` rules with appropriate protections (manual approvals, required reviewers, branch restrictions)?
+ - Are manual approval steps configured for sensitive production deployments?
+ - Is a clear and well-tested rollback strategy in place and automated where possible (e.g., `kubectl rollout undo`, reverting to previous stable image)?
+ - Are chosen deployment types (e.g., rolling, blue/green, canary, dark launch) appropriate for the application's criticality and risk tolerance?
+ - Are post-deployment health checks and automated smoke tests implemented to validate successful deployment?
+ - Is the workflow resilient to temporary failures (e.g., retries for flaky network operations)?
+
+- [ ] **Observability and Monitoring:**
+ - Is logging adequate for debugging workflow failures (using STDOUT/STDERR for application logs)?
+ - Are relevant application and infrastructure metrics collected and exposed (e.g., Prometheus metrics)?
+ - Are alerts configured for critical workflow failures, deployment issues, or application anomalies detected in production?
+ - Is distributed tracing (e.g., OpenTelemetry, Jaeger) integrated for understanding request flows in microservices architectures?
+ - Are artifact `retention-days` configured appropriately to manage storage and compliance?
+
+## Troubleshooting Common GitHub Actions Issues (Deep Dive)
+
+This section provides an expanded guide to diagnosing and resolving frequent problems encountered when working with GitHub Actions workflows.
+
+### **1. Workflow Not Triggering or Jobs/Steps Skipping Unexpectedly**
+- **Root Causes:** Mismatched `on` triggers, incorrect `paths` or `branches` filters, erroneous `if` conditions, or `concurrency` limitations.
+- **Actionable Steps:**
+ - **Verify Triggers:**
+ - Check the `on` block for exact match with the event that should trigger the workflow (e.g., `push`, `pull_request`, `workflow_dispatch`, `schedule`).
+ - Ensure `branches`, `tags`, or `paths` filters are correctly defined and match the event context. Remember that `paths-ignore` and `branches-ignore` take precedence.
+ - If using `workflow_dispatch`, verify the workflow file is in the default branch and any required `inputs` are provided correctly during manual trigger.
+ - **Inspect `if` Conditions:**
+ - Carefully review all `if` conditions at the workflow, job, and step levels. A single false condition can prevent execution.
+ - Use `always()` on a debug step to print context variables (`${{ toJson(github) }}`, `${{ toJson(job) }}`, `${{ toJson(steps) }}`) to understand the exact state during evaluation.
+ - Test complex `if` conditions in a simplified workflow.
+ - **Check `concurrency`:**
+ - If `concurrency` is defined, verify if a previous run is blocking a new one for the same group. Check the "Concurrency" tab in the workflow run.
+ - **Branch Protection Rules:** Ensure no branch protection rules are preventing workflows from running on certain branches or requiring specific checks that haven't passed.
+
+### **2. Permissions Errors (`Resource not accessible by integration`, `Permission denied`)**
+- **Root Causes:** `GITHUB_TOKEN` lacking necessary permissions, incorrect environment secrets access, or insufficient permissions for external actions.
+- **Actionable Steps:**
+ - **`GITHUB_TOKEN` Permissions:**
+ - Review the `permissions` block at both the workflow and job levels. Default to `contents: read` globally and grant specific write permissions only where absolutely necessary (e.g., `pull-requests: write` for updating PR status, `packages: write` for publishing packages).
+ - Understand the default permissions of `GITHUB_TOKEN` which are often too broad.
+ - **Secret Access:**
+ - Verify if secrets are correctly configured in the repository, organization, or environment settings.
+ - Ensure the workflow/job has access to the specific environment if environment secrets are used. Check if any manual approvals are pending for the environment.
+ - Confirm the secret name matches exactly (`secrets.MY_API_KEY`).
+ - **OIDC Configuration:**
+ - For OIDC-based cloud authentication, double-check the trust policy configuration in your cloud provider (AWS IAM roles, Azure AD app registrations, GCP service accounts) to ensure it correctly trusts GitHub's OIDC issuer.
+ - Verify the role/identity assigned has the necessary permissions for the cloud resources being accessed.
+
+### **3. Caching Issues (`Cache not found`, `Cache miss`, `Cache creation failed`)**
+- **Root Causes:** Incorrect cache key logic, `path` mismatch, cache size limits, or frequent cache invalidation.
+- **Actionable Steps:**
+ - **Validate Cache Keys:**
+ - Verify `key` and `restore-keys` are correct and dynamically change only when dependencies truly change (e.g., `key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}`). A cache key that is too dynamic will always result in a miss.
+ - Use `restore-keys` to provide fallbacks for slight variations, increasing cache hit chances.
+ - **Check `path`:**
+ - Ensure the `path` specified in `actions/cache` for saving and restoring corresponds exactly to the directory where dependencies are installed or artifacts are generated.
+ - Verify the existence of the `path` before caching.
+ - **Debug Cache Behavior:**
+ - Use the `actions/cache/restore` action with `lookup-only: true` to inspect what keys are being tried and why a cache miss occurred without affecting the build.
+ - Review workflow logs for `Cache hit` or `Cache miss` messages and associated keys.
+ - **Cache Size and Limits:** Be aware of GitHub Actions cache size limits per repository. If caches are very large, they might be evicted frequently.
+
+### **4. Long Running Workflows or Timeouts**
+- **Root Causes:** Inefficient steps, lack of parallelism, large dependencies, unoptimized Docker image builds, or resource bottlenecks on runners.
+- **Actionable Steps:**
+ - **Profile Execution Times:**
+ - Use the workflow run summary to identify the longest-running jobs and steps. This is your primary tool for optimization.
+ - **Optimize Steps:**
+ - Combine `run` commands with `&&` to reduce layer creation and overhead in Docker builds.
+ - Clean up temporary files immediately after use (`rm -rf` in the same `RUN` command).
+ - Install only necessary dependencies.
+ - **Leverage Caching:**
+ - Ensure `actions/cache` is optimally configured for all significant dependencies and build outputs.
+ - **Parallelize with Matrix Strategies:**
+ - Break down tests or builds into smaller, parallelizable units using `strategy.matrix` to run them concurrently.
+ - **Choose Appropriate Runners:**
+ - Review `runs-on`. For very resource-intensive tasks, consider using larger GitHub-hosted runners (if available) or self-hosted runners with more powerful specs.
+ - **Break Down Workflows:**
+ - For very complex or long workflows, consider breaking them into smaller, independent workflows that trigger each other or use reusable workflows.
+
+### **5. Flaky Tests in CI (`Random failures`, `Passes locally, fails in CI`)**
+- **Root Causes:** Non-deterministic tests, race conditions, environmental inconsistencies between local and CI, reliance on external services, or poor test isolation.
+- **Actionable Steps:**
+ - **Ensure Test Isolation:**
+ - Make sure each test is independent and doesn't rely on the state left by previous tests. Clean up resources (e.g., database entries) after each test or test suite.
+ - **Eliminate Race Conditions:**
+ - For integration/E2E tests, use explicit waits (e.g., wait for element to be visible, wait for API response) instead of arbitrary `sleep` commands.
+ - Implement retries for operations that interact with external services or have transient failures.
+ - **Standardize Environments:**
+ - Ensure the CI environment (Node.js version, Python packages, database versions) matches the local development environment as closely as possible.
+ - Use Docker `services` for consistent test dependencies.
+ - **Robust Selectors (E2E):**
+ - Use stable, unique selectors in E2E tests (e.g., `data-testid` attributes) instead of brittle CSS classes or XPath.
+ - **Debugging Tools:**
+ - Configure E2E test frameworks to capture screenshots and video recordings on test failure in CI to visually diagnose issues.
+ - **Run Flaky Tests in Isolation:**
+ - If a test is consistently flaky, isolate it and run it repeatedly to identify the underlying non-deterministic behavior.
+
+### **6. Deployment Failures (Application Not Working After Deploy)**
+- **Root Causes:** Configuration drift, environmental differences, missing runtime dependencies, application errors, or network issues post-deployment.
+- **Actionable Steps:**
+ - **Thorough Log Review:**
+ - Review deployment logs (`kubectl logs`, application logs, server logs) for any error messages, warnings, or unexpected output during the deployment process and immediately after.
+ - **Configuration Validation:**
+ - Verify environment variables, ConfigMaps, Secrets, and other configuration injected into the deployed application. Ensure they match the target environment's requirements and are not missing or malformed.
+ - Use pre-deployment checks to validate configuration.
+ - **Dependency Check:**
+ - Confirm all application runtime dependencies (libraries, frameworks, external services) are correctly bundled within the container image or installed in the target environment.
+ - **Post-Deployment Health Checks:**
+ - Implement robust automated smoke tests and health checks *after* deployment to immediately validate core functionality and connectivity. Trigger rollbacks if these fail.
+ - **Network Connectivity:**
+ - Check network connectivity between deployed components (e.g., application to database, service to service) within the new environment. Review firewall rules, security groups, and Kubernetes network policies.
+ - **Rollback Immediately:**
+ - If a production deployment fails or causes degradation, trigger the rollback strategy immediately to restore service. Diagnose the issue in a non-production environment.
+
+## Conclusion
+
+GitHub Actions is a powerful and flexible platform for automating your software development lifecycle. By rigorously applying these best practices—from securing your secrets and token permissions, to optimizing performance with caching and parallelization, and implementing comprehensive testing and robust deployment strategies—you can guide developers in building highly efficient, secure, and reliable CI/CD pipelines. Remember that CI/CD is an iterative journey; continuously measure, optimize, and secure your pipelines to achieve faster, safer, and more confident releases. Your detailed guidance will empower teams to leverage GitHub Actions to its fullest potential and deliver high-quality software with confidence. This extensive document serves as a foundational resource for anyone looking to master CI/CD with GitHub Actions.
+
+---
+
+
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/markdown.instructions.md b/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/markdown.instructions.md
new file mode 100644
index 0000000000000000000000000000000000000000..9bd404ade44174cbfa4b764b262f28d51f5033ec
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/markdown.instructions.md
@@ -0,0 +1,63 @@
+---
+description: 'Documentation and content creation standards'
+applyTo: '**/*.md'
+---
+
+## Markdown Content Rules
+
+The following markdown content rules are enforced in the validators:
+
+1. **Headings**: Use appropriate heading levels (H2, H3, etc.) to structure your content. Do not
+ use an H1 heading, as this will be generated based on the title.
+2. **Lists**: Use bullet points or numbered lists for lists. Ensure proper indentation and spacing.
+3. **Code Blocks**: Use fenced code blocks for code snippets. Specify the language for syntax
+ highlighting.
+4. **Links**: Use proper markdown syntax for links. Ensure that links are valid and accessible.
+5. **Images**: Use proper markdown syntax for images. Include alt text for accessibility.
+6. **Tables**: Use markdown tables for tabular data. Ensure proper formatting and alignment.
+7. **Line Length**: Limit line length to 400 characters for readability.
+8. **Whitespace**: Use appropriate whitespace to separate sections and improve readability.
+9. **Front Matter**: Include YAML front matter at the beginning of the file with required metadata
+ fields.
+
+## Formatting and Structure
+
+Follow these guidelines for formatting and structuring your markdown content:
+
+- **Headings**: Use `##` for H2 and `###` for H3. Ensure that headings are used in a hierarchical
+ manner. Recommend restructuring if content includes H4, and more strongly recommend for H5.
+- **Lists**: Use `-` for bullet points and `1.` for numbered lists. Indent nested lists with two
+ spaces.
+- **Code Blocks**: Use triple backticks (`) to create fenced code blocks. Specify the language
+ after the opening backticks for syntax highlighting (e.g.,`csharp).
+- **Links**: Use `[link text](URL)` for links. Ensure that the link text is descriptive and the
+ URL is valid.
+- **Images**: Use `` for images. Include a brief description of the image in
+ the alt text.
+- **Tables**: Use `|` to create tables. Ensure that columns are properly aligned and headers are
+ included.
+- **Line Length**: Break lines at 80 characters to improve readability. Use soft line breaks for
+ long paragraphs.
+- **Whitespace**: Use blank lines to separate sections and improve readability. Avoid excessive
+ whitespace.
+
+## Validation Requirements
+
+Ensure compliance with the following validation requirements:
+
+- **Front Matter**: Include the following fields in the YAML front matter:
+
+ - `post_title`: The title of the post.
+ - `author1`: The primary author of the post.
+ - `post_slug`: The URL slug for the post.
+ - `microsoft_alias`: The Microsoft alias of the author.
+ - `featured_image`: The URL of the featured image.
+ - `categories`: The categories for the post. These categories must be from the list in /categories.txt.
+ - `tags`: The tags for the post.
+ - `ai_note`: Indicate if AI was used in the creation of the post.
+ - `summary`: A brief summary of the post. Recommend a summary based on the content when possible.
+ - `post_date`: The publication date of the post.
+
+- **Content Rules**: Ensure that the content follows the markdown content rules specified above.
+- **Formatting**: Ensure that the content is properly formatted and structured according to the guidelines.
+- **Validation**: Run the validation tools to check for compliance with the rules and guidelines.
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/python.instructions.md b/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/python.instructions.md
new file mode 100644
index 0000000000000000000000000000000000000000..39f54b40179497b5a0aaa4b6463d120a6bb2ecae
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.github/instructions/python.instructions.md
@@ -0,0 +1,56 @@
+---
+description: 'Python coding conventions and guidelines'
+applyTo: '**/*.py'
+---
+
+# Python Coding Conventions
+
+## Python Instructions
+
+- Write clear and concise comments for each function.
+- Ensure functions have descriptive names and include type hints.
+- Provide docstrings following PEP 257 conventions.
+- Use the `typing` module for type annotations (e.g., `List[str]`, `Dict[str, int]`).
+- Break down complex functions into smaller, more manageable functions.
+
+## General Instructions
+
+- Always prioritize readability and clarity.
+- For algorithm-related code, include explanations of the approach used.
+- Write code with good maintainability practices, including comments on why certain design decisions were made.
+- Handle edge cases and write clear exception handling.
+- For libraries or external dependencies, mention their usage and purpose in comments.
+- Use consistent naming conventions and follow language-specific best practices.
+- Write concise, efficient, and idiomatic code that is also easily understandable.
+
+## Code Style and Formatting
+
+- Follow the **PEP 8** style guide for Python.
+- Maintain proper indentation (use 4 spaces for each level of indentation).
+- Ensure lines do not exceed 79 characters.
+- Place function and class docstrings immediately after the `def` or `class` keyword.
+- Use blank lines to separate functions, classes, and code blocks where appropriate.
+
+## Edge Cases and Testing
+
+- Always include test cases for critical paths of the application.
+- Account for common edge cases like empty inputs, invalid data types, and large datasets.
+- Include comments for edge cases and the expected behavior in those cases.
+- Write unit tests for functions and document them with docstrings explaining the test cases.
+
+## Example of Proper Documentation
+
+```python
+def calculate_area(radius: float) -> float:
+ """
+ Calculate the area of a circle given the radius.
+
+ Parameters:
+ radius (float): The radius of the circle.
+
+ Returns:
+ float: The area of the circle, calculated as π * radius^2.
+ """
+ import math
+ return math.pi * radius ** 2
+```
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.github/workflows/main.yml b/tasks/tasksmith-ae872f5c3953/tests/source/.github/workflows/main.yml
new file mode 100644
index 0000000000000000000000000000000000000000..6bea22bf40a35ce4d2230d0cc83835956ec5be65
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.github/workflows/main.yml
@@ -0,0 +1,158 @@
+name: Python application and Docker image CI
+
+on:
+ push:
+ branches: [ master, develop, feature/* ]
+ tags: [ '*.*.*' ] # Enable pipeline on tag pushes
+ pull_request:
+ branches: [ master, develop ]
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ python-version: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13', '3.14']
+
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Install dependencies
+ run: |
+ curl -LsSf https://astral.sh/uv/install.sh | sh
+ sudo apt-get -qq update
+ sudo apt-get install -y libemail-outlook-message-perl
+ uv sync
+ export PERL_MM_USE_DEFAULT=1
+ sudo cpan -f -i Email::Outlook::Message
+
+ - name: Run tests
+ env:
+ PYTHONPATH: src
+ run: |
+ make test
+ uv run mail-parser -v
+ uv run mail-parser -h
+ uv run mail-parser -f tests/mails/mail_malformed_3 -j
+ cat tests/mails/mail_malformed_3 | uv run mail-parser -k -j
+
+ - name: Run pre-commit
+ run: |
+ make pre-commit
+
+ - name: Report to Coveralls
+ if: matrix.python-version == '3.10'
+ uses: coverallsapp/github-action@v2.2.3
+ with:
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build
+ if: matrix.python-version == '3.10'
+ run: |
+ uv build
+
+ - name: Upload artifacts
+ if: matrix.python-version == '3.10'
+ uses: actions/upload-artifact@v4
+ with:
+ name: build-artifacts
+ path: |
+ dist/mail_parser-*
+
+ - name: Publish to PyPI
+ if: matrix.python-version == '3.10' && startsWith(github.ref, 'refs/tags/')
+ uses: pypa/gh-action-pypi-publish@v1.13.0
+ with:
+ user: ${{ secrets.PYPI_USERNAME }}
+ password: ${{ secrets.PYPI_PASSWORD }}
+
+ docker:
+ if: github.event_name == 'push' && (github.ref == 'refs/heads/master' || github.ref == 'refs/heads/develop' || startsWith(github.ref, 'refs/tags/'))
+ runs-on: ubuntu-latest
+ needs: build
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Download build artifacts
+ uses: actions/download-artifact@v4
+ with:
+ name: build-artifacts
+ path: dist/
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Log in to GitHub Container Registry
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Log in to Docker Hub
+ uses: docker/login-action@v3
+ with:
+ registry: docker.io
+ username: ${{ secrets.DOCKER_USERNAME }}
+ password: ${{ secrets.DOCKER_PASSWORD }}
+
+ - name: Extract branch or tag name
+ id: extract_ref
+ run: |
+ if [ -n "${GITHUB_HEAD_REF}" ]; then
+ REF_NAME=${GITHUB_HEAD_REF}
+ else
+ REF_NAME=$(git describe --tags --exact-match 2>/dev/null || git rev-parse --abbrev-ref HEAD)
+ fi
+ echo "REF_NAME=${REF_NAME,,}" >> $GITHUB_ENV
+
+ - name: Build and push Docker image on GitHub Container Registry
+ run: |
+ IMAGE_NAME=ghcr.io/ghcr.io/spamscope/mail-parser/mailparser
+ if [[ $GITHUB_REF == refs/tags/* ]]; then
+ TAG=${GITHUB_REF#refs/tags/}
+ docker build \
+ --label "org.opencontainers.image.source=${{ github.repositoryUrl }}" \
+ --label "org.opencontainers.image.description=Easy way to pass from raw mail to Python object" \
+ --label "org.opencontainers.image.licenses=Apache-2.0" \
+ -t $IMAGE_NAME:$TAG \
+ -t $IMAGE_NAME:latest .
+ docker push $IMAGE_NAME:$TAG
+ docker push $IMAGE_NAME:latest
+ else
+ docker build \
+ --label "org.opencontainers.image.source=${{ github.repositoryUrl }}" \
+ --label "org.opencontainers.image.description=Easy way to pass from raw mail to Python object" \
+ --label "org.opencontainers.image.licenses=Apache-2.0" \
+ -t $IMAGE_NAME:develop .
+ docker push $IMAGE_NAME:develop
+ fi
+
+ - name: Build and push Docker image on Docker Hub
+ run: |
+ IMAGE_NAME=docker.io/${{ secrets.DOCKER_USERNAME }}/spamscope-mail-parser
+ if [[ $GITHUB_REF == refs/tags/* ]]; then
+ TAG=${GITHUB_REF#refs/tags/}
+ docker build \
+ --label "org.opencontainers.image.source=${{ github.repositoryUrl }}" \
+ --label "org.opencontainers.image.description=Easy way to pass from raw mail to Python object" \
+ --label "org.opencontainers.image.licenses=Apache-2.0" \
+ -t $IMAGE_NAME:$TAG \
+ -t $IMAGE_NAME:latest .
+ docker push $IMAGE_NAME:$TAG
+ docker push $IMAGE_NAME:latest
+ else
+ docker build \
+ --label "org.opencontainers.image.source=${{ github.repositoryUrl }}" \
+ --label "org.opencontainers.image.description=Easy way to pass from raw mail to Python object" \
+ --label "org.opencontainers.image.licenses=Apache-2.0" \
+ -t $IMAGE_NAME:develop .
+ docker push $IMAGE_NAME:develop
+ fi
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.gitignore b/tasks/tasksmith-ae872f5c3953/tests/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..0a25d5a87c69994c969602434d8621882e8b703b
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.gitignore
@@ -0,0 +1,23 @@
+# python_template defaults
+/env/
+/build/
+/dist/
+*.egg-info
+*.pyc
+/pip-wheel-metadata/
+.pytest_cache/
+coverage.xml
+coverage.json
+.coverage
+htmlcov/
+.mypy_cache/
+.eggs/
+.*.tgt
+.idea/
+.vscode/
+junit.xml
+/venv/
+/__pycache__/
+/*.egg-info/
+.DS_Store
+VERSION
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.markdownlint.yaml b/tasks/tasksmith-ae872f5c3953/tests/source/.markdownlint.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..89e1ea2104e7f97742eb48cde105ecee5a29b972
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.markdownlint.yaml
@@ -0,0 +1,20 @@
+# Markdownlint configuration
+# See https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md
+
+# MD013/line-length - Line length
+MD013:
+ # Disable line length check for code blocks and tables
+ line_length: 120
+ code_blocks: false
+ tables: false
+
+# MD033/no-inline-html - Inline HTML
+MD033:
+ # Allow specific HTML elements commonly used in GitHub markdown
+ allowed_elements:
+ - a
+ - img
+ - br
+
+# MD041/first-line-heading - First line in file should be a top level heading
+MD041: false # Allow files to start with badges or other content
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/.pre-commit-config.yaml b/tasks/tasksmith-ae872f5c3953/tests/source/.pre-commit-config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..560fc6d32d163d7e78ab00186fd9c4d52c52c3d0
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/.pre-commit-config.yaml
@@ -0,0 +1,36 @@
+# See https://pre-commit.com for more information
+# See https://pre-commit.com/hooks.html for more hooks
+repos:
+- repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v6.0.0
+ hooks:
+ - id: trailing-whitespace
+ - id: end-of-file-fixer
+ - id: check-yaml
+ - id: check-added-large-files
+ args: ['--maxkb=5000']
+ - id: check-case-conflict
+ - id: check-json
+ - id: check-merge-conflict
+ - id: detect-aws-credentials
+ args: ["--allow-missing-credentials"]
+ - id: detect-private-key
+ - id: mixed-line-ending
+ - id: check-ast
+
+- repo: https://github.com/astral-sh/ruff-pre-commit
+ # Ruff version.
+ rev: v0.14.1
+ hooks:
+ # Run the linter.
+ - id: ruff
+ args: [ --fix ]
+ # Run the formatter.
+ - id: ruff-format
+
+- repo: https://github.com/igorshubovych/markdownlint-cli
+ rev: v0.45.0
+ hooks:
+ - id: markdownlint
+ args: ['--fix']
+ exclude: '^\.github/instructions/'
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/Dockerfile b/tasks/tasksmith-ae872f5c3953/tests/source/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..45f5750b228d69c2c34b3a372870a21e28124f42
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/Dockerfile
@@ -0,0 +1,8 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir hatchling==1.33.0 pytest==9.2.0 pytest-cov==7.1.0 coverage==7.17.3 pytest-mock==3.17.0 pytest-ordering==0.6
+COPY . /workspace
+RUN python -m pip install --no-cache-dir -e .
+RUN rm -rf /workspace/.git /root/.cache/pip
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/LICENSE.txt b/tasks/tasksmith-ae872f5c3953/tests/source/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/Makefile b/tasks/tasksmith-ae872f5c3953/tests/source/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..3008ff7e662f59a83b8604960faf97796692d694
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/Makefile
@@ -0,0 +1,56 @@
+.PHONY: help clean clean-build clean-test test lint format check install build release
+.DEFAULT_GOAL := help
+
+define PRINT_HELP_PYSCRIPT
+import re, sys
+
+for line in sys.stdin:
+ match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)
+ if match:
+ target, help = match.groups()
+ print("%-20s %s" % (target, help))
+endef
+export PRINT_HELP_PYSCRIPT
+
+help: ## show this help message
+ @python3 -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST)
+
+install: ## install dependencies using uv
+ uv sync
+
+clean-build: ## remove build artifacts
+ find . -type d -name "build" -exec rm -rf {} +
+ find . -type d -name "dist" -exec rm -rf {} +
+ find . -type d -name "*.egg-info" -exec rm -rf {} +
+
+clean-test: ## remove test and coverage artifacts
+ find . -type f -name "*.log" -delete
+ find . -type f -name "coverage.xml" -delete
+ find . -type f -name "junit.xml" -delete
+ find . -type f -name ".coverage" -delete
+ find . -type d -name ".pytest_cache" -exec rm -rf {} +
+ find . -type d -name "htmlcov" -exec rm -rf {} +
+ find . -type d -name ".mypy_cache" -exec rm -rf {} +
+ find . -type d -name "__pycache__" -exec rm -rf {} +
+
+clean: clean-test clean-build ## remove all artifacts
+
+test: ## run tests
+ uv run pytest
+
+lint: ## run linting with ruff
+ uv run ruff check .
+
+format: ## format code with ruff
+ uv run ruff format .
+
+check: lint test ## run linting and tests
+
+build: clean ## build package
+ uv build
+
+pre-commit: ## run pre-commit hooks
+ uv run pre-commit run --all-files
+
+release: build ## build and upload to PyPI
+ uv run twine upload dist/*
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/NOTICE.txt b/tasks/tasksmith-ae872f5c3953/tests/source/NOTICE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f94f7dee49f7d648eb2f4a2bb81882034fa8047d
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/NOTICE.txt
@@ -0,0 +1,13 @@
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/README.md b/tasks/tasksmith-ae872f5c3953/tests/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..89e8459128a79e0f0ec30c6ee48b3b6d48203b2d
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/README.md
@@ -0,0 +1,482 @@
+[](https://pypi.org/project/mail-parser/)
+[](https://coveralls.io/github/SpamScope/mail-parser?branch=develop)
+[](https://pypistats.org/packages/mail-parser)
+
+
+
+# mail-parser
+
+mail-parser is a **production-grade, RFC-compliant email parsing library** that goes far beyond a
+simple wrapper for Python's [email module](https://docs.python.org/2/library/email.message.html).
+It transforms raw email messages into richly structured Python objects with unparalleled precision,
+making complex email processing accessible and reliable.
+
+As the **battle-tested foundation of [SpamScope](https://github.com/SpamScope/spamscope)**—a
+powerful email security and threat analysis platform—mail-parser has proven itself in demanding
+production environments where accuracy and security matter most.
+
+## Why Choose mail-parser?
+
+**🔒 Security-First Design**: Built specifically for email security analysis and digital forensics,
+mail-parser excels at detecting malformed structures, hidden content, and RFC non-compliance that
+could indicate malicious intent.
+
+**🎯 Comprehensive Parsing**: Extracts every component of an email—headers, bodies (plain text and
+HTML), attachments, metadata, routing information, and even subtle defects that other parsers miss.
+
+**🔍 Multi-Format Access**: Every parsed element is accessible in three formats (Python object, raw
+string, and JSON), enabling seamless integration with any workflow or downstream system.
+
+**🛡️ Defect Detection**: Identifies and categorizes RFC violations, malformed MIME boundaries, and
+structural anomalies that could hide malicious payloads or bypass security filters.
+
+**📧 Outlook Support**: Native handling of Microsoft Outlook .msg files alongside standard email
+formats, making it versatile for diverse email ecosystems.
+
+**⚡ Production-Ready**: Trusted by security professionals and developers worldwide, with extensive
+test coverage and proven reliability in high-stakes environments.
+
+Additionally, mail-parser provides full support for parsing Outlook email formats (.msg). To enable
+this functionality on Debian-based systems, simply install the required system package:
+
+```bash
+apt-get install libemail-outlook-message-perl
+```
+
+For further details about the package, you can run:
+
+```bash
+apt-cache show libemail-outlook-message-perl
+```
+
+mail-parser is fully compatible with Python 3, ensuring modern performance and reliability.
+
+# Apache 2 Open Source License
+
+mail-parser can be downloaded, used, and modified free of charge. It is available under the Apache 2 license.
+
+# Support the Future of mail-parser
+
+mail-parser is a **labor of love and commitment to the open-source community**. Thousands of
+developers and security professionals worldwide rely on this library for critical email processing
+and threat analysis. Your support directly fuels continued innovation and excellence.
+
+## Invest in Innovation
+
+Your contribution—no matter the size—makes a real difference. By supporting mail-parser, you enable us to:
+
+- **Advance Security Capabilities**: Develop cutting-edge detection mechanisms for emerging email
+ threats and attack vectors.
+- **Expand Format Support**: Add compatibility with new email formats and standards as they evolve.
+- **Enhance Performance**: Optimize parsing speed and memory efficiency for large-scale deployments.
+- **Maintain Excellence**: Ensure comprehensive testing, documentation, and bug-free releases that
+ you can trust in production.
+- **Foster Community**: Respond to issues, review contributions, and build a thriving ecosystem
+ around email security.
+- **Stay RFC-Compliant**: Keep pace with evolving email standards and specifications to ensure
+ maximum compatibility.
+
+Every donation, whether $5 or $500, directly funds development time and infrastructure costs. Join
+the community of supporters who believe in **accessible, reliable, and secure email parsing for
+everyone**.
+
+[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=VEPXYP745KJF2)
+
+Or contribute with Bitcoin:
+
+
+
+
+
+**Bitcoin Address:** `bc1qxhz3tghztpjqdt7atey68s344wvmugtl55tm32`
+
+Thank you for supporting the evolution of mail-parser!
+
+# mail-parser on Web
+
+Explore mail-parser on these platforms:
+
+- **[FreeBSD port](https://www.freshports.org/mail/py-mail-parser/)**
+- **[Arch User Repository](https://aur.archlinux.org/packages/mailparser/)**
+- **[REMnux](https://docs.remnux.org/discover-the-tools/analyze+documents/email+messages#mail-parser)**
+
+# Description
+
+mail-parser transforms raw email messages into comprehensive, RFC-compliant Python objects that
+faithfully mirror the structure defined by [IETF email protocol standards](https://www.iana.org/assignments/message-headers/message-headers.xhtml).
+Each property of the parsed object directly corresponds to standard RFC headers—"From", "To", "Cc",
+"Bcc", "Subject", and many more—providing intuitive, Pythonic access to every email component.
+
+## Core Parsing Capabilities
+
+The library extracts and structures every aspect of an email message:
+
+- **Multi-format Bodies**: Both plain text and HTML body content, cleanly separated and accessible.
+- **Complete Attachments**: Full metadata extraction including filename, content type, encoding,
+ content disposition, content-ID, charset, and base64-encoded payloads.
+- **Routing Intelligence**: Parsed "Received" headers revealing the complete email journey,
+ including hop-by-hop analysis with timestamps, delays, server information, and envelope data.
+- **Advanced Diagnostics**: Timestamp parsing with timezone detection, defect identification for
+ RFC non-compliance, and structural anomaly detection.
+- **Custom Headers**: Full support for non-standard and vendor-specific headers using intuitive
+ underscore substitution for hyphenated names.
+
+## Triple-Format Property Access
+
+Every parsed element offers **three distinct access patterns** for maximum flexibility:
+
+- **Native Python objects**: Structured, typed data ready for immediate programmatic use
+ (`mail.to`, `mail.date`, `mail.attachments`).
+- **Raw strings**: Original, unprocessed header content preserving exact formatting
+ (`mail.to_raw`, `mail.subject_raw`).
+- **JSON serialization**: Clean, standardized JSON representations for easy integration with APIs,
+ databases, or other tools (`mail.to_json`, `mail.headers_json`).
+
+This versatile architecture makes mail-parser exceptionally powerful for diverse use cases—from
+security analysis and forensics to email migration, compliance auditing, and automated processing
+pipelines.
+
+**Standard RFC Headers** (directly accessible as properties):
+
+- `bcc` - Blind carbon copy recipients
+- `cc` - Carbon copy recipients
+- `date` - Parsed timestamp with timezone support
+- `delivered_to` - Final delivery address
+- `from_` - Sender address (underscore used since `from` is a Python keyword)
+- `message_id` - Unique message identifier
+- `received` - Parsed routing chain with hop-by-hop details
+- `reply_to` - Reply-to address
+- `subject` - Email subject line
+- `to` - Primary recipients
+
+**Additional Parsed Components**:
+
+- `body` - Complete message body
+- `text_html` - HTML body parts (list)
+- `text_plain` - Plain text body parts (list)
+- `headers` - All headers as a structured object
+- `attachments` - Complete attachment metadata and payloads
+- `get_server_ipaddress()` - Reliable sender IP extraction with trust levels
+- `to_domains` - Extracted recipient domains for analysis
+- `timezone` - Detected timezone information
+- `defects` - RFC compliance issues for security analysis
+- `defects_categories` - Categorized defect types
+
+The `attachments` property returns a list of dictionaries, each containing comprehensive metadata:
+
+- `binary` - Boolean flag indicating binary content
+- `charset` - Character encoding of the attachment
+- `content_transfer_encoding` - Transfer encoding method (e.g., base64, quoted-printable)
+- `content-disposition` - Disposition type (attachment, inline, etc.)
+- `content-id` - Content identifier for referencing within HTML bodies
+- `filename` - Original filename of the attachment
+- `mail_content_type` - MIME content type
+- `payload` - Base64-encoded attachment data, ready for decoding or storage
+
+To access custom or vendor-specific headers, replace hyphens with underscores. For example, to
+access the `X-MSMail-Priority` header:
+
+```python
+mail.X_MSMail_Priority
+```
+
+The `received` header is intelligently parsed into individual hops, revealing the complete email
+routing path. Each hop contains structured fields:
+
+- `by` - Receiving mail server
+- `date` - Timestamp of receipt (original timezone)
+- `date_utc` - Normalized UTC timestamp
+- `delay` - Time elapsed between consecutive hops
+- `envelope_from` - SMTP envelope sender
+- `envelope_sender` - Alternative envelope sender field
+- `for` - Intended recipient
+- `from` - Sending mail server
+- `hop` - Sequential hop number
+- `with` - Protocol used for transmission (SMTP, ESMTP, etc.)
+
+> **Critical Security Feature**: mail-parser detects and reports structural defects in email
+> messages.
+
+The [defects](https://docs.python.org/3/library/email.message.html#email.message.Message.defects)
+property identifies RFC non-compliance issues that may indicate malformed or malicious emails—a
+crucial capability for security analysis and threat detection.
+
+**Multi-Format Property Access Pattern**:
+
+All parsed properties provide three access variants using intuitive suffixes:
+
+- `property_name` - Returns structured Python object
+- `property_name_json` - Returns JSON-serialized representation
+- `property_name_raw` - Returns original, unprocessed header string
+
+Example usage:
+
+```python
+mail.to # Python list of recipient objects
+mail.to_json # JSON string representation
+mail.to_raw # Original "To:" header string as it appears in the email
+```
+
+The command-line tool outputs parsed emails in JSON format by default for easy integration with
+other tools and pipelines.
+
+## Defects and Their Critical Role in Email Security
+
+Email structural defects are not merely technical curiosities—they represent **potential security
+vulnerabilities** that sophisticated attackers actively exploit to bypass spam filters, antivirus
+scanners, and email security gateways.
+
+### Real-World Threat Scenarios
+
+Malformed MIME boundaries, for example, can conceal illegitimate epilogue sections containing:
+
+- **Malware Payloads**: Executable files or scripts hidden in non-standard message parts
+- **Phishing Links**: Obfuscated URLs that bypass pattern-matching filters
+- **Command-and-Control Data**: Encoded instructions for compromised systems
+- **Data Exfiltration**: Steganographically hidden sensitive information
+
+### mail-parser's Security Advantage
+
+mail-parser was **specifically engineered for security analysis and digital forensics**, with defect
+detection as a core feature rather than an afterthought. The library captures and categorizes even
+subtle structural anomalies that other parsers silently ignore or mishandle.
+
+By leveraging mail-parser's defect detection, security teams can:
+
+- **Expose Hidden Content**: Discover deliberately obfuscated message parts that may contain
+ malicious payloads.
+- **Identify Attack Patterns**: Recognize non-standard formatting techniques used by threat actors
+ to evade detection.
+- **Enable Deep Forensics**: Conduct thorough structural analysis of suspicious emails during
+ incident response.
+- **Strengthen Defenses**: Build more resilient email security rules based on identified defect
+ patterns.
+- **Ensure Compliance**: Verify that outbound emails meet RFC standards to avoid delivery issues.
+
+This robust defect detection mechanism has made mail-parser the **trusted choice for security
+platforms like SpamScope**, where identifying malicious intent hidden in structural anomalies can
+mean the difference between a blocked threat and a successful attack.
+
+# Authors
+
+## Main Author
+
+**Fedele Mantuano**: [LinkedIn](https://www.linkedin.com/in/fmantuano/)
+
+# Installation
+
+mail-parser requires Python 3 and can be installed in seconds using pip. Follow these steps:
+
+## Quick Install
+
+1. Ensure Python 3 is installed on your system.
+1. Open your terminal or command prompt.
+1. Install mail-parser from PyPI:
+
+```bash
+pip install mail-parser
+```
+
+1. (Optional) Verify the installation:
+
+```bash
+pip show mail-parser
+```
+
+## Development Installation
+
+For contributors and developers who want to work with the source code, we recommend using `uv` for
+dependency management:
+
+```bash
+git clone https://github.com/SpamScope/mail-parser.git
+cd mail-parser
+uv sync
+```
+
+This setup installs all development and testing dependencies in an isolated virtual environment,
+ensuring a clean and reproducible development workflow.
+
+For comprehensive documentation about `uv`, visit the [official uv documentation](https://docs.astral.sh/uv/).
+
+# Usage in a Project
+
+## Basic Usage
+
+Import the `mailparser` module and use the convenient factory functions:
+
+```python
+import mailparser
+
+mail = mailparser.parse_from_bytes(byte_mail) # Parse from bytes object
+mail = mailparser.parse_from_file(f) # Parse from file path
+mail = mailparser.parse_from_file_msg(outlook_mail) # Parse Outlook .msg file
+mail = mailparser.parse_from_file_obj(fp) # Parse from file object
+mail = mailparser.parse_from_string(raw_mail) # Parse from string
+```
+
+## Accessing Parsed Components
+
+Once parsed, access all email components through intuitive properties:
+
+```python
+mail.attachments # List of all attachments with metadata
+mail.body # Complete message body
+mail.date # Parsed datetime object (UTC)
+mail.defects # List of RFC compliance defects
+mail.defects_categories # Categorized defect types
+mail.delivered_to # Delivery address
+mail.from_ # Sender information
+mail.get_server_ipaddress(trust="my_server_mail_trust") # Reliable sender IP
+mail.headers # All headers as structured object
+mail.mail # Fully tokenized mail object
+mail.message # Underlying email.message.Message object
+mail.message_as_string # Reconstructed message as string
+mail.message_id # Unique message identifier
+mail.received # Parsed routing information (hop-by-hop)
+mail.subject # Email subject
+mail.text_plain # Plain text body parts (list)
+mail.text_html # HTML body parts (list)
+mail.text_not_managed # Unprocessed text parts (check logs for subtypes)
+mail.to # Recipient information
+mail.to_domains # Extracted recipient domains
+mail.timezone # Timezone information (offset from UTC)
+mail.mail_partial # Partial mail object (main parts only)
+```
+
+## Saving Attachments to Disk
+
+Write all attachments to a specified directory:
+
+```python
+mail.write_attachments(base_path)
+```
+
+# Usage from Command Line
+
+After installing mail-parser with pip, you can use the `mailparser` command-line tool for quick
+email analysis, batch processing, or integration with shell scripts and pipelines.
+
+## Command-Line Options
+
+```text
+usage: mailparser [-h] (-f FILE | -s STRING | -k)
+ [-l {CRITICAL,ERROR,WARNING,INFO,DEBUG,NOTSET}] [-j] [-b]
+ [-a] [-r] [-t] [-dt] [-m] [-u] [-c] [-d] [-o]
+ [-i Trust mail server string] [-p] [-z] [-v]
+
+Wrapper for email Python Standard Library
+
+optional arguments:
+ -h, --help show this help message and exit
+ -f FILE, --file FILE Raw email file (default: None)
+ -s STRING, --string STRING
+ Raw email string (default: None)
+ -k, --stdin Enable parsing from stdin (default: False)
+ -l {CRITICAL,ERROR,WARNING,INFO,DEBUG,NOTSET}, --log-level {CRITICAL,ERROR,WARNING,INFO,DEBUG,NOTSET}
+ Set log level (default: WARNING)
+ -j, --json Show the JSON of parsed mail (default: False)
+ -b, --body Print the body of mail (default: False)
+ -a, --attachments Print the attachments of mail (default: False)
+ -r, --headers Print the headers of mail (default: False)
+ -t, --to Print the to of mail (default: False)
+ -dt, --delivered-to Print the delivered-to of mail (default: False)
+ -m, --from Print the from of mail (default: False)
+ -u, --subject Print the subject of mail (default: False)
+ -c, --receiveds Print all receiveds of mail (default: False)
+ -d, --defects Print the defects of mail (default: False)
+ -o, --outlook Analyze Outlook msg (default: False)
+ -i Trust mail server string, --senderip Trust mail server string
+ Extract a reliable sender IP address heuristically
+ (default: None)
+ -p, --mail-hash Print mail fingerprints without headers (default:
+ False)
+ -z, --attachments-hash
+ Print attachments with fingerprints (default: False)
+ -sa, --store-attachments
+ Store attachments on disk (default: False)
+ -ap ATTACHMENTS_PATH, --attachments-path ATTACHMENTS_PATH
+ Path where store attachments (default: /tmp)
+ -v, --version show program's version number and exit
+
+It takes as input a raw mail and generates a parsed object.
+```
+
+## Examples
+
+Parse an email file and output as formatted JSON:
+
+```shell
+mailparser -f example_mail -j
+```
+
+Extract only the subject and sender:
+
+```shell
+mailparser -f example_mail -u -m
+```
+
+Analyze an Outlook .msg file with defect detection:
+
+```shell
+mailparser -f email.msg -o -d -j
+```
+
+Parse from stdin (useful for pipelines):
+
+```shell
+cat raw_email.eml | mailparser -k -j
+```
+
+See the transformation from [raw email](https://gist.github.com/fedelemantuano/5dd702004c25a46b2bd60de21e67458e)
+to [beautifully parsed JSON output](https://gist.github.com/fedelemantuano/e958aa2813c898db9d2d09469db8e6f6).
+
+# Exception Hierarchy
+
+mail-parser uses a well-structured exception hierarchy for precise error handling:
+
+```text
+MailParserError: Base MailParser Exception
+|
+\── MailParserOutlookError: Raised with Outlook integration errors
+|
+\── MailParserEnvironmentError: Raised when the environment is not correct
+|
+\── MailParserOSError: Raised when there is an OS error
+|
+\── MailParserReceivedParsingError: Raised when a received header cannot be parsed
+```
+
+# Docker Deployment
+
+A pre-built Docker image is available for easy deployment and containerized workflows. Find the
+[official image on Docker Hub](https://hub.docker.com/r/fmantuano/spamscope-mail-parser/).
+
+## Quick Start with Docker
+
+After installing Docker, run the containerized mail-parser:
+
+```shell
+sudo docker run -it --rm -v ~/mails:/mails fmantuano/spamscope-mail-parser
+```
+
+This command mounts your local `~/mails` directory into the container at `/mails`, allowing
+mail-parser to access your email files. You can pass any command-line options supported by
+mail-parser.
+
+## Using Docker Compose
+
+For more complex setups, a `docker-compose.yml` file is included in the repository. Run it with:
+
+```shell
+sudo docker-compose up
+```
+
+The default configuration includes:
+
+- Read-only mount of your local `~/mails` directory to `/mails` in the container.
+- A test command demonstrating mail-parser functionality.
+
+Customize the `docker-compose.yml` file to adjust mount points, command-line options, or
+environment variables for your specific use case.
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/docker-compose.yml b/tasks/tasksmith-ae872f5c3953/tests/source/docker-compose.yml
new file mode 100644
index 0000000000000000000000000000000000000000..a7f0548a8a4912ec336f62a977594c349234909f
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/docker-compose.yml
@@ -0,0 +1,10 @@
+version: '2.1'
+
+services:
+
+ mailparser:
+ image: fmantuano/spamscope-mail-parser:develop
+ command: --json -f /mails/mail_test_1
+ container_name: mailparser
+ volumes:
+ - ~/mails/:/mails/:ro
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/docs/images/Bitcoin SpamScope.jpg b/tasks/tasksmith-ae872f5c3953/tests/source/docs/images/Bitcoin SpamScope.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..275b6c4987edc5f5616e6bc7223e716d6212235e
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/docs/images/Bitcoin SpamScope.jpg
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6ddd918bc801a21b0f9ae49f346716421ca09b27492a68bdfbcd95cdbb7e4668
+size 152309
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/pyproject.toml b/tasks/tasksmith-ae872f5c3953/tests/source/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..ae9f180b844ca1a1658fb376c6d5543d7b2a196b
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/pyproject.toml
@@ -0,0 +1,103 @@
+[project]
+name = "mail-parser"
+dynamic = ["version"]
+description = "A tool that parses emails by enhancing the Python standard library, extracting all details into a comprehensive object."
+license = "Apache-2.0"
+readme = "README.md"
+requires-python = ">=3.9,<3.15"
+keywords = ["email", "mail", "parser", "security", "forensics", "threat detection", "phishing", "malware", "spam"]
+classifiers = [
+ "Natural Language :: English",
+ "Operating System :: Unix",
+ "Operating System :: MacOS",
+ "Operating System :: Microsoft :: Windows",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.9",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Programming Language :: Python :: 3.14",
+]
+authors = [
+ { name = "Fedele Mantuano", email = "mantuano.fedele@gmail.com" }
+]
+maintainers = [
+ { name = "Fedele Mantuano", email = "mantuano.fedele@gmail.com" }
+]
+dependencies = []
+
+[dependency-groups]
+dev = [
+ "build>=1.2.2.post1",
+ "hatch>=1.14.0",
+ "pre-commit>=4.0.1",
+ "ruff>=0.9.9",
+ "twine>=6.0.1",
+ "wheel>=0.45.1",
+]
+test = [
+ "coverage>=7.6.10",
+ "pytest>=8.3.4",
+ "pytest-cov>=6.0.0",
+ "pytest-mock>=3.14.0",
+ "pytest-ordering>=0.6",
+]
+
+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.uv]
+default-groups = ["dev", "test"]
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/mailparser"]
+
+[tool.hatch.version]
+path = "src/mailparser/version.py"
+
+[project.scripts]
+mail-parser = "mailparser.__main__:main"
+
+[tool.pytest.ini_options]
+testpaths = "tests"
+markers = [
+ "integration: integration tests",
+]
+addopts = """
+--strict-markers
+--strict-config
+-ra
+--cov=src
+--cov=tests
+--cov-report=term
+--cov-branch
+--cov-report=xml
+--cov-report=html
+--junitxml=junit.xml
+--verbose
+"""
+
+[tool.ruff.lint]
+select = [
+ # pycodestyle
+ "E",
+ # pyflakes
+ "F",
+ # pyupgrade
+ # "UP",
+ # flask8-bugbear
+ # "B",
+ # flake8-simplify
+ # "SIM",
+ # isort
+ "I",
+ # flask8-bandit
+ # "S",
+ # flake8-pytest-style
+ # "PT",
+ # flake8-annotations
+ # "ANN",
+]
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/__init__.py b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..72b1ef7a1eca5bcc044aee089d082db5e86c2029
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/__init__.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+from mailparser.core import (
+ MailParser,
+ parse_from_bytes,
+ parse_from_file,
+ parse_from_file_msg,
+ parse_from_file_obj,
+ parse_from_string,
+)
+from mailparser.utils import get_header
+
+__all__ = [
+ "MailParser",
+ "parse_from_bytes",
+ "parse_from_file",
+ "parse_from_file_msg",
+ "parse_from_file_obj",
+ "parse_from_string",
+ "get_header",
+]
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/__main__.py b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2db45a47ed7f7aec816f835014f0eabbc89ae2a4
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/__main__.py
@@ -0,0 +1,346 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import argparse
+import logging
+import sys
+
+import mailparser
+from mailparser.exceptions import MailParserOutlookError
+from mailparser.utils import (
+ custom_log,
+ print_attachments,
+ print_mail_fingerprints,
+ safe_print,
+ write_attachments,
+)
+from mailparser.version import __version__
+
+log = logging.getLogger("mailparser")
+
+
+def get_args():
+ """
+ Get arguments from command line.
+ :return: argparse.ArgumentParser
+ :rtype: argparse.ArgumentParser
+ """
+ parser = argparse.ArgumentParser(
+ description="Wrapper for email Python Standard Library",
+ epilog="It takes as input a raw mail and generates a parsed object.",
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+ )
+
+ parsing_group = parser.add_mutually_exclusive_group(required=True)
+ parsing_group.add_argument("-f", "--file", dest="file", help="Raw email file")
+ parsing_group.add_argument("-s", "--string", dest="string", help="Raw email string")
+ parsing_group.add_argument(
+ "-k",
+ "--stdin",
+ dest="stdin",
+ action="store_true",
+ help="Enable parsing from stdin",
+ )
+
+ parser.add_argument(
+ "-l",
+ "--log-level",
+ dest="log_level",
+ default="WARNING",
+ choices=["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"],
+ help="Set log level",
+ )
+
+ parser.add_argument(
+ "-j",
+ "--json",
+ dest="json",
+ action="store_true",
+ help="Show the JSON of parsed mail",
+ )
+
+ parser.add_argument(
+ "-b", "--body", dest="body", action="store_true", help="Print the body of mail"
+ )
+
+ parser.add_argument(
+ "-a",
+ "--attachments",
+ dest="attachments",
+ action="store_true",
+ help="Print the attachments of mail",
+ )
+
+ parser.add_argument(
+ "-r",
+ "--headers",
+ dest="headers",
+ action="store_true",
+ help="Print the headers of mail",
+ )
+
+ parser.add_argument(
+ "-t", "--to", dest="to", action="store_true", help="Print the to of mail"
+ )
+
+ parser.add_argument(
+ "-dt",
+ "--delivered-to",
+ dest="delivered_to",
+ action="store_true",
+ help="Print the delivered-to of mail",
+ )
+
+ parser.add_argument(
+ "-m", "--from", dest="from_", action="store_true", help="Print the from of mail"
+ )
+
+ parser.add_argument(
+ "-u",
+ "--subject",
+ dest="subject",
+ action="store_true",
+ help="Print the subject of mail",
+ )
+
+ parser.add_argument(
+ "-c",
+ "--receiveds",
+ dest="receiveds",
+ action="store_true",
+ help="Print all receiveds of mail",
+ )
+
+ parser.add_argument(
+ "-d",
+ "--defects",
+ dest="defects",
+ action="store_true",
+ help="Print the defects of mail",
+ )
+
+ parser.add_argument(
+ "-o",
+ "--outlook",
+ dest="outlook",
+ action="store_true",
+ help="Analyze Outlook msg",
+ )
+
+ parser.add_argument(
+ "-i",
+ "--senderip",
+ dest="senderip",
+ metavar="Trust mail server string",
+ help="Extract a reliable sender IP address heuristically",
+ )
+
+ parser.add_argument(
+ "-p",
+ "--mail-hash",
+ dest="mail_hash",
+ action="store_true",
+ help="Print mail fingerprints without headers",
+ )
+
+ parser.add_argument(
+ "-z",
+ "--attachments-hash",
+ dest="attachments_hash",
+ action="store_true",
+ help="Print attachments with fingerprints",
+ )
+
+ parser.add_argument(
+ "-sa",
+ "--store-attachments",
+ dest="store_attachments",
+ action="store_true",
+ help="Store attachments on disk",
+ )
+
+ parser.add_argument(
+ "-ap",
+ "--attachments-path",
+ dest="attachments_path",
+ default="/tmp",
+ help="Path where store attachments",
+ )
+
+ parser.add_argument(
+ "-v", "--version", action="version", version=f"%(prog)s {__version__}"
+ )
+
+ return parser
+
+
+def main():
+ """
+ Main function.
+ """
+ args = get_args().parse_args()
+ log = custom_log(level=args.log_level, name="mailparser")
+
+ try:
+ parser = get_parser(args)
+ process_output(args, parser)
+ except Exception as e:
+ log.exception(f"An error occurred: {e}")
+ sys.exit(1)
+
+
+def get_parser(args):
+ """
+ Get the correct parser based on the input source.
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ :return: MailParser
+ :rtype: mailparser.core.MailParser
+ """
+ if args.file:
+ return parse_file(args)
+ elif args.string:
+ log.debug("Start analysis by string mail")
+ return mailparser.parse_from_string(args.string)
+ elif args.stdin:
+ return parse_stdin(args)
+ else:
+ raise ValueError("No input source provided")
+
+
+def parse_file(args):
+ """
+ Parse the file based on the arguments provided.
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ :return: MailParser
+ :rtype: mailparser.core.MailParser
+ """
+ log.debug("Start analysis by file mail")
+ if args.outlook:
+ log.debug("Start analysis by Outlook msg")
+ return mailparser.parse_from_file_msg(args.file)
+ else:
+ log.debug("Start analysis by raw mail")
+ return mailparser.parse_from_file(args.file)
+
+
+def parse_stdin(args):
+ """
+ Parse the stdin based on the arguments provided.
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ :return: MailParser
+ :rtype: mailparser.core.MailParser
+ """
+ log.debug("Start analysis by stdin mail")
+ if args.outlook:
+ raise MailParserOutlookError("You can't use stdin with msg Outlook")
+ return mailparser.parse_from_file_obj(sys.stdin)
+
+
+def process_output(args, parser):
+ """
+ Process the output based on the arguments provided.
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ :param parser: MailParser
+ :type parser: mailparser.core.MailParser
+ :param log: logger
+ :type log: logging.Logger
+ """
+ if args.json:
+ safe_print(parser.mail_json)
+
+ if args.body:
+ safe_print(parser.body)
+
+ if args.headers:
+ safe_print(parser.headers_json)
+
+ if args.to:
+ safe_print(parser.to_json)
+
+ if args.delivered_to:
+ safe_print(parser.delivered_to_json)
+
+ if args.from_:
+ safe_print(parser.from_json)
+
+ if args.subject:
+ safe_print(parser.subject)
+
+ if args.receiveds:
+ safe_print(parser.received_json)
+
+ if args.defects:
+ print_defects(parser)
+
+ if args.senderip:
+ print_sender_ip(parser, args)
+
+ if args.attachments or args.attachments_hash:
+ print_attachments_details(parser, args)
+
+ if args.mail_hash:
+ log.debug("Printing also mail fingerprints")
+ print_mail_fingerprints(parser.body.encode("utf-8"))
+
+ if args.store_attachments:
+ log.debug("Store attachments on disk")
+ write_attachments(parser.attachments, args.attachments_path)
+
+
+def print_defects(parser):
+ """
+ Print email defects.
+ :param parser: MailParser
+ :type parser: mailparser.core.MailParser
+ """
+ log.debug("Printing defects")
+ for defect in parser.defects_categories:
+ safe_print(defect)
+
+
+def print_sender_ip(parser, args):
+ """
+ Print sender IP address.
+ :param parser: MailParser
+ :type parser: mailparser.core.MailParser
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ """
+ log.debug("Printing sender IP")
+ sender_ip = parser.get_server_ipaddress(args.senderip)
+ safe_print(sender_ip if sender_ip else "Not Found")
+
+
+def print_attachments_details(parser, args):
+ """
+ Print attachments details.
+ :param parser: MailParser
+ :type parser: mailparser.core.MailParser
+ :param args: argparse.Namespace
+ :type args: argparse.Namespace
+ """
+ log.debug("Printing attachments details")
+ print_attachments(parser.attachments, args.attachments_hash)
+
+
+if __name__ == "__main__": # pragma: no cover
+ main()
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/const.py b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/const.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d172243828f9cc0d1f68a4f46c073ecccbde5ef
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/const.py
@@ -0,0 +1,101 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2018 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import re
+
+REGXIP = re.compile(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
+
+JUNK_PATTERN = r"[ \(\)\[\]\t\n]+"
+
+# Patterns for receiveds
+RECEIVED_PATTERNS = [
+ # FIXED: More restrictive 'from' clause
+ # Only matches 'from' at the beginning of the header (^) or after
+ # newline/whitespace to avoid matching within "for from "
+ # constructs which caused duplicate matches in IBM gateway headers
+ (
+ r"(?:(?:^|\n\s*)from\s+(?P.+?)(?:\s*[(]?"
+ r"envelope-from|\s*[(]?envelope-sender|\s+"
+ r"by|\s+with(?! cipher)|\s+id|\s+via|;))"
+ ),
+ # IMPROVED: More precise 'by' clause
+ # Modified to not consume 'with' clause, allowing proper separation
+ # of 'by' (server name) and 'with' (protocol) fields
+ (
+ r"(?:(?:^|\s)by\s+(?P[^\s]+(?:\s+[^\s]+)*?)"
+ r"(?:\s+with(?! cipher)|\s*[(]?envelope-from|\s*"
+ r"[(]?envelope-sender|\s+id|\s+for|\s+via|;))"
+ ),
+ # IMPROVED: 'with' clause with better boundary detection
+ (
+ r"(?:(?:^|\s)with(?! cipher)\s+(?P.+?)"
+ r"(?:\s*[(]?envelope-from|\s*[(]?"
+ r"envelope-sender|\s+id|\s+for|\s+via|;))"
+ ),
+ # IMPROVED: 'id' clause with cleaner boundaries
+ (
+ r"(?:(?:^|\s)id\s+(?P.+?)(?:\s*[(]?envelope-from|\s*"
+ r"[(]?envelope-sender|\s+for|\s+via|;))"
+ ),
+ # IMPROVED: 'for' clause - handles "for from " pattern
+ # Stops before 'from' keyword to prevent the 'from' pattern from
+ # matching the sender email in this construct
+ (
+ r"(?:(?:^|\s)for\s+(?P<[^>]+>|[^\s]+)"
+ r"(?:\s+from|\s*[(]?envelope-from|\s*[(]?"
+ r"envelope-sender|\s+via|;))"
+ ),
+ # IMPROVED: 'via' clause with better termination
+ (
+ r"(?:(?:^|\s)via\s+(?P.+?)(?:\s*[(]?"
+ r"envelope-from|\s*[(]?envelope-sender|;))"
+ ),
+ # assumes emails are always inside <>
+ r"(?:envelope-from\s+<(?P.+?)>)",
+ r"(?:envelope-sender\s+<(?P.+?)>)",
+ # datetime comes after ; at the end
+ r";\s*(?P.*)",
+ # sendgrid datetime
+ (
+ r"(?P\d{4}-\d{2}-\d{2} \d{2}:\d{2}:"
+ r"\d{2}\.\d{9} \+0000 UTC) m=\+\d+\.\d+"
+ ),
+]
+
+RECEIVED_COMPILED_LIST = [re.compile(i, re.I | re.DOTALL) for i in RECEIVED_PATTERNS]
+
+EPILOGUE_DEFECTS = {"StartBoundaryNotFoundDefect"}
+
+ADDRESSES_HEADERS = set(["bcc", "cc", "delivered-to", "from", "reply-to", "to"])
+
+# These parts are always returned
+OTHERS_PARTS = set(
+ [
+ "attachments",
+ "body",
+ "date",
+ "message-id",
+ "received",
+ "subject",
+ "timezone",
+ "to_domains",
+ "user-agent",
+ "x-mailer",
+ "x-original-to",
+ ]
+)
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/core.py b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5e865853725046fa4028b306e3458314fa5a71b
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/core.py
@@ -0,0 +1,759 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import base64
+import email
+import ipaddress
+import json
+import logging
+import os
+
+from mailparser.const import ADDRESSES_HEADERS, EPILOGUE_DEFECTS, REGXIP
+from mailparser.utils import (
+ convert_mail_date,
+ decode_header_part,
+ find_between,
+ get_header,
+ get_mail_keys,
+ get_to_domains,
+ msgconvert,
+ ported_open,
+ ported_string,
+ random_string,
+ receiveds_parsing,
+ write_attachments,
+)
+
+log = logging.getLogger(__name__)
+
+
+def parse_from_file_obj(fp):
+ """
+ Parsing email from a file-like object.
+
+ Args:
+ fp (file-like object): file-like object of raw email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_file_obj(fp)
+
+
+def parse_from_file(fp):
+ """
+ Parsing email from file.
+
+ Args:
+ fp (string): file path of raw email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_file(fp)
+
+
+def parse_from_file_msg(fp):
+ """
+ Parsing email from file Outlook msg.
+
+ Args:
+ fp (string): file path of raw Outlook email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_file_msg(fp)
+
+
+def parse_from_string(s):
+ """
+ Parsing email from string.
+
+ Args:
+ s (string): raw email
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_string(s)
+
+
+def parse_from_bytes(bt):
+ """
+ Parsing email from bytes. Only for Python 3
+
+ Args:
+ bt (bytes-like object): raw email as bytes-like object
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+ return MailParser.from_bytes(bt)
+
+
+class MailParser:
+ """
+ MailParser package provides a standard parser that understands
+ most email document structures like official email package.
+ MailParser handles the encoding of email and split the raw email for you.
+
+ Headers:
+ https://www.iana.org/assignments/message-headers/message-headers.xhtml
+ """
+
+ def __init__(self, message=None):
+ """
+ Init a new object from a message object structure.
+ """
+ self._message = message
+ log.debug("All headers of emails: {}".format(", ".join(message.keys())))
+ self.parse()
+
+ def __str__(self):
+ if self.message:
+ return self.subject
+ else:
+ return str()
+
+ @classmethod
+ def from_file_obj(cls, fp):
+ """
+ Init a new object from a file-like object.
+ Not for Outlook msg.
+
+ Args:
+ fp (file-like object): file-like object of raw email
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug("Parsing email from file object")
+ try:
+ fp.seek(0)
+ except OSError:
+ # When stdout is a TTY it's a character device
+ # and it's not seekable, you cannot seek in a TTY.
+ pass
+ finally:
+ s = fp.read()
+
+ return cls.from_string(s)
+
+ @classmethod
+ def from_file(cls, fp, is_outlook=False):
+ """
+ Init a new object from a file path.
+
+ Args:
+ fp (string): file path of raw email
+ is_outlook (boolean): if True is an Outlook email
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug(f"Parsing email from file {fp!r}")
+
+ with ported_open(fp) as f:
+ message = email.message_from_file(f)
+
+ if is_outlook:
+ log.debug(f"Removing temp converted Outlook email {fp!r}")
+ os.remove(fp)
+
+ return cls(message)
+
+ @classmethod
+ def from_file_msg(cls, fp):
+ """
+ Init a new object from a Outlook message file,
+ mime type: application/vnd.ms-outlook
+
+ Args:
+ fp (string): file path of raw Outlook email
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug("Parsing email from file Outlook")
+ f, _ = msgconvert(fp)
+ return cls.from_file(f, True)
+
+ @classmethod
+ def from_string(cls, s):
+ """
+ Init a new object from a string.
+
+ Args:
+ s (string): raw email
+
+ Returns:
+ Instance of MailParser
+ """
+
+ log.debug("Parsing email from string")
+ message = email.message_from_string(s)
+ return cls(message)
+
+ @classmethod
+ def from_bytes(cls, bt):
+ """
+ Init a new object from bytes.
+
+ Args:
+ bt (bytes-like object): raw email as bytes-like object
+
+ Returns:
+ Instance of MailParser
+ """
+ log.debug("Parsing email from bytes")
+ message = email.message_from_bytes(bt)
+ return cls(message)
+
+ def _reset(self):
+ """
+ Reset the state of mail object.
+ """
+ log.debug("Reset all variables")
+
+ self._attachments = []
+ self._text_plain = []
+ self._text_html = []
+ self._text_not_managed = []
+ self._defects = []
+ self._defects_categories = set()
+ self._has_defects = False
+
+ def _append_defects(self, part, part_content_type):
+ """
+ Add new defects and defects categories to object attributes.
+
+ The defects are a list of all the problems found
+ when parsing this message.
+
+ Args:
+ part (string): mail part
+ part_content_type (string): content type of part
+ """
+
+ part_defects = {}
+
+ for e in part.defects:
+ defects = f"{e.__class__.__name__}: {e.__doc__}"
+ self._defects_categories.add(e.__class__.__name__)
+ part_defects.setdefault(part_content_type, []).append(defects)
+ log.debug(f"Added defect {defects!r}")
+
+ # Tag mail with defect
+ if part_defects:
+ self._has_defects = True
+
+ # Save all defects
+ self._defects.append(part_defects)
+
+ def _make_mail(self, complete=True):
+ """
+ This method assigns the right values to all tokens of email.
+ Returns a parsed object
+
+ Keyword Arguments:
+ complete {bool} -- If True returns all mails parts
+ (default: {True})
+
+ Returns:
+ dict -- Parsed email object
+ """
+
+ mail = {}
+ keys = get_mail_keys(self.message, complete)
+
+ for i in keys:
+ log.debug(f"Getting header or part {i!r}")
+ value = getattr(self, i)
+ if value:
+ mail[i] = value
+
+ # add defects
+ mail["has_defects"] = self.has_defects
+ if self.has_defects:
+ mail["defects"] = self.defects
+ mail["defects_categories"] = list(self.defects_categories)
+
+ return mail
+
+ def parse(self):
+ """
+ This method parses the raw email and makes the tokens.
+
+ Returns:
+ Instance of MailParser with raw email parsed
+ """
+
+ if not self.message:
+ return self
+
+ # reset and start parsing
+ self._reset()
+ parts = [] # Normal parts plus defects
+
+ # walk all mail parts to search defects
+ for p in self.message.walk():
+ part_content_type = p.get_content_type()
+ self._append_defects(p, part_content_type)
+ parts.append(p)
+
+ # If defects are in epilogue defects get epilogue
+ if self.defects_categories & EPILOGUE_DEFECTS:
+ log.debug("Found defects in emails")
+ epilogue = find_between(
+ self.message.epilogue,
+ "{}".format("--" + self.message.get_boundary()),
+ "{}".format("--" + self.message.get_boundary() + "--"),
+ )
+
+ try:
+ p = email.message_from_string(epilogue)
+ parts.append(p)
+ except TypeError:
+ log.debug("Failed to get epilogue part for TypeError")
+ except Exception:
+ log.error("Failed to get epilogue part. Check raw mail.")
+
+ # walk all mail parts
+ for i, p in enumerate(parts):
+ if (
+ not p.is_multipart()
+ or ported_string(p.get_content_disposition()).lower() == "attachment"
+ ):
+ charset = p.get_content_charset("utf-8")
+ charset_raw = p.get_content_charset()
+ log.debug(f"Charset {charset!r} part {i!r}")
+ content_disposition = ported_string(p.get_content_disposition()).lower()
+ log.debug(f"content-disposition {content_disposition!r} part {i!r}")
+ content_id = ported_string(p.get("content-id"))
+ log.debug(f"content-id {content_id!r} part {i!r}")
+ content_subtype = ported_string(p.get_content_subtype())
+ log.debug(f"content subtype {content_subtype!r} part {i!r}")
+ filename = decode_header_part(p.get_filename())
+
+ is_attachment = False
+ if filename:
+ is_attachment = True
+ else:
+ if content_id and content_subtype not in ("html", "plain"):
+ is_attachment = True
+ filename = content_id
+ elif content_subtype in ("rtf"):
+ is_attachment = True
+ filename = f"{random_string()}.rtf"
+ elif content_disposition == "attachment":
+ is_attachment = True
+ filename = f"{random_string()}.txt"
+
+ # this is an attachment
+ if is_attachment:
+ log.debug(f"Email part {i!r} is an attachment")
+ log.debug(f"Filename {filename!r} part {i!r}")
+ binary = False
+ mail_content_type = ported_string(p.get_content_type())
+ log.debug(f"Mail content type {mail_content_type!r} part {i!r}")
+ transfer_encoding = ported_string(
+ p.get("content-transfer-encoding", "")
+ ).lower()
+ log.debug(f"Transfer encoding {transfer_encoding!r} part {i!r}")
+ content_disposition = ported_string(p.get("content-disposition"))
+ log.debug(f"content-disposition {content_disposition!r} part {i!r}")
+
+ if p.is_multipart():
+ payload = "".join(
+ [m.as_string() for m in p.get_payload(decode=False)]
+ )
+ binary = False
+ log.debug(f"Filename {filename!r} part {i!r} is multipart")
+ elif transfer_encoding == "base64" or (
+ transfer_encoding
+ == "quoted-\
+ printable"
+ and "application" in mail_content_type
+ ):
+ payload = p.get_payload(decode=False)
+ binary = True
+ log.debug(f"Filename {filename!r} part {i!r} is binary")
+ elif "uuencode" in transfer_encoding:
+ # Re-encode in base64
+ payload = base64.b64encode(p.get_payload(decode=True)).decode(
+ "ascii"
+ )
+ binary = True
+ transfer_encoding = "base64"
+ log.debug(
+ f"Filename {filename!r} part {i!r} is binary (uuencode"
+ " re-encoded to base64)"
+ )
+ else:
+ payload = ported_string(
+ p.get_payload(decode=True), encoding=charset
+ )
+ log.debug(f"Filename {filename!r} part {i!r} is not binary")
+
+ self._attachments.append(
+ {
+ "filename": filename,
+ "payload": payload,
+ "binary": binary,
+ "mail_content_type": mail_content_type,
+ "content-id": content_id,
+ "content-disposition": content_disposition,
+ "charset": charset_raw,
+ "content_transfer_encoding": transfer_encoding,
+ }
+ )
+
+ # this isn't an attachments
+ else:
+ log.debug(f"Email part {i!r} is not an attachment")
+
+ # Get the payload using get_payload method with decode=True
+ # As Python truly decodes only 'base64',
+ # 'quoted-printable', 'x-uuencode',
+ # 'uuencode', 'uue', 'x-uue'
+ # And for other encodings it breaks the characters so
+ # we need to decode them with encoding python is appying
+ # To maintain the characters
+ payload = p.get_payload(decode=True)
+ cte = p.get("Content-Transfer-Encoding")
+ if cte:
+ cte = cte.lower()
+
+ if not cte or cte in ["7bit", "8bit"]:
+ try:
+ payload = payload.decode("raw-unicode-escape")
+ except UnicodeDecodeError:
+ payload = ported_string(payload, encoding=charset)
+ else:
+ payload = ported_string(payload, encoding=charset)
+
+ if payload:
+ if p.get_content_subtype() == "html":
+ self._text_html.append(payload)
+ elif p.get_content_subtype() == "plain":
+ self._text_plain.append(payload)
+ else:
+ log.warning(
+ f"Email content {p.get_content_subtype()!r} not handled"
+ )
+ self._text_not_managed.append(payload)
+
+ # Parsed object mail with all parts
+ self._mail = self._make_mail()
+
+ # Parsed object mail with mains parts
+ self._mail_partial = self._make_mail(complete=False)
+
+ def get_server_ipaddress(self, trust):
+ """
+ Return the ip address of sender
+
+ Overview:
+ Extract a reliable sender IP address heuristically for each message.
+ Although the message format dictates a chain of relaying IP
+ addresses in each message, a malicious relay can easily alter that.
+ Therefore we cannot simply take the first IP in
+ the chain. Instead, our method is as follows.
+ First we trust the sender IP reported by our mail server in the
+ Received headers, and if the previous relay IP address is on our trust
+ list (e.g. other well-known mail services), we continue to
+ follow the previous Received line, till we reach the first unrecognized
+ IP address in the email header.
+
+ From article Characterizing Botnets from Email Spam Records:
+ Li Zhuang, J. D. Tygar
+
+ In our case we trust only our mail server with the trust string.
+
+ Args:
+ trust (string): String that identify our mail server
+
+ Returns:
+ string with the ip address
+ """
+ log.debug(f"Trust string is {trust!r}")
+
+ if not trust.strip():
+ return
+
+ received = self.message.get_all("received", [])
+
+ for i in received:
+ i = ported_string(i)
+ if trust in i:
+ log.debug(f"Trust string {trust!r} is in {i!r}")
+ ip_str = self._extract_ip(i)
+ if ip_str:
+ return ip_str
+
+ def _extract_ip(self, received_header):
+ """
+ Extract the IP address from the received header if it is not private.
+
+ Args:
+ received_header (string): The received header string
+
+ Returns:
+ string with the ip address or None
+ """
+ check = REGXIP.findall(received_header[0 : received_header.find("by")])
+ if check:
+ try:
+ ip_str = str(check[-1])
+ log.debug(f"Found sender IP {ip_str!r} in {received_header!r}")
+ ip = ipaddress.ip_address(ip_str)
+ except ValueError:
+ return None
+ else:
+ if not ip.is_private:
+ log.debug(f"IP {ip_str!r} not private")
+ return ip_str
+ return None
+
+ def write_attachments(self, base_path):
+ """This method writes the attachments of mail on disk
+
+ Arguments:
+ base_path {str} -- Base path where write the attachments
+ """
+ write_attachments(attachments=self.attachments, base_path=base_path)
+
+ def __getattr__(self, name):
+ name = name.strip("_").lower()
+ name_header = name.replace("_", "-")
+
+ # json headers
+ if name.endswith("_json"):
+ name = name[:-5]
+ return json.dumps(getattr(self, name), ensure_ascii=False)
+
+ # raw headers
+ elif name.endswith("_raw"):
+ name = name[:-4]
+ raw = self.message.get_all(name)
+ return json.dumps(raw, ensure_ascii=False)
+
+ # object headers
+ elif name_header in ADDRESSES_HEADERS:
+ h = decode_header_part(self.message.get(name_header, str()))
+ h_parsed = email.utils.getaddresses([h], strict=True)
+ return (
+ h_parsed
+ if h_parsed != [("", "")]
+ else email.utils.getaddresses([h], strict=False)
+ )
+
+ # others headers
+ else:
+ return get_header(self.message, name_header)
+
+ @property
+ def attachments(self):
+ """
+ Return a list of all attachments in the mail
+ """
+ return self._attachments
+
+ @property
+ def received(self):
+ """
+ Return a list of all received headers parsed
+ """
+ output = self.received_raw
+ return receiveds_parsing(output)
+
+ @property
+ def received_json(self):
+ """
+ Return a JSON of all received headers
+ """
+ return json.dumps(self.received, ensure_ascii=False, indent=2)
+
+ @property
+ def received_raw(self):
+ """
+ Return a list of all received headers in raw format
+ """
+ output = []
+ for i in self.message.get_all("received", []):
+ output.append(decode_header_part(i))
+ return output
+
+ @property
+ def body(self):
+ """
+ Return all text plain and text html parts of mail delimited from string
+ "--- mail_boundary ---"
+ """
+ return "\n--- mail_boundary ---\n".join(
+ self.text_plain + self.text_html + self.text_not_managed
+ )
+
+ @property
+ def headers(self) -> dict:
+ """
+ Return only the headers as Python object
+ """
+ all_headers = set(self.message.keys()) - set(["headers"])
+ return {i: getattr(self, i) for i in all_headers}
+
+ @property
+ def headers_json(self):
+ """
+ Return the JSON of headers
+ """
+ return json.dumps(self.headers, ensure_ascii=False, indent=2)
+
+ @property
+ def text_plain(self):
+ """
+ Return a list of all text plain parts of email.
+ """
+ return self._text_plain
+
+ @property
+ def text_html(self):
+ """
+ Return a list of all text html parts of email.
+ """
+ return self._text_html
+
+ @property
+ def text_not_managed(self):
+ """
+ Return a list of all text not managed of email.
+ """
+ return self._text_not_managed
+
+ @property
+ def date(self):
+ """
+ Return the mail date in datetime.datetime format and UTC.
+ """
+ date = self.message.get("date")
+ conv = None
+
+ try:
+ conv, _ = convert_mail_date(date)
+ except Exception:
+ pass
+ return conv
+
+ @property
+ def timezone(self):
+ """
+ Return timezone. Offset from UTC.
+ """
+ date = self.message.get("date")
+ timezone = 0
+
+ try:
+ _, timezone = convert_mail_date(date)
+ except Exception:
+ pass
+ return timezone
+
+ @property
+ def date_json(self):
+ """
+ Return the JSON of date
+ """
+ if self.date:
+ return json.dumps(self.date.isoformat(), ensure_ascii=False)
+
+ @property
+ def mail(self):
+ """
+ Return the Python object of mail parsed
+ """
+ return self._mail
+
+ @property
+ def mail_json(self):
+ """
+ Return the JSON of mail parsed
+ """
+ if self.mail.get("date"):
+ self._mail["date"] = self.date.isoformat()
+ return json.dumps(self.mail, ensure_ascii=False, indent=2)
+
+ @property
+ def mail_partial(self):
+ """
+ Return the Python object of mail parsed
+ with only the mains headers
+ """
+ return self._mail_partial
+
+ @property
+ def mail_partial_json(self):
+ """
+ Return the JSON of mail parsed partial
+ """
+ if self.mail_partial.get("date"):
+ self._mail_partial["date"] = self.date.isoformat()
+ return json.dumps(self.mail_partial, ensure_ascii=False, indent=2)
+
+ @property
+ def defects(self):
+ """
+ The defects property contains a list of
+ all the problems found when parsing this message.
+ """
+ return self._defects
+
+ @property
+ def defects_categories(self):
+ """
+ Return a set with only defects categories.
+ """
+ return self._defects_categories
+
+ @property
+ def has_defects(self):
+ """
+ Return a boolean: True if mail has defects.
+ """
+ return self._has_defects
+
+ @property
+ def message(self):
+ """
+ email.message.Message class.
+ """
+ return self._message
+
+ @property
+ def message_as_string(self):
+ """
+ Return the entire message flattened as a string.
+ """
+ return self.message.as_string()
+
+ @property
+ def to_domains(self):
+ """
+ Return all domain of 'to' and 'reply-to' email addresses
+ """
+ return get_to_domains(self.to, self.reply_to)
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/exceptions.py b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..143cba662f72ff4a3d6849b0dd7c2f4f646aa59f
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/exceptions.py
@@ -0,0 +1,65 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2018 Fedele Mantuano (https://www.linkedin.com/in/fmantuano/)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+__all__ = (
+ "MailParserError",
+ "MailParserOutlookError",
+ "MailParserEnvironmentError",
+ "MailParserOSError",
+ "MailParserReceivedParsingError",
+)
+
+
+class MailParserError(Exception):
+ """
+ Base MailParser Exception
+ """
+
+ pass
+
+
+class MailParserOutlookError(MailParserError):
+ """
+ Raised when there is an error with Outlook integration
+ """
+
+ pass
+
+
+class MailParserEnvironmentError(MailParserError):
+ """
+ Raised when the environment is not correct
+ """
+
+ pass
+
+
+class MailParserOSError(MailParserError):
+ """
+ Raised when there is an OS error
+ """
+
+ pass
+
+
+class MailParserReceivedParsingError(MailParserError):
+ """
+ Raised when a received header cannot be parsed
+ """
+
+ pass
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/utils.py b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c73cd2c58cdcf1a9dfb31bd4d2feb6f29f9f6ab9
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/utils.py
@@ -0,0 +1,581 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import base64
+import datetime
+import email
+import functools
+import hashlib
+import json
+import logging
+import os
+import random
+import re
+import string
+import subprocess
+import sys
+import tempfile
+from collections import Counter, namedtuple
+from email.errors import HeaderParseError
+from email.header import decode_header
+from unicodedata import normalize
+
+from mailparser.const import (
+ ADDRESSES_HEADERS,
+ JUNK_PATTERN,
+ OTHERS_PARTS,
+ RECEIVED_COMPILED_LIST,
+)
+from mailparser.exceptions import MailParserOSError, MailParserReceivedParsingError
+
+log = logging.getLogger(__name__)
+
+
+def custom_log(level="WARNING", name=None): # pragma: no cover
+ """
+ This function returns a custom logger.
+ :param level: logging level
+ :type level: str
+ :param name: logger name
+ :type name: str
+ :return: logger
+ """
+ if name:
+ log = logging.getLogger(name)
+ else:
+ log = logging.getLogger()
+ log.setLevel(level)
+ ch = logging.StreamHandler(sys.stdout)
+ formatter = logging.Formatter(
+ "%(asctime)s | "
+ "%(name)s | "
+ "%(module)s | "
+ "%(funcName)s | "
+ "%(lineno)d | "
+ "%(levelname)s | "
+ "%(message)s"
+ )
+ ch.setFormatter(formatter)
+ log.addHandler(ch)
+ return log
+
+
+def sanitize(func):
+ """NFC is the normalization form recommended by W3C."""
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ return normalize("NFC", func(*args, **kwargs))
+
+ return wrapper
+
+
+@sanitize
+def ported_string(raw_data, encoding="utf-8", errors="ignore"):
+ """
+ Give as input raw data and output a str in Python 3.
+
+ Args:
+ raw_data: bytes or str to convert to str
+ encoding: string giving the name of an encoding
+ errors: specifies the treatment of characters
+ which are invalid in the input encoding
+
+ Returns:
+ str
+ """
+
+ if not raw_data:
+ return str()
+
+ if isinstance(raw_data, str):
+ return raw_data
+
+ # raw_data is bytes, decode it
+ try:
+ return str(raw_data, encoding)
+ except (LookupError, UnicodeDecodeError):
+ return str(raw_data, "utf-8", errors)
+
+
+def decode_header_part(header):
+ """
+ Given a raw header returns a decoded header
+
+ Args:
+ header (string): header to decode
+
+ Returns:
+ str
+ """
+ if not header:
+ return str()
+
+ output = str()
+
+ try:
+ for d, c in decode_header(header):
+ c = c if c else "utf-8"
+ output += ported_string(d, c, "ignore")
+
+ # Header parsing failed, when header has charset Shift_JIS
+ except (HeaderParseError, UnicodeError):
+ log.error(f"Failed decoding header part: {header}")
+ output += header
+
+ return output.strip()
+
+
+def ported_open(file_):
+ """Open a file with UTF-8 encoding and ignore errors.
+
+ Args:
+ file_: path to the file to open
+
+ Returns:
+ file object
+ """
+ return open(file_, encoding="utf-8", errors="ignore")
+
+
+def find_between(text, first_token, last_token):
+ try:
+ start = text.index(first_token) + len(first_token)
+ end = text.index(last_token, start)
+ return text[start:end].strip()
+ except ValueError:
+ return
+
+
+def fingerprints(data):
+ """
+ This function return the fingerprints of data.
+
+ Args:
+ data (string): raw data
+
+ Returns:
+ namedtuple: fingerprints md5, sha1, sha256, sha512
+ """
+
+ hashes = namedtuple("Hashes", "md5 sha1 sha256 sha512")
+
+ if not isinstance(data, bytes):
+ data = data.encode("utf-8")
+
+ # md5
+ md5 = hashlib.md5()
+ md5.update(data)
+ md5 = md5.hexdigest()
+
+ # sha1
+ sha1 = hashlib.sha1()
+ sha1.update(data)
+ sha1 = sha1.hexdigest()
+
+ # sha256
+ sha256 = hashlib.sha256()
+ sha256.update(data)
+ sha256 = sha256.hexdigest()
+
+ # sha512
+ sha512 = hashlib.sha512()
+ sha512.update(data)
+ sha512 = sha512.hexdigest()
+
+ return hashes(md5, sha1, sha256, sha512)
+
+
+def msgconvert(email):
+ """
+ Exec msgconvert tool, to convert msg Outlook
+ mail in eml mail format
+
+ Args:
+ email (string): file path of Outlook msg mail
+
+ Returns:
+ tuple with file path of mail converted and
+ standard output data (str)
+ """
+ log.debug("Started converting Outlook email")
+ temph, temp = tempfile.mkstemp(prefix="outlook_")
+ command = ["msgconvert", "--outfile", temp, email]
+
+ try:
+ out = subprocess.Popen(
+ command,
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ )
+
+ except OSError as e:
+ message = f"Check if 'msgconvert' tool is installed / {e!r}"
+ log.exception(message)
+ raise MailParserOSError(message)
+
+ else:
+ stdoutdata, _ = out.communicate()
+ return temp, stdoutdata.decode("utf-8").strip()
+
+ finally:
+ os.close(temph)
+
+
+def parse_received(received):
+ """
+ Parse a single received header.
+ Return a dictionary of values by clause.
+
+ Arguments:
+ received {str} -- single received header
+
+ Raises:
+ MailParserReceivedParsingError -- Raised when a
+ received header cannot be parsed
+
+ Returns:
+ dict -- values by clause
+ """
+
+ values_by_clause = {}
+ for pattern in RECEIVED_COMPILED_LIST:
+ matches = [match for match in pattern.finditer(received)]
+
+ if len(matches) == 0:
+ # no matches for this clause, but it's ok! keep going!
+ log.debug("No matches found for %s in %s" % (pattern.pattern, received))
+ elif len(matches) > 1:
+ # uh, can't have more than one of each clause in a received.
+ # so either there's more than one or the current regex is wrong
+ msg = "More than one match found for %s in %s" % (pattern.pattern, received)
+ log.error(msg)
+ raise MailParserReceivedParsingError(msg)
+ else:
+ # otherwise we have one matching clause!
+ log.debug("Found one match for %s in %s" % (pattern.pattern, received))
+ match = matches[0].groupdict()
+ key = list(match.keys())[0]
+ value = list(match.values())[0]
+ values_by_clause[key] = value
+
+ if len(values_by_clause) == 0:
+ # we weren't able to match anything...
+ msg = "Unable to match any clauses in %s" % (received)
+
+ # Modification #1: Commenting the following log as
+ # this raised exception is caught above and then
+ # raw header is updated in response
+ # We dont want to get so many errors in our error
+ # logger as we are not even trying to parse the
+ # received headers
+ # Wanted to make it configurable via settiings,
+ # but this package does not depend on django and
+ # making configurable setting
+ # will make it django dependent,
+ # so better to keep it working with only python
+ # dependent and on any framework of python
+ # commenting it just for our use
+
+ # log.error(msg)
+
+ raise MailParserReceivedParsingError(msg)
+ return values_by_clause
+
+
+def receiveds_parsing(receiveds):
+ """
+ This function parses the receiveds headers.
+
+ Args:
+ receiveds (list): list of raw receiveds headers
+
+ Returns:
+ a list of parsed receiveds headers with first hop in first position
+ """
+
+ parsed = []
+ receiveds = [re.sub(JUNK_PATTERN, " ", i).strip() for i in receiveds]
+ n = len(receiveds)
+ log.debug(f"Nr. of receiveds. {n}")
+
+ for idx, received in enumerate(receiveds):
+ log.debug(f"Parsing received {idx + 1}/{n}")
+ log.debug(f"Try to parse {received!r}")
+ try:
+ # try to parse the current received header...
+ values_by_clause = parse_received(received)
+ except MailParserReceivedParsingError:
+ # if we can't, let's append the raw
+ parsed.append({"raw": received})
+ else:
+ # otherwise append the full values_by_clause dict
+ parsed.append(values_by_clause)
+
+ log.debug("len(receiveds) %s, len(parsed) %s" % (len(receiveds), len(parsed)))
+
+ if len(receiveds) != len(parsed):
+ # something really bad happened,
+ # so just return raw receiveds with hop indices
+ log.error(
+ "len(receiveds): %s, len(parsed): %s, receiveds: %s, \
+ parsed: %s"
+ % (len(receiveds), len(parsed), receiveds, parsed)
+ )
+ return receiveds_not_parsed(receiveds)
+
+ else:
+ # all's good! we have parsed or raw receiveds for each received header
+ return receiveds_format(parsed)
+
+
+def convert_mail_date(date):
+ """
+ Convert a mail date in a datetime object.
+ """
+ log.debug(f"Date to parse: {date!r}")
+ d = email.utils.parsedate_tz(date)
+ log.debug(f"Date parsed: {d!r}")
+ t = email.utils.mktime_tz(d)
+ log.debug(f"Date parsed in timestamp: {t!r}")
+ date_utc = datetime.datetime.fromtimestamp(t, datetime.timezone.utc)
+ timezone = d[9] / 3600.0 if d[9] else 0
+ timezone = f"{timezone:+.1f}"
+ log.debug(f"Calculated timezone: {timezone!r}")
+ return date_utc, timezone
+
+
+def receiveds_not_parsed(receiveds):
+ """
+ If receiveds are not parsed, makes a new structure with raw
+ field. It's useful to have the same structure of receiveds
+ parsed.
+
+ Args:
+ receiveds (list): list of raw receiveds headers
+
+ Returns:
+ a list of not parsed receiveds headers with first hop in first position
+ """
+ log.debug("Receiveds for this email are not parsed")
+
+ output = []
+ counter = Counter()
+
+ for i in receiveds[::-1]:
+ j = {"raw": i.strip()}
+ j["hop"] = counter["hop"] + 1
+ counter["hop"] += 1
+ output.append(j)
+
+ return output
+
+
+def receiveds_format(receiveds):
+ """
+ Given a list of receiveds hop, adds metadata and reformat
+ field values
+
+ Args:
+ receiveds (list): list of receiveds hops already formatted
+
+ Returns:
+ list of receiveds reformated and with new fields
+ """
+ log.debug("Receiveds for this email are parsed")
+
+ output = []
+ counter = Counter()
+
+ for i in receiveds[::-1]:
+ # Clean strings
+ j = {k: v.strip() for k, v in i.items() if v}
+
+ # Add hop
+ j["hop"] = counter["hop"] + 1
+
+ # Add UTC date
+ if i.get("date"):
+ # Modify date to manage strange header like:
+ # "for ; Tue, 7 Mar 2017 14:29:24 -0800",
+ i["date"] = i["date"].split(";")[-1]
+ try:
+ j["date_utc"], _ = convert_mail_date(i["date"])
+ except TypeError:
+ j["date_utc"] = None
+
+ # Add delay
+ size = len(output)
+ now = j.get("date_utc")
+
+ if size and now:
+ before = output[counter["hop"] - 1].get("date_utc")
+ if before:
+ j["delay"] = (now - before).total_seconds()
+ else:
+ j["delay"] = 0
+ else:
+ j["delay"] = 0
+
+ # append result
+ output.append(j)
+
+ # new hop
+ counter["hop"] += 1
+
+ for i in output:
+ if i.get("date_utc"):
+ i["date_utc"] = i["date_utc"].isoformat()
+ return output
+
+
+def get_to_domains(to=[], reply_to=[]):
+ domains = set()
+ for i in to + reply_to:
+ try:
+ domains.add(i[1].split("@")[-1].lower().strip())
+ except (KeyError, IndexError):
+ pass
+
+ return list(domains)
+
+
+def get_header(message, name):
+ """
+ Gets an email.message.Message and a header name and returns
+ the mail header decoded with the correct charset.
+
+ Args:
+ message (email.message.Message): email message object
+ name (string): header to get
+
+ Returns:
+ str if there is an header
+ list if there are more than one
+ """
+
+ headers = message.get_all(name)
+ log.debug(f"Getting header {name!r}: {headers!r}")
+ if headers:
+ headers = [decode_header_part(i) for i in headers]
+ if len(headers) == 1:
+ # in this case return a string
+ return headers[0].strip()
+ # in this case return a list
+ return headers
+ return str()
+
+
+def get_mail_keys(message, complete=True):
+ """
+ Given an email.message.Message, return a set with all email parts to get
+
+ Args:
+ message (email.message.Message): email message object
+ complete (bool): if True returns all email headers
+
+ Returns:
+ set with all email parts
+ """
+
+ if complete:
+ log.debug("Get all headers")
+ all_headers_keys = {i.lower() for i in message.keys()}
+ all_parts = ADDRESSES_HEADERS | OTHERS_PARTS | all_headers_keys
+ else:
+ log.debug("Get only mains headers")
+ all_parts = ADDRESSES_HEADERS | OTHERS_PARTS
+
+ log.debug("All parts to get: {}".format(", ".join(all_parts)))
+ return all_parts
+
+
+def safe_print(data): # pragma: no cover
+ try:
+ print(data)
+ except UnicodeEncodeError:
+ print(data.encode("utf-8"))
+
+
+def print_mail_fingerprints(data): # pragma: no cover
+ md5, sha1, sha256, sha512 = fingerprints(data)
+ print(f"md5:\t{md5}")
+ print(f"sha1:\t{sha1}")
+ print(f"sha256:\t{sha256}")
+ print(f"sha512:\t{sha512}")
+
+
+def print_attachments(attachments, flag_hash): # pragma: no cover
+ if flag_hash:
+ for i in attachments:
+ if i.get("content_transfer_encoding") == "base64":
+ payload = base64.b64decode(i["payload"])
+ else:
+ payload = i["payload"]
+
+ i["md5"], i["sha1"], i["sha256"], i["sha512"] = fingerprints(payload)
+
+ for i in attachments:
+ safe_print(json.dumps(i, ensure_ascii=False, indent=4))
+
+
+def write_attachments(attachments, base_path): # pragma: no cover
+ for a in attachments:
+ write_sample(
+ binary=a["binary"],
+ payload=a["payload"],
+ path=base_path,
+ filename=a["filename"],
+ )
+
+
+def write_sample(binary, payload, path, filename): # pragma: no cover
+ """
+ This function writes a sample on file system.
+
+ Args:
+ binary (bool): True if it's a binary file
+ payload: payload of sample, in base64 if it's a binary
+ path (string): path of file
+ filename (string): name of file
+ hash_ (string): file hash
+ """
+ if not os.path.exists(path):
+ os.makedirs(path)
+ sample = os.path.join(path, filename)
+
+ if binary:
+ with open(sample, "wb") as f:
+ f.write(base64.b64decode(payload))
+ else:
+ with open(sample, "w") as f:
+ f.write(payload)
+
+
+def random_string(string_length=10):
+ """Generate a random string of fixed length
+
+ Keyword Arguments:
+ string_length {int} -- String length (default: {10})
+
+ Returns:
+ str -- Random string
+ """
+ letters = string.ascii_lowercase
+ return "".join(random.choice(letters) for _ in range(string_length))
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/version.py b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdb9febd21372eaa7a89fcc338874320839b2cab
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/src/mailparser/version.py
@@ -0,0 +1,19 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+__version__ = "4.1.4"
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/tests/mails/mail_test_17 b/tasks/tasksmith-ae872f5c3953/tests/source/tests/mails/mail_test_17
new file mode 100644
index 0000000000000000000000000000000000000000..79822075c44407c760361074dc89abb1bbaa35f2
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/tests/mails/mail_test_17
@@ -0,0 +1,4 @@
+From: =?UTF-8?B?bm90aWZpY2FjY2lvbi1jbGllbnRlc0BiYnZhLm14?=
+
+
+Test message.
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/tests/mails/mail_test_18 b/tasks/tasksmith-ae872f5c3953/tests/source/tests/mails/mail_test_18
new file mode 100644
index 0000000000000000000000000000000000000000..d186bc0ffe142b13197e91a71b09750b0d63da90
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/tests/mails/mail_test_18
@@ -0,0 +1,5 @@
+From: =?iso-8859-1?Q?Last=DFlName=2C_FirstName?=
+To: =?UTF-8?B?dG9ueS5zdGFya0BleGFtcGxlLmNvbQ==?=
+Cc: simple@example.net, =?UTF-8?Q?John_=22Johnny=22_Doe?=
+
+Test message.
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/tests/tasksmith_behavior.py b/tasks/tasksmith-ae872f5c3953/tests/source/tests/tasksmith_behavior.py
new file mode 100644
index 0000000000000000000000000000000000000000..b83a47169bffb9124585d48cc90299844231ed8c
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/tests/tasksmith_behavior.py
@@ -0,0 +1,51 @@
+import mailparser
+import pytest
+
+
+def test_plain_address_header_unaffected():
+ """Adjacent behavior: plain unencoded From/To headers parse correctly on
+ both old and new code (regression guard)."""
+ raw = (
+ "MIME-Version: 1.0\r\n"
+ "From: Alice Smith \r\n"
+ "To: bob@example.com\r\n"
+ "Subject: Hello\r\n"
+ "\r\n"
+ "Body\r\n"
+ )
+ mail = mailparser.parse_from_string(raw)
+ assert mail.from_ == [("Alice Smith", "alice@example.com")]
+ assert mail.to == [("", "bob@example.com")]
+
+
+def test_comma_in_encoded_display_name():
+ """Encoded display name containing a comma must yield a single address tuple."""
+ import os
+ mail_test_18 = os.path.join(
+ os.path.realpath(os.path.dirname(__file__)), "..", "tests", "mails", "mail_test_18"
+ )
+ mail = mailparser.parse_from_file(mail_test_18)
+ assert mail.from_ == [("Last\u00dflName, FirstName", "comma.name@example.com")]
+
+
+def test_encoded_name_equals_email_suppressed():
+ """When decoded display name equals the email address, display name is empty string."""
+ import os
+ mail_test_18 = os.path.join(
+ os.path.realpath(os.path.dirname(__file__)), "..", "tests", "mails", "mail_test_18"
+ )
+ mail = mailparser.parse_from_file(mail_test_18)
+ assert mail.to == [("", "tony.stark@example.com")]
+
+
+def test_mixed_cc_header():
+ """Cc header mixing plain and encoded-name addresses parses into two correct tuples."""
+ import os
+ mail_test_18 = os.path.join(
+ os.path.realpath(os.path.dirname(__file__)), "..", "tests", "mails", "mail_test_18"
+ )
+ mail = mailparser.parse_from_file(mail_test_18)
+ assert mail.cc == [
+ ("", "simple@example.net"),
+ ('John "Johnny" Doe', "john.doe@example.com"),
+ ]
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_improved_received_patterns.py b/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_improved_received_patterns.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb4b9d39bd733a007619e097232e11a9c9d3f3ce
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_improved_received_patterns.py
@@ -0,0 +1,167 @@
+#!/usr/bin/env python
+"""
+Test cases for improved RECEIVED_PATTERNS regex.
+
+This test module specifically validates the fixes made to RECEIVED_PATTERNS
+to handle edge cases that were previously causing parsing failures.
+
+Key improvements:
+1. Fixed duplicate "from" matches in headers with "for from "
+2. Better separation of 'by' and 'with' clauses
+3. More precise boundary detection for all clauses
+"""
+
+import unittest
+
+from mailparser.utils import parse_received
+
+
+class TestImprovedReceivedPatterns(unittest.TestCase):
+ """Test cases for improved received header parsing."""
+
+ def test_ibm_gateway_header_with_for_from_pattern(self):
+ """
+ Test IBM gateway headers with 'for from ' pattern.
+
+ These headers previously caused "More than one match found for 'from'"
+ errors because the regex matched both the actual 'from' clause and
+ the 'from' keyword within the 'for from ' construct.
+ """
+ # ruff: noqa: E501
+ header = """from localhost
+ by e06smtp10.uk.ibm.com with IBM ESMTP SMTP Gateway: Authorized Use Only! Violators will be prosecuted
+ for from ;
+ Wed, 8 Mar 2017 16:46:25 -0000"""
+
+ # Should parse without raising MailParserReceivedParsingError
+ parsed = parse_received(header)
+
+ # Validate extracted fields
+ self.assertIn("from", parsed)
+ self.assertIn("by", parsed)
+ self.assertIn("with", parsed)
+ self.assertIn("for", parsed)
+ self.assertIn("date", parsed)
+
+ # Validate field values
+ self.assertEqual(parsed["from"].strip(), "localhost")
+ self.assertEqual(parsed["for"], "")
+ self.assertIn("Wed, 8 Mar 2017 16:46:25 -0000", parsed["date"])
+
+ def test_ibm_gateway_variant_with_esmtp_details(self):
+ """
+ Test another IBM gateway variant with detailed ESMTP information.
+ """
+ header = """from localhost
+ by smtp.notes.na.collabserv.com with smtp.notes.na.collabserv.com ESMTP
+ for from ;
+ Wed, 8 Mar 2017 16:46:15 -0000"""
+
+ parsed = parse_received(header)
+
+ self.assertIn("from", parsed)
+ self.assertIn("by", parsed)
+ self.assertIn("with", parsed)
+ self.assertIn("for", parsed)
+ self.assertEqual(parsed["from"].strip(), "localhost")
+ self.assertEqual(parsed["for"], "")
+
+ def test_standard_header_with_helo(self):
+ """
+ Test standard received header with HELO information.
+
+ This is a common, well-formed header that should continue to work.
+ """
+ # ruff: noqa: E501
+ header = """from smtprelay0207.b.hostedemail.com (HELO smtprelay.b.hostedemail.com) (64.98.42.207)
+ by smtp.server.net with SMTP; 22 Aug 2016 14:23:01 -0000"""
+
+ parsed = parse_received(header)
+
+ self.assertIn("from", parsed)
+ self.assertIn("by", parsed)
+ self.assertIn("with", parsed)
+ self.assertIn("date", parsed)
+
+ # Verify 'from' captures the full server information
+ self.assertIn("smtprelay0207.b.hostedemail.com", parsed["from"])
+ self.assertIn("HELO", parsed["from"])
+
+ # Verify 'by' and 'with' are separate
+ self.assertEqual(parsed["by"].strip(), "smtp.server.net")
+ self.assertEqual(parsed["with"].strip(), "SMTP")
+
+ def test_header_with_envelope_from(self):
+ """
+ Test header with envelope-from clause.
+ """
+ # ruff: noqa: E501
+ header = """from host86-187-174-57.range86-187.btcentralplus.com ([86.187.174.57]:45321 helo=User)
+ by localhost.localdomain (envelope-from )
+ with ESMTP id ABC123; Mon, 21 Aug 2016 10:49:40 -0000"""
+
+ parsed = parse_received(header)
+
+ self.assertIn("from", parsed)
+ self.assertIn("by", parsed)
+ self.assertIn("with", parsed)
+ self.assertIn("id", parsed)
+ self.assertIn("envelope_from", parsed)
+ self.assertEqual(parsed["envelope_from"], "sender@example.com")
+
+ def test_header_with_via_clause(self):
+ """
+ Test header with via clause.
+ """
+ header = """from DM6PR06MB4475.namprd06.prod.outlook.com (2603:10b6:207:3d::31)
+ by BL0PR06MB4465.namprd06.prod.outlook.com with HTTPS id 12345 via
+ BL0PR02CA0054.NAMPRD02.PROD.OUTLOOK.COM; Mon, 1 Oct 2018 09:49:22 +0000"""
+
+ parsed = parse_received(header)
+
+ self.assertIn("from", parsed)
+ self.assertIn("by", parsed)
+ self.assertIn("with", parsed)
+ self.assertIn("id", parsed)
+ self.assertIn("via", parsed)
+
+ def test_minimal_header_with_only_date(self):
+ """
+ Test minimal header with only date (qmail invoked headers).
+ """
+ header = "(qmail 11769 invoked from network); 22 Aug 2016 14:23:01 -0000"
+
+ parsed = parse_received(header)
+
+ # Should at least extract the date
+ self.assertIn("date", parsed)
+ self.assertIn("22 Aug 2016 14:23:01 -0000", parsed["date"])
+
+ def test_header_with_multiple_spaces_and_newlines(self):
+ """
+ Test that headers with irregular whitespace are handled correctly.
+ """
+ # ruff: noqa: E501
+ header = """from filter.hostedemail.com (10.5.19.248.rfc1918.com [10.5.19.248])
+ by smtprelay06.b.hostedemail.com (Postfix) with ESMTP id 2CC378D014
+ for ; Mon, 22 Aug 2016 14:22:58 +0000 (UTC)"""
+
+ parsed = parse_received(header)
+
+ self.assertIn("from", parsed)
+ self.assertIn("by", parsed)
+ self.assertIn("with", parsed)
+ self.assertIn("id", parsed)
+ self.assertIn("for", parsed)
+ self.assertIn("date", parsed)
+
+ def test_received_complex_edge_case(self):
+ """Test complex received header with multiple patterns"""
+ received = (
+ "from mail-server.example.com (mail-server.example.com [192.0.2.1]) "
+ "by mx.example.org (Postfix) with ESMTP id ABC123 "
+ "for ; Mon, 1 Jan 2024 12:00:00 +0000"
+ )
+ parsed = parse_received(received)
+ self.assertIsNotNone(parsed)
+ self.assertIsInstance(parsed, dict)
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_mail_parser.py b/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_mail_parser.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c3867228836d28b1119fd291a348c7475374ba2
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_mail_parser.py
@@ -0,0 +1,955 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import datetime
+import hashlib
+import os
+import shutil
+import sys
+import tempfile
+import unittest
+from unittest.mock import patch
+
+import mailparser
+from mailparser.utils import (
+ convert_mail_date,
+ fingerprints,
+ get_header,
+ get_mail_keys,
+ get_to_domains,
+ parse_received,
+ ported_open,
+ ported_string,
+ random_string,
+ receiveds_parsing,
+)
+
+# base paths
+base_path = os.path.realpath(os.path.dirname(__file__))
+root = os.path.join(base_path, "..")
+
+# raw mails to test
+mail_test_1 = os.path.join(base_path, "mails", "mail_test_1")
+mail_test_2 = os.path.join(base_path, "mails", "mail_test_2")
+mail_test_3 = os.path.join(base_path, "mails", "mail_test_3")
+mail_test_4 = os.path.join(base_path, "mails", "mail_test_4")
+mail_test_5 = os.path.join(base_path, "mails", "mail_test_5")
+mail_test_6 = os.path.join(base_path, "mails", "mail_test_6")
+mail_test_7 = os.path.join(base_path, "mails", "mail_test_7")
+mail_test_8 = os.path.join(base_path, "mails", "mail_test_8")
+mail_test_9 = os.path.join(base_path, "mails", "mail_test_9")
+mail_test_10 = os.path.join(base_path, "mails", "mail_test_10")
+mail_test_11 = os.path.join(base_path, "mails", "mail_test_11")
+mail_test_12 = os.path.join(base_path, "mails", "mail_test_12")
+mail_test_13 = os.path.join(base_path, "mails", "mail_test_13")
+mail_test_14 = os.path.join(base_path, "mails", "mail_test_14")
+mail_test_15 = os.path.join(base_path, "mails", "mail_test_15")
+mail_test_16 = os.path.join(base_path, "mails", "mail_test_16")
+mail_test_17 = os.path.join(base_path, "mails", "mail_test_17")
+mail_test_18 = os.path.join(base_path, "mails", "mail_test_18")
+mail_malformed_1 = os.path.join(base_path, "mails", "mail_malformed_1")
+mail_malformed_2 = os.path.join(base_path, "mails", "mail_malformed_2")
+mail_malformed_3 = os.path.join(base_path, "mails", "mail_malformed_3")
+mail_outlook_1 = os.path.join(base_path, "mails", "mail_outlook_1")
+
+
+class TestMailParser(unittest.TestCase):
+ def setUp(self):
+ self.all_mails = (
+ mail_test_1,
+ mail_test_2,
+ mail_test_3,
+ mail_test_4,
+ mail_test_5,
+ mail_test_6,
+ mail_test_7,
+ mail_test_8,
+ mail_test_9,
+ mail_test_10,
+ mail_test_11,
+ mail_test_12,
+ mail_test_13,
+ mail_malformed_1,
+ mail_malformed_2,
+ mail_malformed_3,
+ )
+
+ def test_write_attachments(self):
+ attachments = [
+ "<_1_0B4E44A80B15F6FC005C1243C12580DD>",
+ "<_1_0B4E420C0B4E3DD0005C1243C12580DD>",
+ "<_1_0B4E24640B4E1564005C1243C12580DD>",
+ "Move To Eight ZWEP6227F.pdf",
+ ]
+ random_path = os.path.join(root, "tests", random_string())
+ mail = mailparser.parse_from_file(mail_test_10)
+ os.makedirs(random_path)
+ mail.write_attachments(random_path)
+ for i in attachments:
+ self.assertTrue(os.path.exists(os.path.join(random_path, i)))
+ shutil.rmtree(random_path)
+
+ def test_issue62(self):
+ mail = mailparser.parse_from_file(mail_test_14)
+ received_spf = mail.Received_SPF
+ self.assertIsInstance(received_spf, list)
+ self.assertIn("custom_header1", received_spf)
+ self.assertIn("custom_header2", received_spf)
+
+ def test_html_field(self):
+ mail = mailparser.parse_from_file(mail_malformed_1)
+ self.assertIsInstance(mail.text_html, list)
+ self.assertIsInstance(mail.text_html_json, str)
+ self.assertEqual(len(mail.text_html), 1)
+
+ def test_text_not_managed(self):
+ mail = mailparser.parse_from_file(mail_test_14)
+ self.assertIsInstance(mail.text_not_managed, list)
+ self.assertIsInstance(mail.text_not_managed_json, str)
+ self.assertEqual(len(mail.text_not_managed), 1)
+ self.assertEqual("PNG here", mail.text_not_managed[0])
+
+ def test_get_mail_keys(self):
+ mail = mailparser.parse_from_file(mail_test_11)
+ all_parts = get_mail_keys(mail.message)
+ mains_parts = get_mail_keys(mail.message, False)
+ self.assertNotEqual(all_parts, mains_parts)
+ self.assertIn("message-id", mains_parts)
+ self.assertIn("x-filterd-recvd-size", all_parts)
+ self.assertNotIn("x-filterd-recvd-size", mains_parts)
+
+ def test_mail_partial(self):
+ mail = mailparser.parse_from_file(mail_test_10)
+ self.assertNotEqual(mail.mail, mail.mail_partial)
+ self.assertIn("message-id", mail.mail_partial)
+ self.assertIn("x-ibm-av-version", mail.mail)
+ self.assertNotIn("x-ibm-av-version", mail.mail_partial)
+ result = mail.mail_partial_json
+ self.assertIsInstance(result, str)
+ nr_attachments = len(mail._attachments)
+ self.assertEqual(nr_attachments, 4)
+
+ def test_not_parsed_received(self):
+ mail = mailparser.parse_from_file(mail_test_9)
+ for i in mail.received:
+ self.assertNotIn("raw", i)
+ self.assertIn("hop", i)
+
+ def test_issue_received(self):
+ mail = mailparser.parse_from_file(mail_test_8)
+ for i in mail.received:
+ self.assertIn("date_utc", i)
+ self.assertIsNotNone(i["date_utc"])
+
+ def test_get_header(self):
+ mail = mailparser.parse_from_file(mail_test_1)
+ h1 = get_header(mail.message, "from")
+ self.assertIsInstance(h1, str)
+
+ def test_receiveds_parsing(self):
+ for i in self.all_mails:
+ mail = mailparser.parse_from_file(i)
+ receiveds = mail.received_raw
+ result = receiveds_parsing(receiveds)
+ self.assertIsInstance(result, list)
+ for j in result:
+ self.assertIsInstance(j, dict)
+ self.assertIn("hop", j)
+ self.assertIn("delay", j)
+
+ def test_ipaddress(self):
+ mail = mailparser.parse_from_file(mail_test_2)
+ trust = "smtp.customers.net"
+
+ ip = "217.76.210.112"
+ result = mail.get_server_ipaddress(trust)
+ self.assertEqual(result, ip)
+
+ trust = ""
+ result = mail.get_server_ipaddress(trust)
+ self.assertIsNone(result)
+
+ trust = " "
+ result = mail.get_server_ipaddress(trust)
+ self.assertIsNone(result)
+
+ def test_ipaddress_unicodeerror(self):
+ mail = mailparser.parse_from_file(mail_test_12)
+ trust = "localhost"
+ result = mail.get_server_ipaddress(trust)
+ self.assertEqual(result, "96.202.181.20")
+
+ def test_fingerprints_body(self):
+ mail = mailparser.parse_from_file(mail_test_1)
+ md5, sha1, sha256, sha512 = fingerprints(mail.body.encode("utf-8"))
+ self.assertEqual(md5, "55852a2efe95e7249887c92cc02123f8")
+ self.assertEqual(sha1, "62fef1e38327ed09363624c3aff8ea11723ee05f")
+ self.assertEqual(
+ sha256,
+ ("cd4af1017f2e623f6d38f691048b6a28d8b1f44a0478137b4337eac6de78f71a"),
+ )
+ self.assertEqual(
+ sha512,
+ (
+ "4a573c7929b078f2a2c1c0f869d418b0c020d4"
+ "d37196bd6dcc209f9ccb29ca67355aa5e47b97"
+ "c8bf90377204f59efde7ba1fc071b6f250a665"
+ "72f63b997e92e8"
+ ),
+ )
+
+ def test_fingerprints_unicodeencodeerror(self):
+ mail = mailparser.parse_from_file(mail_test_7)
+ for i in mail.attachments:
+ fingerprints(i["payload"])
+
+ def test_malformed_mail(self):
+ mail = mailparser.parse_from_file(mail_malformed_3)
+ defects_categories = mail.defects_categories
+ self.assertIn("StartBoundaryNotFoundDefect", defects_categories)
+ self.assertIn("MultipartInvariantViolationDefect", defects_categories)
+ self.assertIn("reply-to", mail.mail)
+ self.assertNotIn("reply_to", mail.mail)
+ reply_to = [("VICTORIA Souvenirs", "smgesi4@gmail.com")]
+ self.assertEqual(mail.reply_to, reply_to)
+ self.assertEqual(mail.fake_header, str())
+
+ # This email has header X-MSMail-Priority
+ msmail_priority = mail.X_MSMail_Priority
+ self.assertEqual(msmail_priority, "High")
+
+ def test_type_error(self):
+ mail = mailparser.parse_from_file(mail_test_5)
+ self.assertEqual(len(mail.attachments), 5)
+ for i in mail.attachments:
+ self.assertIsInstance(i["filename"], str)
+
+ def test_filename_decode(self):
+ mail = mailparser.parse_from_file(mail_test_11)
+ for i in mail.attachments:
+ self.assertIsInstance(i["filename"], str)
+
+ def test_valid_mail(self):
+ m = mailparser.parse_from_string("fake mail")
+ self.assertFalse(m.message)
+
+ def test_receiveds(self):
+ mail = mailparser.parse_from_file(mail_test_1)
+ self.assertEqual(len(mail.received), 6)
+
+ self.assertIsInstance(mail.received, list)
+ for i in mail.received:
+ self.assertIsInstance(i, dict)
+
+ self.assertIsInstance(mail.received_raw, list)
+ for i in mail.received_raw:
+ self.assertIsInstance(i, str)
+
+ self.assertIsInstance(mail.received_json, str)
+
+ def test_parsing_know_values(self):
+ mail = mailparser.parse_from_file(mail_test_2)
+ trust = "smtp.customers.net"
+
+ self.assertFalse(mail.has_defects)
+
+ raw = "217.76.210.112"
+ result = mail.get_server_ipaddress(trust)
+ self.assertEqual(raw, result)
+
+ raw = "<4516257BC5774408ADC1263EEBBBB73F@ad.regione.vda.it>"
+ result = mail.message_id
+ self.assertEqual(raw, result)
+
+ raw = "echo@tu-berlin.de"
+ result = mail.to
+ self.assertEqual(len(result), 2)
+ self.assertIsInstance(result, list)
+ self.assertIsInstance(result[0], tuple)
+ self.assertIsInstance(mail.to_json, str)
+ self.assertIsInstance(mail.to_raw, str)
+ self.assertEqual(raw, result[0][1])
+
+ raw = "meteo@regione.vda.it"
+ result = mail.from_
+ self.assertEqual(raw, result[0][1])
+
+ raw = "Bollettino Meteorologico del 29/11/2015"
+ result = mail.subject
+ self.assertEqual(raw, result)
+
+ result = mail.has_defects
+ self.assertFalse(result)
+
+ result = len(mail.attachments)
+ self.assertEqual(3, result)
+
+ self.assertIsInstance(mail.date_raw, str)
+ self.assertIsInstance(mail.date_json, str)
+ raw_utc = "2015-11-29T08:45:18+00:00"
+ result = mail.date.isoformat()
+ self.assertEqual(raw_utc, result)
+
+ def test_types(self):
+ mail = mailparser.parse_from_file(mail_test_2)
+ trust = "smtp.customers.net"
+
+ self.assertFalse(mail.has_defects)
+
+ result = mail.mail
+ self.assertIsInstance(result, dict)
+ self.assertNotIn("defects", result)
+ self.assertIn("has_defects", result)
+
+ result = mail.get_server_ipaddress(trust)
+ self.assertIsInstance(result, str)
+
+ result = mail.mail_json
+ self.assertIsInstance(result, str)
+
+ result = mail.headers_json
+ self.assertIsInstance(result, str)
+
+ result = mail.headers
+ self.assertIsInstance(result, dict)
+
+ result = mail.body
+ self.assertIsInstance(result, str)
+
+ result = mail.date
+ self.assertIsInstance(result, datetime.datetime)
+
+ result = mail.from_
+ self.assertIsInstance(result, list)
+
+ result = mail.to
+ self.assertIsInstance(result, list)
+ self.assertEqual(len(result), 2)
+ self.assertIsInstance(result[0], tuple)
+ self.assertEqual(len(result[0]), 2)
+
+ result = mail.subject
+ self.assertIsInstance(result, str)
+
+ result = mail.message_id
+ self.assertIsInstance(result, str)
+
+ result = mail.attachments
+ self.assertIsInstance(result, list)
+
+ result = mail.date
+ self.assertIsInstance(result, datetime.datetime)
+
+ result = mail.defects
+ self.assertIsInstance(result, list)
+
+ def test_defects(self):
+ mail = mailparser.parse_from_file(mail_malformed_1)
+
+ self.assertTrue(mail.has_defects)
+ self.assertEqual(1, len(mail.defects))
+ self.assertEqual(1, len(mail.defects_categories))
+ self.assertIn("defects", mail.mail)
+ self.assertIn("StartBoundaryNotFoundDefect", mail.defects_categories)
+ self.assertIsInstance(mail.mail_json, str)
+
+ result = len(mail.attachments)
+ self.assertEqual(1, result)
+
+ mail = mailparser.parse_from_file(mail_test_1)
+ self.assertTrue(mail.has_defects)
+ self.assertEqual(1, len(mail.defects))
+ self.assertEqual(1, len(mail.defects_categories))
+ self.assertIn("defects", mail.mail)
+ self.assertIn("CloseBoundaryNotFoundDefect", mail.defects_categories)
+
+ def test_defects_bug(self):
+ mail = mailparser.parse_from_file(mail_malformed_2)
+
+ self.assertTrue(mail.has_defects)
+ self.assertEqual(1, len(mail.defects))
+ self.assertEqual(1, len(mail.defects_categories))
+ self.assertIn("defects", mail.mail)
+ self.assertIn("StartBoundaryNotFoundDefect", mail.defects_categories)
+ self.assertIsInstance(mail.parsed_mail_json, str)
+
+ result = len(mail.attachments)
+ self.assertEqual(1, result)
+
+ def test_add_content_type(self):
+ mail = mailparser.parse_from_file(mail_test_3)
+
+ self.assertFalse(mail.has_defects)
+
+ result = mail.mail
+
+ self.assertEqual(len(result["attachments"]), 1)
+ self.assertIsInstance(result["attachments"][0]["mail_content_type"], str)
+ self.assertFalse(result["attachments"][0]["binary"])
+ self.assertIsInstance(result["attachments"][0]["payload"], str)
+ self.assertEqual(
+ result["attachments"][0]["content_transfer_encoding"], "quoted-printable"
+ )
+ self.assertEqual(result["attachments"][0]["charset"], "iso-8859-1")
+ self.assertEqual(result["attachments"][0]["content-disposition"], "inline")
+
+ mail = mailparser.parse_from_file(mail_malformed_1)
+ attachments = mail.mail["attachments"]
+ self.assertEqual(attachments[0]["content-disposition"], "")
+
+ def test_classmethods(self):
+ # MailParser.from_file
+ m = mailparser.MailParser.from_file(mail_test_3)
+ m.parse()
+ result = m.mail
+ self.assertEqual(len(result["attachments"]), 1)
+
+ # MailParser.from_string
+ m = mailparser.MailParser.from_string(m.message_as_string)
+ m.parse()
+ result = m.mail
+ self.assertEqual(len(result["attachments"]), 1)
+
+ def test_bug_UnicodeDecodeError(self):
+ m = mailparser.parse_from_file(mail_test_6)
+ self.assertIsInstance(m.mail, dict)
+ self.assertIsInstance(m.mail_json, str)
+
+ @patch("mailparser.core.os.remove")
+ @patch("mailparser.core.msgconvert")
+ def test_parse_from_file_msg(self, mock_msgconvert, mock_remove):
+ """
+ Tested mail from VirusTotal: md5 b89bf096c9e3717f2d218b3307c69bd0
+
+ The email used for unittest were found randomly on VirusTotal and
+ then already publicly available so can not be considered
+ as privacy violation
+ """
+ mock_msgconvert.return_value = (mail_test_2, None)
+ m = mailparser.parse_from_file_msg(mail_outlook_1)
+ mock_remove.assert_called_once_with(mail_test_2)
+ email = m.mail
+ self.assertIn("attachments", email)
+ self.assertEqual(len(email["attachments"]), 3)
+ self.assertIn("from", email)
+ self.assertEqual(email["from"][0][1], "meteo@regione.vda.it")
+ self.assertIn("subject", email)
+
+ def test_from_file_obj(self):
+ with ported_open(mail_test_2) as fp:
+ mail = mailparser.parse_from_file_obj(fp)
+ trust = "smtp.customers.net"
+
+ self.assertFalse(mail.has_defects)
+
+ result = mail.mail
+ self.assertIsInstance(result, dict)
+ self.assertNotIn("defects", result)
+ self.assertNotIn("anomalies", result)
+ self.assertIn("has_defects", result)
+
+ result = mail.get_server_ipaddress(trust)
+ self.assertIsInstance(result, str)
+
+ result = mail.mail_json
+ self.assertIsInstance(result, str)
+
+ result = mail.headers
+ self.assertIsInstance(result, dict)
+
+ result = mail.headers_json
+ self.assertIsInstance(result, str)
+
+ result = mail.body
+ self.assertIsInstance(result, str)
+
+ result = mail.date
+ self.assertIsInstance(result, datetime.datetime)
+
+ result = mail.from_
+ self.assertIsInstance(result, list)
+
+ result = mail.to
+ self.assertIsInstance(result, list)
+ self.assertEqual(len(result), 2)
+ self.assertIsInstance(result[0], tuple)
+ self.assertEqual(len(result[0]), 2)
+
+ result = mail.subject
+ self.assertIsInstance(result, str)
+
+ result = mail.message_id
+ self.assertIsInstance(result, str)
+
+ result = mail.attachments
+ self.assertIsInstance(result, list)
+
+ result = mail.date
+ self.assertIsInstance(result, datetime.datetime)
+
+ result = mail.defects
+ self.assertIsInstance(result, list)
+
+ result = mail.timezone
+ self.assertEqual(result, "+1.0")
+
+ def test_get_to_domains(self):
+ m = mailparser.parse_from_file(mail_test_6)
+
+ domains_1 = get_to_domains(m.to, m.reply_to)
+ self.assertIsInstance(domains_1, list)
+ self.assertIn("test.it", domains_1)
+
+ domains_2 = m.to_domains
+ self.assertIsInstance(domains_2, list)
+ self.assertIn("test.it", domains_2)
+ self.assertEqual(domains_1, domains_2)
+
+ self.assertIsInstance(m.to_domains_json, str)
+
+ def test_convert_mail_date(self):
+ s = "Mon, 20 Mar 2017 05:12:54 +0600"
+ d, t = convert_mail_date(s)
+ self.assertEqual(t, "+6.0")
+ self.assertEqual(str(d), "2017-03-19 23:12:54+00:00")
+ s = "Mon, 20 Mar 2017 05:12:54 -0600"
+ d, t = convert_mail_date(s)
+ self.assertEqual(t, "-6.0")
+ s = "Mon, 11 Dec 2017 15:27:44 +0530"
+ d, t = convert_mail_date(s)
+ self.assertEqual(t, "+5.5")
+
+ def test_ported_string(self):
+ raw_data = ""
+ s = ported_string(raw_data)
+ self.assertEqual(s, str())
+
+ raw_data = "test"
+ s = ported_string(raw_data)
+ self.assertEqual(s, "test")
+
+ def test_parse_domain_with_tld_dot_id(self):
+ """Support for .id tld (Indonesia)"""
+ received = """
+ from web.myhost.id
+ by smtp.domain.id (Proxmox) with ESMTPS id SOMEIDHERE
+ for ; Wed, 19 Feb 2025 15:00:00 +0700 (WIB)
+ """.strip()
+
+ expected = {
+ "from": "web.myhost.id",
+ "by": "smtp.domain.id (Proxmox)",
+ "with": "ESMTPS",
+ "id": "SOMEIDHERE",
+ "for": "",
+ "date": "Wed, 19 Feb 2025 15:00:00 +0700 (WIB)",
+ }
+
+ values_by_clause = parse_received(received)
+
+ self.assertEqual(expected, values_by_clause)
+
+ def test_parse_domain_with_tld_dot_by(self):
+ """Support for .by tld (Belarus)"""
+ received = """
+ from web.myhost.by
+ by smtp.domain.by (Proxmox) with ESMTPS id SOMEIDHERE
+ for ; Wed, 19 Feb 2025 15:00:00 +0700 (WIB)
+ """.strip()
+
+ expected = {
+ "from": "web.myhost.by",
+ "by": "smtp.domain.by (Proxmox)",
+ "with": "ESMTPS",
+ "id": "SOMEIDHERE",
+ "for": "",
+ "date": "Wed, 19 Feb 2025 15:00:00 +0700 (WIB)",
+ }
+
+ values_by_clause = parse_received(received)
+
+ self.assertEqual(expected, values_by_clause)
+
+ def test_standard_outlook(self):
+ """Verify a basic outlook received header works."""
+ received = """
+ from DM3NAM03FT035
+ by CY4PR0601CA0051.outlook.office365.com
+ with Microsoft SMTP Server version=TLS1_2, cipher=TLS
+ id 15.20.1185.23
+ via Frontend Transport; Mon, 1 Oct 2018 09:49:21 +0000
+ """.strip()
+
+ expected = {
+ "from": "DM3NAM03FT035",
+ "by": "CY4PR0601CA0051.outlook.office365.com",
+ "with": "Microsoft SMTP Server version=TLS1_2, cipher=TLS",
+ "id": "15.20.1185.23",
+ "via": "Frontend Transport",
+ "date": "Mon, 1 Oct 2018 09:49:21 +0000",
+ }
+ values_by_clause = parse_received(received)
+
+ self.assertEqual(expected, values_by_clause)
+
+ def test_standard_google__with_cipher(self):
+ """Verify that we don't match 'with cipher' a la google."""
+ received = """
+ from mail_yw1_f65.google.com
+ by subdomain.domain.com Postfix with ESMTPS
+ id abc123 for ;
+ Tue, 25 Sep 2018 13:09:36 +0000 (UTC)"""
+
+ expected = {
+ "from": "mail_yw1_f65.google.com",
+ "by": "subdomain.domain.com Postfix",
+ "with": "ESMTPS",
+ "id": "abc123",
+ "for": "",
+ "date": "Tue, 25 Sep 2018 13:09:36 +0000 (UTC)",
+ }
+ values_by_clause = parse_received(received)
+ self.assertEqual(expected, values_by_clause)
+
+ @unittest.skipIf(sys.version_info[0] < 3, "Must be using Python 3")
+ def test_parse_from_bytes(self):
+ with open(mail_test_2, "rb") as f:
+ mail_bytes = f.read()
+
+ mail = mailparser.parse_from_bytes(mail_bytes)
+ trust = "smtp.customers.net"
+
+ self.assertFalse(mail.has_defects)
+
+ raw = "217.76.210.112"
+ result = mail.get_server_ipaddress(trust)
+ self.assertEqual(raw, result)
+
+ raw = "<4516257BC5774408ADC1263EEBBBB73F@ad.regione.vda.it>"
+ result = mail.message_id
+ self.assertEqual(raw, result)
+
+ raw = "echo@tu-berlin.de"
+ result = mail.to
+ self.assertEqual(len(result), 2)
+ self.assertIsInstance(result, list)
+ self.assertIsInstance(result[0], tuple)
+ self.assertIsInstance(mail.to_json, str)
+ self.assertIsInstance(mail.to_raw, str)
+ self.assertEqual(raw, result[0][1])
+
+ raw = "meteo@regione.vda.it"
+ result = mail.from_
+ self.assertEqual(raw, result[0][1])
+
+ raw = "Bollettino Meteorologico del 29/11/2015"
+ result = mail.subject
+ self.assertEqual(raw, result)
+
+ result = mail.has_defects
+ self.assertFalse(result)
+
+ result = len(mail.attachments)
+ self.assertEqual(3, result)
+
+ self.assertIsInstance(mail.date_raw, str)
+ self.assertIsInstance(mail.date_json, str)
+ raw_utc = "2015-11-29T08:45:18+00:00"
+ result = mail.date.isoformat()
+ self.assertEqual(raw_utc, result)
+
+ def test_write_uuencode_attachment(self):
+ mail = mailparser.parse_from_file(mail_test_15)
+ temp_dir = tempfile.mkdtemp()
+ mail.write_attachments(temp_dir)
+ md5 = hashlib.md5()
+ with open(os.path.join(temp_dir, "REQUEST FOR QUOTE.zip"), "rb") as f:
+ md5.update(f.read())
+ shutil.rmtree(temp_dir)
+ self.assertEqual(md5.hexdigest(), "4f2cf891e7cfb349fca812091f184ecc")
+
+ def test_issue_139(self):
+ mail = mailparser.parse_from_file(mail_test_16)
+ assert mail.headers == {
+ "MIME-Version": "1.0",
+ "Precedence": "junk",
+ "Content-Type": "text/plain; charset=us-ascii",
+ "From": [("Sender", "sender@example.net")],
+ "Date": "Wed, 23 Jul 2003 23:30:00 +0200",
+ "Content-Transfer-Encoding": "7bit",
+ "Message-ID": "",
+ "Subject": "Test spam mail (GTUBE)",
+ "To": [("Recipient", "recipient@example.net")],
+ }
+
+ def test_issue_136(self):
+ mail = mailparser.parse_from_file(mail_test_17)
+ assert mail.from_ == [
+ ("", "notificaccion-clientes@bbva.mx"),
+ ]
+
+ def test_str_method_with_message(self):
+ """Test __str__ method returns subject when message exists"""
+ mail = mailparser.parse_from_file(mail_test_1)
+ str_result = str(mail)
+ self.assertEqual(str_result, mail.subject)
+
+ def test_str_method_without_message(self):
+ """Test __str__ method returns empty string when no message"""
+ # Create a MailParser with None message
+ parser = mailparser.MailParser.__new__(mailparser.MailParser)
+ parser._message = None
+ str_result = str(parser)
+ self.assertEqual(str_result, "")
+
+ def test_from_file_obj_seekable(self):
+ """Test from_file_obj with seekable file object"""
+ import os
+ import tempfile
+
+ content = "From: test@example.com\nSubject: Test Seekable\n\nBody"
+ # Create a real file to test seekable behavior
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".eml") as f:
+ f.write(content)
+ fname = f.name
+
+ try:
+ with ported_open(fname) as fp:
+ mail = mailparser.parse_from_file_obj(fp)
+ self.assertEqual(mail.subject, "Test Seekable")
+ finally:
+ os.unlink(fname)
+
+ def test_from_file_obj_non_seekable(self):
+ """Test from_file_obj with non-seekable file object (like stdin/TTY)"""
+ import io
+
+ content = "From: test@example.com\nSubject: Test Non-Seekable\n\nBody"
+
+ # Create a mock non-seekable file object that acts like text
+ class NonSeekableIO(io.StringIO):
+ def seek(self, *args):
+ raise OSError("File is not seekable")
+
+ fp = NonSeekableIO(content)
+
+ mail = mailparser.parse_from_file_obj(fp)
+ self.assertEqual(mail.subject, "Test Non-Seekable")
+
+ def test_get_server_ipaddress_invalid_ip(self):
+ """Test get_server_ipaddress with invalid IP that raises ValueError"""
+ # Create mail with received header containing invalid IP
+ raw_mail = """Received: from invalid.example.com (999.999.999.999)
+ by mail.example.com
+Subject: Test
+From: test@example.com
+
+Body"""
+ mail = mailparser.parse_from_string(raw_mail)
+
+ # Should return None for invalid IP
+ result = mail.get_server_ipaddress("trust")
+ # The IP validation should fail and return None
+ self.assertIsNone(result)
+
+ def test_get_server_ipaddress_private_ip(self):
+ """Test get_server_ipaddress with private IP address"""
+ raw_mail = """Received: from internal.example.com (192.168.1.100)
+ by mail.example.com
+Subject: Test
+From: test@example.com
+
+Body"""
+ mail = mailparser.parse_from_string(raw_mail)
+
+ # Private IP should return None
+ result = mail.get_server_ipaddress("trust")
+ self.assertIsNone(result)
+
+ def test_epilogue_parsing_typeerror(self):
+ """Test epilogue parsing with TypeError"""
+ # Create mail with problematic epilogue that causes TypeError
+ # This is edge case where epilogue exists but can't be parsed
+ raw_mail = """Content-Type: multipart/mixed; boundary=boundary
+
+--boundary
+Content-Type: text/plain
+
+Test
+--boundary--
+InvalidEpilogueData"""
+
+ mail = mailparser.parse_from_string(raw_mail)
+ # Should handle TypeError gracefully
+ self.assertIsNotNone(mail)
+
+ def test_epilogue_parsing_typeerror_coverage(self):
+ """Test epilogue parsing TypeError exception handler coverage"""
+ import email
+ from unittest.mock import patch
+
+ # Create a mail with StartBoundaryNotFoundDefect to trigger epilogue parsing
+ raw_mail = """Content-Type: multipart/mixed; boundary="boundary123"
+
+--boundary123
+Content-Type: text/plain
+
+Test content
+--boundary123--
+Extra epilogue content here"""
+
+ # Parse to get the message
+ msg = email.message_from_string(raw_mail)
+
+ # Mock email.message_from_string to raise TypeError
+ with patch("email.message_from_string") as mock_parse:
+ # First call is for initial parsing (let it pass)
+ # Second call is for epilogue parsing (raise TypeError)
+ mock_parse.side_effect = [msg, TypeError("Test TypeError")]
+
+ # This won't trigger the epilogue path without defects
+ # So we need to mock find_between to return something
+ with patch("mailparser.core.find_between") as mock_find:
+ mock_find.return_value = "epilogue content"
+
+ # Mock the message to have epilogue defects
+ with patch.object(
+ mailparser.MailParser,
+ "defects_categories",
+ {"StartBoundaryNotFoundDefect"},
+ ):
+ mail = mailparser.parse_from_string(raw_mail)
+ # Should handle TypeError and continue
+ self.assertIsNotNone(mail)
+
+ def test_epilogue_parsing_general_exception_coverage(self):
+ """Test epilogue parsing general Exception handler coverage"""
+ import email
+ from unittest.mock import patch
+
+ # Create a mail with boundary
+ raw_mail = """Content-Type: multipart/mixed; boundary="boundary123"
+
+--boundary123
+Content-Type: text/plain
+
+Test content
+--boundary123--
+Extra epilogue content"""
+
+ # Parse to get the message
+ msg = email.message_from_string(raw_mail)
+
+ # Mock email.message_from_string to raise a general Exception
+ with patch("email.message_from_string") as mock_parse:
+ mock_parse.side_effect = [msg, Exception("General error")]
+
+ with patch("mailparser.core.find_between") as mock_find:
+ mock_find.return_value = "epilogue content"
+
+ # Mock defects_categories to trigger epilogue parsing
+ with patch.object(
+ mailparser.MailParser,
+ "defects_categories",
+ {"StartBoundaryNotFoundDefect"},
+ ):
+ mail = mailparser.parse_from_string(raw_mail)
+ # Should handle Exception and log error
+ self.assertIsNotNone(mail)
+
+ def test_attachment_with_content_id_no_subtype(self):
+ """Test attachment handling with content-id but no html/plain subtype"""
+ raw_mail = """Content-Type: multipart/mixed; boundary=boundary
+
+--boundary
+Content-Type: image/png
+Content-ID:
+
+ImageData
+--boundary--"""
+
+ mail = mailparser.parse_from_string(raw_mail)
+ self.assertGreater(len(mail.attachments), 0)
+
+ def test_attachment_rtf_type(self):
+ """Test attachment handling for RTF content subtype"""
+ raw_mail = """Content-Type: multipart/mixed; boundary=boundary
+
+--boundary
+Content-Type: application/rtf
+
+RTFData
+--boundary--"""
+
+ mail = mailparser.parse_from_string(raw_mail)
+ attachments = mail.attachments
+ self.assertGreater(len(attachments), 0)
+ # Should have generated RTF filename
+ self.assertTrue(any(".rtf" in att.get("filename", "") for att in attachments))
+
+ def test_attachment_disposition_without_filename(self):
+ """Test attachment with content-disposition but no filename"""
+ raw_mail = """Content-Type: multipart/mixed; boundary=boundary
+
+--boundary
+Content-Type: text/plain
+Content-Disposition: attachment
+
+PlainTextData
+--boundary--"""
+
+ mail = mailparser.parse_from_string(raw_mail)
+ attachments = mail.attachments
+ self.assertGreater(len(attachments), 0)
+ # Should have generated .txt filename
+ self.assertTrue(any(".txt" in att.get("filename", "") for att in attachments))
+
+ def test_text_plain_7bit_encoding(self):
+ """Test text/plain body part with 7bit encoding"""
+ raw_mail = """Content-Type: text/plain
+Content-Transfer-Encoding: 7bit
+
+This is plain text with 7bit encoding."""
+
+ mail = mailparser.parse_from_string(raw_mail)
+ self.assertIn("This is plain text", mail.body)
+
+ def test_text_plain_8bit_encoding(self):
+ """Test text/plain body part with 8bit encoding"""
+ raw_mail = """Content-Type: text/plain; charset=utf-8
+Content-Transfer-Encoding: 8bit
+
+This is plain text with 8bit encoding."""
+
+ mail = mailparser.parse_from_string(raw_mail)
+ self.assertIn("This is plain text", mail.body)
+
+ def test_comma_in_name(self):
+ """
+ Tests the fixes for both the 'comma-in-encoded-name' issue and the
+ 'encoded-name-equals-email' issue (from test_issue_136).
+ """
+
+ mail = mailparser.parse_from_file(mail_test_18)
+
+ assert mail.from_ == [("LastßlName, FirstName", "comma.name@example.com")]
+ assert mail.to == [("", "tony.stark@example.com")]
+ assert mail.cc == [
+ ("", "simple@example.net"),
+ ('John "Johnny" Doe', "john.doe@example.com"),
+ ]
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_main.py b/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc891628409087d1621298fb392132b115ae4d30
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_main.py
@@ -0,0 +1,346 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2017 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from mailparser.__main__ import get_args, process_output
+
+
+@pytest.fixture
+def parser():
+ return get_args()
+
+
+class TestMain:
+ def test_required(self, parser):
+ with pytest.raises(SystemExit):
+ parser.parse_args(["--file", "test", "--string", "test"])
+
+ with pytest.raises(SystemExit):
+ parser.parse_args(["--file", "test", "--stdin"])
+
+ with pytest.raises(SystemExit):
+ parser.parse_args(["--file"])
+
+ with pytest.raises(SystemExit):
+ parser.parse_args(["--string"])
+
+ def test_options(self, parser):
+ args = parser.parse_args(["--file", "mail.eml"])
+ assert args.file == "mail.eml"
+
+ args = parser.parse_args(["--string", "mail.str"])
+ assert args.string == "mail.str"
+
+ args = parser.parse_args(["--file", "mail.eml", "--json"])
+ assert args.json
+
+ args = parser.parse_args(["--file", "mail.eml", "--body"])
+ assert args.body
+
+ args = parser.parse_args(["--file", "mail.eml", "-a"])
+ assert args.attachments
+
+ args = parser.parse_args(["--file", "mail.eml", "-r"])
+ assert args.headers
+
+ args = parser.parse_args(["--file", "mail.eml", "--to"])
+ assert args.to
+
+ args = parser.parse_args(["--file", "mail.eml", "--from"])
+ assert args.from_
+
+ args = parser.parse_args(["--file", "mail.eml", "-u"])
+ assert args.subject
+
+ args = parser.parse_args(["--file", "mail.eml", "-d"])
+ assert args.defects
+
+ args = parser.parse_args(["--file", "mail.eml", "--senderip", "trust"])
+ assert args.senderip
+
+ args = parser.parse_args(["--file", "mail.eml", "-p"])
+ assert args.mail_hash
+
+ args = parser.parse_args(["--file", "mail.eml", "--attachments-hash"])
+ assert args.attachments_hash
+
+ args = parser.parse_args(["--file", "mail.eml", "-c"])
+ assert args.receiveds
+
+ @pytest.mark.parametrize(
+ "args, patch_process_output, mocked",
+ [
+ (
+ ["--file", "mail.eml", "--json"],
+ "mailparser.__main__.safe_print",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--body"],
+ "mailparser.__main__.safe_print",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--headers"],
+ "mailparser.__main__.safe_print",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--to"],
+ "mailparser.__main__.safe_print",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--delivered-to"],
+ "mailparser.__main__.safe_print",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--from"],
+ "mailparser.__main__.safe_print",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--subject"],
+ "mailparser.__main__.safe_print",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--receiveds"],
+ "mailparser.__main__.safe_print",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--defects"],
+ "mailparser.__main__.print_defects",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--senderip", "server"],
+ "mailparser.__main__.print_sender_ip",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--attachments"],
+ "mailparser.__main__.print_attachments_details",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--attachments-hash"],
+ "mailparser.__main__.print_attachments_details",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--mail-hash"],
+ "mailparser.__main__.print_mail_fingerprints",
+ MagicMock(),
+ ),
+ (
+ ["--file", "mail.eml", "--store-attachments"],
+ "mailparser.__main__.write_attachments",
+ MagicMock(),
+ ),
+ ],
+ )
+ def test_process_output(
+ self,
+ args,
+ patch_process_output,
+ mocked,
+ parser,
+ ):
+ args = parser.parse_args(args)
+ with patch(patch_process_output) as mock:
+ process_output(args, mocked)
+ mock.assert_called_once()
+
+ def test_main_success(self, parser, tmp_path):
+ """Test main function with successful execution"""
+ import mailparser.__main__ as main_module
+
+ # Create a test mail file
+ test_mail = tmp_path / "test.eml"
+ test_mail.write_text("From: test@example.com\nSubject: Test\n\nBody")
+
+ with patch("sys.argv", ["mail-parser", "--file", str(test_mail), "--json"]):
+ with patch("mailparser.__main__.safe_print") as mock_print:
+ # main() doesn't necessarily exit, it just processes
+ main_module.main()
+ # Verify that safe_print was called (output was produced)
+ assert mock_print.called
+
+ def test_main_with_exception(self):
+ """Test main function when an exception occurs"""
+ import mailparser.__main__ as main_module
+
+ with patch("sys.argv", ["mail-parser", "--file", "nonexistent.eml"]):
+ with pytest.raises(SystemExit) as exc_info:
+ main_module.main()
+ assert exc_info.value.code == 1
+
+ def test_get_parser_with_file(self, parser, tmp_path):
+ """Test get_parser with file input"""
+ from mailparser.__main__ import get_parser
+
+ test_mail = tmp_path / "test.eml"
+ test_mail.write_text("From: test@example.com\nSubject: Test\n\nBody")
+
+ args = parser.parse_args(["--file", str(test_mail)])
+ result = get_parser(args)
+ assert result is not None
+ assert result.subject == "Test"
+
+ def test_get_parser_with_string(self, parser):
+ """Test get_parser with string input"""
+ from mailparser.__main__ import get_parser
+
+ args = parser.parse_args(
+ ["--string", "From: test@example.com\nSubject: Test\n\nBody"]
+ )
+ result = get_parser(args)
+ assert result is not None
+ assert result.subject == "Test"
+
+ def test_get_parser_with_no_input(self, parser):
+ """Test get_parser raises ValueError when no input provided"""
+ from unittest.mock import Mock
+
+ from mailparser.__main__ import get_parser
+
+ # Create mock args with no input source
+ args = Mock()
+ args.file = None
+ args.string = None
+ args.stdin = None
+
+ with pytest.raises(ValueError, match="No input source provided"):
+ get_parser(args)
+
+ def test_parse_file_outlook(self, parser, tmp_path):
+ """Test parse_file with Outlook flag"""
+ from unittest.mock import patch
+
+ from mailparser.__main__ import parse_file
+ from mailparser.exceptions import MailParserOSError
+
+ # Create a non-existent file path
+ non_existent_file = str(tmp_path / "non_existent.msg")
+ args = parser.parse_args(["--file", non_existent_file, "--outlook"])
+
+ # Mock msgconvert to raise OSError (simulating msgconvert unavailable)
+ with patch(
+ "mailparser.utils.subprocess.Popen",
+ side_effect=OSError("msgconvert not found"),
+ ):
+ with pytest.raises(MailParserOSError, match="msgconvert"):
+ parse_file(args)
+
+ def test_parse_stdin(self, parser):
+ """Test parse_stdin function"""
+ import io
+
+ from mailparser.__main__ import parse_stdin
+
+ test_content = "From: test@example.com\nSubject: Test from stdin\n\nBody"
+
+ args = parser.parse_args(["--stdin"])
+
+ with patch("sys.stdin", io.StringIO(test_content)):
+ result = parse_stdin(args)
+ assert result is not None
+ assert result.subject == "Test from stdin"
+
+ def test_parse_stdin_outlook_error(self, parser):
+ """Test parse_stdin raises error for Outlook files"""
+ from mailparser.__main__ import parse_stdin
+ from mailparser.exceptions import MailParserOutlookError
+
+ args = parser.parse_args(["--stdin", "--outlook"])
+
+ with pytest.raises(
+ MailParserOutlookError, match="You can't use stdin with msg Outlook"
+ ):
+ parse_stdin(args)
+
+ def test_print_defects(self, parser, tmp_path):
+ """Test print_defects function"""
+ import mailparser
+ from mailparser.__main__ import print_defects
+
+ # Use a malformed email to get defects
+ test_mail = tmp_path / "malformed.eml"
+ test_mail.write_text(
+ "Content-Type: multipart/mixed; boundary=boundary\n\n"
+ "--wrongboundary\n"
+ "Content-Type: text/plain\n\n"
+ "Test\n"
+ )
+
+ mail = mailparser.parse_from_file(str(test_mail))
+
+ with patch("mailparser.__main__.safe_print") as mock_print:
+ print_defects(mail)
+ assert mock_print.called
+
+ def test_print_sender_ip(self, parser):
+ """Test print_sender_ip function"""
+ from unittest.mock import Mock
+
+ from mailparser.__main__ import print_sender_ip
+
+ mock_parser = Mock()
+ mock_parser.get_server_ipaddress.return_value = "192.168.1.1"
+
+ args = parser.parse_args(["--file", "test.eml", "--senderip", "trust"])
+
+ with patch("mailparser.__main__.safe_print") as mock_print:
+ print_sender_ip(mock_parser, args)
+ mock_print.assert_called_once_with("192.168.1.1")
+
+ def test_print_sender_ip_not_found(self, parser):
+ """Test print_sender_ip when IP not found"""
+ from unittest.mock import Mock
+
+ from mailparser.__main__ import print_sender_ip
+
+ mock_parser = Mock()
+ mock_parser.get_server_ipaddress.return_value = None
+
+ args = parser.parse_args(["--file", "test.eml", "--senderip", "trust"])
+
+ with patch("mailparser.__main__.safe_print") as mock_print:
+ print_sender_ip(mock_parser, args)
+ mock_print.assert_called_once_with("Not Found")
+
+ def test_print_attachments_details(self, parser):
+ """Test print_attachments_details function"""
+ from unittest.mock import Mock
+
+ from mailparser.__main__ import print_attachments_details
+
+ mock_parser = Mock()
+ mock_parser.attachments = [{"filename": "test.txt", "payload": "data"}]
+
+ args = parser.parse_args(["--file", "test.eml", "--attachments"])
+
+ with patch("mailparser.__main__.print_attachments") as mock_print:
+ print_attachments_details(mock_parser, args)
+ mock_print.assert_called_once_with(mock_parser.attachments, False)
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_utils.py b/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..aea76b779f8330237b436dbd322f5978f4062f5f
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/tests/test_utils.py
@@ -0,0 +1,588 @@
+#!/usr/bin/env python
+
+"""
+Copyright 2017 Fedele Mantuano (https://twitter.com/fedelemantuano)
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import base64
+import os
+import tempfile
+import unittest
+from unittest.mock import Mock, patch
+
+from mailparser.exceptions import MailParserOSError, MailParserReceivedParsingError
+from mailparser.utils import (
+ decode_header_part,
+ find_between,
+ msgconvert,
+ parse_received,
+ ported_open,
+ ported_string,
+ receiveds_parsing,
+)
+
+
+class TestUtils(unittest.TestCase):
+ def test_ported_string_with_invalid_encoding(self):
+ """Test ported_string with invalid encoding falls back to utf-8"""
+ # Test with invalid encoding name
+ data = b"Test data"
+ result = ported_string(data, encoding="invalid-encoding-name")
+ self.assertEqual(result, "Test data")
+
+ def test_ported_string_unicode_decode_error(self):
+ """Test ported_string handles UnicodeDecodeError"""
+ # Create data that will cause UnicodeDecodeError with certain encoding
+ data = b"\xff\xfe" # Invalid UTF-8 sequence
+ result = ported_string(data, encoding="ascii")
+ # Should fall back to utf-8 with errors='ignore'
+ self.assertIsInstance(result, str)
+
+ def test_decode_header_part_with_header_parse_error(self):
+ """Test decode_header_part handles HeaderParseError"""
+ from email.errors import HeaderParseError
+
+ # Mock decode_header to raise HeaderParseError
+ with patch(
+ "mailparser.utils.decode_header",
+ side_effect=HeaderParseError("Header parsing failed"),
+ ):
+ result = decode_header_part("problematic_header")
+ # Should return the original header on error
+ self.assertEqual(result, "problematic_header")
+
+ def test_find_between_with_value_error(self):
+ """Test find_between when tokens not found"""
+ result = find_between("text without tokens", "START", "END")
+ self.assertIsNone(result)
+
+ def test_msgconvert_oserror(self):
+ """Test msgconvert raises MailParserOSError when tool not found"""
+ with tempfile.NamedTemporaryFile(suffix=".msg", delete=False) as tmp:
+ tmp_name = tmp.name
+
+ try:
+ # Mock subprocess.Popen to raise OSError
+ with patch("subprocess.Popen", side_effect=OSError("Command not found")):
+ with self.assertRaises(MailParserOSError) as context:
+ msgconvert(tmp_name)
+ self.assertIn("msgconvert", str(context.exception))
+ finally:
+ if os.path.exists(tmp_name):
+ os.unlink(tmp_name)
+
+ def test_msgconvert_success(self):
+ """Test msgconvert successful execution"""
+ with tempfile.NamedTemporaryFile(suffix=".msg", delete=False) as tmp:
+ tmp_name = tmp.name
+
+ try:
+ # Mock successful subprocess execution
+ mock_process = Mock()
+ mock_process.communicate.return_value = (
+ b"Conversion successful",
+ b"",
+ )
+
+ with patch("subprocess.Popen", return_value=mock_process):
+ temp_file, stdout = msgconvert(tmp_name)
+ self.assertIsInstance(temp_file, str)
+ self.assertEqual(stdout, "Conversion successful")
+ # Clean up the temp file
+ if os.path.exists(temp_file):
+ os.unlink(temp_file)
+ finally:
+ if os.path.exists(tmp_name):
+ os.unlink(tmp_name)
+
+ def test_parse_received_no_matches(self):
+ """Test parse_received with header that matches nothing"""
+ # Header that doesn't match any patterns
+ received = "InvalidReceivedHeader"
+
+ with self.assertRaises(MailParserReceivedParsingError) as context:
+ parse_received(received)
+ self.assertIn("Unable to match any clauses", str(context.exception))
+
+ def test_parse_received_multiple_matches(self):
+ """Test parse_received with header that has multiple matches for one pattern"""
+ # This is a complex edge case - create header with duplicate clause
+ # Note: This is hard to trigger with real data, but tests the error handling
+ received = "from server1 from server2 by mail.example.com"
+
+ # The function should handle this, might raise error or process normally
+ # depending on the regex patterns
+ try:
+ result = parse_received(received)
+ # If it succeeds, result should be a dict
+ self.assertIsInstance(result, dict)
+ except MailParserReceivedParsingError: # pragma: no cover
+ # This is also acceptable - it means the parser detected the issue
+ pass
+
+ def test_receiveds_parsing_mismatch_length(self):
+ """Test receiveds_parsing when parsing fails"""
+ # Test with receiveds that will fail to parse
+ receiveds = ["InvalidReceivedHeader1", "InvalidReceivedHeader2"]
+
+ # These should all fail to parse and fall back to raw format
+ result = receiveds_parsing(receiveds)
+ self.assertIsInstance(result, list)
+ self.assertEqual(len(result), len(receiveds))
+ # Should have 'raw' key in the results
+ self.assertTrue(all("raw" in r or "from" in r for r in result))
+
+ def test_ported_open_python3(self):
+ """Test ported_open in Python 3"""
+ with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as tmp:
+ tmp.write("test content")
+ tmp_name = tmp.name
+
+ try:
+ with ported_open(tmp_name) as f:
+ content = f.read()
+ self.assertEqual(content, "test content")
+ finally:
+ os.unlink(tmp_name)
+
+
+class TestUtilsEdgeCases(unittest.TestCase):
+ def test_parse_received_with_junk_pattern(self):
+ """Test receiveds_parsing removes junk patterns"""
+ # Test that JUNK_PATTERN is properly applied
+ receiveds = ["Received: from server.example.com\n\tby mail.example.com"]
+
+ result = receiveds_parsing(receiveds)
+ self.assertIsInstance(result, list)
+ self.assertGreater(len(result), 0)
+
+ def test_decode_header_part_unicode_error(self):
+ """Test decode_header_part with UnicodeError"""
+ # Mock decode_header to raise UnicodeError
+ with patch("mailparser.utils.decode_header", side_effect=UnicodeError()):
+ result = decode_header_part("test_header")
+ self.assertEqual(result, "test_header")
+
+ def test_ported_string_empty_input(self):
+ """Test ported_string with empty input"""
+ result = ported_string(None)
+ self.assertEqual(result, "")
+
+ result = ported_string("")
+ self.assertEqual(result, "")
+
+ def test_ported_string_already_string(self):
+ """Test ported_string with str input (no conversion needed)"""
+ test_str = "Already a string"
+ result = ported_string(test_str)
+ self.assertEqual(result, test_str)
+
+ def test_ported_string_successful_decode(self):
+ """Test ported_string successful decoding with specified encoding"""
+ data = "test".encode("utf-8")
+ result = ported_string(data, encoding="utf-8")
+ self.assertEqual(result, "test")
+
+ def test_decode_header_part_empty(self):
+ """Test decode_header_part with empty header"""
+ result = decode_header_part("")
+ self.assertEqual(result, "")
+
+ result = decode_header_part(None)
+ self.assertEqual(result, "")
+
+ def test_find_between_successful(self):
+ """Test find_between with successful extraction"""
+ from mailparser.utils import find_between
+
+ text = "prefixsuffix"
+ result = find_between(text, "<", ">")
+ self.assertEqual(result, "content")
+
+ def test_find_between_with_whitespace(self):
+ """Test find_between strips whitespace"""
+ from mailparser.utils import find_between
+
+ text = "prefix< content >suffix"
+ result = find_between(text, "<", ">")
+ self.assertEqual(result, "content")
+
+ def test_fingerprints_with_string_input(self):
+ """Test fingerprints with string input (should encode to bytes)"""
+ from mailparser.utils import fingerprints
+
+ result = fingerprints("test data")
+ self.assertIsNotNone(result.md5)
+ self.assertIsNotNone(result.sha1)
+ self.assertIsNotNone(result.sha256)
+ self.assertIsNotNone(result.sha512)
+
+ def test_fingerprints_with_bytes_input(self):
+ """Test fingerprints with bytes input"""
+ from mailparser.utils import fingerprints
+
+ result = fingerprints(b"test data")
+ self.assertIsNotNone(result.md5)
+ self.assertEqual(len(result.md5), 32)
+ self.assertEqual(len(result.sha1), 40)
+ self.assertEqual(len(result.sha256), 64)
+ self.assertEqual(len(result.sha512), 128)
+
+ def test_parse_received_with_multiple_matches_error(self):
+ """Test parse_received raises error on multiple matches for same pattern"""
+ # This tests the error branch when multiple matches are found
+ # We need a received header that triggers duplicate matches
+ received = (
+ "from server.example.com from server2.example.com by mail.example.com"
+ )
+
+ # Depending on the patterns, this might raise an error or succeed
+ # We test that it handles the scenario correctly
+ try:
+ result = parse_received(received)
+ # If it succeeds, it should return a dict
+ self.assertIsInstance(result, dict)
+ except MailParserReceivedParsingError as e:
+ # This is the expected path for multiple matches
+ self.assertIn("More than one match", str(e))
+
+ def test_get_to_domains_with_keyerror(self):
+ """Test get_to_domains handles KeyError gracefully"""
+ from mailparser.utils import get_to_domains
+
+ # Test with malformed data that could cause KeyError
+ to = [("Name", "email@example.com")]
+ reply_to = [("Name2",)] # Missing email part - could cause KeyError
+
+ result = get_to_domains(to, reply_to)
+ # Should handle the error and return only valid domains
+ self.assertIn("example.com", result)
+
+ def test_get_to_domains_normal(self):
+ """Test get_to_domains with normal input"""
+ from mailparser.utils import get_to_domains
+
+ to = [("User1", "user1@example.com"), ("User2", "user2@test.org")]
+ reply_to = [("User3", "user3@example.com")]
+
+ result = get_to_domains(to, reply_to)
+ self.assertIn("example.com", result)
+ self.assertIn("test.org", result)
+ # Should deduplicate
+ self.assertEqual(result.count("example.com"), 1)
+
+ def test_get_header_no_headers(self):
+ """Test get_header when no headers exist"""
+ from email.message import Message
+
+ from mailparser.utils import get_header
+
+ msg = Message()
+ result = get_header(msg, "X-NonExistent-Header")
+ self.assertEqual(result, "")
+
+ def test_get_header_single_header(self):
+ """Test get_header with single header value"""
+ from email.message import Message
+
+ from mailparser.utils import get_header
+
+ msg = Message()
+ msg["X-Test-Header"] = "Test Value"
+
+ result = get_header(msg, "X-Test-Header")
+ self.assertEqual(result, "Test Value")
+
+ def test_get_header_multiple_headers(self):
+ """Test get_header with multiple header values"""
+ from email.message import Message
+
+ from mailparser.utils import get_header
+
+ msg = Message()
+ msg["Received"] = "from server1"
+ msg["Received"] = "from server2"
+
+ result = get_header(msg, "Received")
+ # Should return a list for multiple headers
+ self.assertIsInstance(result, list)
+ self.assertEqual(len(result), 2)
+
+ def test_get_mail_keys_complete_true(self):
+ """Test get_mail_keys with complete=True"""
+ from email.message import Message
+
+ from mailparser.utils import get_mail_keys
+
+ msg = Message()
+ msg["Subject"] = "Test"
+ msg["From"] = "test@example.com"
+ msg["X-Custom-Header"] = "custom"
+
+ result = get_mail_keys(msg, complete=True)
+ self.assertIsInstance(result, set)
+ self.assertIn("subject", result)
+ self.assertIn("from", result)
+ self.assertIn("x-custom-header", result)
+
+ def test_get_mail_keys_complete_false(self):
+ """Test get_mail_keys with complete=False"""
+ from email.message import Message
+
+ from mailparser.utils import get_mail_keys
+
+ msg = Message()
+ msg["Subject"] = "Test"
+ msg["X-Custom-Header"] = "custom"
+
+ result = get_mail_keys(msg, complete=False)
+ self.assertIsInstance(result, set)
+ # Should only contain standard headers, not custom ones
+ # The custom header should not be included when complete=False
+
+ def test_receiveds_format_successful_parsing(self):
+ """Test receiveds_parsing with successfully parsed headers"""
+ from mailparser.utils import receiveds_parsing
+
+ # Valid received header that should parse successfully
+ receiveds = [
+ "from mail.example.com (mail.example.com [192.168.1.1]) "
+ "by mx.example.org; Mon, 1 Jan 2024 12:00:00 +0000"
+ ]
+
+ result = receiveds_parsing(receiveds)
+ self.assertIsInstance(result, list)
+ self.assertEqual(len(result), 1)
+ # Should have parsed data, not just raw
+ self.assertIn("hop", result[0])
+
+ def test_convert_mail_date(self):
+ """Test convert_mail_date function"""
+ from mailparser.utils import convert_mail_date
+
+ # Test with a valid date string
+ date_str = "Mon, 1 Jan 2024 12:00:00 +0000"
+ date_utc, timezone = convert_mail_date(date_str)
+
+ self.assertIsNotNone(date_utc)
+ self.assertEqual(timezone, "+0.0")
+
+ def test_convert_mail_date_with_timezone(self):
+ """Test convert_mail_date with different timezone"""
+ from mailparser.utils import convert_mail_date
+
+ # Test with PST timezone (-0800)
+ date_str = "Mon, 1 Jan 2024 12:00:00 -0800"
+ date_utc, timezone = convert_mail_date(date_str)
+
+ self.assertIsNotNone(date_utc)
+ self.assertEqual(timezone, "-8.0")
+
+ def test_receiveds_not_parsed(self):
+ """Test receiveds_not_parsed function directly"""
+ from mailparser.utils import receiveds_not_parsed
+
+ receiveds = ["Header1", "Header2", "Header3"]
+ result = receiveds_not_parsed(receiveds)
+
+ self.assertIsInstance(result, list)
+ self.assertEqual(len(result), 3)
+ # Should be in reverse order with hop numbers
+ self.assertEqual(result[0]["hop"], 1)
+ self.assertEqual(result[1]["hop"], 2)
+ self.assertEqual(result[2]["hop"], 3)
+ self.assertIn("raw", result[0])
+
+ def test_receiveds_format(self):
+ """Test receiveds_format function"""
+ from mailparser.utils import receiveds_format
+
+ # Test with basic parsed data
+ parsed = [
+ {"from": "server1.example.com", "by": "server2.example.com"},
+ {"from": "server2.example.com", "by": "server3.example.com"},
+ ]
+
+ result = receiveds_format(parsed)
+ self.assertIsInstance(result, list)
+ self.assertEqual(len(result), 2)
+ # Should add hop numbers
+ self.assertEqual(result[0]["hop"], 1)
+ self.assertEqual(result[1]["hop"], 2)
+
+ def test_receiveds_format_with_dates(self):
+ """Test receiveds_format with date parsing"""
+ from mailparser.utils import receiveds_format
+
+ # Test with dates
+ parsed = [
+ {
+ "from": "server1.example.com",
+ "by": "server2.example.com",
+ "date": "Mon, 1 Jan 2024 12:00:00 +0000",
+ },
+ {
+ "from": "server2.example.com",
+ "by": "server3.example.com",
+ "date": "Mon, 1 Jan 2024 12:01:00 +0000",
+ },
+ ]
+
+ result = receiveds_format(parsed)
+ self.assertIsInstance(result, list)
+ # Should have date_utc and delay calculated
+ if result[0].get("date_utc"):
+ self.assertIn("date_utc", result[0])
+ self.assertIn("delay", result[1])
+
+ def test_receiveds_format_with_invalid_date(self):
+ """Test receiveds_format handles invalid dates"""
+ from mailparser.utils import receiveds_format
+
+ # Test with invalid date that will cause TypeError
+ parsed = [
+ {
+ "from": "server1.example.com",
+ "by": "server2.example.com",
+ "date": "invalid date format",
+ }
+ ]
+
+ result = receiveds_format(parsed)
+ self.assertIsInstance(result, list)
+ # Should handle the error gracefully
+ self.assertEqual(result[0]["date_utc"], None)
+
+ def test_write_sample_binary(self):
+ """Test write_sample with binary file"""
+ import os
+ import tempfile
+
+ from mailparser.utils import write_sample
+
+ temp_dir = tempfile.mkdtemp()
+ try:
+ # Test binary file
+ payload = base64.b64encode(b"test binary content").decode()
+ write_sample(
+ binary=True, payload=payload, path=temp_dir, filename="test_binary.bin"
+ )
+
+ file_path = os.path.join(temp_dir, "test_binary.bin")
+ self.assertTrue(os.path.exists(file_path))
+
+ with open(file_path, "rb") as f:
+ content = f.read()
+ self.assertEqual(content, b"test binary content")
+ finally:
+ # Cleanup
+ import shutil
+
+ shutil.rmtree(temp_dir)
+
+ def test_write_sample_text(self):
+ """Test write_sample with text file"""
+ import os
+ import tempfile
+
+ from mailparser.utils import write_sample
+
+ temp_dir = tempfile.mkdtemp()
+ try:
+ # Test text file
+ write_sample(
+ binary=False,
+ payload="test text content",
+ path=temp_dir,
+ filename="test_text.txt",
+ )
+
+ file_path = os.path.join(temp_dir, "test_text.txt")
+ self.assertTrue(os.path.exists(file_path))
+
+ with open(file_path, "r") as f:
+ content = f.read()
+ self.assertEqual(content, "test text content")
+ finally:
+ # Cleanup
+ import shutil
+
+ shutil.rmtree(temp_dir)
+
+ def test_random_string(self):
+ """Test random_string function"""
+ from mailparser.utils import random_string
+
+ # Test default length
+ result = random_string()
+ self.assertEqual(len(result), 10)
+ self.assertTrue(result.isalpha())
+ self.assertTrue(result.islower())
+
+ # Test custom length
+ result = random_string(20)
+ self.assertEqual(len(result), 20)
+
+ def test_parse_received_single_match_standard_pattern(self):
+ """Test parse_received with exactly one match from standard patterns"""
+ from mailparser.utils import parse_received
+
+ # Use a real received header that will match standard patterns
+ # This should trigger the else block at lines 267-269
+ received = (
+ "from smtprelay.b.hostedemail.com (64.98.42.207) "
+ "by smtp.server.net with SMTP; 22 Aug 2016 14:23:01 -0000"
+ )
+
+ result = parse_received(received)
+
+ # Should successfully parse and return dict
+ self.assertIsInstance(result, dict)
+ # Should have multiple keys extracted
+ self.assertIn("from", result)
+ self.assertIn("by", result)
+ self.assertIn("with", result)
+ self.assertIn("date", result)
+
+ def test_receiveds_format_delay_no_previous_date(self):
+ """Test receiveds_format delay calculation when first entry has no valid date"""
+ from mailparser.utils import receiveds_format
+
+ # NOTE: receiveds_format processes the list in REVERSE order ([::-1])
+ # So we need the second item to have the invalid date
+ # After reversal, invalid date will be first, then valid date second
+ parsed = [
+ {
+ "from": "server1.example.com",
+ "by": "server2.example.com",
+ # Valid date - will be processed second
+ "date": "Mon, 1 Jan 2024 12:01:00 +0000",
+ },
+ {
+ "from": "server2.example.com",
+ "by": "server3.example.com",
+ # Will fail - will be processed first
+ "date": "completely invalid garbage",
+ },
+ ]
+
+ result = receiveds_format(parsed)
+
+ # After reversal, result[0] (hop 1) should have None date
+ self.assertIsNone(result[0].get("date_utc"))
+ # result[1] (hop 2) should have delay=0 because before date is None (line 432)
+ self.assertEqual(result[1]["delay"], 0)
+ # But should have a valid date itself
+ self.assertIsNotNone(result[1].get("date_utc"))
diff --git a/tasks/tasksmith-ae872f5c3953/tests/source/uv.lock b/tasks/tasksmith-ae872f5c3953/tests/source/uv.lock
new file mode 100644
index 0000000000000000000000000000000000000000..9b1a9997a0feffbe358430ab8657253efbae6513
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/source/uv.lock
@@ -0,0 +1,1322 @@
+version = 1
+requires-python = ">=3.9, <3.15"
+resolution-markers = [
+ "python_full_version >= '3.10'",
+ "python_full_version < '3.10'",
+]
+
+[[package]]
+name = "anyio"
+version = "4.9.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "exceptiongroup", marker = "python_full_version < '3.11'" },
+ { name = "idna" },
+ { name = "sniffio" },
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/95/7d/4c1bd541d4dffa1b52bd83fb8527089e097a106fc90b467a7313b105f840/anyio-4.9.0.tar.gz", hash = "sha256:673c0c244e15788651a4ff38710fea9675823028a6f08a5eda409e0c9840a028", size = 190949 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a1/ee/48ca1a7c89ffec8b6a0c5d02b89c305671d5ffd8d3c94acf8b8c408575bb/anyio-4.9.0-py3-none-any.whl", hash = "sha256:9f76d541cad6e36af7beb62e978876f3b41e3e04f2c1fbf0884604c0a9c4d93c", size = 100916 },
+]
+
+[[package]]
+name = "backports-tarfile"
+version = "1.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/86/72/cd9b395f25e290e633655a100af28cb253e4393396264a98bd5f5951d50f/backports_tarfile-1.2.0.tar.gz", hash = "sha256:d75e02c268746e1b8144c278978b6e98e85de6ad16f8e4b0844a154557eca991", size = 86406 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b9/fa/123043af240e49752f1c4bd24da5053b6bd00cad78c2be53c0d1e8b975bc/backports.tarfile-1.2.0-py3-none-any.whl", hash = "sha256:77e284d754527b01fb1e6fa8a1afe577858ebe4e9dad8919e34c862cb399bc34", size = 30181 },
+]
+
+[[package]]
+name = "build"
+version = "1.2.2.post1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "os_name == 'nt'" },
+ { name = "importlib-metadata", marker = "python_full_version < '3.10.2'" },
+ { name = "packaging" },
+ { name = "pyproject-hooks" },
+ { name = "tomli", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/7d/46/aeab111f8e06793e4f0e421fcad593d547fb8313b50990f31681ee2fb1ad/build-1.2.2.post1.tar.gz", hash = "sha256:b36993e92ca9375a219c99e606a122ff365a760a2d4bba0caa09bd5278b608b7", size = 46701 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/84/c2/80633736cd183ee4a62107413def345f7e6e3c01563dbca1417363cf957e/build-1.2.2.post1-py3-none-any.whl", hash = "sha256:1d61c0887fa860c01971625baae8bdd338e517b836a2f70dd1f7aa3a6b2fc5b5", size = 22950 },
+]
+
+[[package]]
+name = "certifi"
+version = "2025.6.15"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/73/f7/f14b46d4bcd21092d7d3ccef689615220d8a08fb25e564b65d20738e672e/certifi-2025.6.15.tar.gz", hash = "sha256:d747aa5a8b9bbbb1bb8c22bb13e22bd1f18e9796defa16bab421f7f7a317323b", size = 158753 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/84/ae/320161bd181fc06471eed047ecce67b693fd7515b16d495d8932db763426/certifi-2025.6.15-py3-none-any.whl", hash = "sha256:2e0c7ce7cb5d8f8634ca55d2ba7e6ec2689a2fd6537d8dec1296a477a4910057", size = 157650 },
+]
+
+[[package]]
+name = "cffi"
+version = "1.17.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pycparser" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/fc/97/c783634659c2920c3fc70419e3af40972dbaf758daa229a7d6ea6135c90d/cffi-1.17.1.tar.gz", hash = "sha256:1c39c6016c32bc48dd54561950ebd6836e1670f2ae46128f67cf49e789c52824", size = 516621 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/90/07/f44ca684db4e4f08a3fdc6eeb9a0d15dc6883efc7b8c90357fdbf74e186c/cffi-1.17.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:df8b1c11f177bc2313ec4b2d46baec87a5f3e71fc8b45dab2ee7cae86d9aba14", size = 182191 },
+ { url = "https://files.pythonhosted.org/packages/08/fd/cc2fedbd887223f9f5d170c96e57cbf655df9831a6546c1727ae13fa977a/cffi-1.17.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8f2cdc858323644ab277e9bb925ad72ae0e67f69e804f4898c070998d50b1a67", size = 178592 },
+ { url = "https://files.pythonhosted.org/packages/de/cc/4635c320081c78d6ffc2cab0a76025b691a91204f4aa317d568ff9280a2d/cffi-1.17.1-cp310-cp310-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:edae79245293e15384b51f88b00613ba9f7198016a5948b5dddf4917d4d26382", size = 426024 },
+ { url = "https://files.pythonhosted.org/packages/b6/7b/3b2b250f3aab91abe5f8a51ada1b717935fdaec53f790ad4100fe2ec64d1/cffi-1.17.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:45398b671ac6d70e67da8e4224a065cec6a93541bb7aebe1b198a61b58c7b702", size = 448188 },
+ { url = "https://files.pythonhosted.org/packages/d3/48/1b9283ebbf0ec065148d8de05d647a986c5f22586b18120020452fff8f5d/cffi-1.17.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ad9413ccdeda48c5afdae7e4fa2192157e991ff761e7ab8fdd8926f40b160cc3", size = 455571 },
+ { url = "https://files.pythonhosted.org/packages/40/87/3b8452525437b40f39ca7ff70276679772ee7e8b394934ff60e63b7b090c/cffi-1.17.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5da5719280082ac6bd9aa7becb3938dc9f9cbd57fac7d2871717b1feb0902ab6", size = 436687 },
+ { url = "https://files.pythonhosted.org/packages/8d/fb/4da72871d177d63649ac449aec2e8a29efe0274035880c7af59101ca2232/cffi-1.17.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2bb1a08b8008b281856e5971307cc386a8e9c5b625ac297e853d36da6efe9c17", size = 446211 },
+ { url = "https://files.pythonhosted.org/packages/ab/a0/62f00bcb411332106c02b663b26f3545a9ef136f80d5df746c05878f8c4b/cffi-1.17.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:045d61c734659cc045141be4bae381a41d89b741f795af1dd018bfb532fd0df8", size = 461325 },
+ { url = "https://files.pythonhosted.org/packages/36/83/76127035ed2e7e27b0787604d99da630ac3123bfb02d8e80c633f218a11d/cffi-1.17.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:6883e737d7d9e4899a8a695e00ec36bd4e5e4f18fabe0aca0efe0a4b44cdb13e", size = 438784 },
+ { url = "https://files.pythonhosted.org/packages/21/81/a6cd025db2f08ac88b901b745c163d884641909641f9b826e8cb87645942/cffi-1.17.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:6b8b4a92e1c65048ff98cfe1f735ef8f1ceb72e3d5f0c25fdb12087a23da22be", size = 461564 },
+ { url = "https://files.pythonhosted.org/packages/f8/fe/4d41c2f200c4a457933dbd98d3cf4e911870877bd94d9656cc0fcb390681/cffi-1.17.1-cp310-cp310-win32.whl", hash = "sha256:c9c3d058ebabb74db66e431095118094d06abf53284d9c81f27300d0e0d8bc7c", size = 171804 },
+ { url = "https://files.pythonhosted.org/packages/d1/b6/0b0f5ab93b0df4acc49cae758c81fe4e5ef26c3ae2e10cc69249dfd8b3ab/cffi-1.17.1-cp310-cp310-win_amd64.whl", hash = "sha256:0f048dcf80db46f0098ccac01132761580d28e28bc0f78ae0d58048063317e15", size = 181299 },
+ { url = "https://files.pythonhosted.org/packages/6b/f4/927e3a8899e52a27fa57a48607ff7dc91a9ebe97399b357b85a0c7892e00/cffi-1.17.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a45e3c6913c5b87b3ff120dcdc03f6131fa0065027d0ed7ee6190736a74cd401", size = 182264 },
+ { url = "https://files.pythonhosted.org/packages/6c/f5/6c3a8efe5f503175aaddcbea6ad0d2c96dad6f5abb205750d1b3df44ef29/cffi-1.17.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:30c5e0cb5ae493c04c8b42916e52ca38079f1b235c2f8ae5f4527b963c401caf", size = 178651 },
+ { url = "https://files.pythonhosted.org/packages/94/dd/a3f0118e688d1b1a57553da23b16bdade96d2f9bcda4d32e7d2838047ff7/cffi-1.17.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f75c7ab1f9e4aca5414ed4d8e5c0e303a34f4421f8a0d47a4d019ceff0ab6af4", size = 445259 },
+ { url = "https://files.pythonhosted.org/packages/2e/ea/70ce63780f096e16ce8588efe039d3c4f91deb1dc01e9c73a287939c79a6/cffi-1.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a1ed2dd2972641495a3ec98445e09766f077aee98a1c896dcb4ad0d303628e41", size = 469200 },
+ { url = "https://files.pythonhosted.org/packages/1c/a0/a4fa9f4f781bda074c3ddd57a572b060fa0df7655d2a4247bbe277200146/cffi-1.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:46bf43160c1a35f7ec506d254e5c890f3c03648a4dbac12d624e4490a7046cd1", size = 477235 },
+ { url = "https://files.pythonhosted.org/packages/62/12/ce8710b5b8affbcdd5c6e367217c242524ad17a02fe5beec3ee339f69f85/cffi-1.17.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a24ed04c8ffd54b0729c07cee15a81d964e6fee0e3d4d342a27b020d22959dc6", size = 459721 },
+ { url = "https://files.pythonhosted.org/packages/ff/6b/d45873c5e0242196f042d555526f92aa9e0c32355a1be1ff8c27f077fd37/cffi-1.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:610faea79c43e44c71e1ec53a554553fa22321b65fae24889706c0a84d4ad86d", size = 467242 },
+ { url = "https://files.pythonhosted.org/packages/1a/52/d9a0e523a572fbccf2955f5abe883cfa8bcc570d7faeee06336fbd50c9fc/cffi-1.17.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:a9b15d491f3ad5d692e11f6b71f7857e7835eb677955c00cc0aefcd0669adaf6", size = 477999 },
+ { url = "https://files.pythonhosted.org/packages/44/74/f2a2460684a1a2d00ca799ad880d54652841a780c4c97b87754f660c7603/cffi-1.17.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:de2ea4b5833625383e464549fec1bc395c1bdeeb5f25c4a3a82b5a8c756ec22f", size = 454242 },
+ { url = "https://files.pythonhosted.org/packages/f8/4a/34599cac7dfcd888ff54e801afe06a19c17787dfd94495ab0c8d35fe99fb/cffi-1.17.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:fc48c783f9c87e60831201f2cce7f3b2e4846bf4d8728eabe54d60700b318a0b", size = 478604 },
+ { url = "https://files.pythonhosted.org/packages/34/33/e1b8a1ba29025adbdcda5fb3a36f94c03d771c1b7b12f726ff7fef2ebe36/cffi-1.17.1-cp311-cp311-win32.whl", hash = "sha256:85a950a4ac9c359340d5963966e3e0a94a676bd6245a4b55bc43949eee26a655", size = 171727 },
+ { url = "https://files.pythonhosted.org/packages/3d/97/50228be003bb2802627d28ec0627837ac0bf35c90cf769812056f235b2d1/cffi-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:caaf0640ef5f5517f49bc275eca1406b0ffa6aa184892812030f04c2abf589a0", size = 181400 },
+ { url = "https://files.pythonhosted.org/packages/5a/84/e94227139ee5fb4d600a7a4927f322e1d4aea6fdc50bd3fca8493caba23f/cffi-1.17.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:805b4371bf7197c329fcb3ead37e710d1bca9da5d583f5073b799d5c5bd1eee4", size = 183178 },
+ { url = "https://files.pythonhosted.org/packages/da/ee/fb72c2b48656111c4ef27f0f91da355e130a923473bf5ee75c5643d00cca/cffi-1.17.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:733e99bc2df47476e3848417c5a4540522f234dfd4ef3ab7fafdf555b082ec0c", size = 178840 },
+ { url = "https://files.pythonhosted.org/packages/cc/b6/db007700f67d151abadf508cbfd6a1884f57eab90b1bb985c4c8c02b0f28/cffi-1.17.1-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1257bdabf294dceb59f5e70c64a3e2f462c30c7ad68092d01bbbfb1c16b1ba36", size = 454803 },
+ { url = "https://files.pythonhosted.org/packages/1a/df/f8d151540d8c200eb1c6fba8cd0dfd40904f1b0682ea705c36e6c2e97ab3/cffi-1.17.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:da95af8214998d77a98cc14e3a3bd00aa191526343078b530ceb0bd710fb48a5", size = 478850 },
+ { url = "https://files.pythonhosted.org/packages/28/c0/b31116332a547fd2677ae5b78a2ef662dfc8023d67f41b2a83f7c2aa78b1/cffi-1.17.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d63afe322132c194cf832bfec0dc69a99fb9bb6bbd550f161a49e9e855cc78ff", size = 485729 },
+ { url = "https://files.pythonhosted.org/packages/91/2b/9a1ddfa5c7f13cab007a2c9cc295b70fbbda7cb10a286aa6810338e60ea1/cffi-1.17.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f79fc4fc25f1c8698ff97788206bb3c2598949bfe0fef03d299eb1b5356ada99", size = 471256 },
+ { url = "https://files.pythonhosted.org/packages/b2/d5/da47df7004cb17e4955df6a43d14b3b4ae77737dff8bf7f8f333196717bf/cffi-1.17.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b62ce867176a75d03a665bad002af8e6d54644fad99a3c70905c543130e39d93", size = 479424 },
+ { url = "https://files.pythonhosted.org/packages/0b/ac/2a28bcf513e93a219c8a4e8e125534f4f6db03e3179ba1c45e949b76212c/cffi-1.17.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:386c8bf53c502fff58903061338ce4f4950cbdcb23e2902d86c0f722b786bbe3", size = 484568 },
+ { url = "https://files.pythonhosted.org/packages/d4/38/ca8a4f639065f14ae0f1d9751e70447a261f1a30fa7547a828ae08142465/cffi-1.17.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:4ceb10419a9adf4460ea14cfd6bc43d08701f0835e979bf821052f1805850fe8", size = 488736 },
+ { url = "https://files.pythonhosted.org/packages/86/c5/28b2d6f799ec0bdecf44dced2ec5ed43e0eb63097b0f58c293583b406582/cffi-1.17.1-cp312-cp312-win32.whl", hash = "sha256:a08d7e755f8ed21095a310a693525137cfe756ce62d066e53f502a83dc550f65", size = 172448 },
+ { url = "https://files.pythonhosted.org/packages/50/b9/db34c4755a7bd1cb2d1603ac3863f22bcecbd1ba29e5ee841a4bc510b294/cffi-1.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:51392eae71afec0d0c8fb1a53b204dbb3bcabcb3c9b807eedf3e1e6ccf2de903", size = 181976 },
+ { url = "https://files.pythonhosted.org/packages/8d/f8/dd6c246b148639254dad4d6803eb6a54e8c85c6e11ec9df2cffa87571dbe/cffi-1.17.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f3a2b4222ce6b60e2e8b337bb9596923045681d71e5a082783484d845390938e", size = 182989 },
+ { url = "https://files.pythonhosted.org/packages/8b/f1/672d303ddf17c24fc83afd712316fda78dc6fce1cd53011b839483e1ecc8/cffi-1.17.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0984a4925a435b1da406122d4d7968dd861c1385afe3b45ba82b750f229811e2", size = 178802 },
+ { url = "https://files.pythonhosted.org/packages/0e/2d/eab2e858a91fdff70533cab61dcff4a1f55ec60425832ddfdc9cd36bc8af/cffi-1.17.1-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d01b12eeeb4427d3110de311e1774046ad344f5b1a7403101878976ecd7a10f3", size = 454792 },
+ { url = "https://files.pythonhosted.org/packages/75/b2/fbaec7c4455c604e29388d55599b99ebcc250a60050610fadde58932b7ee/cffi-1.17.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:706510fe141c86a69c8ddc029c7910003a17353970cff3b904ff0686a5927683", size = 478893 },
+ { url = "https://files.pythonhosted.org/packages/4f/b7/6e4a2162178bf1935c336d4da8a9352cccab4d3a5d7914065490f08c0690/cffi-1.17.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de55b766c7aa2e2a3092c51e0483d700341182f08e67c63630d5b6f200bb28e5", size = 485810 },
+ { url = "https://files.pythonhosted.org/packages/c7/8a/1d0e4a9c26e54746dc08c2c6c037889124d4f59dffd853a659fa545f1b40/cffi-1.17.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c59d6e989d07460165cc5ad3c61f9fd8f1b4796eacbd81cee78957842b834af4", size = 471200 },
+ { url = "https://files.pythonhosted.org/packages/26/9f/1aab65a6c0db35f43c4d1b4f580e8df53914310afc10ae0397d29d697af4/cffi-1.17.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd398dbc6773384a17fe0d3e7eeb8d1a21c2200473ee6806bb5e6a8e62bb73dd", size = 479447 },
+ { url = "https://files.pythonhosted.org/packages/5f/e4/fb8b3dd8dc0e98edf1135ff067ae070bb32ef9d509d6cb0f538cd6f7483f/cffi-1.17.1-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:3edc8d958eb099c634dace3c7e16560ae474aa3803a5df240542b305d14e14ed", size = 484358 },
+ { url = "https://files.pythonhosted.org/packages/f1/47/d7145bf2dc04684935d57d67dff9d6d795b2ba2796806bb109864be3a151/cffi-1.17.1-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:72e72408cad3d5419375fc87d289076ee319835bdfa2caad331e377589aebba9", size = 488469 },
+ { url = "https://files.pythonhosted.org/packages/bf/ee/f94057fa6426481d663b88637a9a10e859e492c73d0384514a17d78ee205/cffi-1.17.1-cp313-cp313-win32.whl", hash = "sha256:e03eab0a8677fa80d646b5ddece1cbeaf556c313dcfac435ba11f107ba117b5d", size = 172475 },
+ { url = "https://files.pythonhosted.org/packages/7c/fc/6a8cb64e5f0324877d503c854da15d76c1e50eb722e320b15345c4d0c6de/cffi-1.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:f6a16c31041f09ead72d69f583767292f750d24913dadacf5756b966aacb3f1a", size = 182009 },
+ { url = "https://files.pythonhosted.org/packages/b9/ea/8bb50596b8ffbc49ddd7a1ad305035daa770202a6b782fc164647c2673ad/cffi-1.17.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:b2ab587605f4ba0bf81dc0cb08a41bd1c0a5906bd59243d56bad7668a6fc6c16", size = 182220 },
+ { url = "https://files.pythonhosted.org/packages/ae/11/e77c8cd24f58285a82c23af484cf5b124a376b32644e445960d1a4654c3a/cffi-1.17.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:28b16024becceed8c6dfbc75629e27788d8a3f9030691a1dbf9821a128b22c36", size = 178605 },
+ { url = "https://files.pythonhosted.org/packages/ed/65/25a8dc32c53bf5b7b6c2686b42ae2ad58743f7ff644844af7cdb29b49361/cffi-1.17.1-cp39-cp39-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1d599671f396c4723d016dbddb72fe8e0397082b0a77a4fab8028923bec050e8", size = 424910 },
+ { url = "https://files.pythonhosted.org/packages/42/7a/9d086fab7c66bd7c4d0f27c57a1b6b068ced810afc498cc8c49e0088661c/cffi-1.17.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ca74b8dbe6e8e8263c0ffd60277de77dcee6c837a3d0881d8c1ead7268c9e576", size = 447200 },
+ { url = "https://files.pythonhosted.org/packages/da/63/1785ced118ce92a993b0ec9e0d0ac8dc3e5dbfbcaa81135be56c69cabbb6/cffi-1.17.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f7f5baafcc48261359e14bcd6d9bff6d4b28d9103847c9e136694cb0501aef87", size = 454565 },
+ { url = "https://files.pythonhosted.org/packages/74/06/90b8a44abf3556599cdec107f7290277ae8901a58f75e6fe8f970cd72418/cffi-1.17.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98e3969bcff97cae1b2def8ba499ea3d6f31ddfdb7635374834cf89a1a08ecf0", size = 435635 },
+ { url = "https://files.pythonhosted.org/packages/bd/62/a1f468e5708a70b1d86ead5bab5520861d9c7eacce4a885ded9faa7729c3/cffi-1.17.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdf5ce3acdfd1661132f2a9c19cac174758dc2352bfe37d98aa7512c6b7178b3", size = 445218 },
+ { url = "https://files.pythonhosted.org/packages/5b/95/b34462f3ccb09c2594aa782d90a90b045de4ff1f70148ee79c69d37a0a5a/cffi-1.17.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:9755e4345d1ec879e3849e62222a18c7174d65a6a92d5b346b1863912168b595", size = 460486 },
+ { url = "https://files.pythonhosted.org/packages/fc/fc/a1e4bebd8d680febd29cf6c8a40067182b64f00c7d105f8f26b5bc54317b/cffi-1.17.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:f1e22e8c4419538cb197e4dd60acc919d7696e5ef98ee4da4e01d3f8cfa4cc5a", size = 437911 },
+ { url = "https://files.pythonhosted.org/packages/e6/c3/21cab7a6154b6a5ea330ae80de386e7665254835b9e98ecc1340b3a7de9a/cffi-1.17.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:c03e868a0b3bc35839ba98e74211ed2b05d2119be4e8a0f224fba9384f1fe02e", size = 460632 },
+ { url = "https://files.pythonhosted.org/packages/cb/b5/fd9f8b5a84010ca169ee49f4e4ad6f8c05f4e3545b72ee041dbbcb159882/cffi-1.17.1-cp39-cp39-win32.whl", hash = "sha256:e31ae45bc2e29f6b2abd0de1cc3b9d5205aa847cafaecb8af1476a609a2f6eb7", size = 171820 },
+ { url = "https://files.pythonhosted.org/packages/8c/52/b08750ce0bce45c143e1b5d7357ee8c55341b52bdef4b0f081af1eb248c2/cffi-1.17.1-cp39-cp39-win_amd64.whl", hash = "sha256:d016c76bdd850f3c626af19b0542c9677ba156e4ee4fccfdd7848803533ef662", size = 181290 },
+]
+
+[[package]]
+name = "cfgv"
+version = "3.4.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/11/74/539e56497d9bd1d484fd863dd69cbbfa653cd2aa27abfe35653494d85e94/cfgv-3.4.0.tar.gz", hash = "sha256:e52591d4c5f5dead8e0f673fb16db7949d2cfb3f7da4582893288f0ded8fe560", size = 7114 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl", hash = "sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9", size = 7249 },
+]
+
+[[package]]
+name = "charset-normalizer"
+version = "3.4.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e4/33/89c2ced2b67d1c2a61c19c6751aa8902d46ce3dacb23600a283619f5a12d/charset_normalizer-3.4.2.tar.gz", hash = "sha256:5baececa9ecba31eff645232d59845c07aa030f0c81ee70184a90d35099a0e63", size = 126367 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/95/28/9901804da60055b406e1a1c5ba7aac1276fb77f1dde635aabfc7fd84b8ab/charset_normalizer-3.4.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:7c48ed483eb946e6c04ccbe02c6b4d1d48e51944b6db70f697e089c193404941", size = 201818 },
+ { url = "https://files.pythonhosted.org/packages/d9/9b/892a8c8af9110935e5adcbb06d9c6fe741b6bb02608c6513983048ba1a18/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b2d318c11350e10662026ad0eb71bb51c7812fc8590825304ae0bdd4ac283acd", size = 144649 },
+ { url = "https://files.pythonhosted.org/packages/7b/a5/4179abd063ff6414223575e008593861d62abfc22455b5d1a44995b7c101/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:9cbfacf36cb0ec2897ce0ebc5d08ca44213af24265bd56eca54bee7923c48fd6", size = 155045 },
+ { url = "https://files.pythonhosted.org/packages/3b/95/bc08c7dfeddd26b4be8c8287b9bb055716f31077c8b0ea1cd09553794665/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:18dd2e350387c87dabe711b86f83c9c78af772c748904d372ade190b5c7c9d4d", size = 147356 },
+ { url = "https://files.pythonhosted.org/packages/a8/2d/7a5b635aa65284bf3eab7653e8b4151ab420ecbae918d3e359d1947b4d61/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8075c35cd58273fee266c58c0c9b670947c19df5fb98e7b66710e04ad4e9ff86", size = 149471 },
+ { url = "https://files.pythonhosted.org/packages/ae/38/51fc6ac74251fd331a8cfdb7ec57beba8c23fd5493f1050f71c87ef77ed0/charset_normalizer-3.4.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:5bf4545e3b962767e5c06fe1738f951f77d27967cb2caa64c28be7c4563e162c", size = 151317 },
+ { url = "https://files.pythonhosted.org/packages/b7/17/edee1e32215ee6e9e46c3e482645b46575a44a2d72c7dfd49e49f60ce6bf/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:7a6ab32f7210554a96cd9e33abe3ddd86732beeafc7a28e9955cdf22ffadbab0", size = 146368 },
+ { url = "https://files.pythonhosted.org/packages/26/2c/ea3e66f2b5f21fd00b2825c94cafb8c326ea6240cd80a91eb09e4a285830/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:b33de11b92e9f75a2b545d6e9b6f37e398d86c3e9e9653c4864eb7e89c5773ef", size = 154491 },
+ { url = "https://files.pythonhosted.org/packages/52/47/7be7fa972422ad062e909fd62460d45c3ef4c141805b7078dbab15904ff7/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:8755483f3c00d6c9a77f490c17e6ab0c8729e39e6390328e42521ef175380ae6", size = 157695 },
+ { url = "https://files.pythonhosted.org/packages/2f/42/9f02c194da282b2b340f28e5fb60762de1151387a36842a92b533685c61e/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:68a328e5f55ec37c57f19ebb1fdc56a248db2e3e9ad769919a58672958e8f366", size = 154849 },
+ { url = "https://files.pythonhosted.org/packages/67/44/89cacd6628f31fb0b63201a618049be4be2a7435a31b55b5eb1c3674547a/charset_normalizer-3.4.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:21b2899062867b0e1fde9b724f8aecb1af14f2778d69aacd1a5a1853a597a5db", size = 150091 },
+ { url = "https://files.pythonhosted.org/packages/1f/79/4b8da9f712bc079c0f16b6d67b099b0b8d808c2292c937f267d816ec5ecc/charset_normalizer-3.4.2-cp310-cp310-win32.whl", hash = "sha256:e8082b26888e2f8b36a042a58307d5b917ef2b1cacab921ad3323ef91901c71a", size = 98445 },
+ { url = "https://files.pythonhosted.org/packages/7d/d7/96970afb4fb66497a40761cdf7bd4f6fca0fc7bafde3a84f836c1f57a926/charset_normalizer-3.4.2-cp310-cp310-win_amd64.whl", hash = "sha256:f69a27e45c43520f5487f27627059b64aaf160415589230992cec34c5e18a509", size = 105782 },
+ { url = "https://files.pythonhosted.org/packages/05/85/4c40d00dcc6284a1c1ad5de5e0996b06f39d8232f1031cd23c2f5c07ee86/charset_normalizer-3.4.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:be1e352acbe3c78727a16a455126d9ff83ea2dfdcbc83148d2982305a04714c2", size = 198794 },
+ { url = "https://files.pythonhosted.org/packages/41/d9/7a6c0b9db952598e97e93cbdfcb91bacd89b9b88c7c983250a77c008703c/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:aa88ca0b1932e93f2d961bf3addbb2db902198dca337d88c89e1559e066e7645", size = 142846 },
+ { url = "https://files.pythonhosted.org/packages/66/82/a37989cda2ace7e37f36c1a8ed16c58cf48965a79c2142713244bf945c89/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d524ba3f1581b35c03cb42beebab4a13e6cdad7b36246bd22541fa585a56cccd", size = 153350 },
+ { url = "https://files.pythonhosted.org/packages/df/68/a576b31b694d07b53807269d05ec3f6f1093e9545e8607121995ba7a8313/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28a1005facc94196e1fb3e82a3d442a9d9110b8434fc1ded7a24a2983c9888d8", size = 145657 },
+ { url = "https://files.pythonhosted.org/packages/92/9b/ad67f03d74554bed3aefd56fe836e1623a50780f7c998d00ca128924a499/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fdb20a30fe1175ecabed17cbf7812f7b804b8a315a25f24678bcdf120a90077f", size = 147260 },
+ { url = "https://files.pythonhosted.org/packages/a6/e6/8aebae25e328160b20e31a7e9929b1578bbdc7f42e66f46595a432f8539e/charset_normalizer-3.4.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0f5d9ed7f254402c9e7d35d2f5972c9bbea9040e99cd2861bd77dc68263277c7", size = 149164 },
+ { url = "https://files.pythonhosted.org/packages/8b/f2/b3c2f07dbcc248805f10e67a0262c93308cfa149a4cd3d1fe01f593e5fd2/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:efd387a49825780ff861998cd959767800d54f8308936b21025326de4b5a42b9", size = 144571 },
+ { url = "https://files.pythonhosted.org/packages/60/5b/c3f3a94bc345bc211622ea59b4bed9ae63c00920e2e8f11824aa5708e8b7/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:f0aa37f3c979cf2546b73e8222bbfa3dc07a641585340179d768068e3455e544", size = 151952 },
+ { url = "https://files.pythonhosted.org/packages/e2/4d/ff460c8b474122334c2fa394a3f99a04cf11c646da895f81402ae54f5c42/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:e70e990b2137b29dc5564715de1e12701815dacc1d056308e2b17e9095372a82", size = 155959 },
+ { url = "https://files.pythonhosted.org/packages/a2/2b/b964c6a2fda88611a1fe3d4c400d39c66a42d6c169c924818c848f922415/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0c8c57f84ccfc871a48a47321cfa49ae1df56cd1d965a09abe84066f6853b9c0", size = 153030 },
+ { url = "https://files.pythonhosted.org/packages/59/2e/d3b9811db26a5ebf444bc0fa4f4be5aa6d76fc6e1c0fd537b16c14e849b6/charset_normalizer-3.4.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6b66f92b17849b85cad91259efc341dce9c1af48e2173bf38a85c6329f1033e5", size = 148015 },
+ { url = "https://files.pythonhosted.org/packages/90/07/c5fd7c11eafd561bb51220d600a788f1c8d77c5eef37ee49454cc5c35575/charset_normalizer-3.4.2-cp311-cp311-win32.whl", hash = "sha256:daac4765328a919a805fa5e2720f3e94767abd632ae410a9062dff5412bae65a", size = 98106 },
+ { url = "https://files.pythonhosted.org/packages/a8/05/5e33dbef7e2f773d672b6d79f10ec633d4a71cd96db6673625838a4fd532/charset_normalizer-3.4.2-cp311-cp311-win_amd64.whl", hash = "sha256:e53efc7c7cee4c1e70661e2e112ca46a575f90ed9ae3fef200f2a25e954f4b28", size = 105402 },
+ { url = "https://files.pythonhosted.org/packages/d7/a4/37f4d6035c89cac7930395a35cc0f1b872e652eaafb76a6075943754f095/charset_normalizer-3.4.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:0c29de6a1a95f24b9a1aa7aefd27d2487263f00dfd55a77719b530788f75cff7", size = 199936 },
+ { url = "https://files.pythonhosted.org/packages/ee/8a/1a5e33b73e0d9287274f899d967907cd0bf9c343e651755d9307e0dbf2b3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cddf7bd982eaa998934a91f69d182aec997c6c468898efe6679af88283b498d3", size = 143790 },
+ { url = "https://files.pythonhosted.org/packages/66/52/59521f1d8e6ab1482164fa21409c5ef44da3e9f653c13ba71becdd98dec3/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:fcbe676a55d7445b22c10967bceaaf0ee69407fbe0ece4d032b6eb8d4565982a", size = 153924 },
+ { url = "https://files.pythonhosted.org/packages/86/2d/fb55fdf41964ec782febbf33cb64be480a6b8f16ded2dbe8db27a405c09f/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d41c4d287cfc69060fa91cae9683eacffad989f1a10811995fa309df656ec214", size = 146626 },
+ { url = "https://files.pythonhosted.org/packages/8c/73/6ede2ec59bce19b3edf4209d70004253ec5f4e319f9a2e3f2f15601ed5f7/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4e594135de17ab3866138f496755f302b72157d115086d100c3f19370839dd3a", size = 148567 },
+ { url = "https://files.pythonhosted.org/packages/09/14/957d03c6dc343c04904530b6bef4e5efae5ec7d7990a7cbb868e4595ee30/charset_normalizer-3.4.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:cf713fe9a71ef6fd5adf7a79670135081cd4431c2943864757f0fa3a65b1fafd", size = 150957 },
+ { url = "https://files.pythonhosted.org/packages/0d/c8/8174d0e5c10ccebdcb1b53cc959591c4c722a3ad92461a273e86b9f5a302/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:a370b3e078e418187da8c3674eddb9d983ec09445c99a3a263c2011993522981", size = 145408 },
+ { url = "https://files.pythonhosted.org/packages/58/aa/8904b84bc8084ac19dc52feb4f5952c6df03ffb460a887b42615ee1382e8/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:a955b438e62efdf7e0b7b52a64dc5c3396e2634baa62471768a64bc2adb73d5c", size = 153399 },
+ { url = "https://files.pythonhosted.org/packages/c2/26/89ee1f0e264d201cb65cf054aca6038c03b1a0c6b4ae998070392a3ce605/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:7222ffd5e4de8e57e03ce2cef95a4c43c98fcb72ad86909abdfc2c17d227fc1b", size = 156815 },
+ { url = "https://files.pythonhosted.org/packages/fd/07/68e95b4b345bad3dbbd3a8681737b4338ff2c9df29856a6d6d23ac4c73cb/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:bee093bf902e1d8fc0ac143c88902c3dfc8941f7ea1d6a8dd2bcb786d33db03d", size = 154537 },
+ { url = "https://files.pythonhosted.org/packages/77/1a/5eefc0ce04affb98af07bc05f3bac9094513c0e23b0562d64af46a06aae4/charset_normalizer-3.4.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:dedb8adb91d11846ee08bec4c8236c8549ac721c245678282dcb06b221aab59f", size = 149565 },
+ { url = "https://files.pythonhosted.org/packages/37/a0/2410e5e6032a174c95e0806b1a6585eb21e12f445ebe239fac441995226a/charset_normalizer-3.4.2-cp312-cp312-win32.whl", hash = "sha256:db4c7bf0e07fc3b7d89ac2a5880a6a8062056801b83ff56d8464b70f65482b6c", size = 98357 },
+ { url = "https://files.pythonhosted.org/packages/6c/4f/c02d5c493967af3eda9c771ad4d2bbc8df6f99ddbeb37ceea6e8716a32bc/charset_normalizer-3.4.2-cp312-cp312-win_amd64.whl", hash = "sha256:5a9979887252a82fefd3d3ed2a8e3b937a7a809f65dcb1e068b090e165bbe99e", size = 105776 },
+ { url = "https://files.pythonhosted.org/packages/ea/12/a93df3366ed32db1d907d7593a94f1fe6293903e3e92967bebd6950ed12c/charset_normalizer-3.4.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:926ca93accd5d36ccdabd803392ddc3e03e6d4cd1cf17deff3b989ab8e9dbcf0", size = 199622 },
+ { url = "https://files.pythonhosted.org/packages/04/93/bf204e6f344c39d9937d3c13c8cd5bbfc266472e51fc8c07cb7f64fcd2de/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:eba9904b0f38a143592d9fc0e19e2df0fa2e41c3c3745554761c5f6447eedabf", size = 143435 },
+ { url = "https://files.pythonhosted.org/packages/22/2a/ea8a2095b0bafa6c5b5a55ffdc2f924455233ee7b91c69b7edfcc9e02284/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3fddb7e2c84ac87ac3a947cb4e66d143ca5863ef48e4a5ecb83bd48619e4634e", size = 153653 },
+ { url = "https://files.pythonhosted.org/packages/b6/57/1b090ff183d13cef485dfbe272e2fe57622a76694061353c59da52c9a659/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:98f862da73774290f251b9df8d11161b6cf25b599a66baf087c1ffe340e9bfd1", size = 146231 },
+ { url = "https://files.pythonhosted.org/packages/e2/28/ffc026b26f441fc67bd21ab7f03b313ab3fe46714a14b516f931abe1a2d8/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c9379d65defcab82d07b2a9dfbfc2e95bc8fe0ebb1b176a3190230a3ef0e07c", size = 148243 },
+ { url = "https://files.pythonhosted.org/packages/c0/0f/9abe9bd191629c33e69e47c6ef45ef99773320e9ad8e9cb08b8ab4a8d4cb/charset_normalizer-3.4.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e635b87f01ebc977342e2697d05b56632f5f879a4f15955dfe8cef2448b51691", size = 150442 },
+ { url = "https://files.pythonhosted.org/packages/67/7c/a123bbcedca91d5916c056407f89a7f5e8fdfce12ba825d7d6b9954a1a3c/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:1c95a1e2902a8b722868587c0e1184ad5c55631de5afc0eb96bc4b0d738092c0", size = 145147 },
+ { url = "https://files.pythonhosted.org/packages/ec/fe/1ac556fa4899d967b83e9893788e86b6af4d83e4726511eaaad035e36595/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ef8de666d6179b009dce7bcb2ad4c4a779f113f12caf8dc77f0162c29d20490b", size = 153057 },
+ { url = "https://files.pythonhosted.org/packages/2b/ff/acfc0b0a70b19e3e54febdd5301a98b72fa07635e56f24f60502e954c461/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:32fc0341d72e0f73f80acb0a2c94216bd704f4f0bce10aedea38f30502b271ff", size = 156454 },
+ { url = "https://files.pythonhosted.org/packages/92/08/95b458ce9c740d0645feb0e96cea1f5ec946ea9c580a94adfe0b617f3573/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:289200a18fa698949d2b39c671c2cc7a24d44096784e76614899a7ccf2574b7b", size = 154174 },
+ { url = "https://files.pythonhosted.org/packages/78/be/8392efc43487ac051eee6c36d5fbd63032d78f7728cb37aebcc98191f1ff/charset_normalizer-3.4.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4a476b06fbcf359ad25d34a057b7219281286ae2477cc5ff5e3f70a246971148", size = 149166 },
+ { url = "https://files.pythonhosted.org/packages/44/96/392abd49b094d30b91d9fbda6a69519e95802250b777841cf3bda8fe136c/charset_normalizer-3.4.2-cp313-cp313-win32.whl", hash = "sha256:aaeeb6a479c7667fbe1099af9617c83aaca22182d6cf8c53966491a0f1b7ffb7", size = 98064 },
+ { url = "https://files.pythonhosted.org/packages/e9/b0/0200da600134e001d91851ddc797809e2fe0ea72de90e09bec5a2fbdaccb/charset_normalizer-3.4.2-cp313-cp313-win_amd64.whl", hash = "sha256:aa6af9e7d59f9c12b33ae4e9450619cf2488e2bbe9b44030905877f0b2324980", size = 105641 },
+ { url = "https://files.pythonhosted.org/packages/28/f8/dfb01ff6cc9af38552c69c9027501ff5a5117c4cc18dcd27cb5259fa1888/charset_normalizer-3.4.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:005fa3432484527f9732ebd315da8da8001593e2cf46a3d817669f062c3d9ed4", size = 201671 },
+ { url = "https://files.pythonhosted.org/packages/32/fb/74e26ee556a9dbfe3bd264289b67be1e6d616329403036f6507bb9f3f29c/charset_normalizer-3.4.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e92fca20c46e9f5e1bb485887d074918b13543b1c2a1185e69bb8d17ab6236a7", size = 144744 },
+ { url = "https://files.pythonhosted.org/packages/ad/06/8499ee5aa7addc6f6d72e068691826ff093329fe59891e83b092ae4c851c/charset_normalizer-3.4.2-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:50bf98d5e563b83cc29471fa114366e6806bc06bc7a25fd59641e41445327836", size = 154993 },
+ { url = "https://files.pythonhosted.org/packages/f1/a2/5e4c187680728219254ef107a6949c60ee0e9a916a5dadb148c7ae82459c/charset_normalizer-3.4.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:721c76e84fe669be19c5791da68232ca2e05ba5185575086e384352e2c309597", size = 147382 },
+ { url = "https://files.pythonhosted.org/packages/4c/fe/56aca740dda674f0cc1ba1418c4d84534be51f639b5f98f538b332dc9a95/charset_normalizer-3.4.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:82d8fd25b7f4675d0c47cf95b594d4e7b158aca33b76aa63d07186e13c0e0ab7", size = 149536 },
+ { url = "https://files.pythonhosted.org/packages/53/13/db2e7779f892386b589173dd689c1b1e304621c5792046edd8a978cbf9e0/charset_normalizer-3.4.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b3daeac64d5b371dea99714f08ffc2c208522ec6b06fbc7866a450dd446f5c0f", size = 151349 },
+ { url = "https://files.pythonhosted.org/packages/69/35/e52ab9a276186f729bce7a0638585d2982f50402046e4b0faa5d2c3ef2da/charset_normalizer-3.4.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:dccab8d5fa1ef9bfba0590ecf4d46df048d18ffe3eec01eeb73a42e0d9e7a8ba", size = 146365 },
+ { url = "https://files.pythonhosted.org/packages/a6/d8/af7333f732fc2e7635867d56cb7c349c28c7094910c72267586947561b4b/charset_normalizer-3.4.2-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:aaf27faa992bfee0264dc1f03f4c75e9fcdda66a519db6b957a3f826e285cf12", size = 154499 },
+ { url = "https://files.pythonhosted.org/packages/7a/3d/a5b2e48acef264d71e036ff30bcc49e51bde80219bb628ba3e00cf59baac/charset_normalizer-3.4.2-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:eb30abc20df9ab0814b5a2524f23d75dcf83cde762c161917a2b4b7b55b1e518", size = 157735 },
+ { url = "https://files.pythonhosted.org/packages/85/d8/23e2c112532a29f3eef374375a8684a4f3b8e784f62b01da931186f43494/charset_normalizer-3.4.2-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:c72fbbe68c6f32f251bdc08b8611c7b3060612236e960ef848e0a517ddbe76c5", size = 154786 },
+ { url = "https://files.pythonhosted.org/packages/c7/57/93e0169f08ecc20fe82d12254a200dfaceddc1c12a4077bf454ecc597e33/charset_normalizer-3.4.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:982bb1e8b4ffda883b3d0a521e23abcd6fd17418f6d2c4118d257a10199c0ce3", size = 150203 },
+ { url = "https://files.pythonhosted.org/packages/2c/9d/9bf2b005138e7e060d7ebdec7503d0ef3240141587651f4b445bdf7286c2/charset_normalizer-3.4.2-cp39-cp39-win32.whl", hash = "sha256:43e0933a0eff183ee85833f341ec567c0980dae57c464d8a508e1b2ceb336471", size = 98436 },
+ { url = "https://files.pythonhosted.org/packages/6d/24/5849d46cf4311bbf21b424c443b09b459f5b436b1558c04e45dbb7cc478b/charset_normalizer-3.4.2-cp39-cp39-win_amd64.whl", hash = "sha256:d11b54acf878eef558599658b0ffca78138c8c3655cf4f3a4a673c437e67732e", size = 105772 },
+ { url = "https://files.pythonhosted.org/packages/20/94/c5790835a017658cbfabd07f3bfb549140c3ac458cfc196323996b10095a/charset_normalizer-3.4.2-py3-none-any.whl", hash = "sha256:7f56930ab0abd1c45cd15be65cc741c28b1c9a34876ce8c17a2fa107810c0af0", size = 52626 },
+]
+
+[[package]]
+name = "click"
+version = "8.1.8"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version < '3.10'",
+]
+dependencies = [
+ { name = "colorama", marker = "python_full_version < '3.10' and sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b9/2e/0090cbf739cee7d23781ad4b89a9894a41538e4fcf4c31dcdd705b78eb8b/click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a", size = 226593 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7e/d4/7ebdbd03970677812aac39c869717059dbb71a4cfc033ca6e5221787892c/click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2", size = 98188 },
+]
+
+[[package]]
+name = "click"
+version = "8.2.1"
+source = { registry = "https://pypi.org/simple" }
+resolution-markers = [
+ "python_full_version >= '3.10'",
+]
+dependencies = [
+ { name = "colorama", marker = "python_full_version >= '3.10' and sys_platform == 'win32'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/60/6c/8ca2efa64cf75a977a0d7fac081354553ebe483345c734fb6b6515d96bbc/click-8.2.1.tar.gz", hash = "sha256:27c491cc05d968d271d5a1db13e3b5a184636d9d930f148c50b038f0d0646202", size = 286342 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/85/32/10bb5764d90a8eee674e9dc6f4db6a0ab47c8c4d0d83c27f7c39ac415a4d/click-8.2.1-py3-none-any.whl", hash = "sha256:61a3265b914e850b85317d0b3109c7f8cd35a670f963866005d6ef1d5175a12b", size = 102215 },
+]
+
+[[package]]
+name = "colorama"
+version = "0.4.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335 },
+]
+
+[[package]]
+name = "coverage"
+version = "7.9.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e7/e0/98670a80884f64578f0c22cd70c5e81a6e07b08167721c7487b4d70a7ca0/coverage-7.9.1.tar.gz", hash = "sha256:6cf43c78c4282708a28e466316935ec7489a9c487518a77fa68f716c67909cec", size = 813650 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c1/78/1c1c5ec58f16817c09cbacb39783c3655d54a221b6552f47ff5ac9297603/coverage-7.9.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:cc94d7c5e8423920787c33d811c0be67b7be83c705f001f7180c7b186dcf10ca", size = 212028 },
+ { url = "https://files.pythonhosted.org/packages/98/db/e91b9076f3a888e3b4ad7972ea3842297a52cc52e73fd1e529856e473510/coverage-7.9.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:16aa0830d0c08a2c40c264cef801db8bc4fc0e1892782e45bcacbd5889270509", size = 212420 },
+ { url = "https://files.pythonhosted.org/packages/0e/d0/2b3733412954576b0aea0a16c3b6b8fbe95eb975d8bfa10b07359ead4252/coverage-7.9.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cf95981b126f23db63e9dbe4cf65bd71f9a6305696fa5e2262693bc4e2183f5b", size = 241529 },
+ { url = "https://files.pythonhosted.org/packages/b3/00/5e2e5ae2e750a872226a68e984d4d3f3563cb01d1afb449a17aa819bc2c4/coverage-7.9.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f05031cf21699785cd47cb7485f67df619e7bcdae38e0fde40d23d3d0210d3c3", size = 239403 },
+ { url = "https://files.pythonhosted.org/packages/37/3b/a2c27736035156b0a7c20683afe7df498480c0dfdf503b8c878a21b6d7fb/coverage-7.9.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bb4fbcab8764dc072cb651a4bcda4d11fb5658a1d8d68842a862a6610bd8cfa3", size = 240548 },
+ { url = "https://files.pythonhosted.org/packages/98/f5/13d5fc074c3c0e0dc80422d9535814abf190f1254d7c3451590dc4f8b18c/coverage-7.9.1-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:0f16649a7330ec307942ed27d06ee7e7a38417144620bb3d6e9a18ded8a2d3e5", size = 240459 },
+ { url = "https://files.pythonhosted.org/packages/36/24/24b9676ea06102df824c4a56ffd13dc9da7904478db519efa877d16527d5/coverage-7.9.1-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:cea0a27a89e6432705fffc178064503508e3c0184b4f061700e771a09de58187", size = 239128 },
+ { url = "https://files.pythonhosted.org/packages/be/05/242b7a7d491b369ac5fee7908a6e5ba42b3030450f3ad62c645b40c23e0e/coverage-7.9.1-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:e980b53a959fa53b6f05343afbd1e6f44a23ed6c23c4b4c56c6662bbb40c82ce", size = 239402 },
+ { url = "https://files.pythonhosted.org/packages/73/e0/4de7f87192fa65c9c8fbaeb75507e124f82396b71de1797da5602898be32/coverage-7.9.1-cp310-cp310-win32.whl", hash = "sha256:70760b4c5560be6ca70d11f8988ee6542b003f982b32f83d5ac0b72476607b70", size = 214518 },
+ { url = "https://files.pythonhosted.org/packages/d5/ab/5e4e2fe458907d2a65fab62c773671cfc5ac704f1e7a9ddd91996f66e3c2/coverage-7.9.1-cp310-cp310-win_amd64.whl", hash = "sha256:a66e8f628b71f78c0e0342003d53b53101ba4e00ea8dabb799d9dba0abbbcebe", size = 215436 },
+ { url = "https://files.pythonhosted.org/packages/60/34/fa69372a07d0903a78ac103422ad34db72281c9fc625eba94ac1185da66f/coverage-7.9.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:95c765060e65c692da2d2f51a9499c5e9f5cf5453aeaf1420e3fc847cc060582", size = 212146 },
+ { url = "https://files.pythonhosted.org/packages/27/f0/da1894915d2767f093f081c42afeba18e760f12fdd7a2f4acbe00564d767/coverage-7.9.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ba383dc6afd5ec5b7a0d0c23d38895db0e15bcba7fb0fa8901f245267ac30d86", size = 212536 },
+ { url = "https://files.pythonhosted.org/packages/10/d5/3fc33b06e41e390f88eef111226a24e4504d216ab8e5d1a7089aa5a3c87a/coverage-7.9.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:37ae0383f13cbdcf1e5e7014489b0d71cc0106458878ccde52e8a12ced4298ed", size = 245092 },
+ { url = "https://files.pythonhosted.org/packages/0a/39/7aa901c14977aba637b78e95800edf77f29f5a380d29768c5b66f258305b/coverage-7.9.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:69aa417a030bf11ec46149636314c24c8d60fadb12fc0ee8f10fda0d918c879d", size = 242806 },
+ { url = "https://files.pythonhosted.org/packages/43/fc/30e5cfeaf560b1fc1989227adedc11019ce4bb7cce59d65db34fe0c2d963/coverage-7.9.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0a4be2a28656afe279b34d4f91c3e26eccf2f85500d4a4ff0b1f8b54bf807338", size = 244610 },
+ { url = "https://files.pythonhosted.org/packages/bf/15/cca62b13f39650bc87b2b92bb03bce7f0e79dd0bf2c7529e9fc7393e4d60/coverage-7.9.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:382e7ddd5289f140259b610e5f5c58f713d025cb2f66d0eb17e68d0a94278875", size = 244257 },
+ { url = "https://files.pythonhosted.org/packages/cd/1a/c0f2abe92c29e1464dbd0ff9d56cb6c88ae2b9e21becdb38bea31fcb2f6c/coverage-7.9.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:e5532482344186c543c37bfad0ee6069e8ae4fc38d073b8bc836fc8f03c9e250", size = 242309 },
+ { url = "https://files.pythonhosted.org/packages/57/8d/c6fd70848bd9bf88fa90df2af5636589a8126d2170f3aade21ed53f2b67a/coverage-7.9.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a39d18b3f50cc121d0ce3838d32d58bd1d15dab89c910358ebefc3665712256c", size = 242898 },
+ { url = "https://files.pythonhosted.org/packages/c2/9e/6ca46c7bff4675f09a66fe2797cd1ad6a24f14c9c7c3b3ebe0470a6e30b8/coverage-7.9.1-cp311-cp311-win32.whl", hash = "sha256:dd24bd8d77c98557880def750782df77ab2b6885a18483dc8588792247174b32", size = 214561 },
+ { url = "https://files.pythonhosted.org/packages/a1/30/166978c6302010742dabcdc425fa0f938fa5a800908e39aff37a7a876a13/coverage-7.9.1-cp311-cp311-win_amd64.whl", hash = "sha256:6b55ad10a35a21b8015eabddc9ba31eb590f54adc9cd39bcf09ff5349fd52125", size = 215493 },
+ { url = "https://files.pythonhosted.org/packages/60/07/a6d2342cd80a5be9f0eeab115bc5ebb3917b4a64c2953534273cf9bc7ae6/coverage-7.9.1-cp311-cp311-win_arm64.whl", hash = "sha256:6ad935f0016be24c0e97fc8c40c465f9c4b85cbbe6eac48934c0dc4d2568321e", size = 213869 },
+ { url = "https://files.pythonhosted.org/packages/68/d9/7f66eb0a8f2fce222de7bdc2046ec41cb31fe33fb55a330037833fb88afc/coverage-7.9.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a8de12b4b87c20de895f10567639c0797b621b22897b0af3ce4b4e204a743626", size = 212336 },
+ { url = "https://files.pythonhosted.org/packages/20/20/e07cb920ef3addf20f052ee3d54906e57407b6aeee3227a9c91eea38a665/coverage-7.9.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:5add197315a054e92cee1b5f686a2bcba60c4c3e66ee3de77ace6c867bdee7cb", size = 212571 },
+ { url = "https://files.pythonhosted.org/packages/78/f8/96f155de7e9e248ca9c8ff1a40a521d944ba48bec65352da9be2463745bf/coverage-7.9.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:600a1d4106fe66f41e5d0136dfbc68fe7200a5cbe85610ddf094f8f22e1b0300", size = 246377 },
+ { url = "https://files.pythonhosted.org/packages/3e/cf/1d783bd05b7bca5c10ded5f946068909372e94615a4416afadfe3f63492d/coverage-7.9.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:2a876e4c3e5a2a1715a6608906aa5a2e0475b9c0f68343c2ada98110512ab1d8", size = 243394 },
+ { url = "https://files.pythonhosted.org/packages/02/dd/e7b20afd35b0a1abea09fb3998e1abc9f9bd953bee548f235aebd2b11401/coverage-7.9.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:81f34346dd63010453922c8e628a52ea2d2ccd73cb2487f7700ac531b247c8a5", size = 245586 },
+ { url = "https://files.pythonhosted.org/packages/4e/38/b30b0006fea9d617d1cb8e43b1bc9a96af11eff42b87eb8c716cf4d37469/coverage-7.9.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:888f8eee13f2377ce86d44f338968eedec3291876b0b8a7289247ba52cb984cd", size = 245396 },
+ { url = "https://files.pythonhosted.org/packages/31/e4/4d8ec1dc826e16791f3daf1b50943e8e7e1eb70e8efa7abb03936ff48418/coverage-7.9.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:9969ef1e69b8c8e1e70d591f91bbc37fc9a3621e447525d1602801a24ceda898", size = 243577 },
+ { url = "https://files.pythonhosted.org/packages/25/f4/b0e96c5c38e6e40ef465c4bc7f138863e2909c00e54a331da335faf0d81a/coverage-7.9.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:60c458224331ee3f1a5b472773e4a085cc27a86a0b48205409d364272d67140d", size = 244809 },
+ { url = "https://files.pythonhosted.org/packages/8a/65/27e0a1fa5e2e5079bdca4521be2f5dabf516f94e29a0defed35ac2382eb2/coverage-7.9.1-cp312-cp312-win32.whl", hash = "sha256:5f646a99a8c2b3ff4c6a6e081f78fad0dde275cd59f8f49dc4eab2e394332e74", size = 214724 },
+ { url = "https://files.pythonhosted.org/packages/9b/a8/d5b128633fd1a5e0401a4160d02fa15986209a9e47717174f99dc2f7166d/coverage-7.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:30f445f85c353090b83e552dcbbdad3ec84c7967e108c3ae54556ca69955563e", size = 215535 },
+ { url = "https://files.pythonhosted.org/packages/a3/37/84bba9d2afabc3611f3e4325ee2c6a47cd449b580d4a606b240ce5a6f9bf/coverage-7.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:af41da5dca398d3474129c58cb2b106a5d93bbb196be0d307ac82311ca234342", size = 213904 },
+ { url = "https://files.pythonhosted.org/packages/d0/a7/a027970c991ca90f24e968999f7d509332daf6b8c3533d68633930aaebac/coverage-7.9.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:31324f18d5969feef7344a932c32428a2d1a3e50b15a6404e97cba1cc9b2c631", size = 212358 },
+ { url = "https://files.pythonhosted.org/packages/f2/48/6aaed3651ae83b231556750280682528fea8ac7f1232834573472d83e459/coverage-7.9.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0c804506d624e8a20fb3108764c52e0eef664e29d21692afa375e0dd98dc384f", size = 212620 },
+ { url = "https://files.pythonhosted.org/packages/6c/2a/f4b613f3b44d8b9f144847c89151992b2b6b79cbc506dee89ad0c35f209d/coverage-7.9.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ef64c27bc40189f36fcc50c3fb8f16ccda73b6a0b80d9bd6e6ce4cffcd810bbd", size = 245788 },
+ { url = "https://files.pythonhosted.org/packages/04/d2/de4fdc03af5e4e035ef420ed26a703c6ad3d7a07aff2e959eb84e3b19ca8/coverage-7.9.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d4fe2348cc6ec372e25adec0219ee2334a68d2f5222e0cba9c0d613394e12d86", size = 243001 },
+ { url = "https://files.pythonhosted.org/packages/f5/e8/eed18aa5583b0423ab7f04e34659e51101135c41cd1dcb33ac1d7013a6d6/coverage-7.9.1-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:34ed2186fe52fcc24d4561041979a0dec69adae7bce2ae8d1c49eace13e55c43", size = 244985 },
+ { url = "https://files.pythonhosted.org/packages/17/f8/ae9e5cce8885728c934eaa58ebfa8281d488ef2afa81c3dbc8ee9e6d80db/coverage-7.9.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:25308bd3d00d5eedd5ae7d4357161f4df743e3c0240fa773ee1b0f75e6c7c0f1", size = 245152 },
+ { url = "https://files.pythonhosted.org/packages/5a/c8/272c01ae792bb3af9b30fac14d71d63371db227980682836ec388e2c57c0/coverage-7.9.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:73e9439310f65d55a5a1e0564b48e34f5369bee943d72c88378f2d576f5a5751", size = 243123 },
+ { url = "https://files.pythonhosted.org/packages/8c/d0/2819a1e3086143c094ab446e3bdf07138527a7b88cb235c488e78150ba7a/coverage-7.9.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:37ab6be0859141b53aa89412a82454b482c81cf750de4f29223d52268a86de67", size = 244506 },
+ { url = "https://files.pythonhosted.org/packages/8b/4e/9f6117b89152df7b6112f65c7a4ed1f2f5ec8e60c4be8f351d91e7acc848/coverage-7.9.1-cp313-cp313-win32.whl", hash = "sha256:64bdd969456e2d02a8b08aa047a92d269c7ac1f47e0c977675d550c9a0863643", size = 214766 },
+ { url = "https://files.pythonhosted.org/packages/27/0f/4b59f7c93b52c2c4ce7387c5a4e135e49891bb3b7408dcc98fe44033bbe0/coverage-7.9.1-cp313-cp313-win_amd64.whl", hash = "sha256:be9e3f68ca9edb897c2184ad0eee815c635565dbe7a0e7e814dc1f7cbab92c0a", size = 215568 },
+ { url = "https://files.pythonhosted.org/packages/09/1e/9679826336f8c67b9c39a359352882b24a8a7aee48d4c9cad08d38d7510f/coverage-7.9.1-cp313-cp313-win_arm64.whl", hash = "sha256:1c503289ffef1d5105d91bbb4d62cbe4b14bec4d13ca225f9c73cde9bb46207d", size = 213939 },
+ { url = "https://files.pythonhosted.org/packages/bb/5b/5c6b4e7a407359a2e3b27bf9c8a7b658127975def62077d441b93a30dbe8/coverage-7.9.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0b3496922cb5f4215bf5caaef4cf12364a26b0be82e9ed6d050f3352cf2d7ef0", size = 213079 },
+ { url = "https://files.pythonhosted.org/packages/a2/22/1e2e07279fd2fd97ae26c01cc2186e2258850e9ec125ae87184225662e89/coverage-7.9.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:9565c3ab1c93310569ec0d86b017f128f027cab0b622b7af288696d7ed43a16d", size = 213299 },
+ { url = "https://files.pythonhosted.org/packages/14/c0/4c5125a4b69d66b8c85986d3321520f628756cf524af810baab0790c7647/coverage-7.9.1-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2241ad5dbf79ae1d9c08fe52b36d03ca122fb9ac6bca0f34439e99f8327ac89f", size = 256535 },
+ { url = "https://files.pythonhosted.org/packages/81/8b/e36a04889dda9960be4263e95e777e7b46f1bb4fc32202612c130a20c4da/coverage-7.9.1-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3bb5838701ca68b10ebc0937dbd0eb81974bac54447c55cd58dea5bca8451029", size = 252756 },
+ { url = "https://files.pythonhosted.org/packages/98/82/be04eff8083a09a4622ecd0e1f31a2c563dbea3ed848069e7b0445043a70/coverage-7.9.1-cp313-cp313t-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b30a25f814591a8c0c5372c11ac8967f669b97444c47fd794926e175c4047ece", size = 254912 },
+ { url = "https://files.pythonhosted.org/packages/0f/25/c26610a2c7f018508a5ab958e5b3202d900422cf7cdca7670b6b8ca4e8df/coverage-7.9.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:2d04b16a6062516df97969f1ae7efd0de9c31eb6ebdceaa0d213b21c0ca1a683", size = 256144 },
+ { url = "https://files.pythonhosted.org/packages/c5/8b/fb9425c4684066c79e863f1e6e7ecebb49e3a64d9f7f7860ef1688c56f4a/coverage-7.9.1-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:7931b9e249edefb07cd6ae10c702788546341d5fe44db5b6108a25da4dca513f", size = 254257 },
+ { url = "https://files.pythonhosted.org/packages/93/df/27b882f54157fc1131e0e215b0da3b8d608d9b8ef79a045280118a8f98fe/coverage-7.9.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:52e92b01041151bf607ee858e5a56c62d4b70f4dac85b8c8cb7fb8a351ab2c10", size = 255094 },
+ { url = "https://files.pythonhosted.org/packages/41/5f/cad1c3dbed8b3ee9e16fa832afe365b4e3eeab1fb6edb65ebbf745eabc92/coverage-7.9.1-cp313-cp313t-win32.whl", hash = "sha256:684e2110ed84fd1ca5f40e89aa44adf1729dc85444004111aa01866507adf363", size = 215437 },
+ { url = "https://files.pythonhosted.org/packages/99/4d/fad293bf081c0e43331ca745ff63673badc20afea2104b431cdd8c278b4c/coverage-7.9.1-cp313-cp313t-win_amd64.whl", hash = "sha256:437c576979e4db840539674e68c84b3cda82bc824dd138d56bead1435f1cb5d7", size = 216605 },
+ { url = "https://files.pythonhosted.org/packages/1f/56/4ee027d5965fc7fc126d7ec1187529cc30cc7d740846e1ecb5e92d31b224/coverage-7.9.1-cp313-cp313t-win_arm64.whl", hash = "sha256:18a0912944d70aaf5f399e350445738a1a20b50fbea788f640751c2ed9208b6c", size = 214392 },
+ { url = "https://files.pythonhosted.org/packages/a5/d6/c41dd9b02bf16ec001aaf1cbef665537606899a3db1094e78f5ae17540ca/coverage-7.9.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6f424507f57878e424d9a95dc4ead3fbdd72fd201e404e861e465f28ea469951", size = 212029 },
+ { url = "https://files.pythonhosted.org/packages/f8/c0/40420d81d731f84c3916dcdf0506b3e6c6570817bff2576b83f780914ae6/coverage-7.9.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:535fde4001b2783ac80865d90e7cc7798b6b126f4cd8a8c54acfe76804e54e58", size = 212407 },
+ { url = "https://files.pythonhosted.org/packages/9b/87/f0db7d62d0e09f14d6d2f6ae8c7274a2f09edf74895a34b412a0601e375a/coverage-7.9.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:02532fd3290bb8fa6bec876520842428e2a6ed6c27014eca81b031c2d30e3f71", size = 241160 },
+ { url = "https://files.pythonhosted.org/packages/a9/b7/3337c064f058a5d7696c4867159651a5b5fb01a5202bcf37362f0c51400e/coverage-7.9.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:56f5eb308b17bca3bbff810f55ee26d51926d9f89ba92707ee41d3c061257e55", size = 239027 },
+ { url = "https://files.pythonhosted.org/packages/7e/a9/5898a283f66d1bd413c32c2e0e05408196fd4f37e206e2b06c6e0c626e0e/coverage-7.9.1-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bfa447506c1a52271f1b0de3f42ea0fa14676052549095e378d5bff1c505ff7b", size = 240145 },
+ { url = "https://files.pythonhosted.org/packages/e0/33/d96e3350078a3c423c549cb5b2ba970de24c5257954d3e4066e2b2152d30/coverage-7.9.1-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:9ca8e220006966b4a7b68e8984a6aee645a0384b0769e829ba60281fe61ec4f7", size = 239871 },
+ { url = "https://files.pythonhosted.org/packages/1d/6e/6fb946072455f71a820cac144d49d11747a0f1a21038060a68d2d0200499/coverage-7.9.1-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:49f1d0788ba5b7ba65933f3a18864117c6506619f5ca80326b478f72acf3f385", size = 238122 },
+ { url = "https://files.pythonhosted.org/packages/e4/5c/bc43f25c8586840ce25a796a8111acf6a2b5f0909ba89a10d41ccff3920d/coverage-7.9.1-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:68cd53aec6f45b8e4724c0950ce86eacb775c6be01ce6e3669fe4f3a21e768ed", size = 239058 },
+ { url = "https://files.pythonhosted.org/packages/11/d8/ce2007418dd7fd00ff8c8b898bb150bb4bac2d6a86df05d7b88a07ff595f/coverage-7.9.1-cp39-cp39-win32.whl", hash = "sha256:95335095b6c7b1cc14c3f3f17d5452ce677e8490d101698562b2ffcacc304c8d", size = 214532 },
+ { url = "https://files.pythonhosted.org/packages/20/21/334e76fa246e92e6d69cab217f7c8a70ae0cc8f01438bd0544103f29528e/coverage-7.9.1-cp39-cp39-win_amd64.whl", hash = "sha256:e1b5191d1648acc439b24721caab2fd0c86679d8549ed2c84d5a7ec1bedcc244", size = 215439 },
+ { url = "https://files.pythonhosted.org/packages/3e/e5/c723545c3fd3204ebde3b4cc4b927dce709d3b6dc577754bb57f63ca4a4a/coverage-7.9.1-pp39.pp310.pp311-none-any.whl", hash = "sha256:db0f04118d1db74db6c9e1cb1898532c7dcc220f1d2718f058601f7c3f499514", size = 204009 },
+ { url = "https://files.pythonhosted.org/packages/08/b8/7ddd1e8ba9701dea08ce22029917140e6f66a859427406579fd8d0ca7274/coverage-7.9.1-py3-none-any.whl", hash = "sha256:66b974b145aa189516b6bf2d8423e888b742517d37872f6ee4c5be0073bd9a3c", size = 204000 },
+]
+
+[package.optional-dependencies]
+toml = [
+ { name = "tomli", marker = "python_full_version <= '3.11'" },
+]
+
+[[package]]
+name = "cryptography"
+version = "45.0.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cffi", marker = "platform_python_implementation != 'PyPy'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/fe/c8/a2a376a8711c1e11708b9c9972e0c3223f5fc682552c82d8db844393d6ce/cryptography-45.0.4.tar.gz", hash = "sha256:7405ade85c83c37682c8fe65554759800a4a8c54b2d96e0f8ad114d31b808d57", size = 744890 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ba/14/93b69f2af9ba832ad6618a03f8a034a5851dc9a3314336a3d71c252467e1/cryptography-45.0.4-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:680806cf63baa0039b920f4976f5f31b10e772de42f16310a6839d9f21a26b0d", size = 4205335 },
+ { url = "https://files.pythonhosted.org/packages/67/30/fae1000228634bf0b647fca80403db5ca9e3933b91dd060570689f0bd0f7/cryptography-45.0.4-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4ca0f52170e821bc8da6fc0cc565b7bb8ff8d90d36b5e9fdd68e8a86bdf72036", size = 4431487 },
+ { url = "https://files.pythonhosted.org/packages/6d/5a/7dffcf8cdf0cb3c2430de7404b327e3db64735747d641fc492539978caeb/cryptography-45.0.4-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f3fe7a5ae34d5a414957cc7f457e2b92076e72938423ac64d215722f6cf49a9e", size = 4208922 },
+ { url = "https://files.pythonhosted.org/packages/c6/f3/528729726eb6c3060fa3637253430547fbaaea95ab0535ea41baa4a6fbd8/cryptography-45.0.4-cp311-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:25eb4d4d3e54595dc8adebc6bbd5623588991d86591a78c2548ffb64797341e2", size = 3900433 },
+ { url = "https://files.pythonhosted.org/packages/d9/4a/67ba2e40f619e04d83c32f7e1d484c1538c0800a17c56a22ff07d092ccc1/cryptography-45.0.4-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:ce1678a2ccbe696cf3af15a75bb72ee008d7ff183c9228592ede9db467e64f1b", size = 4464163 },
+ { url = "https://files.pythonhosted.org/packages/7e/9a/b4d5aa83661483ac372464809c4b49b5022dbfe36b12fe9e323ca8512420/cryptography-45.0.4-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:49fe9155ab32721b9122975e168a6760d8ce4cffe423bcd7ca269ba41b5dfac1", size = 4208687 },
+ { url = "https://files.pythonhosted.org/packages/db/b7/a84bdcd19d9c02ec5807f2ec2d1456fd8451592c5ee353816c09250e3561/cryptography-45.0.4-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:2882338b2a6e0bd337052e8b9007ced85c637da19ef9ecaf437744495c8c2999", size = 4463623 },
+ { url = "https://files.pythonhosted.org/packages/d8/84/69707d502d4d905021cac3fb59a316344e9f078b1da7fb43ecde5e10840a/cryptography-45.0.4-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:23b9c3ea30c3ed4db59e7b9619272e94891f8a3a5591d0b656a7582631ccf750", size = 4332447 },
+ { url = "https://files.pythonhosted.org/packages/f3/ee/d4f2ab688e057e90ded24384e34838086a9b09963389a5ba6854b5876598/cryptography-45.0.4-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:b0a97c927497e3bc36b33987abb99bf17a9a175a19af38a892dc4bbb844d7ee2", size = 4572830 },
+ { url = "https://files.pythonhosted.org/packages/fe/51/8c584ed426093aac257462ae62d26ad61ef1cbf5b58d8b67e6e13c39960e/cryptography-45.0.4-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6a5bf57554e80f75a7db3d4b1dacaa2764611ae166ab42ea9a72bcdb5d577637", size = 4195746 },
+ { url = "https://files.pythonhosted.org/packages/5c/7d/4b0ca4d7af95a704eef2f8f80a8199ed236aaf185d55385ae1d1610c03c2/cryptography-45.0.4-cp37-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:46cf7088bf91bdc9b26f9c55636492c1cce3e7aaf8041bbf0243f5e5325cfb2d", size = 4424456 },
+ { url = "https://files.pythonhosted.org/packages/1d/45/5fabacbc6e76ff056f84d9f60eeac18819badf0cefc1b6612ee03d4ab678/cryptography-45.0.4-cp37-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:7bedbe4cc930fa4b100fc845ea1ea5788fcd7ae9562e669989c11618ae8d76ee", size = 4198495 },
+ { url = "https://files.pythonhosted.org/packages/55/b7/ffc9945b290eb0a5d4dab9b7636706e3b5b92f14ee5d9d4449409d010d54/cryptography-45.0.4-cp37-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:eaa3e28ea2235b33220b949c5a0d6cf79baa80eab2eb5607ca8ab7525331b9ff", size = 3885540 },
+ { url = "https://files.pythonhosted.org/packages/7f/e3/57b010282346980475e77d414080acdcb3dab9a0be63071efc2041a2c6bd/cryptography-45.0.4-cp37-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:7ef2dde4fa9408475038fc9aadfc1fb2676b174e68356359632e980c661ec8f6", size = 4452052 },
+ { url = "https://files.pythonhosted.org/packages/37/e6/ddc4ac2558bf2ef517a358df26f45bc774a99bf4653e7ee34b5e749c03e3/cryptography-45.0.4-cp37-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:6a3511ae33f09094185d111160fd192c67aa0a2a8d19b54d36e4c78f651dc5ad", size = 4198024 },
+ { url = "https://files.pythonhosted.org/packages/3a/c0/85fa358ddb063ec588aed4a6ea1df57dc3e3bc1712d87c8fa162d02a65fc/cryptography-45.0.4-cp37-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:06509dc70dd71fa56eaa138336244e2fbaf2ac164fc9b5e66828fccfd2b680d6", size = 4451442 },
+ { url = "https://files.pythonhosted.org/packages/33/67/362d6ec1492596e73da24e669a7fbbaeb1c428d6bf49a29f7a12acffd5dc/cryptography-45.0.4-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:5f31e6b0a5a253f6aa49be67279be4a7e5a4ef259a9f33c69f7d1b1191939872", size = 4325038 },
+ { url = "https://files.pythonhosted.org/packages/53/75/82a14bf047a96a1b13ebb47fb9811c4f73096cfa2e2b17c86879687f9027/cryptography-45.0.4-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:944e9ccf67a9594137f942d5b52c8d238b1b4e46c7a0c2891b7ae6e01e7c80a4", size = 4560964 },
+ { url = "https://files.pythonhosted.org/packages/c4/b9/357f18064ec09d4807800d05a48f92f3b369056a12f995ff79549fbb31f1/cryptography-45.0.4-pp310-pypy310_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:7aad98a25ed8ac917fdd8a9c1e706e5a0956e06c498be1f713b61734333a4507", size = 4143732 },
+ { url = "https://files.pythonhosted.org/packages/c4/9c/7f7263b03d5db329093617648b9bd55c953de0b245e64e866e560f9aac07/cryptography-45.0.4-pp310-pypy310_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:3530382a43a0e524bc931f187fc69ef4c42828cf7d7f592f7f249f602b5a4ab0", size = 4385424 },
+ { url = "https://files.pythonhosted.org/packages/a6/5a/6aa9d8d5073d5acc0e04e95b2860ef2684b2bd2899d8795fc443013e263b/cryptography-45.0.4-pp310-pypy310_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:6b613164cb8425e2f8db5849ffb84892e523bf6d26deb8f9bb76ae86181fa12b", size = 4142438 },
+ { url = "https://files.pythonhosted.org/packages/42/1c/71c638420f2cdd96d9c2b287fec515faf48679b33a2b583d0f1eda3a3375/cryptography-45.0.4-pp310-pypy310_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:96d4819e25bf3b685199b304a0029ce4a3caf98947ce8a066c9137cc78ad2c58", size = 4384622 },
+ { url = "https://files.pythonhosted.org/packages/28/9a/a7d5bb87d149eb99a5abdc69a41e4e47b8001d767e5f403f78bfaafc7aa7/cryptography-45.0.4-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:03dbff8411206713185b8cebe31bc5c0eb544799a50c09035733716b386e61a4", size = 4146899 },
+ { url = "https://files.pythonhosted.org/packages/17/11/9361c2c71c42cc5c465cf294c8030e72fb0c87752bacbd7a3675245e3db3/cryptography-45.0.4-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:51dfbd4d26172d31150d84c19bbe06c68ea4b7f11bbc7b3a5e146b367c311349", size = 4388900 },
+ { url = "https://files.pythonhosted.org/packages/c0/76/f95b83359012ee0e670da3e41c164a0c256aeedd81886f878911581d852f/cryptography-45.0.4-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:0339a692de47084969500ee455e42c58e449461e0ec845a34a6a9b9bf7df7fb8", size = 4146422 },
+ { url = "https://files.pythonhosted.org/packages/09/ad/5429fcc4def93e577a5407988f89cf15305e64920203d4ac14601a9dc876/cryptography-45.0.4-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:0cf13c77d710131d33e63626bd55ae7c0efb701ebdc2b3a7952b9b23a0412862", size = 4388475 },
+]
+
+[[package]]
+name = "distlib"
+version = "0.3.9"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/0d/dd/1bec4c5ddb504ca60fc29472f3d27e8d4da1257a854e1d96742f15c1d02d/distlib-0.3.9.tar.gz", hash = "sha256:a60f20dea646b8a33f3e7772f74dc0b2d0772d2837ee1342a00645c81edf9403", size = 613923 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/91/a1/cf2472db20f7ce4a6be1253a81cfdf85ad9c7885ffbed7047fb72c24cf87/distlib-0.3.9-py2.py3-none-any.whl", hash = "sha256:47f8c22fd27c27e25a65601af709b38e4f0a45ea4fc2e710f65755fa8caaaf87", size = 468973 },
+]
+
+[[package]]
+name = "docutils"
+version = "0.21.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ae/ed/aefcc8cd0ba62a0560c3c18c33925362d46c6075480bfa4df87b28e169a9/docutils-0.21.2.tar.gz", hash = "sha256:3a6b18732edf182daa3cd12775bbb338cf5691468f91eeeb109deff6ebfa986f", size = 2204444 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/8f/d7/9322c609343d929e75e7e5e6255e614fcc67572cfd083959cdef3b7aad79/docutils-0.21.2-py3-none-any.whl", hash = "sha256:dafca5b9e384f0e419294eb4d2ff9fa826435bf15f15b7bd45723e8ad76811b2", size = 587408 },
+]
+
+[[package]]
+name = "exceptiongroup"
+version = "1.3.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "typing-extensions", marker = "python_full_version < '3.13'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/0b/9f/a65090624ecf468cdca03533906e7c69ed7588582240cfe7cc9e770b50eb/exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88", size = 29749 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/36/f4/c6e662dade71f56cd2f3735141b265c3c79293c109549c1e6933b0651ffc/exceptiongroup-1.3.0-py3-none-any.whl", hash = "sha256:4d111e6e0c13d0644cad6ddaa7ed0261a0b36971f6d23e7ec9b4b9097da78a10", size = 16674 },
+]
+
+[[package]]
+name = "filelock"
+version = "3.18.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/0a/10/c23352565a6544bdc5353e0b15fc1c563352101f30e24bf500207a54df9a/filelock-3.18.0.tar.gz", hash = "sha256:adbc88eabb99d2fec8c9c1b229b171f18afa655400173ddc653d5d01501fb9f2", size = 18075 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/4d/36/2a115987e2d8c300a974597416d9de88f2444426de9571f4b59b2cca3acc/filelock-3.18.0-py3-none-any.whl", hash = "sha256:c401f4f8377c4464e6db25fff06205fd89bdd83b65eb0488ed1b160f780e21de", size = 16215 },
+]
+
+[[package]]
+name = "h11"
+version = "0.16.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515 },
+]
+
+[[package]]
+name = "hatch"
+version = "1.14.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "click", version = "8.1.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "click", version = "8.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+ { name = "hatchling" },
+ { name = "httpx" },
+ { name = "hyperlink" },
+ { name = "keyring" },
+ { name = "packaging" },
+ { name = "pexpect" },
+ { name = "platformdirs" },
+ { name = "rich" },
+ { name = "shellingham" },
+ { name = "tomli-w" },
+ { name = "tomlkit" },
+ { name = "userpath" },
+ { name = "uv" },
+ { name = "virtualenv" },
+ { name = "zstandard" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/1f/43/c0b37db0e857a44ce5ffdb7e8a9b8fa6425d0b74dea698fafcd9bddb50d1/hatch-1.14.1.tar.gz", hash = "sha256:ca1aff788f8596b0dd1f8f8dfe776443d2724a86b1976fabaf087406ba3d0713", size = 5188180 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a5/40/19c0935bf9f25808541a0e3144ac459de696c5b6b6d4511a98d456c69604/hatch-1.14.1-py3-none-any.whl", hash = "sha256:39cdaa59e47ce0c5505d88a951f4324a9c5aafa17e4a877e2fde79b36ab66c21", size = 125770 },
+]
+
+[[package]]
+name = "hatchling"
+version = "1.27.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "packaging" },
+ { name = "pathspec" },
+ { name = "pluggy" },
+ { name = "tomli", marker = "python_full_version < '3.11'" },
+ { name = "trove-classifiers" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/8f/8a/cc1debe3514da292094f1c3a700e4ca25442489731ef7c0814358816bb03/hatchling-1.27.0.tar.gz", hash = "sha256:971c296d9819abb3811112fc52c7a9751c8d381898f36533bb16f9791e941fd6", size = 54983 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/08/e7/ae38d7a6dfba0533684e0b2136817d667588ae3ec984c1a4e5df5eb88482/hatchling-1.27.0-py3-none-any.whl", hash = "sha256:d3a2f3567c4f926ea39849cdf924c7e99e6686c9c8e288ae1037c8fa2a5d937b", size = 75794 },
+]
+
+[[package]]
+name = "httpcore"
+version = "1.0.9"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "certifi" },
+ { name = "h11" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784 },
+]
+
+[[package]]
+name = "httpx"
+version = "0.28.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "anyio" },
+ { name = "certifi" },
+ { name = "httpcore" },
+ { name = "idna" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517 },
+]
+
+[[package]]
+name = "hyperlink"
+version = "21.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "idna" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/3a/51/1947bd81d75af87e3bb9e34593a4cf118115a8feb451ce7a69044ef1412e/hyperlink-21.0.0.tar.gz", hash = "sha256:427af957daa58bc909471c6c40f74c5450fa123dd093fc53efd2e91d2705a56b", size = 140743 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/6e/aa/8caf6a0a3e62863cbb9dab27135660acba46903b703e224f14f447e57934/hyperlink-21.0.0-py2.py3-none-any.whl", hash = "sha256:e6b14c37ecb73e89c77d78cdb4c2cc8f3fb59a885c5b3f819ff4ed80f25af1b4", size = 74638 },
+]
+
+[[package]]
+name = "id"
+version = "1.5.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/22/11/102da08f88412d875fa2f1a9a469ff7ad4c874b0ca6fed0048fe385bdb3d/id-1.5.0.tar.gz", hash = "sha256:292cb8a49eacbbdbce97244f47a97b4c62540169c976552e497fd57df0734c1d", size = 15237 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9f/cb/18326d2d89ad3b0dd143da971e77afd1e6ca6674f1b1c3df4b6bec6279fc/id-1.5.0-py3-none-any.whl", hash = "sha256:f1434e1cef91f2cbb8a4ec64663d5a23b9ed43ef44c4c957d02583d61714c658", size = 13611 },
+]
+
+[[package]]
+name = "identify"
+version = "2.6.12"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a2/88/d193a27416618628a5eea64e3223acd800b40749a96ffb322a9b55a49ed1/identify-2.6.12.tar.gz", hash = "sha256:d8de45749f1efb108badef65ee8386f0f7bb19a7f26185f74de6367bffbaf0e6", size = 99254 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7a/cd/18f8da995b658420625f7ef13f037be53ae04ec5ad33f9b718240dcfd48c/identify-2.6.12-py2.py3-none-any.whl", hash = "sha256:ad9672d5a72e0d2ff7c5c8809b62dfa60458626352fb0eb7b55e69bdc45334a2", size = 99145 },
+]
+
+[[package]]
+name = "idna"
+version = "3.10"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f1/70/7703c29685631f5a7590aa73f1f1d3fa9a380e654b86af429e0934a32f7d/idna-3.10.tar.gz", hash = "sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9", size = 190490 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/76/c6/c88e154df9c4e1a2a66ccf0005a88dfb2650c1dffb6f5ce603dfbd452ce3/idna-3.10-py3-none-any.whl", hash = "sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3", size = 70442 },
+]
+
+[[package]]
+name = "importlib-metadata"
+version = "8.7.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "zipp" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/76/66/650a33bd90f786193e4de4b3ad86ea60b53c89b669a5c7be931fac31cdb0/importlib_metadata-8.7.0.tar.gz", hash = "sha256:d13b81ad223b890aa16c5471f2ac3056cf76c5f10f82d6f9292f0b415f389000", size = 56641 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/20/b0/36bd937216ec521246249be3bf9855081de4c5e06a0c9b4219dbeda50373/importlib_metadata-8.7.0-py3-none-any.whl", hash = "sha256:e5dd1551894c77868a30651cef00984d50e1002d06942a7101d34870c5f02afd", size = 27656 },
+]
+
+[[package]]
+name = "iniconfig"
+version = "2.1.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f2/97/ebf4da567aa6827c909642694d71c9fcf53e5b504f2d96afea02718862f3/iniconfig-2.1.0.tar.gz", hash = "sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7", size = 4793 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2c/e1/e6716421ea10d38022b952c159d5161ca1193197fb744506875fbb87ea7b/iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760", size = 6050 },
+]
+
+[[package]]
+name = "jaraco-classes"
+version = "3.4.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "more-itertools" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/06/c0/ed4a27bc5571b99e3cff68f8a9fa5b56ff7df1c2251cc715a652ddd26402/jaraco.classes-3.4.0.tar.gz", hash = "sha256:47a024b51d0239c0dd8c8540c6c7f484be3b8fcf0b2d85c13825780d3b3f3acd", size = 11780 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7f/66/b15ce62552d84bbfcec9a4873ab79d993a1dd4edb922cbfccae192bd5b5f/jaraco.classes-3.4.0-py3-none-any.whl", hash = "sha256:f662826b6bed8cace05e7ff873ce0f9283b5c924470fe664fff1c2f00f581790", size = 6777 },
+]
+
+[[package]]
+name = "jaraco-context"
+version = "6.0.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "backports-tarfile", marker = "python_full_version < '3.12'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/df/ad/f3777b81bf0b6e7bc7514a1656d3e637b2e8e15fab2ce3235730b3e7a4e6/jaraco_context-6.0.1.tar.gz", hash = "sha256:9bae4ea555cf0b14938dc0aee7c9f32ed303aa20a3b73e7dc80111628792d1b3", size = 13912 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ff/db/0c52c4cf5e4bd9f5d7135ec7669a3a767af21b3a308e1ed3674881e52b62/jaraco.context-6.0.1-py3-none-any.whl", hash = "sha256:f797fc481b490edb305122c9181830a3a5b76d84ef6d1aef2fb9b47ab956f9e4", size = 6825 },
+]
+
+[[package]]
+name = "jaraco-functools"
+version = "4.2.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "more-itertools" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/49/1c/831faaaa0f090b711c355c6d8b2abf277c72133aab472b6932b03322294c/jaraco_functools-4.2.1.tar.gz", hash = "sha256:be634abfccabce56fa3053f8c7ebe37b682683a4ee7793670ced17bab0087353", size = 19661 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f3/fd/179a20f832824514df39a90bb0e5372b314fea99f217f5ab942b10a8a4e8/jaraco_functools-4.2.1-py3-none-any.whl", hash = "sha256:590486285803805f4b1f99c60ca9e94ed348d4added84b74c7a12885561e524e", size = 10349 },
+]
+
+[[package]]
+name = "jeepney"
+version = "0.9.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/7b/6f/357efd7602486741aa73ffc0617fb310a29b588ed0fd69c2399acbb85b0c/jeepney-0.9.0.tar.gz", hash = "sha256:cf0e9e845622b81e4a28df94c40345400256ec608d0e55bb8a3feaa9163f5732", size = 106758 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b2/a3/e137168c9c44d18eff0376253da9f1e9234d0239e0ee230d2fee6cea8e55/jeepney-0.9.0-py3-none-any.whl", hash = "sha256:97e5714520c16fc0a45695e5365a2e11b81ea79bba796e26f9f1d178cb182683", size = 49010 },
+]
+
+[[package]]
+name = "keyring"
+version = "25.6.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "importlib-metadata", marker = "python_full_version < '3.12'" },
+ { name = "jaraco-classes" },
+ { name = "jaraco-context" },
+ { name = "jaraco-functools" },
+ { name = "jeepney", marker = "sys_platform == 'linux'" },
+ { name = "pywin32-ctypes", marker = "sys_platform == 'win32'" },
+ { name = "secretstorage", marker = "sys_platform == 'linux'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/70/09/d904a6e96f76ff214be59e7aa6ef7190008f52a0ab6689760a98de0bf37d/keyring-25.6.0.tar.gz", hash = "sha256:0b39998aa941431eb3d9b0d4b2460bc773b9df6fed7621c2dfb291a7e0187a66", size = 62750 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d3/32/da7f44bcb1105d3e88a0b74ebdca50c59121d2ddf71c9e34ba47df7f3a56/keyring-25.6.0-py3-none-any.whl", hash = "sha256:552a3f7af126ece7ed5c89753650eec89c7eaae8617d0aa4d9ad2b75111266bd", size = 39085 },
+]
+
+[[package]]
+name = "mail-parser"
+source = { editable = "." }
+
+[package.dev-dependencies]
+dev = [
+ { name = "build" },
+ { name = "hatch" },
+ { name = "pre-commit" },
+ { name = "ruff" },
+ { name = "twine" },
+ { name = "wheel" },
+]
+test = [
+ { name = "coverage" },
+ { name = "pytest" },
+ { name = "pytest-cov" },
+ { name = "pytest-mock" },
+ { name = "pytest-ordering" },
+]
+
+[package.metadata]
+
+[package.metadata.requires-dev]
+dev = [
+ { name = "build", specifier = ">=1.2.2.post1" },
+ { name = "hatch", specifier = ">=1.14.0" },
+ { name = "pre-commit", specifier = ">=4.0.1" },
+ { name = "ruff", specifier = ">=0.9.9" },
+ { name = "twine", specifier = ">=6.0.1" },
+ { name = "wheel", specifier = ">=0.45.1" },
+]
+test = [
+ { name = "coverage", specifier = ">=7.6.10" },
+ { name = "pytest", specifier = ">=8.3.4" },
+ { name = "pytest-cov", specifier = ">=6.0.0" },
+ { name = "pytest-mock", specifier = ">=3.14.0" },
+ { name = "pytest-ordering", specifier = ">=0.6" },
+]
+
+[[package]]
+name = "markdown-it-py"
+version = "3.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "mdurl" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/38/71/3b932df36c1a044d397a1f92d1cf91ee0a503d91e470cbd670aa66b07ed0/markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb", size = 74596 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/42/d7/1ec15b46af6af88f19b8e5ffea08fa375d433c998b8a7639e76935c14f1f/markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1", size = 87528 },
+]
+
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d6/54/cfe61301667036ec958cb99bd3efefba235e65cdeb9c84d24a8293ba1d90/mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba", size = 8729 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979 },
+]
+
+[[package]]
+name = "more-itertools"
+version = "10.7.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ce/a0/834b0cebabbfc7e311f30b46c8188790a37f89fc8d756660346fe5abfd09/more_itertools-10.7.0.tar.gz", hash = "sha256:9fddd5403be01a94b204faadcff459ec3568cf110265d3c54323e1e866ad29d3", size = 127671 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2b/9f/7ba6f94fc1e9ac3d2b853fdff3035fb2fa5afbed898c4a72b8a020610594/more_itertools-10.7.0-py3-none-any.whl", hash = "sha256:d43980384673cb07d2f7d2d918c616b30c659c089ee23953f601d6609c67510e", size = 65278 },
+]
+
+[[package]]
+name = "nh3"
+version = "0.2.21"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/37/30/2f81466f250eb7f591d4d193930df661c8c23e9056bdc78e365b646054d8/nh3-0.2.21.tar.gz", hash = "sha256:4990e7ee6a55490dbf00d61a6f476c9a3258e31e711e13713b2ea7d6616f670e", size = 16581 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7f/81/b83775687fcf00e08ade6d4605f0be9c4584cb44c4973d9f27b7456a31c9/nh3-0.2.21-cp313-cp313t-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:fcff321bd60c6c5c9cb4ddf2554e22772bb41ebd93ad88171bbbb6f271255286", size = 1297678 },
+ { url = "https://files.pythonhosted.org/packages/22/ee/d0ad8fb4b5769f073b2df6807f69a5e57ca9cea504b78809921aef460d20/nh3-0.2.21-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:31eedcd7d08b0eae28ba47f43fd33a653b4cdb271d64f1aeda47001618348fde", size = 733774 },
+ { url = "https://files.pythonhosted.org/packages/ea/76/b450141e2d384ede43fe53953552f1c6741a499a8c20955ad049555cabc8/nh3-0.2.21-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d426d7be1a2f3d896950fe263332ed1662f6c78525b4520c8e9861f8d7f0d243", size = 760012 },
+ { url = "https://files.pythonhosted.org/packages/97/90/1182275db76cd8fbb1f6bf84c770107fafee0cb7da3e66e416bcb9633da2/nh3-0.2.21-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:9d67709bc0d7d1f5797b21db26e7a8b3d15d21c9c5f58ccfe48b5328483b685b", size = 923619 },
+ { url = "https://files.pythonhosted.org/packages/29/c7/269a7cfbec9693fad8d767c34a755c25ccb8d048fc1dfc7a7d86bc99375c/nh3-0.2.21-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:55823c5ea1f6b267a4fad5de39bc0524d49a47783e1fe094bcf9c537a37df251", size = 1000384 },
+ { url = "https://files.pythonhosted.org/packages/68/a9/48479dbf5f49ad93f0badd73fbb48b3d769189f04c6c69b0df261978b009/nh3-0.2.21-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:818f2b6df3763e058efa9e69677b5a92f9bc0acff3295af5ed013da544250d5b", size = 918908 },
+ { url = "https://files.pythonhosted.org/packages/d7/da/0279c118f8be2dc306e56819880b19a1cf2379472e3b79fc8eab44e267e3/nh3-0.2.21-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:b3b5c58161e08549904ac4abd450dacd94ff648916f7c376ae4b2c0652b98ff9", size = 909180 },
+ { url = "https://files.pythonhosted.org/packages/26/16/93309693f8abcb1088ae143a9c8dbcece9c8f7fb297d492d3918340c41f1/nh3-0.2.21-cp313-cp313t-win32.whl", hash = "sha256:637d4a10c834e1b7d9548592c7aad760611415fcd5bd346f77fd8a064309ae6d", size = 532747 },
+ { url = "https://files.pythonhosted.org/packages/a2/3a/96eb26c56cbb733c0b4a6a907fab8408ddf3ead5d1b065830a8f6a9c3557/nh3-0.2.21-cp313-cp313t-win_amd64.whl", hash = "sha256:713d16686596e556b65e7f8c58328c2df63f1a7abe1277d87625dcbbc012ef82", size = 528908 },
+ { url = "https://files.pythonhosted.org/packages/ba/1d/b1ef74121fe325a69601270f276021908392081f4953d50b03cbb38b395f/nh3-0.2.21-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:a772dec5b7b7325780922dd904709f0f5f3a79fbf756de5291c01370f6df0967", size = 1316133 },
+ { url = "https://files.pythonhosted.org/packages/b8/f2/2c7f79ce6de55b41e7715f7f59b159fd59f6cdb66223c05b42adaee2b645/nh3-0.2.21-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d002b648592bf3033adfd875a48f09b8ecc000abd7f6a8769ed86b6ccc70c759", size = 758328 },
+ { url = "https://files.pythonhosted.org/packages/6d/ad/07bd706fcf2b7979c51b83d8b8def28f413b090cf0cb0035ee6b425e9de5/nh3-0.2.21-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2a5174551f95f2836f2ad6a8074560f261cf9740a48437d6151fd2d4d7d617ab", size = 747020 },
+ { url = "https://files.pythonhosted.org/packages/75/99/06a6ba0b8a0d79c3d35496f19accc58199a1fb2dce5e711a31be7e2c1426/nh3-0.2.21-cp38-abi3-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:b8d55ea1fc7ae3633d758a92aafa3505cd3cc5a6e40470c9164d54dff6f96d42", size = 944878 },
+ { url = "https://files.pythonhosted.org/packages/79/d4/dc76f5dc50018cdaf161d436449181557373869aacf38a826885192fc587/nh3-0.2.21-cp38-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6ae319f17cd8960d0612f0f0ddff5a90700fa71926ca800e9028e7851ce44a6f", size = 903460 },
+ { url = "https://files.pythonhosted.org/packages/cd/c3/d4f8037b2ab02ebf5a2e8637bd54736ed3d0e6a2869e10341f8d9085f00e/nh3-0.2.21-cp38-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:63ca02ac6f27fc80f9894409eb61de2cb20ef0a23740c7e29f9ec827139fa578", size = 839369 },
+ { url = "https://files.pythonhosted.org/packages/11/a9/1cd3c6964ec51daed7b01ca4686a5c793581bf4492cbd7274b3f544c9abe/nh3-0.2.21-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a5f77e62aed5c4acad635239ac1290404c7e940c81abe561fd2af011ff59f585", size = 739036 },
+ { url = "https://files.pythonhosted.org/packages/fd/04/bfb3ff08d17a8a96325010ae6c53ba41de6248e63cdb1b88ef6369a6cdfc/nh3-0.2.21-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:087ffadfdcd497658c3adc797258ce0f06be8a537786a7217649fc1c0c60c293", size = 768712 },
+ { url = "https://files.pythonhosted.org/packages/9e/aa/cfc0bf545d668b97d9adea4f8b4598667d2b21b725d83396c343ad12bba7/nh3-0.2.21-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:ac7006c3abd097790e611fe4646ecb19a8d7f2184b882f6093293b8d9b887431", size = 930559 },
+ { url = "https://files.pythonhosted.org/packages/78/9d/6f5369a801d3a1b02e6a9a097d56bcc2f6ef98cffebf03c4bb3850d8e0f0/nh3-0.2.21-cp38-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:6141caabe00bbddc869665b35fc56a478eb774a8c1dfd6fba9fe1dfdf29e6efa", size = 1008591 },
+ { url = "https://files.pythonhosted.org/packages/a6/df/01b05299f68c69e480edff608248313cbb5dbd7595c5e048abe8972a57f9/nh3-0.2.21-cp38-abi3-musllinux_1_2_i686.whl", hash = "sha256:20979783526641c81d2f5bfa6ca5ccca3d1e4472474b162c6256745fbfe31cd1", size = 925670 },
+ { url = "https://files.pythonhosted.org/packages/3d/79/bdba276f58d15386a3387fe8d54e980fb47557c915f5448d8c6ac6f7ea9b/nh3-0.2.21-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:a7ea28cd49293749d67e4fcf326c554c83ec912cd09cd94aa7ec3ab1921c8283", size = 917093 },
+ { url = "https://files.pythonhosted.org/packages/e7/d8/c6f977a5cd4011c914fb58f5ae573b071d736187ccab31bfb1d539f4af9f/nh3-0.2.21-cp38-abi3-win32.whl", hash = "sha256:6c9c30b8b0d291a7c5ab0967ab200598ba33208f754f2f4920e9343bdd88f79a", size = 537623 },
+ { url = "https://files.pythonhosted.org/packages/23/fc/8ce756c032c70ae3dd1d48a3552577a325475af2a2f629604b44f571165c/nh3-0.2.21-cp38-abi3-win_amd64.whl", hash = "sha256:bb0014948f04d7976aabae43fcd4cb7f551f9f8ce785a4c9ef66e6c2590f8629", size = 535283 },
+]
+
+[[package]]
+name = "nodeenv"
+version = "1.9.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/43/16/fc88b08840de0e0a72a2f9d8c6bae36be573e475a6326ae854bcc549fc45/nodeenv-1.9.1.tar.gz", hash = "sha256:6ec12890a2dab7946721edbfbcd91f3319c6ccc9aec47be7c7e6b7011ee6645f", size = 47437 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/d2/1d/1b658dbd2b9fa9c4c9f32accbfc0205d532c8c6194dc0f2a4c0428e7128a/nodeenv-1.9.1-py2.py3-none-any.whl", hash = "sha256:ba11c9782d29c27c70ffbdda2d7415098754709be8a7056d79a737cd901155c9", size = 22314 },
+]
+
+[[package]]
+name = "packaging"
+version = "25.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a1/d4/1fc4078c65507b51b96ca8f8c3ba19e6a61c8253c72794544580a7b6c24d/packaging-25.0.tar.gz", hash = "sha256:d443872c98d677bf60f6a1f2f8c1cb748e8fe762d2bf9d3148b5599295b0fc4f", size = 165727 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/20/12/38679034af332785aac8774540895e234f4d07f7545804097de4b666afd8/packaging-25.0-py3-none-any.whl", hash = "sha256:29572ef2b1f17581046b3a2227d5c611fb25ec70ca1ba8554b24b0e69331a484", size = 66469 },
+]
+
+[[package]]
+name = "pathspec"
+version = "0.12.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/ca/bc/f35b8446f4531a7cb215605d100cd88b7ac6f44ab3fc94870c120ab3adbf/pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712", size = 51043 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/cc/20/ff623b09d963f88bfde16306a54e12ee5ea43e9b597108672ff3a408aad6/pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08", size = 31191 },
+]
+
+[[package]]
+name = "pexpect"
+version = "4.9.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "ptyprocess" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/42/92/cc564bf6381ff43ce1f4d06852fc19a2f11d180f23dc32d9588bee2f149d/pexpect-4.9.0.tar.gz", hash = "sha256:ee7d41123f3c9911050ea2c2dac107568dc43b2d3b0c7557a33212c398ead30f", size = 166450 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9e/c3/059298687310d527a58bb01f3b1965787ee3b40dce76752eda8b44e9a2c5/pexpect-4.9.0-py2.py3-none-any.whl", hash = "sha256:7236d1e080e4936be2dc3e326cec0af72acf9212a7e1d060210e70a47e253523", size = 63772 },
+]
+
+[[package]]
+name = "platformdirs"
+version = "4.3.8"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/fe/8b/3c73abc9c759ecd3f1f7ceff6685840859e8070c4d947c93fae71f6a0bf2/platformdirs-4.3.8.tar.gz", hash = "sha256:3d512d96e16bcb959a814c9f348431070822a6496326a4be0911c40b5a74c2bc", size = 21362 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/fe/39/979e8e21520d4e47a0bbe349e2713c0aac6f3d853d0e5b34d76206c439aa/platformdirs-4.3.8-py3-none-any.whl", hash = "sha256:ff7059bb7eb1179e2685604f4aaf157cfd9535242bd23742eadc3c13542139b4", size = 18567 },
+]
+
+[[package]]
+name = "pluggy"
+version = "1.6.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538 },
+]
+
+[[package]]
+name = "pre-commit"
+version = "4.2.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cfgv" },
+ { name = "identify" },
+ { name = "nodeenv" },
+ { name = "pyyaml" },
+ { name = "virtualenv" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/08/39/679ca9b26c7bb2999ff122d50faa301e49af82ca9c066ec061cfbc0c6784/pre_commit-4.2.0.tar.gz", hash = "sha256:601283b9757afd87d40c4c4a9b2b5de9637a8ea02eaff7adc2d0fb4e04841146", size = 193424 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/88/74/a88bf1b1efeae488a0c0b7bdf71429c313722d1fc0f377537fbe554e6180/pre_commit-4.2.0-py2.py3-none-any.whl", hash = "sha256:a009ca7205f1eb497d10b845e52c838a98b6cdd2102a6c8e4540e94ee75c58bd", size = 220707 },
+]
+
+[[package]]
+name = "ptyprocess"
+version = "0.7.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/20/e5/16ff212c1e452235a90aeb09066144d0c5a6a8c0834397e03f5224495c4e/ptyprocess-0.7.0.tar.gz", hash = "sha256:5c5d0a3b48ceee0b48485e0c26037c0acd7d29765ca3fbb5cb3831d347423220", size = 70762 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/22/a6/858897256d0deac81a172289110f31629fc4cee19b6f01283303e18c8db3/ptyprocess-0.7.0-py2.py3-none-any.whl", hash = "sha256:4b41f3967fce3af57cc7e94b888626c18bf37a083e3651ca8feeb66d492fef35", size = 13993 },
+]
+
+[[package]]
+name = "pycparser"
+version = "2.22"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/1d/b2/31537cf4b1ca988837256c910a668b553fceb8f069bedc4b1c826024b52c/pycparser-2.22.tar.gz", hash = "sha256:491c8be9c040f5390f5bf44a5b07752bd07f56edf992381b05c701439eec10f6", size = 172736 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/13/a3/a812df4e2dd5696d1f351d58b8fe16a405b234ad2886a0dab9183fb78109/pycparser-2.22-py3-none-any.whl", hash = "sha256:c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc", size = 117552 },
+]
+
+[[package]]
+name = "pygments"
+version = "2.19.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/b0/77/a5b8c569bf593b0140bde72ea885a803b82086995367bf2037de0159d924/pygments-2.19.2.tar.gz", hash = "sha256:636cb2477cec7f8952536970bc533bc43743542f70392ae026374600add5b887", size = 4968631 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217 },
+]
+
+[[package]]
+name = "pyproject-hooks"
+version = "1.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e7/82/28175b2414effca1cdac8dc99f76d660e7a4fb0ceefa4b4ab8f5f6742925/pyproject_hooks-1.2.0.tar.gz", hash = "sha256:1e859bd5c40fae9448642dd871adf459e5e2084186e8d2c2a79a824c970da1f8", size = 19228 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bd/24/12818598c362d7f300f18e74db45963dbcb85150324092410c8b49405e42/pyproject_hooks-1.2.0-py3-none-any.whl", hash = "sha256:9e5c6bfa8dcc30091c74b0cf803c81fdd29d94f01992a7707bc97babb1141913", size = 10216 },
+]
+
+[[package]]
+name = "pytest"
+version = "8.4.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "colorama", marker = "sys_platform == 'win32'" },
+ { name = "exceptiongroup", marker = "python_full_version < '3.11'" },
+ { name = "iniconfig" },
+ { name = "packaging" },
+ { name = "pluggy" },
+ { name = "pygments" },
+ { name = "tomli", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/08/ba/45911d754e8eba3d5a841a5ce61a65a685ff1798421ac054f85aa8747dfb/pytest-8.4.1.tar.gz", hash = "sha256:7c67fd69174877359ed9371ec3af8a3d2b04741818c51e5e99cc1742251fa93c", size = 1517714 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/29/16/c8a903f4c4dffe7a12843191437d7cd8e32751d5de349d45d3fe69544e87/pytest-8.4.1-py3-none-any.whl", hash = "sha256:539c70ba6fcead8e78eebbf1115e8b589e7565830d7d006a8723f19ac8a0afb7", size = 365474 },
+]
+
+[[package]]
+name = "pytest-cov"
+version = "6.2.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "coverage", extra = ["toml"] },
+ { name = "pluggy" },
+ { name = "pytest" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/18/99/668cade231f434aaa59bbfbf49469068d2ddd945000621d3d165d2e7dd7b/pytest_cov-6.2.1.tar.gz", hash = "sha256:25cc6cc0a5358204b8108ecedc51a9b57b34cc6b8c967cc2c01a4e00d8a67da2", size = 69432 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bc/16/4ea354101abb1287856baa4af2732be351c7bee728065aed451b678153fd/pytest_cov-6.2.1-py3-none-any.whl", hash = "sha256:f5bc4c23f42f1cdd23c70b1dab1bbaef4fc505ba950d53e0081d0730dd7e86d5", size = 24644 },
+]
+
+[[package]]
+name = "pytest-mock"
+version = "3.14.1"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pytest" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/71/28/67172c96ba684058a4d24ffe144d64783d2a270d0af0d9e792737bddc75c/pytest_mock-3.14.1.tar.gz", hash = "sha256:159e9edac4c451ce77a5cdb9fc5d1100708d2dd4ba3c3df572f14097351af80e", size = 33241 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/b2/05/77b60e520511c53d1c1ca75f1930c7dd8e971d0c4379b7f4b3f9644685ba/pytest_mock-3.14.1-py3-none-any.whl", hash = "sha256:178aefcd11307d874b4cd3100344e7e2d888d9791a6a1d9bfe90fbc1b74fd1d0", size = 9923 },
+]
+
+[[package]]
+name = "pytest-ordering"
+version = "0.6"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pytest" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e1/ba/65091c36e6e18da479d22d860586e3ba3a4237cc92a66e3ddd945e4fe761/pytest-ordering-0.6.tar.gz", hash = "sha256:561ad653626bb171da78e682f6d39ac33bb13b3e272d406cd555adb6b006bda6", size = 2629 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ec/98/adc368fe369465f291ab24e18b9900473786ed1afdf861ba90467eb0767e/pytest_ordering-0.6-py3-none-any.whl", hash = "sha256:3f314a178dbeb6777509548727dc69edf22d6d9a2867bf2d310ab85c403380b6", size = 4643 },
+]
+
+[[package]]
+name = "pywin32-ctypes"
+version = "0.2.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/85/9f/01a1a99704853cb63f253eea009390c88e7131c67e66a0a02099a8c917cb/pywin32-ctypes-0.2.3.tar.gz", hash = "sha256:d162dc04946d704503b2edc4d55f3dba5c1d539ead017afa00142c38b9885755", size = 29471 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/de/3d/8161f7711c017e01ac9f008dfddd9410dff3674334c233bde66e7ba65bbf/pywin32_ctypes-0.2.3-py3-none-any.whl", hash = "sha256:8a1513379d709975552d202d942d9837758905c8d01eb82b8bcc30918929e7b8", size = 30756 },
+]
+
+[[package]]
+name = "pyyaml"
+version = "6.0.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/54/ed/79a089b6be93607fa5cdaedf301d7dfb23af5f25c398d5ead2525b063e17/pyyaml-6.0.2.tar.gz", hash = "sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e", size = 130631 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/9b/95/a3fac87cb7158e231b5a6012e438c647e1a87f09f8e0d123acec8ab8bf71/PyYAML-6.0.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:0a9a2848a5b7feac301353437eb7d5957887edbf81d56e903999a75a3d743086", size = 184199 },
+ { url = "https://files.pythonhosted.org/packages/c7/7a/68bd47624dab8fd4afbfd3c48e3b79efe09098ae941de5b58abcbadff5cb/PyYAML-6.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:29717114e51c84ddfba879543fb232a6ed60086602313ca38cce623c1d62cfbf", size = 171758 },
+ { url = "https://files.pythonhosted.org/packages/49/ee/14c54df452143b9ee9f0f29074d7ca5516a36edb0b4cc40c3f280131656f/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8824b5a04a04a047e72eea5cec3bc266db09e35de6bdfe34c9436ac5ee27d237", size = 718463 },
+ { url = "https://files.pythonhosted.org/packages/4d/61/de363a97476e766574650d742205be468921a7b532aa2499fcd886b62530/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7c36280e6fb8385e520936c3cb3b8042851904eba0e58d277dca80a5cfed590b", size = 719280 },
+ { url = "https://files.pythonhosted.org/packages/6b/4e/1523cb902fd98355e2e9ea5e5eb237cbc5f3ad5f3075fa65087aa0ecb669/PyYAML-6.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ec031d5d2feb36d1d1a24380e4db6d43695f3748343d99434e6f5f9156aaa2ed", size = 751239 },
+ { url = "https://files.pythonhosted.org/packages/b7/33/5504b3a9a4464893c32f118a9cc045190a91637b119a9c881da1cf6b7a72/PyYAML-6.0.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:936d68689298c36b53b29f23c6dbb74de12b4ac12ca6cfe0e047bedceea56180", size = 695802 },
+ { url = "https://files.pythonhosted.org/packages/5c/20/8347dcabd41ef3a3cdc4f7b7a2aff3d06598c8779faa189cdbf878b626a4/PyYAML-6.0.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:23502f431948090f597378482b4812b0caae32c22213aecf3b55325e049a6c68", size = 720527 },
+ { url = "https://files.pythonhosted.org/packages/be/aa/5afe99233fb360d0ff37377145a949ae258aaab831bde4792b32650a4378/PyYAML-6.0.2-cp310-cp310-win32.whl", hash = "sha256:2e99c6826ffa974fe6e27cdb5ed0021786b03fc98e5ee3c5bfe1fd5015f42b99", size = 144052 },
+ { url = "https://files.pythonhosted.org/packages/b5/84/0fa4b06f6d6c958d207620fc60005e241ecedceee58931bb20138e1e5776/PyYAML-6.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:a4d3091415f010369ae4ed1fc6b79def9416358877534caf6a0fdd2146c87a3e", size = 161774 },
+ { url = "https://files.pythonhosted.org/packages/f8/aa/7af4e81f7acba21a4c6be026da38fd2b872ca46226673c89a758ebdc4fd2/PyYAML-6.0.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cc1c1159b3d456576af7a3e4d1ba7e6924cb39de8f67111c735f6fc832082774", size = 184612 },
+ { url = "https://files.pythonhosted.org/packages/8b/62/b9faa998fd185f65c1371643678e4d58254add437edb764a08c5a98fb986/PyYAML-6.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1e2120ef853f59c7419231f3bf4e7021f1b936f6ebd222406c3b60212205d2ee", size = 172040 },
+ { url = "https://files.pythonhosted.org/packages/ad/0c/c804f5f922a9a6563bab712d8dcc70251e8af811fce4524d57c2c0fd49a4/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5d225db5a45f21e78dd9358e58a98702a0302f2659a3c6cd320564b75b86f47c", size = 736829 },
+ { url = "https://files.pythonhosted.org/packages/51/16/6af8d6a6b210c8e54f1406a6b9481febf9c64a3109c541567e35a49aa2e7/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:5ac9328ec4831237bec75defaf839f7d4564be1e6b25ac710bd1a96321cc8317", size = 764167 },
+ { url = "https://files.pythonhosted.org/packages/75/e4/2c27590dfc9992f73aabbeb9241ae20220bd9452df27483b6e56d3975cc5/PyYAML-6.0.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ad2a3decf9aaba3d29c8f537ac4b243e36bef957511b4766cb0057d32b0be85", size = 762952 },
+ { url = "https://files.pythonhosted.org/packages/9b/97/ecc1abf4a823f5ac61941a9c00fe501b02ac3ab0e373c3857f7d4b83e2b6/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ff3824dc5261f50c9b0dfb3be22b4567a6f938ccce4587b38952d85fd9e9afe4", size = 735301 },
+ { url = "https://files.pythonhosted.org/packages/45/73/0f49dacd6e82c9430e46f4a027baa4ca205e8b0a9dce1397f44edc23559d/PyYAML-6.0.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:797b4f722ffa07cc8d62053e4cff1486fa6dc094105d13fea7b1de7d8bf71c9e", size = 756638 },
+ { url = "https://files.pythonhosted.org/packages/22/5f/956f0f9fc65223a58fbc14459bf34b4cc48dec52e00535c79b8db361aabd/PyYAML-6.0.2-cp311-cp311-win32.whl", hash = "sha256:11d8f3dd2b9c1207dcaf2ee0bbbfd5991f571186ec9cc78427ba5bd32afae4b5", size = 143850 },
+ { url = "https://files.pythonhosted.org/packages/ed/23/8da0bbe2ab9dcdd11f4f4557ccaf95c10b9811b13ecced089d43ce59c3c8/PyYAML-6.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:e10ce637b18caea04431ce14fabcf5c64a1c61ec9c56b071a4b7ca131ca52d44", size = 161980 },
+ { url = "https://files.pythonhosted.org/packages/86/0c/c581167fc46d6d6d7ddcfb8c843a4de25bdd27e4466938109ca68492292c/PyYAML-6.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab", size = 183873 },
+ { url = "https://files.pythonhosted.org/packages/a8/0c/38374f5bb272c051e2a69281d71cba6fdb983413e6758b84482905e29a5d/PyYAML-6.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725", size = 173302 },
+ { url = "https://files.pythonhosted.org/packages/c3/93/9916574aa8c00aa06bbac729972eb1071d002b8e158bd0e83a3b9a20a1f7/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5", size = 739154 },
+ { url = "https://files.pythonhosted.org/packages/95/0f/b8938f1cbd09739c6da569d172531567dbcc9789e0029aa070856f123984/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b22676e8097e9e22e36d6b7bda33190d0d400f345f23d4065d48f4ca7ae0425", size = 766223 },
+ { url = "https://files.pythonhosted.org/packages/b9/2b/614b4752f2e127db5cc206abc23a8c19678e92b23c3db30fc86ab731d3bd/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80bab7bfc629882493af4aa31a4cfa43a4c57c83813253626916b8c7ada83476", size = 767542 },
+ { url = "https://files.pythonhosted.org/packages/d4/00/dd137d5bcc7efea1836d6264f049359861cf548469d18da90cd8216cf05f/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:0833f8694549e586547b576dcfaba4a6b55b9e96098b36cdc7ebefe667dfed48", size = 731164 },
+ { url = "https://files.pythonhosted.org/packages/c9/1f/4f998c900485e5c0ef43838363ba4a9723ac0ad73a9dc42068b12aaba4e4/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8b9c7197f7cb2738065c481a0461e50ad02f18c78cd75775628afb4d7137fb3b", size = 756611 },
+ { url = "https://files.pythonhosted.org/packages/df/d1/f5a275fdb252768b7a11ec63585bc38d0e87c9e05668a139fea92b80634c/PyYAML-6.0.2-cp312-cp312-win32.whl", hash = "sha256:ef6107725bd54b262d6dedcc2af448a266975032bc85ef0172c5f059da6325b4", size = 140591 },
+ { url = "https://files.pythonhosted.org/packages/0c/e8/4f648c598b17c3d06e8753d7d13d57542b30d56e6c2dedf9c331ae56312e/PyYAML-6.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:7e7401d0de89a9a855c839bc697c079a4af81cf878373abd7dc625847d25cbd8", size = 156338 },
+ { url = "https://files.pythonhosted.org/packages/ef/e3/3af305b830494fa85d95f6d95ef7fa73f2ee1cc8ef5b495c7c3269fb835f/PyYAML-6.0.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:efdca5630322a10774e8e98e1af481aad470dd62c3170801852d752aa7a783ba", size = 181309 },
+ { url = "https://files.pythonhosted.org/packages/45/9f/3b1c20a0b7a3200524eb0076cc027a970d320bd3a6592873c85c92a08731/PyYAML-6.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:50187695423ffe49e2deacb8cd10510bc361faac997de9efef88badc3bb9e2d1", size = 171679 },
+ { url = "https://files.pythonhosted.org/packages/7c/9a/337322f27005c33bcb656c655fa78325b730324c78620e8328ae28b64d0c/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0ffe8360bab4910ef1b9e87fb812d8bc0a308b0d0eef8c8f44e0254ab3b07133", size = 733428 },
+ { url = "https://files.pythonhosted.org/packages/a3/69/864fbe19e6c18ea3cc196cbe5d392175b4cf3d5d0ac1403ec3f2d237ebb5/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:17e311b6c678207928d649faa7cb0d7b4c26a0ba73d41e99c4fff6b6c3276484", size = 763361 },
+ { url = "https://files.pythonhosted.org/packages/04/24/b7721e4845c2f162d26f50521b825fb061bc0a5afcf9a386840f23ea19fa/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70b189594dbe54f75ab3a1acec5f1e3faa7e8cf2f1e08d9b561cb41b845f69d5", size = 759523 },
+ { url = "https://files.pythonhosted.org/packages/2b/b2/e3234f59ba06559c6ff63c4e10baea10e5e7df868092bf9ab40e5b9c56b6/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:41e4e3953a79407c794916fa277a82531dd93aad34e29c2a514c2c0c5fe971cc", size = 726660 },
+ { url = "https://files.pythonhosted.org/packages/fe/0f/25911a9f080464c59fab9027482f822b86bf0608957a5fcc6eaac85aa515/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:68ccc6023a3400877818152ad9a1033e3db8625d899c72eacb5a668902e4d652", size = 751597 },
+ { url = "https://files.pythonhosted.org/packages/14/0d/e2c3b43bbce3cf6bd97c840b46088a3031085179e596d4929729d8d68270/PyYAML-6.0.2-cp313-cp313-win32.whl", hash = "sha256:bc2fa7c6b47d6bc618dd7fb02ef6fdedb1090ec036abab80d4681424b84c1183", size = 140527 },
+ { url = "https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563", size = 156446 },
+ { url = "https://files.pythonhosted.org/packages/65/d8/b7a1db13636d7fb7d4ff431593c510c8b8fca920ade06ca8ef20015493c5/PyYAML-6.0.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:688ba32a1cffef67fd2e9398a2efebaea461578b0923624778664cc1c914db5d", size = 184777 },
+ { url = "https://files.pythonhosted.org/packages/0a/02/6ec546cd45143fdf9840b2c6be8d875116a64076218b61d68e12548e5839/PyYAML-6.0.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:a8786accb172bd8afb8be14490a16625cbc387036876ab6ba70912730faf8e1f", size = 172318 },
+ { url = "https://files.pythonhosted.org/packages/0e/9a/8cc68be846c972bda34f6c2a93abb644fb2476f4dcc924d52175786932c9/PyYAML-6.0.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d8e03406cac8513435335dbab54c0d385e4a49e4945d2909a581c83647ca0290", size = 720891 },
+ { url = "https://files.pythonhosted.org/packages/e9/6c/6e1b7f40181bc4805e2e07f4abc10a88ce4648e7e95ff1abe4ae4014a9b2/PyYAML-6.0.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f753120cb8181e736c57ef7636e83f31b9c0d1722c516f7e86cf15b7aa57ff12", size = 722614 },
+ { url = "https://files.pythonhosted.org/packages/3d/32/e7bd8535d22ea2874cef6a81021ba019474ace0d13a4819c2a4bce79bd6a/PyYAML-6.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3b1fdb9dc17f5a7677423d508ab4f243a726dea51fa5e70992e59a7411c89d19", size = 737360 },
+ { url = "https://files.pythonhosted.org/packages/d7/12/7322c1e30b9be969670b672573d45479edef72c9a0deac3bb2868f5d7469/PyYAML-6.0.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:0b69e4ce7a131fe56b7e4d770c67429700908fc0752af059838b1cfb41960e4e", size = 699006 },
+ { url = "https://files.pythonhosted.org/packages/82/72/04fcad41ca56491995076630c3ec1e834be241664c0c09a64c9a2589b507/PyYAML-6.0.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:a9f8c2e67970f13b16084e04f134610fd1d374bf477b17ec1599185cf611d725", size = 723577 },
+ { url = "https://files.pythonhosted.org/packages/ed/5e/46168b1f2757f1fcd442bc3029cd8767d88a98c9c05770d8b420948743bb/PyYAML-6.0.2-cp39-cp39-win32.whl", hash = "sha256:6395c297d42274772abc367baaa79683958044e5d3835486c16da75d2a694631", size = 144593 },
+ { url = "https://files.pythonhosted.org/packages/19/87/5124b1c1f2412bb95c59ec481eaf936cd32f0fe2a7b16b97b81c4c017a6a/PyYAML-6.0.2-cp39-cp39-win_amd64.whl", hash = "sha256:39693e1f8320ae4f43943590b49779ffb98acb81f788220ea932a6b6c51004d8", size = 162312 },
+]
+
+[[package]]
+name = "readme-renderer"
+version = "44.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "docutils" },
+ { name = "nh3" },
+ { name = "pygments" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/5a/a9/104ec9234c8448c4379768221ea6df01260cd6c2ce13182d4eac531c8342/readme_renderer-44.0.tar.gz", hash = "sha256:8712034eabbfa6805cacf1402b4eeb2a73028f72d1166d6f5cb7f9c047c5d1e1", size = 32056 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e1/67/921ec3024056483db83953ae8e48079ad62b92db7880013ca77632921dd0/readme_renderer-44.0-py3-none-any.whl", hash = "sha256:2fbca89b81a08526aadf1357a8c2ae889ec05fb03f5da67f9769c9a592166151", size = 13310 },
+]
+
+[[package]]
+name = "requests"
+version = "2.32.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "certifi" },
+ { name = "charset-normalizer" },
+ { name = "idna" },
+ { name = "urllib3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/e1/0a/929373653770d8a0d7ea76c37de6e41f11eb07559b103b1c02cafb3f7cf8/requests-2.32.4.tar.gz", hash = "sha256:27d0316682c8a29834d3264820024b62a36942083d52caf2f14c0591336d3422", size = 135258 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7c/e4/56027c4a6b4ae70ca9de302488c5ca95ad4a39e190093d6c1a8ace08341b/requests-2.32.4-py3-none-any.whl", hash = "sha256:27babd3cda2a6d50b30443204ee89830707d396671944c998b5975b031ac2b2c", size = 64847 },
+]
+
+[[package]]
+name = "requests-toolbelt"
+version = "1.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "requests" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/f3/61/d7545dafb7ac2230c70d38d31cbfe4cc64f7144dc41f6e4e4b78ecd9f5bb/requests-toolbelt-1.0.0.tar.gz", hash = "sha256:7681a0a3d047012b5bdc0ee37d7f8f07ebe76ab08caeccfc3921ce23c88d5bc6", size = 206888 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3f/51/d4db610ef29373b879047326cbf6fa98b6c1969d6f6dc423279de2b1be2c/requests_toolbelt-1.0.0-py2.py3-none-any.whl", hash = "sha256:cccfdd665f0a24fcf4726e690f65639d272bb0637b9b92dfd91a5568ccf6bd06", size = 54481 },
+]
+
+[[package]]
+name = "rfc3986"
+version = "2.0.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/85/40/1520d68bfa07ab5a6f065a186815fb6610c86fe957bc065754e47f7b0840/rfc3986-2.0.0.tar.gz", hash = "sha256:97aacf9dbd4bfd829baad6e6309fa6573aaf1be3f6fa735c8ab05e46cecb261c", size = 49026 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/ff/9a/9afaade874b2fa6c752c36f1548f718b5b83af81ed9b76628329dab81c1b/rfc3986-2.0.0-py2.py3-none-any.whl", hash = "sha256:50b1502b60e289cb37883f3dfd34532b8873c7de9f49bb546641ce9cbd256ebd", size = 31326 },
+]
+
+[[package]]
+name = "rich"
+version = "14.0.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "markdown-it-py" },
+ { name = "pygments" },
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/a1/53/830aa4c3066a8ab0ae9a9955976fb770fe9c6102117c8ec4ab3ea62d89e8/rich-14.0.0.tar.gz", hash = "sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725", size = 224078 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0d/9b/63f4c7ebc259242c89b3acafdb37b41d1185c07ff0011164674e9076b491/rich-14.0.0-py3-none-any.whl", hash = "sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0", size = 243229 },
+]
+
+[[package]]
+name = "ruff"
+version = "0.12.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/24/90/5255432602c0b196a0da6720f6f76b93eb50baef46d3c9b0025e2f9acbf3/ruff-0.12.0.tar.gz", hash = "sha256:4d047db3662418d4a848a3fdbfaf17488b34b62f527ed6f10cb8afd78135bc5c", size = 4376101 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e6/fd/b46bb20e14b11ff49dbc74c61de352e0dc07fb650189513631f6fb5fc69f/ruff-0.12.0-py3-none-linux_armv6l.whl", hash = "sha256:5652a9ecdb308a1754d96a68827755f28d5dfb416b06f60fd9e13f26191a8848", size = 10311554 },
+ { url = "https://files.pythonhosted.org/packages/e7/d3/021dde5a988fa3e25d2468d1dadeea0ae89dc4bc67d0140c6e68818a12a1/ruff-0.12.0-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:05ed0c914fabc602fc1f3b42c53aa219e5736cb030cdd85640c32dbc73da74a6", size = 11118435 },
+ { url = "https://files.pythonhosted.org/packages/07/a2/01a5acf495265c667686ec418f19fd5c32bcc326d4c79ac28824aecd6a32/ruff-0.12.0-py3-none-macosx_11_0_arm64.whl", hash = "sha256:07a7aa9b69ac3fcfda3c507916d5d1bca10821fe3797d46bad10f2c6de1edda0", size = 10466010 },
+ { url = "https://files.pythonhosted.org/packages/4c/57/7caf31dd947d72e7aa06c60ecb19c135cad871a0a8a251723088132ce801/ruff-0.12.0-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e7731c3eec50af71597243bace7ec6104616ca56dda2b99c89935fe926bdcd48", size = 10661366 },
+ { url = "https://files.pythonhosted.org/packages/e9/ba/aa393b972a782b4bc9ea121e0e358a18981980856190d7d2b6187f63e03a/ruff-0.12.0-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:952d0630eae628250ab1c70a7fffb641b03e6b4a2d3f3ec6c1d19b4ab6c6c807", size = 10173492 },
+ { url = "https://files.pythonhosted.org/packages/d7/50/9349ee777614bc3062fc6b038503a59b2034d09dd259daf8192f56c06720/ruff-0.12.0-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c021f04ea06966b02614d442e94071781c424ab8e02ec7af2f037b4c1e01cc82", size = 11761739 },
+ { url = "https://files.pythonhosted.org/packages/04/8f/ad459de67c70ec112e2ba7206841c8f4eb340a03ee6a5cabc159fe558b8e/ruff-0.12.0-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:7d235618283718ee2fe14db07f954f9b2423700919dc688eacf3f8797a11315c", size = 12537098 },
+ { url = "https://files.pythonhosted.org/packages/ed/50/15ad9c80ebd3c4819f5bd8883e57329f538704ed57bac680d95cb6627527/ruff-0.12.0-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0c0758038f81beec8cc52ca22de9685b8ae7f7cc18c013ec2050012862cc9165", size = 12154122 },
+ { url = "https://files.pythonhosted.org/packages/76/e6/79b91e41bc8cc3e78ee95c87093c6cacfa275c786e53c9b11b9358026b3d/ruff-0.12.0-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:139b3d28027987b78fc8d6cfb61165447bdf3740e650b7c480744873688808c2", size = 11363374 },
+ { url = "https://files.pythonhosted.org/packages/db/c3/82b292ff8a561850934549aa9dc39e2c4e783ab3c21debe55a495ddf7827/ruff-0.12.0-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:68853e8517b17bba004152aebd9dd77d5213e503a5f2789395b25f26acac0da4", size = 11587647 },
+ { url = "https://files.pythonhosted.org/packages/2b/42/d5760d742669f285909de1bbf50289baccb647b53e99b8a3b4f7ce1b2001/ruff-0.12.0-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:3a9512af224b9ac4757f7010843771da6b2b0935a9e5e76bb407caa901a1a514", size = 10527284 },
+ { url = "https://files.pythonhosted.org/packages/19/f6/fcee9935f25a8a8bba4adbae62495c39ef281256693962c2159e8b284c5f/ruff-0.12.0-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:b08df3d96db798e5beb488d4df03011874aff919a97dcc2dd8539bb2be5d6a88", size = 10158609 },
+ { url = "https://files.pythonhosted.org/packages/37/fb/057febf0eea07b9384787bfe197e8b3384aa05faa0d6bd844b94ceb29945/ruff-0.12.0-py3-none-musllinux_1_2_i686.whl", hash = "sha256:6a315992297a7435a66259073681bb0d8647a826b7a6de45c6934b2ca3a9ed51", size = 11141462 },
+ { url = "https://files.pythonhosted.org/packages/10/7c/1be8571011585914b9d23c95b15d07eec2d2303e94a03df58294bc9274d4/ruff-0.12.0-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:1e55e44e770e061f55a7dbc6e9aed47feea07731d809a3710feda2262d2d4d8a", size = 11641616 },
+ { url = "https://files.pythonhosted.org/packages/6a/ef/b960ab4818f90ff59e571d03c3f992828d4683561095e80f9ef31f3d58b7/ruff-0.12.0-py3-none-win32.whl", hash = "sha256:7162a4c816f8d1555eb195c46ae0bd819834d2a3f18f98cc63819a7b46f474fb", size = 10525289 },
+ { url = "https://files.pythonhosted.org/packages/34/93/8b16034d493ef958a500f17cda3496c63a537ce9d5a6479feec9558f1695/ruff-0.12.0-py3-none-win_amd64.whl", hash = "sha256:d00b7a157b8fb6d3827b49d3324da34a1e3f93492c1f97b08e222ad7e9b291e0", size = 11598311 },
+ { url = "https://files.pythonhosted.org/packages/d0/33/4d3e79e4a84533d6cd526bfb42c020a23256ae5e4265d858bd1287831f7d/ruff-0.12.0-py3-none-win_arm64.whl", hash = "sha256:8cd24580405ad8c1cc64d61725bca091d6b6da7eb3d36f72cc605467069d7e8b", size = 10724946 },
+]
+
+[[package]]
+name = "secretstorage"
+version = "3.3.3"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cryptography" },
+ { name = "jeepney" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/53/a4/f48c9d79cb507ed1373477dbceaba7401fd8a23af63b837fa61f1dcd3691/SecretStorage-3.3.3.tar.gz", hash = "sha256:2403533ef369eca6d2ba81718576c5e0f564d5cca1b58f73a8b23e7d4eeebd77", size = 19739 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/54/24/b4293291fa1dd830f353d2cb163295742fa87f179fcc8a20a306a81978b7/SecretStorage-3.3.3-py3-none-any.whl", hash = "sha256:f356e6628222568e3af06f2eba8df495efa13b3b63081dafd4f7d9a7b7bc9f99", size = 15221 },
+]
+
+[[package]]
+name = "shellingham"
+version = "1.5.4"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/58/15/8b3609fd3830ef7b27b655beb4b4e9c62313a4e8da8c676e142cc210d58e/shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de", size = 10310 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755 },
+]
+
+[[package]]
+name = "sniffio"
+version = "1.3.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/a2/87/a6771e1546d97e7e041b6ae58d80074f81b7d5121207425c964ddf5cfdbd/sniffio-1.3.1.tar.gz", hash = "sha256:f4324edc670a0f49750a81b895f35c3adb843cca46f0530f79fc1babb23789dc", size = 20372 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235 },
+]
+
+[[package]]
+name = "tomli"
+version = "2.2.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/18/87/302344fed471e44a87289cf4967697d07e532f2421fdaf868a303cbae4ff/tomli-2.2.1.tar.gz", hash = "sha256:cd45e1dc79c835ce60f7404ec8119f2eb06d38b1deba146f07ced3bbc44505ff", size = 17175 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/43/ca/75707e6efa2b37c77dadb324ae7d9571cb424e61ea73fad7c56c2d14527f/tomli-2.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:678e4fa69e4575eb77d103de3df8a895e1591b48e740211bd1067378c69e8249", size = 131077 },
+ { url = "https://files.pythonhosted.org/packages/c7/16/51ae563a8615d472fdbffc43a3f3d46588c264ac4f024f63f01283becfbb/tomli-2.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:023aa114dd824ade0100497eb2318602af309e5a55595f76b626d6d9f3b7b0a6", size = 123429 },
+ { url = "https://files.pythonhosted.org/packages/f1/dd/4f6cd1e7b160041db83c694abc78e100473c15d54620083dbd5aae7b990e/tomli-2.2.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ece47d672db52ac607a3d9599a9d48dcb2f2f735c6c2d1f34130085bb12b112a", size = 226067 },
+ { url = "https://files.pythonhosted.org/packages/a9/6b/c54ede5dc70d648cc6361eaf429304b02f2871a345bbdd51e993d6cdf550/tomli-2.2.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6972ca9c9cc9f0acaa56a8ca1ff51e7af152a9f87fb64623e31d5c83700080ee", size = 236030 },
+ { url = "https://files.pythonhosted.org/packages/1f/47/999514fa49cfaf7a92c805a86c3c43f4215621855d151b61c602abb38091/tomli-2.2.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c954d2250168d28797dd4e3ac5cf812a406cd5a92674ee4c8f123c889786aa8e", size = 240898 },
+ { url = "https://files.pythonhosted.org/packages/73/41/0a01279a7ae09ee1573b423318e7934674ce06eb33f50936655071d81a24/tomli-2.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:8dd28b3e155b80f4d54beb40a441d366adcfe740969820caf156c019fb5c7ec4", size = 229894 },
+ { url = "https://files.pythonhosted.org/packages/55/18/5d8bc5b0a0362311ce4d18830a5d28943667599a60d20118074ea1b01bb7/tomli-2.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:e59e304978767a54663af13c07b3d1af22ddee3bb2fb0618ca1593e4f593a106", size = 245319 },
+ { url = "https://files.pythonhosted.org/packages/92/a3/7ade0576d17f3cdf5ff44d61390d4b3febb8a9fc2b480c75c47ea048c646/tomli-2.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:33580bccab0338d00994d7f16f4c4ec25b776af3ffaac1ed74e0b3fc95e885a8", size = 238273 },
+ { url = "https://files.pythonhosted.org/packages/72/6f/fa64ef058ac1446a1e51110c375339b3ec6be245af9d14c87c4a6412dd32/tomli-2.2.1-cp311-cp311-win32.whl", hash = "sha256:465af0e0875402f1d226519c9904f37254b3045fc5084697cefb9bdde1ff99ff", size = 98310 },
+ { url = "https://files.pythonhosted.org/packages/6a/1c/4a2dcde4a51b81be3530565e92eda625d94dafb46dbeb15069df4caffc34/tomli-2.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:2d0f2fdd22b02c6d81637a3c95f8cd77f995846af7414c5c4b8d0545afa1bc4b", size = 108309 },
+ { url = "https://files.pythonhosted.org/packages/52/e1/f8af4c2fcde17500422858155aeb0d7e93477a0d59a98e56cbfe75070fd0/tomli-2.2.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4a8f6e44de52d5e6c657c9fe83b562f5f4256d8ebbfe4ff922c495620a7f6cea", size = 132762 },
+ { url = "https://files.pythonhosted.org/packages/03/b8/152c68bb84fc00396b83e7bbddd5ec0bd3dd409db4195e2a9b3e398ad2e3/tomli-2.2.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8d57ca8095a641b8237d5b079147646153d22552f1c637fd3ba7f4b0b29167a8", size = 123453 },
+ { url = "https://files.pythonhosted.org/packages/c8/d6/fc9267af9166f79ac528ff7e8c55c8181ded34eb4b0e93daa767b8841573/tomli-2.2.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e340144ad7ae1533cb897d406382b4b6fede8890a03738ff1683af800d54192", size = 233486 },
+ { url = "https://files.pythonhosted.org/packages/5c/51/51c3f2884d7bab89af25f678447ea7d297b53b5a3b5730a7cb2ef6069f07/tomli-2.2.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:db2b95f9de79181805df90bedc5a5ab4c165e6ec3fe99f970d0e302f384ad222", size = 242349 },
+ { url = "https://files.pythonhosted.org/packages/ab/df/bfa89627d13a5cc22402e441e8a931ef2108403db390ff3345c05253935e/tomli-2.2.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:40741994320b232529c802f8bc86da4e1aa9f413db394617b9a256ae0f9a7f77", size = 252159 },
+ { url = "https://files.pythonhosted.org/packages/9e/6e/fa2b916dced65763a5168c6ccb91066f7639bdc88b48adda990db10c8c0b/tomli-2.2.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:400e720fe168c0f8521520190686ef8ef033fb19fc493da09779e592861b78c6", size = 237243 },
+ { url = "https://files.pythonhosted.org/packages/b4/04/885d3b1f650e1153cbb93a6a9782c58a972b94ea4483ae4ac5cedd5e4a09/tomli-2.2.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:02abe224de6ae62c19f090f68da4e27b10af2b93213d36cf44e6e1c5abd19fdd", size = 259645 },
+ { url = "https://files.pythonhosted.org/packages/9c/de/6b432d66e986e501586da298e28ebeefd3edc2c780f3ad73d22566034239/tomli-2.2.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b82ebccc8c8a36f2094e969560a1b836758481f3dc360ce9a3277c65f374285e", size = 244584 },
+ { url = "https://files.pythonhosted.org/packages/1c/9a/47c0449b98e6e7d1be6cbac02f93dd79003234ddc4aaab6ba07a9a7482e2/tomli-2.2.1-cp312-cp312-win32.whl", hash = "sha256:889f80ef92701b9dbb224e49ec87c645ce5df3fa2cc548664eb8a25e03127a98", size = 98875 },
+ { url = "https://files.pythonhosted.org/packages/ef/60/9b9638f081c6f1261e2688bd487625cd1e660d0a85bd469e91d8db969734/tomli-2.2.1-cp312-cp312-win_amd64.whl", hash = "sha256:7fc04e92e1d624a4a63c76474610238576942d6b8950a2d7f908a340494e67e4", size = 109418 },
+ { url = "https://files.pythonhosted.org/packages/04/90/2ee5f2e0362cb8a0b6499dc44f4d7d48f8fff06d28ba46e6f1eaa61a1388/tomli-2.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f4039b9cbc3048b2416cc57ab3bda989a6fcf9b36cf8937f01a6e731b64f80d7", size = 132708 },
+ { url = "https://files.pythonhosted.org/packages/c0/ec/46b4108816de6b385141f082ba99e315501ccd0a2ea23db4a100dd3990ea/tomli-2.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:286f0ca2ffeeb5b9bd4fcc8d6c330534323ec51b2f52da063b11c502da16f30c", size = 123582 },
+ { url = "https://files.pythonhosted.org/packages/a0/bd/b470466d0137b37b68d24556c38a0cc819e8febe392d5b199dcd7f578365/tomli-2.2.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a92ef1a44547e894e2a17d24e7557a5e85a9e1d0048b0b5e7541f76c5032cb13", size = 232543 },
+ { url = "https://files.pythonhosted.org/packages/d9/e5/82e80ff3b751373f7cead2815bcbe2d51c895b3c990686741a8e56ec42ab/tomli-2.2.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9316dc65bed1684c9a98ee68759ceaed29d229e985297003e494aa825ebb0281", size = 241691 },
+ { url = "https://files.pythonhosted.org/packages/05/7e/2a110bc2713557d6a1bfb06af23dd01e7dde52b6ee7dadc589868f9abfac/tomli-2.2.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:e85e99945e688e32d5a35c1ff38ed0b3f41f43fad8df0bdf79f72b2ba7bc5272", size = 251170 },
+ { url = "https://files.pythonhosted.org/packages/64/7b/22d713946efe00e0adbcdfd6d1aa119ae03fd0b60ebed51ebb3fa9f5a2e5/tomli-2.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ac065718db92ca818f8d6141b5f66369833d4a80a9d74435a268c52bdfa73140", size = 236530 },
+ { url = "https://files.pythonhosted.org/packages/38/31/3a76f67da4b0cf37b742ca76beaf819dca0ebef26d78fc794a576e08accf/tomli-2.2.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:d920f33822747519673ee656a4b6ac33e382eca9d331c87770faa3eef562aeb2", size = 258666 },
+ { url = "https://files.pythonhosted.org/packages/07/10/5af1293da642aded87e8a988753945d0cf7e00a9452d3911dd3bb354c9e2/tomli-2.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a198f10c4d1b1375d7687bc25294306e551bf1abfa4eace6650070a5c1ae2744", size = 243954 },
+ { url = "https://files.pythonhosted.org/packages/5b/b9/1ed31d167be802da0fc95020d04cd27b7d7065cc6fbefdd2f9186f60d7bd/tomli-2.2.1-cp313-cp313-win32.whl", hash = "sha256:d3f5614314d758649ab2ab3a62d4f2004c825922f9e370b29416484086b264ec", size = 98724 },
+ { url = "https://files.pythonhosted.org/packages/c7/32/b0963458706accd9afcfeb867c0f9175a741bf7b19cd424230714d722198/tomli-2.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:a38aa0308e754b0e3c67e344754dff64999ff9b513e691d0e786265c93583c69", size = 109383 },
+ { url = "https://files.pythonhosted.org/packages/6e/c2/61d3e0f47e2b74ef40a68b9e6ad5984f6241a942f7cd3bbfbdbd03861ea9/tomli-2.2.1-py3-none-any.whl", hash = "sha256:cb55c73c5f4408779d0cf3eef9f762b9c9f147a77de7b258bef0a5628adc85cc", size = 14257 },
+]
+
+[[package]]
+name = "tomli-w"
+version = "1.2.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/19/75/241269d1da26b624c0d5e110e8149093c759b7a286138f4efd61a60e75fe/tomli_w-1.2.0.tar.gz", hash = "sha256:2dd14fac5a47c27be9cd4c976af5a12d87fb1f0b4512f81d69cce3b35ae25021", size = 7184 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/c7/18/c86eb8e0202e32dd3df50d43d7ff9854f8e0603945ff398974c1d91ac1ef/tomli_w-1.2.0-py3-none-any.whl", hash = "sha256:188306098d013b691fcadc011abd66727d3c414c571bb01b1a174ba8c983cf90", size = 6675 },
+]
+
+[[package]]
+name = "tomlkit"
+version = "0.13.3"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/cc/18/0bbf3884e9eaa38819ebe46a7bd25dcd56b67434402b66a58c4b8e552575/tomlkit-0.13.3.tar.gz", hash = "sha256:430cf247ee57df2b94ee3fbe588e71d362a941ebb545dec29b53961d61add2a1", size = 185207 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/bd/75/8539d011f6be8e29f339c42e633aae3cb73bffa95dd0f9adec09b9c58e85/tomlkit-0.13.3-py3-none-any.whl", hash = "sha256:c89c649d79ee40629a9fda55f8ace8c6a1b42deb912b2a8fd8d942ddadb606b0", size = 38901 },
+]
+
+[[package]]
+name = "trove-classifiers"
+version = "2025.5.9.12"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/38/04/1cd43f72c241fedcf0d9a18d0783953ee301eac9e5d9db1df0f0f089d9af/trove_classifiers-2025.5.9.12.tar.gz", hash = "sha256:7ca7c8a7a76e2cd314468c677c69d12cc2357711fcab4a60f87994c1589e5cb5", size = 16940 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/92/ef/c6deb083748be3bcad6f471b6ae983950c161890bf5ae1b2af80cc56c530/trove_classifiers-2025.5.9.12-py3-none-any.whl", hash = "sha256:e381c05537adac78881c8fa345fd0e9970159f4e4a04fcc42cfd3129cca640ce", size = 14119 },
+]
+
+[[package]]
+name = "twine"
+version = "6.1.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "id" },
+ { name = "importlib-metadata", marker = "python_full_version < '3.10'" },
+ { name = "keyring", marker = "platform_machine != 'ppc64le' and platform_machine != 's390x'" },
+ { name = "packaging" },
+ { name = "readme-renderer" },
+ { name = "requests" },
+ { name = "requests-toolbelt" },
+ { name = "rfc3986" },
+ { name = "rich" },
+ { name = "urllib3" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/c8/a2/6df94fc5c8e2170d21d7134a565c3a8fb84f9797c1dd65a5976aaf714418/twine-6.1.0.tar.gz", hash = "sha256:be324f6272eff91d07ee93f251edf232fc647935dd585ac003539b42404a8dbd", size = 168404 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/7c/b6/74e927715a285743351233f33ea3c684528a0d374d2e43ff9ce9585b73fe/twine-6.1.0-py3-none-any.whl", hash = "sha256:a47f973caf122930bf0fbbf17f80b83bc1602c9ce393c7845f289a3001dc5384", size = 40791 },
+]
+
+[[package]]
+name = "typing-extensions"
+version = "4.14.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/d1/bc/51647cd02527e87d05cb083ccc402f93e441606ff1f01739a62c8ad09ba5/typing_extensions-4.14.0.tar.gz", hash = "sha256:8676b788e32f02ab42d9e7c61324048ae4c6d844a399eebace3d4979d75ceef4", size = 107423 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/69/e0/552843e0d356fbb5256d21449fa957fa4eff3bbc135a74a691ee70c7c5da/typing_extensions-4.14.0-py3-none-any.whl", hash = "sha256:a1514509136dd0b477638fc68d6a91497af5076466ad0fa6c338e44e359944af", size = 43839 },
+]
+
+[[package]]
+name = "urllib3"
+version = "2.5.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/15/22/9ee70a2574a4f4599c47dd506532914ce044817c7752a79b6a51286319bc/urllib3-2.5.0.tar.gz", hash = "sha256:3fc47733c7e419d4bc3f6b3dc2b4f890bb743906a30d56ba4a5bfa4bbff92760", size = 393185 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/a7/c2/fe1e52489ae3122415c51f387e221dd0773709bad6c6cdaa599e8a2c5185/urllib3-2.5.0-py3-none-any.whl", hash = "sha256:e6b01673c0fa6a13e374b50871808eb3bf7046c4b125b216f6bf1cc604cff0dc", size = 129795 },
+]
+
+[[package]]
+name = "userpath"
+version = "1.9.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "click", version = "8.1.8", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.10'" },
+ { name = "click", version = "8.2.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/d5/b7/30753098208505d7ff9be5b3a32112fb8a4cb3ddfccbbb7ba9973f2e29ff/userpath-1.9.2.tar.gz", hash = "sha256:6c52288dab069257cc831846d15d48133522455d4677ee69a9781f11dbefd815", size = 11140 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/43/99/3ec6335ded5b88c2f7ed25c56ffd952546f7ed007ffb1e1539dc3b57015a/userpath-1.9.2-py3-none-any.whl", hash = "sha256:2cbf01a23d655a1ff8fc166dfb78da1b641d1ceabf0fe5f970767d380b14e89d", size = 9065 },
+]
+
+[[package]]
+name = "uv"
+version = "0.7.15"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/f2/e2/f4ae75e0d52abaf8c01c6948b423fbac7a6ae4413556a983959bf8f9b658/uv-0.7.15.tar.gz", hash = "sha256:c608cd2d89db7482ab40fc6e7de27afc87b20595e145ed81a2a8702e9a0d7e2d", size = 3343475 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/3a/57/5bd08b88b583bde2daa54abaf418de1b0b6712bc60d5583a3cc9455174b3/uv-0.7.15-py3-none-linux_armv6l.whl", hash = "sha256:804b927f1b08f97ad597405276058bc94bab9e35c77e7f86c4ca635f72269ff8", size = 17276275 },
+ { url = "https://files.pythonhosted.org/packages/3e/60/f8c159919b96ae9c77bd61f78d5e0dda2769840510abb4ebcc66750b2bb3/uv-0.7.15-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:33f57f51ff980a74131cc8cde501b8467faec21aef35518ff6b544450be2f9be", size = 17301675 },
+ { url = "https://files.pythonhosted.org/packages/a1/4c/b36bc5e665d1466782a7687347291f1f148d78ea1bb1534114b6f8437098/uv-0.7.15-py3-none-macosx_11_0_arm64.whl", hash = "sha256:cc5ed8a4c804b6cacc13fdb794ff86fb6cca02b8966e075a9e15ea976c642454", size = 15957360 },
+ { url = "https://files.pythonhosted.org/packages/13/13/ad63a01b2a6fc68b5b0bd5ddcaa99e997e4143233bd09b2db7b0f917c2f9/uv-0.7.15-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:cd374f9d4eca1b07662e2d774c710d18a7865a4387bc95e8d08fc9070473bb5f", size = 16481900 },
+ { url = "https://files.pythonhosted.org/packages/7b/6c/073e8c8d2c1154f72a6323482b0a5388655622c2fe0867e47b4bb8893e3f/uv-0.7.15-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:1d2d9cff6af77e9dd604782da785e271b7082ddf16636e34e0acee1689cc9392", size = 16948631 },
+ { url = "https://files.pythonhosted.org/packages/4e/88/f019ebc681882cac372f403b4008389e7db3481516ae78ad23bb766f9959/uv-0.7.15-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0601b9757f70f0cb243963ba2c4241d1d9207f4b5afc63c68d609ac5e54ce657", size = 17634844 },
+ { url = "https://files.pythonhosted.org/packages/7b/ee/b506ebdc89d9087ac3436eb7eb22c7ac8926eb199e5253769568316db112/uv-0.7.15-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:361b9b004e62a8d620b7eb79f51f9cc9f815ee0b287c2ce42fb3618f84172a2f", size = 18569268 },
+ { url = "https://files.pythonhosted.org/packages/57/32/50b1e80b91ef2b4478217f6a1754c0888f1e90379b8fa77ed70d5f5f0ee9/uv-0.7.15-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:df99a0f54f8d0889879dee3fb99ec3d0748bbd42af31428197b5fe6b90b7b974", size = 18256065 },
+ { url = "https://files.pythonhosted.org/packages/af/01/3a83831b8916ccb3ce22ac1295ba079f95ab74461236c379f8817a2bf47f/uv-0.7.15-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3cd980b68bbfc80ccc9fe8ab4fccec5350ec0be4135569d8c5bddb605a2fd390", size = 18446300 },
+ { url = "https://files.pythonhosted.org/packages/06/65/90760c9c90633ee37bea46687edddb633f047002625fbb24d5dd43c7f465/uv-0.7.15-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2f6f78e6b816b9fb2cb92f1f1857dd7725cc2008d800e4f4cdc195f64f0c96c8", size = 17960970 },
+ { url = "https://files.pythonhosted.org/packages/a8/e3/4552eb0f95beeb84c5d7d60aa184d62357194df71a8a2e34b8f78681890d/uv-0.7.15-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:7edac5d090bf9cb84bf0139ae48d3629384d94638b1e2215ca2441f786b9e8eb", size = 16754011 },
+ { url = "https://files.pythonhosted.org/packages/93/75/a9d1301267f781c5d06df05dd8bb87884b7818f9dfcccb211716754b9805/uv-0.7.15-py3-none-musllinux_1_1_armv7l.whl", hash = "sha256:81201cf430e527fa88bcfa9a6adb91ad4080cf635684bbc456e4bb589cea6e3c", size = 16951202 },
+ { url = "https://files.pythonhosted.org/packages/f2/ed/a199eb35aff558e3276a3c4591e1d7152a7fdd2d1b5dad60c21191748f72/uv-0.7.15-py3-none-musllinux_1_1_i686.whl", hash = "sha256:d78d1e9b05ab6e540ba4567b92d6f16f80176905183db8581d8b77522c39256c", size = 17245178 },
+ { url = "https://files.pythonhosted.org/packages/7d/50/633fe84ac08ad7a233dc3b7113184af6bbfd0668078993b4408edf6fb767/uv-0.7.15-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:8717797f0d4b257a9d3f217959d24119342b0d96c2b224fbfefa44df5d94def2", size = 18074998 },
+ { url = "https://files.pythonhosted.org/packages/5e/0a/5eee2e56063708a25d6d794153884b260d6f322649d3434f4d449fb65e6e/uv-0.7.15-py3-none-win32.whl", hash = "sha256:10ff8e18e617685f1b5ba4726da2782093ae7032e257eb500358444b610a92b1", size = 17528725 },
+ { url = "https://files.pythonhosted.org/packages/be/73/d6d6fd05728263cc5bc81cf2424f2e78203fdd1b6c926f61363921bd8d8e/uv-0.7.15-py3-none-win_amd64.whl", hash = "sha256:9fda476ce40a428861e62b4e7c1d1199deb48ffc9b9197219e7f78e7c59be7a7", size = 19046757 },
+ { url = "https://files.pythonhosted.org/packages/14/89/7f34a13ea6b336f3a0e70856bd584628556d03a865909a8a3854b7468239/uv-0.7.15-py3-none-win_arm64.whl", hash = "sha256:32a1ca819298b6cbe673becc3d52fc51a626ed003b61402824f1614d786650ac", size = 17690893 },
+]
+
+[[package]]
+name = "virtualenv"
+version = "20.31.2"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "distlib" },
+ { name = "filelock" },
+ { name = "platformdirs" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/56/2c/444f465fb2c65f40c3a104fd0c495184c4f2336d65baf398e3c75d72ea94/virtualenv-20.31.2.tar.gz", hash = "sha256:e10c0a9d02835e592521be48b332b6caee6887f332c111aa79a09b9e79efc2af", size = 6076316 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/f3/40/b1c265d4b2b62b58576588510fc4d1fe60a86319c8de99fd8e9fec617d2c/virtualenv-20.31.2-py3-none-any.whl", hash = "sha256:36efd0d9650ee985f0cad72065001e66d49a6f24eb44d98980f630686243cf11", size = 6057982 },
+]
+
+[[package]]
+name = "wheel"
+version = "0.45.1"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/8a/98/2d9906746cdc6a6ef809ae6338005b3f21bb568bea3165cfc6a243fdc25c/wheel-0.45.1.tar.gz", hash = "sha256:661e1abd9198507b1409a20c02106d9670b2576e916d58f520316666abca6729", size = 107545 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/0b/2c/87f3254fd8ffd29e4c02732eee68a83a1d3c346ae39bc6822dcbcb697f2b/wheel-0.45.1-py3-none-any.whl", hash = "sha256:708e7481cc80179af0e556bbf0cc00b8444c7321e2700b8d8580231d13017248", size = 72494 },
+]
+
+[[package]]
+name = "zipp"
+version = "3.23.0"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/e3/02/0f2892c661036d50ede074e376733dca2ae7c6eb617489437771209d4180/zipp-3.23.0.tar.gz", hash = "sha256:a07157588a12518c9d4034df3fbbee09c814741a33ff63c05fa29d26a2404166", size = 25547 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2e/54/647ade08bf0db230bfea292f893923872fd20be6ac6f53b2b936ba839d75/zipp-3.23.0-py3-none-any.whl", hash = "sha256:071652d6115ed432f5ce1d34c336c0adfd6a884660d1e9712a256d3d3bd4b14e", size = 10276 },
+]
+
+[[package]]
+name = "zstandard"
+version = "0.23.0"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "cffi", marker = "platform_python_implementation == 'PyPy'" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/ed/f6/2ac0287b442160a89d726b17a9184a4c615bb5237db763791a7fd16d9df1/zstandard-0.23.0.tar.gz", hash = "sha256:b2d8c62d08e7255f68f7a740bae85b3c9b8e5466baa9cbf7f57f1cde0ac6bc09", size = 681701 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/2a/55/bd0487e86679db1823fc9ee0d8c9c78ae2413d34c0b461193b5f4c31d22f/zstandard-0.23.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:bf0a05b6059c0528477fba9054d09179beb63744355cab9f38059548fedd46a9", size = 788701 },
+ { url = "https://files.pythonhosted.org/packages/e1/8a/ccb516b684f3ad987dfee27570d635822e3038645b1a950c5e8022df1145/zstandard-0.23.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:fc9ca1c9718cb3b06634c7c8dec57d24e9438b2aa9a0f02b8bb36bf478538880", size = 633678 },
+ { url = "https://files.pythonhosted.org/packages/12/89/75e633d0611c028e0d9af6df199423bf43f54bea5007e6718ab7132e234c/zstandard-0.23.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:77da4c6bfa20dd5ea25cbf12c76f181a8e8cd7ea231c673828d0386b1740b8dc", size = 4941098 },
+ { url = "https://files.pythonhosted.org/packages/4a/7a/bd7f6a21802de358b63f1ee636ab823711c25ce043a3e9f043b4fcb5ba32/zstandard-0.23.0-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b2170c7e0367dde86a2647ed5b6f57394ea7f53545746104c6b09fc1f4223573", size = 5308798 },
+ { url = "https://files.pythonhosted.org/packages/79/3b/775f851a4a65013e88ca559c8ae42ac1352db6fcd96b028d0df4d7d1d7b4/zstandard-0.23.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c16842b846a8d2a145223f520b7e18b57c8f476924bda92aeee3a88d11cfc391", size = 5341840 },
+ { url = "https://files.pythonhosted.org/packages/09/4f/0cc49570141dd72d4d95dd6fcf09328d1b702c47a6ec12fbed3b8aed18a5/zstandard-0.23.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:157e89ceb4054029a289fb504c98c6a9fe8010f1680de0201b3eb5dc20aa6d9e", size = 5440337 },
+ { url = "https://files.pythonhosted.org/packages/e7/7c/aaa7cd27148bae2dc095191529c0570d16058c54c4597a7d118de4b21676/zstandard-0.23.0-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:203d236f4c94cd8379d1ea61db2fce20730b4c38d7f1c34506a31b34edc87bdd", size = 4861182 },
+ { url = "https://files.pythonhosted.org/packages/ac/eb/4b58b5c071d177f7dc027129d20bd2a44161faca6592a67f8fcb0b88b3ae/zstandard-0.23.0-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:dc5d1a49d3f8262be192589a4b72f0d03b72dcf46c51ad5852a4fdc67be7b9e4", size = 4932936 },
+ { url = "https://files.pythonhosted.org/packages/44/f9/21a5fb9bb7c9a274b05ad700a82ad22ce82f7ef0f485980a1e98ed6e8c5f/zstandard-0.23.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:752bf8a74412b9892f4e5b58f2f890a039f57037f52c89a740757ebd807f33ea", size = 5464705 },
+ { url = "https://files.pythonhosted.org/packages/49/74/b7b3e61db3f88632776b78b1db597af3f44c91ce17d533e14a25ce6a2816/zstandard-0.23.0-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:80080816b4f52a9d886e67f1f96912891074903238fe54f2de8b786f86baded2", size = 4857882 },
+ { url = "https://files.pythonhosted.org/packages/4a/7f/d8eb1cb123d8e4c541d4465167080bec88481ab54cd0b31eb4013ba04b95/zstandard-0.23.0-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:84433dddea68571a6d6bd4fbf8ff398236031149116a7fff6f777ff95cad3df9", size = 4697672 },
+ { url = "https://files.pythonhosted.org/packages/5e/05/f7dccdf3d121309b60342da454d3e706453a31073e2c4dac8e1581861e44/zstandard-0.23.0-cp310-cp310-musllinux_1_2_ppc64le.whl", hash = "sha256:ab19a2d91963ed9e42b4e8d77cd847ae8381576585bad79dbd0a8837a9f6620a", size = 5206043 },
+ { url = "https://files.pythonhosted.org/packages/86/9d/3677a02e172dccd8dd3a941307621c0cbd7691d77cb435ac3c75ab6a3105/zstandard-0.23.0-cp310-cp310-musllinux_1_2_s390x.whl", hash = "sha256:59556bf80a7094d0cfb9f5e50bb2db27fefb75d5138bb16fb052b61b0e0eeeb0", size = 5667390 },
+ { url = "https://files.pythonhosted.org/packages/41/7e/0012a02458e74a7ba122cd9cafe491facc602c9a17f590367da369929498/zstandard-0.23.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:27d3ef2252d2e62476389ca8f9b0cf2bbafb082a3b6bfe9d90cbcbb5529ecf7c", size = 5198901 },
+ { url = "https://files.pythonhosted.org/packages/65/3a/8f715b97bd7bcfc7342d8adcd99a026cb2fb550e44866a3b6c348e1b0f02/zstandard-0.23.0-cp310-cp310-win32.whl", hash = "sha256:5d41d5e025f1e0bccae4928981e71b2334c60f580bdc8345f824e7c0a4c2a813", size = 430596 },
+ { url = "https://files.pythonhosted.org/packages/19/b7/b2b9eca5e5a01111e4fe8a8ffb56bdcdf56b12448a24effe6cfe4a252034/zstandard-0.23.0-cp310-cp310-win_amd64.whl", hash = "sha256:519fbf169dfac1222a76ba8861ef4ac7f0530c35dd79ba5727014613f91613d4", size = 495498 },
+ { url = "https://files.pythonhosted.org/packages/9e/40/f67e7d2c25a0e2dc1744dd781110b0b60306657f8696cafb7ad7579469bd/zstandard-0.23.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:34895a41273ad33347b2fc70e1bff4240556de3c46c6ea430a7ed91f9042aa4e", size = 788699 },
+ { url = "https://files.pythonhosted.org/packages/e8/46/66d5b55f4d737dd6ab75851b224abf0afe5774976fe511a54d2eb9063a41/zstandard-0.23.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:77ea385f7dd5b5676d7fd943292ffa18fbf5c72ba98f7d09fc1fb9e819b34c23", size = 633681 },
+ { url = "https://files.pythonhosted.org/packages/63/b6/677e65c095d8e12b66b8f862b069bcf1f1d781b9c9c6f12eb55000d57583/zstandard-0.23.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:983b6efd649723474f29ed42e1467f90a35a74793437d0bc64a5bf482bedfa0a", size = 4944328 },
+ { url = "https://files.pythonhosted.org/packages/59/cc/e76acb4c42afa05a9d20827116d1f9287e9c32b7ad58cc3af0721ce2b481/zstandard-0.23.0-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:80a539906390591dd39ebb8d773771dc4db82ace6372c4d41e2d293f8e32b8db", size = 5311955 },
+ { url = "https://files.pythonhosted.org/packages/78/e4/644b8075f18fc7f632130c32e8f36f6dc1b93065bf2dd87f03223b187f26/zstandard-0.23.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:445e4cb5048b04e90ce96a79b4b63140e3f4ab5f662321975679b5f6360b90e2", size = 5344944 },
+ { url = "https://files.pythonhosted.org/packages/76/3f/dbafccf19cfeca25bbabf6f2dd81796b7218f768ec400f043edc767015a6/zstandard-0.23.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd30d9c67d13d891f2360b2a120186729c111238ac63b43dbd37a5a40670b8ca", size = 5442927 },
+ { url = "https://files.pythonhosted.org/packages/0c/c3/d24a01a19b6733b9f218e94d1a87c477d523237e07f94899e1c10f6fd06c/zstandard-0.23.0-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d20fd853fbb5807c8e84c136c278827b6167ded66c72ec6f9a14b863d809211c", size = 4864910 },
+ { url = "https://files.pythonhosted.org/packages/1c/a9/cf8f78ead4597264f7618d0875be01f9bc23c9d1d11afb6d225b867cb423/zstandard-0.23.0-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:ed1708dbf4d2e3a1c5c69110ba2b4eb6678262028afd6c6fbcc5a8dac9cda68e", size = 4935544 },
+ { url = "https://files.pythonhosted.org/packages/2c/96/8af1e3731b67965fb995a940c04a2c20997a7b3b14826b9d1301cf160879/zstandard-0.23.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:be9b5b8659dff1f913039c2feee1aca499cfbc19e98fa12bc85e037c17ec6ca5", size = 5467094 },
+ { url = "https://files.pythonhosted.org/packages/ff/57/43ea9df642c636cb79f88a13ab07d92d88d3bfe3e550b55a25a07a26d878/zstandard-0.23.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:65308f4b4890aa12d9b6ad9f2844b7ee42c7f7a4fd3390425b242ffc57498f48", size = 4860440 },
+ { url = "https://files.pythonhosted.org/packages/46/37/edb78f33c7f44f806525f27baa300341918fd4c4af9472fbc2c3094be2e8/zstandard-0.23.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:98da17ce9cbf3bfe4617e836d561e433f871129e3a7ac16d6ef4c680f13a839c", size = 4700091 },
+ { url = "https://files.pythonhosted.org/packages/c1/f1/454ac3962671a754f3cb49242472df5c2cced4eb959ae203a377b45b1a3c/zstandard-0.23.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8ed7d27cb56b3e058d3cf684d7200703bcae623e1dcc06ed1e18ecda39fee003", size = 5208682 },
+ { url = "https://files.pythonhosted.org/packages/85/b2/1734b0fff1634390b1b887202d557d2dd542de84a4c155c258cf75da4773/zstandard-0.23.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:b69bb4f51daf461b15e7b3db033160937d3ff88303a7bc808c67bbc1eaf98c78", size = 5669707 },
+ { url = "https://files.pythonhosted.org/packages/52/5a/87d6971f0997c4b9b09c495bf92189fb63de86a83cadc4977dc19735f652/zstandard-0.23.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:034b88913ecc1b097f528e42b539453fa82c3557e414b3de9d5632c80439a473", size = 5201792 },
+ { url = "https://files.pythonhosted.org/packages/79/02/6f6a42cc84459d399bd1a4e1adfc78d4dfe45e56d05b072008d10040e13b/zstandard-0.23.0-cp311-cp311-win32.whl", hash = "sha256:f2d4380bf5f62daabd7b751ea2339c1a21d1c9463f1feb7fc2bdcea2c29c3160", size = 430586 },
+ { url = "https://files.pythonhosted.org/packages/be/a2/4272175d47c623ff78196f3c10e9dc7045c1b9caf3735bf041e65271eca4/zstandard-0.23.0-cp311-cp311-win_amd64.whl", hash = "sha256:62136da96a973bd2557f06ddd4e8e807f9e13cbb0bfb9cc06cfe6d98ea90dfe0", size = 495420 },
+ { url = "https://files.pythonhosted.org/packages/7b/83/f23338c963bd9de687d47bf32efe9fd30164e722ba27fb59df33e6b1719b/zstandard-0.23.0-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:b4567955a6bc1b20e9c31612e615af6b53733491aeaa19a6b3b37f3b65477094", size = 788713 },
+ { url = "https://files.pythonhosted.org/packages/5b/b3/1a028f6750fd9227ee0b937a278a434ab7f7fdc3066c3173f64366fe2466/zstandard-0.23.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e172f57cd78c20f13a3415cc8dfe24bf388614324d25539146594c16d78fcc8", size = 633459 },
+ { url = "https://files.pythonhosted.org/packages/26/af/36d89aae0c1f95a0a98e50711bc5d92c144939efc1f81a2fcd3e78d7f4c1/zstandard-0.23.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:b0e166f698c5a3e914947388c162be2583e0c638a4703fc6a543e23a88dea3c1", size = 4945707 },
+ { url = "https://files.pythonhosted.org/packages/cd/2e/2051f5c772f4dfc0aae3741d5fc72c3dcfe3aaeb461cc231668a4db1ce14/zstandard-0.23.0-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:12a289832e520c6bd4dcaad68e944b86da3bad0d339ef7989fb7e88f92e96072", size = 5306545 },
+ { url = "https://files.pythonhosted.org/packages/0a/9e/a11c97b087f89cab030fa71206963090d2fecd8eb83e67bb8f3ffb84c024/zstandard-0.23.0-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:d50d31bfedd53a928fed6707b15a8dbeef011bb6366297cc435accc888b27c20", size = 5337533 },
+ { url = "https://files.pythonhosted.org/packages/fc/79/edeb217c57fe1bf16d890aa91a1c2c96b28c07b46afed54a5dcf310c3f6f/zstandard-0.23.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:72c68dda124a1a138340fb62fa21b9bf4848437d9ca60bd35db36f2d3345f373", size = 5436510 },
+ { url = "https://files.pythonhosted.org/packages/81/4f/c21383d97cb7a422ddf1ae824b53ce4b51063d0eeb2afa757eb40804a8ef/zstandard-0.23.0-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:53dd9d5e3d29f95acd5de6802e909ada8d8d8cfa37a3ac64836f3bc4bc5512db", size = 4859973 },
+ { url = "https://files.pythonhosted.org/packages/ab/15/08d22e87753304405ccac8be2493a495f529edd81d39a0870621462276ef/zstandard-0.23.0-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:6a41c120c3dbc0d81a8e8adc73312d668cd34acd7725f036992b1b72d22c1772", size = 4936968 },
+ { url = "https://files.pythonhosted.org/packages/eb/fa/f3670a597949fe7dcf38119a39f7da49a8a84a6f0b1a2e46b2f71a0ab83f/zstandard-0.23.0-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:40b33d93c6eddf02d2c19f5773196068d875c41ca25730e8288e9b672897c105", size = 5467179 },
+ { url = "https://files.pythonhosted.org/packages/4e/a9/dad2ab22020211e380adc477a1dbf9f109b1f8d94c614944843e20dc2a99/zstandard-0.23.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:9206649ec587e6b02bd124fb7799b86cddec350f6f6c14bc82a2b70183e708ba", size = 4848577 },
+ { url = "https://files.pythonhosted.org/packages/08/03/dd28b4484b0770f1e23478413e01bee476ae8227bbc81561f9c329e12564/zstandard-0.23.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:76e79bc28a65f467e0409098fa2c4376931fd3207fbeb6b956c7c476d53746dd", size = 4693899 },
+ { url = "https://files.pythonhosted.org/packages/2b/64/3da7497eb635d025841e958bcd66a86117ae320c3b14b0ae86e9e8627518/zstandard-0.23.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:66b689c107857eceabf2cf3d3fc699c3c0fe8ccd18df2219d978c0283e4c508a", size = 5199964 },
+ { url = "https://files.pythonhosted.org/packages/43/a4/d82decbab158a0e8a6ebb7fc98bc4d903266bce85b6e9aaedea1d288338c/zstandard-0.23.0-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:9c236e635582742fee16603042553d276cca506e824fa2e6489db04039521e90", size = 5655398 },
+ { url = "https://files.pythonhosted.org/packages/f2/61/ac78a1263bc83a5cf29e7458b77a568eda5a8f81980691bbc6eb6a0d45cc/zstandard-0.23.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a8fffdbd9d1408006baaf02f1068d7dd1f016c6bcb7538682622c556e7b68e35", size = 5191313 },
+ { url = "https://files.pythonhosted.org/packages/e7/54/967c478314e16af5baf849b6ee9d6ea724ae5b100eb506011f045d3d4e16/zstandard-0.23.0-cp312-cp312-win32.whl", hash = "sha256:dc1d33abb8a0d754ea4763bad944fd965d3d95b5baef6b121c0c9013eaf1907d", size = 430877 },
+ { url = "https://files.pythonhosted.org/packages/75/37/872d74bd7739639c4553bf94c84af7d54d8211b626b352bc57f0fd8d1e3f/zstandard-0.23.0-cp312-cp312-win_amd64.whl", hash = "sha256:64585e1dba664dc67c7cdabd56c1e5685233fbb1fc1966cfba2a340ec0dfff7b", size = 495595 },
+ { url = "https://files.pythonhosted.org/packages/80/f1/8386f3f7c10261fe85fbc2c012fdb3d4db793b921c9abcc995d8da1b7a80/zstandard-0.23.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:576856e8594e6649aee06ddbfc738fec6a834f7c85bf7cadd1c53d4a58186ef9", size = 788975 },
+ { url = "https://files.pythonhosted.org/packages/16/e8/cbf01077550b3e5dc86089035ff8f6fbbb312bc0983757c2d1117ebba242/zstandard-0.23.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:38302b78a850ff82656beaddeb0bb989a0322a8bbb1bf1ab10c17506681d772a", size = 633448 },
+ { url = "https://files.pythonhosted.org/packages/06/27/4a1b4c267c29a464a161aeb2589aff212b4db653a1d96bffe3598f3f0d22/zstandard-0.23.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d2240ddc86b74966c34554c49d00eaafa8200a18d3a5b6ffbf7da63b11d74ee2", size = 4945269 },
+ { url = "https://files.pythonhosted.org/packages/7c/64/d99261cc57afd9ae65b707e38045ed8269fbdae73544fd2e4a4d50d0ed83/zstandard-0.23.0-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2ef230a8fd217a2015bc91b74f6b3b7d6522ba48be29ad4ea0ca3a3775bf7dd5", size = 5306228 },
+ { url = "https://files.pythonhosted.org/packages/7a/cf/27b74c6f22541f0263016a0fd6369b1b7818941de639215c84e4e94b2a1c/zstandard-0.23.0-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:774d45b1fac1461f48698a9d4b5fa19a69d47ece02fa469825b442263f04021f", size = 5336891 },
+ { url = "https://files.pythonhosted.org/packages/fa/18/89ac62eac46b69948bf35fcd90d37103f38722968e2981f752d69081ec4d/zstandard-0.23.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6f77fa49079891a4aab203d0b1744acc85577ed16d767b52fc089d83faf8d8ed", size = 5436310 },
+ { url = "https://files.pythonhosted.org/packages/a8/a8/5ca5328ee568a873f5118d5b5f70d1f36c6387716efe2e369010289a5738/zstandard-0.23.0-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ac184f87ff521f4840e6ea0b10c0ec90c6b1dcd0bad2f1e4a9a1b4fa177982ea", size = 4859912 },
+ { url = "https://files.pythonhosted.org/packages/ea/ca/3781059c95fd0868658b1cf0440edd832b942f84ae60685d0cfdb808bca1/zstandard-0.23.0-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:c363b53e257246a954ebc7c488304b5592b9c53fbe74d03bc1c64dda153fb847", size = 4936946 },
+ { url = "https://files.pythonhosted.org/packages/ce/11/41a58986f809532742c2b832c53b74ba0e0a5dae7e8ab4642bf5876f35de/zstandard-0.23.0-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:e7792606d606c8df5277c32ccb58f29b9b8603bf83b48639b7aedf6df4fe8171", size = 5466994 },
+ { url = "https://files.pythonhosted.org/packages/83/e3/97d84fe95edd38d7053af05159465d298c8b20cebe9ccb3d26783faa9094/zstandard-0.23.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a0817825b900fcd43ac5d05b8b3079937073d2b1ff9cf89427590718b70dd840", size = 4848681 },
+ { url = "https://files.pythonhosted.org/packages/6e/99/cb1e63e931de15c88af26085e3f2d9af9ce53ccafac73b6e48418fd5a6e6/zstandard-0.23.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:9da6bc32faac9a293ddfdcb9108d4b20416219461e4ec64dfea8383cac186690", size = 4694239 },
+ { url = "https://files.pythonhosted.org/packages/ab/50/b1e703016eebbc6501fc92f34db7b1c68e54e567ef39e6e59cf5fb6f2ec0/zstandard-0.23.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:fd7699e8fd9969f455ef2926221e0233f81a2542921471382e77a9e2f2b57f4b", size = 5200149 },
+ { url = "https://files.pythonhosted.org/packages/aa/e0/932388630aaba70197c78bdb10cce2c91fae01a7e553b76ce85471aec690/zstandard-0.23.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:d477ed829077cd945b01fc3115edd132c47e6540ddcd96ca169facff28173057", size = 5655392 },
+ { url = "https://files.pythonhosted.org/packages/02/90/2633473864f67a15526324b007a9f96c96f56d5f32ef2a56cc12f9548723/zstandard-0.23.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:fa6ce8b52c5987b3e34d5674b0ab529a4602b632ebab0a93b07bfb4dfc8f8a33", size = 5191299 },
+ { url = "https://files.pythonhosted.org/packages/b0/4c/315ca5c32da7e2dc3455f3b2caee5c8c2246074a61aac6ec3378a97b7136/zstandard-0.23.0-cp313-cp313-win32.whl", hash = "sha256:a9b07268d0c3ca5c170a385a0ab9fb7fdd9f5fd866be004c4ea39e44edce47dd", size = 430862 },
+ { url = "https://files.pythonhosted.org/packages/a2/bf/c6aaba098e2d04781e8f4f7c0ba3c7aa73d00e4c436bcc0cf059a66691d1/zstandard-0.23.0-cp313-cp313-win_amd64.whl", hash = "sha256:f3513916e8c645d0610815c257cbfd3242adfd5c4cfa78be514e5a3ebb42a41b", size = 495578 },
+ { url = "https://files.pythonhosted.org/packages/fb/96/4fcafeb7e013a2386d22f974b5b97a0b9a65004ed58c87ae001599bfbd48/zstandard-0.23.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:3aa014d55c3af933c1315eb4bb06dd0459661cc0b15cd61077afa6489bec63bb", size = 788697 },
+ { url = "https://files.pythonhosted.org/packages/83/ff/a52ce725be69b86a2967ecba0497a8184540cc284c0991125515449e54e2/zstandard-0.23.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:0a7f0804bb3799414af278e9ad51be25edf67f78f916e08afdb983e74161b916", size = 633679 },
+ { url = "https://files.pythonhosted.org/packages/34/0f/3dc62db122f6a9c481c335fff6fc9f4e88d8f6e2d47321ee3937328addb4/zstandard-0.23.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fb2b1ecfef1e67897d336de3a0e3f52478182d6a47eda86cbd42504c5cbd009a", size = 4940416 },
+ { url = "https://files.pythonhosted.org/packages/1d/e5/9fe0dd8c85fdc2f635e6660d07872a5dc4b366db566630161e39f9f804e1/zstandard-0.23.0-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:837bb6764be6919963ef41235fd56a6486b132ea64afe5fafb4cb279ac44f259", size = 5307693 },
+ { url = "https://files.pythonhosted.org/packages/73/bf/fe62c0cd865c171ee8ed5bc83174b5382a2cb729c8d6162edfb99a83158b/zstandard-0.23.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1516c8c37d3a053b01c1c15b182f3b5f5eef19ced9b930b684a73bad121addf4", size = 5341236 },
+ { url = "https://files.pythonhosted.org/packages/39/86/4fe79b30c794286110802a6cd44a73b6a314ac8196b9338c0fbd78c2407d/zstandard-0.23.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:48ef6a43b1846f6025dde6ed9fee0c24e1149c1c25f7fb0a0585572b2f3adc58", size = 5439101 },
+ { url = "https://files.pythonhosted.org/packages/72/ed/cacec235c581ebf8c608c7fb3d4b6b70d1b490d0e5128ea6996f809ecaef/zstandard-0.23.0-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:11e3bf3c924853a2d5835b24f03eeba7fc9b07d8ca499e247e06ff5676461a15", size = 4860320 },
+ { url = "https://files.pythonhosted.org/packages/f6/1e/2c589a2930f93946b132fc852c574a19d5edc23fad2b9e566f431050c7ec/zstandard-0.23.0-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:2fb4535137de7e244c230e24f9d1ec194f61721c86ebea04e1581d9d06ea1269", size = 4931933 },
+ { url = "https://files.pythonhosted.org/packages/8e/f5/30eadde3686d902b5d4692bb5f286977cbc4adc082145eb3f49d834b2eae/zstandard-0.23.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:8c24f21fa2af4bb9f2c492a86fe0c34e6d2c63812a839590edaf177b7398f700", size = 5463878 },
+ { url = "https://files.pythonhosted.org/packages/e0/c8/8aed1f0ab9854ef48e5ad4431367fcb23ce73f0304f7b72335a8edc66556/zstandard-0.23.0-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:a8c86881813a78a6f4508ef9daf9d4995b8ac2d147dcb1a450448941398091c9", size = 4857192 },
+ { url = "https://files.pythonhosted.org/packages/a8/c6/55e666cfbcd032b9e271865e8578fec56e5594d4faeac379d371526514f5/zstandard-0.23.0-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:fe3b385d996ee0822fd46528d9f0443b880d4d05528fd26a9119a54ec3f91c69", size = 4696513 },
+ { url = "https://files.pythonhosted.org/packages/dc/bd/720b65bea63ec9de0ac7414c33b9baf271c8de8996e5ff324dc93fc90ff1/zstandard-0.23.0-cp39-cp39-musllinux_1_2_ppc64le.whl", hash = "sha256:82d17e94d735c99621bf8ebf9995f870a6b3e6d14543b99e201ae046dfe7de70", size = 5204823 },
+ { url = "https://files.pythonhosted.org/packages/d8/40/d678db1556e3941d330cd4e95623a63ef235b18547da98fa184cbc028ecf/zstandard-0.23.0-cp39-cp39-musllinux_1_2_s390x.whl", hash = "sha256:c7c517d74bea1a6afd39aa612fa025e6b8011982a0897768a2f7c8ab4ebb78a2", size = 5666490 },
+ { url = "https://files.pythonhosted.org/packages/ed/cc/c89329723d7515898a1fc7ef5d251264078548c505719d13e9511800a103/zstandard-0.23.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:1fd7e0f1cfb70eb2f95a19b472ee7ad6d9a0a992ec0ae53286870c104ca939e5", size = 5196622 },
+ { url = "https://files.pythonhosted.org/packages/78/4c/634289d41e094327a94500dfc919e58841b10ea3a9efdfafbac614797ec2/zstandard-0.23.0-cp39-cp39-win32.whl", hash = "sha256:43da0f0092281bf501f9c5f6f3b4c975a8a0ea82de49ba3f7100e64d422a1274", size = 430620 },
+ { url = "https://files.pythonhosted.org/packages/a2/e2/0b0c5a0f4f7699fecd92c1ba6278ef9b01f2b0b0dd46f62bfc6729c05659/zstandard-0.23.0-cp39-cp39-win_amd64.whl", hash = "sha256:f8346bfa098532bc1fb6c7ef06783e969d87a99dd1d2a5a18a892c1d7a643c58", size = 495528 },
+]
diff --git a/tasks/tasksmith-ae872f5c3953/tests/test.sh b/tasks/tasksmith-ae872f5c3953/tests/test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..80254c0fc64954034729dff8cdf6a0745fe24aa2
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/test.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+set -eu
+exec /usr/local/bin/python -B -I -S /tests/grade.py
diff --git a/tasks/tasksmith-ae872f5c3953/tests/test_driver.py b/tasks/tasksmith-ae872f5c3953/tests/test_driver.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0b8bb331c4499e300b92f0e022ff6a723a4a562
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/test_driver.py
@@ -0,0 +1,41 @@
+"""Private pytest entry point with a bounded framework-tampering check.
+
+The host still owns reward parsing. This guard detects replacement or in-place
+editing of unittest assertions, a demonstrated attack against repository tests.
+It does not claim to isolate arbitrary test and solution code in one interpreter.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+
+
+def run(arguments: list[str]) -> int:
+ import pytest
+
+ # Capture before pytest imports any repository modules. Retain code objects
+ # too: an attacker can mutate function.__code__ without replacing a method.
+ original = {
+ name: (value, getattr(value, "__code__", None))
+ for name, value in vars(unittest.TestCase).items()
+ if name.startswith("assert") and callable(value)
+ }
+ case = unittest.TestCase
+ # The harness supplies selectors and reporting explicitly. Repository addopts
+ # often enable optional coverage/report plugins that are intentionally not
+ # auto-loaded in this isolated verifier; they are not test dependencies.
+ code = int(pytest.main(["-o", "addopts=", *arguments]))
+ changed = []
+ for name, (method, implementation) in original.items():
+ current = getattr(case, name, None)
+ if current is not method or getattr(current, "__code__", None) is not implementation:
+ changed.append(name)
+ if unittest.TestCase is not case or changed:
+ sys.stderr.write("Verifier framework was modified: " + ", ".join(changed) + "\n")
+ return 254
+ return code
+
+
+if __name__ == "__main__":
+ raise SystemExit(run(sys.argv[1:]))
diff --git a/tasks/tasksmith-ae872f5c3953/tests/test_results.py b/tasks/tasksmith-ae872f5c3953/tests/test_results.py
new file mode 100644
index 0000000000000000000000000000000000000000..05ce2c730e38e02bad44f2344e88e5f1cb02cb8d
--- /dev/null
+++ b/tasks/tasksmith-ae872f5c3953/tests/test_results.py
@@ -0,0 +1,65 @@
+"""Strict test evidence used by repository recipes and their exported verifiers."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from xml.etree import ElementTree
+
+
+@dataclass(frozen=True)
+class TestResults:
+ __test__ = False
+ statuses: dict[str, str]
+ returncode: int
+
+ @property
+ def passed(self) -> set[str]:
+ return {name for name, status in self.statuses.items() if status == "passed"}
+
+
+def parse_junit(text: str, *, returncode: int) -> TestResults:
+ if " dict[str, list[str]]:
+ if healthy.returncode != 0 or not healthy.passed:
+ raise ValueError("Reference must execute successfully with passing tests")
+ if healthy.statuses.keys() != defective.statuses.keys():
+ raise ValueError("Mutation changed test collection; contrast is not comparable")
+ failing = sorted(
+ name for name in healthy.passed if defective.statuses[name] in {"failed", "error"}
+ )
+ if not failing or defective.returncode != 1:
+ raise ValueError("No intended fail-to-pass contrast")
+ return {"FAIL_TO_PASS": failing, "PASS_TO_PASS": sorted(healthy.passed - set(failing))}
diff --git a/tasks/tasksmith-b6d969373e1e/environment/Dockerfile b/tasks/tasksmith-b6d969373e1e/environment/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..c9592622b513380ef938bdc5c44d6447cd8170ba
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/Dockerfile
@@ -0,0 +1,9 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir setuptools==84.2.1 'setuptools_scm[toml]==10.3.4' pytest==9.2.0 pytest-cov==7.1.0 xlrd==2.0.2 xlwt==1.3.0 odfpy==1.4.1 openpyxl==3.1.5 pyyaml==6.0.3 tabulate==0.10.0
+COPY source /workspace
+RUN SETUPTOOLS_SCM_PRETEND_VERSION=0.0.1 python -m pip install --no-cache-dir -e .
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
+RUN apt-get update && apt-get install -y --no-install-recommends tmux && rm -rf /var/lib/apt/lists/*
+RUN useradd -m learner && chown -R learner:learner /workspace
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/.coveragerc b/tasks/tasksmith-b6d969373e1e/environment/source/.coveragerc
new file mode 100644
index 0000000000000000000000000000000000000000..0ab42b3eb0df78b1b040d9e2fbffa9ab918d6fa9
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/.coveragerc
@@ -0,0 +1,10 @@
+# .coveragerc to control coverage.py
+
+[report]
+# Regexes for lines to exclude from consideration
+exclude_lines =
+ # Have to re-enable the standard pragma:
+ pragma: no cover
+
+ # Don't complain if non-runnable code isn't run:
+ if __name__ == .__main__.:
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/.gitignore b/tasks/tasksmith-b6d969373e1e/environment/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..df3ae4039cafb57b78ab4ad649a9266cfc447d12
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/.gitignore
@@ -0,0 +1,43 @@
+# application builds
+build/*
+dist/*
+MANIFEST
+
+# python skin
+*.pyc
+*.pyo
+
+# osx noise
+.DS_Store
+profile
+
+# pycharm noise
+.idea
+.idea/*
+
+# vi noise
+*.swp
+docs/_build/*
+coverage.xml
+nosetests.xml
+junit-py25.xml
+junit-py26.xml
+junit-py27.xml
+
+# tox noise
+.tox
+
+# pyenv noise
+.python-version
+tablib.egg-info/*
+
+# Coverage
+.coverage
+htmlcov
+
+# setuptools noise
+.eggs
+*.egg-info
+
+# generated by setuptools-scm
+/src/tablib/_version.py
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/AUTHORS b/tasks/tasksmith-b6d969373e1e/environment/source/AUTHORS
new file mode 100644
index 0000000000000000000000000000000000000000..cd73e6574899f595d1065e9c5ceeb6a553e192dc
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/AUTHORS
@@ -0,0 +1,43 @@
+Tablib was originally written by Kenneth Reitz and is now maintained
+by the Jazzband GitHub team.
+
+Here is a list of past and present much-appreciated contributors:
+
+ Alex Gaynor
+ Andrew Graham-Yooll
+ Andrii Soldatenko
+ Benjamin Wohlwend
+ Bruno Soares
+ Claude Paroz
+ Daniel Santos
+ Egor Osokin
+ Erik Youngren
+ Hugo van Kemenade
+ Ian Stride
+ Iuri de Silvio
+ Jakub Janoszek
+ James Douglass
+ Joel Friedly
+ Josh Ourisman
+ Kenneth Reitz
+ Luca Beltrame
+ Luke Lee
+ Marc Abramowitz
+ Marco Dallagiacoma
+ Maris Nartiss
+ Mark Rogers
+ Mark Walling
+ Mathias Loesch
+ Matthew Hegarty
+ Matthias Dellweg
+ Mike Waldner
+ Nicholas Pilon
+ Peyman Salehi
+ Rabin Nankhwa
+ Tak Hogan
+ Tommy Anthony
+ Tsuyoshi Hombashi
+ Tushar Makkar
+ Vidit Patankar
+ Vineeth Sai
+ Yunis Yilmaz
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/Dockerfile b/tasks/tasksmith-b6d969373e1e/environment/source/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..7ee5a1058470aa5653fba97eb0f2b60acaeebd23
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/Dockerfile
@@ -0,0 +1,8 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir setuptools==84.2.1 'setuptools_scm[toml]==10.3.4' pytest==9.2.0 pytest-cov==7.1.0 xlrd==2.0.2 xlwt==1.3.0 odfpy==1.4.1 openpyxl==3.1.5 pyyaml==6.0.3 tabulate==0.10.0
+COPY . /workspace
+RUN SETUPTOOLS_SCM_PRETEND_VERSION=0.0.1 python -m pip install --no-cache-dir -e .
+RUN rm -rf /workspace/.git /root/.cache/pip
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/LICENSE b/tasks/tasksmith-b6d969373e1e/environment/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..9bfca256684905e950decdeaf85de465c2977b63
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/LICENSE
@@ -0,0 +1,20 @@
+Copyright 2016 Kenneth Reitz
+Copyright 2019 Jazzband
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/README.md b/tasks/tasksmith-b6d969373e1e/environment/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..f85770fef901c5725dc43cee1f2754d22d520f75
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/README.md
@@ -0,0 +1,46 @@
+# Tablib: format-agnostic tabular dataset library
+
+[](https://jazzband.co/)
+[](https://pypi.org/project/tablib/)
+[](https://pypi.org/project/tablib/)
+[](https://pypistats.org/packages/tablib)
+[](https://github.com/jazzband/tablib/actions)
+[](https://codecov.io/gh/jazzband/tablib)
+[](LICENSE)
+
+ _____ ______ ___________ ______
+ __ /_______ ____ /_ ___ /___(_)___ /_
+ _ __/_ __ `/__ __ \__ / __ / __ __ \
+ / /_ / /_/ / _ /_/ /_ / _ / _ /_/ /
+ \__/ \__,_/ /_.___/ /_/ /_/ /_.___/
+
+
+Tablib is a format-agnostic tabular dataset library, written in Python.
+
+Output formats supported:
+
+- Excel (Sets + Books)
+- JSON (Sets + Books)
+- YAML (Sets + Books)
+- Pandas DataFrames (Sets)
+- HTML (Sets)
+- Jira (Sets)
+- LaTeX (Sets)
+- TSV (Sets)
+- ODS (Sets)
+- CSV (Sets)
+- DBF (Sets)
+- SQL (Sets)
+
+Note that tablib *purposefully* excludes XML support. It always will. (Note: This is a
+joke. Pull requests are welcome.)
+
+Tablib documentation is graciously hosted on https://tablib.readthedocs.io
+
+It is also available in the ``docs`` directory of the source distribution.
+
+Make sure to check out [Tablib on PyPI](https://pypi.org/project/tablib/)!
+
+## Contribute
+
+Please see the [contributing guide](https://github.com/jazzband/tablib/blob/master/.github/CONTRIBUTING.md).
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/pyproject.toml b/tasks/tasksmith-b6d969373e1e/environment/source/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..cd74362ccf00692a38d222e97a965a33a11d4179
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/pyproject.toml
@@ -0,0 +1,89 @@
+[build-system]
+requires = ["setuptools>=58", "setuptools_scm[toml]>=6.2"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "tablib"
+description = "Format agnostic tabular data library (XLS, JSON, YAML, CSV, etc.)"
+readme = "README.md"
+license = {text = "MIT License"}
+authors = [
+ {name = "Kenneth Reitz", email = "me@kennethreitz.org"}
+]
+maintainers = [
+ {name = "Jazzband Team", email = "roadies@jazzband.co"},
+ {name = "Hugo van Kemenade"},
+ {name = "Claude Paroz", email = "claude@2xlibre.net"},
+]
+requires-python = ">=3.10"
+classifiers = [
+ "Development Status :: 5 - Production/Stable",
+ "Intended Audience :: Developers",
+ "Natural Language :: English",
+ "License :: OSI Approved :: MIT License",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3 :: Only",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Programming Language :: Python :: 3.14",
+]
+dynamic = ["version"]
+
+[project.optional-dependencies]
+all = [
+ "odfpy",
+ "openpyxl>=2.6.0",
+ "pandas",
+ "pyyaml",
+ "tabulate",
+ "xlrd",
+ "xlwt",
+]
+cli = ["tabulate"]
+html = []
+ods = ["odfpy"]
+pandas = ["pandas"]
+xls = ["xlrd", "xlwt"]
+xlsx = ["openpyxl>=2.6.0"]
+yaml = ["pyyaml"]
+
+[project.urls]
+homepage = "https://tablib.readthedocs.io"
+documentation = "https://tablib.readthedocs.io"
+repository = "https://github.com/jazzband/tablib"
+changelog = "https://github.com/jazzband/tablib/blob/master/HISTORY.md"
+
+[tool.setuptools_scm]
+write_to = "src/tablib/_version.py"
+
+[tool.ruff]
+fix = true
+line-length = 99
+
+lint.select = [
+ "C4", # flake8-comprehensions
+ "E", # pycodestyle errors
+ "F", # pyflakes
+ "I", # isort
+ "ISC", # flake8-implicit-str-concat
+ "PGH", # pygrep-hooks
+ "PIE", # flake8-pie
+ "RUF022", # unsorted-dunder-all
+ "RUF100", # unused noqa (yesqa)
+ "UP", # pyupgrade
+ "W", # pycodestyle warnings
+ "YTT", # flake8-2020
+]
+lint.ignore = [
+ "E203", # Whitespace before ':'
+ "E221", # Multiple spaces before operator
+ "E226", # Missing whitespace around arithmetic operator
+ "E241", # Multiple spaces after ','
+ "E741", # Ambiguous variable name
+ "PIE790", # Unnecessary pass statement
+ "UP038", # Makes code slower and more verbose
+]
+lint.isort.known-first-party = [ "tablib" ]
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/pytest.ini b/tasks/tasksmith-b6d969373e1e/environment/source/pytest.ini
new file mode 100644
index 0000000000000000000000000000000000000000..32b87e390599b474a12da34a3f59934938ebe544
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/pytest.ini
@@ -0,0 +1,3 @@
+[pytest]
+norecursedirs = .git .*
+addopts = -rsxX --showlocals --tb=native --cov=tablib --cov=tests --cov-report xml --cov-report term --cov-report html
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/PKG-INFO b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/PKG-INFO
new file mode 100644
index 0000000000000000000000000000000000000000..75e0cc273ad029b6004552f6a2ea46a32ea0beb6
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/PKG-INFO
@@ -0,0 +1,98 @@
+Metadata-Version: 2.4
+Name: tablib
+Version: 0.0.1
+Summary: Format agnostic tabular data library (XLS, JSON, YAML, CSV, etc.)
+Author-email: Kenneth Reitz
+Maintainer: Hugo van Kemenade
+Maintainer-email: Jazzband Team , Claude Paroz
+License: MIT License
+Project-URL: homepage, https://tablib.readthedocs.io
+Project-URL: documentation, https://tablib.readthedocs.io
+Project-URL: repository, https://github.com/jazzband/tablib
+Project-URL: changelog, https://github.com/jazzband/tablib/blob/master/HISTORY.md
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Natural Language :: English
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Requires-Python: >=3.10
+Description-Content-Type: text/markdown
+License-File: LICENSE
+License-File: AUTHORS
+Provides-Extra: all
+Requires-Dist: odfpy; extra == "all"
+Requires-Dist: openpyxl>=2.6.0; extra == "all"
+Requires-Dist: pandas; extra == "all"
+Requires-Dist: pyyaml; extra == "all"
+Requires-Dist: tabulate; extra == "all"
+Requires-Dist: xlrd; extra == "all"
+Requires-Dist: xlwt; extra == "all"
+Provides-Extra: cli
+Requires-Dist: tabulate; extra == "cli"
+Provides-Extra: html
+Provides-Extra: ods
+Requires-Dist: odfpy; extra == "ods"
+Provides-Extra: pandas
+Requires-Dist: pandas; extra == "pandas"
+Provides-Extra: xls
+Requires-Dist: xlrd; extra == "xls"
+Requires-Dist: xlwt; extra == "xls"
+Provides-Extra: xlsx
+Requires-Dist: openpyxl>=2.6.0; extra == "xlsx"
+Provides-Extra: yaml
+Requires-Dist: pyyaml; extra == "yaml"
+Dynamic: license-file
+
+# Tablib: format-agnostic tabular dataset library
+
+[](https://jazzband.co/)
+[](https://pypi.org/project/tablib/)
+[](https://pypi.org/project/tablib/)
+[](https://pypistats.org/packages/tablib)
+[](https://github.com/jazzband/tablib/actions)
+[](https://codecov.io/gh/jazzband/tablib)
+[](LICENSE)
+
+ _____ ______ ___________ ______
+ __ /_______ ____ /_ ___ /___(_)___ /_
+ _ __/_ __ `/__ __ \__ / __ / __ __ \
+ / /_ / /_/ / _ /_/ /_ / _ / _ /_/ /
+ \__/ \__,_/ /_.___/ /_/ /_/ /_.___/
+
+
+Tablib is a format-agnostic tabular dataset library, written in Python.
+
+Output formats supported:
+
+- Excel (Sets + Books)
+- JSON (Sets + Books)
+- YAML (Sets + Books)
+- Pandas DataFrames (Sets)
+- HTML (Sets)
+- Jira (Sets)
+- LaTeX (Sets)
+- TSV (Sets)
+- ODS (Sets)
+- CSV (Sets)
+- DBF (Sets)
+- SQL (Sets)
+
+Note that tablib *purposefully* excludes XML support. It always will. (Note: This is a
+joke. Pull requests are welcome.)
+
+Tablib documentation is graciously hosted on https://tablib.readthedocs.io
+
+It is also available in the ``docs`` directory of the source distribution.
+
+Make sure to check out [Tablib on PyPI](https://pypi.org/project/tablib/)!
+
+## Contribute
+
+Please see the [contributing guide](https://github.com/jazzband/tablib/blob/master/.github/CONTRIBUTING.md).
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/SOURCES.txt b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/SOURCES.txt
new file mode 100644
index 0000000000000000000000000000000000000000..4dc1bc992de75b82bde8b302be10e25c5ecd9349
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/SOURCES.txt
@@ -0,0 +1,41 @@
+AUTHORS
+LICENSE
+README.md
+pyproject.toml
+src/tablib/__init__.py
+src/tablib/_version.py
+src/tablib/core.py
+src/tablib/exceptions.py
+src/tablib/utils.py
+src/tablib.egg-info/PKG-INFO
+src/tablib.egg-info/SOURCES.txt
+src/tablib.egg-info/dependency_links.txt
+src/tablib.egg-info/requires.txt
+src/tablib.egg-info/top_level.txt
+src/tablib/_vendor/__init__.py
+src/tablib/_vendor/dbfpy/__init__.py
+src/tablib/_vendor/dbfpy/dbf.py
+src/tablib/_vendor/dbfpy/dbfnew.py
+src/tablib/_vendor/dbfpy/fields.py
+src/tablib/_vendor/dbfpy/header.py
+src/tablib/_vendor/dbfpy/record.py
+src/tablib/_vendor/dbfpy/utils.py
+src/tablib/formats/__init__.py
+src/tablib/formats/_cli.py
+src/tablib/formats/_csv.py
+src/tablib/formats/_dbf.py
+src/tablib/formats/_df.py
+src/tablib/formats/_html.py
+src/tablib/formats/_jira.py
+src/tablib/formats/_json.py
+src/tablib/formats/_latex.py
+src/tablib/formats/_ods.py
+src/tablib/formats/_rst.py
+src/tablib/formats/_sql.py
+src/tablib/formats/_tsv.py
+src/tablib/formats/_xls.py
+src/tablib/formats/_xlsx.py
+src/tablib/formats/_yaml.py
+tests/test_tablib.py
+tests/test_tablib_dbfpy_packages_fields.py
+tests/test_tablib_dbfpy_packages_utils.py
\ No newline at end of file
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/dependency_links.txt b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/dependency_links.txt
new file mode 100644
index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/requires.txt b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/requires.txt
new file mode 100644
index 0000000000000000000000000000000000000000..40ed2a57f73959d3b647505f2f5c194effaece60
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/requires.txt
@@ -0,0 +1,30 @@
+
+[all]
+odfpy
+openpyxl>=2.6.0
+pandas
+pyyaml
+tabulate
+xlrd
+xlwt
+
+[cli]
+tabulate
+
+[html]
+
+[ods]
+odfpy
+
+[pandas]
+pandas
+
+[xls]
+xlrd
+xlwt
+
+[xlsx]
+openpyxl>=2.6.0
+
+[yaml]
+pyyaml
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/top_level.txt b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e383933276ca6df7358fd077f3be6b58f2186f7e
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib.egg-info/top_level.txt
@@ -0,0 +1 @@
+tablib
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/__init__.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d528c7bf8230d76e874fb2221ed63e7e7a05b91f
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/__init__.py
@@ -0,0 +1,22 @@
+""" Tablib. """
+
+__lazy_modules__ = {"tablib.core"}
+
+try:
+ # Generated by setuptools-scm.
+ from ._version import version as __version__
+except ImportError:
+ # Some broken installation.
+ __version__ = None
+
+
+from .core import ( # noqa: F401
+ Databook,
+ Dataset,
+ InvalidDatasetType,
+ InvalidDimensions,
+ UnsupportedFormat,
+ detect_format,
+ import_book,
+ import_set,
+)
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/__init__.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/__init__.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/dbf.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/dbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..197a1856d6d3160829590254097f4696b99f39a3
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/dbf.py
@@ -0,0 +1,295 @@
+#! /usr/bin/env python
+
+from . import header, record
+from .utils import INVALID_VALUE
+
+__version__ = "$Revision: 1.7 $"[11:-2]
+__date__ = "$Date: 2007/02/11 09:23:13 $"[7:-2]
+__author__ = "Jeff Kunce "
+__all__ = ["Dbf"]
+
+"""DBF accessing helpers.
+
+FIXME: more documentation needed
+
+Examples:
+
+ Create new table, setup structure, add records:
+
+ dbf = Dbf(filename, new=True)
+ dbf.addField(
+ ("NAME", "C", 15),
+ ("SURNAME", "C", 25),
+ ("INITIALS", "C", 10),
+ ("BIRTHDATE", "D"),
+ )
+ for (n, s, i, b) in (
+ ("John", "Miller", "YC", (1980, 10, 11)),
+ ("Andy", "Larkin", "", (1980, 4, 11)),
+ ):
+ rec = dbf.newRecord()
+ rec["NAME"] = n
+ rec["SURNAME"] = s
+ rec["INITIALS"] = i
+ rec["BIRTHDATE"] = b
+ rec.store()
+ dbf.close()
+
+ Open existed dbf, read some data:
+
+ dbf = Dbf(filename, True)
+ for rec in dbf:
+ for fldName in dbf.fieldNames:
+ print('%s:\t %s (%s)' % (fldName, rec[fldName],
+ type(rec[fldName])))
+ print()
+ dbf.close()
+
+"""
+"""History (most recent first):
+11-feb-2007 [als] export INVALID_VALUE;
+ Dbf: added .ignoreErrors, .INVALID_VALUE
+04-jul-2006 [als] added export declaration
+20-dec-2005 [yc] removed fromStream and newDbf methods:
+ use argument of __init__ call must be used instead;
+ added class fields pointing to the header and
+ record classes.
+17-dec-2005 [yc] split to several modules; reimplemented
+13-dec-2005 [yc] adapted to the changes of the `strutil` module.
+13-sep-2002 [als] support FoxPro Timestamp datatype
+15-nov-1999 [jjk] documentation updates, add demo
+24-aug-1998 [jjk] add some encodeValue methods (not tested), other tweaks
+08-jun-1998 [jjk] fix problems, add more features
+20-feb-1998 [jjk] fix problems, add more features
+19-feb-1998 [jjk] add create/write capabilities
+18-feb-1998 [jjk] from dbfload.py
+"""
+
+
+class Dbf:
+ """DBF accessor.
+
+ FIXME:
+ docs and examples needed (dont' forget to tell
+ about problems adding new fields on the fly)
+
+ Implementation notes:
+ ``_new`` field is used to indicate whether this is
+ a new data table. `addField` could be used only for
+ the new tables! If at least one record was appended
+ to the table it's structure couldn't be changed.
+
+ """
+
+ __slots__ = ("name", "header", "stream",
+ "_changed", "_new", "_ignore_errors")
+
+ HeaderClass = header.DbfHeader
+ RecordClass = record.DbfRecord
+ INVALID_VALUE = INVALID_VALUE
+
+ # initialization and creation helpers
+
+ def __init__(self, f, readOnly=False, new=False, ignoreErrors=False):
+ """Initialize instance.
+
+ Arguments:
+ f:
+ Filename or file-like object.
+ new:
+ True if new data table must be created. Assume
+ data table exists if this argument is False.
+ readOnly:
+ if ``f`` argument is a string file will
+ be opend in read-only mode; in other cases
+ this argument is ignored. This argument is ignored
+ even if ``new`` argument is True.
+ headerObj:
+ `header.DbfHeader` instance or None. If this argument
+ is None, new empty header will be used with the
+ all fields set by default.
+ ignoreErrors:
+ if set, failing field value conversion will return
+ ``INVALID_VALUE`` instead of raising conversion error.
+
+ """
+ if isinstance(f, str):
+ # a filename
+ self.name = f
+ if new:
+ # new table (table file must be
+ # created or opened and truncated)
+ self.stream = open(f, "w+b")
+ else:
+ # table file must exist
+ self.stream = open(f, ("r+b", "rb")[bool(readOnly)])
+ else:
+ # a stream
+ self.name = getattr(f, "name", "")
+ self.stream = f
+ if new:
+ # if this is a new table, header will be empty
+ self.header = self.HeaderClass()
+ else:
+ # or instantiated using stream
+ self.header = self.HeaderClass.fromStream(self.stream)
+ self.ignoreErrors = ignoreErrors
+ self._new = bool(new)
+ self._changed = False
+
+ # properties
+
+ closed = property(lambda self: self.stream.closed)
+ recordCount = property(lambda self: self.header.recordCount)
+ fieldNames = property(
+ lambda self: [_fld.name for _fld in self.header.fields])
+ fieldDefs = property(lambda self: self.header.fields)
+ changed = property(lambda self: self._changed or self.header.changed)
+
+ def ignoreErrors(self, value):
+ """Update `ignoreErrors` flag on the header object and self"""
+ self.header.ignoreErrors = self._ignore_errors = bool(value)
+
+ ignoreErrors = property(
+ lambda self: self._ignore_errors,
+ ignoreErrors,
+ doc="""Error processing mode for DBF field value conversion
+
+ if set, failing field value conversion will return
+ ``INVALID_VALUE`` instead of raising conversion error.
+
+ """)
+
+ # protected methods
+
+ def _fixIndex(self, index):
+ """Return fixed index.
+
+ This method fails if index isn't a numeric object
+ (long or int). Or index isn't in a valid range
+ (less or equal to the number of records in the db).
+
+ If ``index`` is a negative number, it will be
+ treated as a negative indexes for list objects.
+
+ Return:
+ Return value is numeric object maning valid index.
+
+ """
+ if not isinstance(index, int):
+ raise TypeError("Index must be a numeric object")
+ if index < 0:
+ # index from the right side
+ # fix it to the left-side index
+ index += len(self) + 1
+ if index >= len(self):
+ raise IndexError("Record index out of range")
+ return index
+
+ # interface methods
+
+ def close(self):
+ self.flush()
+ self.stream.close()
+
+ def flush(self):
+ """Flush data to the associated stream."""
+ if self.changed:
+ self.header.setCurrentDate()
+ self.header.write(self.stream)
+ self.stream.flush()
+ self._changed = False
+
+ def indexOfFieldName(self, name):
+ """Index of field named ``name``."""
+ # FIXME: move this to header class
+ names = [f.name for f in self.header.fields]
+ return names.index(name.upper())
+
+ def newRecord(self):
+ """Return new record, which belong to this table."""
+ return self.RecordClass(self)
+
+ def append(self, record):
+ """Append ``record`` to the database."""
+ record.index = self.header.recordCount
+ record._write()
+ self.header.recordCount += 1
+ self._changed = True
+ self._new = False
+
+ def addField(self, *defs):
+ """Add field definitions.
+
+ For more information see `header.DbfHeader.addField`.
+
+ """
+ if self._new:
+ self.header.addField(*defs)
+ else:
+ raise TypeError("At least one record was added, "
+ "structure can't be changed")
+
+ # 'magic' methods (representation and sequence interface)
+
+ def __repr__(self):
+ return f"Dbf stream '{self.stream}'\n" + repr(self.header)
+
+ def __len__(self):
+ """Return number of records."""
+ return self.recordCount
+
+ def __getitem__(self, index):
+ """Return `DbfRecord` instance."""
+ return self.RecordClass.fromStream(self, self._fixIndex(index))
+
+ def __setitem__(self, index, record):
+ """Write `DbfRecord` instance to the stream."""
+ record.index = self._fixIndex(index)
+ record._write()
+ self._changed = True
+ self._new = False
+
+ # def __del__(self):
+ # """Flush stream upon deletion of the object."""
+ # self.flush()
+
+
+def demo_read(filename):
+ _dbf = Dbf(filename, True)
+ for _rec in _dbf:
+ print()
+ print(repr(_rec))
+ _dbf.close()
+
+
+def demo_create(filename):
+ _dbf = Dbf(filename, new=True)
+ _dbf.addField(
+ ("NAME", "C", 15),
+ ("SURNAME", "C", 25),
+ ("INITIALS", "C", 10),
+ ("BIRTHDATE", "D"),
+ )
+ for (_n, _s, _i, _b) in (
+ ("John", "Miller", "YC", (1981, 1, 2)),
+ ("Andy", "Larkin", "AL", (1982, 3, 4)),
+ ("Bill", "Clinth", "", (1983, 5, 6)),
+ ("Bobb", "McNail", "", (1984, 7, 8)),
+ ):
+ _rec = _dbf.newRecord()
+ _rec["NAME"] = _n
+ _rec["SURNAME"] = _s
+ _rec["INITIALS"] = _i
+ _rec["BIRTHDATE"] = _b
+ _rec.store()
+ print(repr(_dbf))
+ _dbf.close()
+
+
+if __name__ == '__main__':
+ import sys
+
+ _name = len(sys.argv) > 1 and sys.argv[1] or "county.dbf"
+ demo_create(_name)
+ demo_read(_name)
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/dbfnew.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/dbfnew.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bea5508f70a3ebce43f79ac185557051cc41ce4
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/dbfnew.py
@@ -0,0 +1,188 @@
+#!/usr/bin/python
+
+__version__ = "$Revision: 1.4 $"[11:-2]
+__date__ = "$Date: 2006/07/04 08:18:18 $"[7:-2]
+
+__all__ = ["dbf_new"]
+
+from .dbf import Dbf
+from .fields import (
+ DbfCharacterFieldDef,
+ DbfDateFieldDef,
+ DbfDateTimeFieldDef,
+ DbfLogicalFieldDef,
+ DbfNumericFieldDef,
+)
+from .header import DbfHeader
+from .record import DbfRecord
+
+""".DBF creation helpers.
+
+Note: this is a legacy interface. New code should use Dbf class
+ for table creation (see examples in dbf.py)
+
+TODO:
+ - handle Memo fields.
+ - check length of the fields according to the
+ `https://www.clicketyclick.dk/databases/xbase/format/data_types.html`
+
+"""
+"""History (most recent first)
+04-jul-2006 [als] added export declaration;
+ updated for dbfpy 2.0
+15-dec-2005 [yc] define dbf_new.__slots__
+14-dec-2005 [yc] added vim modeline; retab'd; added doc-strings;
+ dbf_new now is a new class (inherited from object)
+??-jun-2000 [--] added by Hans Fiby
+"""
+
+
+class _FieldDefinition:
+ """Field definition.
+
+ This is a simple structure, which contains ``name``, ``type``,
+ ``len``, ``dec`` and ``cls`` fields.
+
+ Objects also implement get/setitem magic functions, so fields
+ could be accessed via sequence interface, where 'name' has
+ index 0, 'type' index 1, 'len' index 2, 'dec' index 3 and
+ 'cls' could be located at index 4.
+
+ """
+
+ __slots__ = "name", "type", "len", "dec", "cls"
+
+ # WARNING: be attentive - dictionaries are mutable!
+ FLD_TYPES = {
+ # type: (cls, len)
+ "C": (DbfCharacterFieldDef, None),
+ "N": (DbfNumericFieldDef, None),
+ "L": (DbfLogicalFieldDef, 1),
+ # FIXME: support memos
+ # "M": (DbfMemoFieldDef),
+ "D": (DbfDateFieldDef, 8),
+ # FIXME: I'm not sure length should be 14 characters!
+ # but temporary I use it, cuz date is 8 characters
+ # and time 6 (hhmmss)
+ "T": (DbfDateTimeFieldDef, 14),
+ }
+
+ def __init__(self, name, type, len=None, dec=0):
+ _cls, _len = self.FLD_TYPES[type]
+ if _len is None:
+ if len is None:
+ raise ValueError("Field length must be defined")
+ _len = len
+ self.name = name
+ self.type = type
+ self.len = _len
+ self.dec = dec
+ self.cls = _cls
+
+ def getDbfField(self):
+ """Return `DbfFieldDef` instance from the current definition."""
+ return self.cls(self.name, self.len, self.dec)
+
+ def appendToHeader(self, dbfh):
+ """Create a `DbfFieldDef` instance and append it to the dbf header.
+
+ Arguments:
+ dbfh: `DbfHeader` instance.
+
+ """
+ _dbff = self.getDbfField()
+ dbfh.addField(_dbff)
+
+
+class dbf_new:
+ """New .DBF creation helper.
+
+ Example Usage:
+
+ dbfn = dbf_new()
+ dbfn.add_field("name",'C',80)
+ dbfn.add_field("price",'N',10,2)
+ dbfn.add_field("date",'D',8)
+ dbfn.write("tst.dbf")
+
+ Note:
+ This module cannot handle Memo-fields,
+ they are special.
+
+ """
+
+ __slots__ = ("fields",)
+
+ FieldDefinitionClass = _FieldDefinition
+
+ def __init__(self):
+ self.fields = []
+
+ def add_field(self, name, typ, len, dec=0):
+ """Add field definition.
+
+ Arguments:
+ name:
+ field name (str object). field name must not
+ contain ASCII NULs and it's length shouldn't
+ exceed 10 characters.
+ typ:
+ type of the field. this must be a single character
+ from the "CNLMDT" set meaning character, numeric,
+ logical, memo, date and date/time respectively.
+ len:
+ length of the field. this argument is used only for
+ the character and numeric fields. all other fields
+ have fixed length.
+ FIXME: use None as a default for this argument?
+ dec:
+ decimal precision. used only for the numric fields.
+
+ """
+ self.fields.append(self.FieldDefinitionClass(name, typ, len, dec))
+
+ def write(self, filename):
+ """Create empty .DBF file using current structure."""
+ _dbfh = DbfHeader()
+ _dbfh.setCurrentDate()
+ for _fldDef in self.fields:
+ _fldDef.appendToHeader(_dbfh)
+
+ _dbfStream = open(filename, "wb")
+ _dbfh.write(_dbfStream)
+ _dbfStream.close()
+
+
+if __name__ == '__main__':
+ # create a new DBF-File
+ dbfn = dbf_new()
+ dbfn.add_field("name", 'C', 80)
+ dbfn.add_field("price", 'N', 10, 2)
+ dbfn.add_field("date", 'D', 8)
+ dbfn.write("tst.dbf")
+ # test new dbf
+ print("*** created tst.dbf: ***")
+ dbft = Dbf('tst.dbf', readOnly=0)
+ print(repr(dbft))
+ # add a record
+ rec = DbfRecord(dbft)
+ rec['name'] = 'something'
+ rec['price'] = 10.5
+ rec['date'] = (2000, 1, 12)
+ rec.store()
+ # add another record
+ rec = DbfRecord(dbft)
+ rec['name'] = 'foo and bar'
+ rec['price'] = 12234
+ rec['date'] = (1992, 7, 15)
+ rec.store()
+
+ # show the records
+ print("*** inserted 2 records into tst.dbf: ***")
+ print(repr(dbft))
+ for i1 in range(len(dbft)):
+ rec = dbft[i1]
+ for fldName in dbft.fieldNames:
+ print(f'{fldName}:\t {rec[fldName]}')
+ print()
+ dbft.close()
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/fields.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/fields.py
new file mode 100644
index 0000000000000000000000000000000000000000..d91f050084a6dca05c51d54538a0e0a9cc6a1bcf
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/fields.py
@@ -0,0 +1,474 @@
+import datetime
+import struct
+from functools import total_ordering
+
+from . import utils
+
+__version__ = "$Revision: 1.14 $"[11:-2]
+__date__ = "$Date: 2009/05/26 05:16:51 $"[7:-2]
+
+__all__ = ["lookupFor"] # field classes added at the end of the module
+
+
+"""DBF fields definitions.
+
+TODO:
+ - make memos work
+"""
+"""History (most recent first):
+26-may-2009 [als] DbfNumericFieldDef.decodeValue: strip zero bytes
+05-feb-2009 [als] DbfDateFieldDef.encodeValue: empty arg produces empty date
+16-sep-2008 [als] DbfNumericFieldDef decoding looks for decimal point
+ in the value to select float or integer return type
+13-mar-2008 [als] check field name length in constructor
+11-feb-2007 [als] handle value conversion errors
+10-feb-2007 [als] DbfFieldDef: added .rawFromRecord()
+01-dec-2006 [als] Timestamp columns use None for empty values
+31-oct-2006 [als] support field types 'F' (float), 'I' (integer)
+ and 'Y' (currency);
+ automate export and registration of field classes
+04-jul-2006 [als] added export declaration
+10-mar-2006 [als] decode empty values for Date and Logical fields;
+ show field name in errors
+10-mar-2006 [als] fix Numeric value decoding: according to spec,
+ value always is string representation of the number;
+ ensure that encoded Numeric value fits into the field
+20-dec-2005 [yc] use field names in upper case
+15-dec-2005 [yc] field definitions moved from `dbf`.
+"""
+
+# abstract definitions
+
+
+@total_ordering
+class DbfFieldDef:
+ """Abstract field definition.
+
+ Child classes must override ``type`` class attribute to provide datatype
+ information of the field definition. For more info about types visit
+ `https://www.clicketyclick.dk/databases/xbase/format/data_types.html`
+
+ Also child classes must override ``defaultValue`` field to provide
+ default value for the field value.
+
+ If child class has fixed length ``length`` class attribute must be
+ overridden and set to the valid value. None value means, that field
+ isn't of fixed length.
+
+ Note: ``name`` field must not be changed after instantiation.
+
+ """
+
+ __slots__ = ("name", "decimalCount", "start", "end", "ignoreErrors")
+
+ # length of the field, None in case of variable-length field,
+ # or a number if this field is a fixed-length field
+ length = None
+
+ # field type. for more information about fields types visit
+ # `https://www.clicketyclick.dk/databases/xbase/format/data_types.html`
+ # must be overridden in child classes
+ typeCode = None
+
+ # default value for the field. this field must be
+ # overridden in child classes
+ defaultValue = None
+
+ def __init__(self, name, length=None, decimalCount=None,
+ start=None, stop=None, ignoreErrors=False):
+ """Initialize instance."""
+ assert self.typeCode is not None, "Type code must be overridden"
+ assert self.defaultValue is not None, "Default value must be overridden"
+ # fix arguments
+ if len(name) > 10:
+ raise ValueError(f"Field name \"{name}\" is too long")
+ name = str(name).upper()
+ if self.__class__.length is None:
+ if length is None:
+ raise ValueError(f"[{name}] Length isn't specified")
+ length = int(length)
+ if length <= 0:
+ raise ValueError(f"[{name}] Length must be a positive integer")
+ else:
+ length = self.length
+ if decimalCount is None:
+ decimalCount = 0
+ # set fields
+ self.name = name
+ # FIXME: validate length according to the specification at
+ # https://www.clicketyclick.dk/databases/xbase/format/data_types.html
+ self.length = length
+ self.decimalCount = decimalCount
+ self.ignoreErrors = ignoreErrors
+ self.start = start
+ self.end = stop
+
+ def __eq__(self, other):
+ return repr(self) == repr(other)
+
+ def __ne__(self, other):
+ return repr(self) != repr(other)
+
+ def __lt__(self, other):
+ return repr(self) < repr(other)
+
+ def __hash__(self):
+ return hash(self.name)
+
+ def fromString(cls, string, start, ignoreErrors=False):
+ """Decode dbf field definition from the string data.
+
+ Arguments:
+ string:
+ a string, dbf definition is decoded from. length of
+ the string must be 32 bytes.
+ start:
+ position in the database file.
+ ignoreErrors:
+ initial error processing mode for the new field (boolean)
+
+ """
+ assert len(string) == 32
+ _length = string[16]
+ return cls(utils.unzfill(string)[:11].decode('utf-8'), _length,
+ string[17], start, start + _length, ignoreErrors=ignoreErrors)
+ fromString = classmethod(fromString)
+
+ def toString(self):
+ """Return encoded field definition.
+
+ Return:
+ Return value is a string object containing encoded
+ definition of this field.
+
+ """
+ _name = self.name.ljust(11, '\0')
+ return (
+ _name +
+ self.typeCode +
+ # data address
+ chr(0) * 4 +
+ chr(self.length) +
+ chr(self.decimalCount) +
+ chr(0) * 14
+ )
+
+ def __repr__(self):
+ return "%-10s %1s %3d %3d" % self.fieldInfo() # noqa: UP031
+
+ def fieldInfo(self):
+ """Return field information.
+
+ Return:
+ Return value is a (name, type, length, decimals) tuple.
+
+ """
+ return self.name, self.typeCode, self.length, self.decimalCount
+
+ def rawFromRecord(self, record):
+ """Return a "raw" field value from the record string."""
+ return record[self.start:self.end]
+
+ def decodeFromRecord(self, record):
+ """Return decoded field value from the record string."""
+ try:
+ return self.decodeValue(self.rawFromRecord(record))
+ except Exception:
+ if self.ignoreErrors:
+ return utils.INVALID_VALUE
+ else:
+ raise
+
+ def decodeValue(self, value):
+ """Return decoded value from string value.
+
+ This method shouldn't be used publicly. It's called from the
+ `decodeFromRecord` method.
+
+ This is an abstract method and it must be overridden in child classes.
+ """
+ raise NotImplementedError
+
+ def encodeValue(self, value):
+ """Return str object containing encoded field value.
+
+ This is an abstract method and it must be overridden in child classes.
+ """
+ raise NotImplementedError
+
+# real classes
+
+
+class DbfCharacterFieldDef(DbfFieldDef):
+ """Definition of the character field."""
+
+ typeCode = "C"
+ defaultValue = b''
+
+ def decodeValue(self, value):
+ """Return string object.
+
+ Return value is a ``value`` argument with stripped right spaces.
+
+ """
+ return value.rstrip(b' ').decode('utf-8')
+
+ def encodeValue(self, value):
+ """Return raw data string encoded from a ``value``."""
+ return str(value)[:self.length].ljust(self.length)
+
+
+class DbfNumericFieldDef(DbfFieldDef):
+ """Definition of the numeric field."""
+
+ typeCode = "N"
+ # XXX: now I'm not sure it was a good idea to make a class field
+ # `defaultValue` instead of a generic method as it was implemented
+ # previously -- it's ok with all types except number, cuz
+ # if self.decimalCount is 0, we should return 0 and 0.0 otherwise.
+ defaultValue = 0
+
+ def decodeValue(self, value):
+ """Return a number decoded from ``value``.
+
+ If decimals is zero, value will be decoded as an integer;
+ or as a float otherwise.
+
+ Return:
+ Return value is a int (long) or float instance.
+
+ """
+ value = value.strip(b' \0')
+ if b'.' in value:
+ # a float (has decimal separator)
+ return float(value)
+ elif value:
+ # must be an integer
+ return int(value)
+ else:
+ return 0
+
+ def encodeValue(self, value):
+ """Return string containing encoded ``value``."""
+ _rv = ("%*.*f" % (self.length, self.decimalCount, value)) # noqa: UP031
+ if len(_rv) > self.length:
+ _ppos = _rv.find(".")
+ if 0 <= _ppos <= self.length:
+ _rv = _rv[:self.length]
+ else:
+ raise ValueError(
+ f"[{self.name}] Numeric overflow: {_rv} (field width: {self.length})"
+ )
+ return _rv
+
+
+class DbfFloatFieldDef(DbfNumericFieldDef):
+ """Definition of the float field - same as numeric."""
+
+ typeCode = "F"
+
+
+class DbfIntegerFieldDef(DbfFieldDef):
+ """Definition of the integer field."""
+
+ typeCode = "I"
+ length = 4
+ defaultValue = 0
+
+ def decodeValue(self, value):
+ """Return an integer number decoded from ``value``."""
+ return struct.unpack("= 1:
+ _rv = datetime.datetime.fromordinal(_jdn - self.JDN_GDN_DIFF)
+ _rv += datetime.timedelta(0, _msecs / 1000.0)
+ else:
+ # empty date
+ _rv = None
+ return _rv
+
+ def encodeValue(self, value):
+ """Return a string-encoded ``value``."""
+ if value:
+ value = utils.getDateTime(value)
+ # LE byteorder
+ _rv = struct.pack("<2I", value.toordinal() + self.JDN_GDN_DIFF,
+ (value.hour * 3600 + value.minute * 60 + value.second) * 1000)
+ else:
+ _rv = "\0" * self.length
+ assert len(_rv) == self.length
+ return _rv
+
+
+_fieldsRegistry = {}
+
+
+def registerField(fieldCls):
+ """Register field definition class.
+
+ ``fieldCls`` should be subclass of the `DbfFieldDef`.
+
+ Use `lookupFor` to retrieve field definition class
+ by the type code.
+
+ """
+ assert fieldCls.typeCode is not None, "Type code isn't defined"
+ # XXX: use fieldCls.typeCode.upper()? in case of any decign
+ # don't forget to look to the same comment in ``lookupFor`` method
+ _fieldsRegistry[fieldCls.typeCode] = fieldCls
+
+
+def lookupFor(typeCode):
+ """Return field definition class for the given type code.
+
+ ``typeCode`` must be a single character. That type should be
+ previously registered.
+
+ Use `registerField` to register new field class.
+
+ Return:
+ Return value is a subclass of the `DbfFieldDef`.
+
+ """
+ # XXX: use typeCode.upper()? in case of any decign don't
+ # forget to look to the same comment in ``registerField``
+ return _fieldsRegistry[chr(typeCode)]
+
+# register generic types
+
+
+for (_name, _val) in list(globals().items()):
+ if isinstance(_val, type) and issubclass(_val, DbfFieldDef) \
+ and (_name != "DbfFieldDef"):
+ __all__.append(_name)
+ registerField(_val)
+del _name, _val
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/header.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/header.py
new file mode 100644
index 0000000000000000000000000000000000000000..40329185e4d6a8d428048a98fbc78bead75ff587
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/header.py
@@ -0,0 +1,272 @@
+import datetime
+import io
+import struct
+import sys
+
+from . import fields
+from .utils import getDate
+
+__version__ = "$Revision: 1.6 $"[11:-2]
+__date__ = "$Date: 2010/09/16 05:06:39 $"[7:-2]
+
+__all__ = ["DbfHeader"]
+
+
+"""DBF header definition.
+
+TODO:
+ - handle encoding of the character fields
+ (encoding information stored in the DBF header)
+
+"""
+"""History (most recent first):
+16-sep-2010 [als] fromStream: fix century of the last update field
+11-feb-2007 [als] added .ignoreErrors
+10-feb-2007 [als] added __getitem__: return field definitions
+ by field name or field number (zero-based)
+04-jul-2006 [als] added export declaration
+15-dec-2005 [yc] created
+"""
+
+
+class DbfHeader:
+ """Dbf header definition.
+
+ For more information about dbf header format visit
+ `http://www.clicketyclick.dk/databases/xbase/format/dbf.html#DBF_STRUCT`
+
+ Examples:
+ Create an empty dbf header and add some field definitions:
+ dbfh = DbfHeader()
+ dbfh.addField(("name", "C", 10))
+ dbfh.addField(("date", "D"))
+ dbfh.addField(DbfNumericFieldDef("price", 5, 2))
+ Create a dbf header with field definitions:
+ dbfh = DbfHeader([
+ ("name", "C", 10),
+ ("date", "D"),
+ DbfNumericFieldDef("price", 5, 2),
+ ])
+
+ """
+
+ __slots__ = ("signature", "fields", "lastUpdate", "recordLength",
+ "recordCount", "headerLength", "changed", "_ignore_errors")
+
+ # instance construction and initialization methods
+
+ def __init__(self, fields=None, headerLength=0, recordLength=0,
+ recordCount=0, signature=0x03, lastUpdate=None, ignoreErrors=False):
+ """Initialize instance.
+
+ Arguments:
+ fields:
+ a list of field definitions;
+ recordLength:
+ size of the records;
+ headerLength:
+ size of the header;
+ recordCount:
+ number of records stored in DBF;
+ signature:
+ version number (aka signature). using 0x03 as a default meaning
+ "File without DBT". for more information about this field visit
+ ``http://www.clicketyclick.dk/databases/xbase/format/dbf.html#DBF_NOTE_1_TARGET``
+ lastUpdate:
+ date of the DBF's update. this could be a string ('yymmdd' or
+ 'yyyymmdd'), timestamp (int or float), datetime/date value,
+ a sequence (assuming (yyyy, mm, dd, ...)) or an object having
+ callable ``ticks`` field.
+ ignoreErrors:
+ error processing mode for DBF fields (boolean)
+
+ """
+ self.signature = signature
+ if fields is None:
+ self.fields = []
+ else:
+ self.fields = list(fields)
+ self.lastUpdate = getDate(lastUpdate)
+ self.recordLength = recordLength
+ self.headerLength = headerLength
+ self.recordCount = recordCount
+ self.ignoreErrors = ignoreErrors
+ # XXX: I'm not sure this is safe to
+ # initialize `self.changed` in this way
+ self.changed = bool(self.fields)
+
+ # @classmethod
+ def fromString(cls, string):
+ """Return header instance from the string object."""
+ return cls.fromStream(io.StringIO(str(string)))
+ fromString = classmethod(fromString)
+
+ # @classmethod
+ def fromStream(cls, stream):
+ """Return header object from the stream."""
+ stream.seek(0)
+ first_32 = stream.read(32)
+ if not isinstance(first_32, bytes):
+ _data = bytes(first_32, sys.getfilesystemencoding())
+ _data = first_32
+ (_cnt, _hdrLen, _recLen) = struct.unpack(" DbfRecord._write();
+ added delete() method.
+16-dec-2005 [yc] record definition moved from `dbf`.
+"""
+
+
+class DbfRecord:
+ """DBF record.
+
+ Instances of this class shouldn't be created manually,
+ use `dbf.Dbf.newRecord` instead.
+
+ Class implements mapping/sequence interface, so
+ fields could be accessed via their names or indexes
+ (names is a preferred way to access fields).
+
+ Hint:
+ Use `store` method to save modified record.
+
+ Examples:
+ Add new record to the database:
+ db = Dbf(filename)
+ rec = db.newRecord()
+ rec["FIELD1"] = value1
+ rec["FIELD2"] = value2
+ rec.store()
+ Or the same, but modify existed
+ (second in this case) record:
+ db = Dbf(filename)
+ rec = db[2]
+ rec["FIELD1"] = value1
+ rec["FIELD2"] = value2
+ rec.store()
+
+ """
+
+ __slots__ = "dbf", "index", "deleted", "fieldData"
+
+ # creation and initialization
+
+ def __init__(self, dbf, index=None, deleted=False, data=None):
+ """Instance initialization.
+
+ Arguments:
+ dbf:
+ A `Dbf.Dbf` instance this record belongs to.
+ index:
+ An integer record index or None. If this value is
+ None, record will be appended to the DBF.
+ deleted:
+ Boolean flag indicating whether this record
+ is a deleted record.
+ data:
+ A sequence or None. This is a data of the fields.
+ If this argument is None, default values will be used.
+
+ """
+ self.dbf = dbf
+ # XXX: I'm not sure ``index`` is necessary
+ self.index = index
+ self.deleted = deleted
+ if data is None:
+ self.fieldData = [_fd.defaultValue for _fd in dbf.header.fields]
+ else:
+ self.fieldData = list(data)
+
+ # XXX: validate self.index before calculating position?
+ position = property(lambda self: self.dbf.header.headerLength +
+ self.index * self.dbf.header.recordLength)
+
+ def rawFromStream(cls, dbf, index):
+ """Return raw record contents read from the stream.
+
+ Arguments:
+ dbf:
+ A `Dbf.Dbf` instance containing the record.
+ index:
+ Index of the record in the records' container.
+ This argument can't be None in this call.
+
+ Return value is a string containing record data in DBF format.
+
+ """
+ # XXX: may be write smth assuming, that current stream
+ # position is the required one? it could save some
+ # time required to calculate where to seek in the file
+ dbf.stream.seek(dbf.header.headerLength + index * dbf.header.recordLength)
+ return dbf.stream.read(dbf.header.recordLength)
+
+ rawFromStream = classmethod(rawFromStream)
+
+ def fromStream(cls, dbf, index):
+ """Return a record read from the stream.
+
+ Arguments:
+ dbf:
+ A `Dbf.Dbf` instance new record should belong to.
+ index:
+ Index of the record in the records' container.
+ This argument can't be None in this call.
+
+ Return value is an instance of the current class.
+
+ """
+ return cls.fromString(dbf, cls.rawFromStream(dbf, index), index)
+
+ fromStream = classmethod(fromStream)
+
+ def fromString(cls, dbf, string, index=None):
+ """Return record read from the string object.
+
+ Arguments:
+ dbf:
+ A `Dbf.Dbf` instance new record should belong to.
+ string:
+ A string new record should be created from.
+ index:
+ Index of the record in the container. If this
+ argument is None, record will be appended.
+
+ Return value is an instance of the current class.
+
+ """
+ return cls(dbf, index, string[0] == "*",
+ [_fd.decodeFromRecord(string) for _fd in dbf.header.fields])
+
+ fromString = classmethod(fromString)
+
+ # object representation
+
+ def __repr__(self):
+ _template = "%%%ds: %%s (%%s)" % max(len(_fld) for _fld in self.dbf.fieldNames) # noqa: UP031
+ _rv = []
+ for _fld in self.dbf.fieldNames:
+ _val = self[_fld]
+ if _val is utils.INVALID_VALUE:
+ _rv.append(_template % (_fld, "None", "value cannot be decoded"))
+ else:
+ _rv.append(_template % (_fld, _val, type(_val)))
+ return "\n".join(_rv)
+
+ # protected methods
+
+ def _write(self):
+ """Write data to the dbf stream.
+
+ Note:
+ This isn't a public method, it's better to
+ use 'store' instead publicly.
+ Be design ``_write`` method should be called
+ only from the `Dbf` instance.
+
+ """
+ self._validateIndex(False)
+ self.dbf.stream.seek(self.position)
+ self.dbf.stream.write(bytes(self.toString(),
+ sys.getfilesystemencoding()))
+ # FIXME: may be move this write somewhere else?
+ # why we should check this condition for each record?
+ if self.index == len(self.dbf):
+ # this is the last record,
+ # we should write SUB (ASCII 26)
+ self.dbf.stream.write(b"\x1A")
+
+ # utility methods
+
+ def _validateIndex(self, allowUndefined=True, checkRange=False):
+ """Valid ``self.index`` value.
+
+ If ``allowUndefined`` argument is True functions does nothing
+ in case of ``self.index`` pointing to None object.
+
+ """
+ if self.index is None:
+ if not allowUndefined:
+ raise ValueError("Index is undefined")
+ elif self.index < 0:
+ raise ValueError(f"Index can't be negative ({self.index})")
+ elif checkRange and self.index <= self.dbf.header.recordCount:
+ raise ValueError(
+ f"There are only {self.dbf.header.recordCount} records in the DBF"
+ )
+
+ # interface methods
+
+ def store(self):
+ """Store current record in the DBF.
+
+ If ``self.index`` is None, this record will be appended to the
+ records of the DBF this records belongs to; or replaced otherwise.
+
+ """
+ self._validateIndex()
+ if self.index is None:
+ self.index = len(self.dbf)
+ self.dbf.append(self)
+ else:
+ self.dbf[self.index] = self
+
+ def delete(self):
+ """Mark method as deleted."""
+ self.deleted = True
+
+ def toString(self):
+ """Return string packed record values."""
+ return "".join([" *"[self.deleted]] + [
+ _def.encodeValue(_dat) for (_def, _dat) in zip(self.dbf.header.fields, self.fieldData)
+ ])
+
+ def asList(self):
+ """Return a flat list of fields.
+
+ Note:
+ Change of the list's values won't change
+ real values stored in this object.
+
+ """
+ return self.fieldData[:]
+
+ def asDict(self):
+ """Return a dictionary of fields.
+
+ Note:
+ Change of the dicts's values won't change
+ real values stored in this object.
+
+ """
+ return dict(list(zip(self.dbf.fieldNames, self.fieldData)))
+
+ def __getitem__(self, key):
+ """Return value by field name or field index."""
+ if isinstance(key, int):
+ # integer index of the field
+ return self.fieldData[key]
+ # assuming string field name
+ return self.fieldData[self.dbf.indexOfFieldName(key)]
+
+ def __setitem__(self, key, value):
+ """Set field value by integer index of the field or string name."""
+ if isinstance(key, int):
+ # integer index of the field
+ return self.fieldData[key]
+ # assuming string field name
+ self.fieldData[self.dbf.indexOfFieldName(key)] = value
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/utils.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c20cec11819375ed0852596ccec6f5ebd9ea6b82
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_vendor/dbfpy/utils.py
@@ -0,0 +1,169 @@
+import datetime
+import time
+
+__version__ = "$Revision: 1.4 $"[11:-2]
+__date__ = "$Date: 2007/02/11 08:57:17 $"[7:-2]
+
+
+"""String utilities.
+
+TODO:
+ - allow strings in getDateTime routine;
+"""
+"""History (most recent first):
+11-feb-2007 [als] added INVALID_VALUE
+10-feb-2007 [als] allow date strings padded with spaces instead of zeroes
+20-dec-2005 [yc] handle long objects in getDate/getDateTime
+16-dec-2005 [yc] created from ``strutil`` module.
+"""
+
+
+def unzfill(str):
+ """Return a string without ASCII NULs.
+
+ This function searchers for the first NUL (ASCII 0) occurrence
+ and truncates string till that position.
+
+ """
+ try:
+ return str[:str.index(b'\0')]
+ except ValueError:
+ return str
+
+
+def getDate(date=None):
+ """Return `datetime.date` instance.
+
+ Type of the ``date`` argument could be one of the following:
+ None:
+ use current date value;
+ datetime.date:
+ this value will be returned;
+ datetime.datetime:
+ the result of the date.date() will be returned;
+ string:
+ assuming "%Y%m%d" or "%y%m%dd" format;
+ number:
+ assuming it's a timestamp (returned for example
+ by the time.time() call;
+ sequence:
+ assuming (year, month, day, ...) sequence;
+
+ Additionally, if ``date`` has callable ``ticks`` attribute,
+ it will be used and result of the called would be treated
+ as a timestamp value.
+
+ """
+ if date is None:
+ # use current value
+ return datetime.date.today()
+ if isinstance(date, datetime.date):
+ return date
+ if isinstance(date, datetime.datetime):
+ return date.date()
+ if isinstance(date, (int, float)):
+ # date is a timestamp
+ return datetime.date.fromtimestamp(date)
+ if isinstance(date, str):
+ date = date.replace(" ", "0")
+ if len(date) == 6:
+ # yymmdd
+ return datetime.date(*time.strptime(date, "%y%m%d")[:3])
+ # yyyymmdd
+ return datetime.date(*time.strptime(date, "%Y%m%d")[:3])
+ if hasattr(date, "__getitem__"):
+ # a sequence (assuming date/time tuple)
+ return datetime.date(*date[:3])
+ return datetime.date.fromtimestamp(date.ticks())
+
+
+def getDateTime(value=None):
+ """Return `datetime.datetime` instance.
+
+ Type of the ``value`` argument could be one of the following:
+ None:
+ use current date value;
+ datetime.date:
+ result will be converted to the `datetime.datetime` instance
+ using midnight;
+ datetime.datetime:
+ ``value`` will be returned as is;
+ string:
+ *** CURRENTLY NOT SUPPORTED ***;
+ number:
+ assuming it's a timestamp (returned for example
+ by the time.time() call;
+ sequence:
+ assuming (year, month, day, ...) sequence;
+
+ Additionally, if ``value`` has callable ``ticks`` attribute,
+ it will be used and result of the called would be treated
+ as a timestamp value.
+
+ """
+ if value is None:
+ # use current value
+ return datetime.datetime.today()
+ if isinstance(value, datetime.datetime):
+ return value
+ if isinstance(value, datetime.date):
+ return datetime.datetime.fromordinal(value.toordinal())
+ if isinstance(value, (int, float)):
+ # value is a timestamp
+ return datetime.datetime.fromtimestamp(value)
+ if isinstance(value, str):
+ raise NotImplementedError("Strings aren't currently implemented")
+ if hasattr(value, "__getitem__"):
+ # a sequence (assuming date/time tuple)
+ return datetime.datetime(*tuple(value)[:6])
+ return datetime.datetime.fromtimestamp(value.ticks())
+
+
+class classproperty(property):
+ """Works in the same way as a ``property``, but for the classes."""
+
+ def __get__(self, obj, cls):
+ return self.fget(cls)
+
+
+class _InvalidValue:
+
+ """Value returned from DBF records when field validation fails
+
+ The value is not equal to anything except for itself
+ and equal to all empty values: None, 0, empty string etc.
+ In other words, invalid value is equal to None and not equal
+ to None at the same time.
+
+ This value yields zero upon explicit conversion to a number type,
+ empty string for string types, and False for boolean.
+
+ """
+
+ def __eq__(self, other):
+ return not other
+
+ def __ne__(self, other):
+ return other is not self
+
+ def __bool__(self):
+ return False
+
+ def __int__(self):
+ return 0
+ __long__ = __int__
+
+ def __float__(self):
+ return 0.0
+
+ def __str__(self):
+ return ""
+
+ def __repr__(self):
+ return ""
+
+
+# invalid value is a constant singleton
+INVALID_VALUE = _InvalidValue()
+
+# vim: set et sts=4 sw=4 :
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_version.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..2438ee983030095501285554f9a560c69155bead
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/_version.py
@@ -0,0 +1,24 @@
+# file generated by vcs-versioning
+# don't change, don't track in version control
+from __future__ import annotations
+
+__all__ = [
+ "__version__",
+ "__version_tuple__",
+ "version",
+ "version_tuple",
+ "__commit_id__",
+ "commit_id",
+]
+
+version: str
+__version__: str
+__version_tuple__: tuple[int | str, ...]
+version_tuple: tuple[int | str, ...]
+commit_id: str | None
+__commit_id__: str | None
+
+__version__ = version = '0.0.1'
+__version_tuple__ = version_tuple = (0, 0, 1)
+
+__commit_id__ = commit_id = None
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/core.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0b56fd2323cf5e0809c756a829327a64c17a693
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/core.py
@@ -0,0 +1,966 @@
+"""
+ tablib.core
+ ~~~~~~~~~~~
+
+ This module implements the central Tablib objects.
+
+ :copyright: (c) 2016 by Kenneth Reitz. 2019 Jazzband.
+ :license: MIT, see LICENSE for more details.
+"""
+
+__lazy_modules__ = {
+ "copy",
+ "operator",
+ "tablib.exceptions",
+ "tablib.utils",
+}
+
+from copy import copy
+from operator import itemgetter
+
+from .exceptions import (
+ HeadersNeeded,
+ InvalidDatasetIndex,
+ InvalidDatasetType,
+ InvalidDimensions,
+ UnsupportedFormat,
+)
+from .formats import registry
+from .utils import normalize_input
+
+__title__ = 'tablib'
+__author__ = 'Kenneth Reitz'
+__license__ = 'MIT'
+__copyright__ = 'Copyright 2017 Kenneth Reitz. 2019 Jazzband.'
+__docformat__ = 'restructuredtext'
+
+
+class Row:
+ """Internal Row object. Mainly used for filtering."""
+
+ __slots__ = ['_row', 'tags']
+
+ def __init__(self, row=(), tags=()):
+ self._row = list(row)
+ self.tags = list(tags)
+
+ def __iter__(self):
+ return (col for col in self._row)
+
+ def __len__(self):
+ return len(self._row)
+
+ def __repr__(self):
+ return repr(self._row)
+
+ def __getitem__(self, i):
+ return self._row[i]
+
+ def __setitem__(self, i, value):
+ self._row[i] = value
+
+ def __delitem__(self, i):
+ del self._row[i]
+
+ def __getstate__(self):
+ return self._row, self.tags
+
+ def __setstate__(self, state):
+ self._row, self.tags = state
+
+ def rpush(self, value):
+ self.insert(len(self._row), value)
+
+ def lpush(self, value):
+ self.insert(0, value)
+
+ def append(self, value):
+ self.rpush(value)
+
+ def insert(self, index, value):
+ self._row.insert(index, value)
+
+ def copy(self):
+ return Row(self._row.copy(), self.tags.copy())
+
+ def __contains__(self, item):
+ return item in self._row
+
+ @property
+ def tuple(self):
+ """Tuple representation of :class:`Row`."""
+ return tuple(self._row)
+
+ @property
+ def list(self):
+ """List representation of :class:`Row`."""
+ return list(self._row)
+
+ def has_tag(self, tag):
+ """Returns true if current row contains tag."""
+
+ if tag is None:
+ return False
+ elif isinstance(tag, str):
+ return tag in self.tags
+ else:
+ return bool(len(set(tag) & set(self.tags)))
+
+
+class Dataset:
+ """The :class:`Dataset` object is the heart of Tablib. It provides all core
+ functionality.
+
+ Usually you create a :class:`Dataset` instance in your main module, and append
+ rows as you collect data. ::
+
+ data = tablib.Dataset()
+ data.headers = ('name', 'age')
+
+ for (name, age) in some_collector():
+ data.append((name, age))
+
+
+ Setting columns is similar. The column data length must equal the
+ current height of the data and headers must be set. ::
+
+ data = tablib.Dataset()
+ data.headers = ('first_name', 'last_name')
+
+ data.append(('John', 'Adams'))
+ data.append(('George', 'Washington'))
+
+ data.append_col((90, 67), header='age')
+
+
+ You can also set rows and headers upon instantiation. This is useful if
+ dealing with dozens or hundreds of :class:`Dataset` objects. ::
+
+ headers = ('first_name', 'last_name')
+ data = [('John', 'Adams'), ('George', 'Washington')]
+
+ data = tablib.Dataset(*data, headers=headers)
+
+ :param \\*args: (optional) list of rows to populate Dataset
+ :param headers: (optional) list strings for Dataset header row
+ :param title: (optional) string to use as title of the Dataset
+
+
+ .. admonition:: Format Attributes Definition
+
+ If you look at the code, the various output/import formats are not
+ defined within the :class:`Dataset` object. To add support for a new format, see
+ :ref:`Adding New Formats `.
+
+ """
+
+ def __init__(self, *args, **kwargs):
+ self._data = [Row(arg) for arg in args]
+ self.__headers = None
+
+ # ('title', index) tuples
+ self._separators = []
+
+ # (column, callback) tuples
+ self._formatters = []
+
+ # {col_index: col_func}
+ self._dynamic_columns = {}
+
+ self.headers = kwargs.get('headers')
+
+ self.title = kwargs.get('title')
+
+ def __len__(self):
+ return self.height
+
+ def __getitem__(self, key):
+ if isinstance(key, str):
+ if self.headers is None:
+ raise HeadersNeeded()
+ if key in self.headers:
+ pos = self.headers.index(key) # get 'key' index from each data
+ return [row[pos] for row in self._data]
+ else:
+ raise KeyError
+ else:
+ _results = self._data[key]
+ if isinstance(_results, Row):
+ return _results.tuple
+ else:
+ return [result.tuple for result in _results]
+
+ def __setitem__(self, key, value):
+ self._validate(value)
+ self._data[key] = Row(value)
+
+ def __delitem__(self, key):
+ if isinstance(key, str):
+ if self.headers is None:
+ raise HeadersNeeded()
+
+ if key in self.headers:
+
+ pos = self.headers.index(key)
+ del self.headers[pos]
+ if pos in self._dynamic_columns:
+ del self._dynamic_columns[pos]
+
+ for i, row in enumerate(self._data):
+
+ del row[pos]
+ self._data[i] = row
+ else:
+ raise KeyError
+ else:
+ del self._data[key]
+
+ def __repr__(self):
+ try:
+ return f'<{self.title.lower()} dataset>'
+ except AttributeError:
+ return ''
+
+ def __str__(self):
+ result = []
+
+ # Add str representation of headers.
+ if self.__headers:
+ result.append([str(h) for h in self.__headers])
+
+ # Add str representation of rows.
+ result.extend(list(map(str, row)) for row in self._data)
+
+ lens = [list(map(len, row)) for row in result]
+ field_lens = list(map(max, zip(*lens)))
+
+ # delimiter between header and data
+ if self.__headers:
+ result.insert(1, ['-' * length for length in field_lens])
+
+ format_string = '|'.join('{{{}:{}}}'.format(*item) for item in enumerate(field_lens))
+
+ return '\n'.join(format_string.format(*row) for row in result)
+
+ # ---------
+ # Internals
+ # ---------
+
+ def _get_in_format(self, fmt_key, **kwargs):
+ return registry.get_format(fmt_key).export_set(self, **kwargs)
+
+ def _set_in_format(self, fmt_key, in_stream, **kwargs):
+ in_stream = normalize_input(in_stream)
+ return registry.get_format(fmt_key).import_set(self, in_stream, **kwargs)
+
+ def _validate(self, row=None, col=None, safety=False):
+ """Assures size of every row in dataset is of proper proportions."""
+ if row:
+ if self.width:
+ is_valid = (
+ len(row) == self.width or
+ len(row) == (self.width - len(self._dynamic_columns))
+ )
+ else:
+ is_valid = True
+ elif col:
+ if len(col) < 1:
+ is_valid = True
+ else:
+ is_valid = (len(col) == self.height) if self.height else True
+ else:
+ is_valid = all(len(x) == self.width for x in self._data)
+
+ if is_valid:
+ return True
+ else:
+ if not safety:
+ raise InvalidDimensions
+ return False
+
+ def _package(self, dicts=True):
+ """Packages Dataset into lists of dictionaries for transmission."""
+ # TODO: Dicts default to false?
+
+ _data = list(self._data)
+
+ def format_row(row):
+ # Execute formatters
+ if self._formatters:
+ row = row.copy() # To not mutate internal data structure
+ for col, callback in self._formatters:
+ if col is None:
+ # Apply formatter to all cells
+ row = [callback(cell) for cell in row]
+ else:
+ row[col] = callback(row[col])
+ return list(row)
+
+ if self.headers:
+ if dicts:
+ data = [dict(list(zip(self.headers, format_row(row)))) for row in _data]
+ else:
+ data = [list(self.headers)] + [format_row(row) for row in _data]
+ else:
+ data = [format_row(row) for row in _data]
+ return data
+
+ def _get_headers(self):
+ """An *optional* list of strings to be used for header rows and attribute names.
+
+ This must be set manually. The given list length must equal :attr:`Dataset.width`.
+
+ """
+ return self.__headers
+
+ def _set_headers(self, collection):
+ """Validating headers setter."""
+ self._validate(collection)
+ if collection:
+ self.__headers = list(collection)
+ else:
+ self.__headers = None
+
+ headers = property(_get_headers, _set_headers)
+
+ def _get_dict(self):
+ """A native Python representation of the :class:`Dataset` object. If headers have
+ been set, a list of Python dictionaries will be returned. If no headers have been set,
+ a list of tuples (rows) will be returned instead.
+
+ A dataset object can also be imported by setting the `Dataset.dict` attribute: ::
+
+ data = tablib.Dataset()
+ data.dict = [{'age': 90, 'first_name': 'Kenneth', 'last_name': 'Reitz'}]
+
+ """
+ return self._package()
+
+ def _set_dict(self, pickle):
+ """A native Python representation of the Dataset object. If headers have been
+ set, a list of Python dictionaries will be returned. If no headers have been
+ set, a list of tuples (rows) will be returned instead.
+
+ A dataset object can also be imported by setting the :attr:`Dataset.dict` attribute. ::
+
+ data = tablib.Dataset()
+ data.dict = [{'age': 90, 'first_name': 'Kenneth', 'last_name': 'Reitz'}]
+
+ """
+ error_details = (
+ "Please check format documentation "
+ "https://tablib.readthedocs.io/en/stable/formats.html"
+ )
+
+ if not pickle:
+ return
+
+ if not isinstance(pickle, list):
+ # sometimes pickle is a dict and len(pickle) returns True.
+ # since we access index 0 we should check if the type is list
+ raise UnsupportedFormat(error_details)
+
+ # if list of rows
+ if isinstance(pickle[0], list):
+ self.wipe()
+ for row in pickle:
+ self.append(Row(row))
+
+ # if list of objects
+ elif isinstance(pickle[0], dict):
+ self.wipe()
+ self.headers = list(pickle[0].keys())
+ for row in pickle:
+ self.append(Row(list(row.values())))
+ else:
+ raise UnsupportedFormat(error_details)
+
+ dict = property(_get_dict, _set_dict)
+
+ def _clean_col(self, col):
+ """Prepares the given column for insert/append. `col` is not supposed to
+ contain any header value.
+ """
+
+ col = list(col)
+
+ if len(col) == 1 and hasattr(col[0], '__call__'):
+ col = list(map(col[0], self._data))
+
+ return col
+
+ @property
+ def height(self):
+ """The number of rows currently in the :class:`Dataset`.
+ Cannot be directly modified.
+ """
+ return len(self._data)
+
+ @property
+ def width(self):
+ """The number of columns currently in the :class:`Dataset`.
+ Cannot be directly modified.
+ """
+
+ try:
+ return len(self._data[0])
+ except IndexError:
+ try:
+ return len(self.headers)
+ except TypeError:
+ return 0
+
+ def load(self, in_stream, format=None, **kwargs):
+ """
+ Import `in_stream` to the :class:`Dataset` object using the `format`.
+ `in_stream` can be a file-like object, a string, or a bytestring.
+
+ :param \\*\\*kwargs: (optional) custom configuration to the format `import_set`.
+ """
+
+ stream = normalize_input(in_stream)
+ if not format:
+ format = detect_format(stream)
+
+ fmt = registry.get_format(format)
+ if not hasattr(fmt, 'import_set'):
+ raise UnsupportedFormat(f'Format {format} cannot be imported.')
+
+ fmt.import_set(self, stream, **kwargs)
+ return self
+
+ def export(self, format, **kwargs):
+ """
+ Export :class:`Dataset` object to `format`.
+
+ :param \\*\\*kwargs: (optional) custom configuration to the format `export_set`.
+ """
+ fmt = registry.get_format(format)
+ if not hasattr(fmt, 'export_set'):
+ raise UnsupportedFormat(f'Format {format} cannot be exported.')
+
+ return fmt.export_set(self, **kwargs)
+
+ # ----
+ # Rows
+ # ----
+
+ def insert(self, index, row, tags=()):
+ """Inserts a row to the :class:`Dataset` at the given index.
+
+ Rows inserted must be the correct size (height or width).
+
+ The default behaviour is to insert the given row to the :class:`Dataset`
+ object at the given index.
+
+ You can add :ref:`tags ` to the row you are inserting.
+ This gives you the ability to :method:`filter ` your
+ :class:`Dataset` later.
+ """
+
+ self._validate(row)
+ if len(row) < self.width:
+ for pos, func in self._dynamic_columns.items():
+ row = list(row)
+ row.insert(pos, func(row))
+ self._data.insert(index, Row(row, tags=tags))
+
+ def rpush(self, row, tags=()):
+ """Adds a row to the end of the :class:`Dataset`.
+ See :method:`Dataset.insert` for additional documentation.
+ """
+
+ self.insert(self.height, row=row, tags=tags)
+
+ def lpush(self, row, tags=()):
+ """Adds a row to the top of the :class:`Dataset`.
+ See :method:`Dataset.insert` for additional documentation.
+ """
+
+ self.insert(0, row=row, tags=tags)
+
+ def append(self, row, tags=()):
+ """Adds a row to the :class:`Dataset`.
+ See :method:`Dataset.insert` for additional documentation.
+ """
+
+ self.rpush(row, tags)
+
+ def extend(self, rows, tags=()):
+ """Adds a list of rows to the :class:`Dataset` using
+ :method:`Dataset.append`
+ """
+
+ for row in rows:
+ self.append(row, tags)
+
+ def lpop(self):
+ """Removes and returns the first row of the :class:`Dataset`."""
+
+ cache = self[0]
+ del self[0]
+
+ return cache
+
+ def rpop(self):
+ """Removes and returns the last row of the :class:`Dataset`."""
+
+ cache = self[-1]
+ del self[-1]
+
+ return cache
+
+ def pop(self):
+ """Removes and returns the last row of the :class:`Dataset`."""
+
+ return self.rpop()
+
+ def get(self, index):
+ """Returns the row from the :class:`Dataset` at the given index."""
+
+ if isinstance(index, int):
+ return self[index]
+
+ raise TypeError('Row indices must be integers.')
+
+ # -------
+ # Columns
+ # -------
+
+ def insert_col(self, index, col=None, header=None):
+ """Inserts a column to the :class:`Dataset` at the given index.
+
+ Columns inserted must be the correct height.
+
+ You can also insert a column of a single callable object, which will
+ add a new column with the return values of the callable each as an
+ item in the column. ::
+
+ data.append_col(col=random.randint)
+
+ If inserting a column, and :attr:`Dataset.headers` is set, the
+ header attribute must be set, and will be considered the header for
+ that row.
+
+ See :ref:`dyncols` for an in-depth example.
+ """
+
+ if col is None:
+ col = []
+
+ # Callable Columns...
+ if callable(col):
+ self._dynamic_columns[self.width] = col
+ col = list(map(col, self._data))
+
+ col = self._clean_col(col)
+ self._validate(col=col)
+
+ if self.headers:
+ # pop the first item off, add to headers
+ if not header:
+ raise HeadersNeeded()
+
+ # corner case - if header is set without data
+ elif header and self.height == 0 and len(col):
+ raise InvalidDimensions
+
+ self.headers.insert(index, header)
+
+ if self.height and self.width:
+
+ for i, row in enumerate(self._data):
+
+ row.insert(index, col[i])
+ self._data[i] = row
+ else:
+ self._data = [Row([row]) for row in col]
+
+ def rpush_col(self, col, header=None):
+ """Adds a column to the end of the :class:`Dataset`.
+ See :method:`Dataset.insert` for additional documentation.
+ """
+
+ self.insert_col(self.width, col, header=header)
+
+ def lpush_col(self, col, header=None):
+ """Adds a column to the top of the :class:`Dataset`.
+ See :method:`Dataset.insert` for additional documentation.
+ """
+
+ self.insert_col(0, col, header=header)
+
+ def insert_separator(self, index, text='-'):
+ """Adds a separator to :class:`Dataset` at given index."""
+
+ sep = (index, text)
+ self._separators.append(sep)
+
+ def append_separator(self, text='-'):
+ """Adds a :ref:`separator ` to the :class:`Dataset`."""
+
+ # change offsets if headers are or aren't defined
+ if not self.headers:
+ index = self.height if self.height else 0
+ else:
+ index = (self.height + 1) if self.height else 1
+
+ self.insert_separator(index, text)
+
+ def append_col(self, col, header=None):
+ """Adds a column to the :class:`Dataset`.
+ See :method:`Dataset.insert_col` for additional documentation.
+ """
+
+ self.rpush_col(col, header)
+
+ def get_col(self, index):
+ """Returns the column from the :class:`Dataset` at the given index."""
+
+ return [row[index] for row in self._data]
+
+ # ----
+ # Misc
+ # ----
+
+ def add_formatter(self, col, handler):
+ """Adds a formatter to the :class:`Dataset`.
+
+ :param col: column to. Accepts index int, header str, or None to apply
+ the formatter to all columns.
+ :param handler: reference to callback function to execute against
+ each cell value.
+ """
+
+ if isinstance(col, str):
+ if col in self.headers:
+ col = self.headers.index(col) # get 'key' index from each data
+ else:
+ raise KeyError
+
+ if col is None or col <= self.width:
+ self._formatters.append((col, handler))
+ else:
+ raise InvalidDatasetIndex
+
+ return True
+
+ def filter(self, tag):
+ """Returns a new instance of the :class:`Dataset`, excluding any rows
+ that do not contain the given :ref:`tags `.
+ """
+ _dset = copy(self)
+ _dset._data = [row for row in _dset._data if row.has_tag(tag)]
+
+ return _dset
+
+ def sort(self, col, reverse=False):
+ """Sort a :class:`Dataset` by a specific column, given string (for
+ header) or integer (for column index). The order can be reversed by
+ setting ``reverse`` to ``True``.
+
+ Returns a new :class:`Dataset` instance where columns have been
+ sorted.
+ """
+
+ if isinstance(col, str):
+
+ if not self.headers:
+ raise HeadersNeeded
+
+ _sorted = sorted(self.dict, key=itemgetter(col), reverse=reverse)
+ _dset = Dataset(headers=self.headers, title=self.title)
+
+ for item in _sorted:
+ row = [item[key] for key in self.headers]
+ _dset.append(row=row)
+
+ else:
+ if self.headers:
+ col = self.headers[col]
+
+ _sorted = sorted(self.dict, key=itemgetter(col), reverse=reverse)
+ _dset = Dataset(headers=self.headers, title=self.title)
+
+ for item in _sorted:
+ if self.headers:
+ row = [item[key] for key in self.headers]
+ else:
+ row = item
+ _dset.append(row=row)
+
+ return _dset
+
+ def _transpose_with_headers(self):
+ """Transpose a :class:`Dataset`, turning rows into columns and vice
+ versa, returning a new ``Dataset`` instance. The first row of the
+ original instance becomes the new header row."""
+
+ _dset = Dataset()
+ # The first element of the headers stays in the headers,
+ # it is our "hinge" on which we rotate the data
+ new_headers = [self.headers[0]] + self[self.headers[0]]
+
+ _dset.headers = new_headers
+ for index, column in enumerate(self.headers):
+
+ if column == self.headers[0]:
+ # It's in the headers, so skip it
+ continue
+
+ # Adding the column name as now they're a regular column
+ # Use `get_col(index)` in case there are repeated values
+ row_data = [column] + self.get_col(index)
+ row_data = Row(row_data)
+ _dset.append(row=row_data)
+ return _dset
+
+ def _transpose_without_headers(self):
+ """Transpose a :class:`Dataset`, turning rows into columns and vice
+ versa, returning a new ``Dataset`` instance. This instance should not
+ have headers, or the dimension would be invalid."""
+
+ _dset = Dataset()
+
+ # Add columns as rows in new instance
+ for index in range(len(self._data[0])):
+ row_data = self.get_col(index)
+ _dset.append(row=row_data)
+
+ return _dset
+
+ def transpose(self):
+ """Transpose a :class:`Dataset`, turning rows into columns and vice
+ versa, returning a new ``Dataset`` instance. If the instance has
+ headers, the first row of the original instance becomes the new header
+ row."""
+
+ # Don't transpose if there is no data
+ if not self:
+ return
+
+ if self.headers is None:
+ return self._transpose_without_headers()
+ else:
+ return self._transpose_with_headers()
+
+ def stack(self, other):
+ """Stack two :class:`Dataset` instances together by
+ joining at the row level, and return new combined
+ ``Dataset`` instance."""
+
+ if not isinstance(other, Dataset):
+ raise TypeError("'other' must be a Dataset instance")
+
+ if self.width != other.width:
+ raise InvalidDimensions
+
+ # Copy the source data
+ _dset = copy(self)
+
+ rows_to_stack = list(_dset._data)
+ other_rows = list(other._data)
+
+ rows_to_stack.extend(other_rows)
+ _dset._data = rows_to_stack
+
+ return _dset
+
+ def stack_cols(self, other):
+ """Stack two :class:`Dataset` instances together by
+ joining at the column level, and return a new
+ combined ``Dataset`` instance. If either ``Dataset``
+ has headers set, than the other must as well."""
+
+ if not isinstance(other, Dataset):
+ raise TypeError("'other' must be a Dataset instance")
+
+ if self.headers or other.headers:
+ if not self.headers or not other.headers:
+ raise HeadersNeeded
+
+ if self.height != other.height:
+ raise InvalidDimensions
+
+ try:
+ new_headers = self.headers + other.headers
+ except TypeError:
+ new_headers = None
+
+ _dset = Dataset()
+
+ if self.headers:
+ for column in self.headers:
+ _dset.append_col(col=self[column])
+
+ for column in other.headers:
+ _dset.append_col(col=other[column])
+ else:
+ for index in range(self.width):
+ _dset.append_col(col=self.get_col(index))
+
+ for index in range(other.width):
+ _dset.append_col(col=other.get_col(index))
+
+ _dset.headers = new_headers
+
+ return _dset
+
+ def remove_duplicates(self):
+ """Removes all duplicate rows from the :class:`Dataset` object
+ while maintaining the original order."""
+ seen = set()
+ self._data[:] = [
+ row for row in self._data if not (tuple(row) in seen or seen.add(tuple(row)))
+ ]
+
+ def wipe(self):
+ """Removes all content and headers from the :class:`Dataset` object."""
+ self._data = []
+ self.__headers = None
+
+ def subset(self, rows=None, cols=None):
+ """Returns a new instance of the :class:`Dataset`,
+ including only specified rows and columns.
+ """
+
+ # Don't return if no data
+ if not self:
+ return
+
+ if rows is None:
+ rows = list(range(self.height))
+
+ if cols is None:
+ cols = list(self.headers)
+
+ # filter out impossible rows and columns
+ rows = [row for row in rows if row in range(self.height)]
+ cols = [header for header in cols if header in self.headers]
+
+ _dset = Dataset()
+
+ # filtering rows and columns
+ _dset.headers = list(cols)
+
+ _dset._data = []
+ for row_no, row in enumerate(self._data):
+ data_row = []
+ for key in _dset.headers:
+ if key in self.headers:
+ pos = self.headers.index(key)
+ data_row.append(row[pos])
+ else:
+ raise KeyError
+
+ if row_no in rows:
+ _dset.append(row=Row(data_row))
+
+ return _dset
+
+
+class Databook:
+ """A book of :class:`Dataset` objects.
+ """
+
+ def __init__(self, sets=None):
+ self._datasets = sets or []
+
+ def __repr__(self):
+ try:
+ return f'<{self.title.lower()} databook>'
+ except AttributeError:
+ return ''
+
+ def wipe(self):
+ """Removes all :class:`Dataset` objects from the :class:`Databook`."""
+ self._datasets = []
+
+ def sheets(self):
+ return self._datasets
+
+ def add_sheet(self, dataset):
+ """Adds given :class:`Dataset` to the :class:`Databook`."""
+ if isinstance(dataset, Dataset):
+ self._datasets.append(dataset)
+ else:
+ raise InvalidDatasetType
+
+ def _package(self):
+ """Packages :class:`Databook` for delivery."""
+ collector = []
+
+ for dset in self._datasets:
+ collector.append({
+ 'title': dset.title,
+ 'data': dset._package()
+ })
+ return collector
+
+ @property
+ def size(self):
+ """The number of the :class:`Dataset` objects within :class:`Databook`."""
+ return len(self._datasets)
+
+ def load(self, in_stream, format, **kwargs):
+ """
+ Import `in_stream` to the :class:`Databook` object using the `format`.
+ `in_stream` can be a file-like object, a string, or a bytestring.
+
+ :param \\*\\*kwargs: (optional) custom configuration to the format `import_book`.
+ """
+
+ stream = normalize_input(in_stream)
+ if not format:
+ format = detect_format(stream)
+
+ fmt = registry.get_format(format)
+ if not hasattr(fmt, 'import_book'):
+ raise UnsupportedFormat(f'Format {format} cannot be loaded.')
+
+ fmt.import_book(self, stream, **kwargs)
+ return self
+
+ def export(self, format, **kwargs):
+ """
+ Export :class:`Databook` object to `format`.
+
+ :param \\*\\*kwargs: (optional) custom configuration to the format `export_book`.
+ """
+ fmt = registry.get_format(format)
+ if not hasattr(fmt, 'export_book'):
+ raise UnsupportedFormat(f'Format {format} cannot be exported.')
+
+ return fmt.export_book(self, **kwargs)
+
+
+def detect_format(stream):
+ """Return format name of given stream (file-like object, string, or bytestring)."""
+ stream = normalize_input(stream)
+ fmt_title = None
+ for fmt in registry.formats():
+ try:
+ if fmt.detect(stream):
+ fmt_title = fmt.title
+ break
+ except AttributeError:
+ pass
+ finally:
+ if hasattr(stream, 'seek'):
+ stream.seek(0)
+ return fmt_title
+
+
+def import_set(stream, format=None, **kwargs):
+ """Return dataset of given stream (file-like object, string, or bytestring)."""
+
+ return Dataset().load(stream, format, **kwargs)
+
+
+def import_book(stream, format=None, **kwargs):
+ """Return dataset of given stream (file-like object, string, or bytestring)."""
+
+ return Databook().load(stream, format, **kwargs)
+
+
+registry.register_builtins()
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/exceptions.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab64ad25fc9007f5c5ba1142dd71bb5e85c39d74
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/exceptions.py
@@ -0,0 +1,22 @@
+class TablibException(Exception):
+ """Tablib common exception."""
+
+
+class InvalidDatasetType(TablibException, TypeError):
+ """Only Datasets can be added to a Databook."""
+
+
+class InvalidDimensions(TablibException, ValueError):
+ """The size of the column or row doesn't fit the table dimensions."""
+
+
+class InvalidDatasetIndex(TablibException, IndexError):
+ """Outside of Dataset size."""
+
+
+class HeadersNeeded(TablibException, AttributeError):
+ """Header parameter must be given when appending a column to this Dataset."""
+
+
+class UnsupportedFormat(TablibException, NotImplementedError):
+ """Format not supported."""
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/__init__.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d698d59ffa91be9b48ce6921eb574549736a8a5d
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/__init__.py
@@ -0,0 +1,144 @@
+""" Tablib - formats
+"""
+
+__lazy_modules__ = {
+ "functools",
+ "importlib",
+ "importlib.util",
+ "tablib.exceptions",
+ "tablib.formats._csv",
+ "tablib.formats._json",
+ "tablib.formats._tsv",
+ "tablib.utils",
+}
+
+from functools import partialmethod
+from importlib import import_module
+from importlib.util import find_spec
+
+from ..exceptions import UnsupportedFormat
+from ..utils import normalize_input
+from ._csv import CSVFormat
+from ._json import JSONFormat
+from ._tsv import TSVFormat
+
+uninstalled_format_messages = {
+ "cli": {"package_name": "tabulate package", "extras_name": "cli"},
+ "df": {"package_name": "pandas package", "extras_name": "pandas"},
+ "ods": {"package_name": "odfpy package", "extras_name": "ods"},
+ "xls": {"package_name": "xlrd and xlwt packages", "extras_name": "xls"},
+ "xlsx": {"package_name": "openpyxl package", "extras_name": "xlsx"},
+ "yaml": {"package_name": "pyyaml package", "extras_name": "yaml"},
+}
+
+
+def load_format_class(dotted_path):
+ try:
+ module_path, class_name = dotted_path.rsplit('.', 1)
+ return getattr(import_module(module_path), class_name)
+ except (ValueError, AttributeError) as err:
+ raise ImportError(f"Unable to load format class '{dotted_path}' ({err})")
+
+
+class FormatDescriptorBase:
+ def __init__(self, key, format_or_path):
+ self.key = key
+ self._format_path = None
+ if isinstance(format_or_path, str):
+ self._format = None
+ self._format_path = format_or_path
+ else:
+ self._format = format_or_path
+
+ def ensure_format_loaded(self):
+ if self._format is None:
+ self._format = load_format_class(self._format_path)
+
+
+class ImportExportBookDescriptor(FormatDescriptorBase):
+ def __get__(self, obj, cls, **kwargs):
+ self.ensure_format_loaded()
+ return self._format.export_book(obj, **kwargs)
+
+ def __set__(self, obj, val):
+ self.ensure_format_loaded()
+ return self._format.import_book(obj, normalize_input(val))
+
+
+class ImportExportSetDescriptor(FormatDescriptorBase):
+ def __get__(self, obj, cls, **kwargs):
+ self.ensure_format_loaded()
+ return self._format.export_set(obj, **kwargs)
+
+ def __set__(self, obj, val):
+ self.ensure_format_loaded()
+ return self._format.import_set(obj, normalize_input(val))
+
+
+class Registry:
+ _formats = {}
+
+ def register(self, key, format_or_path):
+ from ..core import Databook, Dataset
+
+ # Create Databook. read or read/write properties
+ setattr(Databook, key, ImportExportBookDescriptor(key, format_or_path))
+
+ # Create Dataset. read or read/write properties,
+ # and Dataset.get_/set_ methods.
+ setattr(Dataset, key, ImportExportSetDescriptor(key, format_or_path))
+ try:
+ setattr(Dataset, f'get_{key}', partialmethod(Dataset._get_in_format, key))
+ setattr(Dataset, f'set_{key}', partialmethod(Dataset._set_in_format, key))
+ except AttributeError:
+ setattr(Dataset, f'get_{key}', partialmethod(Dataset._get_in_format, key))
+
+ self._formats[key] = format_or_path
+
+ def register_builtins(self):
+ # Registration ordering matters for autodetection.
+ self.register('json', JSONFormat())
+ # xlsx before as xls (xlrd) can also read xlsx
+ if find_spec('openpyxl'):
+ self.register('xlsx', 'tablib.formats._xlsx.XLSXFormat')
+ if find_spec('xlrd') and find_spec('xlwt'):
+ self.register('xls', 'tablib.formats._xls.XLSFormat')
+ if find_spec('yaml'):
+ self.register('yaml', 'tablib.formats._yaml.YAMLFormat')
+ self.register('csv', CSVFormat())
+ self.register('tsv', TSVFormat())
+ if find_spec('odf'):
+ self.register('ods', 'tablib.formats._ods.ODSFormat')
+ self.register('dbf', 'tablib.formats._dbf.DBFFormat')
+ self.register('html', 'tablib.formats._html.HTMLFormat')
+ self.register('jira', 'tablib.formats._jira.JIRAFormat')
+ self.register('latex', 'tablib.formats._latex.LATEXFormat')
+ if find_spec('pandas'):
+ self.register('df', 'tablib.formats._df.DataFrameFormat')
+ self.register('rst', 'tablib.formats._rst.ReSTFormat')
+ self.register('sql', 'tablib.formats._sql.SQLFormat')
+ if find_spec('tabulate'):
+ self.register('cli', 'tablib.formats._cli.CLIFormat')
+
+ def formats(self):
+ for key, frm in self._formats.items():
+ if isinstance(frm, str):
+ self._formats[key] = load_format_class(frm)
+ yield self._formats[key]
+
+ def get_format(self, key):
+ if key not in self._formats:
+ if key in uninstalled_format_messages:
+ raise UnsupportedFormat(
+ "The '{key}' format is not available. You may want to install the "
+ "{package_name} (or `pip install \"tablib[{extras_name}]\"`).".format(
+ **uninstalled_format_messages[key], key=key
+ )
+ )
+ raise UnsupportedFormat(f"Tablib has no format '{key}' or it is not registered.")
+ if isinstance(self._formats[key], str):
+ self._formats[key] = load_format_class(self._formats[key])
+ return self._formats[key]
+
+
+registry = Registry()
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_cli.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..db57a9c0a855a5bb88b42e493bcee94532967e65
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_cli.py
@@ -0,0 +1,23 @@
+"""Tablib - Command-line Interface table export support.
+
+ Generates a representation for CLI from the dataset.
+ Wrapper for tabulate library.
+"""
+
+__lazy_modules__ = {"tabulate"}
+
+from tabulate import tabulate as Tabulate
+
+
+class CLIFormat:
+ """ Class responsible to export to CLI Format """
+ title = 'cli'
+ DEFAULT_FMT = 'plain'
+
+ @classmethod
+ def export_set(cls, dataset, **kwargs):
+ """Returns CLI representation of a Dataset."""
+ if dataset.headers:
+ kwargs.setdefault('headers', dataset.headers)
+ kwargs.setdefault('tablefmt', cls.DEFAULT_FMT)
+ return Tabulate(dataset, **kwargs)
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_csv.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_csv.py
new file mode 100644
index 0000000000000000000000000000000000000000..e57e1d9ed12cfcd140997ab1c23ad105a89dd9b7
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_csv.py
@@ -0,0 +1,63 @@
+""" Tablib - *SV Support.
+"""
+
+__lazy_modules__ = {"csv", "io"}
+
+import csv
+from io import StringIO
+
+
+class CSVFormat:
+ title = 'csv'
+ extensions = ('csv',)
+
+ DEFAULT_DELIMITER = ','
+
+ @classmethod
+ def export_stream_set(cls, dataset, **kwargs):
+ """Returns CSV representation of Dataset as file-like."""
+ stream = StringIO()
+
+ kwargs.setdefault('delimiter', cls.DEFAULT_DELIMITER)
+
+ _csv = csv.writer(stream, **kwargs)
+
+ for row in dataset._package(dicts=False):
+ _csv.writerow(row)
+
+ stream.seek(0)
+ return stream
+
+ @classmethod
+ def export_set(cls, dataset, **kwargs):
+ """Returns CSV representation of Dataset."""
+ stream = cls.export_stream_set(dataset, **kwargs)
+ return stream.getvalue()
+
+ @classmethod
+ def import_set(cls, dset, in_stream, headers=True, skip_lines=0, **kwargs):
+ """Returns dataset from CSV stream."""
+
+ dset.wipe()
+
+ kwargs.setdefault('delimiter', cls.DEFAULT_DELIMITER)
+
+ rows = csv.reader(in_stream, **kwargs)
+ for i, row in enumerate(rows):
+ if i < skip_lines:
+ continue
+ if i == skip_lines and headers:
+ dset.headers = row
+ elif row:
+ if i > 0 and len(row) < dset.width:
+ row += [''] * (dset.width - len(row))
+ dset.append(row)
+
+ @classmethod
+ def detect(cls, stream, delimiter=None):
+ """Returns True if given stream is valid CSV."""
+ try:
+ csv.Sniffer().sniff(stream.read(2048), delimiters=delimiter or cls.DEFAULT_DELIMITER)
+ return True
+ except Exception:
+ return False
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_dbf.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_dbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..16737037369fd700d718e7b5050f0af8a9fca7fa
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_dbf.py
@@ -0,0 +1,74 @@
+""" Tablib - DBF Support.
+"""
+
+__lazy_modules__ = {
+ "io",
+ "os",
+ "tablib._vendor",
+ "tempfile",
+}
+
+import io
+import os
+import tempfile
+
+from .._vendor.dbfpy import dbf, dbfnew
+from .._vendor.dbfpy import record as dbfrecord
+
+
+class DBFFormat:
+ title = 'dbf'
+ extensions = ('csv',)
+
+ DEFAULT_ENCODING = 'utf-8'
+
+ @classmethod
+ def export_set(cls, dataset):
+ """Returns DBF representation of a Dataset"""
+ new_dbf = dbfnew.dbf_new()
+ temp_file, temp_uri = tempfile.mkstemp()
+
+ # create the appropriate fields based on the contents of the first row
+ first_row = dataset[0]
+ for fieldname, field_value in zip(dataset.headers, first_row):
+ if type(field_value) in [int, float]:
+ new_dbf.add_field(fieldname, 'N', 10, 8)
+ else:
+ new_dbf.add_field(fieldname, 'C', 80)
+
+ new_dbf.write(temp_uri)
+
+ dbf_file = dbf.Dbf(temp_uri, readOnly=0)
+ for row in dataset:
+ record = dbfrecord.DbfRecord(dbf_file)
+ for fieldname, field_value in zip(dataset.headers, row):
+ record[fieldname] = field_value
+ record.store()
+
+ dbf_file.close()
+ dbf_stream = open(temp_uri, 'rb')
+ stream = io.BytesIO(dbf_stream.read())
+ dbf_stream.close()
+ os.close(temp_file)
+ os.remove(temp_uri)
+ return stream.getvalue()
+
+ @classmethod
+ def import_set(cls, dset, in_stream):
+ """Returns a dataset from a DBF stream."""
+
+ dset.wipe()
+ _dbf = dbf.Dbf(in_stream)
+ dset.headers = _dbf.fieldNames
+ for record in range(_dbf.recordCount):
+ row = [_dbf[record][f] for f in _dbf.fieldNames]
+ dset.append(row)
+
+ @classmethod
+ def detect(cls, stream):
+ """Returns True if the given stream is valid DBF"""
+ try:
+ dbf.Dbf(stream, readOnly=True)
+ return True
+ except Exception:
+ return False
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_df.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_df.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4f9d80c39dcd1ae49de5fa8a62dd7805ec27f90
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_df.py
@@ -0,0 +1,41 @@
+""" Tablib - DataFrame Support.
+"""
+
+try:
+ from pandas import DataFrame
+except ImportError:
+ DataFrame = None
+
+
+class DataFrameFormat:
+ title = 'df'
+ extensions = ('df',)
+
+ @classmethod
+ def detect(cls, stream):
+ """Returns True if given stream is a DataFrame."""
+ if DataFrame is None:
+ return False
+ elif isinstance(stream, DataFrame):
+ return True
+ try:
+ DataFrame(stream.read())
+ return True
+ except ValueError:
+ return False
+
+ @classmethod
+ def export_set(cls, dset):
+ """Returns DataFrame representation of DataBook."""
+ if DataFrame is None:
+ raise NotImplementedError(
+ 'DataFrame Format requires `pandas` to be installed.'
+ ' Try `pip install "tablib[pandas]"`.')
+ dataframe = DataFrame(dset.dict, columns=dset.headers)
+ return dataframe
+
+ @classmethod
+ def import_set(cls, dset, in_stream):
+ """Returns dataset from DataFrame."""
+ dset.wipe()
+ dset.dict = in_stream.to_dict(orient='records')
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_html.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_html.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc6930093d8a2867527aafe0986e252b9e6ae018
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_html.py
@@ -0,0 +1,117 @@
+""" Tablib - HTML export support.
+"""
+
+__lazy_modules__ = {"xml", "xml.etree"}
+
+from html.parser import HTMLParser
+from xml.etree import ElementTree as ET
+
+
+class HTMLFormat:
+ BOOK_ENDINGS = 'h3'
+
+ title = 'html'
+ extensions = ('html', )
+
+ @classmethod
+ def export_set(cls, dataset):
+ """HTML representation of a Dataset."""
+
+ table = ET.Element('table')
+ if dataset.headers is not None:
+ head = ET.Element('thead')
+ tr = ET.Element('tr')
+ for header in dataset.headers:
+ th = ET.Element('th')
+ th.text = str(header) if header is not None else ''
+ tr.append(th)
+ head.append(tr)
+ table.append(head)
+
+ body = ET.Element('tbody')
+ for row in dataset:
+ tr = ET.Element('tr')
+ for item in row:
+ td = ET.Element('td')
+ td.text = str(item) if item is not None else ''
+ tr.append(td)
+ body.append(tr)
+ table.append(body)
+
+ return ET.tostring(table, method='html', encoding='unicode')
+
+ @classmethod
+ def export_book(cls, databook):
+ """HTML representation of a Databook."""
+
+ result = ''
+ for i, dset in enumerate(databook._datasets):
+ title = dset.title if dset.title else f'Set {i}'
+ result += f'<{cls.BOOK_ENDINGS}>{title}{cls.BOOK_ENDINGS}>\n'
+ result += dset.html
+ result += '\n'
+
+ return result
+
+ @classmethod
+ def import_set(cls, dset, in_stream, table_id=None):
+ """Returns dataset from HTML content."""
+
+ dset.wipe()
+ parser = TablibHTMLParser(dset, table_id=table_id)
+ parser.feed(in_stream.read())
+ if not parser.table_found:
+ if table_id:
+ raise ValueError(f'No
found with id="{table_id}" in input HTML')
+ else:
+ raise ValueError('No
found in input HTML')
+
+
+class TablibHTMLParser(HTMLParser):
+ def __init__(self, dataset, *args, table_id=None, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.dset = dataset
+ self.table_id = table_id
+ self.table_found = False
+ self.table_open = False
+ self.thead_open = False
+ self.cell_open = False
+ self.headers = []
+ self.current_row = []
+ self.current_data = ''
+
+ def handle_starttag(self, tag, attrs):
+ if (
+ tag == 'table' and not self.table_found and
+ (not self.table_id or dict(attrs).get('id') == self.table_id)
+ ):
+ self.table_open = True
+ self.table_found = True
+ elif self.table_open:
+ if tag == 'thead':
+ self.thead_open = True
+ elif tag in ['td', 'th']:
+ self.cell_open = True
+
+ def handle_endtag(self, tag):
+ if not self.table_open:
+ return
+ if tag == 'table':
+ self.table_open = False
+ elif tag == 'thead':
+ self.thead_open = False
+ self.dset.headers = self.headers
+ elif tag == 'tr' and self.current_row:
+ self.dset.append(self.current_row)
+ self.current_row = []
+ elif tag in ['td', 'th']:
+ if self.thead_open:
+ self.headers.append(self.current_data)
+ else:
+ self.current_row.append(self.current_data)
+ self.cell_open = False
+ self.current_data = ''
+
+ def handle_data(self, data):
+ if self.cell_open:
+ self.current_data += data
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_jira.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_jira.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bb62e79c3eaeaab08ccba51f838c41fc7ebcbd6
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_jira.py
@@ -0,0 +1,40 @@
+"""Tablib - Jira table export support.
+
+ Generates a Jira table from the dataset.
+"""
+
+
+class JIRAFormat:
+ title = 'jira'
+
+ @classmethod
+ def export_set(cls, dataset):
+ """Formats the dataset according to the Jira table syntax:
+
+ ||heading 1||heading 2||heading 3||
+ |col A1|col A2|col A3|
+ |col B1|col B2|col B3|
+
+ :param dataset: dataset to serialize
+ :type dataset: tablib.core.Dataset
+ """
+
+ header = cls._get_header(dataset.headers) if dataset.headers else ''
+ body = cls._get_body(dataset)
+ return f'{header}\n{body}' if header else body
+
+ @classmethod
+ def _get_body(cls, dataset):
+ return '\n'.join([cls._serialize_row(row) for row in dataset])
+
+ @classmethod
+ def _get_header(cls, headers):
+ return cls._serialize_row(headers, delimiter='||')
+
+ @classmethod
+ def _serialize_row(cls, row, delimiter='|'):
+ return '{}{}{}'.format(
+ delimiter,
+ delimiter.join([str(item) if item else ' ' for item in row]),
+ delimiter
+ )
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_json.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_json.py
new file mode 100644
index 0000000000000000000000000000000000000000..246188369f135cd34a71921030731a8c28d9fff5
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_json.py
@@ -0,0 +1,65 @@
+""" Tablib - JSON Support
+"""
+
+__lazy_modules__ = {"decimal", "json", "uuid"}
+
+import decimal
+import json
+from uuid import UUID
+
+import tablib
+
+
+def serialize_objects_handler(obj):
+ if isinstance(obj, (decimal.Decimal, UUID)):
+ return str(obj)
+ elif hasattr(obj, 'isoformat'):
+ return obj.isoformat()
+ else:
+ return obj
+
+
+class JSONFormat:
+ title = 'json'
+ extensions = ('json', 'jsn')
+
+ @classmethod
+ def export_set(cls, dataset):
+ """Returns JSON representation of Dataset."""
+ return json.dumps(
+ dataset.dict, default=serialize_objects_handler, ensure_ascii=False
+ )
+
+ @classmethod
+ def export_book(cls, databook):
+ """Returns JSON representation of Databook."""
+ return json.dumps(
+ databook._package(), default=serialize_objects_handler, ensure_ascii=False
+ )
+
+ @classmethod
+ def import_set(cls, dset, in_stream):
+ """Returns dataset from JSON stream."""
+
+ dset.wipe()
+ dset.dict = json.load(in_stream)
+
+ @classmethod
+ def import_book(cls, dbook, in_stream):
+ """Returns databook from JSON stream."""
+
+ dbook.wipe()
+ for sheet in json.load(in_stream):
+ data = tablib.Dataset()
+ data.title = sheet['title']
+ data.dict = sheet['data']
+ dbook.add_sheet(data)
+
+ @classmethod
+ def detect(cls, stream):
+ """Returns True if given stream is valid JSON."""
+ try:
+ json.load(stream)
+ return True
+ except (TypeError, ValueError):
+ return False
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_latex.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_latex.py
new file mode 100644
index 0000000000000000000000000000000000000000..20204201eddab4cbbfd6f002de9e30e33e681f30
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_latex.py
@@ -0,0 +1,135 @@
+"""Tablib - LaTeX table export support.
+
+ Generates a LaTeX booktabs-style table from the dataset.
+"""
+
+__lazy_modules__ = {"re"}
+
+import re
+
+
+class LATEXFormat:
+ title = 'latex'
+ extensions = ('tex',)
+
+ TABLE_TEMPLATE = """\
+%% Note: add \\usepackage{booktabs} to your preamble
+%%
+\\begin{table}[!htbp]
+ \\centering
+ %(CAPTION)s
+ \\begin{tabular}{%(COLSPEC)s}
+ \\toprule
+%(HEADER)s
+ %(MIDRULE)s
+%(BODY)s
+ \\bottomrule
+ \\end{tabular}
+\\end{table}
+"""
+
+ TEX_RESERVED_SYMBOLS_MAP = {
+ '\\': '\\textbackslash{}',
+ '{': '\\{',
+ '}': '\\}',
+ '$': '\\$',
+ '&': '\\&',
+ '#': '\\#',
+ '^': '\\textasciicircum{}',
+ '_': '\\_',
+ '~': '\\textasciitilde{}',
+ '%': '\\%',
+ }
+
+ TEX_RESERVED_SYMBOLS_RE = re.compile(
+ '({})'.format('|'.join(map(re.escape, TEX_RESERVED_SYMBOLS_MAP.keys()))))
+
+ @classmethod
+ def export_set(cls, dataset):
+ """Returns LaTeX representation of dataset
+
+ :param dataset: dataset to serialize
+ :type dataset: tablib.core.Dataset
+ """
+
+ caption = f'\\caption{{{dataset.title}}}' if dataset.title else '%'
+ colspec = cls._colspec(dataset.width)
+ header = cls._serialize_row(dataset.headers) if dataset.headers else ''
+ midrule = cls._midrule(dataset.width)
+ body = '\n'.join([cls._serialize_row(row) for row in dataset])
+ return cls.TABLE_TEMPLATE % {'CAPTION': caption, 'COLSPEC': colspec,
+ 'HEADER': header, 'MIDRULE': midrule, 'BODY': body}
+
+ @classmethod
+ def _colspec(cls, dataset_width):
+ """Generates the column specification for the LaTeX `tabular` environment
+ based on the dataset width.
+
+ The first column is justified to the left, all further columns are aligned
+ to the right.
+
+ .. note:: This is only a heuristic and most probably has to be fine-tuned
+ post export. Column alignment should depend on the data type, e.g., textual
+ content should usually be aligned to the left while numeric content almost
+ always should be aligned to the right.
+
+ :param dataset_width: width of the dataset
+ """
+
+ spec = 'l'
+ for _ in range(1, dataset_width):
+ spec += 'r'
+ return spec
+
+ @classmethod
+ def _midrule(cls, dataset_width):
+ """Generates the table `midrule`, which may be composed of several
+ `cmidrules`.
+
+ :param dataset_width: width of the dataset to serialize
+ """
+
+ if not dataset_width or dataset_width == 1:
+ return '\\midrule'
+ return ' '.join([cls._cmidrule(colindex, dataset_width) for colindex in
+ range(1, dataset_width + 1)])
+
+ @classmethod
+ def _cmidrule(cls, colindex, dataset_width):
+ """Generates the `cmidrule` for a single column with appropriate trimming
+ based on the column position.
+
+ :param colindex: Column index
+ :param dataset_width: width of the dataset
+ """
+
+ rule = '\\cmidrule(%s){%d-%d}'
+ if colindex == 1:
+ # Rule of first column is trimmed on the right
+ return rule % ('r', colindex, colindex)
+ if colindex == dataset_width:
+ # Rule of last column is trimmed on the left
+ return rule % ('l', colindex, colindex)
+ # Inner columns are trimmed on the left and right
+ return rule % ('lr', colindex, colindex)
+
+ @classmethod
+ def _serialize_row(cls, row):
+ """Returns string representation of a single row.
+
+ :param row: single dataset row
+ """
+
+ new_row = [cls._escape_tex_reserved_symbols(str(item)) if item else ''
+ for item in row]
+ return 6 * ' ' + ' & '.join(new_row) + ' \\\\'
+
+ @classmethod
+ def _escape_tex_reserved_symbols(cls, string):
+ """Escapes all TeX reserved symbols ('_', '~', etc.) in a string.
+
+ :param string: String to escape
+ """
+ def replace(match):
+ return cls.TEX_RESERVED_SYMBOLS_MAP[match.group()]
+ return cls.TEX_RESERVED_SYMBOLS_RE.sub(replace, string)
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_ods.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_ods.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba3e05304176487cd661ce097e5750ac383c84e7
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_ods.py
@@ -0,0 +1,257 @@
+""" Tablib - ODF Support.
+"""
+
+__lazy_modules__ = {"datetime", "io", "numbers"}
+
+import datetime as dt
+import numbers
+from io import BytesIO
+
+from odf import number, opendocument, style, table, text
+
+import tablib
+
+bold = style.Style(name="bold", family="paragraph")
+bold.addElement(style.TextProperties(
+ fontweight="bold",
+ fontweightasian="bold",
+ fontweightcomplex="bold",
+))
+
+
+def set_date_style(style):
+ style.addElement(number.Year(style="long"))
+ style.addElement(number.Text(text="-"))
+ style.addElement(number.Month(style="long"))
+ style.addElement(number.Text(text="-"))
+ style.addElement(number.Day(style="long"))
+
+
+def set_time_style(style):
+ style.addElement(number.Hours(style="long"))
+ style.addElement(number.Text(text=":"))
+ style.addElement(number.Minutes(style="long"))
+ style.addElement(number.Text(text=":"))
+ style.addElement(number.Seconds(style="long", decimalplaces="0"))
+
+
+date_style = number.DateStyle(name="date-style1")
+set_date_style(date_style)
+ds = style.Style(
+ name="ds1",
+ datastylename="date-style1",
+ parentstylename="Default",
+ family="table-cell",
+)
+
+time_style = number.DateStyle(name="time-style1")
+set_time_style(time_style)
+ts = style.Style(
+ name="ts1",
+ datastylename="time-style1",
+ parentstylename="Default",
+ family="table-cell",
+)
+
+datetime_style = number.DateStyle(name="datetime-style1")
+set_date_style(datetime_style)
+datetime_style.addElement(number.Text(text=" "))
+set_time_style(datetime_style)
+dts = style.Style(
+ name="dts1",
+ datastylename="datetime-style1",
+ parentstylename="Default",
+ family="table-cell",
+)
+
+
+class ODSFormat:
+ title = 'ods'
+ extensions = ('ods',)
+
+ @classmethod
+ def export_set(cls, dataset):
+ """Returns ODF representation of Dataset."""
+
+ wb = opendocument.OpenDocumentSpreadsheet()
+ wb.automaticstyles.addElement(bold)
+ wb.styles.addElement(date_style)
+ wb.automaticstyles.addElement(ds)
+ wb.styles.addElement(time_style)
+ wb.automaticstyles.addElement(ts)
+ wb.styles.addElement(datetime_style)
+ wb.automaticstyles.addElement(dts)
+
+ ws = table.Table(name=dataset.title if dataset.title else 'Tablib Dataset')
+ wb.spreadsheet.addElement(ws)
+ cls.dset_sheet(dataset, ws)
+
+ stream = BytesIO()
+ wb.save(stream)
+ return stream.getvalue()
+
+ @classmethod
+ def export_book(cls, databook):
+ """Returns ODF representation of DataBook."""
+
+ wb = opendocument.OpenDocumentSpreadsheet()
+ wb.automaticstyles.addElement(bold)
+
+ for i, dset in enumerate(databook._datasets):
+ ws = table.Table(name=dset.title if dset.title else f"Sheet{i}")
+ wb.spreadsheet.addElement(ws)
+ cls.dset_sheet(dset, ws)
+
+ stream = BytesIO()
+ wb.save(stream)
+ return stream.getvalue()
+
+ @classmethod
+ def import_sheet(cls, dset, sheet, headers=True, skip_lines=0):
+ """Populate dataset `dset` with sheet data."""
+
+ dset.title = sheet.getAttribute('name')
+
+ def is_real_cell(cell):
+ return cell.hasChildNodes() or not cell.getAttribute('numbercolumnsrepeated')
+
+ rows = (row for row in sheet.childNodes if row.tagName == "table:table-row")
+
+ for i, row in enumerate(rows):
+ if i < skip_lines:
+ continue
+ row_vals = [cls.read_cell(cell) for cell in row.childNodes if is_real_cell(cell)]
+ if not row_vals:
+ continue
+ if i == skip_lines and headers:
+ dset.headers = row_vals
+ else:
+ if i > skip_lines and len(row_vals) < dset.width:
+ row_vals += [''] * (dset.width - len(row_vals))
+ dset.append(row_vals)
+
+ @classmethod
+ def read_cell(cls, cell, value_type=None):
+ def convert_date(val):
+ if 'T' in val:
+ return dt.datetime.strptime(val, "%Y-%m-%dT%H:%M:%S")
+ else:
+ return dt.datetime.strptime(val, "%Y-%m-%d").date()
+
+ if value_type is None:
+ value_type = cell.getAttribute('valuetype')
+ if value_type == 'date':
+ date_value = cell.getAttribute('datevalue')
+ if date_value:
+ return convert_date(date_value)
+ if value_type == 'time':
+ time_value = cell.getAttribute('timevalue')
+ try:
+ return dt.datetime.strptime(time_value, "PT%HH%MM%SS").time()
+ except ValueError:
+ # backwards compatibility for times exported with older tablib versions
+ return dt.datetime.strptime(time_value, "%H:%M:%S").time()
+ if value_type == 'boolean':
+ bool_value = cell.getAttribute('booleanvalue')
+ return bool_value == 'true'
+ if not cell.childNodes:
+ value = getattr(cell, 'data', None)
+ if value is None:
+ try:
+ value = cell.getAttribute('value')
+ except ValueError:
+ pass
+ if value is None:
+ return ''
+ if value_type == 'float':
+ return float(value)
+ if value_type == 'date':
+ return convert_date(value)
+ return value # Any other type default to 'string'
+
+ for subnode in cell.childNodes:
+ return cls.read_cell(subnode, value_type)
+
+ @classmethod
+ def import_set(cls, dset, in_stream, headers=True, skip_lines=0):
+ """Populate dataset `dset` from ODS stream."""
+
+ dset.wipe()
+
+ ods_book = opendocument.load(in_stream)
+ for sheet in ods_book.spreadsheet.childNodes:
+ if sheet.qname[1] == 'table':
+ cls.import_sheet(dset, sheet, headers, skip_lines)
+
+ @classmethod
+ def import_book(cls, dbook, in_stream, headers=True):
+ """Populate databook `dbook` from ODS stream."""
+
+ dbook.wipe()
+
+ ods_book = opendocument.load(in_stream)
+
+ for sheet in ods_book.spreadsheet.childNodes:
+ if sheet.qname[1] != 'table':
+ continue
+ dset = tablib.Dataset()
+ cls.import_sheet(dset, sheet, headers)
+ dbook.add_sheet(dset)
+
+ @classmethod
+ def dset_sheet(cls, dataset, ws):
+ """Completes given worksheet from given Dataset."""
+ _package = dataset._package(dicts=False)
+
+ for i, sep in enumerate(dataset._separators):
+ _offset = i
+ _package.insert((sep[0] + _offset), (sep[1],))
+
+ for row_number, row in enumerate(_package, start=1):
+ is_header = row_number == 1 and dataset.headers
+ style = bold if is_header else None
+ odf_row = table.TableRow(stylename=style)
+ ws.addElement(odf_row)
+ for j, col in enumerate(row):
+ if isinstance(col, bool):
+ cell = table.TableCell(
+ valuetype="boolean",
+ booleanvalue="true" if col else "false",
+ )
+ elif isinstance(col, numbers.Number):
+ cell = table.TableCell(valuetype="float", value=col)
+ elif isinstance(col, dt.datetime):
+ cell = table.TableCell(
+ valuetype="date",
+ datevalue=col.strftime('%Y-%m-%dT%H:%M:%S'),
+ stylename=dts,
+ )
+ cell.addElement(text.P(text=col.strftime('%Y-%m-%d %H:%M:%S')))
+ elif isinstance(col, dt.date):
+ date_value = col.strftime('%Y-%m-%d')
+ cell = table.TableCell(valuetype="date", datevalue=date_value, stylename=ds)
+ cell.addElement(text.P(text=date_value))
+ elif isinstance(col, dt.time):
+ cell = table.TableCell(
+ valuetype="time",
+ timevalue=col.strftime('PT%HH%MM%SS'),
+ stylename=ts,
+ )
+ cell.addElement(text.P(text=col.strftime('%H:%M:%S')))
+ elif col is None:
+ cell = table.TableCell(valuetype="void")
+ else:
+ cell = table.TableCell(valuetype="string")
+ cell.addElement(text.P(text=str(col), stylename=style))
+ odf_row.addElement(cell)
+
+ @classmethod
+ def detect(cls, stream):
+ if isinstance(stream, bytes):
+ # load expects a file-like object.
+ stream = BytesIO(stream)
+ try:
+ opendocument.load(stream)
+ return True
+ except Exception:
+ return False
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_rst.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_rst.py
new file mode 100644
index 0000000000000000000000000000000000000000..f64e2622f2273c61c8381d6b3f1dc78ff901ceb4
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_rst.py
@@ -0,0 +1,269 @@
+""" Tablib - reStructuredText Support
+"""
+
+__lazy_modules__ = {"itertools", "statistics", "textwrap"}
+
+from itertools import zip_longest
+from statistics import median
+from textwrap import TextWrapper
+
+JUSTIFY_LEFT = 'left'
+JUSTIFY_CENTER = 'center'
+JUSTIFY_RIGHT = 'right'
+JUSTIFY_VALUES = (JUSTIFY_LEFT, JUSTIFY_CENTER, JUSTIFY_RIGHT)
+
+
+def to_str(value):
+ if isinstance(value, bytes):
+ return value.decode('utf-8')
+ return str(value)
+
+
+def _max_word_len(text):
+ """
+ Return the length of the longest word in `text`.
+
+ >>> _max_word_len('Python Module for Tabular Datasets')
+ 8
+ """
+ return max((len(word) for word in text.split()), default=0) if text else 0
+
+
+class ReSTFormat:
+ title = 'rst'
+ extensions = ('rst',)
+
+ MAX_TABLE_WIDTH = 80 # Roughly. It may be wider to avoid breaking words.
+
+ @classmethod
+ def _get_column_string_lengths(cls, dataset):
+ """
+ Returns a list of string lengths of each column, and a list of
+ maximum word lengths.
+ """
+ if dataset.headers:
+ column_lengths = [[len(h)] for h in dataset.headers]
+ word_lens = [_max_word_len(h) for h in dataset.headers]
+ else:
+ column_lengths = [[] for _ in range(dataset.width)]
+ word_lens = [0 for _ in range(dataset.width)]
+ for row in dataset.dict:
+ values = iter(row.values() if hasattr(row, 'values') else row)
+ for i, val in enumerate(values):
+ text = to_str(val)
+ column_lengths[i].append(len(text))
+ word_lens[i] = max(word_lens[i], _max_word_len(text))
+ return column_lengths, word_lens
+
+ @classmethod
+ def _row_to_lines(cls, values, widths, wrapper, sep='|', justify=JUSTIFY_LEFT):
+ """
+ Returns a table row of wrapped values as a list of lines
+ """
+ if justify not in JUSTIFY_VALUES:
+ raise ValueError('Value of "justify" must be one of "{}"'.format(
+ '", "'.join(JUSTIFY_VALUES)
+ ))
+
+ def just(text_, width_):
+ if justify == JUSTIFY_LEFT:
+ return text_.ljust(width_)
+ elif justify == JUSTIFY_CENTER:
+ return text_.center(width_)
+ else:
+ return text_.rjust(width_)
+ lpad = sep + ' ' if sep else ''
+ rpad = ' ' + sep if sep else ''
+ pad = ' ' + sep + ' '
+ cells = []
+ for value, width in zip(values, widths):
+ wrapper.width = width
+ text = to_str(value)
+ cell = wrapper.wrap(text)
+ cells.append(cell)
+ lines = zip_longest(*cells, fillvalue='')
+ lines = (
+ (just(cell_line, widths[i]) for i, cell_line in enumerate(line))
+ for line in lines
+ )
+ lines = [''.join((lpad, pad.join(line), rpad)) for line in lines]
+ return lines
+
+ @classmethod
+ def _get_column_widths(cls, dataset, max_table_width=MAX_TABLE_WIDTH, pad_len=3):
+ """
+ Returns a list of column widths proportional to the median length
+ of the text in their cells.
+ """
+ str_lens, word_lens = cls._get_column_string_lengths(dataset)
+ median_lens = [int(median(lens)) for lens in str_lens]
+ total = sum(median_lens)
+ if total > max_table_width - (pad_len * len(median_lens)):
+ column_widths = (max_table_width * lens // total for lens in median_lens)
+ else:
+ column_widths = (lens for lens in median_lens)
+ # Allow for separator and padding:
+ column_widths = (w - pad_len if w > pad_len else w for w in column_widths)
+ # Rather widen table than break words:
+ column_widths = [max(w, l) for w, l in zip(column_widths, word_lens)]
+ return column_widths
+
+ @classmethod
+ def export_set_as_simple_table(cls, dataset, column_widths=None):
+ """
+ Returns reStructuredText grid table representation of dataset.
+ """
+ lines = []
+ wrapper = TextWrapper()
+ if column_widths is None:
+ column_widths = cls._get_column_widths(dataset, pad_len=2)
+ border = ' '.join(['=' * w for w in column_widths])
+
+ lines.append(border)
+ if dataset.headers:
+ lines.extend(cls._row_to_lines(
+ dataset.headers,
+ column_widths,
+ wrapper,
+ sep='',
+ justify=JUSTIFY_CENTER,
+ ))
+ lines.append(border)
+ for row in dataset.dict:
+ values = iter(row.values() if hasattr(row, 'values') else row)
+ lines.extend(cls._row_to_lines(values, column_widths, wrapper, ''))
+ lines.append(border)
+ return '\n'.join(lines)
+
+ @classmethod
+ def export_set_as_grid_table(cls, dataset, column_widths=None):
+ """
+ Returns reStructuredText grid table representation of dataset.
+
+
+ >>> from tablib import Dataset
+ >>> from tablib.formats import registry
+ >>> bits = ((0, 0), (1, 0), (0, 1), (1, 1))
+ >>> data = Dataset()
+ >>> data.headers = ['A', 'B', 'A and B']
+ >>> for a, b in bits:
+ ... data.append([bool(a), bool(b), bool(a * b)])
+ >>> rst = registry.get_format('rst')
+ >>> print(rst.export_set(data, force_grid=True))
+ +-------+-------+-------+
+ | A | B | A and |
+ | | | B |
+ +=======+=======+=======+
+ | False | False | False |
+ +-------+-------+-------+
+ | True | False | False |
+ +-------+-------+-------+
+ | False | True | False |
+ +-------+-------+-------+
+ | True | True | True |
+ +-------+-------+-------+
+
+ """
+ lines = []
+ wrapper = TextWrapper()
+ if column_widths is None:
+ column_widths = cls._get_column_widths(dataset)
+ header_sep = '+=' + '=+='.join(['=' * w for w in column_widths]) + '=+'
+ row_sep = '+-' + '-+-'.join(['-' * w for w in column_widths]) + '-+'
+
+ lines.append(row_sep)
+
+ if dataset.headers:
+ lines.extend(cls._row_to_lines(
+ dataset.headers,
+ column_widths,
+ wrapper,
+ justify=JUSTIFY_CENTER,
+ ))
+ lines.append(header_sep)
+ for row in dataset.dict:
+ values = iter(row.values() if hasattr(row, 'values') else row)
+ lines.extend(cls._row_to_lines(values, column_widths, wrapper))
+ lines.append(row_sep)
+ return '\n'.join(lines)
+
+ @classmethod
+ def _use_simple_table(cls, head0, col0, width0):
+ """
+ Use a simple table if the text in the first column is never wrapped
+
+
+ >>> from tablib.formats import registry
+ >>> rst = registry.get_format('rst')
+ >>> rst._use_simple_table('menu', ['egg', 'bacon'], 10)
+ True
+ >>> rst._use_simple_table(None, ['lobster thermidor', 'spam'], 10)
+ False
+
+ """
+ if head0 is not None:
+ head0 = to_str(head0)
+ if len(head0) > width0:
+ return False
+ for cell in col0:
+ cell = to_str(cell)
+ if len(cell) > width0:
+ return False
+ return True
+
+ @classmethod
+ def export_set(cls, dataset, **kwargs):
+ """
+ Returns reStructuredText table representation of dataset.
+
+ Returns a simple table if the text in the first column is never
+ wrapped, otherwise returns a grid table.
+
+
+ >>> from tablib import Dataset
+ >>> bits = ((0, 0), (1, 0), (0, 1), (1, 1))
+ >>> data = Dataset()
+ >>> data.headers = ['A', 'B', 'A and B']
+ >>> for a, b in bits:
+ ... data.append([bool(a), bool(b), bool(a * b)])
+ >>> table = data.rst
+ >>> table.split('\\n') == [
+ ... '===== ===== =====',
+ ... ' A B A and',
+ ... ' B ',
+ ... '===== ===== =====',
+ ... 'False False False',
+ ... 'True False False',
+ ... 'False True False',
+ ... 'True True True ',
+ ... '===== ===== =====',
+ ... ]
+ True
+
+ """
+ if not dataset.dict:
+ return ''
+ force_grid = kwargs.get('force_grid', False)
+ max_table_width = kwargs.get('max_table_width', cls.MAX_TABLE_WIDTH)
+ column_widths = cls._get_column_widths(dataset, max_table_width)
+
+ use_simple_table = cls._use_simple_table(
+ dataset.headers[0] if dataset.headers else None,
+ dataset.get_col(0),
+ column_widths[0],
+ )
+ if use_simple_table and not force_grid:
+ return cls.export_set_as_simple_table(dataset, column_widths)
+ else:
+ return cls.export_set_as_grid_table(dataset, column_widths)
+
+ @classmethod
+ def export_book(cls, databook):
+ """
+ reStructuredText representation of a Databook.
+
+ Tables are separated by a blank line. All tables use the grid
+ format.
+ """
+ return '\n\n'.join(cls.export_set(dataset, force_grid=True)
+ for dataset in databook._datasets)
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_sql.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_sql.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4ec8f9e9dde9f9fd9935f7c92bb9107baf31411
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_sql.py
@@ -0,0 +1,77 @@
+"""Tablib - SQL INSERT Export Support."""
+
+__lazy_modules__ = {
+ "datetime",
+ "decimal",
+ "tablib.exceptions",
+}
+
+import datetime
+import decimal
+
+from ..exceptions import UnsupportedFormat
+
+
+class SQLFormat:
+ """Export Dataset rows as SQL INSERT statements."""
+ title = 'sql'
+ extensions = ('sql',)
+
+ @staticmethod
+ def _render_literal(value):
+ """Render a Python value as an SQL literal."""
+ if value is None:
+ return 'NULL'
+ if isinstance(value, bool):
+ return 'TRUE' if value else 'FALSE'
+ if isinstance(value, (int, decimal.Decimal)):
+ return str(value)
+ if isinstance(value, float):
+ # Represent finite floats; non-finite as NULL
+ try:
+ if value == value and value not in (float('inf'), -float('inf')):
+ return repr(value)
+ except Exception:
+ pass
+ return 'NULL'
+ if isinstance(value, datetime.datetime):
+ # ANSI SQL timestamp literal
+ return f"TIMESTAMP '{value.isoformat(sep=' ')}'"
+ if isinstance(value, datetime.date):
+ # ANSI SQL date literal
+ return f"DATE '{value.isoformat()}'"
+ # Fallback for strings and others
+ text = str(value).replace("'", "''")
+ return f"'{text}'"
+
+ @classmethod
+ def export_set(cls, dataset, table=None, columns=None, commit=False):
+ """
+ Return SQL INSERT statements for Dataset rows.
+ :param table: optional table name; defaults to dataset.title or 'data'
+ """
+ tbl = table or getattr(dataset, 'title', None) or 'export_table'
+ tbl_ident = str(tbl)
+ columns_headers = (','.join(
+ columns if columns is not None else
+ dataset.headers if dataset.headers is not None else []
+ )
+ )
+ columns_headers = f' ({columns_headers})' if columns_headers else ''
+ statements = []
+ for row in dataset._data:
+ values = ', '.join(cls._render_literal(v) for v in row)
+ statements.append(
+ f'INSERT INTO {tbl_ident}{columns_headers} VALUES ({values});'
+ )
+ return '\n'.join(statements) + '\n' + ('COMMIT;\n' if commit else '')
+
+ @classmethod
+ def import_set(cls, dataset, in_stream, **kwargs):
+ """Importing SQL is not supported."""
+ raise UnsupportedFormat('SQL import is not supported.')
+
+ @classmethod
+ def detect(cls, stream):
+ """Always return False: no autodetect for SQL."""
+ return False
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_tsv.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_tsv.py
new file mode 100644
index 0000000000000000000000000000000000000000..928246c8e449edb5a54a194e37dde7b929b0e6f4
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_tsv.py
@@ -0,0 +1,11 @@
+""" Tablib - TSV (Tab Separated Values) Support.
+"""
+
+from ._csv import CSVFormat
+
+
+class TSVFormat(CSVFormat):
+ title = 'tsv'
+ extensions = ('tsv',)
+
+ DEFAULT_DELIMITER = '\t'
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_xls.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_xls.py
new file mode 100644
index 0000000000000000000000000000000000000000..02c1b9be692c02e5ac5d9e3644722f9b78a35324
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_xls.py
@@ -0,0 +1,183 @@
+""" Tablib - XLS Support.
+"""
+
+__lazy_modules__ = {"datetime", "io", "xlrd", "xlrd.xldate"}
+
+import datetime
+import re
+from io import BytesIO
+
+import xlrd
+import xlwt
+from xlrd.xldate import xldate_as_datetime
+
+import tablib
+
+# special styles
+wrap = xlwt.easyxf("alignment: wrap on")
+bold = xlwt.easyxf("font: bold on")
+datetime_style = xlwt.easyxf(num_format_str='M/D/YY h:mm')
+date_style = xlwt.easyxf(num_format_str='M/D/YY')
+time_style = xlwt.easyxf(num_format_str='h:mm:ss')
+
+INVALID_TITLE_REGEX = re.compile(r'[\\*?:/\[\]]')
+
+
+def safe_xls_sheet_title(s, replace="-"):
+ return re.sub(INVALID_TITLE_REGEX, replace, s)[:31]
+
+
+class XLSFormat:
+ title = 'xls'
+ extensions = ('xls',)
+
+ @classmethod
+ def detect(cls, stream):
+ """Returns True if given stream is a readable excel file."""
+ try:
+ xlrd.open_workbook(file_contents=stream)
+ return True
+ except Exception:
+ pass
+ try:
+ xlrd.open_workbook(file_contents=stream.read())
+ return True
+ except Exception:
+ pass
+ try:
+ xlrd.open_workbook(filename=stream)
+ return True
+ except Exception:
+ return False
+
+ @classmethod
+ def export_set(cls, dataset, invalid_char_subst="-"):
+ """Returns XLS representation of Dataset.
+
+ If ``dataset.title`` contains characters which are
+ considered invalid for an XLSX/XLS file sheet name
+ (https://web.archive.org/web/20230323081941/https://www.excelcodex.com/2012/06/worksheets-naming-conventions/),
+ they will be replaced with ``invalid_char_subst``.
+
+ """
+
+ wb = xlwt.Workbook(encoding='utf8')
+ ws = wb.add_sheet(
+ safe_xls_sheet_title(dataset.title, invalid_char_subst)
+ if dataset.title
+ else 'Tablib Dataset'
+ )
+
+ cls.dset_sheet(dataset, ws)
+
+ stream = BytesIO()
+ wb.save(stream)
+ return stream.getvalue()
+
+ @classmethod
+ def export_book(cls, databook, invalid_char_subst="-"):
+ """Returns XLS representation of DataBook."""
+
+ wb = xlwt.Workbook(encoding='utf8')
+
+ for i, dset in enumerate(databook._datasets):
+ ws = wb.add_sheet(safe_xls_sheet_title(
+ dset.title, invalid_char_subst)
+ if dset.title else f"Sheet{i}"
+ )
+
+ cls.dset_sheet(dset, ws)
+
+ stream = BytesIO()
+ wb.save(stream)
+ return stream.getvalue()
+
+ @classmethod
+ def import_set(cls, dset, in_stream, headers=True, skip_lines=0):
+ """Returns databook from XLS stream."""
+
+ dset.wipe()
+
+ xls_book = xlrd.open_workbook(file_contents=in_stream.read())
+ sheet = xls_book.sheet_by_index(0)
+
+ dset.title = sheet.name
+
+ def cell_value(value, type_):
+ if type_ == xlrd.XL_CELL_ERROR:
+ return xlrd.error_text_from_code[value]
+ elif type_ == xlrd.XL_CELL_DATE:
+ return xldate_as_datetime(value, xls_book.datemode)
+ return value
+
+ for i in range(sheet.nrows):
+ if i < skip_lines:
+ continue
+ if i == skip_lines and headers:
+ dset.headers = sheet.row_values(i)
+ else:
+ dset.append([
+ cell_value(val, typ)
+ for val, typ in zip(sheet.row_values(i), sheet.row_types(i))
+ ])
+
+ @classmethod
+ def import_book(cls, dbook, in_stream, headers=True):
+ """Returns databook from XLS stream."""
+
+ dbook.wipe()
+
+ xls_book = xlrd.open_workbook(file_contents=in_stream.read())
+
+ for sheet in xls_book.sheets():
+ data = tablib.Dataset()
+ data.title = sheet.name
+
+ for i in range(sheet.nrows):
+ if i == 0 and headers:
+ data.headers = sheet.row_values(0)
+ else:
+ data.append(sheet.row_values(i))
+
+ dbook.add_sheet(data)
+
+ @classmethod
+ def dset_sheet(cls, dataset, ws):
+ """Completes given worksheet from given Dataset."""
+ _package = dataset._package(dicts=False)
+
+ for i, sep in enumerate(dataset._separators):
+ _offset = i
+ _package.insert((sep[0] + _offset), (sep[1],))
+
+ for i, row in enumerate(_package):
+ for j, col in enumerate(row):
+
+ # bold headers
+ if (i == 0) and dataset.headers:
+ ws.write(i, j, col, bold)
+
+ # frozen header row
+ ws.panes_frozen = True
+ ws.horz_split_pos = 1
+
+ # bold separators
+ elif len(row) < dataset.width:
+ ws.write(i, j, col, bold)
+
+ # format date types
+ elif isinstance(col, datetime.datetime):
+ ws.write(i, j, col, datetime_style)
+ elif isinstance(col, datetime.date):
+ ws.write(i, j, col, date_style)
+ elif isinstance(col, datetime.time):
+ ws.write(i, j, col, time_style)
+ # wrap the rest
+ else:
+ try:
+ if '\n' in col:
+ ws.write(i, j, col, wrap)
+ else:
+ ws.write(i, j, col)
+ except TypeError:
+ ws.write(i, j, col)
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_xlsx.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_xlsx.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3ad88bd77cfba4a3ae6b996ca78ed7a3c20c48e
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_xlsx.py
@@ -0,0 +1,218 @@
+""" Tablib - XLSX Support.
+"""
+
+__lazy_modules__ = {
+ "io",
+ "openpyxl",
+ "openpyxl.reader",
+ "openpyxl.reader.excel",
+ "openpyxl.styles",
+ "openpyxl.utils",
+ "openpyxl.workbook",
+}
+
+import re
+from io import BytesIO
+
+from openpyxl.reader.excel import ExcelReader, load_workbook
+from openpyxl.styles import Alignment, Font
+from openpyxl.utils import get_column_letter
+from openpyxl.workbook import Workbook
+
+import tablib
+
+INVALID_TITLE_REGEX = re.compile(r'[\\*?:/\[\]]')
+
+
+def safe_xlsx_sheet_title(s, replace="-"):
+ return re.sub(INVALID_TITLE_REGEX, replace, s)[:31]
+
+
+class XLSXFormat:
+ title = 'xlsx'
+ extensions = ('xlsx',)
+
+ @classmethod
+ def detect(cls, stream):
+ """Returns True if given stream is a readable excel file."""
+ try:
+ # No need to fully load the file, it should be enough to be able to
+ # read the manifest.
+ reader = ExcelReader(stream, read_only=False)
+ reader.read_manifest()
+ return True
+ except Exception:
+ return False
+
+ @classmethod
+ def export_set(cls, dataset, freeze_panes=True, invalid_char_subst="-",
+ escape=False, column_width="adaptive"):
+ """Returns XLSX representation of Dataset.
+
+ If ``freeze_panes`` is True, Export will freeze panes only after first line.
+
+ If ``dataset.title`` contains characters which are
+ considered invalid for an XLSX file sheet name
+ (https://web.archive.org/web/20230323081941/https://www.excelcodex.com/2012/06/worksheets-naming-conventions/),
+ they will be replaced with ``invalid_char_subst``.
+
+ If ``escape`` is True, formulae will have the leading '=' character removed.
+ This is a security measure to prevent formulae from executing by default
+ in exported XLSX files.
+
+ If ``column_width`` is set to "adaptive", the column width will be set to the maximum
+ width of the content in each column. If it is set to an integer, the column width will be
+ set to that integer value. If it is set to None, the column width will be set as the
+ default openpyxl.Worksheet width value.
+
+ """
+ wb = Workbook()
+ ws = wb.worksheets[0]
+
+ ws.title = (
+ safe_xlsx_sheet_title(dataset.title, invalid_char_subst)
+ if dataset.title else 'Tablib Dataset'
+ )
+
+ cls.dset_sheet(dataset, ws, freeze_panes=freeze_panes, escape=escape)
+
+ cls._adapt_column_width(ws, column_width)
+
+ stream = BytesIO()
+ wb.save(stream)
+ return stream.getvalue()
+
+ @classmethod
+ def export_book(cls, databook, freeze_panes=True, invalid_char_subst="-",
+ escape=False, column_width=None):
+ """Returns XLSX representation of DataBook.
+ See export_set().
+ """
+
+ wb = Workbook()
+ for sheet in wb.worksheets:
+ wb.remove(sheet)
+ for i, dset in enumerate(databook._datasets):
+ ws = wb.create_sheet()
+ ws.title = (
+ safe_xlsx_sheet_title(dset.title, invalid_char_subst)
+ if dset.title else f"Sheet{i}"
+ )
+
+ cls.dset_sheet(dset, ws, freeze_panes=freeze_panes, escape=escape)
+
+ cls._adapt_column_width(ws, column_width)
+
+ stream = BytesIO()
+ wb.save(stream)
+ return stream.getvalue()
+
+ @classmethod
+ def import_sheet(cls, dset, sheet, headers=True, skip_lines=0):
+ """Populates dataset with sheet."""
+
+ dset.title = sheet.title
+
+ for i, row in enumerate(sheet.rows):
+ if i < skip_lines:
+ continue
+ row_vals = [c.value for c in row]
+ if i == skip_lines and headers:
+ dset.headers = row_vals
+ else:
+ if i > skip_lines and len(row_vals) < dset.width:
+ row_vals += [''] * (dset.width - len(row_vals))
+ dset.append(row_vals)
+
+ @classmethod
+ def import_set(cls, dset, in_stream, headers=True, read_only=True, skip_lines=0):
+ """Returns databook from XLS stream."""
+
+ dset.wipe()
+
+ xls_book = load_workbook(in_stream, read_only=read_only, data_only=True)
+ sheet = xls_book.active
+ cls.import_sheet(dset, sheet, headers, skip_lines)
+
+ @classmethod
+ def import_book(cls, dbook, in_stream, headers=True, read_only=True):
+ """Returns databook from XLS stream."""
+
+ dbook.wipe()
+
+ xls_book = load_workbook(in_stream, read_only=read_only, data_only=True)
+
+ for sheet in xls_book.worksheets:
+ dset = tablib.Dataset()
+ cls.import_sheet(dset, sheet, headers)
+ dbook.add_sheet(dset)
+
+ @classmethod
+ def dset_sheet(cls, dataset, ws, freeze_panes=True, escape=False):
+ """Completes given worksheet from given Dataset."""
+ _package = dataset._package(dicts=False)
+
+ for i, sep in enumerate(dataset._separators):
+ _offset = i
+ _package.insert((sep[0] + _offset), (sep[1],))
+
+ bold = Font(bold=True)
+ wrap_text = Alignment(wrap_text=True)
+
+ for i, row in enumerate(_package):
+ row_number = i + 1
+ for j, col in enumerate(row):
+ col_idx = get_column_letter(j + 1)
+ cell = ws[f'{col_idx}{row_number}']
+
+ # bold headers
+ if (row_number == 1) and dataset.headers:
+ cell.font = bold
+ if freeze_panes:
+ # Export Freeze only after first Line
+ ws.freeze_panes = 'A2'
+
+ # bold separators
+ elif len(row) < dataset.width:
+ cell.font = bold
+
+ # wrap the rest
+ else:
+ if '\n' in str(col):
+ cell.alignment = wrap_text
+
+ try:
+ cell.value = col
+ except ValueError:
+ cell.value = str(col)
+
+ if escape and cell.data_type == 'f' and cell.value.startswith('='):
+ cell.value = cell.value[1:]
+
+ @classmethod
+ def _adapt_column_width(cls, worksheet, width):
+ if isinstance(width, str) and width != "adaptive":
+ msg = (
+ f"Invalid value for column_width: {width}. "
+ "Must be 'adaptive' or an integer."
+ )
+ raise ValueError(msg)
+
+ if width is None:
+ return
+
+ column_widths = []
+ if width == "adaptive":
+ for row in worksheet.values:
+ for i, cell in enumerate(row):
+ cell_width = len(str(cell))
+ if len(column_widths) > i:
+ if cell_width > column_widths[i]:
+ column_widths[i] = cell_width
+ else:
+ column_widths.append(cell_width)
+ else:
+ column_widths = [width] * worksheet.max_column
+
+ for i, column_width in enumerate(column_widths, 1): # start at 1
+ worksheet.column_dimensions[get_column_letter(i)].width = column_width
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_yaml.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_yaml.py
new file mode 100644
index 0000000000000000000000000000000000000000..db6e4c4080f06dbcce073c4f6ba7776c26cb5aa6
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/formats/_yaml.py
@@ -0,0 +1,65 @@
+""" Tablib - YAML Support.
+"""
+
+__lazy_modules__ = {"yaml"}
+
+import yaml
+
+import tablib
+
+
+class YAMLFormat:
+ title = 'yaml'
+ extensions = ('yaml', 'yml')
+
+ @classmethod
+ def export_set(cls, dataset):
+ """Returns YAML representation of Dataset."""
+ return yaml.safe_dump(
+ dataset._package(),
+ default_flow_style=None,
+ allow_unicode=True,
+ sort_keys=False,
+ )
+
+ @classmethod
+ def export_book(cls, databook):
+ """Returns YAML representation of Databook."""
+ return yaml.safe_dump(
+ databook._package(),
+ default_flow_style=None,
+ allow_unicode=True,
+ sort_keys=False,
+ )
+
+ @classmethod
+ def import_set(cls, dset, in_stream):
+ """Returns dataset from YAML stream."""
+
+ dset.wipe()
+ dset.dict = yaml.safe_load(in_stream)
+
+ @classmethod
+ def import_book(cls, dbook, in_stream):
+ """Returns databook from YAML stream."""
+
+ dbook.wipe()
+
+ for sheet in yaml.safe_load(in_stream):
+ data = tablib.Dataset()
+ data.title = sheet['title']
+ data.dict = sheet['data']
+ dbook.add_sheet(data)
+
+ @classmethod
+ def detect(cls, stream):
+ """Returns True if given stream is valid YAML."""
+ try:
+ _yaml = yaml.safe_load(stream)
+ if isinstance(_yaml, (list, tuple, dict)):
+ return True
+ else:
+ return False
+ except (yaml.parser.ParserError, yaml.reader.ReaderError,
+ yaml.scanner.ScannerError):
+ return False
diff --git a/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/utils.py b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3fbafd9af8407b42c0f22bc7816243736173f33
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/environment/source/src/tablib/utils.py
@@ -0,0 +1,15 @@
+__lazy_modules__ = {"io"}
+
+from io import BytesIO, StringIO
+
+
+def normalize_input(stream):
+ """
+ Accept either a str/bytes stream or a file-like object and always return a
+ file-like object.
+ """
+ if isinstance(stream, str):
+ return StringIO(stream, newline='')
+ elif isinstance(stream, bytes):
+ return BytesIO(stream)
+ return stream
diff --git a/tasks/tasksmith-b6d969373e1e/instruction.md b/tasks/tasksmith-b6d969373e1e/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..0950d653a6b687582cbc1537116acd1e6de7f3bd
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/instruction.md
@@ -0,0 +1,8 @@
+When loading an XLS file as a `tablib.Databook` (via `Databook().load(fh, 'xls')`), cell values must be converted in the same way as when loading via `tablib.Dataset`:
+
+- Excel date serials must become `datetime.datetime` objects. For example, loading `dates.xls` as a Databook and accessing the `birth_date` column must yield `datetime.datetime(2015, 4, 12, 0, 0)`, not a raw float like `42106.0`.
+- Excel error codes must become their string representations. For example, loading `errors.xls` as a Databook must yield `'#N/A'` for N/A cells, not the raw integer `42`. All four error columns (`#DIV/0!`, `#NAME?`, `#N/A`, `#N/A`) must be represented as strings.
+
+This parity must hold for every sheet in a multi-sheet workbook. The Dataset import path (`Dataset().load(fh, 'xls')`) must continue to work as before.
+
+Work in `/workspace`. Submit your fix in Python source files under `src/tablib`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files.
diff --git a/tasks/tasksmith-b6d969373e1e/solution/reference/src/tablib/formats/_xls.py b/tasks/tasksmith-b6d969373e1e/solution/reference/src/tablib/formats/_xls.py
new file mode 100644
index 0000000000000000000000000000000000000000..060d0742fe2dfb3fe82269ccff812f7f845ede41
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/solution/reference/src/tablib/formats/_xls.py
@@ -0,0 +1,184 @@
+""" Tablib - XLS Support.
+"""
+
+__lazy_modules__ = {"datetime", "io", "xlrd", "xlrd.xldate"}
+
+import datetime
+import re
+from io import BytesIO
+
+import xlrd
+import xlwt
+from xlrd.xldate import xldate_as_datetime
+
+import tablib
+
+# special styles
+wrap = xlwt.easyxf("alignment: wrap on")
+bold = xlwt.easyxf("font: bold on")
+datetime_style = xlwt.easyxf(num_format_str='M/D/YY h:mm')
+date_style = xlwt.easyxf(num_format_str='M/D/YY')
+time_style = xlwt.easyxf(num_format_str='h:mm:ss')
+
+INVALID_TITLE_REGEX = re.compile(r'[\\*?:/\[\]]')
+
+
+def safe_xls_sheet_title(s, replace="-"):
+ return re.sub(INVALID_TITLE_REGEX, replace, s)[:31]
+
+
+class XLSFormat:
+ title = 'xls'
+ extensions = ('xls',)
+
+ @classmethod
+ def detect(cls, stream):
+ """Returns True if given stream is a readable excel file."""
+ try:
+ xlrd.open_workbook(file_contents=stream)
+ return True
+ except Exception:
+ pass
+ try:
+ xlrd.open_workbook(file_contents=stream.read())
+ return True
+ except Exception:
+ pass
+ try:
+ xlrd.open_workbook(filename=stream)
+ return True
+ except Exception:
+ return False
+
+ @classmethod
+ def export_set(cls, dataset, invalid_char_subst="-"):
+ """Returns XLS representation of Dataset.
+
+ If ``dataset.title`` contains characters which are
+ considered invalid for an XLSX/XLS file sheet name
+ (https://web.archive.org/web/20230323081941/https://www.excelcodex.com/2012/06/worksheets-naming-conventions/),
+ they will be replaced with ``invalid_char_subst``.
+
+ """
+
+ wb = xlwt.Workbook(encoding='utf8')
+ ws = wb.add_sheet(
+ safe_xls_sheet_title(dataset.title, invalid_char_subst)
+ if dataset.title
+ else 'Tablib Dataset'
+ )
+
+ cls.dset_sheet(dataset, ws)
+
+ stream = BytesIO()
+ wb.save(stream)
+ return stream.getvalue()
+
+ @classmethod
+ def export_book(cls, databook, invalid_char_subst="-"):
+ """Returns XLS representation of DataBook."""
+
+ wb = xlwt.Workbook(encoding='utf8')
+
+ for i, dset in enumerate(databook._datasets):
+ ws = wb.add_sheet(safe_xls_sheet_title(
+ dset.title, invalid_char_subst)
+ if dset.title else f"Sheet{i}"
+ )
+
+ cls.dset_sheet(dset, ws)
+
+ stream = BytesIO()
+ wb.save(stream)
+ return stream.getvalue()
+
+ @classmethod
+ def read_cell(cls, value, type_, datemode):
+ """Returns the Python value of a cell, based on its xlrd type."""
+ if type_ == xlrd.XL_CELL_ERROR:
+ return xlrd.error_text_from_code[value]
+ elif type_ == xlrd.XL_CELL_DATE:
+ return xldate_as_datetime(value, datemode)
+ return value
+
+ @classmethod
+ def import_sheet(cls, dset, sheet, datemode, headers=True, skip_lines=0):
+ """Populates dataset with sheet."""
+
+ dset.title = sheet.name
+
+ for i in range(sheet.nrows):
+ if i < skip_lines:
+ continue
+ if i == skip_lines and headers:
+ dset.headers = sheet.row_values(i)
+ else:
+ dset.append([
+ cls.read_cell(val, typ, datemode)
+ for val, typ in zip(sheet.row_values(i), sheet.row_types(i))
+ ])
+
+ @classmethod
+ def import_set(cls, dset, in_stream, headers=True, skip_lines=0):
+ """Returns databook from XLS stream."""
+
+ dset.wipe()
+
+ xls_book = xlrd.open_workbook(file_contents=in_stream.read())
+ sheet = xls_book.sheet_by_index(0)
+
+ cls.import_sheet(dset, sheet, xls_book.datemode, headers, skip_lines)
+
+ @classmethod
+ def import_book(cls, dbook, in_stream, headers=True):
+ """Returns databook from XLS stream."""
+
+ dbook.wipe()
+
+ xls_book = xlrd.open_workbook(file_contents=in_stream.read())
+
+ for sheet in xls_book.sheets():
+ dset = tablib.Dataset()
+ cls.import_sheet(dset, sheet, xls_book.datemode, headers)
+ dbook.add_sheet(dset)
+
+ @classmethod
+ def dset_sheet(cls, dataset, ws):
+ """Completes given worksheet from given Dataset."""
+ _package = dataset._package(dicts=False)
+
+ for i, sep in enumerate(dataset._separators):
+ _offset = i
+ _package.insert((sep[0] + _offset), (sep[1],))
+
+ for i, row in enumerate(_package):
+ for j, col in enumerate(row):
+
+ # bold headers
+ if (i == 0) and dataset.headers:
+ ws.write(i, j, col, bold)
+
+ # frozen header row
+ ws.panes_frozen = True
+ ws.horz_split_pos = 1
+
+ # bold separators
+ elif len(row) < dataset.width:
+ ws.write(i, j, col, bold)
+
+ # format date types
+ elif isinstance(col, datetime.datetime):
+ ws.write(i, j, col, datetime_style)
+ elif isinstance(col, datetime.date):
+ ws.write(i, j, col, date_style)
+ elif isinstance(col, datetime.time):
+ ws.write(i, j, col, time_style)
+ # wrap the rest
+ else:
+ try:
+ if '\n' in col:
+ ws.write(i, j, col, wrap)
+ else:
+ ws.write(i, j, col)
+ except TypeError:
+ ws.write(i, j, col)
diff --git a/tasks/tasksmith-b6d969373e1e/solution/solve.sh b/tasks/tasksmith-b6d969373e1e/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..faf607a83ca01e0de43e5ccbc146b0113570baa4
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/solution/solve.sh
@@ -0,0 +1,4 @@
+#!/bin/sh
+set -eu
+mkdir -p -- /workspace/src/tablib/formats
+cp /solution/reference/src/tablib/formats/_xls.py /workspace/src/tablib/formats/_xls.py
diff --git a/tasks/tasksmith-b6d969373e1e/task.toml b/tasks/tasksmith-b6d969373e1e/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..1392331aa6462a5ccbcb4d5fae455ecd85158cc9
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/task.toml
@@ -0,0 +1,257 @@
+schema_version = "1.3"
+
+[task]
+name = "repo2rlenv/tasksmith-b6d969373e1e"
+
+[metadata.repo2env]
+recipe = "tasksmith"
+recipe_version = "1"
+source_url = "https://github.com/jazzband/tablib/pull/665"
+source_head = "4189fab2a7e7d4a15b2e681ab69188a4329e252e"
+source_base = "234f434a56cab7540230888112808f6b89fbf7a0"
+workspace_strategy = "head_minus_source_patch"
+source_diff_sha256 = "c3fdf8b57aa62fe65f6a29e0a37f64c1db0b78f47eedbdd3f7907be9f3dc43bf"
+acceptance_profile = "practical-generation-v1"
+upstream_test_policy = "retain"
+reward_kinds = [
+ "test_execution",
+]
+quality_status = "exported"
+fail_to_pass_count = 2
+pass_to_pass_count = 7
+tracked_files = [
+ "environment/Dockerfile",
+ "environment/source/.coveragerc",
+ "environment/source/.gitignore",
+ "environment/source/AUTHORS",
+ "environment/source/Dockerfile",
+ "environment/source/LICENSE",
+ "environment/source/README.md",
+ "environment/source/pyproject.toml",
+ "environment/source/pytest.ini",
+ "environment/source/src/tablib.egg-info/PKG-INFO",
+ "environment/source/src/tablib.egg-info/SOURCES.txt",
+ "environment/source/src/tablib.egg-info/dependency_links.txt",
+ "environment/source/src/tablib.egg-info/requires.txt",
+ "environment/source/src/tablib.egg-info/top_level.txt",
+ "environment/source/src/tablib/__init__.py",
+ "environment/source/src/tablib/_vendor/__init__.py",
+ "environment/source/src/tablib/_vendor/dbfpy/__init__.py",
+ "environment/source/src/tablib/_vendor/dbfpy/dbf.py",
+ "environment/source/src/tablib/_vendor/dbfpy/dbfnew.py",
+ "environment/source/src/tablib/_vendor/dbfpy/fields.py",
+ "environment/source/src/tablib/_vendor/dbfpy/header.py",
+ "environment/source/src/tablib/_vendor/dbfpy/record.py",
+ "environment/source/src/tablib/_vendor/dbfpy/utils.py",
+ "environment/source/src/tablib/_version.py",
+ "environment/source/src/tablib/core.py",
+ "environment/source/src/tablib/exceptions.py",
+ "environment/source/src/tablib/formats/__init__.py",
+ "environment/source/src/tablib/formats/_cli.py",
+ "environment/source/src/tablib/formats/_csv.py",
+ "environment/source/src/tablib/formats/_dbf.py",
+ "environment/source/src/tablib/formats/_df.py",
+ "environment/source/src/tablib/formats/_html.py",
+ "environment/source/src/tablib/formats/_jira.py",
+ "environment/source/src/tablib/formats/_json.py",
+ "environment/source/src/tablib/formats/_latex.py",
+ "environment/source/src/tablib/formats/_ods.py",
+ "environment/source/src/tablib/formats/_rst.py",
+ "environment/source/src/tablib/formats/_sql.py",
+ "environment/source/src/tablib/formats/_tsv.py",
+ "environment/source/src/tablib/formats/_xls.py",
+ "environment/source/src/tablib/formats/_xlsx.py",
+ "environment/source/src/tablib/formats/_yaml.py",
+ "environment/source/src/tablib/utils.py",
+ "solution/reference/src/tablib/formats/_xls.py",
+ "solution/solve.sh",
+ "tests/Dockerfile",
+ "tests/contract.json",
+ "tests/grade.py",
+ "tests/source/.coveragerc",
+ "tests/source/.github/CONTRIBUTING.md",
+ "tests/source/.github/release-drafter.yml",
+ "tests/source/.github/release.yml",
+ "tests/source/.github/workflows/docs-lint.yml",
+ "tests/source/.github/workflows/release-drafter.yml",
+ "tests/source/.github/workflows/release.yml",
+ "tests/source/.github/workflows/require-pr-label.yml",
+ "tests/source/.github/workflows/test.yml",
+ "tests/source/.gitignore",
+ "tests/source/.pre-commit-config.yaml",
+ "tests/source/.readthedocs.yaml",
+ "tests/source/AUTHORS",
+ "tests/source/CODE_OF_CONDUCT.md",
+ "tests/source/Dockerfile",
+ "tests/source/HISTORY.md",
+ "tests/source/LICENSE",
+ "tests/source/README.md",
+ "tests/source/RELEASING.md",
+ "tests/source/docs/Makefile",
+ "tests/source/docs/__init__.py",
+ "tests/source/docs/_templates/sidebarintro.html",
+ "tests/source/docs/_templates/sidebarlogo.html",
+ "tests/source/docs/api.rst",
+ "tests/source/docs/conf.py",
+ "tests/source/docs/development.rst",
+ "tests/source/docs/formats.rst",
+ "tests/source/docs/index.rst",
+ "tests/source/docs/install.rst",
+ "tests/source/docs/intro.rst",
+ "tests/source/docs/krstyle.sty",
+ "tests/source/docs/requirements.txt",
+ "tests/source/docs/tutorial.rst",
+ "tests/source/pyproject.toml",
+ "tests/source/pytest.ini",
+ "tests/source/src/tablib.egg-info/PKG-INFO",
+ "tests/source/src/tablib.egg-info/SOURCES.txt",
+ "tests/source/src/tablib.egg-info/dependency_links.txt",
+ "tests/source/src/tablib.egg-info/requires.txt",
+ "tests/source/src/tablib.egg-info/top_level.txt",
+ "tests/source/src/tablib/__init__.py",
+ "tests/source/src/tablib/_vendor/__init__.py",
+ "tests/source/src/tablib/_vendor/dbfpy/__init__.py",
+ "tests/source/src/tablib/_vendor/dbfpy/dbf.py",
+ "tests/source/src/tablib/_vendor/dbfpy/dbfnew.py",
+ "tests/source/src/tablib/_vendor/dbfpy/fields.py",
+ "tests/source/src/tablib/_vendor/dbfpy/header.py",
+ "tests/source/src/tablib/_vendor/dbfpy/record.py",
+ "tests/source/src/tablib/_vendor/dbfpy/utils.py",
+ "tests/source/src/tablib/_version.py",
+ "tests/source/src/tablib/core.py",
+ "tests/source/src/tablib/exceptions.py",
+ "tests/source/src/tablib/formats/__init__.py",
+ "tests/source/src/tablib/formats/_cli.py",
+ "tests/source/src/tablib/formats/_csv.py",
+ "tests/source/src/tablib/formats/_dbf.py",
+ "tests/source/src/tablib/formats/_df.py",
+ "tests/source/src/tablib/formats/_html.py",
+ "tests/source/src/tablib/formats/_jira.py",
+ "tests/source/src/tablib/formats/_json.py",
+ "tests/source/src/tablib/formats/_latex.py",
+ "tests/source/src/tablib/formats/_ods.py",
+ "tests/source/src/tablib/formats/_rst.py",
+ "tests/source/src/tablib/formats/_sql.py",
+ "tests/source/src/tablib/formats/_tsv.py",
+ "tests/source/src/tablib/formats/_xls.py",
+ "tests/source/src/tablib/formats/_xlsx.py",
+ "tests/source/src/tablib/formats/_yaml.py",
+ "tests/source/src/tablib/utils.py",
+ "tests/source/tests/files/bad_dimensions.xlsx",
+ "tests/source/tests/files/book.ods",
+ "tests/source/tests/files/dates.xls",
+ "tests/source/tests/files/errors.xls",
+ "tests/source/tests/files/founders.xlsx",
+ "tests/source/tests/files/issue_524.yaml",
+ "tests/source/tests/files/ragged.ods",
+ "tests/source/tests/files/ragged.xlsx",
+ "tests/source/tests/files/unknown_value_type.ods",
+ "tests/source/tests/files/xlsx_cell_values.xlsx",
+ "tests/source/tests/requirements.txt",
+ "tests/source/tests/test_tablib.py",
+ "tests/source/tests/test_tablib_dbfpy_packages_fields.py",
+ "tests/source/tests/test_tablib_dbfpy_packages_utils.py",
+ "tests/source/tox.ini",
+ "tests/test.sh",
+ "tests/test_driver.py",
+ "tests/test_results.py",
+]
+executable_files = [
+ "environment/source/src/tablib/formats/_ods.py",
+ "solution/solve.sh",
+ "tests/source/src/tablib/formats/_ods.py",
+ "tests/source/tests/test_tablib.py",
+ "tests/test.sh",
+]
+bundle_hash = "sha256:bc1a47b24dc4e4aeb47fe0cc4327d3cb15f12d9bd0756dce79592d6cc69f2a91"
+
+[metadata.repo2env.evaluation]
+schema_version = "1"
+status = "verified"
+stage = "complete"
+reason_codes = [
+ "quality_verified",
+]
+detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile."
+checked_at = "2026-11-20T09:45:06.976707Z"
+provenance = "unknown"
+subject_bundle_hash = "sha256:bc1a47b24dc4e4aeb47fe0cc4327d3cb15f12d9bd0756dce79592d6cc69f2a91"
+profile = "evidence-review-v2"
+source_task_path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b07486fb0a9c/candidates/b6d969373e1e/quality/revisions/r0/tasksmith-b6d969373e1e"
+source_task_toml_sha256 = "2a5ae802b2953e2cad72fadaa7d031b72a3a3116c4a3e2a02b64d4341dfc59cf"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "quality_result"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b07486fb0a9c/candidates/b6d969373e1e/quality/result.json"
+sha256 = "960e582090075e402be184c7fe589558eba3f1f0fc9c33f43cf34c8bb6e10087"
+subject_bundle_hash = "sha256:bc1a47b24dc4e4aeb47fe0cc4327d3cb15f12d9bd0756dce79592d6cc69f2a91"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "baseline"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b07486fb0a9c/candidates/b6d969373e1e/quality/trials/r0-baseline/tsbatch-195cc094e760-b07486fb0a9c-q-b6d96937-r0-baseline/tasksmith-b6d969373e1e__rPuKERU/result.json"
+sha256 = "aaa4d3a4e1e6f99039c0a631c77b4ac2c6528fc99564a64e9a87e7625081a4f7"
+subject_bundle_hash = "sha256:bc1a47b24dc4e4aeb47fe0cc4327d3cb15f12d9bd0756dce79592d6cc69f2a91"
+harbor_task_checksum = "365ff825b52a04464be18a10b76c303c8fef469d7a2e1b2dcd1a93d494127b95"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "oracle"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b07486fb0a9c/candidates/b6d969373e1e/quality/trials/r0-oracle/tsbatch-195cc094e760-b07486fb0a9c-q-b6d96937-r0-oracle/tasksmith-b6d969373e1e__Ye6Hn5M/result.json"
+sha256 = "412c281b9b686bf513a5f71b444bfca5e4183b8a0b7fc61d85e468176ef31cae"
+subject_bundle_hash = "sha256:bc1a47b24dc4e4aeb47fe0cc4327d3cb15f12d9bd0756dce79592d6cc69f2a91"
+harbor_task_checksum = "365ff825b52a04464be18a10b76c303c8fef469d7a2e1b2dcd1a93d494127b95"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "probe"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b07486fb0a9c/candidates/b6d969373e1e/quality/trials/r0-probe0/tsbatch-195cc094e760-b07486fb0a9c-q-b6d96937-r0-probe0/tasksmith-b6d969373e1e__Fn3qQkD/result.json"
+sha256 = "a1a1933d1e922df629ab77c11450c94e3417d043b4d5f909cb68a1e29ed8e163"
+subject_bundle_hash = "sha256:db6cc6ca6aebe83a9ec77a0739748e17b21801ef9124907e75e72ec87051e9f6"
+harbor_task_checksum = "16f42a925e1545cd6d7e40bb91d53ecbdff05ec954ad4a031c776a8a23f30241"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "probe"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b07486fb0a9c/candidates/b6d969373e1e/quality/trials/r0-probe1/tsbatch-195cc094e760-b07486fb0a9c-q-b6d96937-r0-probe1/tasksmith-b6d969373e1e__42uZTcq/result.json"
+sha256 = "646e0200eb53e5861f2626b2fce19d36bbc14d1549ecdb3f417f72e804823702"
+subject_bundle_hash = "sha256:07c990736a57cd5b3acafc7818b58ecdd0e84a78f921b4f2faf39d93ad1dce28"
+harbor_task_checksum = "b98678c955eb69c79ab42d94eeaee1a4ff24c23b4b3982170e42ec2afbeb3245"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "rollout"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b07486fb0a9c/candidates/b6d969373e1e/quality/trials/r0-rollout/tsbatch-195cc094e760-b07486fb0a9c-q-b6d96937-r0-rollout/tasksmith-b6d969373e1e__FFXQavY/result.json"
+sha256 = "e1cffe2bbcb8ecf84fa34af57d7d19973ef481a50b71d02580989716d76938e5"
+subject_bundle_hash = "sha256:bc1a47b24dc4e4aeb47fe0cc4327d3cb15f12d9bd0756dce79592d6cc69f2a91"
+harbor_task_checksum = "365ff825b52a04464be18a10b76c303c8fef469d7a2e1b2dcd1a93d494127b95"
+
+[metadata.repo2env.quality_requirements]
+probe_focus = [
+ "general",
+]
+
+[environment]
+cpus = 1
+memory_mb = 2048
+build_timeout_sec = 600
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 600
+user = "learner"
+network_mode = "no-network"
+
+[verifier]
+timeout_sec = 90
+user = "root"
+network_mode = "no-network"
+environment_mode = "separate"
+
+[verifier.environment]
+network_mode = "no-network"
+cpus = 1
+memory_mb = 512
+
+[[artifacts]]
+source = "/workspace/src/tablib"
+exclude = [
+ "__pycache__",
+ "*.pyc",
+ ".pytest_cache",
+]
diff --git a/tasks/tasksmith-b6d969373e1e/tests/Dockerfile b/tasks/tasksmith-b6d969373e1e/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..e21db9b137ada808a680cbd1ec3c511992fa2272
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/Dockerfile
@@ -0,0 +1,10 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir setuptools==84.2.1 'setuptools_scm[toml]==10.3.4' pytest==9.2.0 pytest-cov==7.1.0 xlrd==2.0.2 xlwt==1.3.0 odfpy==1.4.1 openpyxl==3.1.5 pyyaml==6.0.3 tabulate==0.10.0
+COPY source /workspace
+RUN SETUPTOOLS_SCM_PRETEND_VERSION=0.0.1 python -m pip install --no-cache-dir -e .
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
+RUN useradd -m -u 1001 grader
+COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/
+RUN chmod 755 /tests && chmod 644 /tests/*
diff --git a/tasks/tasksmith-b6d969373e1e/tests/contract.json b/tasks/tasksmith-b6d969373e1e/tests/contract.json
new file mode 100644
index 0000000000000000000000000000000000000000..39d87e59a188b9029d72624aba86ebe776426035
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/contract.json
@@ -0,0 +1 @@
+{"expected_passes": ["tests.test_tablib.XLSTests::test_xls_book_date_import", "tests.test_tablib.XLSTests::test_xls_book_import_with_errors", "tests.test_tablib.XLSTests::test_book_import_from_stream", "tests.test_tablib.XLSTests::test_xls_bad_chars_sheet_name", "tests.test_tablib.XLSTests::test_xls_date_import", "tests.test_tablib.XLSTests::test_xls_export_with_dates", "tests.test_tablib.XLSTests::test_xls_format_detect", "tests.test_tablib.XLSTests::test_xls_import_with_errors", "tests.test_tablib.XLSTests::test_xlsx_import_set_skip_lines"], "immutable_assets": {}, "optional_files": [], "pytest_args": [], "submitted_files": ["src/tablib/__init__.py", "src/tablib/_vendor/__init__.py", "src/tablib/_vendor/dbfpy/__init__.py", "src/tablib/_vendor/dbfpy/dbf.py", "src/tablib/_vendor/dbfpy/dbfnew.py", "src/tablib/_vendor/dbfpy/fields.py", "src/tablib/_vendor/dbfpy/header.py", "src/tablib/_vendor/dbfpy/record.py", "src/tablib/_vendor/dbfpy/utils.py", "src/tablib/_version.py", "src/tablib/core.py", "src/tablib/exceptions.py", "src/tablib/formats/__init__.py", "src/tablib/formats/_cli.py", "src/tablib/formats/_csv.py", "src/tablib/formats/_dbf.py", "src/tablib/formats/_df.py", "src/tablib/formats/_html.py", "src/tablib/formats/_jira.py", "src/tablib/formats/_json.py", "src/tablib/formats/_latex.py", "src/tablib/formats/_ods.py", "src/tablib/formats/_rst.py", "src/tablib/formats/_sql.py", "src/tablib/formats/_tsv.py", "src/tablib/formats/_xls.py", "src/tablib/formats/_xlsx.py", "src/tablib/formats/_yaml.py", "src/tablib/utils.py"], "submitted_roots": ["src/tablib"], "test_paths": ["tests/test_tablib.py::XLSTests"], "timeout_sec": 60}
\ No newline at end of file
diff --git a/tasks/tasksmith-b6d969373e1e/tests/grade.py b/tasks/tasksmith-b6d969373e1e/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..a803a55bfcc142c8279645ea59cea90b2a90918a
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/grade.py
@@ -0,0 +1,196 @@
+"""Standalone trusted entry point; copied into each separate verifier image.
+
+No Repo2RLEnv installation is needed to grade an exported task. Submitted Python
+runs as an unprivileged user; this parent owns the result parser and reward file.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import os
+import signal
+import stat
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+
+def child_environment(temporary: str) -> dict[str, str]:
+ """Preserve prepared runtime assets without inheriting controller credentials."""
+ return {
+ **{
+ key: os.environ[key]
+ for key in (
+ "LD_LIBRARY_PATH",
+ "CUDA_VISIBLE_DEVICES",
+ "NVIDIA_VISIBLE_DEVICES",
+ "NVIDIA_DRIVER_CAPABILITIES",
+ "NCCL_SOCKET_IFNAME",
+ "GLOO_SOCKET_IFNAME",
+ "HF_HOME",
+ "HF_HUB_CACHE",
+ "HF_HUB_OFFLINE",
+ "TRANSFORMERS_OFFLINE",
+ "HF_DATASETS_OFFLINE",
+ )
+ if key in os.environ
+ },
+ "PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin",
+ "HOME": temporary,
+ "PYTHONDONTWRITEBYTECODE": "1",
+ "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
+ }
+
+
+def validate_submission(workspace: Path, contract: dict) -> None:
+ """Validate private staging and remove inert backups before importing Python."""
+ submitted = set(contract["submitted_files"])
+ backups: set[str] = set()
+ optional = submitted & set(contract.get("optional_files", []))
+ paths = submitted - optional
+ for relative in optional:
+ path = workspace / relative
+ if any(component.is_symlink() for component in (path, *path.parents)):
+ raise ValueError("Submitted source contains a symlink")
+ # Added standalone modules may be absent in the baseline. If supplied,
+ # apply the same regular-file and size checks as every required module.
+ if path.exists():
+ paths.add(relative)
+ roots = contract.get("submitted_roots", [])
+ immutable = contract.get("immutable_assets", {})
+ paths.update(immutable)
+ for relative in roots:
+ root = workspace / relative
+ if root.is_symlink() or not root.is_dir():
+ raise ValueError("Submitted source root is missing or linked")
+ for path in root.rglob("*"):
+ if path.is_symlink():
+ raise ValueError("Submitted source contains a symlink")
+ if path.is_dir():
+ continue
+ name = path.relative_to(workspace).as_posix()
+ if path.suffix != ".py" and name not in immutable:
+ if name not in submitted and path.name.endswith((".py.bak", ".py~")):
+ backups.add(name)
+ else:
+ raise ValueError("Only Python source files may be added")
+ paths.add(name)
+ for relative in sorted(paths):
+ path = workspace / relative
+ for component in (path, *path.parents):
+ if component.is_symlink():
+ raise ValueError("Submitted source contains a symlink")
+ if (
+ not path.is_file()
+ or not stat.S_ISREG(path.stat().st_mode)
+ or path.stat().st_size > 8 * 1024 * 1024
+ ):
+ raise ValueError("Submitted source is not a bounded regular file")
+ if (
+ relative in immutable
+ and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative]
+ ):
+ raise ValueError("Non-Python source assets must remain unchanged")
+ if relative not in backups:
+ # os.chown doesn't exist on Windows. This module only ever runs for
+ # real inside the Linux verifier container (every other path here
+ # is an absolute container path); the guard exists so the tests
+ # that call validate_submission() directly can run on a Windows
+ # host without touching real container-only ownership semantics.
+ if sys.platform != "win32":
+ os.chown(path, 0, 0)
+ path.chmod(0o644)
+ # Only the verifier's collected copy is cleaned. The learner workspace and
+ # archived submission retain their bytes. Validate every path first so a
+ # backup cannot bypass linked, oversized, required, or immutable file checks.
+ for relative in sorted(backups):
+ (workspace / relative).unlink()
+
+
+def main() -> None:
+ directory = Path("/tests")
+ parser_spec = importlib.util.spec_from_file_location(
+ "test_results", directory / "test_results.py"
+ )
+ parser = importlib.util.module_from_spec(parser_spec)
+ sys.modules[parser_spec.name] = parser
+ parser_spec.loader.exec_module(parser)
+ contract = json.loads((directory / "contract.json").read_text())
+ logs = Path("/logs/verifier")
+ logs.mkdir(parents=True, exist_ok=True)
+ logs.chmod(0o755)
+ reward = logs / "reward.txt"
+ reward.write_text("0\n")
+ reward.chmod(0o644)
+ try:
+ validate_submission(Path("/workspace"), contract)
+ except (ValueError, OSError) as exc:
+ (logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)}))
+ return
+ with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary:
+ working = Path(temporary)
+ if sys.platform != "win32": # os.chown doesn't exist on Windows; see above
+ os.chown(working, 1001, 1001)
+ working.chmod(0o700)
+ report = working / "results.xml"
+ command = [
+ sys.executable,
+ "-I",
+ "/tests/test_driver.py",
+ *contract["test_paths"],
+ *contract.get("pytest_args", []),
+ "-q",
+ "--tb=short",
+ "-p",
+ "no:cacheprovider",
+ f"--junitxml={report}",
+ ]
+ with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr:
+ process = subprocess.Popen(
+ command,
+ cwd="/workspace",
+ stdout=stdout,
+ stderr=stderr,
+ user=1001,
+ group=1001,
+ extra_groups=[],
+ start_new_session=True,
+ env=child_environment(temporary),
+ )
+ try:
+ code = process.wait(timeout=contract["timeout_sec"])
+ finally:
+ # Terminate descendants too: they must not keep modifying the
+ # child-owned report while the trusted parent checks it.
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024:
+ (logs / "result.json").write_text(
+ json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"})
+ )
+ return
+ text = report.read_text()
+ (logs / "results.xml").write_text(text)
+ try:
+ parsed = parser.parse_junit(text, returncode=code)
+ except ValueError as exc:
+ (logs / "result.json").write_text(
+ json.dumps({"passed": False, "returncode": code, "reason": str(exc)})
+ )
+ return
+ expected = set(contract["expected_passes"])
+ passed = code == 0 and bool(expected) and parsed.passed == expected
+ (logs / "result.json").write_text(
+ json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses})
+ )
+ reward.write_text("1\n" if passed else "0\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.coveragerc b/tasks/tasksmith-b6d969373e1e/tests/source/.coveragerc
new file mode 100644
index 0000000000000000000000000000000000000000..0ab42b3eb0df78b1b040d9e2fbffa9ab918d6fa9
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.coveragerc
@@ -0,0 +1,10 @@
+# .coveragerc to control coverage.py
+
+[report]
+# Regexes for lines to exclude from consideration
+exclude_lines =
+ # Have to re-enable the standard pragma:
+ pragma: no cover
+
+ # Don't complain if non-runnable code isn't run:
+ if __name__ == .__main__.:
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.github/CONTRIBUTING.md b/tasks/tasksmith-b6d969373e1e/tests/source/.github/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..4c82fbe27658773078016684476920eeaa430912
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.github/CONTRIBUTING.md
@@ -0,0 +1,10 @@
+[](https://jazzband.co/)
+
+This is a [Jazzband](https://jazzband.co/) project. By contributing you agree to abide
+by the [Contributor Code of Conduct](https://jazzband.co/about/conduct) and follow the
+[guidelines](https://jazzband.co/about/guidelines).
+
+If you'd like to contribute, simply fork
+[the repository](https://github.com/jazzband/tablib), commit your changes to a feature
+branch, and send a pull request to `master`. Make sure you add yourself to
+[AUTHORS](https://github.com/jazzband/tablib/blob/master/AUTHORS).
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.github/release-drafter.yml b/tasks/tasksmith-b6d969373e1e/tests/source/.github/release-drafter.yml
new file mode 100644
index 0000000000000000000000000000000000000000..04404b64ff88a0a318d668dbf20507a319b94fc6
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.github/release-drafter.yml
@@ -0,0 +1,48 @@
+name-template: "v$RESOLVED_VERSION"
+tag-template: "v$RESOLVED_VERSION"
+
+categories:
+ - title: "Added"
+ labels:
+ - "changelog: Added"
+ - "enhancement"
+ - title: "Changed"
+ label: "changelog: Changed"
+ - title: "Deprecated"
+ label: "changelog: Deprecated"
+ - title: "Removed"
+ label: "changelog: Removed"
+ - title: "Fixed"
+ labels:
+ - "changelog: Fixed"
+ - "bug"
+ - title: "Security"
+ label: "changelog: Security"
+
+exclude-labels:
+ - "changelog: skip"
+
+autolabeler:
+ - label: "changelog: skip"
+ branch:
+ - "/pre-commit-ci-update-config/"
+
+template: |
+ $CHANGES
+
+version-resolver:
+ major:
+ labels:
+ - "changelog: Removed"
+ minor:
+ labels:
+ - "changelog: Added"
+ - "changelog: Changed"
+ - "changelog: Deprecated"
+ - "enhancement"
+
+ patch:
+ labels:
+ - "changelog: Fixed"
+ - "bug"
+ default: minor
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.github/release.yml b/tasks/tasksmith-b6d969373e1e/tests/source/.github/release.yml
new file mode 100644
index 0000000000000000000000000000000000000000..9d1e0987bfc323000b570d680343f00c53ddbc3d
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.github/release.yml
@@ -0,0 +1,5 @@
+changelog:
+ exclude:
+ authors:
+ - dependabot
+ - pre-commit-ci
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/docs-lint.yml b/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/docs-lint.yml
new file mode 100644
index 0000000000000000000000000000000000000000..bace37bfac6ae0ad9ae3f6f832bc7375322e212f
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/docs-lint.yml
@@ -0,0 +1,38 @@
+name: Docs and lint
+
+on: [push, pull_request, workflow_dispatch]
+
+env:
+ FORCE_COLOR: 1
+ PIP_DISABLE_PIP_VERSION_CHECK: 1
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ env:
+ - TOXENV: docs
+ - TOXENV: lint
+
+ steps:
+ - uses: actions/checkout@v5
+
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ with:
+ python-version: "3.x"
+ cache: pip
+ cache-dependency-path: "pyproject.toml"
+
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install --upgrade tox
+
+ - name: Tox
+ run: tox
+ env: ${{ matrix.env }}
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/release-drafter.yml b/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/release-drafter.yml
new file mode 100644
index 0000000000000000000000000000000000000000..6de43e03c01c02926ad38bcdaf569f5730c5f44a
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/release-drafter.yml
@@ -0,0 +1,31 @@
+name: Release drafter
+
+on:
+ push:
+ # branches to consider in the event; optional, defaults to all
+ branches:
+ - master
+ # pull_request event is required only for autolabeler
+ pull_request:
+ # Only following types are handled by the action, but one can default to all as well
+ types: [opened, reopened, synchronize]
+ # pull_request_target event is required for autolabeler to support PRs from forks
+ # pull_request_target:
+ # types: [opened, reopened, synchronize]
+ workflow_dispatch:
+
+jobs:
+ update_release_draft:
+ if: github.event.repository.fork == false
+ permissions:
+ # write permission is required to create a GitHub Release
+ contents: write
+ # write permission is required for autolabeler
+ # otherwise, read permission is required at least
+ pull-requests: write
+ runs-on: ubuntu-latest
+ steps:
+ # Drafts your next release notes as pull requests are merged into "main"
+ - uses: release-drafter/release-drafter@v6
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/release.yml b/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/release.yml
new file mode 100644
index 0000000000000000000000000000000000000000..2aa93c8a13f4ed8dfe5e2c098ddfd7322278e641
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/release.yml
@@ -0,0 +1,45 @@
+name: Release
+
+on:
+ push:
+ branches:
+ - master
+ release:
+ types:
+ - published
+ workflow_dispatch:
+
+jobs:
+ build:
+ if: github.repository_owner == 'jazzband'
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v5
+ with:
+ fetch-depth: 0
+
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ with:
+ python-version: "3.x"
+ cache: pip
+ cache-dependency-path: "pyproject.toml"
+
+ - name: Install dependencies
+ run: |
+ python -m pip install -U pip
+ python -m pip install build twine
+
+ - name: Build package
+ run: |
+ python -m build
+ twine check dist/*
+
+ - name: Upload packages to Jazzband
+ if: github.event.action == 'published'
+ uses: pypa/gh-action-pypi-publish@release/v1
+ with:
+ user: jazzband
+ password: ${{ secrets.JAZZBAND_RELEASE_KEY }}
+ repository-url: https://jazzband.co/projects/tablib/upload
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/require-pr-label.yml b/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/require-pr-label.yml
new file mode 100644
index 0000000000000000000000000000000000000000..5f7a28032b44f9d1812de0f4ad55c9ee3e473e30
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/require-pr-label.yml
@@ -0,0 +1,27 @@
+name: Require PR label
+
+on:
+ pull_request:
+ types: [opened, reopened, labeled, unlabeled, synchronize]
+
+jobs:
+ label:
+ runs-on: ubuntu-latest
+
+ permissions:
+ issues: write
+ pull-requests: write
+
+ steps:
+ - uses: mheap/github-action-required-labels@v5
+ with:
+ mode: minimum
+ count: 1
+ labels: |
+ changelog: Added
+ changelog: Changed
+ changelog: Deprecated
+ changelog: Fixed
+ changelog: Removed
+ changelog: Security
+ changelog: skip
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/test.yml b/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/test.yml
new file mode 100644
index 0000000000000000000000000000000000000000..271e8d341940ea5c2a175ce805afa5581b6f356c
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.github/workflows/test.yml
@@ -0,0 +1,46 @@
+name: Test
+
+on: [push, pull_request, workflow_dispatch]
+
+permissions:
+ contents: read
+
+env:
+ FORCE_COLOR: 1
+ PIP_DISABLE_PIP_VERSION_CHECK: 1
+
+jobs:
+ test:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
+ os: [ubuntu-latest, macOS-latest, windows-latest]
+
+ steps:
+ - uses: actions/checkout@v5
+
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v6
+ with:
+ python-version: ${{ matrix.python-version }}
+ allow-prereleases: true
+ cache: pip
+ cache-dependency-path: "pyproject.toml"
+
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ python -m pip install --upgrade tox
+ python -m pip install -e .
+
+ - name: Tox tests
+ shell: bash
+ run: |
+ tox -e py
+
+ - name: Upload coverage
+ uses: codecov/codecov-action@v5
+ with:
+ name: ${{ matrix.os }} Python ${{ matrix.python-version }}
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.gitignore b/tasks/tasksmith-b6d969373e1e/tests/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..df3ae4039cafb57b78ab4ad649a9266cfc447d12
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.gitignore
@@ -0,0 +1,43 @@
+# application builds
+build/*
+dist/*
+MANIFEST
+
+# python skin
+*.pyc
+*.pyo
+
+# osx noise
+.DS_Store
+profile
+
+# pycharm noise
+.idea
+.idea/*
+
+# vi noise
+*.swp
+docs/_build/*
+coverage.xml
+nosetests.xml
+junit-py25.xml
+junit-py26.xml
+junit-py27.xml
+
+# tox noise
+.tox
+
+# pyenv noise
+.python-version
+tablib.egg-info/*
+
+# Coverage
+.coverage
+htmlcov
+
+# setuptools noise
+.eggs
+*.egg-info
+
+# generated by setuptools-scm
+/src/tablib/_version.py
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.pre-commit-config.yaml b/tasks/tasksmith-b6d969373e1e/tests/source/.pre-commit-config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..94630ae5e302fe1fe8d1aecdeca9c66c67cea516
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.pre-commit-config.yaml
@@ -0,0 +1,33 @@
+repos:
+ - repo: https://github.com/astral-sh/ruff-pre-commit
+ rev: v0.15.20
+ hooks:
+ - id: ruff-check
+ args: [--exit-non-zero-on-fix]
+
+ - repo: https://github.com/pre-commit/pygrep-hooks
+ rev: v1.10.0
+ hooks:
+ - id: rst-backticks
+
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v6.0.0
+ hooks:
+ - id: check-added-large-files
+ - id: check-case-conflict
+ - id: check-merge-conflict
+ - id: check-toml
+ - id: check-yaml
+ - id: debug-statements
+ - id: end-of-file-fixer
+ - id: forbid-submodules
+ - id: requirements-txt-fixer
+ - id: trailing-whitespace
+
+ - repo: meta
+ hooks:
+ - id: check-hooks-apply
+ - id: check-useless-excludes
+
+ci:
+ autoupdate_schedule: quarterly
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/.readthedocs.yaml b/tasks/tasksmith-b6d969373e1e/tests/source/.readthedocs.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..2911d6dab26ea074a2c9bb8eee269cedde294857
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/.readthedocs.yaml
@@ -0,0 +1,15 @@
+version: 2
+
+build:
+ os: ubuntu-26.04
+ tools:
+ python: "3.14"
+
+sphinx:
+ configuration: docs/conf.py
+
+python:
+ install:
+ - requirements: docs/requirements.txt
+ - method: pip
+ path: .
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/AUTHORS b/tasks/tasksmith-b6d969373e1e/tests/source/AUTHORS
new file mode 100644
index 0000000000000000000000000000000000000000..cd73e6574899f595d1065e9c5ceeb6a553e192dc
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/AUTHORS
@@ -0,0 +1,43 @@
+Tablib was originally written by Kenneth Reitz and is now maintained
+by the Jazzband GitHub team.
+
+Here is a list of past and present much-appreciated contributors:
+
+ Alex Gaynor
+ Andrew Graham-Yooll
+ Andrii Soldatenko
+ Benjamin Wohlwend
+ Bruno Soares
+ Claude Paroz
+ Daniel Santos
+ Egor Osokin
+ Erik Youngren
+ Hugo van Kemenade
+ Ian Stride
+ Iuri de Silvio
+ Jakub Janoszek
+ James Douglass
+ Joel Friedly
+ Josh Ourisman
+ Kenneth Reitz
+ Luca Beltrame
+ Luke Lee
+ Marc Abramowitz
+ Marco Dallagiacoma
+ Maris Nartiss
+ Mark Rogers
+ Mark Walling
+ Mathias Loesch
+ Matthew Hegarty
+ Matthias Dellweg
+ Mike Waldner
+ Nicholas Pilon
+ Peyman Salehi
+ Rabin Nankhwa
+ Tak Hogan
+ Tommy Anthony
+ Tsuyoshi Hombashi
+ Tushar Makkar
+ Vidit Patankar
+ Vineeth Sai
+ Yunis Yilmaz
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/CODE_OF_CONDUCT.md b/tasks/tasksmith-b6d969373e1e/tests/source/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000000000000000000000000000000000..e0d5efab56fb94577e7804603eb6f21f36977cb2
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/CODE_OF_CONDUCT.md
@@ -0,0 +1,46 @@
+# Code of Conduct
+
+As contributors and maintainers of the Jazzband projects, and in the interest of
+fostering an open and welcoming community, we pledge to respect all people who
+contribute through reporting issues, posting feature requests, updating documentation,
+submitting pull requests or patches, and other activities.
+
+We are committed to making participation in the Jazzband a harassment-free experience
+for everyone, regardless of the level of experience, gender, gender identity and
+expression, sexual orientation, disability, personal appearance, body size, race,
+ethnicity, age, religion, or nationality.
+
+Examples of unacceptable behavior by participants include:
+
+- The use of sexualized language or imagery
+- Personal attacks
+- Trolling or insulting/derogatory comments
+- Public or private harassment
+- Publishing other's private information, such as physical or electronic addresses,
+ without explicit permission
+- Other unethical or unprofessional conduct
+
+The Jazzband roadies have the right and responsibility to remove, edit, or reject
+comments, commits, code, wiki edits, issues, and other contributions that are not
+aligned to this Code of Conduct, or to ban temporarily or permanently any contributor
+for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
+
+By adopting this Code of Conduct, the roadies commit themselves to fairly and
+consistently applying these principles to every aspect of managing the jazzband
+projects. Roadies who do not follow or enforce the Code of Conduct may be permanently
+removed from the Jazzband roadies.
+
+This code of conduct applies both within project spaces and in public spaces when an
+individual is representing the project or its community.
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by
+contacting the roadies at `roadies@jazzband.co`. All complaints will be reviewed and
+investigated and will result in a response that is deemed necessary and appropriate to
+the circumstances. Roadies are obligated to maintain confidentiality with regard to the
+reporter of an incident.
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version
+1.3.0, available at [https://contributor-covenant.org/version/1/3/0/][version]
+
+[homepage]: https://contributor-covenant.org
+[version]: https://contributor-covenant.org/version/1/3/0/
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/Dockerfile b/tasks/tasksmith-b6d969373e1e/tests/source/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..7ee5a1058470aa5653fba97eb0f2b60acaeebd23
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/Dockerfile
@@ -0,0 +1,8 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir setuptools==84.2.1 'setuptools_scm[toml]==10.3.4' pytest==9.2.0 pytest-cov==7.1.0 xlrd==2.0.2 xlwt==1.3.0 odfpy==1.4.1 openpyxl==3.1.5 pyyaml==6.0.3 tabulate==0.10.0
+COPY . /workspace
+RUN SETUPTOOLS_SCM_PRETEND_VERSION=0.0.1 python -m pip install --no-cache-dir -e .
+RUN rm -rf /workspace/.git /root/.cache/pip
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/HISTORY.md b/tasks/tasksmith-b6d969373e1e/tests/source/HISTORY.md
new file mode 100644
index 0000000000000000000000000000000000000000..77f3b6b3460877c12ec91bba3e9e19f0b1dd5923
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/HISTORY.md
@@ -0,0 +1,463 @@
+# History
+
+## 3.9.0 and newer
+
+See GitHub Releases:
+
+- https://github.com/jazzband/tablib/releases
+
+## 3.8.0 (2025-01-22)
+
+### Improvements
+
+- Add support for exporting XLSX with column width (#516)
+- Remove redundant check from `Dataset.load()` (#604)
+
+## 3.7.0 (2024-10-08)
+
+### Improvements
+
+- Add support for Python 3.13 (#592)
+- Drop support for EOL Python 3.8 (#598)
+- Add styling to datetime, date and time values for ODS (#594)
+- Add styling for date/time types for XLS (#596)
+
+### Bugfixes
+
+- Fix time and datetime export in ODS format (#595)
+- Avoid normalizing input twice in `import_set`/`book` (#591)
+
+## 3.6.1 (2024-04-04)
+
+### Bugfixes
+
+- Fix broken installs with pip failing to resolve the request for `tablib[html]` in some cases (#588).
+
+## 3.6.0 (2024-03-23)
+
+### Improvements
+
+- It's now possible to access a dataset row using its index without slicing (#24).
+- The dataset `transpose()` method can be called on datasets without headers.
+- The html format now supports importing from HTML content (#243)
+- The ODS format now supports importing from .ods files (#567). The support is
+ still a bit experimental.
+- When adding rows to a dataset with dynamic columns, it's now possible to
+ provide only static values, and dynamic column values will be automatically
+ calculated and added to the row (#572).
+
+### Changes
+
+- The html export format does not depend on MarkupPy any longer, therefore the
+ tablib[html] install target was removed also.
+
+### Bugfixes
+
+- Fix crash when loading a databook from an XLS file (#522).
+- `None` Python values are now converted to the empty string by the ODS formatter.
+- When applying formatters, the internal data is no longer mutated (#578).
+- Columns can be inserted even when a dataset has headers but no values (#583).
+
+## 3.5.0 (2023-06-11)
+
+### Improvements
+
+- Add support for Python 3.12 (#550)
+- Drop support for EOL Python 3.7 (#551)
+- Allow importing 'ragged' .xlsx files through dataset (#547)
+- Release: replace deprecated `repository_url` with `repository-url` (#545)
+
+## 3.4.0 (2023-03-24)
+
+### Improvements
+
+- Move setup to `pyproject.toml` (#542)
+- xlsx export: remove redundant code (#541)
+- xlsx export: support escape of formulae (#540)
+- Add <tbody> tags to HTML output (#539)
+- Check for type list and improve error msg (#524)
+
+### Bugfixes
+
+- Fix bug when yaml file is empty (#535)
+- Fix linting issues raised by Flake8 (#536)
+
+## 3.3.0 (2022-12-10)
+
+### Improvements
+
+- Add support for Python 3.11 (#525).
+- ODS export: integers/floats/decimals are exported as numbers (#527).
+
+## 3.2.1 (2022-04-09)
+
+### Bugfixes
+
+- Support solo CR in text input imports (#518).
+
+## 3.2.0 (2022-01-27)
+
+### Changes
+
+- Dropped Python 3.6 support (#513).
+
+### Bugfixes
+
+- Corrected order of arguments to a regex call in `safe_xlsx_sheet_title` (#510).
+
+## 3.1.0 (2021-10-26)
+
+### Improvements
+
+- Add support for Python 3.10 (#504).
+- The csv, xls, and xlsx formats gained support for the `skip_lines` keyword
+ argument for their `import_set()` method to be able to skip the nth first
+ lines of a read file (#497).
+
+### Bugfixes
+
+- Avoided mutable parameter defaults (#494).
+- Specify build backend for editable installs (#501).
+- Doubled sample size passed to `csv.Sniffer()` in `_csv.detect()` (#503).
+
+## 3.0.0 (2020-12-05)
+
+### Breaking changes
+
+- Dropped Python 3.5 support.
+- JSON-exported data is no longer forced to ASCII characters.
+- YAML-exported data is no longer forced to ASCII characters.
+
+### Improvements
+
+- Added Python 3.9 support.
+- Added read_only option to xlsx file reader (#482).
+
+### Bugfixes
+
+- Prevented crash in rst export with only-space strings (#469).
+
+## 2.0.0 (2020-05-16)
+
+### Breaking changes
+
+- The `Row.lpush/rpush` logic was reversed. `lpush` was appending while `rpush`
+ and `append` were prepending. This was fixed (reversed behavior). If you
+ counted on the broken behavior, please update your code (#453).
+
+### Bugfixes
+
+- Fixed minimal openpyxl dependency version to 2.6.0 (#457).
+- Dates from xls files are now read as Python datetime objects (#373).
+- Allow import of "ragged" xlsx files (#465).
+
+### Improvements
+
+- When importing an xlsx file, Tablib will now read cell values instead of formulas (#462).
+
+## 1.1.0 (2020-02-13)
+
+### Deprecations
+
+- Upcoming breaking change in Tablib 2.0.0: the `Row.lpush/rpush` logic is reversed.
+ `lpush` is appending while `rpush` and `append` are prepending. The broken behavior
+ will remain in Tablib 1.x and will be fixed (reversed) in Tablib 2.0.0 (#453). If you
+ count on the broken behavior, please update your code when you upgrade to Tablib 2.x.
+
+### Improvements
+
+- Tablib is now able to import CSV content where not all rows have the same
+ length. Missing columns on any line receive the empty string (#226).
+
+## 1.0.0 (2020-01-13)
+
+### Breaking changes
+
+- Dropped Python 2 support
+- Dependencies are now all optional. To install `tablib` as before with all
+ possible supported formats, run `pip install tablib[all]`
+
+### Improvements
+
+- Formats can now be dynamically registered through the
+ `tablib.formats.registry.refister` API (#256).
+- Tablib methods expecting data input (`detect_format`, `import_set`,
+ `Dataset.load`, `Databook.load`) now accepts file-like objects in addition
+ to raw strings and bytestrings (#440).
+
+### Bugfixes
+
+- Fixed a crash when exporting an empty string with the ReST format (#368)
+- Error cells from imported .xls files contain now the error string (#202)
+
+## 0.14.0 (2019-10-19)
+
+### Deprecations
+
+- The 0.14.x series will be the last to support Python 2
+
+### Breaking changes
+
+- Dropped Python 3.4 support
+
+### Improvements
+
+- Added Python 3.7 and 3.8 support
+- The project is now maintained by the Jazzband team, https://jazzband.co
+- Improved format autodetection and added autodetection for the odf format.
+- Added search to all documentation pages
+- Open xlsx workbooks in read-only mode (#316)
+- Unpin requirements
+- Only install backports.csv on Python 2
+
+### Bugfixes
+
+- Fixed `DataBook().load` parameter ordering (first stream, then format).
+- Fixed a regression for xlsx exports where non-string values were forced to
+ strings (#314)
+- Fixed xlsx format detection (which was often detected as `xls` format)
+
+## 0.13.0 (2019-03-08)
+
+- Added reStructuredText output capability (#336)
+- Added Jira output capability
+- Stopped calling openpyxl deprecated methods (accessing cells, removing sheets)
+ (openpyxl minimal version is now 2.4.0)
+- Fixed a circular dependency issue in JSON output (#332)
+- Fixed Unicode error for the CSV export on Python 2 (#215)
+- Removed usage of optional `ujson` (#311)
+- Dropped Python 3.3 support
+
+## 0.12.1 (2017-09-01)
+
+- Favor `Dataset.export()` over `Dataset.` syntax in docs
+- Make Panda dependency optional
+
+## 0.12.0 (2017-08-27)
+
+- Add initial Panda DataFrame support
+- Dropped Python 2.6 support
+
+## 0.11.5 (2017-06-13)
+
+- Use `yaml.safe_load` for importing yaml.
+
+## 0.11.4 (2017-01-23)
+
+- Use built-in `json` package if available
+- Support Python 3.5+ in classifiers
+
+### Bugfixes
+
+- Fixed textual representation for Dataset with no headers
+- Handle decimal types
+
+## 0.11.3 (2016-02-16)
+
+- Release fix.
+
+## 0.11.2 (2016-02-16)
+
+### Bugfixes
+
+- Fix export only formats.
+- Fix for xlsx output.
+
+## 0.11.1 (2016-02-07)
+
+### Bugfixes
+
+- Fixed packaging error on Python 3.
+
+
+## 0.11.0 (2016-02-07)
+
+### New Formats!
+
+- Added LaTeX table export format (`Dataset.latex`).
+- Support for dBase (DBF) files (`Dataset.dbf`).
+
+### Improvements
+
+- New import/export interface (`Dataset.export()`, `Dataset.load()`).
+- CSV custom delimiter support (`Dataset.export('csv', delimiter='$')`).
+- Adding ability to remove duplicates to all rows in a dataset (`Dataset.remove_duplicates()`).
+- Added a mechanism to avoid `datetime.datetime` issues when serializing data.
+- New `detect_format()` function (mostly for internal use).
+- Update the vendored unicodecsv to fix `None` handling.
+- Only freeze the headers row, not the headers columns (xls).
+
+### Breaking Changes
+
+- `detect()` function removed.
+
+### Bugfixes
+
+- Fix XLSX import.
+- Bugfix for `Dataset.transpose().transpose()`.
+
+
+## 0.10.0 (2014-05-27)
+
+* Unicode Column Headers
+* ALL the bugfixes!
+
+## 0.9.11 (2011-06-30)
+
+* Bugfixes
+
+## 0.9.10 (2011-06-22)
+
+* Bugfixes
+
+## 0.9.9 (2011-06-21)
+
+* Dataset API Changes
+* `stack_rows` => `stack`, `stack_columns` => `stack_cols`
+* column operations have their own methods now (`append_col`, `insert_col`)
+* List-style `pop()`
+* Redis-style `rpush`, `lpush`, `rpop`, `lpop`, `rpush_col`, and `lpush_col`
+
+## 0.9.8 (2011-05-22)
+
+* OpenDocument Spreadsheet support (.ods)
+* Full Unicode TSV support
+
+
+## 0.9.7 (2011-05-12)
+
+* Full XLSX Support!
+* Pickling Bugfix
+* Compat Module
+
+
+## 0.9.6 (2011-05-12)
+
+* `seperators` renamed to `separators`
+* Full unicode CSV support
+
+
+## 0.9.5 (2011-03-24)
+
+* Python 3.1, Python 3.2 Support (same code base!)
+* Formatter callback support
+* Various bug fixes
+
+
+
+## 0.9.4 (2011-02-18)
+
+* Python 2.5 Support!
+* Tox Testing for 2.5, 2.6, 2.7
+* AnyJSON Integrated
+* OrderedDict support
+* Caved to community pressure (spaces)
+
+
+## 0.9.3 (2011-01-31)
+
+* Databook duplication leak fix.
+* HTML Table output.
+* Added column sorting.
+
+
+## 0.9.2 (2010-11-17)
+
+* Transpose method added to Datasets.
+* New frozen top row in Excel output.
+* Pickling support for Datasets and Rows.
+* Support for row/column stacking.
+
+
+## 0.9.1 (2010-11-04)
+
+* Minor reference shadowing bugfix.
+
+
+## 0.9.0 (2010-11-04)
+
+* Massive documentation update!
+* Tablib.org!
+* Row tagging and Dataset filtering!
+* Column insert/delete support
+* Column append API change (header required)
+* Internal Changes (Row object and use thereof)
+
+
+## 0.8.5 (2010-10-06)
+
+* New import system. All dependencies attempt to load from site-packages,
+ then fallback on tenderized modules.
+
+
+## 0.8.4 (2010-10-04)
+
+* Updated XLS output: Only wrap if '\\n' in cell.
+
+
+## 0.8.3 (2010-10-04)
+
+* Ability to append new column passing a callable
+ as the value that will be applied to every row.
+
+
+## 0.8.2 (2010-10-04)
+
+* Added alignment wrapping to written cells.
+* Added separator support to XLS.
+
+
+## 0.8.1 (2010-09-28)
+
+* Packaging Fix
+
+
+## 0.8.0 (2010-09-25)
+
+* New format plugin system!
+* Imports! ELEGANT Imports!
+* Tests. Lots of tests.
+
+
+## 0.7.1 (2010-09-20)
+
+* Reverting methods back to properties.
+* Windows bug compensated in documentation.
+
+
+## 0.7.0 (2010-09-20)
+
+* Renamed DataBook Databook for consistency.
+* Export properties changed to methods (XLS filename / StringIO bug).
+* Optional Dataset.xls(path='filename') support (for writing on windows).
+* Added utf-8 on the worksheet level.
+
+
+## 0.6.4 (2010-09-19)
+
+* Updated unicode export for XLS.
+* More exhaustive unit tests.
+
+
+## 0.6.3 (2010-09-14)
+
+* Added Dataset.append() support for columns.
+
+
+## 0.6.2 (2010-09-13)
+
+* Fixed Dataset.append() error on empty dataset.
+* Updated Dataset.headers property w/ validation.
+* Added Testing Fixtures.
+
+## 0.6.1 (2010-09-12)
+
+* Packaging hotfixes.
+
+
+## 0.6.0 (2010-09-11)
+
+* Public Release.
+* Export Support for XLS, JSON, YAML, and CSV.
+* DataBook Export for XLS, JSON, and YAML.
+* Python Dict Property Support.
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/LICENSE b/tasks/tasksmith-b6d969373e1e/tests/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..9bfca256684905e950decdeaf85de465c2977b63
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/LICENSE
@@ -0,0 +1,20 @@
+Copyright 2016 Kenneth Reitz
+Copyright 2019 Jazzband
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/README.md b/tasks/tasksmith-b6d969373e1e/tests/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..f85770fef901c5725dc43cee1f2754d22d520f75
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/README.md
@@ -0,0 +1,46 @@
+# Tablib: format-agnostic tabular dataset library
+
+[](https://jazzband.co/)
+[](https://pypi.org/project/tablib/)
+[](https://pypi.org/project/tablib/)
+[](https://pypistats.org/packages/tablib)
+[](https://github.com/jazzband/tablib/actions)
+[](https://codecov.io/gh/jazzband/tablib)
+[](LICENSE)
+
+ _____ ______ ___________ ______
+ __ /_______ ____ /_ ___ /___(_)___ /_
+ _ __/_ __ `/__ __ \__ / __ / __ __ \
+ / /_ / /_/ / _ /_/ /_ / _ / _ /_/ /
+ \__/ \__,_/ /_.___/ /_/ /_/ /_.___/
+
+
+Tablib is a format-agnostic tabular dataset library, written in Python.
+
+Output formats supported:
+
+- Excel (Sets + Books)
+- JSON (Sets + Books)
+- YAML (Sets + Books)
+- Pandas DataFrames (Sets)
+- HTML (Sets)
+- Jira (Sets)
+- LaTeX (Sets)
+- TSV (Sets)
+- ODS (Sets)
+- CSV (Sets)
+- DBF (Sets)
+- SQL (Sets)
+
+Note that tablib *purposefully* excludes XML support. It always will. (Note: This is a
+joke. Pull requests are welcome.)
+
+Tablib documentation is graciously hosted on https://tablib.readthedocs.io
+
+It is also available in the ``docs`` directory of the source distribution.
+
+Make sure to check out [Tablib on PyPI](https://pypi.org/project/tablib/)!
+
+## Contribute
+
+Please see the [contributing guide](https://github.com/jazzband/tablib/blob/master/.github/CONTRIBUTING.md).
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/RELEASING.md b/tasks/tasksmith-b6d969373e1e/tests/source/RELEASING.md
new file mode 100644
index 0000000000000000000000000000000000000000..23ccf97961bf2df1c985001af583506cf9176539
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/RELEASING.md
@@ -0,0 +1,24 @@
+# Release checklist
+
+Jazzband guidelines: https://jazzband.co/about/releases
+
+* [ ] Get `master` to the appropriate code release state.
+ [GitHub Actions](https://github.com/jazzband/tablib/actions)
+ should pass on `master`.
+ [](https://github.com/jazzband/tablib/actions)
+
+* [ ] Edit release draft, adjust text if needed:
+ https://github.com/hugovk/em-keyboard/releases
+
+* [ ] Check next tag is correct, amend if needed
+
+* [ ] Publish release
+
+* [ ] Once GitHub Actions has built and uploaded distributions, check files at
+ [Jazzband](https://jazzband.co/projects/tablib) and release to
+ [PyPI](https://pypi.org/pypi/tablib)
+
+* [ ] Check installation:
+```bash
+pip uninstall -y tablib && pip install -U tablib
+```
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/Makefile b/tasks/tasksmith-b6d969373e1e/tests/source/docs/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..9d5fd7e0ef88489245e08be1d03e4957157d50ac
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/Makefile
@@ -0,0 +1,130 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+PAPER =
+BUILDDIR = _build
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
+
+help:
+ @echo "Please use \`make ' where is one of"
+ @echo " html to make standalone HTML files"
+ @echo " dirhtml to make HTML files named index.html in directories"
+ @echo " singlehtml to make a single large HTML file"
+ @echo " pickle to make pickle files"
+ @echo " json to make JSON files"
+ @echo " htmlhelp to make HTML files and a HTML help project"
+ @echo " qthelp to make HTML files and a qthelp project"
+ @echo " devhelp to make HTML files and a Devhelp project"
+ @echo " epub to make an epub"
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+ @echo " latexpdf to make LaTeX files and run them through pdflatex"
+ @echo " text to make text files"
+ @echo " man to make manual pages"
+ @echo " changes to make an overview of all changed/added/deprecated items"
+ @echo " linkcheck to check all external links for integrity"
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+ -rm -rf $(BUILDDIR)/*
+
+html:
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+singlehtml:
+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+ @echo
+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+pickle:
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+ @echo
+ @echo "Build finished; now you can process the pickle files."
+
+json:
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+ @echo
+ @echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+ @echo
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+ @echo
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Tablib.qhcp"
+ @echo "To view the help file:"
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Tablib.qhc"
+
+devhelp:
+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+ @echo
+ @echo "Build finished."
+ @echo "To view the help file:"
+ @echo "# mkdir -p $$HOME/.local/share/devhelp/Tablib"
+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Tablib"
+ @echo "# devhelp"
+
+epub:
+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+ @echo
+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+latex:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+ @echo "Run \`make' in that directory to run these through (pdf)latex" \
+ "(use \`make latexpdf' here to do that automatically)."
+
+latexpdf:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo "Running LaTeX files through pdflatex..."
+ make -C $(BUILDDIR)/latex all-pdf
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+text:
+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
+ @echo
+ @echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+man:
+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
+ @echo
+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+changes:
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+ @echo
+ @echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+ @echo
+ @echo "Link check complete; look for any errors in the above output " \
+ "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+ @echo "Testing of doctests in the sources finished, look at the " \
+ "results in $(BUILDDIR)/doctest/output.txt."
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/__init__.py b/tasks/tasksmith-b6d969373e1e/tests/source/docs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/_templates/sidebarintro.html b/tasks/tasksmith-b6d969373e1e/tests/source/docs/_templates/sidebarintro.html
new file mode 100644
index 0000000000000000000000000000000000000000..44e82c1cb17864d7c47593d10d8ed800b8cb9084
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/_templates/sidebarintro.html
@@ -0,0 +1,12 @@
+
+ Tablib is an MIT Licensed format-agnostic tabular dataset library, written in Python. It allows you to import, export, and manipulate tabular data sets. Advanced features include, segregation, dynamic columns, tags & filtering, and seamless format import & export.
+
+ Tablib is an MIT Licensed format-agnostic tabular dataset library, written in Python. It allows you to import, export, and manipulate tabular data sets. Advanced features include, segregation, dynamic columns, tags & filtering, and seamless format import & export.
+
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/api.rst b/tasks/tasksmith-b6d969373e1e/tests/source/docs/api.rst
new file mode 100644
index 0000000000000000000000000000000000000000..9d915590df37ddb48b1ae1442227c34c5db400eb
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/api.rst
@@ -0,0 +1,52 @@
+.. _api:
+
+===
+API
+===
+
+
+.. module:: tablib
+
+This part of the documentation covers all the interfaces of Tablib. For
+parts where Tablib depends on external libraries, we document the most
+important right here and provide links to the canonical documentation.
+
+
+--------------
+Dataset Object
+--------------
+
+
+.. autoclass:: Dataset
+ :inherited-members:
+
+
+---------------
+Databook Object
+---------------
+
+
+.. autoclass:: Databook
+ :inherited-members:
+
+
+---------
+Functions
+---------
+
+
+.. autofunction:: detect_format
+
+.. autofunction:: import_set
+
+
+----------
+Exceptions
+----------
+
+
+.. automodule:: tablib.exceptions
+ :members:
+
+
+Now, go start some :ref:`Tablib Development `.
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/conf.py b/tasks/tasksmith-b6d969373e1e/tests/source/docs/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea3e45c40317d0db67f6ea4471790068b538e8b2
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/conf.py
@@ -0,0 +1,230 @@
+#
+# Tablib documentation build configuration file, created by
+# sphinx-quickstart on Tue Oct 5 15:25:21 2010.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+import tablib
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+# sys.path.insert(0, os.path.abspath('..'))
+# -- General configuration -----------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+# needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = [
+ 'sphinx.ext.autodoc', 'sphinx.ext.todo', 'sphinx.ext.coverage',
+ 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx'
+]
+intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+# source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = 'Tablib'
+copyright = '2019 Jazzband'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The full version, including alpha/beta/rc tags.
+release = tablib.__version__
+# The short X.Y version.
+version = '.'.join(tablib.__version__.split('.')[:2])
+# for example take major/minor
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+# language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+# today = ''
+# Else, today_fmt is used as the format for a strftime call.
+# today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+# default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+# add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+# show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+# pygments_style = ''
+
+# A list of ignored prefixes for module index sorting.
+# modindex_common_prefix = []
+
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+html_theme = 'alabaster'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+# html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+# html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# " v documentation".
+# html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+# html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+# html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+# html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+# html_static_path = ['static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+# html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+html_sidebars = {
+ 'index': ['sidebarintro.html', 'sourcelink.html', 'searchbox.html'],
+ '**': ['sidebarlogo.html', 'localtoc.html', 'relations.html',
+ 'sourcelink.html', 'searchbox.html']
+}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+# html_additional_pages = {}
+
+# If false, no module index is generated.
+# html_domain_indices = True
+
+# If false, no index is generated.
+# html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+# html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+html_show_sphinx = False
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+# html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+# html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+# html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'Tablibdoc'
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+# The paper size ('letter' or 'a4').
+# latex_paper_size = 'letter'
+
+# The font size ('10pt', '11pt' or '12pt').
+# latex_font_size = '10pt'
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+ ('index', 'Tablib.tex', 'Tablib Documentation',
+ 'Jazzband', 'manual'),
+]
+
+latex_use_modindex = False
+
+latex_elements = {
+ 'papersize': 'a4paper',
+ 'pointsize': '12pt',
+}
+latex_use_parts = True
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+# latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+# latex_use_parts = False
+
+# If true, show page references after internal links.
+# latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+# latex_show_urls = False
+
+# Additional stuff for the LaTeX preamble.
+# latex_preamble = ''
+
+# Documents to append as an appendix to all manuals.
+# latex_appendices = []
+
+# If false, no module index is generated.
+# latex_domain_indices = True
+
+
+# -- Options for manual page output --------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ ('index', 'tablib', 'Tablib Documentation',
+ ['Jazzband'], 1)
+]
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/development.rst b/tasks/tasksmith-b6d969373e1e/tests/source/docs/development.rst
new file mode 100644
index 0000000000000000000000000000000000000000..08c7502e3e78148aea7036b52340a827431534d5
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/development.rst
@@ -0,0 +1,214 @@
+.. _development:
+
+Development
+===========
+
+Tablib is under active development, and contributors are welcome.
+
+If you have a feature request, suggestion, or bug report, please open a new
+issue on GitHub_. To submit patches, please send a pull request on GitHub_.
+
+.. _GitHub: https://github.com/jazzband/tablib/
+
+
+
+.. _design:
+
+---------------------
+Design Considerations
+---------------------
+
+Tablib was developed with a few :pep:`20` idioms in mind.
+
+#. Beautiful is better than ugly.
+#. Explicit is better than implicit.
+#. Simple is better than complex.
+#. Complex is better than complicated.
+#. Readability counts.
+
+A few other things to keep in mind:
+
+#. Keep your code DRY.
+#. Strive to be as simple (to use) as possible.
+
+.. _scm:
+
+--------------
+Source Control
+--------------
+
+
+Tablib source is controlled with Git_, the lean, mean, distributed source
+control machine.
+
+The repository is publicly accessible.
+
+.. code-block:: console
+
+ git clone git://github.com/jazzband/tablib.git
+
+The project is hosted on **GitHub**.
+
+ GitHub:
+ https://github.com/jazzband/tablib
+
+
+Git Branch Structure
+++++++++++++++++++++
+
+Feature / Hotfix / Release branches follow a `Successful Git Branching Model`_ .
+Git-flow_ is a great tool for managing the repository. I highly recommend it.
+
+``master``
+ Current production release (|version|) on PyPi.
+
+Each release is tagged.
+
+When submitting patches, please place your feature/change in its own branch prior to opening a pull request on GitHub_.
+
+
+.. _Git: https://git-scm.org
+.. _`Successful Git Branching Model`: https://nvie.com/posts/a-successful-git-branching-model/
+.. _git-flow: https://github.com/nvie/gitflow
+
+
+.. _newformats:
+
+------------------
+Adding New Formats
+------------------
+
+Tablib welcomes new format additions! Format suggestions include:
+
+* MySQL Dump
+
+
+Coding by Convention
+++++++++++++++++++++
+
+Tablib features a micro-framework for adding format support.
+The easiest way to understand it is to use it.
+So, let's define our own format, named *xxx*.
+
+From version 1.0, Tablib formats are class-based and can be dynamically
+registered.
+
+1. Write your custom format class::
+
+ class MyXXXFormatClass:
+ title = 'xxx'
+
+ @classmethod
+ def export_set(cls, dset):
+ ....
+ # returns string representation of given dataset
+
+ @classmethod
+ def export_book(cls, dbook):
+ ....
+ # returns string representation of given databook
+
+ @classmethod
+ def import_set(cls, dset, in_stream):
+ ...
+ # populates given Dataset with given datastream
+
+ @classmethod
+ def import_book(cls, dbook, in_stream):
+ ...
+ # returns Databook instance
+
+ @classmethod
+ def detect(cls, stream):
+ ...
+ # returns True if given stream is parsable as xxx
+
+ .. admonition:: Excluding Support
+
+ If the format excludes support for an import/export mechanism (*e.g.*
+ :class:`csv ` excludes
+ :class:`Databook ` support),
+ simply don't define the respective class methods.
+ Appropriate errors will be raised.
+
+2. Register your class::
+
+ from tablib.formats import registry
+
+ registry.register('xxx', MyXXXFormatClass())
+
+3. From then on, you should be able to use your new custom format as if it were
+a built-in Tablib format, e.g. using ``dataset.export('xxx')`` will use the
+``MyXXXFormatClass.export_set`` method.
+
+.. _testing:
+
+--------------
+Testing Tablib
+--------------
+
+Testing is crucial to Tablib's stability.
+This stable project is used in production by many companies and developers,
+so it is important to be certain that every version released is fully operational.
+When developing a new feature for Tablib, be sure to write proper tests for it as well.
+
+When developing a feature for Tablib,
+the easiest way to test your changes for potential issues is to simply run the test suite directly.
+
+.. code-block:: console
+
+ $ tox
+
+----------------------
+Continuous Integration
+----------------------
+
+Every pull request is automatically tested and inspected upon receipt with `GitHub Actions`_.
+If you broke the build, you will receive an email accordingly.
+
+Anyone may view the build status and history at any time.
+
+ https://github.com/jazzband/tablib/actions
+
+Additional reports will also be included here in the future, including :pep:`8` checks and stress reports for extremely large datasets.
+
+.. _`GitHub Actions`: https://github.com/jazzband/tablib/actions
+
+
+.. _docs:
+
+-----------------
+Building the Docs
+-----------------
+
+Documentation is written in the powerful, flexible,
+and standard Python documentation format, `reStructured Text`_.
+Documentation builds are powered by the powerful Pocoo project, Sphinx_.
+The :ref:`API Documentation ` is mostly documented inline throughout the module.
+
+The Docs live in ``tablib/docs``.
+In order to build them, you will first need to install Sphinx.
+
+.. code-block:: console
+
+ $ pip install sphinx
+
+
+Then, to build an HTML version of the docs, simply run the following from the ``docs`` directory:
+
+.. code-block:: console
+
+ $ make html
+
+Your ``docs/_build/html`` directory will then contain an HTML representation of the documentation,
+ready for publication on most web servers.
+
+You can also generate the documentation in **epub**, **latex**, **json**, *&c* similarly.
+
+.. _`reStructured Text`: http://docutils.sourceforge.net/rst.html
+.. _Sphinx: http://sphinx.pocoo.org
+.. _`GitHub Pages`: https://pages.github.com
+
+----------
+
+Make sure to check out the :ref:`API Documentation `.
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/formats.rst b/tasks/tasksmith-b6d969373e1e/tests/source/docs/formats.rst
new file mode 100644
index 0000000000000000000000000000000000000000..be7f8c56de0e4508ca2594343845203b7cf9cf93
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/formats.rst
@@ -0,0 +1,347 @@
+.. _formats:
+
+=======
+Formats
+=======
+
+Tablib supports a wide variety of different tabular formats, both for input and
+output. Moreover, you can :ref:`register your own formats `.
+
+cli
+===
+
+The ``cli`` format is currently export-only. The exports produce a representation
+table suited to a terminal.
+
+When exporting to a CLI you can pass the table format with the ``tablefmt``
+parameter, the supported formats are::
+
+ >>> import tabulate
+ >>> list(tabulate._table_formats)
+ ['simple', 'plain', 'grid', 'fancy_grid', 'github', 'pipe', 'orgtbl',
+ 'jira', 'presto', 'psql', 'rst', 'mediawiki', 'moinmoin', 'youtrack',
+ 'html', 'latex', 'latex_raw', 'latex_booktabs', 'tsv', 'textile']
+
+For example::
+
+ dataset.export("cli", tablefmt="github")
+ dataset.export("cli", tablefmt="grid")
+
+This format is optional, install Tablib with ``pip install "tablib[cli]"`` to
+make the format available.
+
+csv
+===
+
+When you import CSV data, you can specify if the first line of your data source
+is headers with the ``headers`` boolean parameter (defaults to ``True``)::
+
+ import tablib
+
+ tablib.import_set(your_data_stream, format='csv', headers=False)
+
+It is also possible to provide the ``skip_lines`` parameter for the number of
+lines that should be skipped before starting to read data.
+
+.. versionchanged:: 3.1.0
+
+ The ``skip_lines`` parameter was added.
+
+When exporting with the ``csv`` format, the top row will contain headers, if
+they have been set. Otherwise, the top row will contain the first row of the
+dataset.
+
+When importing a CSV data source or exporting a dataset as CSV, you can pass any
+parameter supported by the :py:func:`csv.reader` and :py:func:`csv.writer`
+functions. For example::
+
+ tablib.import_set(your_data_stream, format='csv', dialect='unix')
+
+ dataset.export('csv', delimiter=' ', quotechar='|')
+
+.. admonition:: Line endings
+
+ Exporting uses \\r\\n line endings by default so, make sure to include
+ ``newline=''`` otherwise you will get a blank line between each row
+ when you open the file in Excel::
+
+ with open('output.csv', 'w', newline='') as f:
+ f.write(dataset.export('csv'))
+
+ If you do not do this, and you export the file on Windows, your
+ CSV file will open in Excel with a blank line between each row.
+
+dbf
+===
+
+Import/export using the dBASE_ format.
+
+.. admonition:: Binary Warning
+
+ The ``dbf`` format contains binary data, so make sure to write in binary
+ mode::
+
+ with open('output.dbf', 'wb') as f:
+ f.write(dataset.export('dbf')
+
+.. _dBASE: https://en.wikipedia.org/wiki/DBase
+
+df (DataFrame)
+==============
+
+Import/export using the pandas_ DataFrame format. This format is optional,
+install Tablib with ``pip install "tablib[pandas]"`` to make the format available.
+
+.. _pandas: https://pandas.pydata.org/
+
+html
+====
+
+The exports produce an HTML page with the data in a ``
``. If headers have
+been set, they will be used as table headers (``thead``).
+
+When you import HTML, you can specify a specific table to import by providing
+the ``table_id`` argument::
+
+ import tablib
+
+ tablib.import_set(your_html, format='html', table_id='some_table_id')
+
+Otherwise, the first table found will be imported.
+
+.. versionchanged:: 3.6.0
+
+ The ability to import HTML was added. The dependency on MarkupPy was dropped.
+
+jira
+====
+
+The ``jira`` format is currently export-only. Exports format the dataset
+according to the Jira table syntax::
+
+ ||heading 1||heading 2||heading 3||
+ |col A1|col A2|col A3|
+ |col B1|col B2|col B3|
+
+json
+====
+
+Import/export using the JSON_ format. If headers have been set, a JSON list of
+objects will be returned. If no headers have been set, a JSON list of lists
+(rows) will be returned instead.
+
+Import assumes (for now) that headers exist.
+
+.. _JSON: http://json.org/
+
+latex
+=====
+
+Import/export using the LaTeX_ format. This format is export-only.
+If a title has been set, it will be exported as the table caption.
+
+.. _LaTeX: https://www.latex-project.org/
+
+ods
+===
+
+Import/export data in OpenDocument Spreadsheet format.
+
+.. versionadded:: 3.6.0
+
+ Import functionality was added.
+
+This format is optional, install Tablib with ``pip install "tablib[ods]"`` to
+make the format available.
+
+The ``import_set()`` method also supports a ``skip_lines`` parameter that you
+can set to a number of lines that should be skipped before starting to read
+data.
+
+.. admonition:: Binary Warning
+
+ :class:`Dataset.ods` contains binary data, so make sure to write in binary mode::
+
+ with open('output.ods', 'wb') as f:
+ f.write(data.ods)
+
+rst
+===
+
+Export data as a reStructuredText_ table representation of a dataset. The
+``rst`` format is export-only.
+
+Exporting returns a simple table if the text in the first column is never
+wrapped, otherwise returns a grid table::
+
+ >>> from tablib import Dataset
+ >>> bits = ((0, 0), (1, 0), (0, 1), (1, 1))
+ >>> data = Dataset()
+ >>> data.headers = ['A', 'B', 'A and B']
+ >>> for a, b in bits:
+ ... data.append([bool(a), bool(b), bool(a * b)])
+ >>> table = data.export('rst')
+ >>> table.split('\\n') == [
+ ... '===== ===== =====',
+ ... ' A B A and',
+ ... ' B ',
+ ... '===== ===== =====',
+ ... 'False False False',
+ ... 'True False False',
+ ... 'False True False',
+ ... 'True True True ',
+ ... '===== ===== =====',
+ ... ]
+ True
+
+.. _reStructuredText: http://docutils.sourceforge.net/rst.html
+
+tsv
+===
+
+A variant of the csv_ format with tabulators as fields separators.
+
+xls
+===
+
+Import/export data in Legacy Excel Spreadsheet representation.
+
+This format is optional, install Tablib with ``pip install "tablib[xls]"`` to
+make the format available.
+
+Its ``import_set()`` method also supports a ``skip_lines`` parameter that you
+can set to a number of lines that should be skipped before starting to read
+data.
+
+.. versionchanged:: 3.1.0
+
+ The ``skip_lines`` parameter for ``import_set()`` was added.
+
+.. note::
+
+ XLS files are limited to a maximum of 65,000 rows. Use xlsx_ to avoid this
+ limitation.
+
+.. admonition:: Binary Warning
+
+ The ``xls`` file format is binary, so make sure to write in binary mode::
+
+ with open('output.xls', 'wb') as f:
+ f.write(data.export('xls'))
+
+xlsx
+====
+
+Import/export data in Excel 07+ Spreadsheet representation.
+
+This format is optional, install Tablib with ``pip install "tablib[xlsx]"`` to
+make the format available.
+
+The ``import_set()`` and ``import_book()`` methods accept keyword
+argument ``read_only``. If its value is ``True`` (the default), the
+XLSX data source is read lazily. Lazy reading generally reduces time
+and memory consumption, especially for large spreadsheets. However,
+it relies on the XLSX data source declaring correct dimensions. Some
+programs generate XLSX files with incorrect dimensions. Such files
+may need to be loaded with this optimization turned off by passing
+``read_only=False``.
+
+The ``import_set()`` method also supports a ``skip_lines`` parameter that you
+can set to a number of lines that should be skipped before starting to read
+data.
+
+The ``export_set()`` method supports a ``column_width`` parameter. Depending
+on the value passed, the column width will be set accordingly. It can be
+either ``None``, an integer, or default "adaptive". If "adaptive" is passed,
+the column width will be unique and will be calculated based on values' length.
+For example::
+
+ data = tablib.Dataset()
+ data.export('xlsx', column_width='adaptive')
+
+This works with ``Databook`` as well::
+
+ data = tablib.Databook()
+ data.export('xlsx', column_width='adaptive')
+
+The adaptive width will be calculated for each sheet in the databook.
+
+.. versionchanged:: 3.8.0
+ The ``column_width`` parameter for ``export_set()`` was added.
+
+.. versionchanged:: 3.1.0
+
+ The ``skip_lines`` parameter for ``import_set()`` was added.
+
+.. note::
+
+ When reading an ``xlsx`` file containing formulas in its cells, Tablib will
+ read the cell values, not the cell formulas.
+
+.. versionchanged:: 2.0.0
+
+ Reads cell values instead of formulas.
+
+You can export data to xlsx format by calling :meth:`export('xlsx') <.export>`.
+There are optional parameters to control the export.
+For available parameters, see :meth:`tablib.formats._xlsx.XLSXFormat.export_set`.
+
+.. admonition:: Binary Warning
+
+ The ``xlsx`` file format is binary, so make sure to write in binary mode::
+
+ with open('output.xlsx', 'wb') as f:
+ f.write(data.export('xlsx'))
+
+yaml
+====
+
+Import/export data in the YAML_ format.
+When exporting, if headers have been set, a YAML list of objects will be
+returned. If no headers have been set, a YAML list of lists (rows) will be
+returned instead.
+
+Import assumes (for now) that headers exist.
+
+This format is optional, install Tablib with ``pip install "tablib[yaml]"`` to
+make the format available.
+
+.. _YAML: https://yaml.org
+
+sql
+===
+
+.. versionadded:: 3.9.0
+
+The ``sql`` format is export-only. It produces SQL INSERT statements (one per row)
+assuming the target table already exists with the same columns.
+The table name can be passed as an argument or will be taken from the dataset's title (or defaults to ``export_table``).
+Columns can be passed as an argument or will be taken from the dataset's headers.
+Values are rendered as ANSI SQL literals.
+Additionally the argument ``commit`` can be passed to add a ``COMMIT;`` statement at the end.
+
+- ``NULL`` for null values
+- ``TRUE``/``FALSE`` for booleans
+- ``DATE 'YYYY-MM-DD'`` for date values
+- ``TIMESTAMP 'YYYY-MM-DD HH:MM:SS'`` for timestamp values
+- Numeric literals for ints/floats/decimals
+- Single-quoted strings with embedded quotes escaped
+
+Example::
+
+ import datetime
+ from tablib import Dataset
+
+ data = Dataset(title='users')
+ data.headers = ['id', 'name', 'joined']
+ data.append([1, 'Alice', datetime.date(2021,1,1)])
+
+ print(data.export('sql'))
+ print(data.export('sql', table='\"User_Updates\"', columns=['id', 'username', 'update_date'], commit=True))
+
+Output::
+
+ INSERT INTO users (id,name,joined) VALUES (1, 'Alice', DATE '2021-01-01');
+
+ INSERT INTO "User_Updates" (id,username,update_date) VALUES (1, 'Alice', DATE '2021-01-01');
+ COMMIT;
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/index.rst b/tasks/tasksmith-b6d969373e1e/tests/source/docs/index.rst
new file mode 100644
index 0000000000000000000000000000000000000000..8bf4ac990bf00e5a4f8d486e176ce29c0a874979
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/index.rst
@@ -0,0 +1,121 @@
+.. Tablib documentation master file, created by
+ sphinx-quickstart on Tue Oct 5 15:25:21 2010.
+ You can adapt this file completely to your liking, but it should at least
+ contain the root ``toctree`` directive.
+
+Tablib: Pythonic Tabular Datasets
+=================================
+
+Release v\ |version|. (:ref:`Installation `)
+
+.. Contents:
+..
+.. .. toctree::
+.. :maxdepth: 2
+..
+
+.. Indices and tables
+.. ==================
+..
+.. * :ref:`genindex`
+.. * :ref:`modindex`
+.. * :ref:`search`
+
+
+Tablib is an `MIT Licensed `_ format-agnostic tabular dataset library, written in Python.
+It allows you to import, export, and manipulate tabular data sets.
+Advanced features include segregation, dynamic columns, tags & filtering,
+and seamless format import & export.
+
+::
+
+ >>> data = tablib.Dataset(headers=['First Name', 'Last Name', 'Age'])
+ >>> for i in [('Kenneth', 'Reitz', 22), ('Bessie', 'Monke', 21)]:
+ ... data.append(i)
+
+
+ >>> print(data.export('json'))
+ [{"Last Name": "Reitz", "First Name": "Kenneth", "Age": 22}, {"Last Name": "Monke", "First Name": "Bessie", "Age": 21}]
+
+ >>> print(data.export('yaml'))
+ - {Age: 22, First Name: Kenneth, Last Name: Reitz}
+ - {Age: 21, First Name: Bessie, Last Name: Monke}
+
+ >>> data.export('xlsx')
+
+
+ >>> data.export('df')
+ First Name Last Name Age
+ 0 Kenneth Reitz 22
+ 1 Bessie Monke 21
+
+
+Testimonials
+------------
+
+`National Geographic `_,
+`Digg, Inc `_,
+`Northrop Grumman `_,
+`Discovery Channel `_,
+and `The Sunlight Foundation `_ use Tablib internally.
+
+
+
+**Greg Thorton**
+ Tablib by @kennethreitz saved my life.
+ I had to consolidate like 5 huge poorly maintained lists of domains and data.
+ It was a breeze!
+
+**Dave Coutts**
+ It's turning into one of my most used modules of 2010.
+ You really hit a sweet spot for managing tabular data with a minimal amount of code and effort.
+
+**Joshua Ourisman**
+ Tablib has made it so much easier to deal with the inevitable 'I want an Excel file!' requests from clients...
+
+**Brad Montgomery**
+ I think you nailed the "Python Zen" with tablib.
+ Thanks again for an awesome lib!
+
+
+User's Guide
+------------
+
+This part of the documentation, which is mostly prose, begins with some background information about Tablib, then focuses on step-by-step instructions for getting the most out of your datasets.
+
+.. toctree::
+ :maxdepth: 2
+
+ intro
+
+.. toctree::
+ :maxdepth: 2
+
+ install
+
+.. toctree::
+ :maxdepth: 2
+
+ tutorial
+
+.. toctree::
+ :maxdepth: 2
+
+ formats
+
+.. toctree::
+ :maxdepth: 2
+
+ development
+
+
+API Reference
+-------------
+
+If you are looking for information on a specific function, class or
+method, this part of the documentation is for you.
+
+.. toctree::
+ :maxdepth: 2
+
+ api
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/install.rst b/tasks/tasksmith-b6d969373e1e/tests/source/docs/install.rst
new file mode 100644
index 0000000000000000000000000000000000000000..e3cb3f30546522fad6ae71b223287e1f01062ab3
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/install.rst
@@ -0,0 +1,85 @@
+.. _install:
+
+Installation
+============
+
+This part of the documentation covers the installation of Tablib. The first step to using any software package is getting it properly installed.
+
+
+.. _installing:
+
+-----------------
+Installing Tablib
+-----------------
+
+Distribute & Pip
+----------------
+
+Of course, the recommended way to install Tablib is with `pip `_:
+
+.. code-block:: console
+
+ $ pip install tablib
+
+You can also choose to install more dependencies to have more import/export
+formats available:
+
+.. code-block:: console
+
+ $ pip install "tablib[xlsx]"
+
+Or all possible formats:
+
+.. code-block:: console
+
+ $ pip install "tablib[all]"
+
+which is equivalent to:
+
+.. code-block:: console
+
+ $ pip install "tablib[html, pandas, ods, xls, xlsx, yaml]"
+
+-------------------
+Download the Source
+-------------------
+
+You can also install Tablib from source.
+The latest release (|version|) is available from GitHub.
+
+* tarball_
+* zipball_
+
+.. _
+
+Once you have a copy of the source,
+you can embed it in your Python package,
+or install it into your site-packages easily.
+
+.. code-block:: console
+
+ $ python setup.py install
+
+
+To download the full source history from Git, see :ref:`Source Control `.
+
+.. _tarball: https://github.com/jazzband/tablib/tarball/master
+.. _zipball: https://github.com/jazzband/tablib/zipball/master
+
+
+.. _updates:
+
+Staying Updated
+---------------
+
+The latest version of Tablib will always be available here:
+
+* PyPI: https://pypi.org/project/tablib/
+* GitHub: https://github.com/jazzband/tablib/
+
+When a new version is available, upgrading is simple::
+
+ $ pip install tablib --upgrade
+
+
+Now, go get a :ref:`Quick Start `.
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/intro.rst b/tasks/tasksmith-b6d969373e1e/tests/source/docs/intro.rst
new file mode 100644
index 0000000000000000000000000000000000000000..cec9947798c3016776f0d9218da7dedf9560a30a
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/intro.rst
@@ -0,0 +1,55 @@
+.. _intro:
+
+Introduction
+============
+
+This part of the documentation covers all the interfaces of Tablib.
+Tablib is a format-agnostic tabular dataset library, written in Python.
+It allows you to Pythonically import, export, and manipulate tabular data sets.
+Advanced features include segregation, dynamic columns, tags/filtering, and
+seamless format import/export.
+
+
+Philosophy
+----------
+
+Tablib was developed with a few :pep:`20` idioms in mind.
+
+#. Beautiful is better than ugly.
+#. Explicit is better than implicit.
+#. Simple is better than complex.
+#. Complex is better than complicated.
+#. Readability counts.
+
+All contributions to Tablib should keep these important rules in mind.
+
+.. _license:
+
+Tablib License
+--------------
+
+Tablib is released under terms of `The MIT License`_.
+
+Copyright 2017 Kenneth Reitz
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+.. _`The MIT License`: https://opensource.org/licenses/mit-license.php
+
+Now, go :ref:`install Tablib `.
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/krstyle.sty b/tasks/tasksmith-b6d969373e1e/tests/source/docs/krstyle.sty
new file mode 100644
index 0000000000000000000000000000000000000000..b2d073d061322997abe6e60cf028dd657c9b190d
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/krstyle.sty
@@ -0,0 +1,118 @@
+\definecolor{TitleColor}{rgb}{0,0,0}
+\definecolor{InnerLinkColor}{rgb}{0,0,0}
+
+\renewcommand{\maketitle}{%
+ \begin{titlepage}%
+ \let\footnotesize\small
+ \let\footnoterule\relax
+ \ifsphinxpdfoutput
+ \begingroup
+ % This \def is required to deal with multi-line authors; it
+ % changes \\ to ', ' (comma-space), making it pass muster for
+ % generating document info in the PDF file.
+ \def\\{, }
+ \pdfinfo{
+ /Author (\@author)
+ /Title (\@title)
+ }
+ \endgroup
+ \fi
+ \begin{flushright}%
+ %\sphinxlogo%
+ {\center
+ \vspace*{3cm}
+ \includegraphics{logo.pdf}
+ \vspace{3cm}
+ \par
+ {\rm\Huge \@title \par}%
+ {\em\LARGE \py@release\releaseinfo \par}
+ {\large
+ \@date \par
+ \py@authoraddress \par
+ }}%
+ \end{flushright}%\par
+ \@thanks
+ \end{titlepage}%
+ \cleardoublepage%
+ \setcounter{footnote}{0}%
+ \let\thanks\relax\let\maketitle\relax
+ %\gdef\@thanks{}\gdef\@author{}\gdef\@title{}
+}
+
+\fancypagestyle{normal}{
+ \fancyhf{}
+ \fancyfoot[LE,RO]{{\thepage}}
+ \fancyfoot[LO]{{\nouppercase{\rightmark}}}
+ \fancyfoot[RE]{{\nouppercase{\leftmark}}}
+ \fancyhead[LE,RO]{{ \@title, \py@release}}
+ \renewcommand{\headrulewidth}{0.4pt}
+ \renewcommand{\footrulewidth}{0.4pt}
+}
+
+\fancypagestyle{plain}{
+ \fancyhf{}
+ \fancyfoot[LE,RO]{{\thepage}}
+ \renewcommand{\headrulewidth}{0pt}
+ \renewcommand{\footrulewidth}{0.4pt}
+}
+
+\titleformat{\section}{\Large}%
+ {\py@TitleColor\thesection}{0.5em}{\py@TitleColor}{\py@NormalColor}
+\titleformat{\subsection}{\large}%
+ {\py@TitleColor\thesubsection}{0.5em}{\py@TitleColor}{\py@NormalColor}
+\titleformat{\subsubsection}{}%
+ {\py@TitleColor\thesubsubsection}{0.5em}{\py@TitleColor}{\py@NormalColor}
+\titleformat{\paragraph}{\large}%
+ {\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor}
+
+\ChNameVar{\raggedleft\normalsize}
+\ChNumVar{\raggedleft \bfseries\Large}
+\ChTitleVar{\raggedleft \rm\Huge}
+
+\renewcommand\thepart{\@Roman\c@part}
+\renewcommand\part{%
+ \pagestyle{empty}
+ \if@noskipsec \leavevmode \fi
+ \cleardoublepage
+ \vspace*{6cm}%
+ \@afterindentfalse
+ \secdef\@part\@spart}
+
+\def\@part[#1]#2{%
+ \ifnum \c@secnumdepth >\m@ne
+ \refstepcounter{part}%
+ \addcontentsline{toc}{part}{\thepart\hspace{1em}#1}%
+ \else
+ \addcontentsline{toc}{part}{#1}%
+ \fi
+ {\parindent \z@ %\center
+ \interlinepenalty \@M
+ \normalfont
+ \ifnum \c@secnumdepth >\m@ne
+ \rm\Large \partname~\thepart
+ \par\nobreak
+ \fi
+ \MakeUppercase{\rm\Huge #2}%
+ \markboth{}{}\par}%
+ \nobreak
+ \vskip 8ex
+ \@afterheading}
+\def\@spart#1{%
+ {\parindent \z@ %\center
+ \interlinepenalty \@M
+ \normalfont
+ \huge \bfseries #1\par}%
+ \nobreak
+ \vskip 3ex
+ \@afterheading}
+
+% use inconsolata font
+\usepackage{inconsolata}
+
+% fix single quotes, for inconsolata. (does not work)
+%%\usepackage{textcomp}
+%%\begingroup
+%% \catcode`'=\active
+%% \g@addto@macro\@noligs{\let'\textsinglequote}
+%% \endgroup
+%%\endinput
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/requirements.txt b/tasks/tasksmith-b6d969373e1e/tests/source/docs/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b6ff2b54006ededf10dabdf0826dd55d0c692096
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/requirements.txt
@@ -0,0 +1 @@
+sphinx==9.1.0
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/docs/tutorial.rst b/tasks/tasksmith-b6d969373e1e/tests/source/docs/tutorial.rst
new file mode 100644
index 0000000000000000000000000000000000000000..e4c2ae6f9730e29acc7413147219c54db715ec63
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/docs/tutorial.rst
@@ -0,0 +1,423 @@
+.. _quickstart:
+
+==========
+Quickstart
+==========
+
+
+Eager to get started?
+This page gives a good introduction in how to get started with Tablib.
+This assumes you already have Tablib installed.
+If you do not, head over to the :ref:`Installation ` section.
+
+First, make sure that:
+
+* Tablib is :ref:`installed `
+* Tablib is :ref:`up-to-date `
+
+
+Let's get started with some simple use cases and examples.
+
+
+
+------------------
+Creating a Dataset
+------------------
+
+
+A :class:`Dataset ` is nothing more than what its name implies—a set of data.
+
+Creating your own instance of the :class:`tablib.Dataset` object is simple. ::
+
+ data = tablib.Dataset()
+
+You can now start filling this :class:`Dataset ` object with data.
+
+.. admonition:: Example Context
+
+ From here on out, if you see ``data``, assume that it's a fresh
+ :class:`Dataset ` object.
+
+
+
+-----------
+Adding Rows
+-----------
+
+
+Let's say you want to collect a simple list of names. ::
+
+ # collection of names
+ names = ['Kenneth Reitz', 'Bessie Monke']
+
+ for name in names:
+ # split name appropriately
+ fname, lname = name.split()
+
+ # add names to Dataset
+ data.append([fname, lname])
+
+You can get a nice, Pythonic view of the dataset at any time with :class:`Dataset.dict`::
+
+ >>> data.dict
+ [('Kenneth', 'Reitz'), ('Bessie', 'Monke')]
+
+
+
+--------------
+Adding Headers
+--------------
+
+
+It's time to enhance our :class:`Dataset` by giving our columns some titles.
+To do so, set :class:`Dataset.headers`. ::
+
+ data.headers = ['First Name', 'Last Name']
+
+Now our data looks a little different. ::
+
+ >>> data.dict
+ [{'Last Name': 'Reitz', 'First Name': 'Kenneth'},
+ {'Last Name': 'Monke', 'First Name': 'Bessie'}]
+
+
+
+
+--------------
+Adding Columns
+--------------
+
+
+Now that we have a basic :class:`Dataset` in place, let's add a column of **ages** to it. ::
+
+ data.append_col([22, 20], header='Age')
+
+Let's view the data now. ::
+
+ >>> data.dict
+ [{'Last Name': 'Reitz', 'First Name': 'Kenneth', 'Age': 22},
+ {'Last Name': 'Monke', 'First Name': 'Bessie', 'Age': 20}]
+
+It's that easy.
+
+
+--------------
+Importing Data
+--------------
+Creating a :class:`tablib.Dataset` object by importing a pre-existing file is simple. ::
+
+ with open('data.csv', 'r') as fh:
+ imported_data = Dataset().load(fh)
+
+This detects what sort of data is being passed in, and uses an appropriate formatter to do the import. So you can import from a variety of different file types.
+
+.. admonition:: Source without headers
+
+ When the format is :class:`csv `, :class:`tsv `, :class:`dbf `, :class:`xls ` or :class:`xlsx `, and the data source does not have headers, the import should be done as follows ::
+
+ with open('data.csv', 'r') as fh:
+ imported_data = Dataset().load(fh, headers=False)
+
+--------------
+Exporting Data
+--------------
+
+Tablib's killer feature is the ability to export your :class:`Dataset` objects into a number of formats.
+
+**Comma-Separated Values** ::
+
+ >>> data.export('csv')
+ Last Name,First Name,Age
+ Reitz,Kenneth,22
+ Monke,Bessie,20
+
+**JavaScript Object Notation** ::
+
+ >>> data.export('json')
+ [{"Last Name": "Reitz", "First Name": "Kenneth", "Age": 22}, {"Last Name": "Monke", "First Name": "Bessie", "Age": 20}]
+
+
+**YAML Ain't Markup Language** ::
+
+ >>> data.export('yaml')
+ - {Age: 22, First Name: Kenneth, Last Name: Reitz}
+ - {Age: 20, First Name: Bessie, Last Name: Monke}
+
+
+**Microsoft Excel** ::
+
+ >>> data.export('xls')
+
+
+
+**Pandas DataFrame** ::
+
+ >>> data.export('df')
+ First Name Last Name Age
+ 0 Kenneth Reitz 22
+ 1 Bessie Monke 21
+
+
+------------------------
+Selecting Rows & Columns
+------------------------
+
+
+You can slice and dice your data, just like a standard Python list. ::
+
+ >>> data[0]
+ ('Kenneth', 'Reitz', 22)
+ >>> data[0:2]
+ [('Kenneth', 'Reitz', 22), ('Bessie', 'Monke', 20)]
+
+You can also access a row using its index without slicing. ::
+
+ >>> data.get(0)
+ ('Kenneth', 'Reitz', 22)
+
+If we had a set of data consisting of thousands of rows,
+it could be useful to get a list of values in a column.
+To do so, we access the :class:`Dataset` as if it were a standard Python dictionary. ::
+
+ >>> data['First Name']
+ ['Kenneth', 'Bessie']
+
+You can also access the column using its index. ::
+
+ >>> data.headers
+ ['Last Name', 'First Name', 'Age']
+ >>> data.get_col(1)
+ ['Kenneth', 'Bessie']
+
+Let's find the average age. ::
+
+ >>> ages = data['Age']
+ >>> float(sum(ages)) / len(ages)
+ 21.0
+
+
+
+-----------------------
+Removing Rows & Columns
+-----------------------
+
+It's easier than you could imagine. Delete a column::
+
+ >>> del data['Col Name']
+
+Delete a range of rows::
+
+ >>> del data[0:12]
+
+
+==============
+Advanced Usage
+==============
+
+This part of the documentation services to give you an idea that are otherwise hard to extract from the :ref:`API Documentation `.
+
+And now for something completely different.
+
+
+.. _dyncols:
+
+---------------
+Dynamic Columns
+---------------
+
+Thanks to Josh Ourisman, Tablib now supports adding dynamic columns.
+A dynamic column is a single callable object (*e.g.* a function).
+
+Let's add a dynamic column to our :class:`Dataset` object.
+In this example, we have a function that generates a random grade for our students. ::
+
+ import random
+
+ def random_grade(row):
+ """Returns a random integer for entry."""
+ return (random.randint(60,100)/100.0)
+
+ data.append_col(random_grade, header='Grade')
+
+Let's have a look at our data. ::
+
+ >>> data.export('yaml')
+ - {Age: 22, First Name: Kenneth, Grade: 0.6, Last Name: Reitz}
+ - {Age: 20, First Name: Bessie, Grade: 0.75, Last Name: Monke}
+
+
+Let's remove that column. ::
+
+ >>> del data['Grade']
+
+
+When you add a dynamic column, the first argument that is passed in to the given callable is the current data row.
+You can use this to perform calculations against your data row.
+
+For example, we can use the data available in the row to guess the gender of a student. ::
+
+ def guess_gender(row):
+ """Calculates gender of given student data row."""
+ m_names = ('Kenneth', 'Mike', 'Yuri')
+ f_names = ('Bessie', 'Samantha', 'Heather')
+
+ name = row[0]
+
+ if name in m_names:
+ return 'Male'
+ elif name in f_names:
+ return 'Female'
+ else:
+ return 'Unknown'
+
+Adding this function to our dataset as a dynamic column would result in: ::
+
+ >>> data.export('yaml')
+ - {Age: 22, First Name: Kenneth, Gender: Male, Last Name: Reitz}
+ - {Age: 20, First Name: Bessie, Gender: Female, Last Name: Monke}
+
+When you add new rows to a dataset that contains dynamic columns, you should
+either provide all values in the row, or only the non-dynamic values and then
+the dynamic values will be automatically generated using the function initially
+provided for the column calculation.
+
+..versionchanged:: 3.6.0
+
+ In older versions, you could only add new rows with fully-populated rows,
+ including dynamic columns.
+
+.. _tags:
+
+----------------------------
+Filtering Datasets with Tags
+----------------------------
+
+When constructing a :class:`Dataset` object,
+you can add tags to rows by specifying the ``tags`` parameter.
+This allows you to filter your :class:`Dataset` later.
+This can be useful to separate rows of data based on arbitrary criteria
+(*e.g.* origin) that you don't want to include in your :class:`Dataset`.
+
+Let's tag some students. ::
+
+ students = tablib.Dataset()
+
+ students.headers = ['first', 'last']
+
+ students.rpush(['Kenneth', 'Reitz'], tags=['male', 'technical'])
+ students.rpush(['Daniel', 'Dupont'], tags=['male', 'creative' ])
+ students.rpush(['Bessie', 'Monke'], tags=['female', 'creative'])
+
+Now that we have extra meta-data on our rows, we can easily filter our :class:`Dataset`. Let's just see Female students. ::
+
+ >>> students.filter(['female']).yaml
+ - {first: Bessie, Last: Monke}
+
+By default, when you pass a list of tags you get filter type or. ::
+
+ >>> students.filter(['female', 'creative']).yaml
+ - {first: Daniel, Last: Dupont}
+ - {first: Bessie, Last: Monke}
+
+Using chaining you can get a filter type and. ::
+
+ >>> students.filter(['female']).filter(['creative']).yaml
+ - {first: Bessie, Last: Monke}
+
+It's that simple. The original :class:`Dataset` is untouched.
+
+Open an Excel Workbook and read first sheet
+-------------------------------------------
+
+Open an Excel 2007 and later workbook with a single sheet (or a workbook with multiple sheets but you just want the first sheet). ::
+
+ data = tablib.Dataset()
+ with open('my_excel_file.xlsx', 'rb') as fh:
+ data.load(fh, 'xlsx')
+ print(data)
+
+Excel Workbook With Multiple Sheets
+------------------------------------
+
+When dealing with a large number of :class:`Datasets ` in spreadsheet format,
+it's quite common to group multiple spreadsheets into a single Excel file, known as a Workbook.
+Tablib makes it extremely easy to build workbooks with the handy :class:`Databook` class.
+
+Let's say we have 3 different :class:`Datasets `.
+All we have to do is add them to a :class:`Databook` object... ::
+
+ book = tablib.Databook((data1, data2, data3))
+
+... and export to Excel just like :class:`Datasets `. ::
+
+ with open('students.xls', 'wb') as f:
+ f.write(book.export('xls'))
+
+The resulting ``students.xls`` file will contain a separate spreadsheet for each :class:`Dataset` object in the :class:`Databook`.
+
+.. admonition:: Binary Warning
+
+ Make sure to open the output file in binary mode.
+
+
+.. _separators:
+
+----------
+Separators
+----------
+
+When constructing a spreadsheet,
+it's often useful to create a blank row containing information on the upcoming data. So,
+
+::
+
+ daniel_tests = [
+ ('11/24/09', 'Math 101 Mid-term Exam', 56.),
+ ('05/24/10', 'Math 101 Final Exam', 62.)
+ ]
+
+ suzie_tests = [
+ ('11/24/09', 'Math 101 Mid-term Exam', 56.),
+ ('05/24/10', 'Math 101 Final Exam', 62.)
+ ]
+
+ # Create new dataset
+ tests = tablib.Dataset()
+ tests.headers = ['Date', 'Test Name', 'Grade']
+
+ # Daniel's Tests
+ tests.append_separator('Daniel\'s Scores')
+
+ for test_row in daniel_tests:
+ tests.append(test_row)
+
+ # Susie's Tests
+ tests.append_separator('Susie\'s Scores')
+
+ for test_row in suzie_tests:
+ tests.append(test_row)
+
+ # Write spreadsheet to disk
+ with open('grades.xls', 'wb') as f:
+ f.write(tests.export('xls'))
+
+The resulting **tests.xls** will have the following layout:
+
+
+ Daniel's Scores:
+ * '11/24/09', 'Math 101 Mid-term Exam', 56.
+ * '05/24/10', 'Math 101 Final Exam', 62.
+
+ Suzie's Scores:
+ * '11/24/09', 'Math 101 Mid-term Exam', 56.
+ * '05/24/10', 'Math 101 Final Exam', 62.
+
+
+
+.. admonition:: Format Support
+
+ At this time, only :class:`Excel ` output supports separators.
+
+----
+
+Now, go check out the :ref:`API Documentation ` or begin :ref:`Tablib Development `.
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/pyproject.toml b/tasks/tasksmith-b6d969373e1e/tests/source/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..cd74362ccf00692a38d222e97a965a33a11d4179
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/pyproject.toml
@@ -0,0 +1,89 @@
+[build-system]
+requires = ["setuptools>=58", "setuptools_scm[toml]>=6.2"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "tablib"
+description = "Format agnostic tabular data library (XLS, JSON, YAML, CSV, etc.)"
+readme = "README.md"
+license = {text = "MIT License"}
+authors = [
+ {name = "Kenneth Reitz", email = "me@kennethreitz.org"}
+]
+maintainers = [
+ {name = "Jazzband Team", email = "roadies@jazzband.co"},
+ {name = "Hugo van Kemenade"},
+ {name = "Claude Paroz", email = "claude@2xlibre.net"},
+]
+requires-python = ">=3.10"
+classifiers = [
+ "Development Status :: 5 - Production/Stable",
+ "Intended Audience :: Developers",
+ "Natural Language :: English",
+ "License :: OSI Approved :: MIT License",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3 :: Only",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Programming Language :: Python :: 3.14",
+]
+dynamic = ["version"]
+
+[project.optional-dependencies]
+all = [
+ "odfpy",
+ "openpyxl>=2.6.0",
+ "pandas",
+ "pyyaml",
+ "tabulate",
+ "xlrd",
+ "xlwt",
+]
+cli = ["tabulate"]
+html = []
+ods = ["odfpy"]
+pandas = ["pandas"]
+xls = ["xlrd", "xlwt"]
+xlsx = ["openpyxl>=2.6.0"]
+yaml = ["pyyaml"]
+
+[project.urls]
+homepage = "https://tablib.readthedocs.io"
+documentation = "https://tablib.readthedocs.io"
+repository = "https://github.com/jazzband/tablib"
+changelog = "https://github.com/jazzband/tablib/blob/master/HISTORY.md"
+
+[tool.setuptools_scm]
+write_to = "src/tablib/_version.py"
+
+[tool.ruff]
+fix = true
+line-length = 99
+
+lint.select = [
+ "C4", # flake8-comprehensions
+ "E", # pycodestyle errors
+ "F", # pyflakes
+ "I", # isort
+ "ISC", # flake8-implicit-str-concat
+ "PGH", # pygrep-hooks
+ "PIE", # flake8-pie
+ "RUF022", # unsorted-dunder-all
+ "RUF100", # unused noqa (yesqa)
+ "UP", # pyupgrade
+ "W", # pycodestyle warnings
+ "YTT", # flake8-2020
+]
+lint.ignore = [
+ "E203", # Whitespace before ':'
+ "E221", # Multiple spaces before operator
+ "E226", # Missing whitespace around arithmetic operator
+ "E241", # Multiple spaces after ','
+ "E741", # Ambiguous variable name
+ "PIE790", # Unnecessary pass statement
+ "UP038", # Makes code slower and more verbose
+]
+lint.isort.known-first-party = [ "tablib" ]
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/pytest.ini b/tasks/tasksmith-b6d969373e1e/tests/source/pytest.ini
new file mode 100644
index 0000000000000000000000000000000000000000..32b87e390599b474a12da34a3f59934938ebe544
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/pytest.ini
@@ -0,0 +1,3 @@
+[pytest]
+norecursedirs = .git .*
+addopts = -rsxX --showlocals --tb=native --cov=tablib --cov=tests --cov-report xml --cov-report term --cov-report html
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/PKG-INFO b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/PKG-INFO
new file mode 100644
index 0000000000000000000000000000000000000000..75e0cc273ad029b6004552f6a2ea46a32ea0beb6
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/PKG-INFO
@@ -0,0 +1,98 @@
+Metadata-Version: 2.4
+Name: tablib
+Version: 0.0.1
+Summary: Format agnostic tabular data library (XLS, JSON, YAML, CSV, etc.)
+Author-email: Kenneth Reitz
+Maintainer: Hugo van Kemenade
+Maintainer-email: Jazzband Team , Claude Paroz
+License: MIT License
+Project-URL: homepage, https://tablib.readthedocs.io
+Project-URL: documentation, https://tablib.readthedocs.io
+Project-URL: repository, https://github.com/jazzband/tablib
+Project-URL: changelog, https://github.com/jazzband/tablib/blob/master/HISTORY.md
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Intended Audience :: Developers
+Classifier: Natural Language :: English
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 3 :: Only
+Classifier: Programming Language :: Python :: 3
+Classifier: Programming Language :: Python :: 3.10
+Classifier: Programming Language :: Python :: 3.11
+Classifier: Programming Language :: Python :: 3.12
+Classifier: Programming Language :: Python :: 3.13
+Classifier: Programming Language :: Python :: 3.14
+Requires-Python: >=3.10
+Description-Content-Type: text/markdown
+License-File: LICENSE
+License-File: AUTHORS
+Provides-Extra: all
+Requires-Dist: odfpy; extra == "all"
+Requires-Dist: openpyxl>=2.6.0; extra == "all"
+Requires-Dist: pandas; extra == "all"
+Requires-Dist: pyyaml; extra == "all"
+Requires-Dist: tabulate; extra == "all"
+Requires-Dist: xlrd; extra == "all"
+Requires-Dist: xlwt; extra == "all"
+Provides-Extra: cli
+Requires-Dist: tabulate; extra == "cli"
+Provides-Extra: html
+Provides-Extra: ods
+Requires-Dist: odfpy; extra == "ods"
+Provides-Extra: pandas
+Requires-Dist: pandas; extra == "pandas"
+Provides-Extra: xls
+Requires-Dist: xlrd; extra == "xls"
+Requires-Dist: xlwt; extra == "xls"
+Provides-Extra: xlsx
+Requires-Dist: openpyxl>=2.6.0; extra == "xlsx"
+Provides-Extra: yaml
+Requires-Dist: pyyaml; extra == "yaml"
+Dynamic: license-file
+
+# Tablib: format-agnostic tabular dataset library
+
+[](https://jazzband.co/)
+[](https://pypi.org/project/tablib/)
+[](https://pypi.org/project/tablib/)
+[](https://pypistats.org/packages/tablib)
+[](https://github.com/jazzband/tablib/actions)
+[](https://codecov.io/gh/jazzband/tablib)
+[](LICENSE)
+
+ _____ ______ ___________ ______
+ __ /_______ ____ /_ ___ /___(_)___ /_
+ _ __/_ __ `/__ __ \__ / __ / __ __ \
+ / /_ / /_/ / _ /_/ /_ / _ / _ /_/ /
+ \__/ \__,_/ /_.___/ /_/ /_/ /_.___/
+
+
+Tablib is a format-agnostic tabular dataset library, written in Python.
+
+Output formats supported:
+
+- Excel (Sets + Books)
+- JSON (Sets + Books)
+- YAML (Sets + Books)
+- Pandas DataFrames (Sets)
+- HTML (Sets)
+- Jira (Sets)
+- LaTeX (Sets)
+- TSV (Sets)
+- ODS (Sets)
+- CSV (Sets)
+- DBF (Sets)
+- SQL (Sets)
+
+Note that tablib *purposefully* excludes XML support. It always will. (Note: This is a
+joke. Pull requests are welcome.)
+
+Tablib documentation is graciously hosted on https://tablib.readthedocs.io
+
+It is also available in the ``docs`` directory of the source distribution.
+
+Make sure to check out [Tablib on PyPI](https://pypi.org/project/tablib/)!
+
+## Contribute
+
+Please see the [contributing guide](https://github.com/jazzband/tablib/blob/master/.github/CONTRIBUTING.md).
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/SOURCES.txt b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/SOURCES.txt
new file mode 100644
index 0000000000000000000000000000000000000000..4dc1bc992de75b82bde8b302be10e25c5ecd9349
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/SOURCES.txt
@@ -0,0 +1,41 @@
+AUTHORS
+LICENSE
+README.md
+pyproject.toml
+src/tablib/__init__.py
+src/tablib/_version.py
+src/tablib/core.py
+src/tablib/exceptions.py
+src/tablib/utils.py
+src/tablib.egg-info/PKG-INFO
+src/tablib.egg-info/SOURCES.txt
+src/tablib.egg-info/dependency_links.txt
+src/tablib.egg-info/requires.txt
+src/tablib.egg-info/top_level.txt
+src/tablib/_vendor/__init__.py
+src/tablib/_vendor/dbfpy/__init__.py
+src/tablib/_vendor/dbfpy/dbf.py
+src/tablib/_vendor/dbfpy/dbfnew.py
+src/tablib/_vendor/dbfpy/fields.py
+src/tablib/_vendor/dbfpy/header.py
+src/tablib/_vendor/dbfpy/record.py
+src/tablib/_vendor/dbfpy/utils.py
+src/tablib/formats/__init__.py
+src/tablib/formats/_cli.py
+src/tablib/formats/_csv.py
+src/tablib/formats/_dbf.py
+src/tablib/formats/_df.py
+src/tablib/formats/_html.py
+src/tablib/formats/_jira.py
+src/tablib/formats/_json.py
+src/tablib/formats/_latex.py
+src/tablib/formats/_ods.py
+src/tablib/formats/_rst.py
+src/tablib/formats/_sql.py
+src/tablib/formats/_tsv.py
+src/tablib/formats/_xls.py
+src/tablib/formats/_xlsx.py
+src/tablib/formats/_yaml.py
+tests/test_tablib.py
+tests/test_tablib_dbfpy_packages_fields.py
+tests/test_tablib_dbfpy_packages_utils.py
\ No newline at end of file
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/dependency_links.txt b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/dependency_links.txt
new file mode 100644
index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/requires.txt b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/requires.txt
new file mode 100644
index 0000000000000000000000000000000000000000..40ed2a57f73959d3b647505f2f5c194effaece60
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/requires.txt
@@ -0,0 +1,30 @@
+
+[all]
+odfpy
+openpyxl>=2.6.0
+pandas
+pyyaml
+tabulate
+xlrd
+xlwt
+
+[cli]
+tabulate
+
+[html]
+
+[ods]
+odfpy
+
+[pandas]
+pandas
+
+[xls]
+xlrd
+xlwt
+
+[xlsx]
+openpyxl>=2.6.0
+
+[yaml]
+pyyaml
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/top_level.txt b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/top_level.txt
new file mode 100644
index 0000000000000000000000000000000000000000..e383933276ca6df7358fd077f3be6b58f2186f7e
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib.egg-info/top_level.txt
@@ -0,0 +1 @@
+tablib
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/__init__.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d528c7bf8230d76e874fb2221ed63e7e7a05b91f
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/__init__.py
@@ -0,0 +1,22 @@
+""" Tablib. """
+
+__lazy_modules__ = {"tablib.core"}
+
+try:
+ # Generated by setuptools-scm.
+ from ._version import version as __version__
+except ImportError:
+ # Some broken installation.
+ __version__ = None
+
+
+from .core import ( # noqa: F401
+ Databook,
+ Dataset,
+ InvalidDatasetType,
+ InvalidDimensions,
+ UnsupportedFormat,
+ detect_format,
+ import_book,
+ import_set,
+)
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/__init__.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/__init__.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/dbf.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/dbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..197a1856d6d3160829590254097f4696b99f39a3
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/dbf.py
@@ -0,0 +1,295 @@
+#! /usr/bin/env python
+
+from . import header, record
+from .utils import INVALID_VALUE
+
+__version__ = "$Revision: 1.7 $"[11:-2]
+__date__ = "$Date: 2007/02/11 09:23:13 $"[7:-2]
+__author__ = "Jeff Kunce "
+__all__ = ["Dbf"]
+
+"""DBF accessing helpers.
+
+FIXME: more documentation needed
+
+Examples:
+
+ Create new table, setup structure, add records:
+
+ dbf = Dbf(filename, new=True)
+ dbf.addField(
+ ("NAME", "C", 15),
+ ("SURNAME", "C", 25),
+ ("INITIALS", "C", 10),
+ ("BIRTHDATE", "D"),
+ )
+ for (n, s, i, b) in (
+ ("John", "Miller", "YC", (1980, 10, 11)),
+ ("Andy", "Larkin", "", (1980, 4, 11)),
+ ):
+ rec = dbf.newRecord()
+ rec["NAME"] = n
+ rec["SURNAME"] = s
+ rec["INITIALS"] = i
+ rec["BIRTHDATE"] = b
+ rec.store()
+ dbf.close()
+
+ Open existed dbf, read some data:
+
+ dbf = Dbf(filename, True)
+ for rec in dbf:
+ for fldName in dbf.fieldNames:
+ print('%s:\t %s (%s)' % (fldName, rec[fldName],
+ type(rec[fldName])))
+ print()
+ dbf.close()
+
+"""
+"""History (most recent first):
+11-feb-2007 [als] export INVALID_VALUE;
+ Dbf: added .ignoreErrors, .INVALID_VALUE
+04-jul-2006 [als] added export declaration
+20-dec-2005 [yc] removed fromStream and newDbf methods:
+ use argument of __init__ call must be used instead;
+ added class fields pointing to the header and
+ record classes.
+17-dec-2005 [yc] split to several modules; reimplemented
+13-dec-2005 [yc] adapted to the changes of the `strutil` module.
+13-sep-2002 [als] support FoxPro Timestamp datatype
+15-nov-1999 [jjk] documentation updates, add demo
+24-aug-1998 [jjk] add some encodeValue methods (not tested), other tweaks
+08-jun-1998 [jjk] fix problems, add more features
+20-feb-1998 [jjk] fix problems, add more features
+19-feb-1998 [jjk] add create/write capabilities
+18-feb-1998 [jjk] from dbfload.py
+"""
+
+
+class Dbf:
+ """DBF accessor.
+
+ FIXME:
+ docs and examples needed (dont' forget to tell
+ about problems adding new fields on the fly)
+
+ Implementation notes:
+ ``_new`` field is used to indicate whether this is
+ a new data table. `addField` could be used only for
+ the new tables! If at least one record was appended
+ to the table it's structure couldn't be changed.
+
+ """
+
+ __slots__ = ("name", "header", "stream",
+ "_changed", "_new", "_ignore_errors")
+
+ HeaderClass = header.DbfHeader
+ RecordClass = record.DbfRecord
+ INVALID_VALUE = INVALID_VALUE
+
+ # initialization and creation helpers
+
+ def __init__(self, f, readOnly=False, new=False, ignoreErrors=False):
+ """Initialize instance.
+
+ Arguments:
+ f:
+ Filename or file-like object.
+ new:
+ True if new data table must be created. Assume
+ data table exists if this argument is False.
+ readOnly:
+ if ``f`` argument is a string file will
+ be opend in read-only mode; in other cases
+ this argument is ignored. This argument is ignored
+ even if ``new`` argument is True.
+ headerObj:
+ `header.DbfHeader` instance or None. If this argument
+ is None, new empty header will be used with the
+ all fields set by default.
+ ignoreErrors:
+ if set, failing field value conversion will return
+ ``INVALID_VALUE`` instead of raising conversion error.
+
+ """
+ if isinstance(f, str):
+ # a filename
+ self.name = f
+ if new:
+ # new table (table file must be
+ # created or opened and truncated)
+ self.stream = open(f, "w+b")
+ else:
+ # table file must exist
+ self.stream = open(f, ("r+b", "rb")[bool(readOnly)])
+ else:
+ # a stream
+ self.name = getattr(f, "name", "")
+ self.stream = f
+ if new:
+ # if this is a new table, header will be empty
+ self.header = self.HeaderClass()
+ else:
+ # or instantiated using stream
+ self.header = self.HeaderClass.fromStream(self.stream)
+ self.ignoreErrors = ignoreErrors
+ self._new = bool(new)
+ self._changed = False
+
+ # properties
+
+ closed = property(lambda self: self.stream.closed)
+ recordCount = property(lambda self: self.header.recordCount)
+ fieldNames = property(
+ lambda self: [_fld.name for _fld in self.header.fields])
+ fieldDefs = property(lambda self: self.header.fields)
+ changed = property(lambda self: self._changed or self.header.changed)
+
+ def ignoreErrors(self, value):
+ """Update `ignoreErrors` flag on the header object and self"""
+ self.header.ignoreErrors = self._ignore_errors = bool(value)
+
+ ignoreErrors = property(
+ lambda self: self._ignore_errors,
+ ignoreErrors,
+ doc="""Error processing mode for DBF field value conversion
+
+ if set, failing field value conversion will return
+ ``INVALID_VALUE`` instead of raising conversion error.
+
+ """)
+
+ # protected methods
+
+ def _fixIndex(self, index):
+ """Return fixed index.
+
+ This method fails if index isn't a numeric object
+ (long or int). Or index isn't in a valid range
+ (less or equal to the number of records in the db).
+
+ If ``index`` is a negative number, it will be
+ treated as a negative indexes for list objects.
+
+ Return:
+ Return value is numeric object maning valid index.
+
+ """
+ if not isinstance(index, int):
+ raise TypeError("Index must be a numeric object")
+ if index < 0:
+ # index from the right side
+ # fix it to the left-side index
+ index += len(self) + 1
+ if index >= len(self):
+ raise IndexError("Record index out of range")
+ return index
+
+ # interface methods
+
+ def close(self):
+ self.flush()
+ self.stream.close()
+
+ def flush(self):
+ """Flush data to the associated stream."""
+ if self.changed:
+ self.header.setCurrentDate()
+ self.header.write(self.stream)
+ self.stream.flush()
+ self._changed = False
+
+ def indexOfFieldName(self, name):
+ """Index of field named ``name``."""
+ # FIXME: move this to header class
+ names = [f.name for f in self.header.fields]
+ return names.index(name.upper())
+
+ def newRecord(self):
+ """Return new record, which belong to this table."""
+ return self.RecordClass(self)
+
+ def append(self, record):
+ """Append ``record`` to the database."""
+ record.index = self.header.recordCount
+ record._write()
+ self.header.recordCount += 1
+ self._changed = True
+ self._new = False
+
+ def addField(self, *defs):
+ """Add field definitions.
+
+ For more information see `header.DbfHeader.addField`.
+
+ """
+ if self._new:
+ self.header.addField(*defs)
+ else:
+ raise TypeError("At least one record was added, "
+ "structure can't be changed")
+
+ # 'magic' methods (representation and sequence interface)
+
+ def __repr__(self):
+ return f"Dbf stream '{self.stream}'\n" + repr(self.header)
+
+ def __len__(self):
+ """Return number of records."""
+ return self.recordCount
+
+ def __getitem__(self, index):
+ """Return `DbfRecord` instance."""
+ return self.RecordClass.fromStream(self, self._fixIndex(index))
+
+ def __setitem__(self, index, record):
+ """Write `DbfRecord` instance to the stream."""
+ record.index = self._fixIndex(index)
+ record._write()
+ self._changed = True
+ self._new = False
+
+ # def __del__(self):
+ # """Flush stream upon deletion of the object."""
+ # self.flush()
+
+
+def demo_read(filename):
+ _dbf = Dbf(filename, True)
+ for _rec in _dbf:
+ print()
+ print(repr(_rec))
+ _dbf.close()
+
+
+def demo_create(filename):
+ _dbf = Dbf(filename, new=True)
+ _dbf.addField(
+ ("NAME", "C", 15),
+ ("SURNAME", "C", 25),
+ ("INITIALS", "C", 10),
+ ("BIRTHDATE", "D"),
+ )
+ for (_n, _s, _i, _b) in (
+ ("John", "Miller", "YC", (1981, 1, 2)),
+ ("Andy", "Larkin", "AL", (1982, 3, 4)),
+ ("Bill", "Clinth", "", (1983, 5, 6)),
+ ("Bobb", "McNail", "", (1984, 7, 8)),
+ ):
+ _rec = _dbf.newRecord()
+ _rec["NAME"] = _n
+ _rec["SURNAME"] = _s
+ _rec["INITIALS"] = _i
+ _rec["BIRTHDATE"] = _b
+ _rec.store()
+ print(repr(_dbf))
+ _dbf.close()
+
+
+if __name__ == '__main__':
+ import sys
+
+ _name = len(sys.argv) > 1 and sys.argv[1] or "county.dbf"
+ demo_create(_name)
+ demo_read(_name)
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/dbfnew.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/dbfnew.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bea5508f70a3ebce43f79ac185557051cc41ce4
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/dbfnew.py
@@ -0,0 +1,188 @@
+#!/usr/bin/python
+
+__version__ = "$Revision: 1.4 $"[11:-2]
+__date__ = "$Date: 2006/07/04 08:18:18 $"[7:-2]
+
+__all__ = ["dbf_new"]
+
+from .dbf import Dbf
+from .fields import (
+ DbfCharacterFieldDef,
+ DbfDateFieldDef,
+ DbfDateTimeFieldDef,
+ DbfLogicalFieldDef,
+ DbfNumericFieldDef,
+)
+from .header import DbfHeader
+from .record import DbfRecord
+
+""".DBF creation helpers.
+
+Note: this is a legacy interface. New code should use Dbf class
+ for table creation (see examples in dbf.py)
+
+TODO:
+ - handle Memo fields.
+ - check length of the fields according to the
+ `https://www.clicketyclick.dk/databases/xbase/format/data_types.html`
+
+"""
+"""History (most recent first)
+04-jul-2006 [als] added export declaration;
+ updated for dbfpy 2.0
+15-dec-2005 [yc] define dbf_new.__slots__
+14-dec-2005 [yc] added vim modeline; retab'd; added doc-strings;
+ dbf_new now is a new class (inherited from object)
+??-jun-2000 [--] added by Hans Fiby
+"""
+
+
+class _FieldDefinition:
+ """Field definition.
+
+ This is a simple structure, which contains ``name``, ``type``,
+ ``len``, ``dec`` and ``cls`` fields.
+
+ Objects also implement get/setitem magic functions, so fields
+ could be accessed via sequence interface, where 'name' has
+ index 0, 'type' index 1, 'len' index 2, 'dec' index 3 and
+ 'cls' could be located at index 4.
+
+ """
+
+ __slots__ = "name", "type", "len", "dec", "cls"
+
+ # WARNING: be attentive - dictionaries are mutable!
+ FLD_TYPES = {
+ # type: (cls, len)
+ "C": (DbfCharacterFieldDef, None),
+ "N": (DbfNumericFieldDef, None),
+ "L": (DbfLogicalFieldDef, 1),
+ # FIXME: support memos
+ # "M": (DbfMemoFieldDef),
+ "D": (DbfDateFieldDef, 8),
+ # FIXME: I'm not sure length should be 14 characters!
+ # but temporary I use it, cuz date is 8 characters
+ # and time 6 (hhmmss)
+ "T": (DbfDateTimeFieldDef, 14),
+ }
+
+ def __init__(self, name, type, len=None, dec=0):
+ _cls, _len = self.FLD_TYPES[type]
+ if _len is None:
+ if len is None:
+ raise ValueError("Field length must be defined")
+ _len = len
+ self.name = name
+ self.type = type
+ self.len = _len
+ self.dec = dec
+ self.cls = _cls
+
+ def getDbfField(self):
+ """Return `DbfFieldDef` instance from the current definition."""
+ return self.cls(self.name, self.len, self.dec)
+
+ def appendToHeader(self, dbfh):
+ """Create a `DbfFieldDef` instance and append it to the dbf header.
+
+ Arguments:
+ dbfh: `DbfHeader` instance.
+
+ """
+ _dbff = self.getDbfField()
+ dbfh.addField(_dbff)
+
+
+class dbf_new:
+ """New .DBF creation helper.
+
+ Example Usage:
+
+ dbfn = dbf_new()
+ dbfn.add_field("name",'C',80)
+ dbfn.add_field("price",'N',10,2)
+ dbfn.add_field("date",'D',8)
+ dbfn.write("tst.dbf")
+
+ Note:
+ This module cannot handle Memo-fields,
+ they are special.
+
+ """
+
+ __slots__ = ("fields",)
+
+ FieldDefinitionClass = _FieldDefinition
+
+ def __init__(self):
+ self.fields = []
+
+ def add_field(self, name, typ, len, dec=0):
+ """Add field definition.
+
+ Arguments:
+ name:
+ field name (str object). field name must not
+ contain ASCII NULs and it's length shouldn't
+ exceed 10 characters.
+ typ:
+ type of the field. this must be a single character
+ from the "CNLMDT" set meaning character, numeric,
+ logical, memo, date and date/time respectively.
+ len:
+ length of the field. this argument is used only for
+ the character and numeric fields. all other fields
+ have fixed length.
+ FIXME: use None as a default for this argument?
+ dec:
+ decimal precision. used only for the numric fields.
+
+ """
+ self.fields.append(self.FieldDefinitionClass(name, typ, len, dec))
+
+ def write(self, filename):
+ """Create empty .DBF file using current structure."""
+ _dbfh = DbfHeader()
+ _dbfh.setCurrentDate()
+ for _fldDef in self.fields:
+ _fldDef.appendToHeader(_dbfh)
+
+ _dbfStream = open(filename, "wb")
+ _dbfh.write(_dbfStream)
+ _dbfStream.close()
+
+
+if __name__ == '__main__':
+ # create a new DBF-File
+ dbfn = dbf_new()
+ dbfn.add_field("name", 'C', 80)
+ dbfn.add_field("price", 'N', 10, 2)
+ dbfn.add_field("date", 'D', 8)
+ dbfn.write("tst.dbf")
+ # test new dbf
+ print("*** created tst.dbf: ***")
+ dbft = Dbf('tst.dbf', readOnly=0)
+ print(repr(dbft))
+ # add a record
+ rec = DbfRecord(dbft)
+ rec['name'] = 'something'
+ rec['price'] = 10.5
+ rec['date'] = (2000, 1, 12)
+ rec.store()
+ # add another record
+ rec = DbfRecord(dbft)
+ rec['name'] = 'foo and bar'
+ rec['price'] = 12234
+ rec['date'] = (1992, 7, 15)
+ rec.store()
+
+ # show the records
+ print("*** inserted 2 records into tst.dbf: ***")
+ print(repr(dbft))
+ for i1 in range(len(dbft)):
+ rec = dbft[i1]
+ for fldName in dbft.fieldNames:
+ print(f'{fldName}:\t {rec[fldName]}')
+ print()
+ dbft.close()
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/fields.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/fields.py
new file mode 100644
index 0000000000000000000000000000000000000000..d91f050084a6dca05c51d54538a0e0a9cc6a1bcf
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/fields.py
@@ -0,0 +1,474 @@
+import datetime
+import struct
+from functools import total_ordering
+
+from . import utils
+
+__version__ = "$Revision: 1.14 $"[11:-2]
+__date__ = "$Date: 2009/05/26 05:16:51 $"[7:-2]
+
+__all__ = ["lookupFor"] # field classes added at the end of the module
+
+
+"""DBF fields definitions.
+
+TODO:
+ - make memos work
+"""
+"""History (most recent first):
+26-may-2009 [als] DbfNumericFieldDef.decodeValue: strip zero bytes
+05-feb-2009 [als] DbfDateFieldDef.encodeValue: empty arg produces empty date
+16-sep-2008 [als] DbfNumericFieldDef decoding looks for decimal point
+ in the value to select float or integer return type
+13-mar-2008 [als] check field name length in constructor
+11-feb-2007 [als] handle value conversion errors
+10-feb-2007 [als] DbfFieldDef: added .rawFromRecord()
+01-dec-2006 [als] Timestamp columns use None for empty values
+31-oct-2006 [als] support field types 'F' (float), 'I' (integer)
+ and 'Y' (currency);
+ automate export and registration of field classes
+04-jul-2006 [als] added export declaration
+10-mar-2006 [als] decode empty values for Date and Logical fields;
+ show field name in errors
+10-mar-2006 [als] fix Numeric value decoding: according to spec,
+ value always is string representation of the number;
+ ensure that encoded Numeric value fits into the field
+20-dec-2005 [yc] use field names in upper case
+15-dec-2005 [yc] field definitions moved from `dbf`.
+"""
+
+# abstract definitions
+
+
+@total_ordering
+class DbfFieldDef:
+ """Abstract field definition.
+
+ Child classes must override ``type`` class attribute to provide datatype
+ information of the field definition. For more info about types visit
+ `https://www.clicketyclick.dk/databases/xbase/format/data_types.html`
+
+ Also child classes must override ``defaultValue`` field to provide
+ default value for the field value.
+
+ If child class has fixed length ``length`` class attribute must be
+ overridden and set to the valid value. None value means, that field
+ isn't of fixed length.
+
+ Note: ``name`` field must not be changed after instantiation.
+
+ """
+
+ __slots__ = ("name", "decimalCount", "start", "end", "ignoreErrors")
+
+ # length of the field, None in case of variable-length field,
+ # or a number if this field is a fixed-length field
+ length = None
+
+ # field type. for more information about fields types visit
+ # `https://www.clicketyclick.dk/databases/xbase/format/data_types.html`
+ # must be overridden in child classes
+ typeCode = None
+
+ # default value for the field. this field must be
+ # overridden in child classes
+ defaultValue = None
+
+ def __init__(self, name, length=None, decimalCount=None,
+ start=None, stop=None, ignoreErrors=False):
+ """Initialize instance."""
+ assert self.typeCode is not None, "Type code must be overridden"
+ assert self.defaultValue is not None, "Default value must be overridden"
+ # fix arguments
+ if len(name) > 10:
+ raise ValueError(f"Field name \"{name}\" is too long")
+ name = str(name).upper()
+ if self.__class__.length is None:
+ if length is None:
+ raise ValueError(f"[{name}] Length isn't specified")
+ length = int(length)
+ if length <= 0:
+ raise ValueError(f"[{name}] Length must be a positive integer")
+ else:
+ length = self.length
+ if decimalCount is None:
+ decimalCount = 0
+ # set fields
+ self.name = name
+ # FIXME: validate length according to the specification at
+ # https://www.clicketyclick.dk/databases/xbase/format/data_types.html
+ self.length = length
+ self.decimalCount = decimalCount
+ self.ignoreErrors = ignoreErrors
+ self.start = start
+ self.end = stop
+
+ def __eq__(self, other):
+ return repr(self) == repr(other)
+
+ def __ne__(self, other):
+ return repr(self) != repr(other)
+
+ def __lt__(self, other):
+ return repr(self) < repr(other)
+
+ def __hash__(self):
+ return hash(self.name)
+
+ def fromString(cls, string, start, ignoreErrors=False):
+ """Decode dbf field definition from the string data.
+
+ Arguments:
+ string:
+ a string, dbf definition is decoded from. length of
+ the string must be 32 bytes.
+ start:
+ position in the database file.
+ ignoreErrors:
+ initial error processing mode for the new field (boolean)
+
+ """
+ assert len(string) == 32
+ _length = string[16]
+ return cls(utils.unzfill(string)[:11].decode('utf-8'), _length,
+ string[17], start, start + _length, ignoreErrors=ignoreErrors)
+ fromString = classmethod(fromString)
+
+ def toString(self):
+ """Return encoded field definition.
+
+ Return:
+ Return value is a string object containing encoded
+ definition of this field.
+
+ """
+ _name = self.name.ljust(11, '\0')
+ return (
+ _name +
+ self.typeCode +
+ # data address
+ chr(0) * 4 +
+ chr(self.length) +
+ chr(self.decimalCount) +
+ chr(0) * 14
+ )
+
+ def __repr__(self):
+ return "%-10s %1s %3d %3d" % self.fieldInfo() # noqa: UP031
+
+ def fieldInfo(self):
+ """Return field information.
+
+ Return:
+ Return value is a (name, type, length, decimals) tuple.
+
+ """
+ return self.name, self.typeCode, self.length, self.decimalCount
+
+ def rawFromRecord(self, record):
+ """Return a "raw" field value from the record string."""
+ return record[self.start:self.end]
+
+ def decodeFromRecord(self, record):
+ """Return decoded field value from the record string."""
+ try:
+ return self.decodeValue(self.rawFromRecord(record))
+ except Exception:
+ if self.ignoreErrors:
+ return utils.INVALID_VALUE
+ else:
+ raise
+
+ def decodeValue(self, value):
+ """Return decoded value from string value.
+
+ This method shouldn't be used publicly. It's called from the
+ `decodeFromRecord` method.
+
+ This is an abstract method and it must be overridden in child classes.
+ """
+ raise NotImplementedError
+
+ def encodeValue(self, value):
+ """Return str object containing encoded field value.
+
+ This is an abstract method and it must be overridden in child classes.
+ """
+ raise NotImplementedError
+
+# real classes
+
+
+class DbfCharacterFieldDef(DbfFieldDef):
+ """Definition of the character field."""
+
+ typeCode = "C"
+ defaultValue = b''
+
+ def decodeValue(self, value):
+ """Return string object.
+
+ Return value is a ``value`` argument with stripped right spaces.
+
+ """
+ return value.rstrip(b' ').decode('utf-8')
+
+ def encodeValue(self, value):
+ """Return raw data string encoded from a ``value``."""
+ return str(value)[:self.length].ljust(self.length)
+
+
+class DbfNumericFieldDef(DbfFieldDef):
+ """Definition of the numeric field."""
+
+ typeCode = "N"
+ # XXX: now I'm not sure it was a good idea to make a class field
+ # `defaultValue` instead of a generic method as it was implemented
+ # previously -- it's ok with all types except number, cuz
+ # if self.decimalCount is 0, we should return 0 and 0.0 otherwise.
+ defaultValue = 0
+
+ def decodeValue(self, value):
+ """Return a number decoded from ``value``.
+
+ If decimals is zero, value will be decoded as an integer;
+ or as a float otherwise.
+
+ Return:
+ Return value is a int (long) or float instance.
+
+ """
+ value = value.strip(b' \0')
+ if b'.' in value:
+ # a float (has decimal separator)
+ return float(value)
+ elif value:
+ # must be an integer
+ return int(value)
+ else:
+ return 0
+
+ def encodeValue(self, value):
+ """Return string containing encoded ``value``."""
+ _rv = ("%*.*f" % (self.length, self.decimalCount, value)) # noqa: UP031
+ if len(_rv) > self.length:
+ _ppos = _rv.find(".")
+ if 0 <= _ppos <= self.length:
+ _rv = _rv[:self.length]
+ else:
+ raise ValueError(
+ f"[{self.name}] Numeric overflow: {_rv} (field width: {self.length})"
+ )
+ return _rv
+
+
+class DbfFloatFieldDef(DbfNumericFieldDef):
+ """Definition of the float field - same as numeric."""
+
+ typeCode = "F"
+
+
+class DbfIntegerFieldDef(DbfFieldDef):
+ """Definition of the integer field."""
+
+ typeCode = "I"
+ length = 4
+ defaultValue = 0
+
+ def decodeValue(self, value):
+ """Return an integer number decoded from ``value``."""
+ return struct.unpack("= 1:
+ _rv = datetime.datetime.fromordinal(_jdn - self.JDN_GDN_DIFF)
+ _rv += datetime.timedelta(0, _msecs / 1000.0)
+ else:
+ # empty date
+ _rv = None
+ return _rv
+
+ def encodeValue(self, value):
+ """Return a string-encoded ``value``."""
+ if value:
+ value = utils.getDateTime(value)
+ # LE byteorder
+ _rv = struct.pack("<2I", value.toordinal() + self.JDN_GDN_DIFF,
+ (value.hour * 3600 + value.minute * 60 + value.second) * 1000)
+ else:
+ _rv = "\0" * self.length
+ assert len(_rv) == self.length
+ return _rv
+
+
+_fieldsRegistry = {}
+
+
+def registerField(fieldCls):
+ """Register field definition class.
+
+ ``fieldCls`` should be subclass of the `DbfFieldDef`.
+
+ Use `lookupFor` to retrieve field definition class
+ by the type code.
+
+ """
+ assert fieldCls.typeCode is not None, "Type code isn't defined"
+ # XXX: use fieldCls.typeCode.upper()? in case of any decign
+ # don't forget to look to the same comment in ``lookupFor`` method
+ _fieldsRegistry[fieldCls.typeCode] = fieldCls
+
+
+def lookupFor(typeCode):
+ """Return field definition class for the given type code.
+
+ ``typeCode`` must be a single character. That type should be
+ previously registered.
+
+ Use `registerField` to register new field class.
+
+ Return:
+ Return value is a subclass of the `DbfFieldDef`.
+
+ """
+ # XXX: use typeCode.upper()? in case of any decign don't
+ # forget to look to the same comment in ``registerField``
+ return _fieldsRegistry[chr(typeCode)]
+
+# register generic types
+
+
+for (_name, _val) in list(globals().items()):
+ if isinstance(_val, type) and issubclass(_val, DbfFieldDef) \
+ and (_name != "DbfFieldDef"):
+ __all__.append(_name)
+ registerField(_val)
+del _name, _val
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/header.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/header.py
new file mode 100644
index 0000000000000000000000000000000000000000..40329185e4d6a8d428048a98fbc78bead75ff587
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/header.py
@@ -0,0 +1,272 @@
+import datetime
+import io
+import struct
+import sys
+
+from . import fields
+from .utils import getDate
+
+__version__ = "$Revision: 1.6 $"[11:-2]
+__date__ = "$Date: 2010/09/16 05:06:39 $"[7:-2]
+
+__all__ = ["DbfHeader"]
+
+
+"""DBF header definition.
+
+TODO:
+ - handle encoding of the character fields
+ (encoding information stored in the DBF header)
+
+"""
+"""History (most recent first):
+16-sep-2010 [als] fromStream: fix century of the last update field
+11-feb-2007 [als] added .ignoreErrors
+10-feb-2007 [als] added __getitem__: return field definitions
+ by field name or field number (zero-based)
+04-jul-2006 [als] added export declaration
+15-dec-2005 [yc] created
+"""
+
+
+class DbfHeader:
+ """Dbf header definition.
+
+ For more information about dbf header format visit
+ `http://www.clicketyclick.dk/databases/xbase/format/dbf.html#DBF_STRUCT`
+
+ Examples:
+ Create an empty dbf header and add some field definitions:
+ dbfh = DbfHeader()
+ dbfh.addField(("name", "C", 10))
+ dbfh.addField(("date", "D"))
+ dbfh.addField(DbfNumericFieldDef("price", 5, 2))
+ Create a dbf header with field definitions:
+ dbfh = DbfHeader([
+ ("name", "C", 10),
+ ("date", "D"),
+ DbfNumericFieldDef("price", 5, 2),
+ ])
+
+ """
+
+ __slots__ = ("signature", "fields", "lastUpdate", "recordLength",
+ "recordCount", "headerLength", "changed", "_ignore_errors")
+
+ # instance construction and initialization methods
+
+ def __init__(self, fields=None, headerLength=0, recordLength=0,
+ recordCount=0, signature=0x03, lastUpdate=None, ignoreErrors=False):
+ """Initialize instance.
+
+ Arguments:
+ fields:
+ a list of field definitions;
+ recordLength:
+ size of the records;
+ headerLength:
+ size of the header;
+ recordCount:
+ number of records stored in DBF;
+ signature:
+ version number (aka signature). using 0x03 as a default meaning
+ "File without DBT". for more information about this field visit
+ ``http://www.clicketyclick.dk/databases/xbase/format/dbf.html#DBF_NOTE_1_TARGET``
+ lastUpdate:
+ date of the DBF's update. this could be a string ('yymmdd' or
+ 'yyyymmdd'), timestamp (int or float), datetime/date value,
+ a sequence (assuming (yyyy, mm, dd, ...)) or an object having
+ callable ``ticks`` field.
+ ignoreErrors:
+ error processing mode for DBF fields (boolean)
+
+ """
+ self.signature = signature
+ if fields is None:
+ self.fields = []
+ else:
+ self.fields = list(fields)
+ self.lastUpdate = getDate(lastUpdate)
+ self.recordLength = recordLength
+ self.headerLength = headerLength
+ self.recordCount = recordCount
+ self.ignoreErrors = ignoreErrors
+ # XXX: I'm not sure this is safe to
+ # initialize `self.changed` in this way
+ self.changed = bool(self.fields)
+
+ # @classmethod
+ def fromString(cls, string):
+ """Return header instance from the string object."""
+ return cls.fromStream(io.StringIO(str(string)))
+ fromString = classmethod(fromString)
+
+ # @classmethod
+ def fromStream(cls, stream):
+ """Return header object from the stream."""
+ stream.seek(0)
+ first_32 = stream.read(32)
+ if not isinstance(first_32, bytes):
+ _data = bytes(first_32, sys.getfilesystemencoding())
+ _data = first_32
+ (_cnt, _hdrLen, _recLen) = struct.unpack(" DbfRecord._write();
+ added delete() method.
+16-dec-2005 [yc] record definition moved from `dbf`.
+"""
+
+
+class DbfRecord:
+ """DBF record.
+
+ Instances of this class shouldn't be created manually,
+ use `dbf.Dbf.newRecord` instead.
+
+ Class implements mapping/sequence interface, so
+ fields could be accessed via their names or indexes
+ (names is a preferred way to access fields).
+
+ Hint:
+ Use `store` method to save modified record.
+
+ Examples:
+ Add new record to the database:
+ db = Dbf(filename)
+ rec = db.newRecord()
+ rec["FIELD1"] = value1
+ rec["FIELD2"] = value2
+ rec.store()
+ Or the same, but modify existed
+ (second in this case) record:
+ db = Dbf(filename)
+ rec = db[2]
+ rec["FIELD1"] = value1
+ rec["FIELD2"] = value2
+ rec.store()
+
+ """
+
+ __slots__ = "dbf", "index", "deleted", "fieldData"
+
+ # creation and initialization
+
+ def __init__(self, dbf, index=None, deleted=False, data=None):
+ """Instance initialization.
+
+ Arguments:
+ dbf:
+ A `Dbf.Dbf` instance this record belongs to.
+ index:
+ An integer record index or None. If this value is
+ None, record will be appended to the DBF.
+ deleted:
+ Boolean flag indicating whether this record
+ is a deleted record.
+ data:
+ A sequence or None. This is a data of the fields.
+ If this argument is None, default values will be used.
+
+ """
+ self.dbf = dbf
+ # XXX: I'm not sure ``index`` is necessary
+ self.index = index
+ self.deleted = deleted
+ if data is None:
+ self.fieldData = [_fd.defaultValue for _fd in dbf.header.fields]
+ else:
+ self.fieldData = list(data)
+
+ # XXX: validate self.index before calculating position?
+ position = property(lambda self: self.dbf.header.headerLength +
+ self.index * self.dbf.header.recordLength)
+
+ def rawFromStream(cls, dbf, index):
+ """Return raw record contents read from the stream.
+
+ Arguments:
+ dbf:
+ A `Dbf.Dbf` instance containing the record.
+ index:
+ Index of the record in the records' container.
+ This argument can't be None in this call.
+
+ Return value is a string containing record data in DBF format.
+
+ """
+ # XXX: may be write smth assuming, that current stream
+ # position is the required one? it could save some
+ # time required to calculate where to seek in the file
+ dbf.stream.seek(dbf.header.headerLength + index * dbf.header.recordLength)
+ return dbf.stream.read(dbf.header.recordLength)
+
+ rawFromStream = classmethod(rawFromStream)
+
+ def fromStream(cls, dbf, index):
+ """Return a record read from the stream.
+
+ Arguments:
+ dbf:
+ A `Dbf.Dbf` instance new record should belong to.
+ index:
+ Index of the record in the records' container.
+ This argument can't be None in this call.
+
+ Return value is an instance of the current class.
+
+ """
+ return cls.fromString(dbf, cls.rawFromStream(dbf, index), index)
+
+ fromStream = classmethod(fromStream)
+
+ def fromString(cls, dbf, string, index=None):
+ """Return record read from the string object.
+
+ Arguments:
+ dbf:
+ A `Dbf.Dbf` instance new record should belong to.
+ string:
+ A string new record should be created from.
+ index:
+ Index of the record in the container. If this
+ argument is None, record will be appended.
+
+ Return value is an instance of the current class.
+
+ """
+ return cls(dbf, index, string[0] == "*",
+ [_fd.decodeFromRecord(string) for _fd in dbf.header.fields])
+
+ fromString = classmethod(fromString)
+
+ # object representation
+
+ def __repr__(self):
+ _template = "%%%ds: %%s (%%s)" % max(len(_fld) for _fld in self.dbf.fieldNames) # noqa: UP031
+ _rv = []
+ for _fld in self.dbf.fieldNames:
+ _val = self[_fld]
+ if _val is utils.INVALID_VALUE:
+ _rv.append(_template % (_fld, "None", "value cannot be decoded"))
+ else:
+ _rv.append(_template % (_fld, _val, type(_val)))
+ return "\n".join(_rv)
+
+ # protected methods
+
+ def _write(self):
+ """Write data to the dbf stream.
+
+ Note:
+ This isn't a public method, it's better to
+ use 'store' instead publicly.
+ Be design ``_write`` method should be called
+ only from the `Dbf` instance.
+
+ """
+ self._validateIndex(False)
+ self.dbf.stream.seek(self.position)
+ self.dbf.stream.write(bytes(self.toString(),
+ sys.getfilesystemencoding()))
+ # FIXME: may be move this write somewhere else?
+ # why we should check this condition for each record?
+ if self.index == len(self.dbf):
+ # this is the last record,
+ # we should write SUB (ASCII 26)
+ self.dbf.stream.write(b"\x1A")
+
+ # utility methods
+
+ def _validateIndex(self, allowUndefined=True, checkRange=False):
+ """Valid ``self.index`` value.
+
+ If ``allowUndefined`` argument is True functions does nothing
+ in case of ``self.index`` pointing to None object.
+
+ """
+ if self.index is None:
+ if not allowUndefined:
+ raise ValueError("Index is undefined")
+ elif self.index < 0:
+ raise ValueError(f"Index can't be negative ({self.index})")
+ elif checkRange and self.index <= self.dbf.header.recordCount:
+ raise ValueError(
+ f"There are only {self.dbf.header.recordCount} records in the DBF"
+ )
+
+ # interface methods
+
+ def store(self):
+ """Store current record in the DBF.
+
+ If ``self.index`` is None, this record will be appended to the
+ records of the DBF this records belongs to; or replaced otherwise.
+
+ """
+ self._validateIndex()
+ if self.index is None:
+ self.index = len(self.dbf)
+ self.dbf.append(self)
+ else:
+ self.dbf[self.index] = self
+
+ def delete(self):
+ """Mark method as deleted."""
+ self.deleted = True
+
+ def toString(self):
+ """Return string packed record values."""
+ return "".join([" *"[self.deleted]] + [
+ _def.encodeValue(_dat) for (_def, _dat) in zip(self.dbf.header.fields, self.fieldData)
+ ])
+
+ def asList(self):
+ """Return a flat list of fields.
+
+ Note:
+ Change of the list's values won't change
+ real values stored in this object.
+
+ """
+ return self.fieldData[:]
+
+ def asDict(self):
+ """Return a dictionary of fields.
+
+ Note:
+ Change of the dicts's values won't change
+ real values stored in this object.
+
+ """
+ return dict(list(zip(self.dbf.fieldNames, self.fieldData)))
+
+ def __getitem__(self, key):
+ """Return value by field name or field index."""
+ if isinstance(key, int):
+ # integer index of the field
+ return self.fieldData[key]
+ # assuming string field name
+ return self.fieldData[self.dbf.indexOfFieldName(key)]
+
+ def __setitem__(self, key, value):
+ """Set field value by integer index of the field or string name."""
+ if isinstance(key, int):
+ # integer index of the field
+ return self.fieldData[key]
+ # assuming string field name
+ self.fieldData[self.dbf.indexOfFieldName(key)] = value
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/utils.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c20cec11819375ed0852596ccec6f5ebd9ea6b82
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_vendor/dbfpy/utils.py
@@ -0,0 +1,169 @@
+import datetime
+import time
+
+__version__ = "$Revision: 1.4 $"[11:-2]
+__date__ = "$Date: 2007/02/11 08:57:17 $"[7:-2]
+
+
+"""String utilities.
+
+TODO:
+ - allow strings in getDateTime routine;
+"""
+"""History (most recent first):
+11-feb-2007 [als] added INVALID_VALUE
+10-feb-2007 [als] allow date strings padded with spaces instead of zeroes
+20-dec-2005 [yc] handle long objects in getDate/getDateTime
+16-dec-2005 [yc] created from ``strutil`` module.
+"""
+
+
+def unzfill(str):
+ """Return a string without ASCII NULs.
+
+ This function searchers for the first NUL (ASCII 0) occurrence
+ and truncates string till that position.
+
+ """
+ try:
+ return str[:str.index(b'\0')]
+ except ValueError:
+ return str
+
+
+def getDate(date=None):
+ """Return `datetime.date` instance.
+
+ Type of the ``date`` argument could be one of the following:
+ None:
+ use current date value;
+ datetime.date:
+ this value will be returned;
+ datetime.datetime:
+ the result of the date.date() will be returned;
+ string:
+ assuming "%Y%m%d" or "%y%m%dd" format;
+ number:
+ assuming it's a timestamp (returned for example
+ by the time.time() call;
+ sequence:
+ assuming (year, month, day, ...) sequence;
+
+ Additionally, if ``date`` has callable ``ticks`` attribute,
+ it will be used and result of the called would be treated
+ as a timestamp value.
+
+ """
+ if date is None:
+ # use current value
+ return datetime.date.today()
+ if isinstance(date, datetime.date):
+ return date
+ if isinstance(date, datetime.datetime):
+ return date.date()
+ if isinstance(date, (int, float)):
+ # date is a timestamp
+ return datetime.date.fromtimestamp(date)
+ if isinstance(date, str):
+ date = date.replace(" ", "0")
+ if len(date) == 6:
+ # yymmdd
+ return datetime.date(*time.strptime(date, "%y%m%d")[:3])
+ # yyyymmdd
+ return datetime.date(*time.strptime(date, "%Y%m%d")[:3])
+ if hasattr(date, "__getitem__"):
+ # a sequence (assuming date/time tuple)
+ return datetime.date(*date[:3])
+ return datetime.date.fromtimestamp(date.ticks())
+
+
+def getDateTime(value=None):
+ """Return `datetime.datetime` instance.
+
+ Type of the ``value`` argument could be one of the following:
+ None:
+ use current date value;
+ datetime.date:
+ result will be converted to the `datetime.datetime` instance
+ using midnight;
+ datetime.datetime:
+ ``value`` will be returned as is;
+ string:
+ *** CURRENTLY NOT SUPPORTED ***;
+ number:
+ assuming it's a timestamp (returned for example
+ by the time.time() call;
+ sequence:
+ assuming (year, month, day, ...) sequence;
+
+ Additionally, if ``value`` has callable ``ticks`` attribute,
+ it will be used and result of the called would be treated
+ as a timestamp value.
+
+ """
+ if value is None:
+ # use current value
+ return datetime.datetime.today()
+ if isinstance(value, datetime.datetime):
+ return value
+ if isinstance(value, datetime.date):
+ return datetime.datetime.fromordinal(value.toordinal())
+ if isinstance(value, (int, float)):
+ # value is a timestamp
+ return datetime.datetime.fromtimestamp(value)
+ if isinstance(value, str):
+ raise NotImplementedError("Strings aren't currently implemented")
+ if hasattr(value, "__getitem__"):
+ # a sequence (assuming date/time tuple)
+ return datetime.datetime(*tuple(value)[:6])
+ return datetime.datetime.fromtimestamp(value.ticks())
+
+
+class classproperty(property):
+ """Works in the same way as a ``property``, but for the classes."""
+
+ def __get__(self, obj, cls):
+ return self.fget(cls)
+
+
+class _InvalidValue:
+
+ """Value returned from DBF records when field validation fails
+
+ The value is not equal to anything except for itself
+ and equal to all empty values: None, 0, empty string etc.
+ In other words, invalid value is equal to None and not equal
+ to None at the same time.
+
+ This value yields zero upon explicit conversion to a number type,
+ empty string for string types, and False for boolean.
+
+ """
+
+ def __eq__(self, other):
+ return not other
+
+ def __ne__(self, other):
+ return other is not self
+
+ def __bool__(self):
+ return False
+
+ def __int__(self):
+ return 0
+ __long__ = __int__
+
+ def __float__(self):
+ return 0.0
+
+ def __str__(self):
+ return ""
+
+ def __repr__(self):
+ return ""
+
+
+# invalid value is a constant singleton
+INVALID_VALUE = _InvalidValue()
+
+# vim: set et sts=4 sw=4 :
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_version.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..2438ee983030095501285554f9a560c69155bead
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/_version.py
@@ -0,0 +1,24 @@
+# file generated by vcs-versioning
+# don't change, don't track in version control
+from __future__ import annotations
+
+__all__ = [
+ "__version__",
+ "__version_tuple__",
+ "version",
+ "version_tuple",
+ "__commit_id__",
+ "commit_id",
+]
+
+version: str
+__version__: str
+__version_tuple__: tuple[int | str, ...]
+version_tuple: tuple[int | str, ...]
+commit_id: str | None
+__commit_id__: str | None
+
+__version__ = version = '0.0.1'
+__version_tuple__ = version_tuple = (0, 0, 1)
+
+__commit_id__ = commit_id = None
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/core.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/core.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0b56fd2323cf5e0809c756a829327a64c17a693
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/core.py
@@ -0,0 +1,966 @@
+"""
+ tablib.core
+ ~~~~~~~~~~~
+
+ This module implements the central Tablib objects.
+
+ :copyright: (c) 2016 by Kenneth Reitz. 2019 Jazzband.
+ :license: MIT, see LICENSE for more details.
+"""
+
+__lazy_modules__ = {
+ "copy",
+ "operator",
+ "tablib.exceptions",
+ "tablib.utils",
+}
+
+from copy import copy
+from operator import itemgetter
+
+from .exceptions import (
+ HeadersNeeded,
+ InvalidDatasetIndex,
+ InvalidDatasetType,
+ InvalidDimensions,
+ UnsupportedFormat,
+)
+from .formats import registry
+from .utils import normalize_input
+
+__title__ = 'tablib'
+__author__ = 'Kenneth Reitz'
+__license__ = 'MIT'
+__copyright__ = 'Copyright 2017 Kenneth Reitz. 2019 Jazzband.'
+__docformat__ = 'restructuredtext'
+
+
+class Row:
+ """Internal Row object. Mainly used for filtering."""
+
+ __slots__ = ['_row', 'tags']
+
+ def __init__(self, row=(), tags=()):
+ self._row = list(row)
+ self.tags = list(tags)
+
+ def __iter__(self):
+ return (col for col in self._row)
+
+ def __len__(self):
+ return len(self._row)
+
+ def __repr__(self):
+ return repr(self._row)
+
+ def __getitem__(self, i):
+ return self._row[i]
+
+ def __setitem__(self, i, value):
+ self._row[i] = value
+
+ def __delitem__(self, i):
+ del self._row[i]
+
+ def __getstate__(self):
+ return self._row, self.tags
+
+ def __setstate__(self, state):
+ self._row, self.tags = state
+
+ def rpush(self, value):
+ self.insert(len(self._row), value)
+
+ def lpush(self, value):
+ self.insert(0, value)
+
+ def append(self, value):
+ self.rpush(value)
+
+ def insert(self, index, value):
+ self._row.insert(index, value)
+
+ def copy(self):
+ return Row(self._row.copy(), self.tags.copy())
+
+ def __contains__(self, item):
+ return item in self._row
+
+ @property
+ def tuple(self):
+ """Tuple representation of :class:`Row`."""
+ return tuple(self._row)
+
+ @property
+ def list(self):
+ """List representation of :class:`Row`."""
+ return list(self._row)
+
+ def has_tag(self, tag):
+ """Returns true if current row contains tag."""
+
+ if tag is None:
+ return False
+ elif isinstance(tag, str):
+ return tag in self.tags
+ else:
+ return bool(len(set(tag) & set(self.tags)))
+
+
+class Dataset:
+ """The :class:`Dataset` object is the heart of Tablib. It provides all core
+ functionality.
+
+ Usually you create a :class:`Dataset` instance in your main module, and append
+ rows as you collect data. ::
+
+ data = tablib.Dataset()
+ data.headers = ('name', 'age')
+
+ for (name, age) in some_collector():
+ data.append((name, age))
+
+
+ Setting columns is similar. The column data length must equal the
+ current height of the data and headers must be set. ::
+
+ data = tablib.Dataset()
+ data.headers = ('first_name', 'last_name')
+
+ data.append(('John', 'Adams'))
+ data.append(('George', 'Washington'))
+
+ data.append_col((90, 67), header='age')
+
+
+ You can also set rows and headers upon instantiation. This is useful if
+ dealing with dozens or hundreds of :class:`Dataset` objects. ::
+
+ headers = ('first_name', 'last_name')
+ data = [('John', 'Adams'), ('George', 'Washington')]
+
+ data = tablib.Dataset(*data, headers=headers)
+
+ :param \\*args: (optional) list of rows to populate Dataset
+ :param headers: (optional) list strings for Dataset header row
+ :param title: (optional) string to use as title of the Dataset
+
+
+ .. admonition:: Format Attributes Definition
+
+ If you look at the code, the various output/import formats are not
+ defined within the :class:`Dataset` object. To add support for a new format, see
+ :ref:`Adding New Formats `.
+
+ """
+
+ def __init__(self, *args, **kwargs):
+ self._data = [Row(arg) for arg in args]
+ self.__headers = None
+
+ # ('title', index) tuples
+ self._separators = []
+
+ # (column, callback) tuples
+ self._formatters = []
+
+ # {col_index: col_func}
+ self._dynamic_columns = {}
+
+ self.headers = kwargs.get('headers')
+
+ self.title = kwargs.get('title')
+
+ def __len__(self):
+ return self.height
+
+ def __getitem__(self, key):
+ if isinstance(key, str):
+ if self.headers is None:
+ raise HeadersNeeded()
+ if key in self.headers:
+ pos = self.headers.index(key) # get 'key' index from each data
+ return [row[pos] for row in self._data]
+ else:
+ raise KeyError
+ else:
+ _results = self._data[key]
+ if isinstance(_results, Row):
+ return _results.tuple
+ else:
+ return [result.tuple for result in _results]
+
+ def __setitem__(self, key, value):
+ self._validate(value)
+ self._data[key] = Row(value)
+
+ def __delitem__(self, key):
+ if isinstance(key, str):
+ if self.headers is None:
+ raise HeadersNeeded()
+
+ if key in self.headers:
+
+ pos = self.headers.index(key)
+ del self.headers[pos]
+ if pos in self._dynamic_columns:
+ del self._dynamic_columns[pos]
+
+ for i, row in enumerate(self._data):
+
+ del row[pos]
+ self._data[i] = row
+ else:
+ raise KeyError
+ else:
+ del self._data[key]
+
+ def __repr__(self):
+ try:
+ return f'<{self.title.lower()} dataset>'
+ except AttributeError:
+ return ''
+
+ def __str__(self):
+ result = []
+
+ # Add str representation of headers.
+ if self.__headers:
+ result.append([str(h) for h in self.__headers])
+
+ # Add str representation of rows.
+ result.extend(list(map(str, row)) for row in self._data)
+
+ lens = [list(map(len, row)) for row in result]
+ field_lens = list(map(max, zip(*lens)))
+
+ # delimiter between header and data
+ if self.__headers:
+ result.insert(1, ['-' * length for length in field_lens])
+
+ format_string = '|'.join('{{{}:{}}}'.format(*item) for item in enumerate(field_lens))
+
+ return '\n'.join(format_string.format(*row) for row in result)
+
+ # ---------
+ # Internals
+ # ---------
+
+ def _get_in_format(self, fmt_key, **kwargs):
+ return registry.get_format(fmt_key).export_set(self, **kwargs)
+
+ def _set_in_format(self, fmt_key, in_stream, **kwargs):
+ in_stream = normalize_input(in_stream)
+ return registry.get_format(fmt_key).import_set(self, in_stream, **kwargs)
+
+ def _validate(self, row=None, col=None, safety=False):
+ """Assures size of every row in dataset is of proper proportions."""
+ if row:
+ if self.width:
+ is_valid = (
+ len(row) == self.width or
+ len(row) == (self.width - len(self._dynamic_columns))
+ )
+ else:
+ is_valid = True
+ elif col:
+ if len(col) < 1:
+ is_valid = True
+ else:
+ is_valid = (len(col) == self.height) if self.height else True
+ else:
+ is_valid = all(len(x) == self.width for x in self._data)
+
+ if is_valid:
+ return True
+ else:
+ if not safety:
+ raise InvalidDimensions
+ return False
+
+ def _package(self, dicts=True):
+ """Packages Dataset into lists of dictionaries for transmission."""
+ # TODO: Dicts default to false?
+
+ _data = list(self._data)
+
+ def format_row(row):
+ # Execute formatters
+ if self._formatters:
+ row = row.copy() # To not mutate internal data structure
+ for col, callback in self._formatters:
+ if col is None:
+ # Apply formatter to all cells
+ row = [callback(cell) for cell in row]
+ else:
+ row[col] = callback(row[col])
+ return list(row)
+
+ if self.headers:
+ if dicts:
+ data = [dict(list(zip(self.headers, format_row(row)))) for row in _data]
+ else:
+ data = [list(self.headers)] + [format_row(row) for row in _data]
+ else:
+ data = [format_row(row) for row in _data]
+ return data
+
+ def _get_headers(self):
+ """An *optional* list of strings to be used for header rows and attribute names.
+
+ This must be set manually. The given list length must equal :attr:`Dataset.width`.
+
+ """
+ return self.__headers
+
+ def _set_headers(self, collection):
+ """Validating headers setter."""
+ self._validate(collection)
+ if collection:
+ self.__headers = list(collection)
+ else:
+ self.__headers = None
+
+ headers = property(_get_headers, _set_headers)
+
+ def _get_dict(self):
+ """A native Python representation of the :class:`Dataset` object. If headers have
+ been set, a list of Python dictionaries will be returned. If no headers have been set,
+ a list of tuples (rows) will be returned instead.
+
+ A dataset object can also be imported by setting the `Dataset.dict` attribute: ::
+
+ data = tablib.Dataset()
+ data.dict = [{'age': 90, 'first_name': 'Kenneth', 'last_name': 'Reitz'}]
+
+ """
+ return self._package()
+
+ def _set_dict(self, pickle):
+ """A native Python representation of the Dataset object. If headers have been
+ set, a list of Python dictionaries will be returned. If no headers have been
+ set, a list of tuples (rows) will be returned instead.
+
+ A dataset object can also be imported by setting the :attr:`Dataset.dict` attribute. ::
+
+ data = tablib.Dataset()
+ data.dict = [{'age': 90, 'first_name': 'Kenneth', 'last_name': 'Reitz'}]
+
+ """
+ error_details = (
+ "Please check format documentation "
+ "https://tablib.readthedocs.io/en/stable/formats.html"
+ )
+
+ if not pickle:
+ return
+
+ if not isinstance(pickle, list):
+ # sometimes pickle is a dict and len(pickle) returns True.
+ # since we access index 0 we should check if the type is list
+ raise UnsupportedFormat(error_details)
+
+ # if list of rows
+ if isinstance(pickle[0], list):
+ self.wipe()
+ for row in pickle:
+ self.append(Row(row))
+
+ # if list of objects
+ elif isinstance(pickle[0], dict):
+ self.wipe()
+ self.headers = list(pickle[0].keys())
+ for row in pickle:
+ self.append(Row(list(row.values())))
+ else:
+ raise UnsupportedFormat(error_details)
+
+ dict = property(_get_dict, _set_dict)
+
+ def _clean_col(self, col):
+ """Prepares the given column for insert/append. `col` is not supposed to
+ contain any header value.
+ """
+
+ col = list(col)
+
+ if len(col) == 1 and hasattr(col[0], '__call__'):
+ col = list(map(col[0], self._data))
+
+ return col
+
+ @property
+ def height(self):
+ """The number of rows currently in the :class:`Dataset`.
+ Cannot be directly modified.
+ """
+ return len(self._data)
+
+ @property
+ def width(self):
+ """The number of columns currently in the :class:`Dataset`.
+ Cannot be directly modified.
+ """
+
+ try:
+ return len(self._data[0])
+ except IndexError:
+ try:
+ return len(self.headers)
+ except TypeError:
+ return 0
+
+ def load(self, in_stream, format=None, **kwargs):
+ """
+ Import `in_stream` to the :class:`Dataset` object using the `format`.
+ `in_stream` can be a file-like object, a string, or a bytestring.
+
+ :param \\*\\*kwargs: (optional) custom configuration to the format `import_set`.
+ """
+
+ stream = normalize_input(in_stream)
+ if not format:
+ format = detect_format(stream)
+
+ fmt = registry.get_format(format)
+ if not hasattr(fmt, 'import_set'):
+ raise UnsupportedFormat(f'Format {format} cannot be imported.')
+
+ fmt.import_set(self, stream, **kwargs)
+ return self
+
+ def export(self, format, **kwargs):
+ """
+ Export :class:`Dataset` object to `format`.
+
+ :param \\*\\*kwargs: (optional) custom configuration to the format `export_set`.
+ """
+ fmt = registry.get_format(format)
+ if not hasattr(fmt, 'export_set'):
+ raise UnsupportedFormat(f'Format {format} cannot be exported.')
+
+ return fmt.export_set(self, **kwargs)
+
+ # ----
+ # Rows
+ # ----
+
+ def insert(self, index, row, tags=()):
+ """Inserts a row to the :class:`Dataset` at the given index.
+
+ Rows inserted must be the correct size (height or width).
+
+ The default behaviour is to insert the given row to the :class:`Dataset`
+ object at the given index.
+
+ You can add :ref:`tags ` to the row you are inserting.
+ This gives you the ability to :method:`filter ` your
+ :class:`Dataset` later.
+ """
+
+ self._validate(row)
+ if len(row) < self.width:
+ for pos, func in self._dynamic_columns.items():
+ row = list(row)
+ row.insert(pos, func(row))
+ self._data.insert(index, Row(row, tags=tags))
+
+ def rpush(self, row, tags=()):
+ """Adds a row to the end of the :class:`Dataset`.
+ See :method:`Dataset.insert` for additional documentation.
+ """
+
+ self.insert(self.height, row=row, tags=tags)
+
+ def lpush(self, row, tags=()):
+ """Adds a row to the top of the :class:`Dataset`.
+ See :method:`Dataset.insert` for additional documentation.
+ """
+
+ self.insert(0, row=row, tags=tags)
+
+ def append(self, row, tags=()):
+ """Adds a row to the :class:`Dataset`.
+ See :method:`Dataset.insert` for additional documentation.
+ """
+
+ self.rpush(row, tags)
+
+ def extend(self, rows, tags=()):
+ """Adds a list of rows to the :class:`Dataset` using
+ :method:`Dataset.append`
+ """
+
+ for row in rows:
+ self.append(row, tags)
+
+ def lpop(self):
+ """Removes and returns the first row of the :class:`Dataset`."""
+
+ cache = self[0]
+ del self[0]
+
+ return cache
+
+ def rpop(self):
+ """Removes and returns the last row of the :class:`Dataset`."""
+
+ cache = self[-1]
+ del self[-1]
+
+ return cache
+
+ def pop(self):
+ """Removes and returns the last row of the :class:`Dataset`."""
+
+ return self.rpop()
+
+ def get(self, index):
+ """Returns the row from the :class:`Dataset` at the given index."""
+
+ if isinstance(index, int):
+ return self[index]
+
+ raise TypeError('Row indices must be integers.')
+
+ # -------
+ # Columns
+ # -------
+
+ def insert_col(self, index, col=None, header=None):
+ """Inserts a column to the :class:`Dataset` at the given index.
+
+ Columns inserted must be the correct height.
+
+ You can also insert a column of a single callable object, which will
+ add a new column with the return values of the callable each as an
+ item in the column. ::
+
+ data.append_col(col=random.randint)
+
+ If inserting a column, and :attr:`Dataset.headers` is set, the
+ header attribute must be set, and will be considered the header for
+ that row.
+
+ See :ref:`dyncols` for an in-depth example.
+ """
+
+ if col is None:
+ col = []
+
+ # Callable Columns...
+ if callable(col):
+ self._dynamic_columns[self.width] = col
+ col = list(map(col, self._data))
+
+ col = self._clean_col(col)
+ self._validate(col=col)
+
+ if self.headers:
+ # pop the first item off, add to headers
+ if not header:
+ raise HeadersNeeded()
+
+ # corner case - if header is set without data
+ elif header and self.height == 0 and len(col):
+ raise InvalidDimensions
+
+ self.headers.insert(index, header)
+
+ if self.height and self.width:
+
+ for i, row in enumerate(self._data):
+
+ row.insert(index, col[i])
+ self._data[i] = row
+ else:
+ self._data = [Row([row]) for row in col]
+
+ def rpush_col(self, col, header=None):
+ """Adds a column to the end of the :class:`Dataset`.
+ See :method:`Dataset.insert` for additional documentation.
+ """
+
+ self.insert_col(self.width, col, header=header)
+
+ def lpush_col(self, col, header=None):
+ """Adds a column to the top of the :class:`Dataset`.
+ See :method:`Dataset.insert` for additional documentation.
+ """
+
+ self.insert_col(0, col, header=header)
+
+ def insert_separator(self, index, text='-'):
+ """Adds a separator to :class:`Dataset` at given index."""
+
+ sep = (index, text)
+ self._separators.append(sep)
+
+ def append_separator(self, text='-'):
+ """Adds a :ref:`separator ` to the :class:`Dataset`."""
+
+ # change offsets if headers are or aren't defined
+ if not self.headers:
+ index = self.height if self.height else 0
+ else:
+ index = (self.height + 1) if self.height else 1
+
+ self.insert_separator(index, text)
+
+ def append_col(self, col, header=None):
+ """Adds a column to the :class:`Dataset`.
+ See :method:`Dataset.insert_col` for additional documentation.
+ """
+
+ self.rpush_col(col, header)
+
+ def get_col(self, index):
+ """Returns the column from the :class:`Dataset` at the given index."""
+
+ return [row[index] for row in self._data]
+
+ # ----
+ # Misc
+ # ----
+
+ def add_formatter(self, col, handler):
+ """Adds a formatter to the :class:`Dataset`.
+
+ :param col: column to. Accepts index int, header str, or None to apply
+ the formatter to all columns.
+ :param handler: reference to callback function to execute against
+ each cell value.
+ """
+
+ if isinstance(col, str):
+ if col in self.headers:
+ col = self.headers.index(col) # get 'key' index from each data
+ else:
+ raise KeyError
+
+ if col is None or col <= self.width:
+ self._formatters.append((col, handler))
+ else:
+ raise InvalidDatasetIndex
+
+ return True
+
+ def filter(self, tag):
+ """Returns a new instance of the :class:`Dataset`, excluding any rows
+ that do not contain the given :ref:`tags `.
+ """
+ _dset = copy(self)
+ _dset._data = [row for row in _dset._data if row.has_tag(tag)]
+
+ return _dset
+
+ def sort(self, col, reverse=False):
+ """Sort a :class:`Dataset` by a specific column, given string (for
+ header) or integer (for column index). The order can be reversed by
+ setting ``reverse`` to ``True``.
+
+ Returns a new :class:`Dataset` instance where columns have been
+ sorted.
+ """
+
+ if isinstance(col, str):
+
+ if not self.headers:
+ raise HeadersNeeded
+
+ _sorted = sorted(self.dict, key=itemgetter(col), reverse=reverse)
+ _dset = Dataset(headers=self.headers, title=self.title)
+
+ for item in _sorted:
+ row = [item[key] for key in self.headers]
+ _dset.append(row=row)
+
+ else:
+ if self.headers:
+ col = self.headers[col]
+
+ _sorted = sorted(self.dict, key=itemgetter(col), reverse=reverse)
+ _dset = Dataset(headers=self.headers, title=self.title)
+
+ for item in _sorted:
+ if self.headers:
+ row = [item[key] for key in self.headers]
+ else:
+ row = item
+ _dset.append(row=row)
+
+ return _dset
+
+ def _transpose_with_headers(self):
+ """Transpose a :class:`Dataset`, turning rows into columns and vice
+ versa, returning a new ``Dataset`` instance. The first row of the
+ original instance becomes the new header row."""
+
+ _dset = Dataset()
+ # The first element of the headers stays in the headers,
+ # it is our "hinge" on which we rotate the data
+ new_headers = [self.headers[0]] + self[self.headers[0]]
+
+ _dset.headers = new_headers
+ for index, column in enumerate(self.headers):
+
+ if column == self.headers[0]:
+ # It's in the headers, so skip it
+ continue
+
+ # Adding the column name as now they're a regular column
+ # Use `get_col(index)` in case there are repeated values
+ row_data = [column] + self.get_col(index)
+ row_data = Row(row_data)
+ _dset.append(row=row_data)
+ return _dset
+
+ def _transpose_without_headers(self):
+ """Transpose a :class:`Dataset`, turning rows into columns and vice
+ versa, returning a new ``Dataset`` instance. This instance should not
+ have headers, or the dimension would be invalid."""
+
+ _dset = Dataset()
+
+ # Add columns as rows in new instance
+ for index in range(len(self._data[0])):
+ row_data = self.get_col(index)
+ _dset.append(row=row_data)
+
+ return _dset
+
+ def transpose(self):
+ """Transpose a :class:`Dataset`, turning rows into columns and vice
+ versa, returning a new ``Dataset`` instance. If the instance has
+ headers, the first row of the original instance becomes the new header
+ row."""
+
+ # Don't transpose if there is no data
+ if not self:
+ return
+
+ if self.headers is None:
+ return self._transpose_without_headers()
+ else:
+ return self._transpose_with_headers()
+
+ def stack(self, other):
+ """Stack two :class:`Dataset` instances together by
+ joining at the row level, and return new combined
+ ``Dataset`` instance."""
+
+ if not isinstance(other, Dataset):
+ raise TypeError("'other' must be a Dataset instance")
+
+ if self.width != other.width:
+ raise InvalidDimensions
+
+ # Copy the source data
+ _dset = copy(self)
+
+ rows_to_stack = list(_dset._data)
+ other_rows = list(other._data)
+
+ rows_to_stack.extend(other_rows)
+ _dset._data = rows_to_stack
+
+ return _dset
+
+ def stack_cols(self, other):
+ """Stack two :class:`Dataset` instances together by
+ joining at the column level, and return a new
+ combined ``Dataset`` instance. If either ``Dataset``
+ has headers set, than the other must as well."""
+
+ if not isinstance(other, Dataset):
+ raise TypeError("'other' must be a Dataset instance")
+
+ if self.headers or other.headers:
+ if not self.headers or not other.headers:
+ raise HeadersNeeded
+
+ if self.height != other.height:
+ raise InvalidDimensions
+
+ try:
+ new_headers = self.headers + other.headers
+ except TypeError:
+ new_headers = None
+
+ _dset = Dataset()
+
+ if self.headers:
+ for column in self.headers:
+ _dset.append_col(col=self[column])
+
+ for column in other.headers:
+ _dset.append_col(col=other[column])
+ else:
+ for index in range(self.width):
+ _dset.append_col(col=self.get_col(index))
+
+ for index in range(other.width):
+ _dset.append_col(col=other.get_col(index))
+
+ _dset.headers = new_headers
+
+ return _dset
+
+ def remove_duplicates(self):
+ """Removes all duplicate rows from the :class:`Dataset` object
+ while maintaining the original order."""
+ seen = set()
+ self._data[:] = [
+ row for row in self._data if not (tuple(row) in seen or seen.add(tuple(row)))
+ ]
+
+ def wipe(self):
+ """Removes all content and headers from the :class:`Dataset` object."""
+ self._data = []
+ self.__headers = None
+
+ def subset(self, rows=None, cols=None):
+ """Returns a new instance of the :class:`Dataset`,
+ including only specified rows and columns.
+ """
+
+ # Don't return if no data
+ if not self:
+ return
+
+ if rows is None:
+ rows = list(range(self.height))
+
+ if cols is None:
+ cols = list(self.headers)
+
+ # filter out impossible rows and columns
+ rows = [row for row in rows if row in range(self.height)]
+ cols = [header for header in cols if header in self.headers]
+
+ _dset = Dataset()
+
+ # filtering rows and columns
+ _dset.headers = list(cols)
+
+ _dset._data = []
+ for row_no, row in enumerate(self._data):
+ data_row = []
+ for key in _dset.headers:
+ if key in self.headers:
+ pos = self.headers.index(key)
+ data_row.append(row[pos])
+ else:
+ raise KeyError
+
+ if row_no in rows:
+ _dset.append(row=Row(data_row))
+
+ return _dset
+
+
+class Databook:
+ """A book of :class:`Dataset` objects.
+ """
+
+ def __init__(self, sets=None):
+ self._datasets = sets or []
+
+ def __repr__(self):
+ try:
+ return f'<{self.title.lower()} databook>'
+ except AttributeError:
+ return ''
+
+ def wipe(self):
+ """Removes all :class:`Dataset` objects from the :class:`Databook`."""
+ self._datasets = []
+
+ def sheets(self):
+ return self._datasets
+
+ def add_sheet(self, dataset):
+ """Adds given :class:`Dataset` to the :class:`Databook`."""
+ if isinstance(dataset, Dataset):
+ self._datasets.append(dataset)
+ else:
+ raise InvalidDatasetType
+
+ def _package(self):
+ """Packages :class:`Databook` for delivery."""
+ collector = []
+
+ for dset in self._datasets:
+ collector.append({
+ 'title': dset.title,
+ 'data': dset._package()
+ })
+ return collector
+
+ @property
+ def size(self):
+ """The number of the :class:`Dataset` objects within :class:`Databook`."""
+ return len(self._datasets)
+
+ def load(self, in_stream, format, **kwargs):
+ """
+ Import `in_stream` to the :class:`Databook` object using the `format`.
+ `in_stream` can be a file-like object, a string, or a bytestring.
+
+ :param \\*\\*kwargs: (optional) custom configuration to the format `import_book`.
+ """
+
+ stream = normalize_input(in_stream)
+ if not format:
+ format = detect_format(stream)
+
+ fmt = registry.get_format(format)
+ if not hasattr(fmt, 'import_book'):
+ raise UnsupportedFormat(f'Format {format} cannot be loaded.')
+
+ fmt.import_book(self, stream, **kwargs)
+ return self
+
+ def export(self, format, **kwargs):
+ """
+ Export :class:`Databook` object to `format`.
+
+ :param \\*\\*kwargs: (optional) custom configuration to the format `export_book`.
+ """
+ fmt = registry.get_format(format)
+ if not hasattr(fmt, 'export_book'):
+ raise UnsupportedFormat(f'Format {format} cannot be exported.')
+
+ return fmt.export_book(self, **kwargs)
+
+
+def detect_format(stream):
+ """Return format name of given stream (file-like object, string, or bytestring)."""
+ stream = normalize_input(stream)
+ fmt_title = None
+ for fmt in registry.formats():
+ try:
+ if fmt.detect(stream):
+ fmt_title = fmt.title
+ break
+ except AttributeError:
+ pass
+ finally:
+ if hasattr(stream, 'seek'):
+ stream.seek(0)
+ return fmt_title
+
+
+def import_set(stream, format=None, **kwargs):
+ """Return dataset of given stream (file-like object, string, or bytestring)."""
+
+ return Dataset().load(stream, format, **kwargs)
+
+
+def import_book(stream, format=None, **kwargs):
+ """Return dataset of given stream (file-like object, string, or bytestring)."""
+
+ return Databook().load(stream, format, **kwargs)
+
+
+registry.register_builtins()
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/exceptions.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab64ad25fc9007f5c5ba1142dd71bb5e85c39d74
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/exceptions.py
@@ -0,0 +1,22 @@
+class TablibException(Exception):
+ """Tablib common exception."""
+
+
+class InvalidDatasetType(TablibException, TypeError):
+ """Only Datasets can be added to a Databook."""
+
+
+class InvalidDimensions(TablibException, ValueError):
+ """The size of the column or row doesn't fit the table dimensions."""
+
+
+class InvalidDatasetIndex(TablibException, IndexError):
+ """Outside of Dataset size."""
+
+
+class HeadersNeeded(TablibException, AttributeError):
+ """Header parameter must be given when appending a column to this Dataset."""
+
+
+class UnsupportedFormat(TablibException, NotImplementedError):
+ """Format not supported."""
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/__init__.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d698d59ffa91be9b48ce6921eb574549736a8a5d
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/__init__.py
@@ -0,0 +1,144 @@
+""" Tablib - formats
+"""
+
+__lazy_modules__ = {
+ "functools",
+ "importlib",
+ "importlib.util",
+ "tablib.exceptions",
+ "tablib.formats._csv",
+ "tablib.formats._json",
+ "tablib.formats._tsv",
+ "tablib.utils",
+}
+
+from functools import partialmethod
+from importlib import import_module
+from importlib.util import find_spec
+
+from ..exceptions import UnsupportedFormat
+from ..utils import normalize_input
+from ._csv import CSVFormat
+from ._json import JSONFormat
+from ._tsv import TSVFormat
+
+uninstalled_format_messages = {
+ "cli": {"package_name": "tabulate package", "extras_name": "cli"},
+ "df": {"package_name": "pandas package", "extras_name": "pandas"},
+ "ods": {"package_name": "odfpy package", "extras_name": "ods"},
+ "xls": {"package_name": "xlrd and xlwt packages", "extras_name": "xls"},
+ "xlsx": {"package_name": "openpyxl package", "extras_name": "xlsx"},
+ "yaml": {"package_name": "pyyaml package", "extras_name": "yaml"},
+}
+
+
+def load_format_class(dotted_path):
+ try:
+ module_path, class_name = dotted_path.rsplit('.', 1)
+ return getattr(import_module(module_path), class_name)
+ except (ValueError, AttributeError) as err:
+ raise ImportError(f"Unable to load format class '{dotted_path}' ({err})")
+
+
+class FormatDescriptorBase:
+ def __init__(self, key, format_or_path):
+ self.key = key
+ self._format_path = None
+ if isinstance(format_or_path, str):
+ self._format = None
+ self._format_path = format_or_path
+ else:
+ self._format = format_or_path
+
+ def ensure_format_loaded(self):
+ if self._format is None:
+ self._format = load_format_class(self._format_path)
+
+
+class ImportExportBookDescriptor(FormatDescriptorBase):
+ def __get__(self, obj, cls, **kwargs):
+ self.ensure_format_loaded()
+ return self._format.export_book(obj, **kwargs)
+
+ def __set__(self, obj, val):
+ self.ensure_format_loaded()
+ return self._format.import_book(obj, normalize_input(val))
+
+
+class ImportExportSetDescriptor(FormatDescriptorBase):
+ def __get__(self, obj, cls, **kwargs):
+ self.ensure_format_loaded()
+ return self._format.export_set(obj, **kwargs)
+
+ def __set__(self, obj, val):
+ self.ensure_format_loaded()
+ return self._format.import_set(obj, normalize_input(val))
+
+
+class Registry:
+ _formats = {}
+
+ def register(self, key, format_or_path):
+ from ..core import Databook, Dataset
+
+ # Create Databook. read or read/write properties
+ setattr(Databook, key, ImportExportBookDescriptor(key, format_or_path))
+
+ # Create Dataset. read or read/write properties,
+ # and Dataset.get_/set_ methods.
+ setattr(Dataset, key, ImportExportSetDescriptor(key, format_or_path))
+ try:
+ setattr(Dataset, f'get_{key}', partialmethod(Dataset._get_in_format, key))
+ setattr(Dataset, f'set_{key}', partialmethod(Dataset._set_in_format, key))
+ except AttributeError:
+ setattr(Dataset, f'get_{key}', partialmethod(Dataset._get_in_format, key))
+
+ self._formats[key] = format_or_path
+
+ def register_builtins(self):
+ # Registration ordering matters for autodetection.
+ self.register('json', JSONFormat())
+ # xlsx before as xls (xlrd) can also read xlsx
+ if find_spec('openpyxl'):
+ self.register('xlsx', 'tablib.formats._xlsx.XLSXFormat')
+ if find_spec('xlrd') and find_spec('xlwt'):
+ self.register('xls', 'tablib.formats._xls.XLSFormat')
+ if find_spec('yaml'):
+ self.register('yaml', 'tablib.formats._yaml.YAMLFormat')
+ self.register('csv', CSVFormat())
+ self.register('tsv', TSVFormat())
+ if find_spec('odf'):
+ self.register('ods', 'tablib.formats._ods.ODSFormat')
+ self.register('dbf', 'tablib.formats._dbf.DBFFormat')
+ self.register('html', 'tablib.formats._html.HTMLFormat')
+ self.register('jira', 'tablib.formats._jira.JIRAFormat')
+ self.register('latex', 'tablib.formats._latex.LATEXFormat')
+ if find_spec('pandas'):
+ self.register('df', 'tablib.formats._df.DataFrameFormat')
+ self.register('rst', 'tablib.formats._rst.ReSTFormat')
+ self.register('sql', 'tablib.formats._sql.SQLFormat')
+ if find_spec('tabulate'):
+ self.register('cli', 'tablib.formats._cli.CLIFormat')
+
+ def formats(self):
+ for key, frm in self._formats.items():
+ if isinstance(frm, str):
+ self._formats[key] = load_format_class(frm)
+ yield self._formats[key]
+
+ def get_format(self, key):
+ if key not in self._formats:
+ if key in uninstalled_format_messages:
+ raise UnsupportedFormat(
+ "The '{key}' format is not available. You may want to install the "
+ "{package_name} (or `pip install \"tablib[{extras_name}]\"`).".format(
+ **uninstalled_format_messages[key], key=key
+ )
+ )
+ raise UnsupportedFormat(f"Tablib has no format '{key}' or it is not registered.")
+ if isinstance(self._formats[key], str):
+ self._formats[key] = load_format_class(self._formats[key])
+ return self._formats[key]
+
+
+registry = Registry()
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_cli.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_cli.py
new file mode 100644
index 0000000000000000000000000000000000000000..db57a9c0a855a5bb88b42e493bcee94532967e65
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_cli.py
@@ -0,0 +1,23 @@
+"""Tablib - Command-line Interface table export support.
+
+ Generates a representation for CLI from the dataset.
+ Wrapper for tabulate library.
+"""
+
+__lazy_modules__ = {"tabulate"}
+
+from tabulate import tabulate as Tabulate
+
+
+class CLIFormat:
+ """ Class responsible to export to CLI Format """
+ title = 'cli'
+ DEFAULT_FMT = 'plain'
+
+ @classmethod
+ def export_set(cls, dataset, **kwargs):
+ """Returns CLI representation of a Dataset."""
+ if dataset.headers:
+ kwargs.setdefault('headers', dataset.headers)
+ kwargs.setdefault('tablefmt', cls.DEFAULT_FMT)
+ return Tabulate(dataset, **kwargs)
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_csv.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_csv.py
new file mode 100644
index 0000000000000000000000000000000000000000..e57e1d9ed12cfcd140997ab1c23ad105a89dd9b7
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_csv.py
@@ -0,0 +1,63 @@
+""" Tablib - *SV Support.
+"""
+
+__lazy_modules__ = {"csv", "io"}
+
+import csv
+from io import StringIO
+
+
+class CSVFormat:
+ title = 'csv'
+ extensions = ('csv',)
+
+ DEFAULT_DELIMITER = ','
+
+ @classmethod
+ def export_stream_set(cls, dataset, **kwargs):
+ """Returns CSV representation of Dataset as file-like."""
+ stream = StringIO()
+
+ kwargs.setdefault('delimiter', cls.DEFAULT_DELIMITER)
+
+ _csv = csv.writer(stream, **kwargs)
+
+ for row in dataset._package(dicts=False):
+ _csv.writerow(row)
+
+ stream.seek(0)
+ return stream
+
+ @classmethod
+ def export_set(cls, dataset, **kwargs):
+ """Returns CSV representation of Dataset."""
+ stream = cls.export_stream_set(dataset, **kwargs)
+ return stream.getvalue()
+
+ @classmethod
+ def import_set(cls, dset, in_stream, headers=True, skip_lines=0, **kwargs):
+ """Returns dataset from CSV stream."""
+
+ dset.wipe()
+
+ kwargs.setdefault('delimiter', cls.DEFAULT_DELIMITER)
+
+ rows = csv.reader(in_stream, **kwargs)
+ for i, row in enumerate(rows):
+ if i < skip_lines:
+ continue
+ if i == skip_lines and headers:
+ dset.headers = row
+ elif row:
+ if i > 0 and len(row) < dset.width:
+ row += [''] * (dset.width - len(row))
+ dset.append(row)
+
+ @classmethod
+ def detect(cls, stream, delimiter=None):
+ """Returns True if given stream is valid CSV."""
+ try:
+ csv.Sniffer().sniff(stream.read(2048), delimiters=delimiter or cls.DEFAULT_DELIMITER)
+ return True
+ except Exception:
+ return False
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_dbf.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_dbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..16737037369fd700d718e7b5050f0af8a9fca7fa
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_dbf.py
@@ -0,0 +1,74 @@
+""" Tablib - DBF Support.
+"""
+
+__lazy_modules__ = {
+ "io",
+ "os",
+ "tablib._vendor",
+ "tempfile",
+}
+
+import io
+import os
+import tempfile
+
+from .._vendor.dbfpy import dbf, dbfnew
+from .._vendor.dbfpy import record as dbfrecord
+
+
+class DBFFormat:
+ title = 'dbf'
+ extensions = ('csv',)
+
+ DEFAULT_ENCODING = 'utf-8'
+
+ @classmethod
+ def export_set(cls, dataset):
+ """Returns DBF representation of a Dataset"""
+ new_dbf = dbfnew.dbf_new()
+ temp_file, temp_uri = tempfile.mkstemp()
+
+ # create the appropriate fields based on the contents of the first row
+ first_row = dataset[0]
+ for fieldname, field_value in zip(dataset.headers, first_row):
+ if type(field_value) in [int, float]:
+ new_dbf.add_field(fieldname, 'N', 10, 8)
+ else:
+ new_dbf.add_field(fieldname, 'C', 80)
+
+ new_dbf.write(temp_uri)
+
+ dbf_file = dbf.Dbf(temp_uri, readOnly=0)
+ for row in dataset:
+ record = dbfrecord.DbfRecord(dbf_file)
+ for fieldname, field_value in zip(dataset.headers, row):
+ record[fieldname] = field_value
+ record.store()
+
+ dbf_file.close()
+ dbf_stream = open(temp_uri, 'rb')
+ stream = io.BytesIO(dbf_stream.read())
+ dbf_stream.close()
+ os.close(temp_file)
+ os.remove(temp_uri)
+ return stream.getvalue()
+
+ @classmethod
+ def import_set(cls, dset, in_stream):
+ """Returns a dataset from a DBF stream."""
+
+ dset.wipe()
+ _dbf = dbf.Dbf(in_stream)
+ dset.headers = _dbf.fieldNames
+ for record in range(_dbf.recordCount):
+ row = [_dbf[record][f] for f in _dbf.fieldNames]
+ dset.append(row)
+
+ @classmethod
+ def detect(cls, stream):
+ """Returns True if the given stream is valid DBF"""
+ try:
+ dbf.Dbf(stream, readOnly=True)
+ return True
+ except Exception:
+ return False
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_df.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_df.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4f9d80c39dcd1ae49de5fa8a62dd7805ec27f90
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_df.py
@@ -0,0 +1,41 @@
+""" Tablib - DataFrame Support.
+"""
+
+try:
+ from pandas import DataFrame
+except ImportError:
+ DataFrame = None
+
+
+class DataFrameFormat:
+ title = 'df'
+ extensions = ('df',)
+
+ @classmethod
+ def detect(cls, stream):
+ """Returns True if given stream is a DataFrame."""
+ if DataFrame is None:
+ return False
+ elif isinstance(stream, DataFrame):
+ return True
+ try:
+ DataFrame(stream.read())
+ return True
+ except ValueError:
+ return False
+
+ @classmethod
+ def export_set(cls, dset):
+ """Returns DataFrame representation of DataBook."""
+ if DataFrame is None:
+ raise NotImplementedError(
+ 'DataFrame Format requires `pandas` to be installed.'
+ ' Try `pip install "tablib[pandas]"`.')
+ dataframe = DataFrame(dset.dict, columns=dset.headers)
+ return dataframe
+
+ @classmethod
+ def import_set(cls, dset, in_stream):
+ """Returns dataset from DataFrame."""
+ dset.wipe()
+ dset.dict = in_stream.to_dict(orient='records')
diff --git a/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_html.py b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_html.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc6930093d8a2867527aafe0986e252b9e6ae018
--- /dev/null
+++ b/tasks/tasksmith-b6d969373e1e/tests/source/src/tablib/formats/_html.py
@@ -0,0 +1,117 @@
+""" Tablib - HTML export support.
+"""
+
+__lazy_modules__ = {"xml", "xml.etree"}
+
+from html.parser import HTMLParser
+from xml.etree import ElementTree as ET
+
+
+class HTMLFormat:
+ BOOK_ENDINGS = 'h3'
+
+ title = 'html'
+ extensions = ('html', )
+
+ @classmethod
+ def export_set(cls, dataset):
+ """HTML representation of a Dataset."""
+
+ table = ET.Element('table')
+ if dataset.headers is not None:
+ head = ET.Element('thead')
+ tr = ET.Element('tr')
+ for header in dataset.headers:
+ th = ET.Element('th')
+ th.text = str(header) if header is not None else ''
+ tr.append(th)
+ head.append(tr)
+ table.append(head)
+
+ body = ET.Element('tbody')
+ for row in dataset:
+ tr = ET.Element('tr')
+ for item in row:
+ td = ET.Element('td')
+ td.text = str(item) if item is not None else ''
+ tr.append(td)
+ body.append(tr)
+ table.append(body)
+
+ return ET.tostring(table, method='html', encoding='unicode')
+
+ @classmethod
+ def export_book(cls, databook):
+ """HTML representation of a Databook."""
+
+ result = ''
+ for i, dset in enumerate(databook._datasets):
+ title = dset.title if dset.title else f'Set {i}'
+ result += f'<{cls.BOOK_ENDINGS}>{title}{cls.BOOK_ENDINGS}>\n'
+ result += dset.html
+ result += '\n'
+
+ return result
+
+ @classmethod
+ def import_set(cls, dset, in_stream, table_id=None):
+ """Returns dataset from HTML content."""
+
+ dset.wipe()
+ parser = TablibHTMLParser(dset, table_id=table_id)
+ parser.feed(in_stream.read())
+ if not parser.table_found:
+ if table_id:
+ raise ValueError(f'No
found with id="{table_id}" in input HTML')
+ else:
+ raise ValueError('No
+ """
+
+ self.assertIsNone(data.headers)
+ self.assertEqual([
+ ('John', 'Adams', '90'),
+ ('George', 'Washington', '67'),
+ ], data[:])
+
+ def test_html_import_no_table(self):
+ html = ""
+
+ with self.assertRaises(ValueError) as exc:
+ data.html = html
+ self.assertEqual('No
found in input HTML', str(exc.exception))
+
+ def test_html_import_table_id(self):
+ """A table with a specific id can be targeted for import."""
+ html_input = """
+
+
+
IGNORE
IGNORE
+
+
+
first_name
last_name
+
John
Adams
"
+
+
+ """
+ dataset = tablib.import_set(html_input, format="html", table_id="import")
+ self.assertEqual(['first_name', 'last_name'], dataset.headers)
+ self.assertEqual([('John', 'Adams')], dataset[:])
+
+ # If the id is not found, an error is raised
+ with self.assertRaises(ValueError) as exc:
+ tablib.import_set(html_input, format="html", table_id="notfound")
+ self.assertEqual('No
+
+### Working with **sessions**
+```python
+>>> xnys.is_session("2022-01-01")
+False
+
+>>> xnys.sessions_in_range("2022-01-01", "2022-01-11")
+DatetimeIndex(['2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06',
+ '2022-01-07', '2022-01-10', '2022-01-11'],
+ dtype='datetime64[ns]', freq='C')
+
+>>> xnys.sessions_window("2022-01-03", 7)
+DatetimeIndex(['2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06',
+ '2022-01-07', '2022-01-10', '2022-01-11'],
+ dtype='datetime64[ns]', freq='C')
+
+>>> xnys.date_to_session("2022-01-01", direction="next")
+Timestamp('2022-01-03 00:00:00', freq='C')
+
+>>> xnys.previous_session("2022-01-11")
+Timestamp('2022-01-10 00:00:00', freq='C')
+
+>>> xhkg.trading_index(
+... "2021-12-30", "2021-12-31", period="90min", force=True
+... )
+IntervalIndex([[2021-12-30 01:30:00, 2021-12-30 03:00:00), [2021-12-30 03:00:00, 2021-12-30 04:00:00), [2021-12-30 05:00:00, 2021-12-30 06:30:00), [2021-12-30 06:30:00, 2021-12-30 08:00:00), [2021-12-31 01:30:00, 2021-12-31 03:00:00), [2021-12-31 03:00:00, 2021-12-31 04:00:00)], dtype='interval[datetime64[ns, UTC], left]')
+```
+See the [sessions tutorial](docs/tutorials/sessions.ipynb) for a deeper dive into sessions.
+
+### Working with **minutes**
+```python
+>>> xhkg.session_minutes("2022-01-03")
+DatetimeIndex(['2022-01-03 01:30:00+00:00', '2022-01-03 01:31:00+00:00',
+ '2022-01-03 01:32:00+00:00', '2022-01-03 01:33:00+00:00',
+ '2022-01-03 01:34:00+00:00', '2022-01-03 01:35:00+00:00',
+ '2022-01-03 01:36:00+00:00', '2022-01-03 01:37:00+00:00',
+ '2022-01-03 01:38:00+00:00', '2022-01-03 01:39:00+00:00',
+ ...
+ '2022-01-03 07:50:00+00:00', '2022-01-03 07:51:00+00:00',
+ '2022-01-03 07:52:00+00:00', '2022-01-03 07:53:00+00:00',
+ '2022-01-03 07:54:00+00:00', '2022-01-03 07:55:00+00:00',
+ '2022-01-03 07:56:00+00:00', '2022-01-03 07:57:00+00:00',
+ '2022-01-03 07:58:00+00:00', '2022-01-03 07:59:00+00:00'],
+ dtype='datetime64[ns, UTC]', length=330, freq=None)
+
+>>> mins = [ "2022-01-03 " + tm for tm in ["01:29", "01:30", "04:20", "07:59", "08:00"] ]
+>>> [ xhkg.is_trading_minute(minute) for minute in mins ]
+[False, True, False, True, False] # by default minutes are closed on the left side
+
+>>> xhkg.is_break_minute("2022-01-03 04:20")
+True
+
+>>> xhkg.previous_close("2022-01-03 08:10")
+Timestamp('2022-01-03 08:00:00+0000', tz='UTC')
+
+>>> xhkg.previous_minute("2022-01-03 08:10")
+Timestamp('2022-01-03 07:59:00+0000', tz='UTC')
+```
+Check out the [minutes tutorial](docs/tutorials/minutes.ipynb) for a deeper dive that includes an explanation of the concept of 'minutes' and how the "side" option determines which minutes are treated as trading minutes.
+
+## Tutorials
+* [sessions.ipynb](docs/tutorials/sessions.ipynb) - all things [sessions](#Working-with-sessions).
+* [minutes.ipynb](docs/tutorials/minutes.ipynb) - all things [minutes](#Working-with-minutes). Don't miss this one!
+* [calendar_properties.ipynb](docs/tutorials/calendar_properties.ipynb) - calendar constrution and a walk through the schedule and all other calendar properties.
+* [calendar_methods.ipynb](docs/tutorials/calendar_methods.ipynb) - a walk through all the methods available to interrogate a calendar.
+* [trading_index.ipynb](docs/tutorials/trading_index.ipynb) - a method that warrants a tutorial all of its own.
+
+Hopefully you'll find that `exchange_calendars` has the method you need to get the information you want. If it doesn't, either [PR](https://github.com/gerrymanoim/exchange_calendars/pulls) it or [raise an issue](https://github.com/gerrymanoim/exchange_calendars/issues) and let us know!
+
+## Command Line Usage
+Print a unix-cal like calendar straight from the command line (holidays are indicated by brackets)...
+
+```bash
+ecal XNYS 2020
+```
+ 2020
+ January February March
+ Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
+ [ 1] 2 3 [ 4] [ 1]
+ [ 5] 6 7 8 9 10 [11] [ 2] 3 4 5 6 7 [ 8] [ 1] 2 3 4 5 6 [ 7]
+ [12] 13 14 15 16 17 [18] [ 9] 10 11 12 13 14 [15] [ 8] 9 10 11 12 13 [14]
+ [19][20] 21 22 23 24 [25] [16][17] 18 19 20 21 [22] [15] 16 17 18 19 20 [21]
+ [26] 27 28 29 30 31 [23] 24 25 26 27 28 [29] [22] 23 24 25 26 27 [28]
+ [29] 30 31
+
+ April May June
+ Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
+ 1 2 3 [ 4] 1 [ 2] 1 2 3 4 5 [ 6]
+ [ 5] 6 7 8 9 [10][11] [ 3] 4 5 6 7 8 [ 9] [ 7] 8 9 10 11 12 [13]
+ [12] 13 14 15 16 17 [18] [10] 11 12 13 14 15 [16] [14] 15 16 17 18 19 [20]
+ [19] 20 21 22 23 24 [25] [17] 18 19 20 21 22 [23] [21] 22 23 24 25 26 [27]
+ [26] 27 28 29 30 [24][25] 26 27 28 29 [30] [28] 29 30
+ [31]
+
+ July August September
+ Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
+ 1 2 [ 3][ 4] [ 1] 1 2 3 4 [ 5]
+ [ 5] 6 7 8 9 10 [11] [ 2] 3 4 5 6 7 [ 8] [ 6][ 7] 8 9 10 11 [12]
+ [12] 13 14 15 16 17 [18] [ 9] 10 11 12 13 14 [15] [13] 14 15 16 17 18 [19]
+ [19] 20 21 22 23 24 [25] [16] 17 18 19 20 21 [22] [20] 21 22 23 24 25 [26]
+ [26] 27 28 29 30 31 [23] 24 25 26 27 28 [29] [27] 28 29 30
+ [30] 31
+
+ October November December
+ Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
+ 1 2 [ 3] 1 2 3 4 [ 5]
+ [ 4] 5 6 7 8 9 [10] [ 1] 2 3 4 5 6 [ 7] [ 6] 7 8 9 10 11 [12]
+ [11] 12 13 14 15 16 [17] [ 8] 9 10 11 12 13 [14] [13] 14 15 16 17 18 [19]
+ [18] 19 20 21 22 23 [24] [15] 16 17 18 19 20 [21] [20] 21 22 23 24 [25][26]
+ [25] 26 27 28 29 30 [31] [22] 23 24 25 [26] 27 [28] [27] 28 29 30 31
+ [29] 30
+
+```bash
+ecal XNYS 1 2020
+```
+
+ January 2020
+ Su Mo Tu We Th Fr Sa
+ [ 1] 2 3 [ 4]
+ [ 5] 6 7 8 9 10 [11]
+ [12] 13 14 15 16 17 [18]
+ [19][20] 21 22 23 24 [25]
+ [26] 27 28 29 30 31
+
+## Frequently Asked Questions
+
+### **How can I create a new calendar?**
+
+First off, make sure the calendar you're after hasn't already been defined; exchange calendars comes with over [50 pre-defined calendars](#Calendars), including major security exchanges.
+
+If you can't find what you're after, a custom calendar can be created as a subclass of [ExchangeCalendar](exchange_calendars/exchange_calendar.py). [This workflow](.github/pull_request_template.md) describes the process to add a new calendar to `exchange_calendars`. Just follow the relevant parts.
+
+To access the new calendar via `get_calendar` call either `xcals.register_calendar` or `xcals.register_calendar_type` to register, respectively, a specific calendar instance or a calendar factory (i.e. the subclass).
+
+### **Can I contribute a new calendar to exchange calendars?**
+
+Yes please! The workflow can be found [here](.github/pull_request_template.md).
+
+### **`` is missing a holiday, has a wrong time, should have a break etc...**
+
+**All** of the exchange calendars are maintained by user contributions. If a calendar you care about needs revising, please open a [PR](https://github.com/gerrymanoim/exchange_calendars/pulls) - that's how this thing works! (Never contributed to a project before and it all seems a bit daunting? Check [this out](https://github.com/firstcontributions/first-contributions/blob/main/README.md) and don't look back!)
+
+You'll find the workflow to modify an existing calendar [here](.github/pull_request_template.md).
+
+### **What times are considered open and closed?**
+
+`exchange_calendars` attempts to be broadly useful by considering an exchange to be open only during periods of regular trading. During any pre-trading, post-trading or auction period the exchange is treated as closed. An exchange is also treated as closed during any observed lunch break.
+
+See the [minutes tutorial](docs/tutorials/minutes.ipynb) for a detailed explanation of which minutes an exchange is considered open over. If you previously used `trading_calendars`, or `exchange_calendars` prior to release 3.4, then this is the place to look for answers to questions of how the definition of trading minutes has changed over time (and is now stable and flexible!).
+
+## Calendars
+
+| Exchange | ISO Code | Country | Version Added | Exchange Website (English) |
+|---------------------------------|----------| -------------- |---------------| ------------------------------------------------------------ |
+| New York Stock Exchange | XNYS | USA | 1.0 | https://www.nyse.com/index |
+| CBOE Futures | XCBF | USA | 1.0 | https://markets.cboe.com/us/futures/overview/ |
+| Chicago Mercantile Exchange | CMES | USA | 1.0 | https://www.cmegroup.com/ |
+| ICE US | IEPA | USA | 1.0 | https://www.theice.com/index |
+| Toronto Stock Exchange | XTSE | Canada | 1.0 | https://www.tsx.com/ |
+| BMF Bovespa | BVMF | Brazil | 1.0 | http://www.b3.com.br/en_us/ |
+| London Stock Exchange | XLON | England | 1.0 | https://www.londonstockexchange.com/ |
+| Euronext Amsterdam | XAMS | Netherlands | 1.2 | https://www.euronext.com/en/regulation/amsterdam |
+| Euronext Brussels | XBRU | Belgium | 1.2 | https://www.euronext.com/en/regulation/brussels |
+| Euronext Lisbon | XLIS | Portugal | 1.2 | https://www.euronext.com/en/regulation/lisbon |
+| Euronext Paris | XPAR | France | 1.2 | https://www.euronext.com/en/regulation/paris |
+| Frankfurt Stock Exchange | XFRA | Germany | 1.2 | http://en.boerse-frankfurt.de/ |
+| SIX Swiss Exchange | XSWX | Switzerland | 1.2 | https://www.six-group.com/en/home.html |
+| Tokyo Stock Exchange | XTKS | Japan | 1.2 | https://www.jpx.co.jp/english/ |
+| Australian Securities Exchange | XASX | Australia | 1.3 | https://www.asx.com.au/ |
+| Bolsa de Madrid | XMAD | Spain | 1.3 | https://www.bolsamadrid.es |
+| Borsa Italiana | XMIL | Italy | 1.3 | https://www.borsaitaliana.it |
+| New Zealand Exchange | XNZE | New Zealand | 1.3 | https://www.nzx.com/ |
+| Wiener Borse | XWBO | Austria | 1.3 | https://www.wienerborse.at/en/ |
+| Hong Kong Stock Exchange | XHKG | Hong Kong | 1.3 | https://www.hkex.com.hk/?sc_lang=en |
+| Copenhagen Stock Exchange | XCSE | Denmark | 1.4 | http://www.nasdaqomxnordic.com/ |
+| Helsinki Stock Exchange | XHEL | Finland | 1.4 | http://www.nasdaqomxnordic.com/ |
+| Stockholm Stock Exchange | XSTO | Sweden | 1.4 | http://www.nasdaqomxnordic.com/ |
+| Oslo Stock Exchange | XOSL | Norway | 1.4 | https://www.oslobors.no/ob_eng/ |
+| Irish Stock Exchange | XDUB | Ireland | 1.4 | http://www.ise.ie/ |
+| Bombay Stock Exchange | XBOM | India | 1.5 | https://www.bseindia.com |
+| Singapore Exchange | XSES | Singapore | 1.5 | https://www.sgx.com |
+| Shanghai Stock Exchange | XSHG | China | 1.5 | http://english.sse.com.cn |
+| Korea Exchange | XKRX | South Korea | 1.6 | http://global.krx.co.kr |
+| Iceland Stock Exchange | XICE | Iceland | 1.7 | http://www.nasdaqomxnordic.com/ |
+| Poland Stock Exchange | XWAR | Poland | 1.9 | http://www.gpw.pl |
+| Santiago Stock Exchange | XSGO | Chile | 1.9 | https://www.bolsadesantiago.com/ |
+| Colombia Securities Exchange | XBOG | Colombia | 1.9 | https://www.bvc.com.co/nueva/https://www.bvc.com.co/nueva/ |
+| Mexican Stock Exchange | XMEX | Mexico | 1.9 | https://www.bmv.com.mx |
+| Lima Stock Exchange | XLIM | Peru | 1.9 | https://www.bvl.com.pe |
+| Prague Stock Exchange | XPRA | Czech Republic | 1.9 | https://www.pse.cz/en/ |
+| Budapest Stock Exchange | XBUD | Hungary | 1.10 | https://bse.hu/ |
+| Athens Stock Exchange | ASEX | Greece | 1.10 | http://www.helex.gr/ |
+| Istanbul Stock Exchange | XIST | Turkey | 1.10 | https://www.borsaistanbul.com/en/ |
+| Johannesburg Stock Exchange | XJSE | South Africa | 1.10 | https://www.jse.co.za/z |
+| Malaysia Stock Exchange | XKLS | Malaysia | 1.11 | http://www.bursamalaysia.com/market/ |
+| Moscow Exchange | XMOS | Russia | 1.11 | https://www.moex.com/en/ |
+| Philippine Stock Exchange | XPHS | Philippines | 1.11 | https://www.pse.com.ph/ |
+| Stock Exchange of Thailand | XBKK | Thailand | 1.11 | https://www.set.or.th/set/mainpage.do?language=en&country=US |
+| Indonesia Stock Exchange | XIDX | Indonesia | 1.11 | https://www.idx.co.id/ |
+| Taiwan Stock Exchange Corp. | XTAI | Taiwan | 1.11 | https://www.twse.com.tw/en/ |
+| Buenos Aires Stock Exchange | XBUE | Argentina | 1.11 | https://www.bcba.sba.com.ar/ |
+| Pakistan Stock Exchange | XKAR | Pakistan | 1.11 | https://www.psx.com.pk/ |
+| Xetra | XETR | Germany | 2.1 | https://www.xetra.com/ |
+| Tel Aviv Stock Exchange | XTAE | Israel | 2.1 | https://www.tase.co.il/ |
+| Astana International Exchange | AIXK | Kazakhstan | 3.2 | https://www.aix.kz/ |
+| Bucharest Stock Exchange | XBSE | Romania | 3.2 | https://www.bvb.ro/ |
+| Saudi Stock Exchange | XSAU | Saudi Arabia | 4.2 | https://www.saudiexchange.sa/ |
+
+> Note that exchange calendars are defined by their [ISO-10383](https://www.iso20022.org/10383/iso-10383-market-identifier-codes) market identifier code.
+
+## [`market-prices`](https://github.com/maread99/market_prices)
+Much of the post v3 development of `exchange_calendars` has been driven by the [`market_prices`](https://github.com/maread99/market_prices) library. Check it out if you like the idea of using `exchange_calendars` to create meaningful OHLCV datasets. It works out-the-box with freely available data!
+
+## Deprecations and Renaming
+
+### Methods renamed in version 4.0.3 and removed in 4.3
+| Previous name | New name |
+| ------------- | -------- |
+| bound_start | bound_min |
+| bound_end | bound_max |
+
+### Methods deprecated in 4.0 and removed in 4.3
+| Deprecated method | Reason |
+| ----------------- | ------ |
+| sessions_closes | use `.closes[start:end]` |
+| sessions_opens | use `.opens[start:end]` |
+
+### Methods with a parameter renamed in 4.0
+| Method
+| ------
+| is_session |
+| is_open_on_minute |
+| minutes_in_range |
+| minutes_window |
+| next_close |
+| next_minute |
+| next_open |
+| previous_close |
+| previous_minute |
+| previous_open |
+| session_break_end |
+| session_break_start |
+| session_close |
+| session_open |
+| sessions_in_range |
+| sessions_window |
+
+### Methods renamed in version 3.4 and removed in 4.0
+| Previous name | New name |
+| ------------- | -------- |
+| all_minutes | minutes |
+| all_minutes_nanos | minutes_nanos |
+| all_sessions | sessions |
+| break_start_and_end_for_session | session_break_start_end |
+| date_to_session_label | date_to_session |
+| first_trading_minute | first_minute |
+| first_trading_session | first_session |
+| has_breaks | sessions_has_break |
+| last_trading_minute | last_minute |
+| last_trading_session | last_session |
+| next_session_label | next_session |
+| open_and_close_for_session | session_open_close |
+| previous_session_label | previous_session |
+| market_break_ends_nanos | break_ends_nanos |
+| market_break_starts_nanos | break_starts_nanos |
+| market_closes_nanos | closes_nanos |
+| market_opens_nanos | opens_nanos |
+| minute_index_to_session_labels | minutes_to_sessions |
+| minute_to_session_label | minute_to_session |
+| minutes_count_for_sessions_in_range | sessions_minutes_count |
+| minutes_for_session | session_minutes |
+| minutes_for_sessions_in_range | sessions_minutes |
+| session_closes_in_range | sessions_closes |
+| session_distance | sessions_distance |
+| session_opens_in_range | sessions_opens |
+
+### Other methods deprecated in 3.4 and removed in 4.0
+| Removed Method
+| -----------------
+| execution_minute_for_session
+| execution_minute_for_sessions_in_range
+| execution_time_from_close
+| execution_time_from_open
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/docs/changes_archive.md b/tasks/tasksmith-ca08ab4caec6/environment/source/docs/changes_archive.md
new file mode 100644
index 0000000000000000000000000000000000000000..699f545da4875dd44ab213d5988cb5fccaeaeb7b
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/docs/changes_archive.md
@@ -0,0 +1,47 @@
+**NOTE**: This file is NOT a comprehensive changes log but rather an archive of sections temporarily included to the README to advise of significant changes.
+
+## **v4 released** (June 2022)
+
+**The earliest stable version of v4 is 4.0.1** (not 4.0).
+
+### What's changed?
+
+Version 4.0.1 completes the transition to a more consistent interface across the package. The most significant changes are:
+
+* **Sessions are now timezone-naive** (previously UTC).
+* Schedule columns now have timezone set as UTC (whilst the times have always been defined in terms of UTC, previously the dtype was timezone-naive).
+* The following schedule columns were renamed:
+ * 'market_open' renamed as 'open'.
+ * 'market_close' renamed as 'close'.
+* Default calendar 'side' for all calendars is now "left" (previously "right" for 24-hour calendars and "both" for all others). This **changes the minutes that are considered trading minutes by default** (see [minutes tutorial](docs/tutorials/minutes.ipynb) for an explanation of trading minutes).
+* The 'count' parameter of `sessions_window` and `minutes_window` methods now reflects the window length (previously window length + 1).
+* New `is_open_at_time` calendar method to evaluate if an exchange is open as at a specific instance (as opposed to over an evaluated minute).
+* The minimum Python version supported is now 3.8 (previously 3.7).
+* Parameters have been renamed for some methods (list [here](#Methods-with-a-parameter-renamed-in-40))
+* The following methods have been deprecated:
+ * `sessions_opens` (use `.opens[start:end]`)
+ * `sessions_closes` (use `.closes[start:end]`)
+* Methods deprecated in 3.4 have been removed (lists [here](#Methods-renamed-in-version-34-and-removed-in-40) and [here](#Other-methods-deprecated-in-34-and-removed-in-40))
+
+See the [4.0 release todo](https://github.com/gerrymanoim/exchange_calendars/issues/61) for a full list of changes and corresponding PRs.
+
+Please offer any feedback at the [v4 discussion](https://github.com/gerrymanoim/exchange_calendars/discussions/202).
+
+## **Changes in 3.4** (released October 2021)
+The 3.4 release introduced notable new features and documentation, including:
+
+* [Tutorials](#Tutorials). Five of them!
+* New calendar methods [#71](https://github.com/gerrymanoim/exchange_calendars/pull/71) (see [calendar_methods.ipynb](docs/tutorials/calendar_methods.ipynb) for usage), including:
+ * trading_index (tutorial [trading_index.ipynb](docs/tutorials/trading_index.ipynb))
+ * is_trading_minute
+ * is_break_minute
+ * minute_offset
+ * session_offset
+ * minute_offset_by_sessions
+* Calendar's now have a `side` parameter to determine which of the open, close, break-start and break-end minutes are treated as trading minutes [#71](https://github.com/gerrymanoim/exchange_calendars/pull/71).
+* 24 hour calendars are now truly 24 hours (open/close times are no longer one minute later/earlier than the actual open/close) [#71](https://github.com/gerrymanoim/exchange_calendars/pull/71).
+* Some calendar methods have been renamed to improve consistency (table of changes [here](#Methods-renamed-in-version-34)) [#85](https://github.com/gerrymanoim/exchange_calendars/issues/85). The previous names will continue to be available until version 4.0. NOTE: Some newly named methods have also made changes to parameter names, for example from `session_label` to `session` and from `start_session_label` to `start`.
+* Under-the-bonnet work has sped up many methods.
+* A test suite overhaul ([#71](https://github.com/gerrymanoim/exchange_calendars/pull/71), [#92](https://github.com/gerrymanoim/exchange_calendars/pull/92), [#96](https://github.com/gerrymanoim/exchange_calendars/pull/96)) has made it simpler to define and test calendars.
+
+Please offer any feedback at the [3.4 discussion](https://github.com/gerrymanoim/exchange_calendars/discussions/107).
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/docs/tutorials/calendar_methods.ipynb b/tasks/tasksmith-ca08ab4caec6/environment/source/docs/tutorials/calendar_methods.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..1476baba42dc04c327221a7d81d7f757569d4f1c
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/docs/tutorials/calendar_methods.ipynb
@@ -0,0 +1,3422 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Calendar methods\n",
+ "\n",
+ "This tutorial offers a walk through of all the `ExchangeCalendar` methods (for properties see the [calendar properties](./calendar_properties.ipynb) tutorial).\n",
+ "\n",
+ "The following sections cover methods according to the nature of the argument(s) they take:\n",
+ "* [Methods that query a Date](#Methods-that-query-a-Date) \n",
+ "* [Methods that query a Session](#Methods-that-query-a-Session) \n",
+ "* [Methods that query a Minute](#Methods-that-query-a-Minute) \n",
+ "* [Methods that query multiple TradingMinute](#Methods-that-query-multiple-TradingMinute) \n",
+ "* [Methods that query a range of dates](#Methods-that-query-a-range-of-dates)\n",
+ "* [Methods that query a time](#Methods-that-query-a-time)\n",
+ "\n",
+ "The following sections cover methods that evaluate an index of trading minutes or sessions:\n",
+ "* [Methods that evaluate an index of contiguous trading minutes](#Methods-that-evaluate-an-index-of-contiguous-trading-minutes)\n",
+ "* [Methods that evaluate an index of contiguous sessions](#Methods-that-evaluate-an-index-of-contiguous-sessions)\n",
+ "\n",
+ "`Date` and `Session` refer to types for 'session' parameters (see [sessions.ipynb](./sessions.ipynb) for a tutorial on how to work with sessions).\n",
+ "\n",
+ "`Minute` and `TradingMinute` refer to types for 'minute' parameters (see [minutes.ipynb](./minutes.ipynb) for a tutorial on how to work with mintues)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# setup\n",
+ "import exchange_calendars as xcals\n",
+ "import pandas as pd\n",
+ "\n",
+ "one_minute = pd.Timedelta(1, \"T\")\n",
+ "\n",
+ "nys = xcals.get_calendar(\"XNYS\") # New York Stock Exchange\n",
+ "hkg = xcals.get_calendar(\"XHKG\") # Hong Kong Stock Exchange"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Methods that query a Date"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The argument of methods in this section takes a `Date` type."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
open
\n",
+ "
break_start
\n",
+ "
break_end
\n",
+ "
close
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
2021-12-31
\n",
+ "
2021-12-31 14:30:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2021-12-31 21:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2022-01-03
\n",
+ "
2022-01-03 14:30:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2022-01-03 21:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2022-01-04
\n",
+ "
2022-01-04 14:30:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2022-01-04 21:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " open break_start break_end \\\n",
+ "2021-12-31 2021-12-31 14:30:00+00:00 NaT NaT \n",
+ "2022-01-03 2022-01-03 14:30:00+00:00 NaT NaT \n",
+ "2022-01-04 2022-01-04 14:30:00+00:00 NaT NaT \n",
+ "\n",
+ " close \n",
+ "2021-12-31 2021-12-31 21:00:00+00:00 \n",
+ "2022-01-03 2022-01-03 21:00:00+00:00 \n",
+ "2022-01-04 2022-01-04 21:00:00+00:00 "
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# for reference, all times are UTC\n",
+ "nys.schedule.loc[\"2021-12-31\":\"2022-01-04\"]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**`is_session`** queries if a date represents a session."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(False, True)"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.is_session(\"2022-01-01\"), nys.is_session(\"2022-01-04\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**`date_to_session`** will return the the passed `date` if `date` represents a session, or otherwise the nearest session in the passed `direction`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2022-01-04 00:00:00')"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# date is a session so `direction` is ignored\n",
+ "nys.date_to_session(\"2022-01-04\", direction=\"next\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2022-01-03 00:00:00', freq='C')"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.date_to_session(\"2022-01-01\", direction=\"next\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2021-12-31 00:00:00', freq='C')"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.date_to_session(\"2022-01-01\", direction=\"previous\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A ValueError is raised if `direction` is not passed and `date` is not a session."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nys.date_to_session(\"2022-01-01\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "ValueError Traceback (most recent call last)\n",
+ "Input In [7], in ()\n",
+ "----> 1 nys.date_to_session(\"2022-01-01\")\n",
+ "\n",
+ "ValueError: `date` '2022-01-01 00:00:00' does not represent a session. Consider passing a `direction`.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Methods that query a Session\n",
+ "\n",
+ "The argument of methods in this section takes a `Session` type.\n",
+ "\n",
+ "The following methods can be used to return the **open, close** and **break times** of a session..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " open break_start \\\n",
+ "2021-06-15 2021-06-15 01:30:00+00:00 2021-06-15 04:00:00+00:00 \n",
+ "\n",
+ " break_end close \n",
+ "2021-06-15 2021-06-15 05:00:00+00:00 2021-06-15 08:00:00+00:00 "
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_left = xcals.get_calendar(\"XHKG\")\n",
+ "hkg_left.schedule.loc[[\"2021-06-15\"]]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**NB** open, close, and break times are **independent of a calendar's `side`**. These properties reflect times corresponding with the start and end of regular trading periods."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# the default side is \"left\", such that the open is a trading minute...\n",
+ "hkg_left.is_trading_minute(\"2021-06-15 01:30\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# ...and so is the break_end (i.e. the open of the afternoon subsession)...\n",
+ "hkg_left.is_trading_minute(\"2021-06-15 05:00\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# but the close is not a trading minute\n",
+ "hkg_left.is_trading_minute(\"2021-06-15 08:00\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# and neither is the break_start (i.e. the close of the morning subsession)...\n",
+ "hkg_left.is_trading_minute(\"2021-06-15 04:00\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[False, False, True, True]"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# everything's reversed when `side` is \"right\"...\n",
+ "hkg_right = xcals.get_calendar(\"XHKG\", side=\"right\")\n",
+ "times = [\"01:30\", \"05:00\", \"08:00\", \"04:00\"]\n",
+ "[ hkg_right.is_trading_minute(\"2021-06-15 \" + tm) for tm in times ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[True, True, True, True]"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# everything's True when `side` is \"both\"...\n",
+ "hkg_both = xcals.get_calendar(\"XHKG\", side=\"both\")\n",
+ "[ hkg_both.is_trading_minute(\"2021-06-15 \" + tm) for tm in times ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[False, False, False, False]"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# and False when `side` is \"neither\".\n",
+ "hkg_neither = xcals.get_calendar(\"XHKG\", side=\"neither\")\n",
+ "[ hkg_neither.is_trading_minute(\"2021-06-15 \" + tm) for tm in times ]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The effect of the calendar's side can be seen in all methods that interrogate or evaluate trading minutes. For example, note the effect of different sides on the minutes associated with the XHKG session \"2021-06-15\":"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-06-15 01:30:00+00:00', '2021-06-15 01:31:00+00:00',\n",
+ " '2021-06-15 01:32:00+00:00', '2021-06-15 01:33:00+00:00',\n",
+ " '2021-06-15 01:34:00+00:00', '2021-06-15 01:35:00+00:00',\n",
+ " '2021-06-15 01:36:00+00:00', '2021-06-15 01:37:00+00:00',\n",
+ " '2021-06-15 01:38:00+00:00', '2021-06-15 01:39:00+00:00',\n",
+ " ...\n",
+ " '2021-06-15 07:50:00+00:00', '2021-06-15 07:51:00+00:00',\n",
+ " '2021-06-15 07:52:00+00:00', '2021-06-15 07:53:00+00:00',\n",
+ " '2021-06-15 07:54:00+00:00', '2021-06-15 07:55:00+00:00',\n",
+ " '2021-06-15 07:56:00+00:00', '2021-06-15 07:57:00+00:00',\n",
+ " '2021-06-15 07:58:00+00:00', '2021-06-15 07:59:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', length=330, freq=None)"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "session = \"2021-06-15\"\n",
+ "hkg_left.session_minutes(session)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-06-15 01:31:00+00:00', '2021-06-15 01:32:00+00:00',\n",
+ " '2021-06-15 01:33:00+00:00', '2021-06-15 01:34:00+00:00',\n",
+ " '2021-06-15 01:35:00+00:00', '2021-06-15 01:36:00+00:00',\n",
+ " '2021-06-15 01:37:00+00:00', '2021-06-15 01:38:00+00:00',\n",
+ " '2021-06-15 01:39:00+00:00', '2021-06-15 01:40:00+00:00',\n",
+ " ...\n",
+ " '2021-06-15 07:51:00+00:00', '2021-06-15 07:52:00+00:00',\n",
+ " '2021-06-15 07:53:00+00:00', '2021-06-15 07:54:00+00:00',\n",
+ " '2021-06-15 07:55:00+00:00', '2021-06-15 07:56:00+00:00',\n",
+ " '2021-06-15 07:57:00+00:00', '2021-06-15 07:58:00+00:00',\n",
+ " '2021-06-15 07:59:00+00:00', '2021-06-15 08:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', length=330, freq=None)"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_right.session_minutes(session)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-06-15 01:30:00+00:00', '2021-06-15 01:31:00+00:00',\n",
+ " '2021-06-15 01:32:00+00:00', '2021-06-15 01:33:00+00:00',\n",
+ " '2021-06-15 01:34:00+00:00', '2021-06-15 01:35:00+00:00',\n",
+ " '2021-06-15 01:36:00+00:00', '2021-06-15 01:37:00+00:00',\n",
+ " '2021-06-15 01:38:00+00:00', '2021-06-15 01:39:00+00:00',\n",
+ " ...\n",
+ " '2021-06-15 07:51:00+00:00', '2021-06-15 07:52:00+00:00',\n",
+ " '2021-06-15 07:53:00+00:00', '2021-06-15 07:54:00+00:00',\n",
+ " '2021-06-15 07:55:00+00:00', '2021-06-15 07:56:00+00:00',\n",
+ " '2021-06-15 07:57:00+00:00', '2021-06-15 07:58:00+00:00',\n",
+ " '2021-06-15 07:59:00+00:00', '2021-06-15 08:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', length=332, freq=None)"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_both.session_minutes(session)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**NOTE:** as a consequence of treating both sides of the session as open, the number of minutes associated with the session is 332, which is two higher than the session duration (330 minutes). This is because both the open and close are treated as trading minutes (+1) and both the break-start and break-open are treated as trading minutes (another +1). NB For calendars/sessions without a break, the difference is +1."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-06-15 01:31:00+00:00', '2021-06-15 01:32:00+00:00',\n",
+ " '2021-06-15 01:33:00+00:00', '2021-06-15 01:34:00+00:00',\n",
+ " '2021-06-15 01:35:00+00:00', '2021-06-15 01:36:00+00:00',\n",
+ " '2021-06-15 01:37:00+00:00', '2021-06-15 01:38:00+00:00',\n",
+ " '2021-06-15 01:39:00+00:00', '2021-06-15 01:40:00+00:00',\n",
+ " ...\n",
+ " '2021-06-15 07:50:00+00:00', '2021-06-15 07:51:00+00:00',\n",
+ " '2021-06-15 07:52:00+00:00', '2021-06-15 07:53:00+00:00',\n",
+ " '2021-06-15 07:54:00+00:00', '2021-06-15 07:55:00+00:00',\n",
+ " '2021-06-15 07:56:00+00:00', '2021-06-15 07:57:00+00:00',\n",
+ " '2021-06-15 07:58:00+00:00', '2021-06-15 07:59:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', length=328, freq=None)"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_neither.session_minutes(session)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**NOTE** for the \"neither\" side the situation is reversed and the number of minutes associated with the session is two less than the session duration (or -1 for calendars/sessions that do not have a break).\n",
+ "\n",
+ "These discrepancies will make themselves known in all methods that evaluate or interrogate minutes. **If you are not aware of how trading minutes are evaluated, you might get output that you weren't expecting...**"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[330, 330, 332, 328]"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "calendars = [hkg_left, hkg_right, hkg_both, hkg_neither]\n",
+ "[ cal.sessions_minutes_count(session, session) for cal in calendars ]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**NOTE**: the default side is **\"left\"**..."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Has it always been this way?\n",
+ "\n",
+ "No.\n",
+ "\n",
+ "The original `trading_calendars` package did not have a side option and treated trading minutes as if side were \"right\". This behaviour came about as a result of defining the open time as one minute later than the true open.\n",
+ "\n",
+ "When support for `trading_calendars` ended `exchange_calendars` came into being. With the initial release 3.0 the opportunity was taken to amend open times to reflect the true open times. Trading minutes continued to be evaluated as previously which had the effect of treating trading minutes as if side were \"both\".\n",
+ "\n",
+ "In release 3.4 the `ExchangeCalendar` side option was implemented to provide users with flexibility over how to treat trading minutes. In order to best preserve behaviour since release 3.0, the default side was \"right\" for the few 24-hour calendars and \"both\" for all others.\n",
+ "\n",
+ "In release 4.0 the default side was set to \"left\" for all calendars. This is not expected to change going forwards."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Can a `minute` parameter have a 'second' component?\n",
+ "\n",
+ "Depends on the `side`...\n",
+ "\n",
+ "#### 'left' and 'right'\n",
+ "\n",
+ "Only if a calenar's side is either \"left\" or \"right\" can `minute` be passed with a second (or milisecond...) component. This is because only these sides allow for a minute timestamp to represent a specific sixty seconds...\n",
+ "\n",
+ "Consider the minute timestamp **\"2021-06-12 15:30:00\"**:\n",
+ "* If the side is \"left\" then this timestamp will sit on the left side of the sixty seconds that it represents, that's to say it will represent the period from **\"2021-06-12 15:30:00\" through \"2021-06-12 15:30:59\"**. Indeed it will represent the period through to the instance before \"2021-06-12 15:31:00\", but it will NOT include \"2021-06-12 15:31:00\".\n",
+ "* If the side is \"right\" then the timestamp will sit on the right of the sixty seconds it represents, that's to say it will represent the period from the instance after \"2021-06-12 15:30:00\" through \"2021-06-12 15:31:00\". It will NOT include \"2021-06-12 15:30:00\" but will include \"2021-06-12 15:31:00\".\n",
+ "\n",
+ "Thought of in this way it becomes clear why an exchange that closes at 16.00 is considered open at \"16:00\" when side is \"right\" but closed when the side is \"left\"...\n",
+ "* when the side is \"right\" the timestamp \"16:00\" refers to the sixty seconds from (but not including) 15:59 through 16:00, i.e. the last minute of the trading day during which the exchange was very much open.\n",
+ "* when the side is \"left\" the timestamp \"16:00\" refers to the sixty seconds from 16:00 to (but not including) 16:01, i.e the first minute after the close when the exchange was very much closed.\n",
+ "\n",
+ "When a `minute` parameter is receieved with a time component more specific than a minute then the corresponding minute timestamp is evaluated by simply rounding up or down if the `side` is \"right\" or \"left\" respectively."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2021-06-15 05:26:00+0000', tz='UTC')"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_left.next_minute(\"2021-06-15 05:25:30\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2021-06-15 05:27:00+0000', tz='UTC')"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_right.next_minute(\"2021-06-15 05:25:30\")\n",
+ "# passed argument is represented by the trading minute \"05:26\", hence next_minute is..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 21,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_left.is_open_on_minute(\"2021-06-15 07:59:59\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### 'both' and 'neither'\n",
+ "\n",
+ "If the calendar's `side` is either \"both\" or \"neither\" then the sixty second period that a minute timestamp refers to is ambiguous. Looked at the other way around, it's ambiguous which minute timestamp represents any specific second. In order to avoid this ambiguity, if the calendar's side is \"both\" or \"neither\" then any `minute` parameter must be received with a time component no more specific than a minute. To the contrary, a ValueError is raised..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "hkg_both.is_open_on_minute(\"2021-06-15 07:59:59\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "ValueError Traceback (most recent call last)\n",
+ "Input In [22], in ()\n",
+ "----> 1 hkg_both.is_open_on_minute(\"2021-06-15 07:59:59\")\n",
+ "\n",
+ "ValueError: `timestamp` cannot have a non-zero second (or more accurate) component for `side` 'both'. `timestamp` parsed as '2021-06-15 07:59:59+00:00'.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `minute` timezone"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "`exchange_calendars` will always return minutes in terms of UTC. However, a `minute` parameter can take a timestamp of any timezone (`exchange_calendars` just parses it to UTC). Consider a session of the New York Stock Exchange:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
open
\n",
+ "
break_start
\n",
+ "
break_end
\n",
+ "
close
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
2021-06-15
\n",
+ "
2021-06-15 13:30:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2021-06-15 20:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " open break_start break_end \\\n",
+ "2021-06-15 2021-06-15 13:30:00+00:00 NaT NaT \n",
+ "\n",
+ " close \n",
+ "2021-06-15 2021-06-15 20:00:00+00:00 "
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys = xcals.get_calendar(\"XNYS\", side=\"left\")\n",
+ "nys.schedule.loc[[\"2021-06-15\"]]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.is_open_on_minute(pd.Timestamp(\"2021-06-15 09:35\"))\n",
+ "# NB tz-naive input is assumed as UTC"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.is_open_on_minute(pd.Timestamp(\"2021-06-15 09:35\", tz=nys.tz))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2021-06-15 13:36:00+0000', tz='UTC')"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.next_minute(pd.Timestamp(\"2021-06-15 09:35\", tz=nys.tz))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2021-06-15 09:36:00-0400', tz='America/New_York')"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.next_minute(pd.Timestamp(\"2021-06-15 09:35\", tz=nys.tz)).tz_convert(nys.tz)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `minute` bounds"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Nearly all methods that have a `minute` parameter will require that `minute` is received as an object representing a minute that's no earlier than the calendar's first trading minute and no later than the calendar's last trading minute (this is always the case for a `minute` annotated with `TradingMinute`)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nys.is_open_on_minute(nys.first_minute - pd.Timedelta(1, \"T\"))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "MinuteOutOfBounds Traceback (most recent call last)\n",
+ "Input In [28], in ()\n",
+ "----> 1 nys.is_open_on_minute(nys.first_minute - pd.Timedelta(1, \"T\"))\n",
+ "\n",
+ "MinuteOutOfBounds: Parameter `minute` receieved as '2002-06-10 13:29:00+00:00' although cannot be earlier than the first trading minute of calendar 'XNYS' ('2002-06-10 13:30:00+00:00').\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nys.next_open(nys.last_minute + pd.Timedelta(1, \"T\"))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "MinuteOutOfBounds Traceback (most recent call last)\n",
+ "Input In [29], in ()\n",
+ "----> 1 nys.next_open(nys.last_minute + pd.Timedelta(1, \"T\"))\n",
+ "\n",
+ "MinuteOutOfBounds: Parameter `minute` receieved as '2023-06-09 20:00:00+00:00' although cannot be later than the last trading minute of calendar 'XNYS' ('2023-06-09 19:59:00+00:00').\n",
+ "```"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python38 xcals",
+ "language": "python",
+ "name": "py38_xcals"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.8.10"
+ },
+ "widgets": {
+ "application/vnd.jupyter.widget-state+json": {
+ "state": {},
+ "version_major": 2,
+ "version_minor": 0
+ }
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/docs/tutorials/sessions.ipynb b/tasks/tasksmith-ca08ab4caec6/environment/source/docs/tutorials/sessions.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..3facaf7578261f01729b365607414b5bf5ec5ecb
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/docs/tutorials/sessions.ipynb
@@ -0,0 +1,666 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Sessions tutorial"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# setup\n",
+ "from datetime import datetime\n",
+ "\n",
+ "import exchange_calendars as xcals\n",
+ "import pandas as pd"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In `exchange_calendars` a 'session' is a timezone-naive timestamp that represents a date on which an exchange is open..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06',\n",
+ " '2022-01-07', '2022-01-10', '2022-01-11', '2022-01-12',\n",
+ " '2022-01-13'],\n",
+ " dtype='datetime64[ns]', freq='C')"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys = xcals.get_calendar(\"XNYS\") # New York Stock Exchange\n",
+ "nys.sessions_in_range(\"2022-01-01\", \"2022-01-13\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The calendar stores in a `schedule` the open and close times for each session. If a session has a lunch break then the break-start and break-end times are also stored. All these times are defined in terms of UTC."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
open
\n",
+ "
break_start
\n",
+ "
break_end
\n",
+ "
close
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
2002-06-10
\n",
+ "
2002-06-10 02:00:00+00:00
\n",
+ "
2002-06-10 04:00:00+00:00
\n",
+ "
2002-06-10 05:00:00+00:00
\n",
+ "
2002-06-10 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-11
\n",
+ "
2002-06-11 02:00:00+00:00
\n",
+ "
2002-06-11 04:00:00+00:00
\n",
+ "
2002-06-11 05:00:00+00:00
\n",
+ "
2002-06-11 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-12
\n",
+ "
2002-06-12 02:00:00+00:00
\n",
+ "
2002-06-12 04:00:00+00:00
\n",
+ "
2002-06-12 05:00:00+00:00
\n",
+ "
2002-06-12 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-13
\n",
+ "
2002-06-13 02:00:00+00:00
\n",
+ "
2002-06-13 04:00:00+00:00
\n",
+ "
2002-06-13 05:00:00+00:00
\n",
+ "
2002-06-13 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-14
\n",
+ "
2002-06-14 02:00:00+00:00
\n",
+ "
2002-06-14 04:00:00+00:00
\n",
+ "
2002-06-14 05:00:00+00:00
\n",
+ "
2002-06-14 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-05
\n",
+ "
2023-06-05 01:30:00+00:00
\n",
+ "
2023-06-05 04:00:00+00:00
\n",
+ "
2023-06-05 05:00:00+00:00
\n",
+ "
2023-06-05 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-06
\n",
+ "
2023-06-06 01:30:00+00:00
\n",
+ "
2023-06-06 04:00:00+00:00
\n",
+ "
2023-06-06 05:00:00+00:00
\n",
+ "
2023-06-06 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-07
\n",
+ "
2023-06-07 01:30:00+00:00
\n",
+ "
2023-06-07 04:00:00+00:00
\n",
+ "
2023-06-07 05:00:00+00:00
\n",
+ "
2023-06-07 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-08
\n",
+ "
2023-06-08 01:30:00+00:00
\n",
+ "
2023-06-08 04:00:00+00:00
\n",
+ "
2023-06-08 05:00:00+00:00
\n",
+ "
2023-06-08 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-09
\n",
+ "
2023-06-09 01:30:00+00:00
\n",
+ "
2023-06-09 04:00:00+00:00
\n",
+ "
2023-06-09 05:00:00+00:00
\n",
+ "
2023-06-09 08:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
5184 rows × 4 columns
\n",
+ "
"
+ ],
+ "text/plain": [
+ " open break_start \\\n",
+ "2002-06-10 2002-06-10 02:00:00+00:00 2002-06-10 04:00:00+00:00 \n",
+ "2002-06-11 2002-06-11 02:00:00+00:00 2002-06-11 04:00:00+00:00 \n",
+ "2002-06-12 2002-06-12 02:00:00+00:00 2002-06-12 04:00:00+00:00 \n",
+ "2002-06-13 2002-06-13 02:00:00+00:00 2002-06-13 04:00:00+00:00 \n",
+ "2002-06-14 2002-06-14 02:00:00+00:00 2002-06-14 04:00:00+00:00 \n",
+ "... ... ... \n",
+ "2023-06-05 2023-06-05 01:30:00+00:00 2023-06-05 04:00:00+00:00 \n",
+ "2023-06-06 2023-06-06 01:30:00+00:00 2023-06-06 04:00:00+00:00 \n",
+ "2023-06-07 2023-06-07 01:30:00+00:00 2023-06-07 04:00:00+00:00 \n",
+ "2023-06-08 2023-06-08 01:30:00+00:00 2023-06-08 04:00:00+00:00 \n",
+ "2023-06-09 2023-06-09 01:30:00+00:00 2023-06-09 04:00:00+00:00 \n",
+ "\n",
+ " break_end close \n",
+ "2002-06-10 2002-06-10 05:00:00+00:00 2002-06-10 08:00:00+00:00 \n",
+ "2002-06-11 2002-06-11 05:00:00+00:00 2002-06-11 08:00:00+00:00 \n",
+ "2002-06-12 2002-06-12 05:00:00+00:00 2002-06-12 08:00:00+00:00 \n",
+ "2002-06-13 2002-06-13 05:00:00+00:00 2002-06-13 08:00:00+00:00 \n",
+ "2002-06-14 2002-06-14 05:00:00+00:00 2002-06-14 08:00:00+00:00 \n",
+ "... ... ... \n",
+ "2023-06-05 2023-06-05 05:00:00+00:00 2023-06-05 08:00:00+00:00 \n",
+ "2023-06-06 2023-06-06 05:00:00+00:00 2023-06-06 08:00:00+00:00 \n",
+ "2023-06-07 2023-06-07 05:00:00+00:00 2023-06-07 08:00:00+00:00 \n",
+ "2023-06-08 2023-06-08 05:00:00+00:00 2023-06-08 08:00:00+00:00 \n",
+ "2023-06-09 2023-06-09 05:00:00+00:00 2023-06-09 08:00:00+00:00 \n",
+ "\n",
+ "[5184 rows x 4 columns]"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg = xcals.get_calendar(\"XHKG\") # Hong Kong Stock Exchange\n",
+ "hkg.schedule"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Each session is associated with a set of contiguous trading minutes (or two sets if the sesson has a lunch break)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "session=Timestamp('2023-06-09 00:00:00', freq='C')\n",
+ "\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2023-06-09 01:30:00+00:00', '2023-06-09 01:31:00+00:00',\n",
+ " '2023-06-09 01:32:00+00:00', '2023-06-09 01:33:00+00:00',\n",
+ " '2023-06-09 01:34:00+00:00', '2023-06-09 01:35:00+00:00',\n",
+ " '2023-06-09 01:36:00+00:00', '2023-06-09 01:37:00+00:00',\n",
+ " '2023-06-09 01:38:00+00:00', '2023-06-09 01:39:00+00:00',\n",
+ " ...\n",
+ " '2023-06-09 07:50:00+00:00', '2023-06-09 07:51:00+00:00',\n",
+ " '2023-06-09 07:52:00+00:00', '2023-06-09 07:53:00+00:00',\n",
+ " '2023-06-09 07:54:00+00:00', '2023-06-09 07:55:00+00:00',\n",
+ " '2023-06-09 07:56:00+00:00', '2023-06-09 07:57:00+00:00',\n",
+ " '2023-06-09 07:58:00+00:00', '2023-06-09 07:59:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', length=330, freq=None)"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "session = hkg.schedule.index[-1]\n",
+ "print(f\"{session=}\\n\") # for reference\n",
+ "\n",
+ "hkg.session_minutes(session)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "See the [minutes.ipynb](./minutes.ipynb) tutorial for an explanation of how trading minutes for a session are evaluated according to the \"side\" option."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A timestamp representing a 'session' takes the date in which **most of the session falls** (based on UTC open/close times). Almost all calendars' have sessions that fall fully within a single date. The schedule above shows this is the case for XHKG.\n",
+ "\n",
+ "A few calendars have sessions that fall over two dates..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
open
\n",
+ "
break_start
\n",
+ "
break_end
\n",
+ "
close
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
2002-06-10
\n",
+ "
2002-06-09 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2002-06-10 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-11
\n",
+ "
2002-06-10 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2002-06-11 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-12
\n",
+ "
2002-06-11 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2002-06-12 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-13
\n",
+ "
2002-06-12 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2002-06-13 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-14
\n",
+ "
2002-06-13 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2002-06-14 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-05
\n",
+ "
2023-06-04 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2023-06-05 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-06
\n",
+ "
2023-06-05 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2023-06-06 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-07
\n",
+ "
2023-06-06 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2023-06-07 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-08
\n",
+ "
2023-06-07 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2023-06-08 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-09
\n",
+ "
2023-06-08 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2023-06-09 22:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
5417 rows × 4 columns
\n",
+ "
"
+ ],
+ "text/plain": [
+ " open break_start break_end \\\n",
+ "2002-06-10 2002-06-09 22:00:00+00:00 NaT NaT \n",
+ "2002-06-11 2002-06-10 22:00:00+00:00 NaT NaT \n",
+ "2002-06-12 2002-06-11 22:00:00+00:00 NaT NaT \n",
+ "2002-06-13 2002-06-12 22:00:00+00:00 NaT NaT \n",
+ "2002-06-14 2002-06-13 22:00:00+00:00 NaT NaT \n",
+ "... ... ... ... \n",
+ "2023-06-05 2023-06-04 22:00:00+00:00 NaT NaT \n",
+ "2023-06-06 2023-06-05 22:00:00+00:00 NaT NaT \n",
+ "2023-06-07 2023-06-06 22:00:00+00:00 NaT NaT \n",
+ "2023-06-08 2023-06-07 22:00:00+00:00 NaT NaT \n",
+ "2023-06-09 2023-06-08 22:00:00+00:00 NaT NaT \n",
+ "\n",
+ " close \n",
+ "2002-06-10 2002-06-10 22:00:00+00:00 \n",
+ "2002-06-11 2002-06-11 22:00:00+00:00 \n",
+ "2002-06-12 2002-06-12 22:00:00+00:00 \n",
+ "2002-06-13 2002-06-13 22:00:00+00:00 \n",
+ "2002-06-14 2002-06-14 22:00:00+00:00 \n",
+ "... ... \n",
+ "2023-06-05 2023-06-05 22:00:00+00:00 \n",
+ "2023-06-06 2023-06-06 22:00:00+00:00 \n",
+ "2023-06-07 2023-06-07 22:00:00+00:00 \n",
+ "2023-06-08 2023-06-08 22:00:00+00:00 \n",
+ "2023-06-09 2023-06-09 22:00:00+00:00 \n",
+ "\n",
+ "[5417 rows x 4 columns]"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "cmes = xcals.get_calendar(\"CMES\")\n",
+ "cmes.schedule"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note how the sessions take their value as the date in which most of the session falls, NOT the date of the open."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `session` parameter\n",
+ "Methods that require a single session to be specified take a `session` parameter. Those that act on a range of sessions take `start` and `end` parameters.\n",
+ "\n",
+ "These parameters can take a `Date` or a `Session` type, defined as:\n",
+ "\n",
+ "```python\n",
+ "Date = typing.Union[pd.Timestamp, str, int, float, datetime.datetime]\n",
+ "Session = Date\n",
+ "```\n",
+ "In short, a `session` parameter can take any type that can be passed as a single argument to pd.Timestamp(). For example, the argument of `next_session` takes a `Session` type and any of the following inputs are valid:\n",
+ ""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "inputs = [\n",
+ " \"2021-06-15\",\n",
+ " pd.Timestamp(\"2021-06-15\"),\n",
+ " datetime(2021, 6, 15),\n",
+ " 1623715200000000000,\n",
+ "]\n",
+ "lon = xcals.get_calendar(\"XLON\")\n",
+ "for input_ in inputs:\n",
+ " assert lon.next_session(input_) == pd.Timestamp('2021-06-16')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The difference between `Date` and `Session` is that whilst an object passed to a parameter annotated `Date` can represent any date, an object passed to a parameter annotated `Session` must represent an actual calendar session.\n",
+ "\n",
+ "For example, the arguments of `sessions_in_range` take a `Date` type, such that the following is valid even though it can be seen that neither of the values passed represent sessions."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2022-01-04', '2022-01-05', '2022-01-06', '2022-01-07'], dtype='datetime64[ns]', freq='C')"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "lon.sessions_in_range(\"2022-01-01\", \"2022-01-09\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "However, passing a date that is not a session to an argument that takes a `Session` will raise a `NotSessionError`..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "lon.session_open(\"2022-01-09\")\n",
+ "# run cell for full traceback"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "NotSessionError Traceback (most recent call last)\n",
+ "Input In [8], in ()\n",
+ "----> 1 lon.session_open(\"2022-01-09\")\n",
+ "\n",
+ "NotSessionError: Parameter `session` takes a session although received input that parsed to '2022-01-09 00:00:00' which is not a session of calendar 'XLON'.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To find out **which type a `session` parameter takes**, simply refer to the annotated types in the method signature:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "lon.session_open?\n",
+ "# run cell for full method doc"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "Signature: lon.session_open(session: 'Session', _parse: 'bool' = True) -> 'pd.Timestamp'\n",
+ "Docstring: Return open time for a given session.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Invalid `session` input"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "##### **Time components** \n",
+ "A `session` parameter cannot include a time component..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "lon.session_open(\"2021-01-07 12:20\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "ValueError Traceback (most recent call last)\n",
+ "Input In [10], in ()\n",
+ "----> 1 lon.session_open(\"2021-01-07 12:20\")\n",
+ "\n",
+ "ValueError: Parameter `session` parsed as '2021-01-07 12:20:00' although a Date must have a time component of 00:00.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "##### **Timezone**\n",
+ "A `session` parameter cannot have a timezone..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "session = pd.Timestamp(\"2021-01-07\", tz=\"UTC\")\n",
+ "lon.session_close(session)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "ValueError Traceback (most recent call last)\n",
+ "Input In [11], in ()\n",
+ " 1 session = pd.Timestamp(\"2021-01-07\", tz=\"UTC\")\n",
+ "----> 2 lon.session_close(session)\n",
+ "\n",
+ "ValueError: Parameter `session` received with timezone defined as 'UTC' although a Date must be timezone naive.\n",
+ "```"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python38 xcals",
+ "language": "python",
+ "name": "py38_xcals"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.8.10"
+ },
+ "widgets": {
+ "application/vnd.jupyter.widget-state+json": {
+ "state": {},
+ "version_major": 2,
+ "version_minor": 0
+ }
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/docs/tutorials/trading_index.ipynb b/tasks/tasksmith-ca08ab4caec6/environment/source/docs/tutorials/trading_index.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..a5b0a8a0be91fff5eb49b0667d362c6e4a9fa5b5
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/docs/tutorials/trading_index.ipynb
@@ -0,0 +1,4072 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# `trading_index`\n",
+ "\n",
+ "This tutorial shows all the ins and outs of the calendars' `trading_index` method. (For other calendar methods see the [calendar_methods.ipynb](./calendar_methods.ipynb) tutorial.)\n",
+ "\n",
+ "The [What does it do?](#What-does-it-do?) section explains basic usage. The following sections then explore the method's arguments and options:\n",
+ "\n",
+ "* [`intervals`](#intervals)\n",
+ "* [`period`](#period)\n",
+ "* [`closed`](#closed)\n",
+ "* [`force_close`, `force_break_close` and `force`](#force_close,-force_break_close-and-force)\n",
+ "* [`ignore_breaks`](#ignore_breaks)\n",
+ "* [`align` and `align_pm`](#align-and-align_pm)\n",
+ "* [`start` and `end` as times](#start-and-end-as-times)\n",
+ "\n",
+ "The final section covers [overlapping indices](#Overlapping-indices)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# setup\n",
+ "from zoneinfo import ZoneInfo\n",
+ "\n",
+ "import exchange_calendars as xcals\n",
+ "import pandas as pd\n",
+ "\n",
+ "hkg = xcals.get_calendar(\"XHKG\") # Hong Kong Stock Exchange\n",
+ "start = \"2021-12-23\"\n",
+ "end = \"2021-12-28\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
open
\n",
+ "
break_start
\n",
+ "
break_end
\n",
+ "
close
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
2021-12-23
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 04:00:00+00:00
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2021-12-24
\n",
+ "
2021-12-24 01:30:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2021-12-24 04:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2021-12-28
\n",
+ "
2021-12-28 01:30:00+00:00
\n",
+ "
2021-12-28 04:00:00+00:00
\n",
+ "
2021-12-28 05:00:00+00:00
\n",
+ "
2021-12-28 08:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " open break_start \\\n",
+ "2021-12-23 2021-12-23 01:30:00+00:00 2021-12-23 04:00:00+00:00 \n",
+ "2021-12-24 2021-12-24 01:30:00+00:00 NaT \n",
+ "2021-12-28 2021-12-28 01:30:00+00:00 2021-12-28 04:00:00+00:00 \n",
+ "\n",
+ " break_end close \n",
+ "2021-12-23 2021-12-23 05:00:00+00:00 2021-12-23 08:00:00+00:00 \n",
+ "2021-12-24 NaT 2021-12-24 04:00:00+00:00 \n",
+ "2021-12-28 2021-12-28 05:00:00+00:00 2021-12-28 08:00:00+00:00 "
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# for reference\n",
+ "schedule = hkg.schedule.loc[start:end]\n",
+ "schedule"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### What does it do?\n",
+ "\n",
+ "`trading_index` creates a trading index at a given period over a range of sessions."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 01:30:00+00:00', '2021-12-23 02:00:00+00:00',\n",
+ " '2021-12-23 02:30:00+00:00', '2021-12-23 03:00:00+00:00',\n",
+ " '2021-12-23 03:30:00+00:00', '2021-12-23 05:00:00+00:00',\n",
+ " '2021-12-23 05:30:00+00:00', '2021-12-23 06:00:00+00:00',\n",
+ " '2021-12-23 06:30:00+00:00', '2021-12-23 07:00:00+00:00',\n",
+ " '2021-12-23 07:30:00+00:00', '2021-12-24 01:30:00+00:00',\n",
+ " '2021-12-24 02:00:00+00:00', '2021-12-24 02:30:00+00:00',\n",
+ " '2021-12-24 03:00:00+00:00', '2021-12-24 03:30:00+00:00',\n",
+ " '2021-12-28 01:30:00+00:00', '2021-12-28 02:00:00+00:00',\n",
+ " '2021-12-28 02:30:00+00:00', '2021-12-28 03:00:00+00:00',\n",
+ " '2021-12-28 03:30:00+00:00', '2021-12-28 05:00:00+00:00',\n",
+ " '2021-12-28 05:30:00+00:00', '2021-12-28 06:00:00+00:00',\n",
+ " '2021-12-28 06:30:00+00:00', '2021-12-28 07:00:00+00:00',\n",
+ " '2021-12-28 07:30:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start, end, \"30min\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Or over a single session, if `start` and `end` are passed as the same session."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 01:30:00+00:00', '2021-12-23 02:00:00+00:00',\n",
+ " '2021-12-23 02:30:00+00:00', '2021-12-23 03:00:00+00:00',\n",
+ " '2021-12-23 03:30:00+00:00', '2021-12-23 05:00:00+00:00',\n",
+ " '2021-12-23 05:30:00+00:00', '2021-12-23 06:00:00+00:00',\n",
+ " '2021-12-23 06:30:00+00:00', '2021-12-23 07:00:00+00:00',\n",
+ " '2021-12-23 07:30:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start=start, end=start, period=\"30min\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Or between times, if `start` and `end` are passed as times (as opposed to dates)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 02:30:00+00:00', '2021-12-23 03:00:00+00:00',\n",
+ " '2021-12-23 03:30:00+00:00', '2021-12-23 05:00:00+00:00',\n",
+ " '2021-12-23 05:30:00+00:00', '2021-12-23 06:00:00+00:00',\n",
+ " '2021-12-23 06:30:00+00:00', '2021-12-23 07:00:00+00:00',\n",
+ " '2021-12-23 07:30:00+00:00', '2021-12-24 01:30:00+00:00',\n",
+ " '2021-12-24 02:00:00+00:00', '2021-12-24 02:30:00+00:00',\n",
+ " '2021-12-24 03:00:00+00:00', '2021-12-24 03:30:00+00:00',\n",
+ " '2021-12-28 01:30:00+00:00', '2021-12-28 02:00:00+00:00',\n",
+ " '2021-12-28 02:30:00+00:00', '2021-12-28 03:00:00+00:00',\n",
+ " '2021-12-28 03:30:00+00:00', '2021-12-28 05:00:00+00:00',\n",
+ " '2021-12-28 05:30:00+00:00', '2021-12-28 06:00:00+00:00',\n",
+ " '2021-12-28 06:30:00+00:00', '2021-12-28 07:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "start_min = \"2021-12-23 02:30\"\n",
+ "end_min = \"2021-12-28 07:00\"\n",
+ "hkg.trading_index(start=start_min, end=end_min, period=\"30min\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that `start` can be passed as a time and `end` as a date, or vice-versa."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 02:30:00+00:00', '2021-12-23 03:00:00+00:00',\n",
+ " '2021-12-23 03:30:00+00:00', '2021-12-23 05:00:00+00:00',\n",
+ " '2021-12-23 05:30:00+00:00', '2021-12-23 06:00:00+00:00',\n",
+ " '2021-12-23 06:30:00+00:00', '2021-12-23 07:00:00+00:00',\n",
+ " '2021-12-23 07:30:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start=start_min, end=start, period=\"30min\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "See the '[`start` and `end` as times](#start-and-end-as-times)' section for further notes on how the first and last indices are defined when `start` and/or `end` are passed as times."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `intervals`\n",
+ "\n",
+ "By passing `intervals` as `False` the index can be output as a `DatetimeIndex`, as shown above. Although by default the index is output as an `IntervalIndex`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "IntervalIndex([[2021-12-23 01:30:00, 2021-12-23 02:00:00), [2021-12-23 02:00:00, 2021-12-23 02:30:00), [2021-12-23 02:30:00, 2021-12-23 03:00:00), [2021-12-23 03:00:00, 2021-12-23 03:30:00), [2021-12-23 03:30:00, 2021-12-23 04:00:00) ... [2021-12-23 05:30:00, 2021-12-23 06:00:00), [2021-12-23 06:00:00, 2021-12-23 06:30:00), [2021-12-23 06:30:00, 2021-12-23 07:00:00), [2021-12-23 07:00:00, 2021-12-23 07:30:00), [2021-12-23 07:30:00, 2021-12-23 08:00:00)], dtype='interval[datetime64[ns, UTC], left]')"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index = hkg.trading_index(start, start, \"30min\")\n",
+ "index"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's make that a bit more readable by setting it to the index of a `DataFrame`, and have columns showing the index's left and right sides."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 01:30:00, 2021-12-23 02:00:00)
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 02:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 02:00:00, 2021-12-23 02:30:00)
\n",
+ "
2021-12-23 02:00:00+00:00
\n",
+ "
2021-12-23 02:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 02:30:00, 2021-12-23 03:00:00)
\n",
+ "
2021-12-23 02:30:00+00:00
\n",
+ "
2021-12-23 03:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:00:00, 2021-12-23 03:30:00)
\n",
+ "
2021-12-23 03:00:00+00:00
\n",
+ "
2021-12-23 03:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:30:00, 2021-12-23 04:00:00)
\n",
+ "
2021-12-23 03:30:00+00:00
\n",
+ "
2021-12-23 04:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 05:30:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 05:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:30:00, 2021-12-23 06:00:00)
\n",
+ "
2021-12-23 05:30:00+00:00
\n",
+ "
2021-12-23 06:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:00:00, 2021-12-23 06:30:00)
\n",
+ "
2021-12-23 06:00:00+00:00
\n",
+ "
2021-12-23 06:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:30:00, 2021-12-23 07:00:00)
\n",
+ "
2021-12-23 06:30:00+00:00
\n",
+ "
2021-12-23 07:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 07:00:00, 2021-12-23 07:30:00)
\n",
+ "
2021-12-23 07:00:00+00:00
\n",
+ "
2021-12-23 07:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 07:30:00, 2021-12-23 08:00:00)
\n",
+ "
2021-12-23 07:30:00+00:00
\n",
+ "
2021-12-23 08:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 02:00:00) 2021-12-23 01:30:00+00:00 \n",
+ "[2021-12-23 02:00:00, 2021-12-23 02:30:00) 2021-12-23 02:00:00+00:00 \n",
+ "[2021-12-23 02:30:00, 2021-12-23 03:00:00) 2021-12-23 02:30:00+00:00 \n",
+ "[2021-12-23 03:00:00, 2021-12-23 03:30:00) 2021-12-23 03:00:00+00:00 \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 03:30:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:00:00+00:00 \n",
+ "[2021-12-23 06:30:00, 2021-12-23 07:00:00) 2021-12-23 06:30:00+00:00 \n",
+ "[2021-12-23 07:00:00, 2021-12-23 07:30:00) 2021-12-23 07:00:00+00:00 \n",
+ "[2021-12-23 07:30:00, 2021-12-23 08:00:00) 2021-12-23 07:30:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 02:00:00) 2021-12-23 02:00:00+00:00 \n",
+ "[2021-12-23 02:00:00, 2021-12-23 02:30:00) 2021-12-23 02:30:00+00:00 \n",
+ "[2021-12-23 02:30:00, 2021-12-23 03:00:00) 2021-12-23 03:00:00+00:00 \n",
+ "[2021-12-23 03:00:00, 2021-12-23 03:30:00) 2021-12-23 03:30:00+00:00 \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 04:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 06:00:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:30:00+00:00 \n",
+ "[2021-12-23 06:30:00, 2021-12-23 07:00:00) 2021-12-23 07:00:00+00:00 \n",
+ "[2021-12-23 07:00:00, 2021-12-23 07:30:00) 2021-12-23 07:30:00+00:00 \n",
+ "[2021-12-23 07:30:00, 2021-12-23 08:00:00) 2021-12-23 08:00:00+00:00 "
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "def show_as_df(index: pd.IntervalIndex) -> pd.DataFrame:\n",
+ " index.name = \"IntervalIndex\"\n",
+ " return pd.DataFrame(\n",
+ " dict(left_side=index.left, right_side=index.right),\n",
+ " index=index\n",
+ " )\n",
+ "\n",
+ "show_as_df(index)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `period`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The trading index represents sessions and subsessions as a number of discrete periods of a given length.\n",
+ "\n",
+ "When output as an `IntervalIndex` each indice represents a discrete period."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Interval('2021-12-23 01:30:00', '2021-12-23 02:00:00', closed='left')"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index[0]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The length of each period for the example above is 30 minutes."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "TimedeltaIndex(['0 days 00:30:00', '0 days 00:30:00', '0 days 00:30:00',\n",
+ " '0 days 00:30:00', '0 days 00:30:00', '0 days 00:30:00',\n",
+ " '0 days 00:30:00', '0 days 00:30:00', '0 days 00:30:00',\n",
+ " '0 days 00:30:00', '0 days 00:30:00'],\n",
+ " dtype='timedelta64[ns]', freq=None)"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index.length"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The period length is defined by the `period` argument which can be passed as the third positional argument or as a keyword argument. `period` can take either a `pd.Timedelta` or a string representing a pandas frequency. All the following are valid inputs representing a period length of 1 hour."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "periods = [\n",
+ " pd.Timedelta(hours=1),\n",
+ " pd.Timedelta(1, \"H\"),\n",
+ " pd.Timedelta(60, \"min\"),\n",
+ " pd.Timedelta(60, \"T\"),\n",
+ " \"1H\",\n",
+ " \"1h\",\n",
+ " \"60T\",\n",
+ " \"60min\",\n",
+ " \"3600s\" \n",
+ "]\n",
+ "\n",
+ "indexes = [ hkg.trading_index(start, start, period) for period in periods ]\n",
+ "for i, index in enumerate(indexes):\n",
+ " pd.testing.assert_index_equal(index, indexes[0])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " open break_start \\\n",
+ "2021-12-23 2021-12-23 01:30:00+00:00 2021-12-23 04:00:00+00:00 \n",
+ "\n",
+ " break_end close \n",
+ "2021-12-23 2021-12-23 05:00:00+00:00 2021-12-23 08:00:00+00:00 "
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# recall\n",
+ "schedule.iloc[[0]]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Hong Kong has a lunch break. The trading index covers the morning subsession starting with the open, and then the afternoon subsession starting with the break-end. The hour and a half represents the difference between the last indice of the morning subsession and the first indice of the afternoon subsession. (See [`ignore_breaks`](#ignore_breaks) for how to treat sessions as continuous.)\n",
+ "\n",
+ "Ok, fine, but why hasn't the index included indices for 04:00 or 08:00? That's because it's `closed` on the \"left\" (by default)..."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `closed`\n",
+ "\n",
+ "The `closed` parameter has a different effect depending on whether the index is being output as an `IntervalIndex` (default) or `DatetimeIndex` (i.e. `intervals=False`).\n",
+ "\n",
+ "If the index is being output as an `IntervalIndex` then `closed` can take either \"left\" (default) or \"right\". This value is simply passed through to the `closed` parameter of the `IntervalIndex` (to define the side on which all the intervals should be closed). In this case `closed` has no other effect.\n",
+ "\n",
+ "If the index is being output as an `DatetimeIndex` then `closed` can take either \"left\", \"right\", \"both\" or \"neither\". In this case `closed` determines **the side of each implied period that an indice should be defined on**. The consequence of each value is best understood by considering whether or not the left side of the first implied period and/or the right side of last implied period are included as indices:\n",
+ "* \"left\" (default) - include left side of first period, do not include right side of last period.\n",
+ "* \"right\" - do not include left side of first period, include right side of last period.\n",
+ "* \"both\" - include both left side of first period and right side of last period.\n",
+ "* \"neither\" - do not include either left side of first period or right side of last period.\n",
+ "\n",
+ "So, going back to the prior example, passing `closed` as right will include the 04:00 and 08:00 indices."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 02:00:00+00:00', '2021-12-23 02:30:00+00:00',\n",
+ " '2021-12-23 03:00:00+00:00', '2021-12-23 03:30:00+00:00',\n",
+ " '2021-12-23 04:00:00+00:00', '2021-12-23 05:30:00+00:00',\n",
+ " '2021-12-23 06:00:00+00:00', '2021-12-23 06:30:00+00:00',\n",
+ " '2021-12-23 07:00:00+00:00', '2021-12-23 07:30:00+00:00',\n",
+ " '2021-12-23 08:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start, start, \"30min\", closed=\"right\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although now that only the right sides of the implied periods are being defined - the open (01:30) and start of the afternoon subsession (05:00) are not included...\n",
+ "\n",
+ "`closed` can be passed as \"both\" to include both the left and the right side of each implied interval."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 01:30:00+00:00', '2021-12-23 02:00:00+00:00',\n",
+ " '2021-12-23 02:30:00+00:00', '2021-12-23 03:00:00+00:00',\n",
+ " '2021-12-23 03:30:00+00:00', '2021-12-23 04:00:00+00:00',\n",
+ " '2021-12-23 05:00:00+00:00', '2021-12-23 05:30:00+00:00',\n",
+ " '2021-12-23 06:00:00+00:00', '2021-12-23 06:30:00+00:00',\n",
+ " '2021-12-23 07:00:00+00:00', '2021-12-23 07:30:00+00:00',\n",
+ " '2021-12-23 08:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 21,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start, start, \"30min\", closed=\"both\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And if you have a use case where you don't require either the left side of a (sub)session's first period or the right side of its last one, then you're after \"neither\"."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 02:00:00+00:00', '2021-12-23 02:30:00+00:00',\n",
+ " '2021-12-23 03:00:00+00:00', '2021-12-23 03:30:00+00:00',\n",
+ " '2021-12-23 05:30:00+00:00', '2021-12-23 06:00:00+00:00',\n",
+ " '2021-12-23 06:30:00+00:00', '2021-12-23 07:00:00+00:00',\n",
+ " '2021-12-23 07:30:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start, start, \"30min\", closed=\"neither\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `force_close`, `force_break_close` and `force`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Have a look at this."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " open break_start \\\n",
+ "2021-12-23 2021-12-23 01:30:00+00:00 2021-12-23 04:00:00+00:00 \n",
+ "\n",
+ " break_end close \n",
+ "2021-12-23 2021-12-23 05:00:00+00:00 2021-12-23 08:00:00+00:00 "
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# for reference\n",
+ "schedule.iloc[[0]]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Interval('2021-12-23 02:50:00', '2021-12-23 04:10:00', closed='left')"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index[1]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It can be seen that whilst this indice represents, like all the others, a period of 80 minutes, only the first 70 minutes of these actually represent a trading period, with the last 10 minutes, from 04:00 to 04:10, falling within the subsequent break.\n",
+ "\n",
+ "Similarly, it can be see that the last indice includes a full hour (08:00 - 09:00) that falls after the close.\n",
+ "\n",
+ "**The final indice of a (sub)session will always include a non-trading period whenever the period length is not a factor of the (sub)session duration.**\n",
+ "\n",
+ "The `force_close` and `force_break_close` options are provided to force the right side of the final period to, respectively, the session / morning subsession close."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:20:00, 2021-12-23 01:40:00) 2021-12-23 01:20:00+00:00 \n",
+ "[2021-12-23 01:40:00, 2021-12-23 02:00:00) 2021-12-23 01:40:00+00:00 \n",
+ "[2021-12-23 02:00:00, 2021-12-23 02:20:00) 2021-12-23 02:00:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:20:00, 2021-12-23 01:40:00) 2021-12-23 01:40:00+00:00 \n",
+ "[2021-12-23 01:40:00, 2021-12-23 02:00:00) 2021-12-23 02:00:00+00:00 \n",
+ "[2021-12-23 02:00:00, 2021-12-23 02:20:00) 2021-12-23 02:20:00+00:00 "
+ ]
+ },
+ "execution_count": 43,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index = hkg.trading_index(start, start, \"20T\", align=\"-20T\")\n",
+ "show_as_df(index)[:3]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Where a calendar observes a break, by default the start of both the morning and afternoon subsessions will be anchored, independently, according to `align`. Alternatively `align_pm` can be passed to anchor the start of the afternoon subsessions:\n",
+ "* to a different alignment, by passing as a `str` or `Timedelta`.\n",
+ "* to the break-end (i.e. the afternoon subsession open), by passing as `False`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `start` and `end` as times"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When `start` and `end` are passed as times, how the first and last indices are defined depends on whether the index is returned as an `IntervalIndex` or a `DatetimeIndex`.\n",
+ "\n",
+ "When returning an `IntervalIndex` (`intervals=True`):\n",
+ "* The first indice will be:\n",
+ " * if `start` coincides with the left side of an indice, then that indice.\n",
+ " * otherwise the nearest indice to `start` with a left side that is later than `start`.\n",
+ "\n",
+ "* The last indice will be:\n",
+ " * if `end` coincides with the right side of an indice, then that indice.\n",
+ " * otherwise the nearest indice to `end` with a right side that is earlier than `end`.\n",
+ "\n",
+ "In the following example the `start` and `end` times coincide with, respectively, the left and right side of indices."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 44,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "start_min = pd.Timestamp(\"2021-12-23 03:00\")\n",
+ "end_min = pd.Timestamp(\"2021-12-23 07:00\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 45,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 03:30:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:00:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 04:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 06:00:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:30:00+00:00 "
+ ]
+ },
+ "execution_count": 46,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "one_min = pd.Timedelta(1, \"T\")\n",
+ "index = hkg.trading_index(start_min + one_min, end_min - one_min, \"30T\", intervals=True)\n",
+ "show_as_df(index)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In short, when returning an `IntervalIndex`:\n",
+ "* the first indice will never include a period that falls before `start`.\n",
+ "* the last indice will never include a period that falls after `end`.\n",
+ "\n",
+ "The same is not true for when a `DatetimeIndex` is returned. In this case the first and last indices are defined without consideration to the periods that the indices may represent.\n",
+ "\n",
+ "When returning an `DatetimeIndex`:\n",
+ "* The first indice will be either `start`, if start is an indice, or otherwise the nearest indice that follows `start`. \n",
+ "* The last indice will be either `end`, if end is an indice, or otherwise the nearest indice that preceeds `end`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 47,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "start_min=Timestamp('2021-12-23 03:00:00')\tend_min=Timestamp('2021-12-23 07:00:00')\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 03:00:00+00:00', '2021-12-23 03:30:00+00:00',\n",
+ " '2021-12-23 05:00:00+00:00', '2021-12-23 05:30:00+00:00',\n",
+ " '2021-12-23 06:00:00+00:00', '2021-12-23 06:30:00+00:00',\n",
+ " '2021-12-23 07:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 47,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "print(f\"{start_min=}\\t{end_min=}\") # for reference\n",
+ "hkg.trading_index(start_min, end_min, \"30T\", closed=\"left\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note the different interpretation of what `end` represents. Here the `end` indice is included even though it represents a period (07:00 - 07:30) that falls after `end_min`. If intervals=True then the analogous indice is excluded."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 48,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 03:00:00, 2021-12-23 03:30:00)
\n",
+ "
2021-12-23 03:00:00+00:00
\n",
+ "
2021-12-23 03:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:30:00, 2021-12-23 04:00:00)
\n",
+ "
2021-12-23 03:30:00+00:00
\n",
+ "
2021-12-23 04:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 05:30:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 05:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:30:00, 2021-12-23 06:00:00)
\n",
+ "
2021-12-23 05:30:00+00:00
\n",
+ "
2021-12-23 06:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:00:00, 2021-12-23 06:30:00)
\n",
+ "
2021-12-23 06:00:00+00:00
\n",
+ "
2021-12-23 06:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:30:00, 2021-12-23 07:00:00)
\n",
+ "
2021-12-23 06:30:00+00:00
\n",
+ "
2021-12-23 07:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 03:00:00, 2021-12-23 03:30:00) 2021-12-23 03:00:00+00:00 \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 03:30:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:00:00+00:00 \n",
+ "[2021-12-23 06:30:00, 2021-12-23 07:00:00) 2021-12-23 06:30:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 03:00:00, 2021-12-23 03:30:00) 2021-12-23 03:30:00+00:00 \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 04:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 06:00:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:30:00+00:00 \n",
+ "[2021-12-23 06:30:00, 2021-12-23 07:00:00) 2021-12-23 07:00:00+00:00 "
+ ]
+ },
+ "execution_count": 48,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index = hkg.trading_index(start_min, end_min, \"30T\", closed=\"left\", intervals=True)\n",
+ "show_as_df(index)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Final point on passing `start` and/or `end` as times:\n",
+ "\n",
+ "* **If the period is one day then `start` and/or `end` cannot be passed as times.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `Overlapping indices`\n",
+ "\n",
+ "Now, if you've been playing with `trading_index` as you've worked through this tutorial and you've managed to get this far without raising an error, then you just haven't been trying hard enough..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 49,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "IntervalIndex([[2021-12-23 01:30:00, 2021-12-23 03:15:00), [2021-12-23 03:15:00, 2021-12-23 05:00:00), [2021-12-23 05:00:00, 2021-12-23 06:45:00), [2021-12-23 06:45:00, 2021-12-23 08:30:00)], dtype='interval[datetime64[ns, UTC], left]')"
+ ]
+ },
+ "execution_count": 49,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "period_105 = hkg.trading_index(start, start, \"105T\")\n",
+ "period_105"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Just one more minute..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "period_106 = hkg.trading_index(start, start, \"106T\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "IntervalsOverlapError Traceback (most recent call last)\n",
+ "Input In [50], in ()\n",
+ "----> 1 period_106 = hkg.trading_index(start, start, \"106T\")\n",
+ "\n",
+ "IntervalsOverlapError: Unable to create trading index as intervals would overlap. This can occur when the frequency is longer than a break or the gap between one session's close and the next session's open (as reduced by any alignment). To shorten intervals that would otherwise overlap either pass `curtail_overlaps` as True or pass `force_close` and/or `force_break_close` as True.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What happened? The error message pretty much explains it. Lets have a better look at the index with the 105 minutes period."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 51,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 01:30:00, 2021-12-23 03:15:00)
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 03:15:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:15:00, 2021-12-23 05:00:00)
\n",
+ "
2021-12-23 03:15:00+00:00
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 06:45:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 06:45:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:45:00, 2021-12-23 08:30:00)
\n",
+ "
2021-12-23 06:45:00+00:00
\n",
+ "
2021-12-23 08:30:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:15:00) 2021-12-23 01:30:00+00:00 \n",
+ "[2021-12-23 03:15:00, 2021-12-23 05:00:00) 2021-12-23 03:15:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:45:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 06:45:00, 2021-12-23 08:30:00) 2021-12-23 06:45:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:15:00) 2021-12-23 03:15:00+00:00 \n",
+ "[2021-12-23 03:15:00, 2021-12-23 05:00:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:45:00) 2021-12-23 06:45:00+00:00 \n",
+ "[2021-12-23 06:45:00, 2021-12-23 08:30:00) 2021-12-23 08:30:00+00:00 "
+ ]
+ },
+ "execution_count": 51,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "show_as_df(period_105)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "See how the right side of the second indice (the last indice of the morning subsession) has bumped right up against the left side of the third indice (the first indice of the afternoon subsession). The indices don't overlap because all the intervals are all `closed` on the \"left\" (by default), so the exact timestamp '2021-12-23 05:00:00' is present in the third indice..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 52,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 52,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "pd.Timestamp('2021-12-23 05:00:00', tz=ZoneInfo(\"UTC\")) in period_105[2]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "...but not the second."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 53,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 53,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "pd.Timestamp('2021-12-23 05:00:00', tz=ZoneInfo(\"UTC\")) in period_105[1]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "However, add just one more minute to the period length and these indices overlap, hence the `IntervalsOverlapError`. As noted in the error message, the overlap can be prevented by forcing close on the break."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 54,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 01:30:00, 2021-12-23 03:16:00)
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 03:16:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:16:00, 2021-12-23 04:00:00)
\n",
+ "
2021-12-23 03:16:00+00:00
\n",
+ "
2021-12-23 04:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 06:46:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 06:46:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:46:00, 2021-12-23 08:32:00)
\n",
+ "
2021-12-23 06:46:00+00:00
\n",
+ "
2021-12-23 08:32:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:16:00) 2021-12-23 01:30:00+00:00 \n",
+ "[2021-12-23 03:16:00, 2021-12-23 04:00:00) 2021-12-23 03:16:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:46:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 06:46:00, 2021-12-23 08:32:00) 2021-12-23 06:46:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:16:00) 2021-12-23 03:16:00+00:00 \n",
+ "[2021-12-23 03:16:00, 2021-12-23 04:00:00) 2021-12-23 04:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:46:00) 2021-12-23 06:46:00+00:00 \n",
+ "[2021-12-23 06:46:00, 2021-12-23 08:32:00) 2021-12-23 08:32:00+00:00 "
+ ]
+ },
+ "execution_count": 54,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "show_as_df(hkg.trading_index(start, start, \"106T\", force_break_close=True))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Or, `curtail_overlaps` can be passed as True to curtail overlapping indices. This has the effect of curtailing the right side of the earlier of the overlapping indices to the left side of the latter."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 55,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 01:30:00, 2021-12-23 03:21:00)
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 03:21:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:21:00, 2021-12-23 05:00:00)
\n",
+ "
2021-12-23 03:21:00+00:00
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 06:51:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 06:51:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:51:00, 2021-12-23 08:42:00)
\n",
+ "
2021-12-23 06:51:00+00:00
\n",
+ "
2021-12-23 08:42:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:21:00) 2021-12-23 01:30:00+00:00 \n",
+ "[2021-12-23 03:21:00, 2021-12-23 05:00:00) 2021-12-23 03:21:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:51:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 06:51:00, 2021-12-23 08:42:00) 2021-12-23 06:51:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:21:00) 2021-12-23 03:21:00+00:00 \n",
+ "[2021-12-23 03:21:00, 2021-12-23 05:00:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:51:00) 2021-12-23 06:51:00+00:00 \n",
+ "[2021-12-23 06:51:00, 2021-12-23 08:42:00) 2021-12-23 08:42:00+00:00 "
+ ]
+ },
+ "execution_count": 55,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index = hkg.trading_index(start, start, \"111T\", curtail_overlaps=True)\n",
+ "show_as_df(index)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Obviously this has the same effect as forcing the close in so much as the lengths of some indices will now be less than the passed `period`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 56,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "TimedeltaIndex(['0 days 01:51:00', '0 days 01:39:00', '0 days 01:51:00',\n",
+ " '0 days 01:51:00'],\n",
+ " dtype='timedelta64[ns]', freq=None)"
+ ]
+ },
+ "execution_count": 56,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index.length"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**NB** that `curtail_overlaps` is only available if outputing as an `IntervalIndex` (if `intervals=False` then `curtail_overlaps` has no effect).\n",
+ "\n",
+ "Another option, not noted by the error message, can be to _increase_ the period. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 57,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 01:30:00, 2021-12-23 04:00:00)
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 04:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 07:30:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 07:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 07:30:00, 2021-12-23 10:00:00)
\n",
+ "
2021-12-23 07:30:00+00:00
\n",
+ "
2021-12-23 10:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 04:00:00) 2021-12-23 01:30:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 07:30:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 07:30:00, 2021-12-23 10:00:00) 2021-12-23 07:30:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 04:00:00) 2021-12-23 04:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 07:30:00) 2021-12-23 07:30:00+00:00 \n",
+ "[2021-12-23 07:30:00, 2021-12-23 10:00:00) 2021-12-23 10:00:00+00:00 "
+ ]
+ },
+ "execution_count": 57,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "show_as_df(hkg.trading_index(start, start, \"150T\"))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "(I'll leave it to you to work out what happened there.)\n",
+ "\n",
+ "The possibility for overlaps are not limited to calendars with lunch breaks. Overlaps can also occur when the right side of the last indice of one session falls later than the left side of the first indice of the next session (as adjusted for any alignment). For a 24 hour calendar, like CMES, this will occur whenever the period is not a factor of 24 hours."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 58,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-22 23:00:00, 2021-12-22 23:07:00) 2021-12-22 23:00:00+00:00 \n",
+ "[2021-12-22 23:07:00, 2021-12-22 23:14:00) 2021-12-22 23:07:00+00:00 \n",
+ "[2021-12-22 23:14:00, 2021-12-22 23:21:00) 2021-12-22 23:14:00+00:00 \n",
+ "[2021-12-22 23:21:00, 2021-12-22 23:28:00) 2021-12-22 23:21:00+00:00 \n",
+ "[2021-12-22 23:28:00, 2021-12-22 23:35:00) 2021-12-22 23:28:00+00:00 \n",
+ "... ... \n",
+ "[2021-12-28 22:27:00, 2021-12-28 22:34:00) 2021-12-28 22:27:00+00:00 \n",
+ "[2021-12-28 22:34:00, 2021-12-28 22:41:00) 2021-12-28 22:34:00+00:00 \n",
+ "[2021-12-28 22:41:00, 2021-12-28 22:48:00) 2021-12-28 22:41:00+00:00 \n",
+ "[2021-12-28 22:48:00, 2021-12-28 22:55:00) 2021-12-28 22:48:00+00:00 \n",
+ "[2021-12-28 22:55:00, 2021-12-28 23:00:00) 2021-12-28 22:55:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-22 23:00:00, 2021-12-22 23:07:00) 2021-12-22 23:07:00+00:00 \n",
+ "[2021-12-22 23:07:00, 2021-12-22 23:14:00) 2021-12-22 23:14:00+00:00 \n",
+ "[2021-12-22 23:14:00, 2021-12-22 23:21:00) 2021-12-22 23:21:00+00:00 \n",
+ "[2021-12-22 23:21:00, 2021-12-22 23:28:00) 2021-12-22 23:28:00+00:00 \n",
+ "[2021-12-22 23:28:00, 2021-12-22 23:35:00) 2021-12-22 23:35:00+00:00 \n",
+ "... ... \n",
+ "[2021-12-28 22:27:00, 2021-12-28 22:34:00) 2021-12-28 22:34:00+00:00 \n",
+ "[2021-12-28 22:34:00, 2021-12-28 22:41:00) 2021-12-28 22:41:00+00:00 \n",
+ "[2021-12-28 22:41:00, 2021-12-28 22:48:00) 2021-12-28 22:48:00+00:00 \n",
+ "[2021-12-28 22:48:00, 2021-12-28 22:55:00) 2021-12-28 22:55:00+00:00 \n",
+ "[2021-12-28 22:55:00, 2021-12-28 23:00:00) 2021-12-28 23:00:00+00:00 \n",
+ "\n",
+ "[618 rows x 2 columns]"
+ ]
+ },
+ "execution_count": 61,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "show_as_df(cmes.trading_index(start, end, \"7T\", force_close=True))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Overlapping indices are also a consideration for trading indexes output as `DatetimeIndex`, although only if the index is being `closed` on either the \"right\" side or \"both\" sides (it's not possible for a `DatetimeIndex` `closed` on the \"left\" side or \"neither\" side to have overlapping indices as the right side is not defined, and hence cannot overlap the left side of the following indice).\n",
+ "\n",
+ "If the index is being `closed` on the \"right\" then the periods represented by the indices will overlap whenever they would overlap for the equivalent `IntervalIndex`. Only difference is that an `IndicesOverlapError` is raised rather than an `IntervalsOverlapError`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "hkg.trading_index(start, start, \"106T\", closed=\"right\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "IndicesOverlapError Traceback (most recent call last)\n",
+ "Input In [62], in ()\n",
+ "----> 1 hkg.trading_index(start, start, \"106T\", closed=\"right\", intervals=False)\n",
+ "\n",
+ "IndicesOverlapError: Unable to create trading index as an indice would fall to the right of (later than) the subsequent indice. This can occur when the frequency is longer than a break or the gap between one session's close and the next session's open (as reduced by any alignment). Consider passing `closed` as `left` or passing `force_close` and/or `force_break_close` as True.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "If the trading index is being closed on \"both\" sides then the overlap will occur one minute earlier, as whilst this is on the limit with `closed` \"right\"..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 63,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 03:15:00+00:00', '2021-12-23 05:00:00+00:00',\n",
+ " '2021-12-23 06:45:00+00:00', '2021-12-23 08:30:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 63,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start, start, \"105T\", closed=\"right\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It's over the limit if `closed` \"both\". This is because here 05:00 would be a minute of both the last implied period of the morning subsession and the first implied period of the afternoon subsession."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "hkg.trading_index(start, start, \"105T\", closed=\"both\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "IndicesOverlapError Traceback (most recent call last)\n",
+ "Input In [64], in ()\n",
+ "----> 1 hkg.trading_index(start, start, \"105T\", closed=\"both\", intervals=False)\n",
+ "\n",
+ "IndicesOverlapError: Unable to create trading index as an indice would fall to the right of (later than) the subsequent indice. This can occur when the frequency is longer than a break or the gap between one session's close and the next session's open (as reduced by any alignment). Consider passing `closed` as `left` or passing `force_close` and/or `force_break_close` as True.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As with an `IntervalIndex`, overlapping indices can be prevented by forcing the applicable close(s). Unlike `IntervalIndex`, `curtail_indices` is **not** available for `DatetimeIndex`.\n",
+ "\n",
+ "Although `curtail_overlaps` is unavailable, a similar effect can be achieved by passing `closed` as \"left\" instead of \"both\" or \"neither\" instead of \"right\" (the effect isn't exactly the same as `curtail_overlaps` allows for curtailing only overlapping indices, whilst changing closed to \"left\" or \"neither\" has the effect of losing the right side of the last implied period of _all_ sessions and subsessions, regardless of whether they would overlap or not)."
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python38 xcals",
+ "language": "python",
+ "name": "py38_xcals"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.8.10"
+ },
+ "widgets": {
+ "application/vnd.jupyter.widget-state+json": {
+ "state": {},
+ "version_major": 2,
+ "version_minor": 0
+ }
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/NYSE-Historical-Closings.pdf b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/NYSE-Historical-Closings.pdf
new file mode 100644
index 0000000000000000000000000000000000000000..35fdcbe42bde4851817aa55ac58d47a04a3ea9f2
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/NYSE-Historical-Closings.pdf
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cbebd12230d3600a92922a97791d4601c6d6326e1b2b0d9348d1d6b1f22f6f77
+size 141885
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/bench.py b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/bench.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f4c780df4ef2c3638e8f92dd15ca79527369fd4
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/bench.py
@@ -0,0 +1,49 @@
+import itertools
+
+import pandas as pd
+
+from exchange_calendars import get_calendar
+from exchange_calendars.calendar_helpers import UTC
+from exchange_calendars.calendar_utils import (
+ ExchangeCalendarDispatcher,
+ _default_calendar_aliases,
+ _default_calendar_factories,
+)
+
+
+def construct_all_calendars():
+ dispatcher = ExchangeCalendarDispatcher(
+ calendars={},
+ calendar_factories=_default_calendar_factories,
+ aliases=_default_calendar_aliases,
+ )
+
+ calendar_names = itertools.chain(
+ _default_calendar_aliases, _default_calendar_factories
+ )
+
+ for name in calendar_names:
+ assert dispatcher.get_calendar(name) is not None
+ dispatcher.deregister_calendar(name)
+
+
+def is_open_on_minute_bench(cal, timestamps):
+ for timestamp in timestamps:
+ cal.is_open_on_minute(timestamp, _parse=False)
+
+
+def test_calendar_construction(benchmark):
+ benchmark(construct_all_calendars)
+
+
+def test_is_open_on_minute(benchmark):
+ xhkg = get_calendar("XHKG")
+ timestamps = [
+ pd.Timestamp("2019-10-11 01:20:00", tz=UTC), # pre open
+ pd.Timestamp("2019-10-11 01:30:00", tz=UTC), # open
+ pd.Timestamp("2019-10-11 01:31:00", tz=UTC), # first minute
+ pd.Timestamp("2019-10-11 04:31:00", tz=UTC), # in break
+ pd.Timestamp("2019-10-11 08:00:00", tz=UTC), # close
+ pd.Timestamp("2019-10-11 08:01:00", tz=UTC), # post close
+ ]
+ benchmark(is_open_on_minute_bench, xhkg, timestamps)
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/check_holidays.py b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/check_holidays.py
new file mode 100644
index 0000000000000000000000000000000000000000..7aba50ca52a111ed197846864427df11d7d41a98
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/check_holidays.py
@@ -0,0 +1,208 @@
+from functools import partial
+
+import click
+import pandas as pd
+
+from exchange_calendars import get_calendar
+from exchange_calendars.calendar_helpers import UTC
+from exchange_calendars.calendar_utils import default_calendar_names
+
+
+class TimestampType(click.ParamType):
+ """A click parameter that parses the value into pandas.Timestamp objects.
+
+ Parameters
+ ----------
+ tz : timezone-coercable, optional
+ The timezone to parse the string as.
+ By default the timezone will be infered from the string or naiive.
+ """
+
+ def __init__(self, tz=None):
+ self.tz = tz
+
+ @property
+ def name(self):
+ return "TIMESTAMP"
+
+ def convert(self, value, param, ctx):
+ try:
+ return pd.Timestamp(value, tz=self.tz)
+ except ValueError:
+ self.fail(
+ "%s is not a valid timestamp." % value,
+ param,
+ ctx,
+ )
+
+
+def check_holidays(
+ holiday_key_path,
+ calendar_column,
+ holiday_column,
+ date_format,
+ delimiter,
+ strip_x_from_cal_name,
+ answer_key_calendar_name,
+ min_date,
+ calendars,
+):
+ data = pd.read_csv(
+ holiday_key_path,
+ sep=delimiter,
+ parse_dates=[holiday_column],
+ date_parser=partial(pd.to_datetime, format=date_format, utc=True),
+ )
+
+ for calendar_name in default_calendar_names:
+ if calendars and calendar_name not in calendars:
+ continue
+
+ cal = get_calendar(calendar_name)
+
+ if answer_key_calendar_name:
+ csv_cal_code = answer_key_calendar_name
+ elif strip_x_from_cal_name:
+ # Convert the calendar name to the format expected in the CSV.
+ csv_cal_code = calendar_name.lstrip("X")
+ else:
+ csv_cal_code = calendar_name
+
+ holidays = set(data[holiday_column][data[calendar_column] == csv_cal_code])
+
+ if holidays:
+ start = max(cal.first_session, min(holidays), min_date)
+ end = min(cal.last_session, max(holidays))
+
+ _check_range(start, end, holidays, cal, calendar_name)
+ else:
+ click.secho(
+ "No holidays found for {} in the holiday key.".format(
+ calendar_name,
+ ),
+ fg="yellow",
+ )
+
+ click.echo()
+
+
+def _check_range(start, end, holidays, cal, calendar_name):
+ msg = ("Checking {} holidays on the {} ({}) calendar between {} and {}.").format(
+ len(holidays),
+ type(cal).__name__,
+ calendar_name,
+ start.date(),
+ end.date(),
+ )
+ click.echo(msg)
+
+ dates = pd.date_range(start, end, freq="B")
+
+ expected_sessions = dates.difference(holidays)
+ actual_sessions = cal.sessions_in_range(start, end)
+
+ unexpected_sessions = actual_sessions.difference(expected_sessions)
+ unexpected_holidays = expected_sessions.difference(actual_sessions)
+
+ if unexpected_sessions.size:
+ click.echo(
+ "\nThese dates are holidays in the given key, but trading days in "
+ "the {} exchange calendar:".format(calendar_name)
+ )
+ for session in unexpected_sessions:
+ click.secho(str(session.date()), fg="red")
+
+ if unexpected_holidays.size:
+ click.echo(
+ "\nThese dates are trading days in the given key, but holidays in "
+ "the {} exchange calendar:".format(calendar_name)
+ )
+ for holiday in unexpected_holidays:
+ click.secho(str(holiday.date()), fg="red")
+
+ if not unexpected_sessions.size and not unexpected_holidays.size:
+ click.secho(
+ "{} calendar matches the holiday key.".format(calendar_name),
+ fg="green",
+ )
+
+
+@click.command(
+ help=(
+ "Checks exchange calendars against a holiday key."
+ " HOLIDAY_KEY_PATH is the path to a CSV file containing the key,"
+ " with a calendar name column and a holiday date column."
+ )
+)
+@click.option(
+ "--min-date",
+ default=pd.Timestamp("2002-01-01"),
+ type=TimestampType(tz=UTC),
+ help="Start the holiday comparison at this date.",
+ show_default=True,
+)
+@click.option(
+ "--calendar",
+ "calendars",
+ multiple=True,
+ type=click.Choice(default_calendar_names),
+ help=(
+ "The name of a calendar to check. Specify multiple times to"
+ " check multiple calendars. Default is to check all calendars."
+ ),
+)
+@click.option("--calendar-column", help="The calendar name column in the CSV.")
+@click.option("--holiday-column", help="The holiday date column in the CSV.")
+@click.option(
+ "--date-format",
+ default="%Y%m%d",
+ help="strftime format string for parsing the date column.",
+ show_default=True,
+)
+@click.option(
+ "--delimiter",
+ default=",",
+ help="Delimiter to use when parsing the key.",
+ show_default=True,
+)
+@click.option(
+ "--strip-x-from-cal-name/--no-strip-x-from-cal-name",
+ help='E.g. "XNYS" is looked up in the key as "NYS".',
+ show_default=True,
+)
+@click.option(
+ "--answer-key-calendar-name",
+ default=None,
+ help=(
+ "Use this if a calendar is identified differently in the answer key."
+ " Not compatible with passing in multiple calendars in --calendars."
+ ),
+ show_default=False,
+)
+@click.argument("holiday_key_path", type=click.Path(exists=True))
+def main(
+ holiday_key_path,
+ min_date,
+ calendars,
+ calendar_column,
+ holiday_column,
+ date_format,
+ delimiter,
+ strip_x_from_cal_name,
+ answer_key_calendar_name,
+):
+ check_holidays(
+ holiday_key_path,
+ calendar_column,
+ holiday_column,
+ date_format,
+ delimiter,
+ strip_x_from_cal_name,
+ answer_key_calendar_name,
+ min_date,
+ calendars,
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/ecal b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/ecal
new file mode 100644
index 0000000000000000000000000000000000000000..b8a92564a630328e74feea1f4dd30273480e566d
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/ecal
@@ -0,0 +1,160 @@
+#!/usr/bin/env python
+from __future__ import print_function
+
+import io
+import sys
+
+import pandas as pd
+
+
+months = [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December",
+]
+
+
+def error(msg):
+ print(msg, file=sys.stderr)
+ exit(-1)
+
+
+def _render_month(calendar, year, month, print_year):
+ out = io.StringIO()
+
+ start = "{year}-{month}".format(year=year, month=month)
+ if month == 12:
+ end = "{year}-{month}".format(year=year + 1, month=1)
+ else:
+ end = "{year}-{month}".format(year=year, month=month + 1)
+
+ days = pd.date_range(start, end)
+
+ title = months[month - 1]
+ if print_year:
+ title += " {year}".format(year=year)
+
+ print("{title:^28}".format(title=title).rstrip(), file=out)
+ print(" Su Mo Tu We Th Fr Sa", file=out)
+ print(
+ " " * (4 * ((days[0].weekday() + 1) % 7)),
+ end="",
+ file=out,
+ )
+
+ for d in days:
+ if d.weekday() == 6:
+ print("", file=out)
+
+ if calendar.is_session(d):
+ a = b = " "
+ else:
+ a = "["
+ b = "]"
+
+ print(
+ "{a}{d.day:>2}{b}".format(a=a, d=d, b=b),
+ end="",
+ file=out,
+ )
+
+ print("", file=out)
+ return out.getvalue()
+
+
+def _concat_lines(strings, width):
+ as_lines = [string.splitlines() for string in strings]
+ max_lines = max(len(lines) for lines in as_lines)
+ for lines in as_lines:
+ missing_lines = max_lines - len(lines)
+ if missing_lines:
+ lines.extend([" " * width] * missing_lines)
+
+ rows = []
+ for row_parts in zip(*as_lines):
+ row_parts = list(row_parts)
+ for n, row_part in enumerate(row_parts):
+ missing_space = width - len(row_part)
+ if missing_space:
+ row_parts[n] = row_part + " " * missing_space
+
+ rows.append(" ".join(row_parts))
+
+ return "\n".join(row.rstrip() for row in rows)
+
+
+def _int_arg(v, name):
+ try:
+ return int(v)
+ except ValueError:
+ error("%s must be an integer, got: %r" % (name, v))
+
+
+def parse_args(argv):
+ usage = "usage: %s CALENDAR [[[DAY] MONTH] YEAR]" % argv[0]
+
+ if len(argv) == 1 or "--help" in argv or "-h" in argv:
+ error(usage)
+
+ if len(argv) > 1:
+ from exchange_calendars import get_calendar
+
+ try:
+ calendar = get_calendar(argv[1])
+ except Exception as e:
+ error(str(e))
+
+ if len(argv) == 2:
+ import datetime
+
+ now = datetime.datetime.now()
+ year = now.year
+ month = now.month
+ elif len(argv) == 3:
+ year = _int_arg(argv[2], "YEAR")
+ month = None
+ elif len(argv) == 4:
+ month = _int_arg(argv[2], "MONTH")
+ year = _int_arg(argv[3], "YEAR")
+ else:
+ error(usage)
+
+ return calendar, year, month
+
+
+def main(argv):
+ """Print a unix-cal like calendar but indicate which days are trading
+ sessions.
+ """
+ calendar, year, month = parse_args(argv)
+
+ if month is not None:
+ print(_render_month(calendar, year, month, print_year=True))
+ else:
+ month_strings = [
+ [
+ _render_month(
+ calendar,
+ year,
+ row * 3 + column + 1,
+ print_year=False,
+ )
+ for column in range(3)
+ ]
+ for row in range(4)
+ ]
+ print("{year:^88}\n".format(year=year).rstrip())
+ print("\n\n".join(_concat_lines(cs, 28) for cs in month_strings))
+
+
+if __name__ == "__main__":
+ main(sys.argv)
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/factory_bounds.py b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/factory_bounds.py
new file mode 100644
index 0000000000000000000000000000000000000000..141dabe42edca89021502d8ee59335ff2abe5c7c
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/factory_bounds.py
@@ -0,0 +1,380 @@
+"""Classes and functions to explore the bounds of calendar factories.
+
+Jul 21. Module written (prior to implementation of `bound_min`,
+`bound_max`) to explore the bounds of calendar factories. Provides for
+evaluating the earliest start date and latest end date for which a
+calendar can be instantiated without raising an error. Also records errors
+raised when dates are passed beyond these limits.
+
+Module retained in case might be useful.
+"""
+
+from __future__ import annotations
+
+import abc
+import dataclasses
+import pathlib
+import pickle
+from typing import Literal, Type
+
+import pandas as pd
+
+import exchange_calendars as xcals
+from exchange_calendars.calendar_helpers import UTC
+
+
+@dataclasses.dataclass
+class FactoryBounds:
+ """Bounds within which an xcals.ExchangeCalendar can be calculated.
+
+ Parameters
+ ----------
+ name :
+ Name of calendar with declared bounds.
+
+ start : pd.Timestamp
+ Earliest start date for which can create a calendar with end date
+ as tomorrow.
+
+ start_error :
+ Error instance raised in event request a calendar with start date
+ one day earlier than `start` and end date as tomorrow.
+
+ end : pd.Timestamp
+ Latest end date for which can create a calendar with start date
+ as yesterday.
+
+ end_error :
+ Error instance raised in event request a calendar with end date
+ one day later than `end` and start date as yesterday.
+ """
+
+ name: str
+ start: pd.Timestamp
+ start_error: Exception
+ end: pd.Timestamp
+ end_error: Exception
+
+
+class _FindFactoryBounds:
+ """Find start and end bounds of a given calendar factory."""
+
+ def __init__(self, Factory: xcals.ExchangeCalendar, watch: bool = False):
+ self.Factory = Factory
+ self.watch = watch
+ self._last_error: Exception | None
+
+ @property
+ def calendar_name(self) -> str:
+ """Calendar name."""
+ if isinstance(self.Factory.name, str):
+ return self.Factory.name
+ else:
+ return self.Factory().name
+
+ @property
+ def today(self) -> pd.Timestamp:
+ return pd.Timestamp.now(tz=UTC).floor("D")
+
+ def _get_calendar(
+ self,
+ start: pd.Timestamp | None = None,
+ end: pd.Timestamp | None = None,
+ ) -> xcals.ExchangeCalendar:
+ """Get calendar for period between now and `start` or `end`."""
+ if self.watch:
+ insert = f"start={start}" if start is not None else f"end={end}"
+ if start is None:
+ start = self.today - pd.Timedelta(1, "D")
+ elif end is None:
+ end = self.today + pd.Timedelta(1, "D")
+ else:
+ raise ValueError("`start` and `end` cannot both be None.")
+ if self.watch:
+ print(f"getting calendar '{self.calendar_name}' with {insert}.")
+ return self.Factory(start=start, end=end)
+
+ def _is_valid_date(
+ self, date: pd.Timestamp, bound: Literal["start", "end"]
+ ) -> bool:
+ kwargs = {bound: date}
+ try:
+ self._get_calendar(**kwargs)
+ except Exception as err: # pylint: disable=broad-except
+ self._last_error = err
+ return False
+ else:
+ return True
+
+ def _get_a_valid_date_by_trying_every_x_days(
+ self,
+ look_from: pd.Timestamp,
+ offset: pd.DateOffset,
+ bound: Literal["start", "end"],
+ ) -> pd.Timestamp:
+ # recursively look for a valid date every offset, return first that's valid
+ if self._is_valid_date(look_from, bound):
+ return look_from
+ else:
+ next_look_from = look_from + offset
+ if ( # if start has move into the future or end into the past
+ look_from <= self.today < next_look_from
+ or look_from >= self.today > next_look_from
+ ):
+ return self.today
+ else:
+ return self._get_a_valid_date_by_trying_every_x_days(
+ next_look_from, offset, bound
+ )
+
+ @property
+ def _first_offset(self) -> pd.DateOffset:
+ return pd.DateOffset(years=100)
+
+ def _is_first_offset(self, offset: pd.DateOffset) -> bool:
+ return offset == self._first_offset or -offset == self._first_offset
+
+ def _offset_iterator(
+ self, bound: Literal["start", "end"]
+ ) -> abc.Iterator[pd.DateOffset]:
+ sign = 1 if bound == "start" else -1
+ iterator = iter(
+ [
+ sign * self._first_offset,
+ sign * pd.DateOffset(years=30),
+ sign * pd.DateOffset(years=10),
+ sign * pd.DateOffset(years=3),
+ sign * pd.DateOffset(years=1),
+ sign * pd.DateOffset(months=3),
+ sign * pd.DateOffset(months=1),
+ sign * pd.DateOffset(days=10),
+ sign * pd.DateOffset(days=3),
+ sign * pd.DateOffset(days=1),
+ ]
+ )
+ return iterator
+
+ def _is_valid_bound(
+ self, date: pd.Timestamp, bound: Literal["start", "end"]
+ ) -> bool:
+ if not self._is_valid_date(date, bound):
+ return False
+ else:
+ day_delta = 1 if bound == "end" else -1
+ date = date + pd.Timedelta(day_delta, "D")
+ return not self._is_valid_date(date, bound)
+
+ def _try_short_cut(
+ self, bound: Literal["start", "end"]
+ ) -> tuple[pd.Timestamp, Exception] | None:
+ """Try known likely bounds around min/max Timestamp.
+
+ These likely bounds are caused by how special closes is calculated.
+
+ Return None if no likely bound is a bound.
+ """
+ if bound == "start":
+ likely_bounds = [
+ pd.Timestamp("1678-01-01", tz=UTC),
+ pd.Timestamp("1679-01-01", tz=UTC),
+ ]
+ else:
+ likely_bounds = [
+ pd.Timestamp("2260-12-31", tz=UTC),
+ pd.Timestamp("2262-04-10", tz=UTC),
+ ]
+
+ for likely_bound in likely_bounds:
+ if self._is_valid_bound(likely_bound, bound):
+ assert self._last_error is not None
+ return (likely_bound, self._last_error)
+ return None
+
+ @staticmethod
+ def _initial_value(bound: Literal["start", "end"]) -> pd.Timestamp:
+ if bound == "start":
+ return pd.Timestamp.min.ceil("D").tz_localize(UTC)
+ else:
+ return pd.Timestamp.max.floor("D").tz_localize(UTC)
+
+ def _get_bound(
+ self, bound: Literal["start", "end"]
+ ) -> tuple[pd.Timestamp, Exception]:
+ self._last_error = None
+ initial_value = self._initial_value(bound)
+
+ try:
+ assert not self._is_valid_bound(initial_value, bound)
+ except pd.errors.OutOfBoundsDatetime as err:
+ # if initial_value is a valid bound then `is_valid_bound` will
+ # raise OutOfBoundsDatetime as prod beyond pandas timestamp bounds
+ return (initial_value, err)
+
+ offset_iterator = self._offset_iterator(bound)
+ offset = next(offset_iterator)
+ look_from = initial_value
+ while offset:
+ look_from += (
+ offset # avoid getting calendar with same parameters as a previous call
+ )
+ valid_date = self._get_a_valid_date_by_trying_every_x_days(
+ look_from, offset, bound
+ )
+ if valid_date == look_from and self._is_first_offset(offset):
+ # first attempt was valid, chances are only calculation of
+ # special closes was causing error on min date. Try short-cut:
+ short_cut = self._try_short_cut(bound)
+ if short_cut is not None:
+ return short_cut
+ look_from = valid_date - offset
+ try:
+ offset = next(offset_iterator)
+ except StopIteration:
+ break
+ return (valid_date, self._last_error)
+
+ def bounds(self) -> FactoryBounds:
+ """Return valid bounds for Factory's `start` and `end` parameters.
+
+ See find_factory_bounds.___doc___
+ """
+ start_bound = self._get_bound("start")
+ end_bound = self._get_bound("end")
+ return FactoryBounds(self.calendar_name, *start_bound, *end_bound)
+
+
+def find_factory_bounds(
+ Factory: xcals.ExchangeCalendar, watch: bool = False
+) -> FactoryBounds:
+ """Return FactoryBounds for a factory.
+
+ Bounds deliniate the longest continuous period, which includes today,
+ through which start and end dates will always return an
+ xcals.ExchangeCalendar. Calling the `Factory` with a start date one day
+ before the start bound, or with an end date one day after the end
+ bound, will raise an error.
+
+ Parameters
+ ----------
+ Factory :
+ xcals.ExchangeCalendar class to query bounds of.
+
+ watch :
+ True for a live print of factory calls as the bounds are
+ sought out and prodded.
+
+ Returns
+ -------
+ FactoryBounds:
+ Dataclass that describes bounds and associated out-of-bounds
+ errors. See FactoryBounds.__doc__.
+
+ Notes
+ -----
+ Uses trial and error to home in on and prod the bounds.
+ """
+ return _FindFactoryBounds(Factory, watch).bounds()
+
+
+def _find_bounds_all_factories(watch=False) -> dict[str, FactoryBounds]:
+ """Find and return Factory Bounds for all calendars.
+
+ NOTE: This function will take a fair while to run! Pass `watch` as
+ True for a live print of factory calls as the bounds are sought and
+ proded.
+ """
+ cal_bounds = {}
+ for name, Factory in xcals.calendar_utils._default_calendar_factories.items():
+ cal_bounds[name] = find_factory_bounds(Factory, watch)
+ return cal_bounds
+
+
+def _factory_bounds_resource_path() -> pathlib.PurePath:
+ path = pathlib.Path(__file__)
+ path = pathlib.Path(path.parent, "resources/_factory_bounds.dat")
+ assert path.exists()
+ return path
+
+
+def _bake_all_calendar_bounds(all_calendar_bounds: dict["str", FactoryBounds]):
+ """Bake `all_calendar_bounds` to resource file.
+
+ NOTE: CHECK passed `all_calendar_bounds` before baking.
+
+ Parameters
+ ----------
+ all_calendar_bounds :
+ As returned by `_find_bounds_all_factories`. CHECK return before
+ baking!!
+ """
+ assert isinstance(all_calendar_bounds, dict)
+ assert len(all_calendar_bounds) > 20
+ key = list(all_calendar_bounds.keys())[0]
+ assert isinstance(key, str)
+ assert isinstance(all_calendar_bounds[key], FactoryBounds)
+ with open(_factory_bounds_resource_path(), "wb") as file:
+ pickle.dump(all_calendar_bounds, file)
+
+
+def _retrieve_all_calendars_bounds() -> dict["str", FactoryBounds]:
+ """Retrieve `all_calendar_bounds` from resources."""
+ with open(_factory_bounds_resource_path(), "rb") as file:
+ all_calendar_bounds = pickle.load(file)
+ return all_calendar_bounds
+
+
+_all_calendars_bounds = _retrieve_all_calendars_bounds()
+
+
+def _get_all_calendars_bounds_exceptions() -> tuple[Type[Exception], ...]:
+ """Exceptions the can be raised when request calendar with oob date."""
+ bounds = _all_calendars_bounds
+ errors = []
+ for cal in bounds:
+ error_types = (type(bounds[cal].start_error), type(bounds[cal].end_error))
+ for error_type in error_types:
+ if error_type not in errors:
+ errors.append(error_type)
+ return tuple(errors)
+
+
+def all_calendars_bounds() -> pd.DataFrame:
+ """Return DataFrame describing start and end bounds for each calendar.
+
+ Bounds deliniate the longest continuous period, which includes today,
+ through which start and end dates will always return an
+ xcals.ExchangeCalendar.
+
+ Returns
+ -------
+ pd.DataFrame
+ Indexed with calendar names.
+ Columns:
+ earliest_valid_start - earliest start date from which a
+ calendar can be instantiated with end date as today.
+ latest_valid_end - latest end date to which a calendar can
+ be instantiated with start date as today.
+ """
+ cal_bounds = _all_calendars_bounds
+ start_bounds = []
+ end_bounds = []
+ for _, factory_bounds in cal_bounds.items():
+ start_bounds.append(factory_bounds.start)
+ end_bounds.append(factory_bounds.end)
+
+ return pd.DataFrame(
+ dict(earliest_valid_start=start_bounds, latest_valid_end=end_bounds),
+ index=cal_bounds.keys(),
+ )
+
+
+def get_calendar_bounds(
+ calendar_name: str,
+) -> tuple[pd.Timestamp, pd.Timestamp]:
+ """Retun 2-tuple describing start and end bounds for a given calendar.
+
+ Bounds deliniate the longest continuous period, which includes today,
+ through which start and end dates will always return a calendar.
+ """
+ bounds = _all_calendars_bounds[calendar_name]
+ return (bounds.start, bounds.end)
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/lunisolar b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/lunisolar
new file mode 100644
index 0000000000000000000000000000000000000000..05447eaad018994a2786ce4c16f43b084a5d19fc
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/lunisolar
@@ -0,0 +1,1616 @@
+#!/usr/bin/env python
+# coding=utf-8
+"""Lunisolar calendar calculations.
+
+Utilities for computing the dates of holidays based on lunar or solar events.
+
+The definition for Chinese New Year comes from:
+Aslaksen, Helmer. "The Mathematics of the Chinese Calendar",
+http://www.math.nus.edu.sg/aslaksen/calendar/cal.pdf
+
+This utility uses NOVAS (http://aa.usno.navy.mil/software/novas/novas_info.php)
+to predict the position of the sun:
+Barron, E. G., Kaplan, G. H., Bangert, J., Bartlett, J. L., Puatua, W., Harris,
+W., & Barrett, P. (2011) "Naval Observatory Vector Astrometry Software (NOVAS)
+Version 3.1, Introducing a Python Edition," Bull. AAS, 43, 2011. (Abstract)
+
+I also found the following book very helpful to understand the underlying
+concepts for these predictions:
+Jean H. Meeus. 1991. Astronomical Algorithms. Willmann-Bell, Incorporated.
+"""
+import contextlib
+import operator as op
+import pathlib
+import re
+
+import click
+import novas.compat as novas
+import numpy as np
+import pandas as pd
+import toolz
+from novas.compat import eph_manager
+
+from exchange_calendars.calendar_helpers import UTC
+
+
+@contextlib.contextmanager
+def ephemeris():
+ """A context manager for managing the novas ephemeris file."""
+ eph_manager.ephem_open()
+ try:
+ yield
+ finally:
+ eph_manager.ephem_close()
+
+
+def load_precomputed_data(root_dir):
+ """Load saved data.
+
+ Parameters
+ ----------
+ root_dir : path-like
+ The directory to load the data from.
+
+ Returns
+ -------
+ values : np.ndarray[float64]
+ The precomputed data.
+ minutes : np.ndarray[M8[m]]
+ The minute labels for the data.
+ """
+ root_dir = pathlib.Path(root_dir)
+
+ pattern = re.compile(r"(.*)_(.*)")
+ files = [(p, pattern.match(p.name)) for p in root_dir.iterdir()]
+ files = list(filter(lambda t: t[1] is not None, files))
+ files = sorted(files, key=lambda t: np.datetime64(t[1][1]))
+
+ values = []
+ minutes = []
+ for path, match in files:
+ values.append(np.fromfile(str(path)))
+ minutes.append(
+ np.arange(
+ match[1],
+ np.datetime64(match[2]) + np.timedelta64(1, "m"),
+ dtype="M8[m]",
+ )
+ )
+
+ return np.hstack(values), np.hstack(minutes)
+
+
+def smooth(arr, window):
+ """Smooth an array by taking a rolling arithmetic mean.
+
+ Parameters
+ ----------
+ arr : np.ndarray
+ The array to smooth.
+ window : int
+ The size of the window to use when taking the mean.
+
+ Returns
+ -------
+ smoothed : np.ndarray
+ The smoothed array of length ``len(arr) - window // 2``.
+ """
+ return np.convolve(np.ones(window) / window, arr, mode="valid")
+
+
+def local_cmp(f, arr):
+ """Compare elements of an array to its direct neighbors.
+
+ Parameters
+ ----------
+ f : callable
+ The comparison to apply.
+ arr : np.ndarray
+ The array to check.
+
+ Returns
+ -------
+ ix : np.ndarray[int64]
+ An array of indices where ``f(arr[i], arr[i + 1])`` and
+ ``f(arr[i - 1], arr[i])`` are true. index 0 and -1 are considered
+ False.
+
+ Examples
+ --------
+ >>> import operator as op
+ # 100 samples of a path of 5 rotations
+ >>> rad = np.fmod(np.linspace(0, 5 * 2 * np.pi, 100), 2 * np.pi)
+ >>> sin = np.sin(rad)
+ >>> local_minima_ix = local_cmp(op.lt, sin)
+
+ # NOTE: this is not all -1 because we only took 100 samples so
+ # 3 * np.pi / 2 doesn't appear exactly in the ``rad`` array.
+ >>> sin[local_minima_ix]
+ array([-0.99886734, -0.99383846, -0.98982144, -0.99685478, -0.99987413])
+
+ >>> rad[local_minima_ix]
+ array([ 4.75998887, 4.82345539, 4.56958931, 4.63305583, 4.69652235])
+ """
+ return np.flatnonzero(
+ np.r_[False, f(arr[1:], arr[:-1])] & np.r_[f(arr[:-1], arr[1:]), False]
+ )
+
+
+def smoothed_local_cmp(f, arr, window):
+ """Smooth an array and then compare elements to its direct neighbors.
+
+ Parameters
+ ----------
+ f : callable
+ The comparison to apply.
+ arr : np.ndarray
+ The array to check.
+ window : int
+ The size of the window to use when smoothing the array.
+
+ Returns
+ -------
+ ix : np.ndarray[int64]
+ An array of indices where ``f(arr[i], arr[i + 1])`` and
+ ``f(arr[i - 1], arr[i])`` are true. index 0 and -1 are considered
+ False.
+ """
+ return local_cmp(f, smooth(arr, window)) + window // 2
+
+
+def utc_to_jd_tt(ts):
+ """Convert UTC datetimes to Julian Date Terrestrial Time.
+
+ Parameters
+ ----------
+ ts : np.ndarray[M8[s]]
+ The timestamps to convert.
+
+ Returns
+ -------
+ jd_tt : np.ndarray[f8]
+ The julian date terrestrial time for the UTC values.
+ """
+ # lookup the corrections stored on this function object
+ corrections = utc_to_jd_tt.corrections
+
+ jd_utc = ts.astype("M8[s]").view("i8") / 86400 + 2440587.5
+ correction_ix = np.searchsorted(
+ corrections["time"],
+ ts,
+ side="right",
+ )
+ correction_ix[correction_ix == len(corrections)] -= 1
+ return jd_utc + corrections["julian_days"][correction_ix]
+
+
+def T(year, month, day):
+ return np.datetime64(f"{year}-{month:02d}-{day:02d}", "D")
+
+
+# UTC to JD TT adjustment factors from:
+# https://www.usno.navy.mil/USNO/earth-orientation/eo-products/long-term
+utc_to_jd_tt.corrections = np.array(
+ [
+ (T(1700, 1, 1), 32.184),
+ (T(1973, 2, 1), 43.4724),
+ (T(1973, 3, 1), 43.5648),
+ (T(1973, 4, 1), 43.6737),
+ (T(1973, 5, 1), 43.7782),
+ (T(1973, 6, 1), 43.8763),
+ (T(1973, 7, 1), 43.9562),
+ (T(1973, 8, 1), 44.0315),
+ (T(1973, 9, 1), 44.1132),
+ (T(1973, 10, 1), 44.1982),
+ (T(1973, 11, 1), 44.2952),
+ (T(1973, 12, 1), 44.3936),
+ (T(1974, 1, 1), 44.4840),
+ (T(1974, 2, 1), 44.5646),
+ (T(1974, 3, 1), 44.6425),
+ (T(1974, 4, 1), 44.7386),
+ (T(1974, 5, 1), 44.8370),
+ (T(1974, 6, 1), 44.9302),
+ (T(1974, 7, 1), 44.9986),
+ (T(1974, 8, 1), 45.0583),
+ (T(1974, 9, 1), 45.1284),
+ (T(1974, 10, 1), 45.2064),
+ (T(1974, 11, 1), 45.2980),
+ (T(1974, 12, 1), 45.3897),
+ (T(1975, 1, 1), 45.4761),
+ (T(1975, 2, 1), 45.5632),
+ (T(1975, 3, 1), 45.6450),
+ (T(1975, 4, 1), 45.7374),
+ (T(1975, 5, 1), 45.8284),
+ (T(1975, 6, 1), 45.9133),
+ (T(1975, 7, 1), 45.9820),
+ (T(1975, 8, 1), 46.0407),
+ (T(1975, 9, 1), 46.1067),
+ (T(1975, 10, 1), 46.1825),
+ (T(1975, 11, 1), 46.2788),
+ (T(1975, 12, 1), 46.3713),
+ (T(1976, 1, 1), 46.4567),
+ (T(1976, 2, 1), 46.5445),
+ (T(1976, 3, 1), 46.6311),
+ (T(1976, 4, 1), 46.7302),
+ (T(1976, 5, 1), 46.8283),
+ (T(1976, 6, 1), 46.9247),
+ (T(1976, 7, 1), 46.9970),
+ (T(1976, 8, 1), 47.0709),
+ (T(1976, 9, 1), 47.1450),
+ (T(1976, 10, 1), 47.2361),
+ (T(1976, 11, 1), 47.3413),
+ (T(1976, 12, 1), 47.4319),
+ (T(1977, 1, 1), 47.5214),
+ (T(1977, 2, 1), 47.6049),
+ (T(1977, 3, 1), 47.6837),
+ (T(1977, 4, 1), 47.7781),
+ (T(1977, 5, 1), 47.8771),
+ (T(1977, 6, 1), 47.9687),
+ (T(1977, 7, 1), 48.0348),
+ (T(1977, 8, 1), 48.0942),
+ (T(1977, 9, 1), 48.1608),
+ (T(1977, 10, 1), 48.2460),
+ (T(1977, 11, 1), 48.3438),
+ (T(1977, 12, 1), 48.4355),
+ (T(1978, 1, 1), 48.5344),
+ (T(1978, 2, 1), 48.6324),
+ (T(1978, 3, 1), 48.7294),
+ (T(1978, 4, 1), 48.8365),
+ (T(1978, 5, 1), 48.9353),
+ (T(1978, 6, 1), 49.0319),
+ (T(1978, 7, 1), 49.1013),
+ (T(1978, 8, 1), 49.1591),
+ (T(1978, 9, 1), 49.2285),
+ (T(1978, 10, 1), 49.3070),
+ (T(1978, 11, 1), 49.4018),
+ (T(1978, 12, 1), 49.4945),
+ (T(1979, 1, 1), 49.5861),
+ (T(1979, 2, 1), 49.6805),
+ (T(1979, 3, 1), 49.7602),
+ (T(1979, 4, 1), 49.8556),
+ (T(1979, 5, 1), 49.9489),
+ (T(1979, 6, 1), 50.0347),
+ (T(1979, 7, 1), 50.1018),
+ (T(1979, 8, 1), 50.1622),
+ (T(1979, 9, 1), 50.2260),
+ (T(1979, 10, 1), 50.2968),
+ (T(1979, 11, 1), 50.3831),
+ (T(1979, 12, 1), 50.4599),
+ (T(1980, 1, 1), 50.5387),
+ (T(1980, 2, 1), 50.6160),
+ (T(1980, 3, 1), 50.6866),
+ (T(1980, 4, 1), 50.7658),
+ (T(1980, 5, 1), 50.8454),
+ (T(1980, 6, 1), 50.9187),
+ (T(1980, 7, 1), 50.9761),
+ (T(1980, 8, 1), 51.0278),
+ (T(1980, 9, 1), 51.0843),
+ (T(1980, 10, 1), 51.1538),
+ (T(1980, 11, 1), 51.2319),
+ (T(1980, 12, 1), 51.3063),
+ (T(1981, 1, 1), 51.3808),
+ (T(1981, 2, 1), 51.4526),
+ (T(1981, 3, 1), 51.5160),
+ (T(1981, 4, 1), 51.5985),
+ (T(1981, 5, 1), 51.6809),
+ (T(1981, 6, 1), 51.7573),
+ (T(1981, 7, 1), 51.8133),
+ (T(1981, 8, 1), 51.8532),
+ (T(1981, 9, 1), 51.9014),
+ (T(1981, 10, 1), 51.9603),
+ (T(1981, 11, 1), 52.0328),
+ (T(1981, 12, 1), 52.0985),
+ (T(1982, 1, 1), 52.1668),
+ (T(1982, 2, 1), 52.2316),
+ (T(1982, 3, 1), 52.2938),
+ (T(1982, 4, 1), 52.3680),
+ (T(1982, 5, 1), 52.4465),
+ (T(1982, 6, 1), 52.5179),
+ (T(1982, 7, 1), 52.5751),
+ (T(1982, 8, 1), 52.6178),
+ (T(1982, 9, 1), 52.6668),
+ (T(1982, 10, 1), 52.7340),
+ (T(1982, 11, 1), 52.8056),
+ (T(1982, 12, 1), 52.8792),
+ (T(1983, 1, 1), 52.9565),
+ (T(1983, 2, 1), 53.0445),
+ (T(1983, 3, 1), 53.1268),
+ (T(1983, 4, 1), 53.2197),
+ (T(1983, 5, 1), 53.3024),
+ (T(1983, 6, 1), 53.3747),
+ (T(1983, 7, 1), 53.4335),
+ (T(1983, 8, 1), 53.4778),
+ (T(1983, 9, 1), 53.5300),
+ (T(1983, 10, 1), 53.5845),
+ (T(1983, 11, 1), 53.6523),
+ (T(1983, 12, 1), 53.7256),
+ (T(1984, 1, 1), 53.7882),
+ (T(1984, 2, 1), 53.8367),
+ (T(1984, 3, 1), 53.8830),
+ (T(1984, 4, 1), 53.9443),
+ (T(1984, 5, 1), 54.0042),
+ (T(1984, 6, 1), 54.0536),
+ (T(1984, 7, 1), 54.0856),
+ (T(1984, 8, 1), 54.1084),
+ (T(1984, 9, 1), 54.1463),
+ (T(1984, 10, 1), 54.1914),
+ (T(1984, 11, 1), 54.2452),
+ (T(1984, 12, 1), 54.2958),
+ (T(1985, 1, 1), 54.3427),
+ (T(1985, 2, 1), 54.3911),
+ (T(1985, 3, 1), 54.4320),
+ (T(1985, 4, 1), 54.4898),
+ (T(1985, 5, 1), 54.5456),
+ (T(1985, 6, 1), 54.5977),
+ (T(1985, 7, 1), 54.6355),
+ (T(1985, 8, 1), 54.6532),
+ (T(1985, 9, 1), 54.6776),
+ (T(1985, 10, 1), 54.7174),
+ (T(1985, 11, 1), 54.7741),
+ (T(1985, 12, 1), 54.8253),
+ (T(1986, 1, 1), 54.8712),
+ (T(1986, 2, 1), 54.9161),
+ (T(1986, 3, 1), 54.9580),
+ (T(1986, 4, 1), 54.9997),
+ (T(1986, 5, 1), 55.0476),
+ (T(1986, 6, 1), 55.0912),
+ (T(1986, 7, 1), 55.1132),
+ (T(1986, 8, 1), 55.1328),
+ (T(1986, 9, 1), 55.1532),
+ (T(1986, 10, 1), 55.1898),
+ (T(1986, 11, 1), 55.2415),
+ (T(1986, 12, 1), 55.2838),
+ (T(1987, 1, 1), 55.3222),
+ (T(1987, 2, 1), 55.3613),
+ (T(1987, 3, 1), 55.4063),
+ (T(1987, 4, 1), 55.4629),
+ (T(1987, 5, 1), 55.5111),
+ (T(1987, 6, 1), 55.5524),
+ (T(1987, 7, 1), 55.5812),
+ (T(1987, 8, 1), 55.6004),
+ (T(1987, 9, 1), 55.6262),
+ (T(1987, 10, 1), 55.6656),
+ (T(1987, 11, 1), 55.7168),
+ (T(1987, 12, 1), 55.7698),
+ (T(1988, 1, 1), 55.8197),
+ (T(1988, 2, 1), 55.8615),
+ (T(1988, 3, 1), 55.9130),
+ (T(1988, 4, 1), 55.9663),
+ (T(1988, 5, 1), 56.0220),
+ (T(1988, 6, 1), 56.0700),
+ (T(1988, 7, 1), 56.0939),
+ (T(1988, 8, 1), 56.1105),
+ (T(1988, 9, 1), 56.1314),
+ (T(1988, 10, 1), 56.1611),
+ (T(1988, 11, 1), 56.2068),
+ (T(1988, 12, 1), 56.2582),
+ (T(1989, 1, 1), 56.3000),
+ (T(1989, 2, 1), 56.3399),
+ (T(1989, 3, 1), 56.3790),
+ (T(1989, 4, 1), 56.4283),
+ (T(1989, 5, 1), 56.4804),
+ (T(1989, 6, 1), 56.5352),
+ (T(1989, 7, 1), 56.5697),
+ (T(1989, 8, 1), 56.5983),
+ (T(1989, 9, 1), 56.6328),
+ (T(1989, 10, 1), 56.6739),
+ (T(1989, 11, 1), 56.7332),
+ (T(1989, 12, 1), 56.7972),
+ (T(1990, 1, 1), 56.8553),
+ (T(1990, 2, 1), 56.9111),
+ (T(1990, 3, 1), 56.9755),
+ (T(1990, 4, 1), 57.0471),
+ (T(1990, 5, 1), 57.1136),
+ (T(1990, 6, 1), 57.1738),
+ (T(1990, 7, 1), 57.2226),
+ (T(1990, 8, 1), 57.2597),
+ (T(1990, 9, 1), 57.3073),
+ (T(1990, 10, 1), 57.3643),
+ (T(1990, 11, 1), 57.4334),
+ (T(1990, 12, 1), 57.5016),
+ (T(1991, 1, 1), 57.5653),
+ (T(1991, 2, 1), 57.6333),
+ (T(1991, 3, 1), 57.6973),
+ (T(1991, 4, 1), 57.7711),
+ (T(1991, 5, 1), 57.8407),
+ (T(1991, 6, 1), 57.9058),
+ (T(1991, 7, 1), 57.9576),
+ (T(1991, 8, 1), 57.9975),
+ (T(1991, 9, 1), 58.0425),
+ (T(1991, 10, 1), 58.1043),
+ (T(1991, 11, 1), 58.1679),
+ (T(1991, 12, 1), 58.2389),
+ (T(1992, 1, 1), 58.3092),
+ (T(1992, 2, 1), 58.3833),
+ (T(1992, 3, 1), 58.4537),
+ (T(1992, 4, 1), 58.5401),
+ (T(1992, 5, 1), 58.6228),
+ (T(1992, 6, 1), 58.6917),
+ (T(1992, 7, 1), 58.7410),
+ (T(1992, 8, 1), 58.7836),
+ (T(1992, 9, 1), 58.8405),
+ (T(1992, 10, 1), 58.8986),
+ (T(1992, 11, 1), 58.9714),
+ (T(1992, 12, 1), 59.0438),
+ (T(1993, 1, 1), 59.1218),
+ (T(1993, 2, 1), 59.2003),
+ (T(1993, 3, 1), 59.2747),
+ (T(1993, 4, 1), 59.3574),
+ (T(1993, 5, 1), 59.4434),
+ (T(1993, 6, 1), 59.5242),
+ (T(1993, 7, 1), 59.5850),
+ (T(1993, 8, 1), 59.6343),
+ (T(1993, 9, 1), 59.6928),
+ (T(1993, 10, 1), 59.7588),
+ (T(1993, 11, 1), 59.8386),
+ (T(1993, 12, 1), 59.9111),
+ (T(1994, 1, 1), 59.9844),
+ (T(1994, 2, 1), 60.0564),
+ (T(1994, 3, 1), 60.1231),
+ (T(1994, 4, 1), 60.2042),
+ (T(1994, 5, 1), 60.2804),
+ (T(1994, 6, 1), 60.3530),
+ (T(1994, 7, 1), 60.4012),
+ (T(1994, 8, 1), 60.4440),
+ (T(1994, 9, 1), 60.4900),
+ (T(1994, 10, 1), 60.5578),
+ (T(1994, 11, 1), 60.6324),
+ (T(1994, 12, 1), 60.7059),
+ (T(1995, 1, 1), 60.7853),
+ (T(1995, 2, 1), 60.8663),
+ (T(1995, 3, 1), 60.9387),
+ (T(1995, 4, 1), 61.0277),
+ (T(1995, 5, 1), 61.1103),
+ (T(1995, 6, 1), 61.1870),
+ (T(1995, 7, 1), 61.2454),
+ (T(1995, 8, 1), 61.2881),
+ (T(1995, 9, 1), 61.3378),
+ (T(1995, 10, 1), 61.4036),
+ (T(1995, 11, 1), 61.4760),
+ (T(1995, 12, 1), 61.5525),
+ (T(1996, 1, 1), 61.6287),
+ (T(1996, 2, 1), 61.6846),
+ (T(1996, 3, 1), 61.7433),
+ (T(1996, 4, 1), 61.8132),
+ (T(1996, 5, 1), 61.8823),
+ (T(1996, 6, 1), 61.9497),
+ (T(1996, 7, 1), 61.9969),
+ (T(1996, 8, 1), 62.0343),
+ (T(1996, 9, 1), 62.0714),
+ (T(1996, 10, 1), 62.1202),
+ (T(1996, 11, 1), 62.1809),
+ (T(1996, 12, 1), 62.2382),
+ (T(1997, 1, 1), 62.2950),
+ (T(1997, 2, 1), 62.3506),
+ (T(1997, 3, 1), 62.3995),
+ (T(1997, 4, 1), 62.4754),
+ (T(1997, 5, 1), 62.5463),
+ (T(1997, 6, 1), 62.6136),
+ (T(1997, 7, 1), 62.6571),
+ (T(1997, 8, 1), 62.6942),
+ (T(1997, 9, 1), 62.7383),
+ (T(1997, 10, 1), 62.7926),
+ (T(1997, 11, 1), 62.8567),
+ (T(1997, 12, 1), 62.9146),
+ (T(1998, 1, 1), 62.9659),
+ (T(1998, 2, 1), 63.0217),
+ (T(1998, 3, 1), 63.0807),
+ (T(1998, 4, 1), 63.1462),
+ (T(1998, 5, 1), 63.2053),
+ (T(1998, 6, 1), 63.2599),
+ (T(1998, 7, 1), 63.2844),
+ (T(1998, 8, 1), 63.2961),
+ (T(1998, 9, 1), 63.3126),
+ (T(1998, 10, 1), 63.3422),
+ (T(1998, 11, 1), 63.3871),
+ (T(1998, 12, 1), 63.4339),
+ (T(1999, 1, 1), 63.4673),
+ (T(1999, 2, 1), 63.4979),
+ (T(1999, 3, 1), 63.5319),
+ (T(1999, 4, 1), 63.5679),
+ (T(1999, 5, 1), 63.6104),
+ (T(1999, 6, 1), 63.6444),
+ (T(1999, 7, 1), 63.6642),
+ (T(1999, 8, 1), 63.6739),
+ (T(1999, 9, 1), 63.6926),
+ (T(1999, 10, 1), 63.7147),
+ (T(1999, 11, 1), 63.7518),
+ (T(1999, 12, 1), 63.7927),
+ (T(2000, 1, 1), 63.8285),
+ (T(2000, 2, 1), 63.8557),
+ (T(2000, 3, 1), 63.8804),
+ (T(2000, 4, 1), 63.9075),
+ (T(2000, 5, 1), 63.9393),
+ (T(2000, 6, 1), 63.9691),
+ (T(2000, 7, 1), 63.9799),
+ (T(2000, 8, 1), 63.9833),
+ (T(2000, 9, 1), 63.9938),
+ (T(2000, 10, 1), 64.0093),
+ (T(2000, 11, 1), 64.0400),
+ (T(2000, 12, 1), 64.0670),
+ (T(2001, 1, 1), 64.0908),
+ (T(2001, 2, 1), 64.1068),
+ (T(2001, 3, 1), 64.1282),
+ (T(2001, 4, 1), 64.1584),
+ (T(2001, 5, 1), 64.1833),
+ (T(2001, 6, 1), 64.2094),
+ (T(2001, 7, 1), 64.2117),
+ (T(2001, 8, 1), 64.2073),
+ (T(2001, 9, 1), 64.2116),
+ (T(2001, 10, 1), 64.2223),
+ (T(2001, 11, 1), 64.2500),
+ (T(2001, 12, 1), 64.2761),
+ (T(2002, 1, 1), 64.2998),
+ (T(2002, 2, 1), 64.3192),
+ (T(2002, 3, 1), 64.3450),
+ (T(2002, 4, 1), 64.3735),
+ (T(2002, 5, 1), 64.3943),
+ (T(2002, 6, 1), 64.4151),
+ (T(2002, 7, 1), 64.4132),
+ (T(2002, 8, 1), 64.4118),
+ (T(2002, 9, 1), 64.4097),
+ (T(2002, 10, 1), 64.4168),
+ (T(2002, 11, 1), 64.4329),
+ (T(2002, 12, 1), 64.4511),
+ (T(2003, 1, 1), 64.4734),
+ (T(2003, 2, 1), 64.4893),
+ (T(2003, 3, 1), 64.5053),
+ (T(2003, 4, 1), 64.5269),
+ (T(2003, 5, 1), 64.5471),
+ (T(2003, 6, 1), 64.5597),
+ (T(2003, 7, 1), 64.5512),
+ (T(2003, 8, 1), 64.5371),
+ (T(2003, 9, 1), 64.5359),
+ (T(2003, 10, 1), 64.5415),
+ (T(2003, 11, 1), 64.5544),
+ (T(2003, 12, 1), 64.5654),
+ (T(2004, 1, 1), 64.5736),
+ (T(2004, 2, 1), 64.5891),
+ (T(2004, 3, 1), 64.6015),
+ (T(2004, 4, 1), 64.6176),
+ (T(2004, 5, 1), 64.6374),
+ (T(2004, 6, 1), 64.6549),
+ (T(2004, 7, 1), 64.6530),
+ (T(2004, 8, 1), 64.6379),
+ (T(2004, 9, 1), 64.6372),
+ (T(2004, 10, 1), 64.6400),
+ (T(2004, 11, 1), 64.6543),
+ (T(2004, 12, 1), 64.6723),
+ (T(2005, 1, 1), 64.6876),
+ (T(2005, 2, 1), 64.7052),
+ (T(2005, 3, 1), 64.7313),
+ (T(2005, 4, 1), 64.7575),
+ (T(2005, 5, 1), 64.7811),
+ (T(2005, 6, 1), 64.8001),
+ (T(2005, 7, 1), 64.7995),
+ (T(2005, 8, 1), 64.7876),
+ (T(2005, 9, 1), 64.7831),
+ (T(2005, 10, 1), 64.7921),
+ (T(2005, 11, 1), 64.8096),
+ (T(2005, 12, 1), 64.8311),
+ (T(2006, 1, 1), 64.8452),
+ (T(2006, 2, 1), 64.8597),
+ (T(2006, 3, 1), 64.8850),
+ (T(2006, 4, 1), 64.9175),
+ (T(2006, 5, 1), 64.9480),
+ (T(2006, 6, 1), 64.9794),
+ (T(2006, 7, 1), 64.9895),
+ (T(2006, 8, 1), 65.0028),
+ (T(2006, 9, 1), 65.0138),
+ (T(2006, 10, 1), 65.0371),
+ (T(2006, 11, 1), 65.0773),
+ (T(2006, 12, 1), 65.1122),
+ (T(2007, 1, 1), 65.1464),
+ (T(2007, 2, 1), 65.1833),
+ (T(2007, 3, 1), 65.2145),
+ (T(2007, 4, 1), 65.2494),
+ (T(2007, 5, 1), 65.2921),
+ (T(2007, 6, 1), 65.3279),
+ (T(2007, 7, 1), 65.3413),
+ (T(2007, 8, 1), 65.3452),
+ (T(2007, 9, 1), 65.3496),
+ (T(2007, 10, 1), 65.3711),
+ (T(2007, 11, 1), 65.3972),
+ (T(2007, 12, 1), 65.4296),
+ (T(2008, 1, 1), 65.4574),
+ (T(2008, 2, 1), 65.4868),
+ (T(2008, 3, 1), 65.5152),
+ (T(2008, 4, 1), 65.5450),
+ (T(2008, 5, 1), 65.5781),
+ (T(2008, 6, 1), 65.6127),
+ (T(2008, 7, 1), 65.6288),
+ (T(2008, 8, 1), 65.6370),
+ (T(2008, 9, 1), 65.6493),
+ (T(2008, 10, 1), 65.6760),
+ (T(2008, 11, 1), 65.7097),
+ (T(2008, 12, 1), 65.7461),
+ (T(2009, 1, 1), 65.7768),
+ (T(2009, 2, 1), 65.8025),
+ (T(2009, 3, 1), 65.8237),
+ (T(2009, 4, 1), 65.8595),
+ (T(2009, 5, 1), 65.8973),
+ (T(2009, 6, 1), 65.9323),
+ (T(2009, 7, 1), 65.9509),
+ (T(2009, 8, 1), 65.9534),
+ (T(2009, 9, 1), 65.9628),
+ (T(2009, 10, 1), 65.9839),
+ (T(2009, 11, 1), 66.0147),
+ (T(2009, 12, 1), 66.0421),
+ (T(2010, 1, 1), 66.0699),
+ (T(2010, 2, 1), 66.0961),
+ (T(2010, 3, 1), 66.1310),
+ (T(2010, 4, 1), 66.1683),
+ (T(2010, 5, 1), 66.2072),
+ (T(2010, 6, 1), 66.2356),
+ (T(2010, 7, 1), 66.2409),
+ (T(2010, 8, 1), 66.2335),
+ (T(2010, 9, 1), 66.2349),
+ (T(2010, 10, 1), 66.2441),
+ (T(2010, 11, 1), 66.2751),
+ (T(2010, 12, 1), 66.3054),
+ (T(2011, 1, 1), 66.3246),
+ (T(2011, 2, 1), 66.3406),
+ (T(2011, 3, 1), 66.3624),
+ (T(2011, 4, 1), 66.3957),
+ (T(2011, 5, 1), 66.4289),
+ (T(2011, 6, 1), 66.4619),
+ (T(2011, 7, 1), 66.4749),
+ (T(2011, 8, 1), 66.4751),
+ (T(2011, 9, 1), 66.4829),
+ (T(2011, 10, 1), 66.5056),
+ (T(2011, 11, 1), 66.5383),
+ (T(2011, 12, 1), 66.5706),
+ (T(2012, 1, 1), 66.6030),
+ (T(2012, 2, 1), 66.6340),
+ (T(2012, 3, 1), 66.6569),
+ (T(2012, 4, 1), 66.6925),
+ (T(2012, 5, 1), 66.7289),
+ (T(2012, 6, 1), 66.7579),
+ (T(2012, 7, 1), 66.7708),
+ (T(2012, 8, 1), 66.7740),
+ (T(2012, 9, 1), 66.7846),
+ (T(2012, 10, 1), 66.8103),
+ (T(2012, 11, 1), 66.8401),
+ (T(2012, 12, 1), 66.8779),
+ (T(2013, 1, 1), 66.9069),
+ (T(2013, 2, 1), 66.9443),
+ (T(2013, 3, 1), 66.9763),
+ (T(2013, 4, 1), 67.0258),
+ (T(2013, 5, 1), 67.0716),
+ (T(2013, 6, 1), 67.1100),
+ (T(2013, 7, 1), 67.1266),
+ (T(2013, 8, 1), 67.1331),
+ (T(2013, 9, 1), 67.1458),
+ (T(2013, 10, 1), 67.1717),
+ (T(2013, 11, 1), 67.2091),
+ (T(2013, 12, 1), 67.2460),
+ (T(2014, 1, 1), 67.2810),
+ (T(2014, 2, 1), 67.3136),
+ (T(2014, 3, 1), 67.3457),
+ (T(2014, 4, 1), 67.3890),
+ (T(2014, 5, 1), 67.4318),
+ (T(2014, 6, 1), 67.4666),
+ (T(2014, 7, 1), 67.4859),
+ (T(2014, 8, 1), 67.4989),
+ (T(2014, 9, 1), 67.5111),
+ (T(2014, 10, 1), 67.5353),
+ (T(2014, 11, 1), 67.5711),
+ (T(2014, 12, 1), 67.6070),
+ (T(2015, 1, 1), 67.6439),
+ (T(2015, 2, 1), 67.6765),
+ (T(2015, 3, 1), 67.7117),
+ (T(2015, 4, 1), 67.7591),
+ (T(2015, 5, 1), 67.8012),
+ (T(2015, 6, 1), 67.8402),
+ (T(2015, 7, 1), 67.8606),
+ (T(2015, 8, 1), 67.8822),
+ (T(2015, 9, 1), 67.9120),
+ (T(2015, 10, 1), 67.9547),
+ (T(2015, 11, 1), 68.0055),
+ (T(2015, 12, 1), 68.0514),
+ (T(2016, 1, 1), 68.1024),
+ (T(2016, 2, 1), 68.1577),
+ (T(2016, 3, 1), 68.2044),
+ (T(2016, 4, 1), 68.2665),
+ (T(2016, 5, 1), 68.3188),
+ (T(2016, 6, 1), 68.3704),
+ (T(2016, 7, 1), 68.3964),
+ (T(2016, 8, 1), 68.4095),
+ (T(2016, 9, 1), 68.4305),
+ (T(2016, 10, 1), 68.4630),
+ (T(2016, 11, 1), 68.5078),
+ (T(2016, 12, 1), 68.5537),
+ (T(2017, 1, 1), 68.5927),
+ (T(2017, 2, 1), 68.6298),
+ (T(2017, 3, 1), 68.6671),
+ (T(2017, 4, 1), 68.7135),
+ (T(2017, 5, 1), 68.7623),
+ (T(2017, 6, 1), 68.8033),
+ (T(2017, 7, 1), 68.8245),
+ (T(2017, 8, 1), 68.8373),
+ (T(2017, 9, 1), 68.8477),
+ (T(2017, 10, 1), 68.8689),
+ (T(2017, 11, 1), 68.9006),
+ (T(2017, 12, 1), 68.9355),
+ (T(2018, 1, 1), 68.9677),
+ (T(2018, 3, 1), 69.14),
+ (T(2018, 6, 1), 69.3),
+ (T(2018, 9, 1), 69.3),
+ (T(2019, 1, 1), 69.5),
+ (T(2019, 3, 1), 69.6),
+ (T(2019, 6, 1), 69.7),
+ (T(2019, 9, 1), 69.8),
+ (T(2020, 1, 1), 69.9),
+ (T(2020, 3, 1), 70.0),
+ (T(2020, 6, 1), 70.0),
+ (T(2020, 9, 1), 70.0),
+ (T(2021, 1, 1), 70.0),
+ (T(2021, 3, 1), 70.0),
+ (T(2021, 6, 1), 70.0),
+ (T(2021, 9, 1), 70.0),
+ (T(2022, 1, 1), 70.0),
+ (T(2022, 3, 1), 70.0),
+ (T(2022, 6, 1), 71.0),
+ (T(2022, 9, 1), 71.0),
+ (T(2023, 1, 1), 71.0),
+ (T(2023, 3, 1), 71.0),
+ (T(2023, 6, 1), 71.0),
+ (T(2023, 9, 1), 71.0),
+ (T(2024, 1, 1), 71.0),
+ (T(2024, 3, 1), 71.0),
+ (T(2024, 6, 1), 71.0),
+ (T(2024, 9, 1), 71.0),
+ (T(2025, 1, 1), 71.0),
+ (T(2025, 3, 1), 72.0),
+ (T(2025, 6, 1), 72.0),
+ (T(2025, 9, 1), 72.0),
+ (T(2026, 1, 1), 72.0),
+ ],
+ dtype=[("time", "M8[D]"), ("julian_days", "f8")],
+)
+# seconds in a julian day
+utc_to_jd_tt.corrections["julian_days"] /= 60 * 60 * 24
+
+
+def compute_ecliptic_longitude(ob, minutes):
+ """Compute an objects ecliptic longitude..
+
+ Parameters
+ ----------
+ minutes : np.array[M8[m]]
+ The minutes to compute the longitude for.
+
+ Returns
+ -------
+ rad : np.ndarray[float64]
+ The ecliptic longitude of the object (in radians).
+
+ Notes
+ -----
+ The ``novas`` ephemeris must be opened before this can be called.
+ """
+ longitude_degrees = np.array(
+ [
+ novas.equ2ecl(
+ jd_tt,
+ # right ascension and declination
+ *novas.app_planet(jd_tt, ob)[:2],
+ # true equator and equinox of date
+ coord_sys=1,
+ )[0]
+ for jd_tt in utc_to_jd_tt(minutes)
+ ]
+ )
+ return np.deg2rad(longitude_degrees)
+
+
+def lunar_ecliptic_longitude_block(root, minutes):
+ """Calculate and save one block of moon phase data.
+
+ Parameters
+ ----------
+ root : pathlib.Path
+ The directory to save the data to.
+ minutes : np.array[M8[m]]
+ The minutes to compute the moon phase for.
+ """
+ ob = novas.make_object(0, 11, "Moon", None)
+ el = compute_ecliptic_longitude(ob, minutes)
+ path = str(root / f"{minutes[0]}_{minutes[-1]}")
+ el.tofile(str(path))
+
+
+def print_dates(dates, *, weekday):
+ """Print an array of dates.
+
+ Parameters
+ ----------
+ dates : np.ndarray[M8]
+ The dates to print.
+ weekday : bool
+ Print the day of the week in a second column?
+ """
+ dates = dates.astype("M8[D]")
+
+ if weekday:
+ weekdays = pd.to_datetime(dates).weekday_name
+
+ for d, weekday in zip(dates, weekdays):
+ print(d, weekday)
+ else:
+ for d in dates:
+ print(d)
+
+
+@click.group()
+def main():
+ """Utilities for computing the Gregorian dates of lunisolar calendar
+ events.
+ """
+
+
+@main.command("lunar-ecliptic-longitude")
+@click.option(
+ "--root-dir",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to save the data to.",
+ default="lunar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "--verbose/--quiet",
+ default=False,
+)
+@click.option(
+ "--start",
+ help="The start date to compute.",
+ default="1980-01-01",
+)
+@click.option(
+ "--stop",
+ help="The stop date to compute.",
+ default="2050-01-01",
+)
+def lunar_ecliptic_longitude(root_dir, verbose, start, stop):
+ """Simulate the ecliptic longitude of the moon."""
+ root_dir = pathlib.Path(root_dir)
+ root_dir.mkdir(parents=True, exist_ok=True)
+
+ with ephemeris():
+ minutes = np.arange(start, stop, dtype="M8[m]")
+ for minutes in toolz.partition_all(60 * 24 * 365, minutes):
+ if verbose:
+ print(f"start={minutes[0]}; stop={minutes[-1]}")
+
+ lunar_ecliptic_longitude_block(root_dir, np.array(minutes))
+
+
+def calculate_new_moon(solar_ecliptic_longitude, lunar_ecliptic_longitude, minutes):
+ """Calculate when the new moon will occur.
+
+ Parameters
+ ----------
+ solar_ecliptic_longitude : np.ndarray[f8]
+ The ecliptic longitude of the sun.
+ lunar_ecliptic_longitude : np.ndarray[f8]
+ The ecliptic longitude of the moon.
+ minutes : np.ndarray[M8[m]]
+ The minute labels for the longitude data.
+
+ Returns
+ -------
+ new_moons : np.ndarray[M8[m]]
+ The minutes when a new moon occurs.
+ """
+ diff = np.abs(solar_ecliptic_longitude - lunar_ecliptic_longitude)
+ new_moon_where = local_cmp(op.lt, diff)
+ # clean up some local mins where the value isn't close to 0
+ new_moon_where = new_moon_where[diff[new_moon_where] < 0.1]
+ return minutes[new_moon_where]
+
+
+def load_new_moons(
+ solar_ecliptic_longitude, lunar_ecliptic_longitude, *, return_solar_data=False
+):
+ """Load the new moon minutes from the precomputed data.
+
+ Parameters
+ ----------
+ solar_ecliptic_longitude : path-like
+ The root dir to read solar ecliptic longitude data from.
+ lunar_ecliptic_longitude : path-like
+ The root dir to read lunar ecliptic longitude data from.
+ return_solar_data : bool, optional
+ Also return the solar data.
+
+ Returns
+ -------
+ new_moons : np.ndarray[M8[m]]
+ The minutes of the new moons.
+ """
+ solar_elon, solar_minutes = load_precomputed_data(solar_ecliptic_longitude)
+ lunar_elon, lunar_minutes = load_precomputed_data(lunar_ecliptic_longitude)
+
+ if not np.all(solar_minutes == lunar_minutes):
+ raise ValueError(
+ "mismatched minutes for solar and lunar ecliptic longitude",
+ )
+
+ new_moons = calculate_new_moon(
+ solar_elon,
+ lunar_elon,
+ # the minutes are equal so it doesn't matter which we use
+ solar_minutes,
+ )
+ if return_solar_data:
+ return new_moons, solar_elon, solar_minutes
+
+ return new_moons
+
+
+@main.command("new-moon")
+@click.option(
+ "--solar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read solar ecliptic longitude data from.",
+ default="solar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "--lunar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read lunar ecliptic longitude data from.",
+ default="lunar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "-o",
+ "--output",
+ type=click.File("w"),
+ default=None,
+ help="The output to write the array of the minutes for each new moon.",
+)
+def new_moon(solar_ecliptic_longitude, lunar_ecliptic_longitude, output):
+ """Calculate the minute of each new moon."""
+ new_moon_minutes = load_new_moons(
+ solar_ecliptic_longitude,
+ lunar_ecliptic_longitude,
+ )
+ if output is None:
+ print(new_moon_minutes)
+ else:
+ new_moon_minutes.tofile(output)
+
+
+def solar_ecliptic_longitude_block(root, minutes):
+ """Compute and save the sun's ecliptic longitude.
+
+ Parameters
+ ----------
+ minutes : np.array[M8[m]]
+ The minutes to compute the sun's position.
+ """
+ ob = novas.make_object(0, 10, "Sun", None)
+ el = compute_ecliptic_longitude(ob, minutes)
+ path = str(root / f"{minutes[0]}_{minutes[-1]}")
+ el.tofile(str(path))
+
+
+@main.command("solar-ecliptic-longitude")
+@click.option(
+ "--root-dir",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to save the data to.",
+ default="solar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "--verbose/--quiet",
+ default=False,
+)
+@click.option(
+ "--start",
+ help="The start date to compute.",
+ default="1980-01-01",
+)
+@click.option(
+ "--stop",
+ help="The stop date to compute.",
+ default="2050-01-01",
+)
+def solar_solar_ecliptic_longitude(root_dir, verbose, start, stop):
+ """Simulate the ecliptic longitude of the sun."""
+ root_dir = pathlib.Path(root_dir)
+ root_dir.mkdir(parents=True, exist_ok=True)
+
+ with ephemeris():
+ minutes = np.arange(start, stop, dtype="M8[m]")
+ for minutes in toolz.partition_all(60 * 24 * 365, minutes):
+ if verbose:
+ print(f"start={minutes[0]}; stop={minutes[-1]}")
+
+ solar_ecliptic_longitude_block(root_dir, np.array(minutes))
+
+
+def minutes_at_phase(longitude, minutes, phase):
+ """Find the minutes where the longitude is nearest to ``phase``.
+
+ Parameters
+ ----------
+ longitude : np.ndarray[float64]
+ The longitude (in radians) of the sun.
+ minutes : np.ndarray[M8[m]]
+ The minute labels for the longitude values.
+ phase : float
+ The target longitude to find the minutes for.
+
+ Returns
+ -------
+ minutes_at_phase : np.ndarray[M8[m]]
+ The minutes where ``longitude`` is closest to ``phase``.
+ """
+ return minutes[local_cmp(op.lt, np.abs(longitude - phase))]
+
+
+def calculate_new_year(solar_longitude, minutes_for_longitude, new_moons):
+ """Calculate the Chinese new year new moon times.
+
+ Parameters
+ ----------
+ solar_ecliptic_longitude_dir : path-like
+ The root dir to read solar ecliptic longitude data from.
+ new_moons : np.ndarray[M8[m]]
+ The sorted minutes when the new moon occurs.
+
+ Returns
+ -------
+ new_years : np.ndarray[M8[m]]
+ The minutes when the first new moon of each year occurs.
+ """
+ months, eleventh_month_ix = chinese_month_start(
+ new_moons,
+ solar_longitude,
+ minutes_for_longitude,
+ return_11th_month=True,
+ )
+ new_year_ix = eleventh_month_ix + 2
+ return months[new_year_ix[new_year_ix < len(months)]]
+
+
+def utc_to_chinese_date(arr):
+ """Convert UTC minutes to a chinese date.
+
+ Parameters
+ ----------
+ arr : np.array[M8[m]]
+ The datetimes to convert.
+
+ Returns
+ -------
+ dates : np.array[M8[ns]]
+ An array of datetime64[ns] at midnight corresponding the date in China
+ of the input.
+ """
+ ts = pd.to_datetime(arr).tz_localize(UTC).tz_convert("Asia/Shanghai")
+ out = ts.normalize().tz_localize(None)
+ if isinstance(out, pd.Timestamp):
+ return out.asm8
+ return out.values
+
+
+@main.command("chinese-new-year")
+@click.option(
+ "--lunar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read lunar ecliptic longitude data from.",
+ default="lunar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "--solar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read solar ecliptic longitude data from.",
+ default="solar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "-o",
+ "--output",
+ type=click.File("w"),
+ default=None,
+ help="The output to write the dates of the Chinese New Year.",
+)
+@click.option(
+ "--weekday/--no-weekday",
+ default=False,
+ help="If printing to stdout, include the weekday?",
+)
+def chinese_new_year(
+ lunar_ecliptic_longitude, solar_ecliptic_longitude, output, weekday
+):
+ """Calculate the Gregorian date of Chinese New Year."""
+ new_moons, solar_elon, solar_minutes = load_new_moons(
+ solar_ecliptic_longitude,
+ lunar_ecliptic_longitude,
+ return_solar_data=True,
+ )
+
+ chinese_new_year = calculate_new_year(
+ solar_elon,
+ solar_minutes,
+ new_moons,
+ )
+
+ chinese_new_year = utc_to_chinese_date(chinese_new_year)
+ if output is None:
+ print_dates(chinese_new_year, weekday=weekday)
+ else:
+ chinese_new_year.tofile(output)
+
+
+@main.command("qingming-festival")
+@click.option(
+ "--solar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read solar ecliptic longitude data from.",
+ default="solar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "-o",
+ "--output",
+ type=click.File("w"),
+ default=None,
+ help="The output to write the dates of the Qingming Festival.",
+)
+@click.option(
+ "--weekday/--no-weekday",
+ default=False,
+ help="If printing to stdout, include the weekday?",
+)
+def qingming_festival(solar_ecliptic_longitude, output, weekday):
+ """Calculate the Gregorian date of Qingming Festival."""
+ longitude, minutes = load_precomputed_data(solar_ecliptic_longitude)
+
+ # The Qingming (清明) festival is celebrated on the calendar day of the
+ # first minor solar period (节气). A solar period is defined as the sun
+ # moving 1/24th of the ecliptic, with 0 being the vernal equinox (春分),
+ # and 1/2 of a rotation being the autumnal equinox (秋分).
+ qingming_minute = minutes_at_phase(longitude, minutes, np.pi / 12)
+
+ qingming_festival_date = utc_to_chinese_date(qingming_minute)
+ if output is None:
+ print_dates(qingming_festival_date, weekday=weekday)
+ else:
+ qingming_festival_date.tofile(output)
+
+
+def chinese_month_start(
+ new_moons, solar_longitude, minutes, *, return_11th_month=False
+):
+ """Get the start date of each lunar month (excluding leap months).
+
+ Parameters
+ ----------
+ new_moons : np.ndarray[M8[m]]
+ The minute of each new moon.
+ solar_longitude : np.ndarray[f8]
+ An array of the ecliptical longitude of the sun.
+ minutes : np.ndarray[M8[m]]
+ The labels for ``solar_longitude``.
+ return_11th_month : bool, optional
+ Return the index of the 11th month.
+
+ Returns
+ -------
+ month_starts : np.ndarray[M8[m]]
+ The minute of the new moon that starts each real month.
+ """
+ winter_solstice = minutes_at_phase(
+ solar_longitude,
+ minutes,
+ 3 * np.pi / 2,
+ )
+ sui_start_index = (
+ utc_to_chinese_date(new_moons)
+ > utc_to_chinese_date(winter_solstice).reshape(-1, 1)
+ ).argmax(axis=1) - 1
+
+ get_next_sui_ix = iter(sui_start_index).__next__
+
+ next_sui_ix = get_next_sui_ix()
+ next_sui = new_moons[next_sui_ix]
+ prev_sui_ix = next_sui_ix - 13
+
+ seen_skipped_month = False
+ month_starts = []
+
+ zhongqi = minutes_at_phase(
+ np.fmod(solar_longitude, np.pi / 6),
+ minutes,
+ 0,
+ )[1:]
+ contains_zhongqi_ix = (
+ utc_to_chinese_date(zhongqi).reshape(-1, 1) < utc_to_chinese_date(new_moons)
+ ).argmax(axis=1) - 1
+ months_with_zhongqi = np.unique(new_moons[contains_zhongqi_ix])
+ possible_skipped_months = np.setdiff1d(new_moons, months_with_zhongqi)
+
+ for new_moon in new_moons:
+ if new_moon == next_sui:
+ seen_skipped_month = False
+
+ possible_skipped_month = new_moon in possible_skipped_months
+ skip = (
+ possible_skipped_month
+ and not seen_skipped_month
+ # check the number of new moons between the two sui to guard
+ # against fake leap months (e.g. 8th month of 2033)
+ and next_sui_ix - prev_sui_ix != 12
+ )
+
+ if new_moon == next_sui:
+ prev_sui_ix = next_sui_ix
+ try:
+ next_sui_ix = get_next_sui_ix()
+ next_sui = new_moons[next_sui_ix]
+ except StopIteration:
+ pass
+
+ if skip:
+ # we only skip the first month without a zhongqi in a given year
+ seen_skipped_month = True
+ else:
+ month_starts.append(new_moon)
+
+ month_starts = np.array(month_starts)
+ if return_11th_month:
+ return (month_starts, np.searchsorted(month_starts, new_moons[sui_start_index]))
+ return month_starts
+
+
+def nth_day_of_nth_chinese_month(
+ lunar_ecliptic_longitude, solar_ecliptic_longitude, month, day
+):
+ """Helper for computing the nth day of the nth lunar month from the cached
+ data.
+
+ Parameters
+ ----------
+ lunar_ecliptic_longitude : path-like
+ The root dir to read lunar ecliptic longitude data from.
+ solar_ecliptic_longitude : path-like
+ The root dir to read solar ecliptic longitude data from.
+ month : int
+ The one indexed month number.
+ day : int
+ The one indexed day number.
+
+ Returns
+ -------
+ dates : np.ndarray[M8[D]]
+ The date of the holiday each year.
+ """
+ new_moons, solar_elon, solar_minutes = load_new_moons(
+ solar_ecliptic_longitude,
+ lunar_ecliptic_longitude,
+ return_solar_data=True,
+ )
+
+ months = chinese_month_start(new_moons, solar_elon, solar_minutes)
+ chinese_new_year = calculate_new_year(
+ solar_elon,
+ solar_minutes,
+ new_moons,
+ )
+ new_year_month_ix = np.searchsorted(months, chinese_new_year)
+
+ # subtract one from month because it is 1-indexed
+ month_start = utc_to_chinese_date(months[new_year_month_ix + (month - 1)])
+ # subtract one from day because it is 1-indexed.
+ return month_start + np.timedelta64(day - 1, "D")
+
+
+@main.command("china-buddhas-birthday")
+@click.option(
+ "--lunar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read lunar ecliptic longitude data from.",
+ default="lunar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "--solar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read solar ecliptic longitude data from.",
+ default="solar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "-o",
+ "--output",
+ type=click.File("w"),
+ default=None,
+ help="The output to write the dates of Buddha's Birthday.",
+)
+@click.option(
+ "--weekday/--no-weekday",
+ default=False,
+ help="If printing to stdout, include the weekday?",
+)
+def china_buddhas_birthday(
+ lunar_ecliptic_longitude, solar_ecliptic_longitude, output, weekday
+):
+ """Calculate the Gregorian date of China's observance of Buddha's Birthday."""
+ # Buddhas birthday is the 8th day (one indexed) of the 4th chinese lunar
+ # month (not counting leap months).
+ buddhas_birthday = nth_day_of_nth_chinese_month(
+ lunar_ecliptic_longitude,
+ solar_ecliptic_longitude,
+ month=4,
+ day=8,
+ )
+ if output is None:
+ print_dates(buddhas_birthday, weekday=weekday)
+ else:
+ buddhas_birthday.tofile(output)
+
+
+@main.command("dragon-boat-festival")
+@click.option(
+ "--lunar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read lunar ecliptic longitude data from.",
+ default="lunar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "--solar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read solar ecliptic longitude data from.",
+ default="solar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "-o",
+ "--output",
+ type=click.File("w"),
+ default=None,
+ help="The output to write the dates of the Dragon Boat Festival.",
+)
+@click.option(
+ "--weekday/--no-weekday",
+ default=False,
+ help="If printing to stdout, include the weekday?",
+)
+def dragon_boat_festival(
+ lunar_ecliptic_longitude, solar_ecliptic_longitude, output, weekday
+):
+ """Calculate the Gregorian date of the Dragon Boat Festival."""
+ # The Dragon Boat Festival is the 5th day of the 5th month.
+ # month (not counting leap months).
+ dragon_boat_festival = nth_day_of_nth_chinese_month(
+ lunar_ecliptic_longitude,
+ solar_ecliptic_longitude,
+ month=5,
+ day=5,
+ )
+ if output is None:
+ print_dates(dragon_boat_festival, weekday=weekday)
+ else:
+ dragon_boat_festival.tofile(output)
+
+
+@main.command("mid-autumn-festival")
+@click.option(
+ "--lunar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read lunar ecliptic longitude data from.",
+ default="lunar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "--solar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read solar ecliptic longitude data from.",
+ default="solar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "-o",
+ "--output",
+ type=click.File("w"),
+ default=None,
+ help="The output to write the dates of the Mid Autumn Festival.",
+)
+@click.option(
+ "--weekday/--no-weekday",
+ default=False,
+ help="If printing to stdout, include the weekday?",
+)
+def mid_autumn_festival(
+ lunar_ecliptic_longitude, solar_ecliptic_longitude, output, weekday
+):
+ """Calculate the Gregorian date of the Mid Autumn Festival."""
+ # The Mid Autumn Festival is the 15th day of the 8th month.
+ # month (not counting leap months).
+ mid_autumn_festival = nth_day_of_nth_chinese_month(
+ lunar_ecliptic_longitude,
+ solar_ecliptic_longitude,
+ month=8,
+ day=15,
+ )
+ if output is None:
+ print_dates(mid_autumn_festival, weekday=weekday)
+ else:
+ mid_autumn_festival.tofile(output)
+
+
+@main.command("double-ninth-festival")
+@click.option(
+ "--lunar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read lunar ecliptic longitude data from.",
+ default="lunar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "--solar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read solar ecliptic longitude data from.",
+ default="solar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "-o",
+ "--output",
+ type=click.File("w"),
+ default=None,
+ help="The output to write the dates of the Double Ninth Festival.",
+)
+@click.option(
+ "--weekday/--no-weekday",
+ default=False,
+ help="If printing to stdout, include the weekday?",
+)
+def double_ninth_festival(
+ lunar_ecliptic_longitude, solar_ecliptic_longitude, output, weekday
+):
+ """Calculate the Gregorian date of the Double Ninth Festival."""
+ # The Double Ninth Festival is the 9th day of the 9th month.
+ # month (not counting leap months).
+ double_ninth_festival = nth_day_of_nth_chinese_month(
+ lunar_ecliptic_longitude,
+ solar_ecliptic_longitude,
+ month=9,
+ day=9,
+ )
+ if output is None:
+ print_dates(double_ninth_festival, weekday=weekday)
+ else:
+ double_ninth_festival.tofile(output)
+
+
+def _render_month(year, months, month, *, print_year):
+ import io
+
+ out = io.StringIO()
+
+ # subtract one from month because it is 1-indexed
+ month_start = utc_to_chinese_date(months[month - 1])
+ month_end = utc_to_chinese_date(months[month])
+ days = pd.date_range(month_start, month_end, closed="left")
+
+ is_leap_month = len(days) > 30
+ title = f'Lunar Month {month}{"(+)" if is_leap_month else ""}'
+ if print_year:
+ title += f" {year}"
+ print(f"{title:^20}".rstrip(), file=out)
+ gregorian_months = f"{days[0].month_name()}-{days[-1].month_name()}"
+ print(f"{gregorian_months:^20}".rstrip(), file=out)
+ print("Su Mo Tu We Th Fr Sa", file=out)
+ print(" " * (3 * ((days[0].weekday() + 1) % 7) - 1), end="", file=out)
+
+ for d in days:
+ if d.weekday() == 6:
+ print("", file=out)
+ else:
+ print(" ", end="", file=out)
+
+ print(f"{d.day:>2}", end="", file=out)
+
+ print("", file=out)
+ return out.getvalue()
+
+
+def _concat_lines(strings, width):
+ as_lines = [string.splitlines() for string in strings]
+ max_lines = max(len(lines) for lines in as_lines)
+ for lines in as_lines:
+ missing_lines = max_lines - len(lines)
+ if missing_lines:
+ lines.extend([" " * width] * missing_lines)
+
+ rows = []
+ for row_parts in zip(*as_lines):
+ row_parts = list(row_parts)
+ for n, row_part in enumerate(row_parts):
+ missing_space = width - len(row_part)
+ if missing_space:
+ row_parts[n] = row_part + " " * missing_space
+
+ rows.append(" ".join(row_parts))
+
+ return "\n".join(row.rstrip() for row in rows)
+
+
+@main.command("chinese-cal")
+@click.argument("month", type=int)
+@click.argument("year", type=int, required=False)
+@click.option(
+ "--lunar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read lunar ecliptic longitude data from.",
+ default="lunar-ecliptic-longitude",
+ show_default=True,
+)
+@click.option(
+ "--solar-ecliptic-longitude",
+ type=click.Path(dir_okay=True, file_okay=False),
+ help="The root dir to read solar ecliptic longitude data from.",
+ default="solar-ecliptic-longitude",
+ show_default=True,
+)
+def chinese_cal(month, year, lunar_ecliptic_longitude, solar_ecliptic_longitude):
+ """Print a unix cal like table for a Chinese lunar month. The day numbers
+ are the Gregorian days of their Gregorian month.
+ """
+ if year is None:
+ year = month
+ month = None
+ full_year = True
+ else:
+ full_year = False
+
+ new_moons, solar_elon, solar_minutes = load_new_moons(
+ solar_ecliptic_longitude,
+ lunar_ecliptic_longitude,
+ return_solar_data=True,
+ )
+
+ months = chinese_month_start(new_moons, solar_elon, solar_minutes)
+ chinese_new_year = calculate_new_year(
+ solar_elon,
+ solar_minutes,
+ new_moons,
+ )
+ given_new_year = chinese_new_year[
+ chinese_new_year.astype("M8[Y]") == np.datetime64(year - 1970, "Y")
+ ]
+ if len(given_new_year) == 0:
+ raise ValueError(f"data does not contain {year}")
+
+ new_year_month_ix = np.searchsorted(months, given_new_year[0])
+ year_months = months[new_year_month_ix:]
+
+ if not full_year:
+ print(_render_month(year, year_months, month, print_year=True))
+ else:
+ month_strings = [
+ [
+ _render_month(
+ year,
+ year_months,
+ row * 3 + column + 1,
+ print_year=False,
+ )
+ for column in range(3)
+ ]
+ for row in range(4)
+ ]
+ print(f"{year:^66}\n".rstrip())
+ print("\n\n".join(_concat_lines(cs, 20) for cs in month_strings))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/make_exchange_calendar_test_csv.py b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/make_exchange_calendar_test_csv.py
new file mode 100644
index 0000000000000000000000000000000000000000..e587b63555057a13d3927e6586afeda2ffa3afaf
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/make_exchange_calendar_test_csv.py
@@ -0,0 +1,76 @@
+"""
+This script can be used to generate the CSV files used in the exchange calendar
+tests. The CSVs include a calendar's sessions, open times, close times,
+break_start times and break_end times.
+
+This script can be run from the root of the repository with:
+ $ python etc/make_exchange_calendar_test_csv.py
+where:
+
+ Code for the corresponding calendar, e.g. "XNYS"
+
+ optional, default: "existing" if existing, else "default"
+ First session to include to CSV file. Can take any of:
+ A date, for example "1998-06-15".
+ "existing" to use first session of any exising csv file.
+ "default" to use calendar's default start date.
+
+ optional, default: "default"
+ NB if is provided then MUST also be provided.
+ Last session to include to CSV file. Can take any of:
+ A date, for example "2026-06-15".
+ "existing" to use last session of any exising csv file.
+ "default" to use calendar's default end date.
+"""
+
+import sys
+import pathlib
+
+import pandas as pd
+
+from exchange_calendars import get_calendar
+
+cal_name = sys.argv[1].upper()
+
+filename = cal_name.replace("/", "-").lower() + ".csv"
+path = pathlib.Path(__file__).parents[1].joinpath("tests/resources", filename)
+
+if len(sys.argv) > 2:
+ start_arg = sys.argv[2]
+else:
+ start_arg = "existing" if path.is_file else "default"
+end_arg = sys.argv[3] if len(sys.argv) > 3 else "default"
+
+if start_arg == "existing" or end_arg == "existing":
+ assert path.is_file
+ df = pd.read_csv(
+ path,
+ index_col=0,
+ parse_dates=[0, 1, 2, 3, 4],
+ infer_datetime_format=True,
+ )
+
+if start_arg == "existing":
+ start = df.index[0].tz_localize(None)
+elif start_arg == "default":
+ start = None
+else:
+ start = start_arg
+
+if end_arg == "existing":
+ end = df.index[-1].tz_localize(None)
+elif end_arg == "default":
+ end = None
+else:
+ end = end_arg
+
+cal = get_calendar(cal_name, start=start, end=end)
+
+df = pd.DataFrame(
+ list(zip(cal.opens, cal.closes, cal.break_starts, cal.break_ends)),
+ columns=["open", "close", "break_start", "break_end"],
+ index=cal.closes.index,
+)
+
+print(f"Writing test CSV file to {path}")
+df.to_csv(path, date_format="%Y-%m-%dT%H:%M:%SZ")
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements.txt b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..06bef11e337e18d4277709674f227fcd5f3b7b1a
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements.txt
@@ -0,0 +1,28 @@
+#
+# This file is autogenerated by pip-compile with Python 3.9
+# by the following command:
+#
+# pip-compile --output-file=etc/requirements.txt pyproject.toml
+#
+korean-lunar-calendar==0.3.1
+ # via exchange_calendars (pyproject.toml)
+numpy==1.26.4
+ # via
+ # exchange_calendars (pyproject.toml)
+ # pandas
+pandas==2.2.0
+ # via exchange_calendars (pyproject.toml)
+pyluach==2.2.0
+ # via exchange_calendars (pyproject.toml)
+python-dateutil==2.8.2
+ # via pandas
+pytz==2024.1
+ # via pandas
+six==1.16.0
+ # via python-dateutil
+toolz==0.12.1
+ # via exchange_calendars (pyproject.toml)
+tzdata==2024.1
+ # via
+ # exchange_calendars (pyproject.toml)
+ # pandas
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_dev.txt b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_dev.txt
new file mode 100644
index 0000000000000000000000000000000000000000..60400a6ad413dc455f7d36b03715a8d0ecae5325
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_dev.txt
@@ -0,0 +1,96 @@
+#
+# This file is autogenerated by pip-compile with Python 3.9
+# by the following command:
+#
+# pip-compile --extra=dev --output-file=etc/requirements_dev.txt pyproject.toml
+#
+attrs==23.2.0
+ # via hypothesis
+build==1.0.3
+ # via pip-tools
+click==8.1.7
+ # via pip-tools
+colorama==0.4.6
+ # via
+ # build
+ # click
+ # pytest
+exceptiongroup==1.2.0
+ # via
+ # hypothesis
+ # pytest
+execnet==2.0.2
+ # via pytest-xdist
+flake8==7.0.0
+ # via exchange_calendars (pyproject.toml)
+hypothesis==6.98.6
+ # via exchange_calendars (pyproject.toml)
+importlib-metadata==7.0.1
+ # via build
+iniconfig==2.0.0
+ # via pytest
+korean-lunar-calendar==0.3.1
+ # via exchange_calendars (pyproject.toml)
+mccabe==0.7.0
+ # via flake8
+numpy==1.26.4
+ # via
+ # exchange_calendars (pyproject.toml)
+ # pandas
+packaging==23.2
+ # via
+ # build
+ # pytest
+pandas==2.2.0
+ # via exchange_calendars (pyproject.toml)
+pip-tools==7.3.0
+ # via exchange_calendars (pyproject.toml)
+pluggy==1.4.0
+ # via pytest
+py-cpuinfo==9.0.0
+ # via pytest-benchmark
+pycodestyle==2.11.1
+ # via flake8
+pyflakes==3.2.0
+ # via flake8
+pyluach==2.2.0
+ # via exchange_calendars (pyproject.toml)
+pyproject-hooks==1.0.0
+ # via build
+pytest==8.0.0
+ # via
+ # exchange_calendars (pyproject.toml)
+ # pytest-benchmark
+ # pytest-xdist
+pytest-benchmark==4.0.0
+ # via exchange_calendars (pyproject.toml)
+pytest-xdist==3.5.0
+ # via exchange_calendars (pyproject.toml)
+python-dateutil==2.8.2
+ # via pandas
+pytz==2024.1
+ # via pandas
+six==1.16.0
+ # via python-dateutil
+sortedcontainers==2.4.0
+ # via hypothesis
+tomli==2.0.1
+ # via
+ # build
+ # pip-tools
+ # pyproject-hooks
+ # pytest
+toolz==0.12.1
+ # via exchange_calendars (pyproject.toml)
+tzdata==2024.1
+ # via
+ # exchange_calendars (pyproject.toml)
+ # pandas
+wheel==0.42.0
+ # via pip-tools
+zipp==3.17.0
+ # via importlib-metadata
+
+# The following packages are considered to be unsafe in a requirements file:
+# pip
+# setuptools
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_lunisolar.txt b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_lunisolar.txt
new file mode 100644
index 0000000000000000000000000000000000000000..8ddd93301ab5b4778b78c1fb5cc776ee620e4a43
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_lunisolar.txt
@@ -0,0 +1,3 @@
+click==6.7
+novas==3.1.1.4
+novas-de405==1997.1
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_minpandas.txt b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_minpandas.txt
new file mode 100644
index 0000000000000000000000000000000000000000..178ce290df7daf1711768fba7d61b777b9e7fd92
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_minpandas.txt
@@ -0,0 +1,99 @@
+#
+# This file is autogenerated by pip-compile with Python 3.9
+# by the following command:
+#
+# pip-compile --extra=dev --output-file=etc/requirements_minpandas.txt pyproject.toml
+#
+# To upgrade with pandas==1.5 fixed run:
+#
+# pip-compile --upgrade --upgrade-package pandas==1.5 --extra=dev --output-file=etc/requirements_minpandas.txt pyproject.toml
+
+#
+attrs==23.2.0
+ # via hypothesis
+build==1.0.3
+ # via pip-tools
+click==8.1.7
+ # via pip-tools
+colorama==0.4.6
+ # via
+ # build
+ # click
+ # pytest
+exceptiongroup==1.2.0
+ # via
+ # hypothesis
+ # pytest
+execnet==2.0.2
+ # via pytest-xdist
+flake8==7.0.0
+ # via exchange_calendars (pyproject.toml)
+hypothesis==6.98.6
+ # via exchange_calendars (pyproject.toml)
+importlib-metadata==7.0.1
+ # via build
+iniconfig==2.0.0
+ # via pytest
+korean-lunar-calendar==0.3.1
+ # via exchange_calendars (pyproject.toml)
+mccabe==0.7.0
+ # via flake8
+numpy==1.26.4
+ # via
+ # exchange_calendars (pyproject.toml)
+ # pandas
+packaging==23.2
+ # via
+ # build
+ # pytest
+pandas==1.5.0
+ # via exchange_calendars (pyproject.toml)
+pip-tools==7.3.0
+ # via exchange_calendars (pyproject.toml)
+pluggy==1.4.0
+ # via pytest
+py-cpuinfo==9.0.0
+ # via pytest-benchmark
+pycodestyle==2.11.1
+ # via flake8
+pyflakes==3.2.0
+ # via flake8
+pyluach==2.2.0
+ # via exchange_calendars (pyproject.toml)
+pyproject-hooks==1.0.0
+ # via build
+pytest==8.0.0
+ # via
+ # exchange_calendars (pyproject.toml)
+ # pytest-benchmark
+ # pytest-xdist
+pytest-benchmark==4.0.0
+ # via exchange_calendars (pyproject.toml)
+pytest-xdist==3.5.0
+ # via exchange_calendars (pyproject.toml)
+python-dateutil==2.8.2
+ # via pandas
+pytz==2024.1
+ # via pandas
+six==1.16.0
+ # via python-dateutil
+sortedcontainers==2.4.0
+ # via hypothesis
+tomli==2.0.1
+ # via
+ # build
+ # pip-tools
+ # pyproject-hooks
+ # pytest
+toolz==0.12.1
+ # via exchange_calendars (pyproject.toml)
+tzdata==2024.1
+ # via exchange_calendars (pyproject.toml)
+wheel==0.42.0
+ # via pip-tools
+zipp==3.17.0
+ # via importlib-metadata
+
+# The following packages are considered to be unsafe in a requirements file:
+# pip
+# setuptools
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_update_xkrx_holidays.txt b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_update_xkrx_holidays.txt
new file mode 100644
index 0000000000000000000000000000000000000000..65a42bead9b83ce2f1bd21b9d4d317b1e1f3afc6
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/requirements_update_xkrx_holidays.txt
@@ -0,0 +1,2 @@
+requests
+pandas
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/etc/update_xkrx_holidays.py b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/update_xkrx_holidays.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ea7264bb7f8aabc549d5da5887f323c6fb63e95
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/etc/update_xkrx_holidays.py
@@ -0,0 +1,121 @@
+import os
+import requests
+import pandas as pd
+
+# Precomputed/adhoc KRX holidays can be checked here
+# http://open.krx.co.kr/contents/MKD/01/0110/01100305/MKD01100305.jsp
+# http://global.krx.co.kr/contents/GLB/05/0501/0501110000/GLB0501110000.jsp
+
+download_holidays_as_dict_oldest_year_available = 1975
+
+
+def download_krx_holidays_as_dict(year=None, page_first_call=False):
+ now = pd.Timestamp.now("Asia/Seoul")
+
+ if year is None:
+ year = now.year
+
+ if year < download_holidays_as_dict_oldest_year_available:
+ raise ValueError(
+ "Year cannot be older than %s but %s given"
+ % (download_holidays_as_dict_oldest_year_available, year)
+ )
+
+ def generate_otp():
+ headers = {
+ "Accept": "*/*",
+ "Accept-Encoding": "gzip, deflate",
+ "Host": "global.krx.co.kr",
+ "Referer": "http://global.krx.co.kr/contents/GLB/05/0501/0501110000/GLB0501110000.jsp",
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
+ "X-Requested-With": "XMLHttpRequest",
+ }
+ params = {
+ "bld": "GLB/05/0501/0501110000/glb0501110000_01",
+ "name": "form",
+ "_": str(int(now.timestamp() * 1000)),
+ }
+ response = requests.get(
+ "http://global.krx.co.kr/contents/COM/GenerateOTP.jspx",
+ headers=headers,
+ params=params,
+ )
+ code = response.content
+ return code
+
+ code = generate_otp()
+ headers = {
+ "Accept": "application/json, text/javascript, */*; q=0.01",
+ "Accept-Encoding": "gzip, deflate",
+ "Host": "global.krx.co.kr",
+ "Origin": "http://global.krx.co.kr",
+ "Referer": "http://global.krx.co.kr/contents/GLB/05/0501/0501110000/GLB0501110000.jsp",
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
+ "X-Requested-With": "XMLHttpRequest",
+ }
+ data = {
+ "search_bas_yy": str(year),
+ "gridTp": "KRX",
+ "pagePath": "/contents/GLB/05/0501/0501110000/GLB0501110000.jsp",
+ "code": code,
+ }
+ if page_first_call:
+ data["pageFirstCall"] = "Y"
+ response = requests.post(
+ "http://global.krx.co.kr/contents/GLB/99/GLB99000001.jspx",
+ headers=headers,
+ data=data,
+ )
+ body = response.json()
+ return body
+
+
+def get_precomputed_krx_holidays_online(from_year=None, to_year=None):
+ if from_year is None:
+ from_year = download_holidays_as_dict_oldest_year_available
+ if to_year is None:
+ now = pd.Timestamp.now("Asia/Seoul")
+ to_year = now.year
+ years = range(from_year, to_year + 1)
+ precomputed_holidays = []
+ for i, year in enumerate(years):
+ page_first_call = i == 0
+ result = download_krx_holidays_as_dict(year, page_first_call=page_first_call)
+ for item in result["block1"]:
+ holiday = item["calnd_dd"]
+ precomputed_holidays.append(holiday)
+ precomputed_holidays = pd.to_datetime(precomputed_holidays)
+ return precomputed_holidays
+
+
+def update_dupmed_precomputed_krx_holidays():
+ xkrx_holidays_py = os.path.join(
+ os.path.dirname(__file__), "../exchange_calendars/xkrx_holidays.py"
+ )
+ with open(xkrx_holidays_py, "r") as f:
+ lines = [line for line in f]
+ start_line = "dumped_precomputed_krx_holidays = pd.to_datetime("
+ end_line = ")"
+ start_line_index = 0
+ end_line_index = 0
+ for i, line in enumerate(lines):
+ if line.startswith(start_line):
+ start_line_index = i + 2
+ elif start_line_index > 0 and line.startswith(end_line):
+ end_line_index = i - 2
+ break
+ if start_line_index > 0 and end_line_index > 0:
+ precomputed_holidays = get_precomputed_krx_holidays_online()
+ precomputed_lines = [
+ ' "%s",\n' % pd.Timestamp(holiday).strftime("%Y-%m-%d")
+ for holiday in precomputed_holidays
+ ]
+ replaced_lines = (
+ lines[:start_line_index] + precomputed_lines + lines[end_line_index + 1 :]
+ )
+ with open(xkrx_holidays_py, "w") as f:
+ f.write("".join(replaced_lines))
+
+
+if __name__ == "__main__":
+ update_dupmed_precomputed_krx_holidays()
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/__init__.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9253954b935754bd47fa3ae0948625c05a627ea9
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/__init__.py
@@ -0,0 +1,64 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from .calendar_utils import (
+ clear_calendars,
+ deregister_calendar,
+ get_calendar,
+ get_calendar_names,
+ register_calendar,
+ register_calendar_alias,
+ register_calendar_type,
+ resolve_alias,
+ names_to_aliases,
+ aliases_to_names,
+)
+from .exchange_calendar import ExchangeCalendar
+
+__all__ = [
+ "clear_calendars",
+ "deregister_calendar",
+ "get_calendar",
+ "get_calendar_names",
+ "register_calendar",
+ "register_calendar_alias",
+ "register_calendar_type",
+ "resolve_alias",
+ "names_to_aliases",
+ "aliases_to_names",
+ "ExchangeCalendar",
+]
+
+__version__ = None
+
+from importlib.metadata import version
+
+try:
+ # get version from installed package
+ __version__ = version("exchange_calendars")
+except ImportError:
+ pass
+
+if __version__ is None:
+ try:
+ # if package not installed, get version as set when package built
+ from ._version import version
+ except Exception:
+ # If package not installed and not built, leave __version__ as None
+ pass
+ else:
+ __version__ = version
+
+del version
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/_version.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..2438ee983030095501285554f9a560c69155bead
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/_version.py
@@ -0,0 +1,24 @@
+# file generated by vcs-versioning
+# don't change, don't track in version control
+from __future__ import annotations
+
+__all__ = [
+ "__version__",
+ "__version_tuple__",
+ "version",
+ "version_tuple",
+ "__commit_id__",
+ "commit_id",
+]
+
+version: str
+__version__: str
+__version_tuple__: tuple[int | str, ...]
+version_tuple: tuple[int | str, ...]
+commit_id: str | None
+__commit_id__: str | None
+
+__version__ = version = '0.0.1'
+__version_tuple__ = version_tuple = (0, 0, 1)
+
+__commit_id__ = commit_id = None
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/always_open.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/always_open.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e76718a87a0435d31ab0164803c2716ccc9c0ee
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/always_open.py
@@ -0,0 +1,15 @@
+from datetime import time
+
+from .exchange_calendar import ExchangeCalendar
+from exchange_calendars.calendar_helpers import UTC
+
+
+class AlwaysOpenCalendar(ExchangeCalendar):
+ """A ExchangeCalendar for an exchange that's open every minute of every day."""
+
+ name = "24/7"
+ tz = UTC
+ weekmask = "1111111"
+ open_times = ((None, time(0)),)
+ close_times = ((None, time(0, 0)),)
+ close_offset = 1
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/calendar_helpers.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/calendar_helpers.py
new file mode 100644
index 0000000000000000000000000000000000000000..55809059462f4d3a2af63a5d8fbd15db710de9f8
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/calendar_helpers.py
@@ -0,0 +1,723 @@
+from __future__ import annotations
+
+import contextlib
+import datetime
+import typing
+from typing import Literal
+from zoneinfo import ZoneInfo
+
+import numpy as np
+import pandas as pd
+
+from exchange_calendars import errors
+
+if typing.TYPE_CHECKING:
+ from exchange_calendars import ExchangeCalendar
+
+UTC = ZoneInfo("UTC")
+
+NANOSECONDS_PER_MINUTE = int(6e10)
+
+NP_NAT = pd.NaT.value
+
+# Use Date type where input does not need to represent an actual session
+# and will be parsed by parse_date.
+Date = typing.Union[pd.Timestamp, str, int, float, datetime.datetime]
+
+# Use Session type where input should represent an actual session and will
+# be parsed by parse_session.
+Session = Date
+
+# Use Minute type where input does not need to represent an actual trading
+# minute and will be parsed by parse_timestamp.
+Minute = typing.Union[pd.Timestamp, str, int, float, datetime.datetime]
+
+# Use TradingMinute where input should represent a trading minute and will
+# be parsed by parse_trading_minute.
+TradingMinute = Minute
+
+
+def next_divider_idx(dividers: np.ndarray, minute_val: int) -> int:
+ divider_idx = np.searchsorted(dividers, minute_val, side="right")
+ target = dividers[divider_idx]
+
+ if minute_val == target:
+ # if dt is exactly on the divider, go to the next value
+ return divider_idx + 1
+ else:
+ return divider_idx
+
+
+def previous_divider_idx(dividers: np.ndarray, minute_val: int) -> int:
+ divider_idx = np.searchsorted(dividers, minute_val)
+
+ if divider_idx == 0:
+ raise ValueError("Cannot go earlier in calendar!")
+
+ return divider_idx - 1
+
+
+def compute_minutes(
+ opens_in_ns: np.ndarray,
+ break_starts_in_ns: np.ndarray,
+ break_ends_in_ns: np.ndarray,
+ closes_in_ns: np.ndarray,
+ side: Literal["left", "right", "both", "neither"] = "both",
+) -> np.ndarray:
+ """Return array of trading minutes."""
+ start_ext = 0 if side in ["left", "both"] else NANOSECONDS_PER_MINUTE
+ # NOTE: Add an extra minute to ending boundaries (break_start and close)
+ # so we include the last bar (arange doesn't include its stop).
+ end_ext = NANOSECONDS_PER_MINUTE if side in ["right", "both"] else 0
+
+ pieces = []
+ for open_time, break_start_time, break_end_time, close_time in zip(
+ opens_in_ns, break_starts_in_ns, break_ends_in_ns, closes_in_ns
+ ):
+ if break_start_time != NP_NAT:
+ pieces.append(
+ np.arange(
+ open_time + start_ext,
+ break_start_time + end_ext,
+ NANOSECONDS_PER_MINUTE,
+ )
+ )
+ pieces.append(
+ np.arange(
+ break_end_time + start_ext,
+ close_time + end_ext,
+ NANOSECONDS_PER_MINUTE,
+ )
+ )
+ else:
+ pieces.append(
+ np.arange(
+ open_time + start_ext,
+ close_time + end_ext,
+ NANOSECONDS_PER_MINUTE,
+ )
+ )
+ out = np.concatenate(pieces).view("datetime64[ns]")
+ return out
+
+
+def one_minute_earlier(arr: np.ndarray) -> np.ndarray:
+ """Return an array of nanos one minute behind a given array."""
+ arr = arr.copy()
+ arr[arr != NP_NAT] -= NANOSECONDS_PER_MINUTE
+ return arr
+
+
+def one_minute_later(arr: np.ndarray) -> np.ndarray:
+ """Return an array of nanos one minute ahead of a given array."""
+ arr = arr.copy()
+ arr[arr != NP_NAT] += NANOSECONDS_PER_MINUTE
+ return arr
+
+
+def is_date(ts: pd.Timestamp) -> bool:
+ """Query if a timestamp represents a date (as opposed to a time).
+
+ `ts` considered to represent a date if tz-naive and has time component
+ as 00:00.
+
+ Parameters
+ ----------
+ ts
+ Timestamp to query.
+
+ Returns
+ -------
+ bool
+ Boolean indicating if `ts` represents a date.
+ """
+ return ts.tz is None and ts == ts.normalize()
+
+
+def to_utc(ts: pd.Timestamp) -> pd.Timestamp:
+ """Return a copy of a given timestamp with timezone set to UTC.
+
+ If `ts` is tz-aware will convert `ts` to UTC.
+ If `ts` is tz-naive will localize as UTC.
+
+ Parameters
+ ----------
+ ts
+ Timestamp to return a copy of with timezone set to UTC.
+ """
+ try:
+ return ts.tz_convert(UTC)
+ except TypeError:
+ return ts.tz_localize(UTC)
+
+
+def parse_timestamp(
+ timestamp: Date | Minute,
+ param_name: str = "minute",
+ calendar: ExchangeCalendar | None = None,
+ raise_oob: bool = True,
+ side: Literal["left", "right", "both", "neither"] | None = None,
+ utc: bool = True,
+) -> pd.Timestamp:
+ """Parse input intended to represent either a date or a minute.
+
+ Parameters
+ ----------
+ timestamp
+ Input to be parsed as either a Date or a Minute. Must be valid
+ input to pd.Timestamp.
+
+ param_name
+ Name of a parameter that was to receive a Date or Minute.
+
+ calendar
+ ExchangeCalendar against which to evaluate out-of-bounds
+ timestamps. Only requried if `raise_oob` True of if relying on
+ `calendar` for `side`.
+
+ raise_oob : default: True
+ True to raise MinuteOutOfBounds if `timestamp` is earlier than the
+ first trading minute or later than the last trading minute of
+ `calendar`. Pass as False if `timestamp` represents a Date (as
+ opposed to a Minute). If True then `calendar` must be passed.
+
+ side : optional, {None, 'left', 'right', 'both', 'neither'}
+ The side that determines which minutes at a session's bounds are
+ considered as trading minutes (as `ExchangeCalendar` 'side'
+ parameter). Only required if `calendar` is not passed or if do not
+ wish to rely on `calendar.side`. Ignored if `timestamp` is accurate
+ to minute resolution.
+
+ utc : default: True
+ True - convert / set timezone to UTC.
+ False - leave any timezone unchanged. Note, if timezone of
+ `timestamp` is UTC then will remain as UTC.
+
+ Raises
+ ------
+ TypeError
+ If `timestamp` is not of type [pd.Timestamp | str | int | float |
+ datetime.datetime].
+
+ ValueError
+ If `timestamp` is not an acceptable single-argument input to
+ pd.Timestamp.
+
+ exchange_calendars.errors.MinuteOutOfBounds
+ If `raise_oob` True and `timestamp` parses to a valid timestamp
+ although timestamp is either before `calendar`'s first trading
+ minute or after `calendar`'s last trading minute.
+ """
+ if isinstance(timestamp, pd.Timestamp):
+ ts = timestamp
+ else:
+ try:
+ ts = pd.Timestamp(timestamp)
+ except Exception as e:
+ msg = (
+ f"Parameter `{param_name}` receieved as '{timestamp}' although"
+ f" a Date or Minute must be passed as a pd.Timestamp or a"
+ f" valid single-argument input to pd.Timestamp."
+ )
+ if isinstance(e, TypeError):
+ raise TypeError(msg) from e
+ else:
+ raise ValueError(msg) from e
+
+ if utc and ts.tz is not UTC:
+ ts = ts.tz_localize(UTC) if ts.tz is None else ts.tz_convert(UTC)
+
+ if ts.second or ts.microsecond or ts.nanosecond:
+ if side is None and calendar is None:
+ raise ValueError(
+ "`side` or `calendar` must be passed if `timestamp` has a"
+ " non-zero second (or more accurate) component. `timestamp`"
+ f" parsed as '{ts}'."
+ )
+ side = side if side is not None else calendar.side
+ if side == "left":
+ ts = ts.floor("min")
+ elif side == "right":
+ ts = ts.ceil("min")
+ else:
+ raise ValueError(
+ "`timestamp` cannot have a non-zero second (or more accurate)"
+ f" component for `side` '{side}'. `timestamp` parsed as '{ts}'."
+ )
+
+ if raise_oob:
+ if calendar is None:
+ raise ValueError("`calendar` must be passed if `raise_oob` is True.")
+ if calendar._minute_oob(ts):
+ raise errors.MinuteOutOfBounds(calendar, ts, param_name)
+
+ return ts
+
+
+def parse_date_or_minute(
+ ts: Date | Minute,
+ param_name: str,
+ calendar: ExchangeCalendar,
+) -> tuple[pd.Timestamp, bool]:
+ """Parse input that can be interpreted as a Date or a Minute.
+
+ Parameters
+ ----------
+ ts
+ Input that can be interpreted as a Date or a Minute. Must be valid
+ input to pd.Timestamp.
+
+ param_name
+ Name of a parameter that was to receive a Date or a Minute.
+
+ calendar
+ ExchangeCalendar against which to evaluate out-of-bounds
+ timestamps.
+
+ Returns
+ -------
+ tuple[pd.Timestamp, bool]:
+ [0] Parsed input to a pd.Timestamp.
+ [1] Boolean indicating if input was interpreted as a Minute (True)
+ or a Date (False).
+ """
+ ts = parse_timestamp(ts, param_name, calendar, raise_oob=False, utc=False)
+ is_time = not is_date(ts)
+ ts = to_utc(ts) if is_time else ts
+ if is_time and calendar._minute_oob(ts):
+ raise errors.MinuteOutOfBounds(calendar, ts, param_name)
+ elif not is_time and calendar._date_oob(ts):
+ raise errors.DateOutOfBounds(calendar, ts, param_name)
+ return ts, is_time
+
+
+def parse_trading_minute(
+ calendar: ExchangeCalendar, minute: TradingMinute, param_name: str = "minute"
+) -> pd.Timestamp:
+ """Parse input intended to represent a trading minute.
+
+ Parameters
+ ----------
+ calendar
+ Calendar which `minute` must be a trading minute of.
+
+ minute
+ Input to be parsed as a trading minute. Must be valid input to
+ pd.Timestamp and represent a trading minute of `calendar`.
+
+ param_name
+ Name of a parameter that was to receive a trading minute.
+
+ Raises
+ ------
+ Errors as `parse_timestamp` and additionally:
+
+ exchange_calendars.errors.NotTradingMinuteError
+ If `minute` parses to a valid timestamp although timestamp does not
+ represent a trading minute of `calendar`.
+ """
+ # let out-of-bounds be handled by more specific NotTradingMinuteError message.
+ minute = parse_timestamp(minute, param_name, raise_oob=False, calendar=calendar)
+ if calendar._minute_oob(minute) or not calendar.is_trading_minute(
+ minute, _parse=False
+ ):
+ raise errors.NotTradingMinuteError(calendar, minute, param_name)
+ return minute
+
+
+def parse_date(
+ date: Date,
+ param_name: str = "date",
+ calendar: ExchangeCalendar | None = None,
+ raise_oob: bool = True,
+) -> pd.Timestamp:
+ """Parse input intended to represent a date.
+
+ Parameters
+ ----------
+ date
+ Input to be parsed as date. Must be valid input to pd.Timestamp
+ and have a time component of 00:00.
+
+ param_name
+ Name of a parameter that was to receive a date.
+
+ calendar
+ ExchangeCalendar against which to evalute out-of-bounds dates.
+ Only requried if `raise_oob` True.
+
+ raise_oob : default: True
+ True to raise DateOutOfBounds if `date` is earlier than the
+ first session or later than the last session of `calendar`. NB if
+ True (default) then `calendar` must be passed.
+
+ Returns
+ -------
+ pd.Timestamp
+ pd.Timestamp (timezone naive with time component of 00:00).
+
+ Raises
+ ------
+ Errors as `parse_timestamp` and additionally:
+
+ ValueError
+ If `date` time component is not 00:00.
+ If `date` is timezone aware.
+
+ exchange_calendars.errors.DateOutOfBounds
+ If `raise_oob` True and `date` parses to a valid timestamp although
+ timestamp is before `calendar`'s first session or after
+ `calendar`'s last session.
+ """
+ # side "left" to get it through 'second' handling. Has undesirable effect of
+ # allowing `date` to be defined with a second (or more accurate) compoment
+ # if it falls within the minute that follows midnight.
+ ts = parse_timestamp(date, param_name, raise_oob=False, side="left", utc=False)
+
+ if ts.tz is not None:
+ raise ValueError(
+ f"Parameter `{param_name}` received with timezone defined as '{ts.tz.key}'"
+ f" although a Date must be timezone naive."
+ )
+
+ if not ts == ts.normalize():
+ raise ValueError(
+ f"Parameter `{param_name}` parsed as '{ts}' although a Date must have"
+ f" a time component of 00:00."
+ )
+
+ if raise_oob:
+ if calendar is None:
+ raise ValueError("`calendar` must be passed if `raise_oob` is True.")
+ if calendar._date_oob(ts):
+ raise errors.DateOutOfBounds(calendar, ts, param_name)
+
+ return ts
+
+
+def parse_session(
+ calendar: ExchangeCalendar, session: Session, param_name: str = "session"
+) -> pd.Timestamp:
+ """Parse input intended to represent a session label.
+
+ Parameters
+ ----------
+ calendar
+ Calendar against which to evaluate `session`.
+
+ session
+ Input to be parsed as session. Must be valid input to pd.Timestamp,
+ have a time component of 00:00 and represent a session of
+ `calendar`.
+
+ param_name
+ Name of a parameter that was to receive a session.
+
+ Returns
+ -------
+ pd.Timestamp
+ pd.Timestamp (timezone naive and with time component of 00:00) that
+ represents a real session of `calendar`.
+
+ Raises
+ ------
+ Errors as `parse_date` and additionally:
+
+ exchange_calendars.errors.NotSessionError
+ If `session` parses to a valid date although date does not
+ represent a session of `calendar`.
+ """
+ # let out-of-bounds be handled by more specific NotSessionError message.
+ ts = parse_date(session, param_name, raise_oob=False)
+ if calendar._date_oob(ts) or not calendar.is_session(ts, _parse=False):
+ raise errors.NotSessionError(calendar, ts, param_name)
+ return ts
+
+
+class _TradingIndex:
+ """Create a trading index.
+
+ Credit to @Stryder-Git at pandas_market_calendars for showing the way
+ with a vectorised solution to creating trading indices.
+
+ Parameters
+ ----------
+ All parameters as ExchangeCalendar.trading_index except:
+
+ align_pm
+ As 'align' parameter of `ExchangeCalendar.trading_index` although
+ applied exclusively to the post-break subsessions.
+ """
+
+ def __init__(
+ self,
+ calendar: ExchangeCalendar,
+ start_: Date | Minute,
+ end_: Date | Minute,
+ period: pd.Timedelta,
+ closed: Literal["left", "right", "both", "neither"],
+ force_close: bool,
+ force_break_close: bool,
+ curtail_overlaps: bool,
+ ignore_breaks: bool,
+ align: pd.Timedelta,
+ align_pm: pd.Timedelta,
+ ):
+ self.closed = closed
+ self.force_break_close = False if ignore_breaks else force_break_close
+ self.force_close = force_close
+ self.curtail_overlaps = curtail_overlaps
+
+ # parse `start_` and `end_`
+ start_, self.start_as_time = parse_date_or_minute(start_, "start", calendar)
+ end_, self.end_as_time = parse_date_or_minute(end_, "end", calendar)
+ self.start_, self.end_ = start_, end_
+ # define start and end as sessions
+ start = (
+ calendar.minute_to_session(start_, "next") if self.start_as_time else start_
+ )
+ end = calendar.minute_to_session(end_, "previous") if self.end_as_time else end_
+
+ # get session bound values over requested range
+ slice_start = calendar.sessions.searchsorted(start)
+ slice_end = calendar.sessions.searchsorted(end, side="right")
+ slce = slice(slice_start, slice_end)
+
+ self.interval_nanos = period.value
+ self.dtype = np.int64 if self.interval_nanos < 3000000000 else np.int32
+
+ self.closes = calendar.closes_nanos[slce]
+
+ def align_opens(opens: pd.Series, align: pd.Timedelta) -> np.ndarray:
+ """Return opens as nanos shifted for alignment."""
+ opens = opens.dt.ceil(align)
+ return opens.values.astype(np.int64)
+
+ if align != pd.Timedelta(1, "min"):
+ self.opens = align_opens(calendar.opens[slce], align)
+ else:
+ self.opens = calendar.opens_nanos[slce]
+
+ if ignore_breaks:
+ self.has_break = False
+ else:
+ self.break_starts = calendar.break_starts_nanos[slce]
+
+ if align_pm != pd.Timedelta(1, "min"):
+ self.break_ends = align_opens(calendar.break_ends[slce], align_pm)
+ else:
+ self.break_ends = calendar.break_ends_nanos[slce]
+
+ self.mask = self.break_starts != pd.NaT.value # break mask
+ self.has_break = self.mask.any()
+
+ self.defaults = {
+ "closed": self.closed,
+ "force_close": self.force_close,
+ "force_break_close": self.force_break_close,
+ }
+
+ @property
+ def closed_right(self) -> bool:
+ return self.closed in ["right", "both"]
+
+ @property
+ def closed_left(self) -> bool:
+ return self.closed in ["left", "both"]
+
+ def verify_non_overlapping(self):
+ """Raise IndicesOverlapError if indices will overlap."""
+ if not self.closed_right:
+ return
+
+ def _check(
+ start_nanos: np.ndarray, end_nanos: np.ndarray, next_start_nanos: np.ndarray
+ ):
+ """Raise IndicesOverlap Error if indices would overlap.
+
+ `next_start_nanos` describe start of (sub)session that follows and could
+ overlap with (sub)session described by `start_nanos` and `end_nanos`.
+
+ All inputs should be of same length.
+ """
+ num_intervals = np.ceil((end_nanos - start_nanos) / self.interval_nanos)
+ right = start_nanos + num_intervals * self.interval_nanos
+ if self.closed == "right" and (right > next_start_nanos).any():
+ raise errors.IndicesOverlapError()
+ if self.closed == "both" and (right >= next_start_nanos).any():
+ raise errors.IndicesOverlapError()
+
+ if self.has_break:
+ if not self.force_break_close:
+ _check(
+ self.opens[self.mask],
+ self.break_starts[self.mask],
+ self.break_ends[self.mask],
+ )
+
+ if not self.force_close:
+ opens, closes, next_opens = (
+ self.opens[:-1],
+ self.closes[:-1],
+ self.opens[1:],
+ )
+ _check(opens, closes, next_opens)
+ if self.has_break:
+ mask = self.mask[:-1]
+ _check(self.break_ends[:-1][mask], closes[mask], next_opens[mask])
+
+ def _create_index_for_sessions(
+ self,
+ start_nanos: np.ndarray,
+ end_nanos: np.ndarray,
+ force_close: bool,
+ ) -> np.ndarray:
+ """Create nano array of indices for sessions of given bounds."""
+ if start_nanos.size == 0:
+ return start_nanos
+
+ # evaluate number of indices for each session
+ num_intervals = (end_nanos - start_nanos) / self.interval_nanos
+ num_indices = np.ceil(num_intervals).astype("int")
+
+ if force_close:
+ if self.closed_right:
+ on_freq = (num_intervals == num_indices).all()
+ if not on_freq:
+ num_indices -= 1 # add the close later
+ else:
+ on_freq = True
+
+ if self.closed == "both":
+ num_indices += 1
+ elif self.closed == "neither":
+ num_indices -= 1
+
+ # by session, evaluate a range of int such that indices of a session
+ # could be evaluted from [ session_open + (freq * i) for i in range ]
+ start = 0 if self.closed_left else 1
+ func = np.vectorize(lambda stop: np.arange(start, stop), otypes=[np.ndarray])
+ stop = num_indices if self.closed_left else num_indices + 1
+ ranges = np.concatenate(func(stop), axis=0, dtype=self.dtype)
+
+ # evaluate index as nano array
+ base = start_nanos.repeat(num_indices)
+ index = base + ranges * self.interval_nanos
+
+ if force_close and not on_freq:
+ index = np.concatenate((index, end_nanos))
+ index.sort()
+
+ return index
+
+ def _trading_index(self) -> np.ndarray:
+ """Create trading index as nano array.
+
+ Notes
+ -----
+ If `self.has_break` then index is returned UNSORTED. Why?
+ Returning unsorted allows `trading_index_intervals` to create
+ indices for the left and right sides and then arrange the right
+ in the same order as the sorted left. Although as required, there
+ are rare circumstances in which the resulting right side will not
+ be in ascending order (it will later be curtailed or an error
+ raised). This can happen when, for example, a calendar has breaks,
+ `force_break_close` is False although `force_close` is True and the
+ period is sufficiently long that the right side of the last
+ interval of a morning subsession exceeds the day close, i.e.
+ exceeds the right side of the subsequent interval. In these cases,
+ sorting the right index by value would result in the indices
+ becoming unsynced with the corresponding left indices.
+ """
+ if self.has_break:
+ # sessions with breaks
+ index_am = self._create_index_for_sessions(
+ self.opens[self.mask],
+ self.break_starts[self.mask],
+ self.force_break_close,
+ )
+
+ index_pm = self._create_index_for_sessions(
+ self.break_ends[self.mask], self.closes[self.mask], self.force_close
+ )
+
+ # sessions without a break
+ index_day = self._create_index_for_sessions(
+ self.opens[~self.mask], self.closes[~self.mask], self.force_close
+ )
+
+ # put it all together
+ index = np.concatenate((index_am, index_pm, index_day))
+
+ else:
+ index = self._create_index_for_sessions(
+ self.opens, self.closes, self.force_close
+ )
+
+ return index
+
+ def curtail_for_times(
+ self, index: pd.DatetimeIndex | pd.IntervalIndex
+ ) -> pd.DatetimeIndex | pd.IntervalIndex:
+ """Curtail start and end of trading index.
+
+ Curtails any unwanted rows from the start and end of `index` if
+ class received `start_` and/or `end_` as times.
+ """
+ intervals = isinstance(index, pd.IntervalIndex)
+ bv: np.ndarray | None = None
+ if self.start_as_time:
+ bv = index.left >= self.start_ if intervals else index >= self.start_
+ if self.end_as_time:
+ bv_end = index.right <= self.end_ if intervals else index <= self.end_
+ bv = bv & bv_end if bv is not None else bv_end
+ return index if bv is None else index[bv]
+
+ def trading_index(self) -> pd.DatetimeIndex:
+ """Create trading index as a DatetimeIndex."""
+ self.verify_non_overlapping()
+ index = self._trading_index()
+ if self.has_break:
+ index.sort()
+ index = pd.DatetimeIndex(index, tz=UTC)
+ return self.curtail_for_times(index)
+
+ @contextlib.contextmanager
+ def _override_defaults(self, **kwargs):
+ for k, v in kwargs.items():
+ setattr(self, k, v)
+ yield
+ for k, v in self.defaults.items():
+ setattr(self, k, v)
+
+ def trading_index_intervals(self) -> pd.IntervalIndex:
+ """Create trading index as a pd.IntervalIndex."""
+ with self._override_defaults(
+ closed="left", force_close=False, force_break_close=False
+ ):
+ left = self._trading_index()
+
+ if not (self.force_close or self.force_break_close):
+ if self.has_break:
+ left.sort()
+ right = left + self.interval_nanos
+ else:
+ with self._override_defaults(closed="right"):
+ right = self._trading_index()
+ if self.has_break:
+ # See _trading_index.__doc__ for note on what's going on here.
+ indices = left.argsort()
+ left.sort()
+ right = right[indices]
+
+ overlaps_next = right[:-1] > left[1:]
+ if overlaps_next.any():
+ if self.curtail_overlaps:
+ right[:-1][overlaps_next] = left[1:][overlaps_next]
+ else:
+ raise errors.IntervalsOverlapError()
+
+ left = pd.DatetimeIndex(left, tz=UTC)
+ right = pd.DatetimeIndex(right, tz=UTC)
+ index = pd.IntervalIndex.from_arrays(left, right, self.closed)
+ return self.curtail_for_times(index)
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/calendar_utils.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/calendar_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4cbc843273e3747374e981c78bafb93b0b431f78
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/calendar_utils.py
@@ -0,0 +1,554 @@
+from __future__ import annotations
+
+from typing import Literal
+
+from .calendar_helpers import parse_date, Date
+from .always_open import AlwaysOpenCalendar
+from .errors import CalendarNameCollision, CyclicCalendarAlias, InvalidCalendarName
+from .exchange_calendar import ExchangeCalendar
+from .exchange_calendar_aixk import AIXKExchangeCalendar
+from .exchange_calendar_asex import ASEXExchangeCalendar
+from .exchange_calendar_bvmf import BVMFExchangeCalendar
+from .exchange_calendar_cmes import CMESExchangeCalendar
+from .exchange_calendar_iepa import IEPAExchangeCalendar
+from .exchange_calendar_xams import XAMSExchangeCalendar
+from .exchange_calendar_xasx import XASXExchangeCalendar
+from .exchange_calendar_xbkk import XBKKExchangeCalendar
+from .exchange_calendar_xbog import XBOGExchangeCalendar
+from .exchange_calendar_xbom import XBOMExchangeCalendar
+from .exchange_calendar_xbru import XBRUExchangeCalendar
+from .exchange_calendar_xbse import XBSEExchangeCalendar
+from .exchange_calendar_xbud import XBUDExchangeCalendar
+from .exchange_calendar_xbue import XBUEExchangeCalendar
+from .exchange_calendar_xcbf import XCBFExchangeCalendar
+from .exchange_calendar_xcse import XCSEExchangeCalendar
+from .exchange_calendar_xdub import XDUBExchangeCalendar
+from .exchange_calendar_xetr import XETRExchangeCalendar
+from .exchange_calendar_xfra import XFRAExchangeCalendar
+from .exchange_calendar_xhel import XHELExchangeCalendar
+from .exchange_calendar_xhkg import XHKGExchangeCalendar
+from .exchange_calendar_xice import XICEExchangeCalendar
+from .exchange_calendar_xidx import XIDXExchangeCalendar
+from .exchange_calendar_xist import XISTExchangeCalendar
+from .exchange_calendar_xjse import XJSEExchangeCalendar
+from .exchange_calendar_xkar import XKARExchangeCalendar
+from .exchange_calendar_xkls import XKLSExchangeCalendar
+from .exchange_calendar_xkrx import XKRXExchangeCalendar
+from .exchange_calendar_xlim import XLIMExchangeCalendar
+from .exchange_calendar_xlis import XLISExchangeCalendar
+from .exchange_calendar_xlon import XLONExchangeCalendar
+from .exchange_calendar_xmad import XMADExchangeCalendar
+from .exchange_calendar_xmex import XMEXExchangeCalendar
+from .exchange_calendar_xmil import XMILExchangeCalendar
+from .exchange_calendar_xmos import XMOSExchangeCalendar
+from .exchange_calendar_xnys import XNYSExchangeCalendar
+from .exchange_calendar_xnze import XNZEExchangeCalendar
+from .exchange_calendar_xosl import XOSLExchangeCalendar
+from .exchange_calendar_xpar import XPARExchangeCalendar
+from .exchange_calendar_xphs import XPHSExchangeCalendar
+from .exchange_calendar_xpra import XPRAExchangeCalendar
+from .exchange_calendar_xsau import XSAUExchangeCalendar
+from .exchange_calendar_xses import XSESExchangeCalendar
+from .exchange_calendar_xsgo import XSGOExchangeCalendar
+from .exchange_calendar_xshg import XSHGExchangeCalendar
+from .exchange_calendar_xsto import XSTOExchangeCalendar
+from .exchange_calendar_xswx import XSWXExchangeCalendar
+from .exchange_calendar_xtae import XTAEExchangeCalendar
+from .exchange_calendar_xtai import XTAIExchangeCalendar
+from .exchange_calendar_xtks import XTKSExchangeCalendar
+from .exchange_calendar_xtse import XTSEExchangeCalendar
+from .exchange_calendar_xwar import XWARExchangeCalendar
+from .exchange_calendar_xwbo import XWBOExchangeCalendar
+from .us_futures_calendar import QuantopianUSFuturesCalendar
+from .weekday_calendar import WeekdayCalendar
+
+_default_calendar_factories = {
+ # Exchange calendars.
+ "AIXK": AIXKExchangeCalendar,
+ "ASEX": ASEXExchangeCalendar,
+ "BVMF": BVMFExchangeCalendar,
+ "CMES": CMESExchangeCalendar,
+ "IEPA": IEPAExchangeCalendar,
+ "XAMS": XAMSExchangeCalendar,
+ "XASX": XASXExchangeCalendar,
+ "XBKK": XBKKExchangeCalendar,
+ "XBOG": XBOGExchangeCalendar,
+ "XBOM": XBOMExchangeCalendar,
+ "XBRU": XBRUExchangeCalendar,
+ "XBSE": XBSEExchangeCalendar,
+ "XBUD": XBUDExchangeCalendar,
+ "XBUE": XBUEExchangeCalendar,
+ "XCBF": XCBFExchangeCalendar,
+ "XCSE": XCSEExchangeCalendar,
+ "XDUB": XDUBExchangeCalendar,
+ "XFRA": XFRAExchangeCalendar,
+ "XETR": XETRExchangeCalendar,
+ "XHEL": XHELExchangeCalendar,
+ "XHKG": XHKGExchangeCalendar,
+ "XICE": XICEExchangeCalendar,
+ "XIDX": XIDXExchangeCalendar,
+ "XIST": XISTExchangeCalendar,
+ "XJSE": XJSEExchangeCalendar,
+ "XKAR": XKARExchangeCalendar,
+ "XKLS": XKLSExchangeCalendar,
+ "XKRX": XKRXExchangeCalendar,
+ "XLIM": XLIMExchangeCalendar,
+ "XLIS": XLISExchangeCalendar,
+ "XLON": XLONExchangeCalendar,
+ "XMAD": XMADExchangeCalendar,
+ "XMEX": XMEXExchangeCalendar,
+ "XMIL": XMILExchangeCalendar,
+ "XMOS": XMOSExchangeCalendar,
+ "XNYS": XNYSExchangeCalendar,
+ "XNZE": XNZEExchangeCalendar,
+ "XOSL": XOSLExchangeCalendar,
+ "XPAR": XPARExchangeCalendar,
+ "XPHS": XPHSExchangeCalendar,
+ "XPRA": XPRAExchangeCalendar,
+ "XSAU": XSAUExchangeCalendar,
+ "XSES": XSESExchangeCalendar,
+ "XSGO": XSGOExchangeCalendar,
+ "XSHG": XSHGExchangeCalendar,
+ "XSTO": XSTOExchangeCalendar,
+ "XSWX": XSWXExchangeCalendar,
+ "XTAE": XTAEExchangeCalendar,
+ "XTAI": XTAIExchangeCalendar,
+ "XTKS": XTKSExchangeCalendar,
+ "XTSE": XTSEExchangeCalendar,
+ "XWAR": XWARExchangeCalendar,
+ "XWBO": XWBOExchangeCalendar,
+ # Miscellaneous calendars.
+ "us_futures": QuantopianUSFuturesCalendar,
+ "24/7": AlwaysOpenCalendar,
+ "24/5": WeekdayCalendar,
+}
+_default_calendar_aliases = {
+ "NYSE": "XNYS",
+ "NASDAQ": "XNYS",
+ "BATS": "XNYS",
+ "XNAS": "XNYS",
+ "FWB": "XFRA",
+ "LSE": "XLON",
+ "TSX": "XTSE",
+ "BMF": "BVMF",
+ "CME": "CMES",
+ "CBOT": "CMES",
+ "COMEX": "CMES",
+ "NYMEX": "CMES",
+ "ICE": "IEPA",
+ "ICEUS": "IEPA",
+ "NYFE": "IEPA",
+ "CFE": "XCBF",
+ "JKT": "XIDX",
+ "SIX": "XSWX",
+ "JPX": "XTKS",
+ "ASX": "XASX",
+ "HKEX": "XHKG",
+ "OSE": "XOSL",
+ "BSE": "XBOM",
+ "SSE": "XSHG",
+ "TASE": "XTAE",
+ "BVB": "XBSE",
+}
+
+default_calendar_names = sorted(_default_calendar_factories.keys())
+
+
+class ExchangeCalendarDispatcher(object):
+ """
+ A class for dispatching and caching exchange calendars.
+
+ Methods of a global instance of this class can be accessed directly
+ from exchange_calendars, for example `exchange_calendars.get_calendar`.
+
+ Parameters
+ ----------
+ calendars : dict[str -> ExchangeCalendar]
+ Initial set of calendars.
+ calendar_factories : dict[str -> function]
+ Factories for lazy calendar creation.
+ aliases : dict[str -> str]
+ Calendar name aliases.
+ """
+
+ def __init__(self, calendars, calendar_factories, aliases):
+ self._calendars = calendars
+ self._calendar_factories = dict(calendar_factories)
+ self._aliases = dict(aliases)
+ # key: factory name, value: (calendar, dict of calendar kwargs)
+ self._factory_output_cache: dict(str, tuple(ExchangeCalendar, dict)) = {}
+
+ def _fabricate(self, name: str, **kwargs) -> ExchangeCalendar:
+ """Fabricate calendar with `name` and `**kwargs`."""
+ try:
+ factory = self._calendar_factories[name]
+ except KeyError as e:
+ raise InvalidCalendarName(calendar_name=name) from e
+ calendar = factory(**kwargs)
+ self._factory_output_cache[name] = (calendar, kwargs)
+ return calendar
+
+ def _get_cached_factory_output(
+ self, name: str, **kwargs
+ ) -> ExchangeCalendar | None:
+ """Get calendar from factory output cache.
+
+ Return None if `name` not in cache or `name` in cache although
+ calendar got with kwargs other than `**kwargs`.
+ """
+ calendar, calendar_kwargs = self._factory_output_cache.get(name, (None, None))
+ if calendar is not None and calendar_kwargs == kwargs:
+ return calendar
+ else:
+ return None
+
+ def get_calendar(
+ self,
+ name: str,
+ start: Date | None = None,
+ end: Date | None = None,
+ side: Literal["left", "right", "both", "neither"] | None = None,
+ ) -> ExchangeCalendar:
+ """Get exchange calendar with a given name.
+
+ Parameters
+ ----------
+ name
+ Name of the ExchangeCalendar to get, for example 'XNYS'.
+
+ The following arguments will be passed to the calendar factory.
+ These arguments can only be passed if `name` is registered as a
+ calendar factory (either by having been included to
+ `calendar_factories` passed to the dispatcher's constructor or
+ having been subsequently registered via the
+ `register_calendar_type` method).
+
+ start : default: as default for calendar factory
+ First calendar session will be `start`, if `start` is a
+ session, or first session after `start`. Cannot be earlier than
+ any date returned by the respective calendar class method
+ `bound_min`.
+
+ end : default: as default for calendar factory
+ Last calendar session will be `end`, if `end` is a session, or
+ last session before `end`. Cannot be later than any date
+ returned by the respective calendar class method `bound_max`.
+
+ side : default: as default for calendar factory
+ Define which of session open/close and break start/end should
+ be treated as a trading minute:
+ "left" - treat session open and break_start as trading minutes,
+ do not treat session close or break_end as trading minutes.
+ "right" - treat session close and break_end as trading minutes,
+ do not treat session open or break_start as tradng minutes.
+ "both" - treat all of session open, session close, break_start
+ and break_end as trading minutes.
+ "neither" - treat none of session open, session close,
+ break_start or break_end as trading minutes.
+
+ Returns
+ -------
+ ExchangeCalendar
+ Requested calendar.
+
+ Raises
+ ------
+ InvalidCalendarName
+ If `name` does not represent a registered calendar.
+
+ ValueError
+ If `start`, `end` or `side` are received although `name` is a
+ registered calendar (as opposed to a calendar factory).
+
+ If `start` or `end` are received although do not parse as a
+ date that could represent a session.
+ """
+ # will raise InvalidCalendarName if name not valid
+ name = self.resolve_alias(name)
+
+ kwargs = {}
+ for k, v in zip(["start", "end", "side"], [start, end, side]):
+ if v is not None:
+ kwargs[k] = v
+
+ if name in self._calendars:
+ if kwargs:
+ raise ValueError(
+ f"Receieved calendar arguments although {name} is registered"
+ f" as a specific instance of class"
+ f" {self._calendars[name].__class__}, not as a calendar factory."
+ )
+ else:
+ return self._calendars[name]
+
+ if kwargs.get("start"):
+ kwargs["start"] = parse_date(kwargs["start"], "start", raise_oob=False)
+ else:
+ kwargs["start"] = None
+ if kwargs.get("end"):
+ kwargs["end"] = parse_date(kwargs["end"], "end", raise_oob=False)
+ else:
+ kwargs["end"] = None
+
+ cached = self._get_cached_factory_output(name, **kwargs)
+ return cached if cached is not None else self._fabricate(name, **kwargs)
+
+ def get_calendar_names(
+ self, include_aliases: bool = True, sort: bool = True
+ ) -> list[str]:
+ """Return all canoncial calendar names and, optionally, aliases.
+
+ Parameters
+ ----------
+ include_aliases : default: True
+ True to include calendar aliases.
+ False to return only canonical calendar names.
+
+ sort : default: True
+ Return calendar names sorted alphabetically.
+
+ Returns
+ -------
+ list of str
+ List of canonical calendar names and, optionally, aliases.
+
+ See Also
+ --------
+ names_to_aliases : Mapping of cononcial names to aliases.
+ aliases_to_names : Mapping of aliases to canoncial names.
+ resolve_alias : Resolve single alias to a canonical name.
+ """
+ keys = set(self._calendar_factories.keys()).union(set(self._calendars.keys()))
+ if include_aliases:
+ keys = keys.union(set(self._aliases.keys()))
+ names = list(keys)
+ if sort:
+ names.sort()
+ return names
+
+ def has_calendar(self, name):
+ """
+ Do we have (or have the ability to make) a calendar with ``name``?
+ """
+ return (
+ name in self._calendars
+ or name in self._calendar_factories
+ or name in self._aliases
+ )
+
+ def register_calendar(self, name, calendar, force=False):
+ """
+ Registers a calendar for retrieval by the get_calendar method.
+
+ Parameters
+ ----------
+ name: str
+ The key with which to register this calendar.
+ calendar: ExchangeCalendar
+ The calendar to be registered for retrieval.
+ force : bool, optional
+ If True, old calendars will be overwritten on a name collision.
+ If False, name collisions will raise an exception.
+ Default is False.
+
+ Raises
+ ------
+ CalendarNameCollision
+ If a calendar is already registered with the given calendar's name.
+ """
+ if force:
+ self.deregister_calendar(name)
+
+ if self.has_calendar(name):
+ raise CalendarNameCollision(calendar_name=name)
+
+ self._calendars[name] = calendar
+
+ def register_calendar_type(self, name, calendar_type, force=False):
+ """
+ Registers a calendar by type.
+
+ This is useful for registering a new calendar to be lazily instantiated
+ at some future point in time.
+
+ Parameters
+ ----------
+ name: str
+ The key with which to register this calendar.
+ calendar_type: type
+ The type of the calendar to register.
+ force : bool, optional
+ If True, old calendars will be overwritten on a name collision.
+ If False, name collisions will raise an exception.
+ Default is False.
+
+ Raises
+ ------
+ CalendarNameCollision
+ If a calendar is already registered with the given calendar's name.
+ """
+ if force:
+ self.deregister_calendar(name)
+
+ if self.has_calendar(name):
+ raise CalendarNameCollision(calendar_name=name)
+
+ self._calendar_factories[name] = calendar_type
+
+ def register_calendar_alias(self, alias, real_name, force=False):
+ """
+ Register an alias for a calendar.
+
+ This is useful when multiple exchanges should share a calendar, or when
+ there are multiple ways to refer to the same exchange.
+
+ After calling ``register_alias('alias', 'real_name')``, subsequent
+ calls to ``get_calendar('alias')`` will return the same result as
+ ``get_calendar('real_name')``.
+
+ Parameters
+ ----------
+ alias : str
+ The name to be used to refer to a calendar.
+ real_name : str
+ The canonical name of the registered calendar.
+ force : bool, optional
+ If True, old calendars will be overwritten on a name collision.
+ If False, name collisions will raise an exception.
+ Default is False.
+ """
+ if force:
+ self.deregister_calendar(alias)
+
+ if self.has_calendar(alias):
+ raise CalendarNameCollision(calendar_name=alias)
+
+ self._aliases[alias] = real_name
+
+ # Ensure that the new alias doesn't create a cycle, and back it out if
+ # we did.
+ try:
+ self.resolve_alias(alias)
+ except CyclicCalendarAlias:
+ del self._aliases[alias]
+ raise
+
+ def resolve_alias(self, name: str):
+ """Resolve an alias to cononcial name of corresponding calendar.
+
+ A cononical name will resolve to itself.
+
+ Parameters
+ ----------
+ name :
+ Alias or canoncial name corresponding to a calendar.
+
+ Returns
+ -------
+ canonical_name : str
+ Canonical name of calendar that would be created for `name`.
+
+ Raises
+ ------
+ InvalidCalendarName
+ If `name` is not an alias or canonical name of any registered
+ calendar.
+
+ See Also
+ --------
+ aliases_to_names : Mapping of aliases to canoncial names.
+ names_to_aliases : Mapping of cononcial names to aliases.
+ """
+ if name not in self.get_calendar_names(include_aliases=True, sort=False):
+ raise InvalidCalendarName(calendar_name=name)
+
+ seen = []
+
+ while name in self._aliases:
+ seen.append(name)
+ name = self._aliases[name]
+
+ # This is O(N ** 2), but if there's an alias chain longer than 2,
+ # something strange has happened.
+ if name in seen:
+ seen.append(name)
+ raise CyclicCalendarAlias(cycle=" -> ".join(repr(k) for k in seen))
+
+ return name
+
+ def aliases_to_names(self) -> dict[str, str]:
+ """Return dictionary mapping aliases to canonical names.
+
+ Returns
+ -------
+ dict of {str, str}
+ Dictionary mapping aliases to canoncial name of corresponding
+ calendar.
+
+ See Also
+ --------
+ resolve_alias : Resolve single alias to a canonical name.
+ names_to_aliases : Mapping of cononcial names to aliases.
+ """
+ return {alias: self.resolve_alias(alias) for alias in self._aliases}
+
+ def names_to_aliases(self) -> dict[str, list[str]]:
+ """Return mapping of canonical calendar names to associated aliases.
+
+ Returns
+ -------
+ dict of {str, list of str}
+ Dictionary mapping canonical calendar names to any associated
+ aliases.
+
+ See Also
+ --------
+ aliases_to_names : Mapping of aliases to canoncial names.
+ """
+ names = self.get_calendar_names(include_aliases=False)
+ dic = {name: [] for name in names}
+ for alias, name in self.aliases_to_names().items():
+ dic[name].append(alias)
+ return dic
+
+ def deregister_calendar(self, name):
+ """
+ If a calendar is registered with the given name, it is de-registered.
+
+ Parameters
+ ----------
+ name : str
+ The name of the calendar to be deregistered.
+ """
+ self._calendars.pop(name, None)
+ self._calendar_factories.pop(name, None)
+ self._aliases.pop(name, None)
+
+ def clear_calendars(self):
+ """
+ Deregisters all current registered calendars
+ """
+ self._calendars.clear()
+ self._calendar_factories.clear()
+ self._aliases.clear()
+
+
+# We maintain a global calendar dispatcher so that users can just do
+# `register_calendar('my_calendar', calendar) and then use `get_calendar`
+# without having to thread around a dispatcher.
+global_calendar_dispatcher = ExchangeCalendarDispatcher(
+ calendars={},
+ calendar_factories=_default_calendar_factories,
+ aliases=_default_calendar_aliases,
+)
+
+get_calendar = global_calendar_dispatcher.get_calendar
+get_calendar_names = global_calendar_dispatcher.get_calendar_names
+clear_calendars = global_calendar_dispatcher.clear_calendars
+deregister_calendar = global_calendar_dispatcher.deregister_calendar
+register_calendar = global_calendar_dispatcher.register_calendar
+register_calendar_type = global_calendar_dispatcher.register_calendar_type
+register_calendar_alias = global_calendar_dispatcher.register_calendar_alias
+resolve_alias = global_calendar_dispatcher.resolve_alias
+aliases_to_names = global_calendar_dispatcher.aliases_to_names
+names_to_aliases = global_calendar_dispatcher.names_to_aliases
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/common_holidays.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/common_holidays.py
new file mode 100644
index 0000000000000000000000000000000000000000..b41083a8d0481bfa536cef74a7daa8617f0637c4
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/common_holidays.py
@@ -0,0 +1,447 @@
+import pandas as pd
+from dateutil.easter import EASTER_ORTHODOX, easter
+from pandas.tseries.holiday import FR, DateOffset, Easter, Holiday
+from pandas.tseries.offsets import Day
+
+from .exchange_calendar import MONDAY, TUESDAY
+
+
+def new_years_day(start_date=None, end_date=None, observance=None, days_of_week=None):
+ return Holiday(
+ "New Year's Day",
+ month=1,
+ day=1,
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def new_years_eve(
+ start_date=None,
+ end_date=None,
+ observance=None,
+ days_of_week=None,
+ offset=None,
+):
+ return Holiday(
+ "New Year's Eve",
+ month=12,
+ day=31,
+ start_date=start_date,
+ end_date=end_date,
+ offset=offset,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def epiphany(
+ start_date=None,
+ end_date=None,
+ observance=None,
+ days_of_week=None,
+ offset=None,
+):
+ return Holiday(
+ "Epiphany",
+ month=1,
+ day=6,
+ start_date=start_date,
+ end_date=end_date,
+ offset=offset,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def anzac_day(start_date=None, end_date=None, observance=None, days_of_week=None):
+ return Holiday(
+ "Anzac Day",
+ month=4,
+ day=25,
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def european_labour_day(
+ start_date=None, end_date=None, observance=None, days_of_week=None
+):
+ return Holiday(
+ "Labour Day",
+ month=5,
+ day=1,
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+# Holy Wednesday, Maundy Thursday, Ascension Day, Whit Monday, and Corpus
+# Christi do not take observance as a parameter because they depend on a
+# particular offset, and offset and observance cannot both be passed to a
+# Holiday.
+def holy_wednesday(start_date=None, end_date=None, days_of_week=None):
+ return Holiday(
+ "Holy Wednesday",
+ month=1,
+ day=1,
+ offset=[Easter(), -Day(4)],
+ start_date=start_date,
+ end_date=end_date,
+ days_of_week=days_of_week,
+ )
+
+
+def maundy_thursday(start_date=None, end_date=None, days_of_week=None):
+ return Holiday(
+ "Maundy Thursday",
+ month=1,
+ day=1,
+ offset=[Easter(), -Day(3)],
+ start_date=start_date,
+ end_date=end_date,
+ days_of_week=days_of_week,
+ )
+
+
+def ascension_day(start_date=None, end_date=None):
+ return Holiday(
+ "Ascension Day",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(39)],
+ start_date=start_date,
+ end_date=end_date,
+ )
+
+
+def whit_monday(start_date=None, end_date=None):
+ return Holiday(
+ "Whit Monday",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(50)],
+ start_date=start_date,
+ end_date=end_date,
+ )
+
+
+def corpus_christi(start_date=None, end_date=None):
+ return Holiday(
+ "Corpus Christi",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(60)],
+ start_date=start_date,
+ end_date=end_date,
+ )
+
+
+def midsummer_eve(start_date=None, end_date=None):
+ return Holiday(
+ "Midsummer Eve",
+ month=6,
+ day=19,
+ offset=DateOffset(weekday=FR(1)),
+ start_date=start_date,
+ end_date=end_date,
+ )
+
+
+def saint_peter_and_saint_paul_day(
+ start_date=None, end_date=None, observance=None, days_of_week=None
+):
+ return Holiday(
+ "Saint Peter and Saint Paul Day",
+ month=6,
+ day=29,
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def assumption_day(start_date=None, end_date=None, observance=None, days_of_week=None):
+ return Holiday(
+ "Assumption Day",
+ month=8,
+ day=15,
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def all_saints_day(start_date=None, end_date=None, observance=None, days_of_week=None):
+ return Holiday(
+ "All Saints Day",
+ month=11,
+ day=1,
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def immaculate_conception(
+ start_date=None, end_date=None, observance=None, days_of_week=None
+):
+ return Holiday(
+ "Immaculate Conception",
+ month=12,
+ day=8,
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def christmas_eve(start_date=None, end_date=None, observance=None, days_of_week=None):
+ return Holiday(
+ "Christmas Eve",
+ month=12,
+ day=24,
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def christmas(start_date=None, end_date=None, observance=None, days_of_week=None):
+ return Holiday(
+ "Christmas",
+ month=12,
+ day=25,
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def weekend_christmas(start_date=None, end_date=None, observance=None):
+ """
+ If christmas day is Saturday Monday 27th is a holiday
+ If christmas day is sunday the Tuesday 27th is a holiday
+ """
+ return Holiday(
+ "Weekend Christmas",
+ month=12,
+ day=27,
+ days_of_week=(MONDAY, TUESDAY),
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ )
+
+
+def boxing_day(start_date=None, end_date=None, observance=None, days_of_week=None):
+ return Holiday(
+ "Boxing Day",
+ month=12,
+ day=26,
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ days_of_week=days_of_week,
+ )
+
+
+def weekend_boxing_day(start_date=None, end_date=None, observance=None):
+ """
+ If boxing day is saturday then Monday 28th is a holiday
+ If boxing day is sunday then Tuesday 28th is a holiday
+ """
+ return Holiday(
+ "Weekend Boxing Day",
+ month=12,
+ day=28,
+ days_of_week=(MONDAY, TUESDAY),
+ start_date=start_date,
+ end_date=end_date,
+ observance=observance,
+ )
+
+
+# These dates were initially calculated using the ummalqura Python
+# package (https://pypi.org/project/ummalqura/), and then tweaked
+# to fit Turkey's observance of Eid al-Fitr. Other countries that
+# observe Eid al-Fitr might use slightly different dates
+eid_al_fitr_first_day = pd.to_datetime(
+ [
+ "1981-08-01",
+ "1982-07-21",
+ "1983-07-11",
+ "1984-06-30",
+ "1985-06-19",
+ "1986-06-08",
+ "1987-05-28",
+ "1988-05-16",
+ "1989-05-06",
+ "1990-04-26",
+ "1991-04-15",
+ "1992-04-04",
+ "1993-03-24",
+ "1994-03-13",
+ "1995-03-02",
+ "1996-02-19",
+ "1997-02-08",
+ "1998-01-29",
+ "1999-01-18",
+ "2000-01-08",
+ "2000-12-27",
+ "2001-12-16",
+ "2002-12-05",
+ "2003-11-25",
+ "2004-11-14",
+ "2005-11-03",
+ "2006-10-23",
+ "2007-10-12",
+ "2008-09-30",
+ "2009-09-20",
+ "2010-09-09",
+ "2011-08-30",
+ "2012-08-19",
+ "2013-08-08",
+ "2014-07-28",
+ "2015-07-17",
+ "2016-07-05",
+ "2017-06-25",
+ "2018-06-15",
+ "2019-06-04",
+ "2020-05-24",
+ "2021-05-13",
+ "2022-05-02",
+ "2023-04-21",
+ "2024-04-10",
+ "2025-03-30",
+ "2026-03-20",
+ "2027-03-09",
+ "2028-02-26",
+ "2029-02-14",
+ "2030-02-04",
+ "2031-01-24",
+ "2032-01-14",
+ "2033-01-02",
+ "2033-12-23",
+ "2034-12-12",
+ "2035-12-01",
+ "2036-11-19",
+ "2037-11-08",
+ "2038-10-29",
+ "2039-10-19",
+ "2040-10-07",
+ "2041-09-26",
+ "2042-09-15",
+ "2043-09-04",
+ "2044-08-24",
+ "2045-08-14",
+ "2046-08-03",
+ "2047-07-24",
+ "2048-07-12",
+ "2049-07-01",
+ ]
+)
+
+# These dates were initially calculated using the ummalqura Python
+# package (https://pypi.org/project/ummalqura/), and then tweaked
+# to fit Turkey's observance of Eid al-Adha. Other countries that
+# observe Eid al-Adha might use slightly different dates
+eid_al_adha_first_day = pd.to_datetime(
+ [
+ "1981-10-08",
+ "1982-09-27",
+ "1983-09-17",
+ "1984-09-05",
+ "1985-08-26",
+ "1986-08-15",
+ "1987-08-04",
+ "1988-07-23",
+ "1989-07-13",
+ "1990-07-02",
+ "1991-06-22",
+ "1992-06-11",
+ "1993-05-31",
+ "1994-05-20",
+ "1995-05-09",
+ "1996-04-27",
+ "1997-04-17",
+ "1998-04-07",
+ "1999-03-27",
+ "2000-03-16",
+ "2001-03-05",
+ "2002-02-22",
+ "2003-02-10",
+ "2004-02-01",
+ "2005-01-20",
+ "2006-01-09",
+ "2006-12-31",
+ "2007-12-20",
+ "2008-12-08",
+ "2009-11-27",
+ "2010-11-16",
+ "2011-11-06",
+ "2012-10-25",
+ "2013-10-15",
+ "2014-10-04",
+ "2015-09-24",
+ "2016-09-12",
+ "2017-09-01",
+ "2018-08-21",
+ "2019-08-11",
+ "2020-07-31",
+ "2021-07-20",
+ "2022-07-09",
+ "2023-06-28",
+ "2024-06-16",
+ "2025-06-06",
+ "2026-05-27",
+ "2027-05-16",
+ "2028-05-05",
+ "2029-04-24",
+ "2030-04-13",
+ "2031-04-02",
+ "2032-03-22",
+ "2033-03-11",
+ "2034-03-01",
+ "2035-02-18",
+ "2036-02-07",
+ "2037-01-26",
+ "2038-01-16",
+ "2039-01-05",
+ "2039-12-26",
+ "2040-12-14",
+ "2041-12-04",
+ "2042-11-23",
+ "2043-11-12",
+ "2044-10-31",
+ "2045-10-21",
+ "2046-10-10",
+ "2047-09-30",
+ "2048-09-19",
+ "2049-09-08",
+ ]
+)
+
+
+def orthodox_easter(start_date="1980", end_date="2030"):
+ """
+ This function gives a DatetimeIndex of Orthodox Easter dates from start_date to end_date
+ """
+ return pd.to_datetime(
+ [
+ easter(year, method=EASTER_ORTHODOX)
+ for year in range(int(start_date), int(end_date) + 1)
+ ]
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/ecal.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/ecal.py
new file mode 100644
index 0000000000000000000000000000000000000000..00f140b9afba68844a776ba9ef18c5d5117eafeb
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/ecal.py
@@ -0,0 +1,166 @@
+from __future__ import print_function
+
+import sys
+
+months = [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December",
+]
+
+
+def error(msg):
+ print(msg, file=sys.stderr)
+ exit(-1)
+
+
+def _render_month(calendar, year, month, print_year):
+ import pandas as pd
+
+ if sys.version_info[0] == 2:
+ import StringIO
+
+ out = StringIO.StringIO()
+ else:
+ import io
+
+ out = io.StringIO()
+
+ start = "{year}-{month}".format(year=year, month=month)
+ if month == 12:
+ end = "{year}-{month}".format(year=year + 1, month=1)
+ else:
+ end = "{year}-{month}".format(year=year, month=month + 1)
+
+ days = pd.date_range(start, end, inclusive="left")
+
+ title = months[month - 1]
+ if print_year:
+ title += " {year}".format(year=year)
+
+ print("{title:^28}".format(title=title).rstrip(), file=out)
+ print(" Su Mo Tu We Th Fr Sa", file=out)
+ print(
+ " " * (4 * ((days[0].weekday() + 1) % 7)),
+ end="",
+ file=out,
+ )
+
+ for d in days:
+ if d.weekday() == 6:
+ print("", file=out)
+
+ if calendar.is_session(d):
+ a = b = " "
+ else:
+ a = "["
+ b = "]"
+
+ print(
+ "{a}{d.day:>2}{b}".format(a=a, d=d, b=b),
+ end="",
+ file=out,
+ )
+
+ print("", file=out)
+ return out.getvalue()
+
+
+def _concat_lines(strings, width):
+ as_lines = [string.splitlines() for string in strings]
+ max_lines = max(len(lines) for lines in as_lines)
+ for lines in as_lines:
+ missing_lines = max_lines - len(lines)
+ if missing_lines:
+ lines.extend([" " * width] * missing_lines)
+
+ rows = []
+ for row_parts in zip(*as_lines):
+ row_parts = list(row_parts)
+ for n, row_part in enumerate(row_parts):
+ missing_space = width - len(row_part)
+ if missing_space:
+ row_parts[n] = row_part + " " * missing_space
+
+ rows.append(" ".join(row_parts))
+
+ return "\n".join(row.rstrip() for row in rows)
+
+
+def _int_arg(v, name):
+ try:
+ return int(v)
+ except ValueError:
+ error("%s must be an integer, got: %r" % (name, v))
+
+
+def parse_args(argv):
+ usage = "usage: %s CALENDAR [[[DAY] MONTH] YEAR]" % argv[0]
+
+ if len(argv) == 1 or "--help" in argv or "-h" in argv:
+ error(usage)
+
+ if len(argv) > 1:
+ from exchange_calendars import get_calendar
+
+ try:
+ calendar = get_calendar(argv[1])
+ except Exception as e:
+ error(str(e))
+
+ if len(argv) == 2:
+ import datetime
+
+ now = datetime.datetime.now()
+ year = now.year
+ month = now.month
+ elif len(argv) == 3:
+ year = _int_arg(argv[2], "YEAR")
+ month = None
+ elif len(argv) == 4:
+ month = _int_arg(argv[2], "MONTH")
+ year = _int_arg(argv[3], "YEAR")
+ else:
+ error(usage)
+
+ return calendar, year, month
+
+
+def main(argv=None):
+ """Print a unix-cal like calendar but indicate which days are trading
+ sessions.
+ """
+ if argv is None:
+ argv = sys.argv
+ calendar, year, month = parse_args(argv)
+
+ if month is not None:
+ print(_render_month(calendar, year, month, print_year=True))
+ else:
+ month_strings = [
+ [
+ _render_month(
+ calendar,
+ year,
+ row * 3 + column + 1,
+ print_year=False,
+ )
+ for column in range(3)
+ ]
+ for row in range(4)
+ ]
+ print("{year:^88}\n".format(year=year).rstrip())
+ print("\n\n".join(_concat_lines(cs, 28) for cs in month_strings))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/errors.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/errors.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbf47d9e0d640f20daa057efcd022e2412fd4a76
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/errors.py
@@ -0,0 +1,338 @@
+#
+# Copyright 2015 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from __future__ import annotations
+import typing
+import pandas as pd
+
+if typing.TYPE_CHECKING:
+ from exchange_calendars import ExchangeCalendar
+
+
+class CalendarError(Exception):
+ msg = None
+
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+
+ def __str__(self):
+ msg = self.msg.format(**self.kwargs)
+ return msg
+
+ __unicode__ = __str__
+ __repr__ = __str__
+
+
+class InvalidCalendarName(CalendarError):
+ """
+ Raised when a calendar with an invalid name is requested.
+ """
+
+ msg = "The requested ExchangeCalendar, {calendar_name}, does not exist."
+
+
+class CalendarNameCollision(CalendarError):
+ """
+ Raised when the static calendar registry already has a calendar with a
+ given name.
+ """
+
+ msg = "A calendar with the name {calendar_name} is already registered."
+
+
+class CyclicCalendarAlias(CalendarError):
+ """
+ Raised when calendar aliases form a cycle.
+ """
+
+ msg = "Cycle in calendar aliases: [{cycle}]"
+
+
+class NoSessionsError(CalendarError):
+ """Raised if a requested calendar would have no sessions.
+
+ NoSessionsError should be raised if `get_calendar` `start` and `end`
+ parameters are passed as dates between and inclusive of which there are
+ no sessions for the given calendar.
+ """
+
+ msg = (
+ "The requested ExchangeCalendar, {calendar_name}, cannot be created as"
+ " there would be no sessions between the requested `start` ('{start}')"
+ " and `end` ('{end}') dates."
+ )
+
+
+class NotSessionError(ValueError):
+ """Input does not represent a valid session.
+
+ Raised if parameter expecting a session label receives input that
+ parses correctly (UTC midnight) although is not a session.
+
+ Parameters
+ ----------
+ calendar
+ Calendar for which `ts` assumed as a session.
+
+ ts
+ Timestamp assumed as a session.
+
+ param_name
+ Name of a parameter that was to receive a session label.
+ """
+
+ def __init__(self, calendar: ExchangeCalendar, ts: pd.Timestamp, param_name: str):
+ self.calendar = calendar
+ self.ts = ts
+ self.param_name = param_name
+
+ def __str__(self) -> str:
+ msg = (
+ f"Parameter `{self.param_name}` takes a session"
+ f" although received input that parsed to '{self.ts}' which"
+ )
+
+ if self.ts < self.calendar.first_session:
+ msg += (
+ " is earlier than the first session of calendar"
+ f" '{self.calendar.name}' ('{self.calendar.first_session}')."
+ )
+ elif self.ts > self.calendar.last_session:
+ msg += (
+ " is later than the last session of calendar"
+ f" '{self.calendar.name}' ('{self.calendar.last_session}')."
+ )
+ else:
+ msg += f" is not a session of calendar '{self.calendar.name}'."
+ return msg
+
+
+class DateOutOfBounds(ValueError):
+ """A date required to be within sessions' bounds is not.
+
+ Parameters
+ ----------
+ calendar
+ Calendar for which `date` required to be within sessions'
+ bounds.
+
+ date
+ Date required to be within `calendar`'s sessions' bounds.
+
+ param_name
+ Name of a parameter receiving date.
+ """
+
+ def __init__(self, calendar: ExchangeCalendar, date: pd.Timestamp, param_name: str):
+ self.calendar = calendar
+ self.date = date
+ self.param_name = param_name
+
+ def __str__(self) -> str:
+ msg = f"Parameter `{self.param_name}` receieved as '{self.date}' although"
+ if self.date < self.calendar.first_session:
+ msg += (
+ " cannot be earlier than the first session of calendar"
+ f" '{self.calendar.name}' ('{self.calendar.first_session}')."
+ )
+ elif self.date > self.calendar.last_session:
+ msg += (
+ " cannot be later than the last session of calendar"
+ f" '{self.calendar.name}' ('{self.calendar.last_session}')."
+ )
+ else:
+ assert (
+ self.date < self.calendar.first_session
+ or self.date > self.calendar.last_session
+ )
+ return msg
+
+
+class NotTradingMinuteError(ValueError):
+ """A timestamp assumed as a trading minute is not a trading minute.
+
+ Parameters
+ ----------
+ calendar
+ Calendar for which `minute` assumed as a trading minute.
+
+ minute
+ Minute assumed as a trading minute.
+
+ param_name
+ Name of a parameter that was to receive a trading minute.
+ """
+
+ def __init__(
+ self,
+ calendar: ExchangeCalendar,
+ minute: pd.Timestamp,
+ param_name: str,
+ ):
+ self.calendar = calendar
+ self.minute = minute
+ self.param_name = param_name
+
+ def __str__(self) -> str:
+ msg = (
+ f"Parameter `{self.param_name}` takes a trading minute although"
+ f" received input that parsed to '{self.minute}' which"
+ )
+ if self.minute < self.calendar.first_minute:
+ msg += (
+ " is earlier than the first trading minute of calendar"
+ f" '{self.calendar.name}' ('{self.calendar.first_session}')."
+ )
+ elif self.minute > self.calendar.last_minute:
+ msg += (
+ " is later than the last trading minute of calendar"
+ f" '{self.calendar.name}' ('{self.calendar.last_session}')."
+ )
+ else:
+ msg += f" is not a trading minute of calendar '{self.calendar.name}'."
+ return msg
+
+
+class MinuteOutOfBounds(ValueError):
+ """A minute required to be within bounds of trading minutes is not.
+
+ Parameters
+ ----------
+ calendar
+ Calendar for which `minute` required to be within bounds of
+ trading minutes.
+
+ minute
+ Minute required to be within bounds of `calendar`'s trading
+ minutes.
+
+ param_name
+ Name of a parameter receiving `minute`.
+ """
+
+ def __init__(
+ self, calendar: ExchangeCalendar, minute: pd.Timestamp, param_name: str
+ ):
+ self.calendar = calendar
+ self.minute = minute
+ self.param_name = param_name
+
+ def __str__(self) -> str:
+ msg = f"Parameter `{self.param_name}` receieved as '{self.minute}' although"
+ if self.minute < self.calendar.first_minute:
+ msg += (
+ " cannot be earlier than the first trading minute of calendar"
+ f" '{self.calendar.name}' ('{self.calendar.first_minute}')."
+ )
+ elif self.minute > self.calendar.last_minute:
+ msg += (
+ " cannot be later than the last trading minute of calendar"
+ f" '{self.calendar.name}' ('{self.calendar.last_minute}')."
+ )
+ else:
+ assert (
+ self.minute < self.calendar.first_minute
+ or self.minute > self.calendar.last_minute
+ )
+ return msg
+
+
+class RequestedSessionOutOfBounds(ValueError):
+ """The requested session would fall beyond calendar bounds.
+
+ Parameters
+ ----------
+ calendar
+ Calendar for which session would be out-of-bounds.
+
+ too_early
+ True if requested session would be earlier than the first calendar
+ session.
+ False if requested session would be later than the last calendar
+ session.
+ """
+
+ def __init__(self, calendar: ExchangeCalendar, too_early: bool):
+ self.calendar = calendar
+ self.adverb = "before" if too_early else "after"
+ self.position = "first" if too_early else "last"
+ self.bound = calendar.first_session if too_early else calendar.last_session
+
+ def __str__(self) -> str:
+ return (
+ f"Requested session would fall {self.adverb} the calendar's {self.position}"
+ f" session ('{self.bound}')."
+ )
+
+
+class RequestedMinuteOutOfBounds(ValueError):
+ """The requested trading minute would fall beyond calendar bounds.
+
+ Parameters
+ ----------
+ calendar
+ Calendar for which minute would be out-of-bounds.
+
+ too_early
+ True if requested minute would be earlier than the first calendar
+ minute.
+ False if requested minute would be later than the last calendar
+ minute.
+ """
+
+ def __init__(self, calendar: ExchangeCalendar, too_early: bool):
+ self.calendar = calendar
+ self.adverb = "before" if too_early else "after"
+ self.position = "first" if too_early else "last"
+ self.bound = calendar.first_minute if too_early else calendar.last_minute
+
+ def __str__(self) -> str:
+ return (
+ f"Requested minute would fall {self.adverb} the calendar's {self.position}"
+ f" trading minute ('{self.bound}')."
+ )
+
+
+class IndexOverlapError(ValueError):
+ """Periods implied by indices overlap."""
+
+
+class IntervalsOverlapError(IndexOverlapError):
+ """Intervals of requested trading index would overlap."""
+
+ # pylint: disable=missing-return-type-doc
+ def __str__(self): # noqa: D105
+ return (
+ "Unable to create trading index as intervals would overlap."
+ " This can occur when the frequency is longer than a break or"
+ " the gap between one session's close and the next session's"
+ " open (as reduced by any alignment). To shorten intervals"
+ " that would otherwise overlap either pass `curtail_overlaps`"
+ " as True or pass `force_close` and/or `force_break_close` as True."
+ )
+
+
+class IndicesOverlapError(IndexOverlapError):
+ """Indices of requested trading index would overlap."""
+
+ # pylint: disable=missing-return-type-doc
+ def __str__(self): # noqa: D105
+ return (
+ "Unable to create trading index as an indice would fall to the"
+ " right of (later than) the subsequent indice. This can occur"
+ " when the frequency is longer than a break or the gap between"
+ " one session's close and the next session's open (as reduced"
+ " by any alignment). Consider passing `closed` as `left` or"
+ " passing `force_close` and/or `force_break_close` as True."
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar.py
new file mode 100644
index 0000000000000000000000000000000000000000..e57127ac8447dd84ffc9def40d50f37d1c1479a7
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar.py
@@ -0,0 +1,2953 @@
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from __future__ import annotations
+
+from abc import ABC, abstractmethod
+from calendar import day_name
+import collections
+from collections.abc import Sequence, Callable
+import datetime
+import functools
+import operator
+from typing import TYPE_CHECKING, Literal, Any
+import warnings
+from zoneinfo import ZoneInfo
+
+import numpy as np
+import pandas as pd
+import toolz
+from pandas.tseries.holiday import AbstractHolidayCalendar
+from pandas.tseries.offsets import CustomBusinessDay
+
+from exchange_calendars import errors
+from .calendar_helpers import (
+ UTC,
+ NANOSECONDS_PER_MINUTE,
+ NP_NAT,
+ Date,
+ Minute,
+ Session,
+ TradingMinute,
+ _TradingIndex,
+ compute_minutes,
+ next_divider_idx,
+ one_minute_earlier,
+ one_minute_later,
+ parse_date,
+ parse_session,
+ parse_timestamp,
+ parse_trading_minute,
+ previous_divider_idx,
+)
+from .utils.pandas_utils import days_at_time
+
+if TYPE_CHECKING:
+ from pandas._libs.tslibs.nattype import NaTType
+
+
+GLOBAL_DEFAULT_START = pd.Timestamp.now().floor("D") - pd.DateOffset(years=20)
+# Give an aggressive buffer for logic that needs to use the next trading
+# day or minute.
+GLOBAL_DEFAULT_END = pd.Timestamp.now().floor("D") + pd.DateOffset(years=1)
+
+NANOS_IN_MINUTE = 60000000000
+MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = range(7)
+WEEKDAYS = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY)
+WEEKENDS = (SATURDAY, SUNDAY)
+
+
+def selection(
+ arr: pd.DatetimeIndex, start: pd.Timestamp, end: pd.Timestamp
+) -> pd.DatetimeIndex:
+ predicates = []
+ if start is not None:
+ predicates.append(start <= arr)
+ if end is not None:
+ predicates.append(arr < end)
+
+ if not predicates:
+ return arr
+
+ return arr[np.all(predicates, axis=0)]
+
+
+def _group_times(
+ sessions: pd.DatetimeIndex,
+ times: None | Sequence[tuple[pd.Timestamp | None, datetime.time]],
+ tz: ZoneInfo,
+ offset: int = 0,
+) -> pd.DatetimeIndex | None:
+ """Evaluate standard times for a specific session bound.
+
+ For example, if `times` passed as standard times for session opens then
+ will return a DatetimeIndex describing standard open times for each
+ session.
+ """
+ if times is None:
+ return None
+ elements = [
+ days_at_time(selection(sessions, start, end), time, tz, offset)
+ for (start, time), (end, _) in toolz.sliding_window(
+ 2, toolz.concatv(times, [(None, None)])
+ )
+ ]
+ return elements[0].append(elements[1:])
+
+
+class deprecate:
+ """Decorator for deprecated ExchangeCalendar methods."""
+
+ def __init__(
+ self,
+ deprecated_release: str = "4.0",
+ message: str | None = None,
+ ):
+ self.deprecated_release = "release " + deprecated_release
+ self.message = message
+
+ def __call__(self, f: Callable) -> Callable:
+ @functools.wraps(f)
+ def wrapped_f(*args, **kwargs):
+ warnings.warn(self._message(f), FutureWarning)
+ return f(*args, **kwargs)
+
+ return wrapped_f
+
+ def _message(self, f: Callable) -> str:
+ msg = (
+ f"`{f.__name__}` was deprecated in {self.deprecated_release}"
+ f" and will be removed in a future release."
+ )
+ if self.message is not None:
+ msg += " " + self.message
+ return msg
+
+
+class HolidayCalendar(AbstractHolidayCalendar):
+ def __init__(self, rules):
+ super().__init__(rules=rules)
+
+
+class ExchangeCalendar(ABC):
+ """Representation of timing information of a single market exchange.
+
+ The timing information comprises sessions, open/close times and, for
+ exchanges that observe an intraday break, break_start/break_end times.
+
+ For exchanges that do not observe an intraday break a session
+ represents a contiguous set of minutes. Where an exchange observes
+ an intraday break a session represents two contiguous sets of minutes
+ separated by the intraday break.
+
+ Each session is labeled as the date that the session represents.
+
+ For each session, we store the open and close time together with, for
+ those exchanges with breaks, the break start and break end. All times
+ are defined as UTC.
+
+ Note that a session may start on the day prior to the session label or
+ end on the day following the session label. Such behaviour is common
+ for calendars that represent futures exchanges.
+
+ Parameters
+ ----------
+ start : default: later of 20 years ago or first supported start date.
+ First calendar session will be `start`, if `start` is a session, or
+ first session after `start`. Cannot be earlier than any date
+ returned by class method `bound_min`.
+
+ end : default: earliest of 1 year from 'today' or last supported end
+ date. Last calendar session will be `end`, if `end` is a session,
+ or last session before `end`. Cannot be later than any date
+ returned by class method `bound_max`.
+
+ side : default: "left"
+ Define which of session open/close and break start/end should
+ be treated as a trading minute:
+ "left" - treat session open and break_start as trading minutes,
+ do not treat session close or break_end as trading minutes.
+ "right" - treat session close and break_end as trading minutes,
+ do not treat session open or break_start as tradng minutes.
+ "both" - treat all of session open, session close, break_start
+ and break_end as trading minutes.
+ "neither" - treat none of session open, session close,
+ break_start or break_end as trading minutes.
+
+ Raises
+ ------
+ ValueError
+ If `start` is earlier than the earliest supported start date.
+ If `end` is later than the latest supported end date.
+ If `start` parses to a later date than `end`.
+
+ Notes
+ -----
+ Exchange calendars were originally defined for the Zipline package from
+ Quantopian under the package 'trading_calendars'. Since 2021 they have
+ been maintained under the 'exchange_calendars' package (a fork of
+ 'trading_calendars') by an active community of contributing users.
+
+ Some calendars have defined start and end bounds within which
+ contributors have endeavoured to ensure the calendar's accuracy and
+ outside of which the calendar would not be accurate. These bounds
+ are enforced such that passing `start` or `end` as dates that are
+ out-of-bounds will raise a ValueError. The bounds of each calendar are
+ exposed via the `bound_min` and `bound_max` class methods.
+
+ Many calendars do not have bounds defined (in these cases `bound_min`
+ and/or `bound_max` return None). These calendars can be created through
+ any date range although it should be noted that the earlier the start
+ date, the greater the potential for inaccuracies.
+
+ In all cases, no guarantees are offered as to the accuracy of any
+ calendar.
+
+
+ -- Internal method parameters --
+
+ _parse: bool
+ Determines if a `minute` or `session` parameter should be
+ parsed (default True). Passed as False:
+ - internally to prevent double parsing.
+ - by tests for efficiency.
+ """
+
+ _LEFT_SIDES = ["left", "both"]
+ _RIGHT_SIDES = ["right", "both"]
+
+ @classmethod
+ def bound_min(cls) -> pd.Timestamp | None:
+ """Earliest date from which calendar can be constructed.
+
+ Returns
+ -------
+ pd.Timestamp or None
+ Earliest date from which calendar can be constructed. Must be
+ timezone naive. None if no limit.
+
+ Notes
+ -----
+ To impose a constraint on the earliest date from which a calendar
+ can be constructed subclass should override this method and
+ optionally override `_bound_min_error_msg`.
+ """
+ return None
+
+ @classmethod
+ def bound_max(cls) -> pd.Timestamp | None:
+ """Latest date to which calendar can be constructed.
+
+ Returns
+ -------
+ pd.Timestamp or None
+ Latest date to which calendar can be constructed. Must be
+ timezone naive. None if no limit.
+
+ Notes
+ -----
+ To impose a constraint on the latest date to which a calendar can
+ be constructed subclass should override this method and optionally
+ override `_bound_max_error_msg`.
+ """
+ return None
+
+ @classmethod
+ def default_start(cls) -> pd.Timestamp:
+ """Return default calendar start date.
+
+ Calendar will start from this date if 'start' is not otherwise
+ passed to the constructor.
+ """
+ bound_min = cls.bound_min()
+ if bound_min is None:
+ return GLOBAL_DEFAULT_START
+ else:
+ return max(GLOBAL_DEFAULT_START, bound_min)
+
+ @classmethod
+ def default_end(cls) -> pd.Timestamp:
+ """Return default calendar end date.
+
+ Calendar will end at this date if 'end' is not otherwise passed to
+ the constructor.
+ """
+ bound_max = cls.bound_max()
+ if bound_max is None:
+ return GLOBAL_DEFAULT_END
+ else:
+ return min(GLOBAL_DEFAULT_END, bound_max)
+
+ def __init__(
+ self,
+ start: Date | None = None,
+ end: Date | None = None,
+ side: Literal["left", "right", "both", "neither"] = "left",
+ ):
+ if side not in self.valid_sides():
+ raise ValueError(
+ f"`side` must be in {self.valid_sides()} although received as {side}."
+ )
+ self._side = side
+
+ if start is None:
+ start = self.default_start()
+ else:
+ start = parse_date(start, "start", raise_oob=False)
+ bound_min = self.bound_min()
+ if bound_min is not None and start < bound_min:
+ raise ValueError(self._bound_min_error_msg(start))
+
+ if end is None:
+ end = self.default_end()
+ else:
+ end = parse_date(end, "end", raise_oob=False)
+ bound_max = self.bound_max()
+ if bound_max is not None and end > bound_max:
+ raise ValueError(self._bound_max_error_msg(end))
+
+ if start >= end:
+ raise ValueError(
+ "`start` must be earlier than `end` although `start` parsed as"
+ f" '{start}' and `end` as '{end}'."
+ )
+
+ _all_days = pd.date_range(start, end, freq=self.day) # session labels
+ if _all_days.empty:
+ raise errors.NoSessionsError(calendar_name=self.name, start=start, end=end)
+
+ # DatetimeIndex of standard times for each day.
+ self._opens = _group_times(
+ _all_days,
+ self.open_times,
+ self.tz,
+ self.open_offset,
+ )
+ self._break_starts = _group_times(
+ _all_days,
+ self.break_start_times,
+ self.tz,
+ )
+ self._break_ends = _group_times(
+ _all_days,
+ self.break_end_times,
+ self.tz,
+ )
+ self._closes = _group_times(
+ _all_days,
+ self.close_times,
+ self.tz,
+ self.close_offset,
+ )
+
+ # Apply any special offsets first
+ self.apply_special_offsets(_all_days, start, end)
+
+ # Series mapping sessions with non-standard opens/closes.
+ _special_opens = self._calculate_special_opens(start, end)
+ _special_closes = self._calculate_special_closes(start, end)
+
+ # Overwrite the special opens and closes on top of the standard ones.
+ _overwrite_special_dates(_all_days, self._opens, _special_opens)
+ _overwrite_special_dates(_all_days, self._closes, _special_closes)
+ _remove_breaks_for_special_dates(_all_days, self._break_starts, _special_closes)
+ _remove_breaks_for_special_dates(_all_days, self._break_ends, _special_closes)
+
+ break_starts = None if self._break_starts is None else self._break_starts
+ break_ends = None if self._break_ends is None else self._break_ends
+ self.schedule = pd.DataFrame(
+ index=_all_days,
+ data=collections.OrderedDict(
+ [
+ ("open", self._opens),
+ ("break_start", break_starts),
+ ("break_end", break_ends),
+ ("close", self._closes),
+ ]
+ ),
+ dtype="datetime64[ns, UTC]",
+ )
+
+ self.opens_nanos = self.schedule.open.values.astype(np.int64)
+ self.break_starts_nanos = self.schedule.break_start.values.astype(np.int64)
+ self.break_ends_nanos = self.schedule.break_end.values.astype(np.int64)
+ self.closes_nanos = self.schedule.close.values.astype(np.int64)
+
+ _check_breaks_match(self.break_starts_nanos, self.break_ends_nanos)
+
+ self._late_opens = _special_opens.index
+ self._early_closes = _special_closes.index
+
+ # --------------- Calendar definition methods/properties --------------
+ # Methods and properties in this section should be overriden or
+ # extended by subclass if and as required.
+
+ @property
+ @abstractmethod
+ def name(self) -> str:
+ """Calendar name."""
+ raise NotImplementedError()
+
+ def _bound_min_error_msg(self, start: pd.Timestamp) -> str:
+ """Return error message to handle `start` being out-of-bounds.
+
+ See Also
+ --------
+ bound_min
+ """
+ return (
+ f"The earliest date from which calendar {self.name} can be"
+ f" evaluated is {self.bound_min()}, although received `start` as"
+ f" {start}."
+ )
+
+ def _bound_max_error_msg(self, end: pd.Timestamp) -> str:
+ """Return error message to handle `end` being out-of-bounds.
+
+ See Also
+ --------
+ bound_max
+ """
+ return (
+ f"The latest date to which calendar {self.name} can be evaluated"
+ f" is {self.bound_max()}, although received `end` as {end}."
+ )
+
+ @property
+ @abstractmethod
+ def tz(self) -> ZoneInfo:
+ """Calendar timezone."""
+ raise NotImplementedError()
+
+ @property
+ @abstractmethod
+ def open_times(self) -> Sequence[tuple[pd.Timestamp | None, datetime.time]]:
+ """Local open time(s).
+
+ Returns
+ -------
+ Sequence[tuple[pd.Timestamp | None, datetime.time]]:
+ Sequence of tuples representing (start_date, open_time) where:
+ start_date: date from which `open_time` applies. Must be
+ timezone-naive. None for first item.
+ open_time: exchange's local open time.
+
+ Notes
+ -----
+ Examples for concreting `open_times` on a subclass.
+
+ Example where open time is constant throughout period covered by
+ calendar:
+ open_times = ((None, datetime.time(9)),)
+
+ Example where open times have varied over period covered by
+ calendar:
+ open_times = (
+ (None, time(9, 30)),
+ (pd.Timestamp("1978-04-01"), datetime.time(10, 0)),
+ (pd.Timestamp("1986-04-01"), datetime.time(9, 40)),
+ (pd.Timestamp("1995-01-01"), datetime.time(9, 30)),
+ (pd.Timestamp("1998-12-07"), datetime.time(9, 0)),
+ )
+ """
+ raise NotImplementedError()
+
+ @property
+ def break_start_times(
+ self,
+ ) -> None | Sequence[tuple[pd.Timestamp | None, datetime.time]]:
+ """Local break start time(s).
+
+ As `close_times` although times represent the close of the morning
+ subsession. None if exchange does not observe a break.
+ """
+ return None
+
+ @property
+ def break_end_times(
+ self,
+ ) -> None | Sequence[tuple[pd.Timestamp | None, datetime.time]]:
+ """Local break end time(s).
+
+ As `open_times` although times represent the open of the afternoon
+ subsession. None if exchange does not observe a break.
+ """
+ return None
+
+ @property
+ @abstractmethod
+ def close_times(self) -> Sequence[tuple[pd.Timestamp | None, datetime.time]]:
+ """Local close time(s).
+
+ Returns
+ -------
+ Sequence[tuple[pd.Timestamp | None, datetime.time]]:
+ Sequence of tuples representing (start_date, close_time) where:
+ start_date: date from which `close_time` applies. Must be
+ timezone naive. None for first item.
+ close_time: exchange's local close time.
+
+ Notes
+ -----
+ Examples for concreting `close_times` on a subclass.
+
+ Example where close time is constant throughout period covered by
+ calendar:
+ close_times = ((None, time(17, 30)),)
+
+ Example where close times have varied over period covered by
+ calendar:
+ close_times = (
+ (None, datetime.time(17, 30)),
+ (pd.Timestamp("1986-04-01"), datetime.time(17, 20)),
+ (pd.Timestamp("1995-01-01"), datetime.time(17, 0)),
+ (pd.Timestamp("2016-08-01"), datetime.time(17, 30)),
+ )
+ """
+ raise NotImplementedError()
+
+ @property
+ def weekmask(self) -> str:
+ """Indicator of weekdays on which the exchange is open.
+
+ Default is '1111100' (i.e. Monday-Friday).
+
+ See Also
+ --------
+ numpy.busdaycalendar
+ """
+ return "1111100"
+
+ @property
+ def open_offset(self) -> int:
+ """Day offset of open time(s) relative to session.
+
+ Returns
+ -------
+ int
+ 0 if the date components of local open times are as the
+ corresponding session labels.
+
+ -1 if the date components of local open times are the day
+ before the corresponding session labels.
+ """
+ return 0
+
+ @property
+ def close_offset(self) -> int:
+ """Day offset of close time(s) relative to session.
+
+ Returns
+ -------
+ int
+ 0 if the date components of local close times are as the
+ corresponding session labels.
+
+ 1 if the date components of local close times are the day
+ after the corresponding session labels.
+ """
+ return 0
+
+ @property
+ def regular_holidays(self) -> HolidayCalendar | None:
+ """Holiday calendar representing calendar's regular holidays."""
+ return None
+
+ @property
+ def adhoc_holidays(self) -> list[pd.Timestamp]:
+ """List of non-regular holidays.
+
+ Returns
+ -------
+ list[pd.Timestamp]
+ List of tz-naive timestamps representing non-regular holidays.
+ """
+ return []
+
+ @property
+ def special_opens(self) -> list[tuple[datetime.time, HolidayCalendar] | int]:
+ """Regular non-standard open times.
+
+ Example of what would be defined as a special open:
+ "EVERY YEAR on national lie-in day the exchange opens
+ at 13:00 rather than the standard 09:00".
+
+ "Every Monday the exchange opens late, at 10:30 rather than
+ the standard 09:00".
+
+ Returns
+ -------
+ list[tuple[datetime.time, HolidayCalendar | int]]:
+ list of tuples each describing a regular non-standard open:
+ [0] datetime.time: regular non-standard open time.
+
+ [1] Describes dates with regular non-standard open time
+ as [0]. As either:
+ HolidayCalendar: defines annual dates by rules.
+
+ int : integer defines a weekday with a regular
+ non-standard open (0 - Monday, ..., 6 - Sunday).
+
+ The same date may be described by more than one tuple, for
+ example, if a late open on an annual holiday coincides with
+ a weekday late open. In this case the time assigned to the
+ date will be that defined by the tuple with the lowest index
+ in the returned list.
+ """
+ return []
+
+ @property
+ def special_opens_adhoc(
+ self,
+ ) -> list[tuple[datetime.time, pd.DatetimeIndex]]:
+ """Adhoc non-standard open times.
+
+ Defines non-standard open times that cannot be otherwise codified
+ within within `special_opens`.
+
+ Example of an event to define as an adhoc special open:
+ "On 2022-02-14 due to a typhoon the exchange opened at 13:00,
+ rather than the standard 09:00".
+
+ Returns
+ -------
+ list[tuple[datetime.time, pd.DatetimeIndex]]:
+ List of tuples each describing an adhoc non-standard open time:
+ [0] datetime.time: non-standard open time.
+
+ [1] pd.DatetimeIndex: date or dates corresponding with the
+ non-standard open time. (Must be timezone-naive.)
+ """
+ return []
+
+ @property
+ def special_closes(self) -> list[tuple[datetime.time, HolidayCalendar | int]]:
+ """Regular non-standard close times.
+
+ Examples of what would be defined as a special close:
+ "On christmas eve the exchange closes at 14:00 rather than
+ the standard 17:00".
+
+ "Every Friday the exchange closes early, at 14:00 rather than
+ the standard 17:00".
+
+ Returns
+ -------
+ list[tuple[datetime.time, HolidayCalendar | int]]:
+ list of tuples each describing a regular non-standard close:
+ [0] datetime.time: regular non-standard close time.
+
+ [1] Describes dates with regular non-standard close time
+ as [0]. As either:
+ HolidayCalendar: defines annual dates by rules.
+
+ int : integer defines a weekday with a regular
+ non-standard close (0 - Monday, ..., 6 - Sunday).
+
+ The same date may be described by more than one tuple, for
+ example, if an early close on an annual holiday coincides with
+ a weekday early close. In this case the time assigned to the
+ date will be that defined by the tuple with the lowest index
+ in the returned list.
+ """
+ return []
+
+ @property
+ def special_closes_adhoc(
+ self,
+ ) -> list[tuple[datetime.time, pd.DatetimeIndex]]:
+ """Adhoc non-standard close times.
+
+ Defines non-standard close times that cannot be otherwise codified
+ within within `special_closes`.
+
+ Example of an event to define as an adhoc special close:
+ "On 2022-02-19 due to a typhoon the exchange closed at 12:00,
+ rather than the standard 16:00".
+
+ Returns
+ -------
+ list[tuple[datetime.time, pd.DatetimeIndex]]:
+ List of tuples each describing an adhoc non-standard close
+ time:
+ [0] datetime.time: non-standard close time.
+
+ [1] pd.DatetimeIndex: date or dates corresponding with the
+ non-standard close time. (Must be timezone-naive.)
+ """
+ return []
+
+ def apply_special_offsets(
+ self, sessions: pd.DatetimeIndex, start: pd.Timestamp, end: pd.Timestamp
+ ) -> None:
+ """Hook for subclass to apply changes.
+
+ Method executed by constructor prior to overwritting special dates.
+
+ Parameters
+ ----------
+ sessions
+ All calendar sessions.
+
+ start
+ Date from which special offsets to be applied.
+
+ end
+ Date through which special offsets to be applied.
+
+ Notes
+ -----
+ Incorporated to provide hook to `exchange_calendar_xkrx`.
+ """
+ return None
+
+ # ------------------------------------------------------------------
+ # -- NO method below this line should be overriden on a subclass! --
+ # ------------------------------------------------------------------
+
+ # Methods and properties that define calendar (continued...).
+
+ @functools.cached_property
+ def day(self) -> CustomBusinessDay:
+ """CustomBusinessDay instance representing calendar sessions."""
+ return CustomBusinessDay(
+ holidays=self.adhoc_holidays,
+ calendar=self.regular_holidays,
+ weekmask=self.weekmask,
+ )
+
+ @classmethod
+ def valid_sides(cls) -> list[str]:
+ """List of valid `side` options."""
+ if cls.close_times == cls.open_times:
+ return ["left", "right"]
+ else:
+ return ["both", "left", "right", "neither"]
+
+ @property
+ def side(self) -> Literal["left", "right", "both", "neither"]:
+ """Side on which sessions are closed.
+
+ Returns
+ -------
+ str
+ "left" - Session open and break_start are trading minutes.
+ Session close and break_end are not trading minutes.
+ "right" - Session close and break_end are trading minutes,
+ Session open and break_start are not tradng minutes.
+ "both" - Session open, session close, break_start and
+ break_end are all trading minutes.
+ "neither" - Session open, session close, break_start and
+ break_end are all not trading minutes.
+
+ Notes
+ -----
+ Subclasses should NOT override this method.
+ """
+ return self._side
+
+ # Properties covering all sessions.
+
+ @property
+ def sessions(self) -> pd.DatetimeIndex:
+ """All calendar sessions."""
+ return self.schedule.index
+
+ @functools.cached_property
+ def sessions_nanos(self) -> np.ndarray:
+ """All calendar sessions as nano seconds."""
+ return self.sessions.values.astype("int64")
+
+ @property
+ def opens(self) -> pd.Series:
+ """Open time of each session.
+
+ Returns
+ -------
+ pd.Series
+ index : pd.DatetimeIndex
+ All sessions.
+ dtype : datetime64[ns, UTC]
+ UTC open time of corresponding session.
+ """
+ return self.schedule.open
+
+ @property
+ def closes(self) -> pd.Series:
+ """Close time of each session.
+
+ Returns
+ -------
+ pd.Series
+ index : pd.DatetimeIndex
+ All sessions.
+ dtype : datetime64[ns, UTC]
+ UTC close time of corresponding session.
+ """
+ return self.schedule.close
+
+ @property
+ def break_starts(self) -> pd.Series:
+ """Break start time of each session.
+
+ Returns
+ -------
+ pd.Series
+ index : pd.DatetimeIndex
+ All sessions.
+ dtype : datetime64[ns, UTC]
+ UTC break-start time of corresponding session. Value is
+ missing (pd.NaT) for any session that does not have a
+ break.
+ """
+ return self.schedule.break_start
+
+ @property
+ def break_ends(self) -> pd.Series:
+ """Break end time of each session.
+
+ Returns
+ -------
+ pd.Series
+ index : pd.DatetimeIndex
+ All sessions.
+ dtype : datetime64[ns, UTC]
+ UTC break-end time of corresponding session.Value is
+ missing (pd.NaT) for any session that does not have a
+ break.
+ """
+ return self.schedule.break_end
+
+ @functools.cached_property
+ def first_minutes_nanos(self) -> np.ndarray:
+ """Each session's first minute as an integer."""
+ if self.side in self._LEFT_SIDES:
+ return self.opens_nanos
+ else:
+ return one_minute_later(self.opens_nanos)
+
+ @functools.cached_property
+ def last_minutes_nanos(self) -> np.ndarray:
+ """Each session's last minute as an integer."""
+ if self.side in self._RIGHT_SIDES:
+ return self.closes_nanos
+ else:
+ return one_minute_earlier(self.closes_nanos)
+
+ @functools.cached_property
+ def last_am_minutes_nanos(self) -> np.ndarray:
+ """Each morning subsessions's last minute as an integer."""
+ if self.side in self._RIGHT_SIDES:
+ return self.break_starts_nanos
+ else:
+ return one_minute_earlier(self.break_starts_nanos)
+
+ @functools.cached_property
+ def first_pm_minutes_nanos(self) -> np.ndarray:
+ """Each afternoon subsessions's first minute as an integer."""
+ if self.side in self._LEFT_SIDES:
+ return self.break_ends_nanos
+ else:
+ return one_minute_later(self.break_ends_nanos)
+
+ def _minutes_as_series(self, nanos: np.ndarray, name: str) -> pd.Series:
+ """Convert trading minute nanos to pd.Series."""
+ ser = pd.Series(pd.DatetimeIndex(nanos, tz=UTC), index=self.sessions)
+ ser.name = name
+ return ser
+
+ @property
+ def first_minutes(self) -> pd.Series:
+ """First trading minute of each session."""
+ return self._minutes_as_series(self.first_minutes_nanos, "first_minutes")
+
+ @property
+ def last_minutes(self) -> pd.Series:
+ """Last trading minute of each session."""
+ return self._minutes_as_series(self.last_minutes_nanos, "last_minutes")
+
+ @property
+ def last_am_minutes(self) -> pd.Series:
+ """Last am trading minute of each session."""
+ return self._minutes_as_series(self.last_am_minutes_nanos, "last_am_minutes")
+
+ @property
+ def first_pm_minutes(self) -> pd.Series:
+ """First pm trading minute of each session."""
+ return self._minutes_as_series(self.first_pm_minutes_nanos, "first_pm_minutes")
+
+ # Properties covering all minutes.
+
+ def _minutes(
+ self, side: Literal["left", "right", "both", "neither"]
+ ) -> pd.DatetimeIndex:
+ return pd.DatetimeIndex(
+ compute_minutes(
+ self.opens_nanos,
+ self.break_starts_nanos,
+ self.break_ends_nanos,
+ self.closes_nanos,
+ side,
+ ),
+ tz=UTC,
+ )
+
+ @functools.cached_property
+ def minutes(self) -> pd.DatetimeIndex:
+ """All trading minutes."""
+ return self._minutes(self.side)
+
+ @functools.cached_property
+ def minutes_nanos(self) -> np.ndarray:
+ """All trading minutes as nanoseconds."""
+ return self.minutes.values.astype(np.int64)
+
+ # Calendar properties.
+
+ @property
+ def first_session(self) -> pd.Timestamp:
+ """First calendar session."""
+ return self.sessions[0]
+
+ @property
+ def last_session(self) -> pd.Timestamp:
+ """Last calendar session."""
+ return self.sessions[-1]
+
+ @property
+ def first_session_open(self) -> pd.Timestamp:
+ """Open time of calendar's first session."""
+ return self.opens.iloc[0]
+
+ @property
+ def last_session_close(self) -> pd.Timestamp:
+ """Close time of calendar's last session."""
+ return self.closes.iloc[-1]
+
+ @property
+ def first_minute(self) -> pd.Timestamp:
+ """Calendar's first trading minute."""
+ return pd.Timestamp(self.minutes_nanos[0], tz=UTC)
+
+ @property
+ def last_minute(self) -> pd.Timestamp:
+ """Calendar's last trading minute."""
+ return pd.Timestamp(self.minutes_nanos[-1], tz=UTC)
+
+ @property
+ def has_break(self) -> bool:
+ """Query if any calendar session has a break."""
+ return self.sessions_has_break(
+ self.first_session, self.last_session, _parse=False
+ )
+
+ @property
+ def late_opens(self) -> pd.DatetimeIndex:
+ """Sessions that open later than the prevailing normal open.
+
+ NB. Prevailing normal open as defined by `open_times`.
+ """
+ return self._late_opens
+
+ @property
+ def early_closes(self) -> pd.DatetimeIndex:
+ """Sessions that close earlier than the prevailing normal close.
+
+ NB. Prevailing normal close as defined by `close_times`.
+ """
+ return self._early_closes
+
+ # Methods that interrogate a given session.
+
+ def _get_session_idx(self, session: Date, _parse=True) -> int:
+ """Index position of a session."""
+ session_ = parse_session(self, session) if _parse else session
+ if TYPE_CHECKING:
+ assert isinstance(session_, pd.Timestamp)
+ return self.sessions_nanos.searchsorted(session_.value, side="left")
+
+ def session_open(self, session: Session, _parse: bool = True) -> pd.Timestamp:
+ """Return open time for a given session."""
+ if _parse:
+ session = parse_session(self, session, "session")
+ return self.schedule.at[session, "open"]
+
+ def session_close(self, session: Session, _parse: bool = True) -> pd.Timestamp:
+ """Return close time for a given session."""
+ if _parse:
+ session = parse_session(self, session, "session")
+ return self.schedule.at[session, "close"]
+
+ def session_break_start(
+ self, session: Session, _parse: bool = True
+ ) -> pd.Timestamp | NaTType:
+ """Return break-start time for a given session.
+
+ Returns pd.NaT if no break.
+ """
+ if _parse:
+ session = parse_session(self, session, "session")
+ break_start = self.schedule.at[session, "break_start"]
+ return break_start
+
+ def session_break_end(
+ self, session: Session, _parse: bool = True
+ ) -> pd.Timestamp | NaTType:
+ """Return break-end time for a given session.
+
+ Returns pd.NaT if no break.
+ """
+ if _parse:
+ session = parse_session(self, session, "session")
+ break_end = self.schedule.at[session, "break_end"]
+ return break_end
+
+ def session_open_close(
+ self, session: Session, _parse: bool = True
+ ) -> tuple[pd.Timestamp, pd.Timestamp]:
+ """Return open and close times for a given session.
+
+ Parameters
+ ----------
+ session
+ Session for which require open and close.
+
+ Returns
+ -------
+ tuple[pd.Timestamp, pd.Timestamp]
+ [0] Open time of `session`.
+ [1] Close time of `session`.
+ """
+ if _parse:
+ session = parse_session(self, session)
+ return self.session_open(session), self.session_close(session)
+
+ def session_break_start_end(
+ self, session: Session, _parse: bool = True
+ ) -> tuple[pd.Timestamp | NaTType, pd.Timestamp | NaTType]:
+ """Return break-start and break-end times for a given session.
+
+ Parameters
+ ----------
+ session
+ Session for which require break-start and break-end.
+
+ Returns
+ -------
+ tuple[pd.Timestamp | NaTType, pd.Timestamp | NaTType]
+ [0] Break-start time of `session`, or pd.NaT if no break.
+ [1] Close time of `session`, or pd.NaT if no break.
+ """
+ if _parse:
+ session = parse_session(self, session)
+ return self.session_break_start(session), self.session_break_end(session)
+
+ def _get_session_minute_from_nanos(
+ self, session: Session, nanos: np.ndarray, _parse: bool
+ ) -> pd.Timestamp:
+ idx = self._get_session_idx(session, _parse=_parse)
+ return pd.Timestamp(nanos[idx], tz=UTC)
+
+ def session_first_minute(
+ self, session: Session, _parse: bool = True
+ ) -> pd.Timestamp:
+ """Return first trading minute of a given session."""
+ nanos = self.first_minutes_nanos
+ return self._get_session_minute_from_nanos(session, nanos, _parse)
+
+ def session_last_minute(
+ self, session: Session, _parse: bool = True
+ ) -> pd.Timestamp:
+ """Return last trading minute of a given session."""
+ nanos = self.last_minutes_nanos
+ return self._get_session_minute_from_nanos(session, nanos, _parse)
+
+ def session_last_am_minute(
+ self, session: Session, _parse: bool = True
+ ) -> pd.Timestamp | pd.NaT:
+ """Return last trading minute of am subsession of a given session."""
+ nanos = self.last_am_minutes_nanos
+ return self._get_session_minute_from_nanos(session, nanos, _parse)
+
+ def session_first_pm_minute(
+ self, session: Session, _parse: bool = True
+ ) -> pd.Timestamp | pd.NaT:
+ """Return first trading minute of pm subsession of a given session."""
+ nanos = self.first_pm_minutes_nanos
+ return self._get_session_minute_from_nanos(session, nanos, _parse)
+
+ def session_first_last_minute(
+ self,
+ session: Session,
+ _parse: bool = True,
+ ) -> tuple[pd.Timestamp, pd.Timestamp]:
+ """Return first and last trading minutes of a given session."""
+ idx = self._get_session_idx(session, _parse=_parse)
+ first = pd.Timestamp(self.first_minutes_nanos[idx], tz=UTC)
+ last = pd.Timestamp(self.last_minutes_nanos[idx], tz=UTC)
+ return (first, last)
+
+ def session_has_break(self, session: Session, _parse: bool = True) -> bool:
+ """Query if a given session has a break.
+
+ Parameters
+ ----------
+ session
+ Session to query.
+
+ Returns
+ -------
+ bool
+ True if `session` has a break, false otherwise.
+ """
+ if _parse:
+ session = parse_session(self, session)
+ return pd.notna(self.session_break_start(session))
+
+ def next_session(self, session: Session, _parse: bool = True) -> pd.Timestamp:
+ """Return session that immediately follows a given session.
+
+ Parameters
+ ----------
+ session
+ Session whose next session is desired.
+
+ Raises
+ ------
+ errors.RequestedSessionOutOfBounds
+ If `session` is the last calendar session.
+
+ See Also
+ --------
+ date_to_session
+ """
+ idx = self._get_session_idx(session, _parse=_parse)
+ try:
+ return self.schedule.index[idx + 1]
+ except IndexError:
+ if idx == len(self.schedule.index) - 1:
+ raise errors.RequestedSessionOutOfBounds(self, False) from None
+ else:
+ raise
+
+ def previous_session(self, session: Session, _parse: bool = True) -> pd.Timestamp:
+ """Return session that immediately preceeds a given session.
+
+ Parameters
+ ----------
+ session
+ Session whose previous session is desired.
+
+ Raises
+ ------
+ errors.RequestedSessionOutOfBounds
+ If `session` is the first calendar session.
+
+ See Also
+ --------
+ date_to_session
+ """
+ idx = self._get_session_idx(session, _parse=_parse)
+ if not idx:
+ raise errors.RequestedSessionOutOfBounds(self, True)
+ return self.schedule.index[idx - 1]
+
+ def session_minutes(
+ self, session: Session, _parse: bool = True
+ ) -> pd.DatetimeIndex:
+ """Return trading minutes corresponding to a given session.
+
+ Parameters
+ ----------
+ session
+ Session for which require trading minutes.
+
+ Returns
+ -------
+ pd.DateTimeIndex
+ Trading minutes for `session`.
+ """
+ first, last = self.session_first_last_minute(session, _parse=_parse)
+ return self.minutes_in_range(start=first, end=last)
+
+ def session_offset(
+ self, session: Session, count: int, _parse: bool = True
+ ) -> pd.Timestamp:
+ """Offset a given session by a number of sessions.
+
+ Parameters
+ ----------
+ session
+ Session from which to offset.
+
+ count
+ Number of sessions to offset `session`. Positive to offset
+ forwards, negative to offset backwards.
+
+ Returns
+ -------
+ pd.Timestamp
+ Offset session.
+
+ Raises
+ ------
+ exchange_calendars.errors.RequestedSessionOutOfBounds
+ If offset session would be either before the calendar's first
+ session or after the calendar's last session.
+ """
+ idx = self._get_session_idx(session, _parse=_parse) + count
+ if idx >= len(self.sessions):
+ raise errors.RequestedSessionOutOfBounds(self, too_early=False)
+ elif idx < 0:
+ raise errors.RequestedSessionOutOfBounds(self, too_early=True)
+ return self.sessions[idx]
+
+ # Methods that interrogate a date.
+
+ def _get_date_idx(self, date: Date, _parse=True) -> int:
+ """Index position of a date.
+
+ Returns
+ -------
+ Index position of session if `date` represents a session,
+ otherwise index position of session that immediately
+ follows `date`.
+ """
+ date_ = parse_date(date, "date", self) if _parse else date
+ if TYPE_CHECKING:
+ assert isinstance(date_, pd.Timestamp)
+ return self.sessions_nanos.searchsorted(date_.value, side="left")
+
+ def _date_oob(self, date: pd.Timestamp) -> bool:
+ """Is `date` out-of-bounds."""
+ return (
+ date.value < self.sessions_nanos[0] or date.value > self.sessions_nanos[-1]
+ )
+
+ def is_session(self, date: Date, _parse: bool = True) -> bool:
+ """Query if a date is a valid session.
+
+ Parameters
+ ----------
+ date
+ Date to be queried.
+
+ Return
+ ------
+ bool
+ True if `date` is a session, False otherwise.
+ """
+ if _parse:
+ date = parse_date(date, "date", self)
+ idx = self._get_date_idx(date, _parse=False)
+ return bool(self.sessions_nanos[idx] == date.value) # convert from np.bool_
+
+ def date_to_session(
+ self,
+ date: Date,
+ direction: Literal["next", "previous", "none"] = "none",
+ _parse: bool = True,
+ ) -> pd.Timestamp:
+ """Return a session corresponding to a given date.
+
+ Parameters
+ ----------
+ date
+ Date for which require session. Can be a date that does not
+ represent an actual session (see `direction`).
+
+ direction : default: "none"
+ Defines behaviour if `date` does not represent a session:
+ "next" - return first session following `date`.
+ "previous" - return first session prior to `date`.
+ "none" - raise ValueError.
+
+ See Also
+ --------
+ next_session
+ previous_session
+ """
+ if _parse:
+ date = parse_date(date, calendar=self)
+ if self.is_session(date, _parse=False):
+ return date
+ elif direction in ["next", "previous"]:
+ idx = self._get_date_idx(date, _parse=False)
+ if direction == "previous":
+ idx -= 1
+ return self.sessions[idx]
+ elif direction == "none":
+ raise ValueError(
+ f"`date` '{date}' does not represent a session. Consider passing"
+ " a `direction`."
+ )
+ else:
+ raise ValueError(
+ f"'{direction}' is not a valid `direction`. Valid `direction`"
+ ' values are "next", "previous" and "none".'
+ )
+
+ # Methods that interrogate a given minute (trading or non-trading).
+
+ def _get_minute_idx(self, minute: Minute, _parse=True) -> int:
+ """Index position of a minute.
+
+ Returns
+ -------
+ Index position of trading minute if `minute` represents a
+ trading minute, otherwise index position of trading
+ minute that immediately follows `minute`.
+ """
+ if _parse:
+ minute = parse_timestamp(minute, "minute", self)
+ return self.minutes_nanos.searchsorted(minute.value, side="left")
+
+ def _minute_oob(self, minute: Minute) -> bool:
+ """Is `minute` out-of-bounds."""
+ return (
+ minute.value < self.minutes_nanos[0]
+ or minute.value > self.minutes_nanos[-1]
+ )
+
+ def is_trading_minute(self, minute: Minute, _parse: bool = True) -> bool:
+ """Query if a given minute is a trading minute.
+
+ Minutes during breaks are not considered trading minutes.
+
+ Note: `self.side` determines whether exchange will be considered
+ open or closed on session open, session close, break start and
+ break end.
+
+ Parameters
+ ----------
+ minute
+ Minute being queried.
+
+ Returns
+ -------
+ bool
+ Boolean indicting if `minute` is a trading minute.
+
+ See Also
+ --------
+ is_open_on_minute
+ is_open_at_time
+ """
+ if _parse:
+ minute = parse_timestamp(minute, calendar=self)
+ idx = self._get_minute_idx(minute, _parse=False)
+ # convert from np.bool_
+ return bool(self.minutes_nanos[idx] == minute.value)
+
+ def is_break_minute(self, minute: Minute, _parse: bool = True) -> bool:
+ """Query if a given minute is within a break.
+
+ Note: `self.side` determines whether either, both or one of break
+ start and break end are treated as break minutes.
+
+ Parameters
+ ----------
+ minute
+ Minute being queried.
+
+ Returns
+ -------
+ bool
+ Boolean indicting if `minute` is a break minute.
+ """
+ if _parse:
+ minute = parse_timestamp(minute, calendar=self)
+ session_idx = np.searchsorted(self.first_minutes_nanos, minute.value) - 1
+ break_start = self.last_am_minutes_nanos[session_idx]
+ break_end = self.first_pm_minutes_nanos[session_idx]
+ # NaT comparisions evalute as False
+ numpy_bool = break_start < minute.value < break_end
+ return bool(numpy_bool)
+
+ def is_open_on_minute(
+ self, minute: Minute, ignore_breaks: bool = False, _parse: bool = True
+ ) -> bool:
+ """Query if exchange is open on a given minute.
+
+ Note: `self.side` determines whether exchange will be considered
+ open or closed on session open, session close, break start and
+ break end.
+
+ Parameters
+ ----------
+ minute
+ Minute being queried.
+
+ ignore_breaks
+ Should exchange be considered open during any break?
+ True - treat exchange as open during any break.
+ False - treat exchange as closed during any break.
+
+ Returns
+ -------
+ bool
+ Boolean indicting if exchange is open on `minute`.
+
+ See Also
+ --------
+ is_trading_minute
+ is_open_at_time
+ """
+ if _parse:
+ minute = parse_timestamp(minute, "minute", self)
+
+ is_trading_minute = self.is_trading_minute(minute, _parse=False)
+ if is_trading_minute or not ignore_breaks:
+ return is_trading_minute
+ else:
+ # not a trading minute although should return True if in break
+ return self.is_break_minute(minute, _parse=False)
+
+ def is_open_at_time(
+ self,
+ timestamp: pd.Timestamp,
+ side: Literal["left", "right", "both", "neither"] = "left",
+ ignore_breaks: bool = False,
+ ) -> bool:
+ """Query if exchange is open at a given timestamp.
+
+ Note: method differs from `is_trading_minute` and
+ `is_open_on_minute` in that it does not consider if the market is
+ open over an evaluated minute, but rather as at a specific
+ instance that can be of any resolution.
+
+ Parameters
+ ----------
+ timestamp
+ Timestamp being queried.
+
+ Can have any resolution (i.e. can be defined with second and
+ more accurate components).
+
+ If timezone naive then will be assumed as representing UTC.
+
+ side
+ Determines whether the exchange will be considered open or
+ closed on a session's open, close, break-start and break-end:
+
+ "left" - treat exchange as open on session open and
+ any break-end, treat as closed on session close and any
+ break-start.
+
+ "right" - treat exchange as open on session close and
+ any break-start, treat as closed on session open and any
+ break-end.
+
+ "both" (default) - treat exchange as open on all of session
+ open, close and any break-start and break-end.
+
+ "neither" - treat exchange as closed on all of session
+ open, close and any break-start and break-end.
+
+ ignore_breaks
+ Should exchange be considered open during any break?
+ True - treat exchange as open during any break.
+ False - treat exchange as closed during any break.
+
+ Returns
+ -------
+ bool
+ Boolean indicting if exchange is open at time.
+
+ See Also
+ --------
+ is_trading_minute
+ is_open_on_minute
+ """
+ ts = timestamp
+ if not isinstance(ts, pd.Timestamp):
+ raise TypeError(
+ "`timestamp` expected to receive type pd.Timestamp although"
+ f" got type {type(ts)}."
+ )
+
+ if ts.tz is not UTC:
+ ts = ts.tz_localize(UTC) if ts.tz is None else ts.tz_convert(UTC)
+
+ if self._minute_oob(ts):
+ raise errors.MinuteOutOfBounds(self, ts, "timestamp")
+
+ op_left = operator.le if side in self._LEFT_SIDES else operator.lt
+ op_right = operator.le if side in self._RIGHT_SIDES else operator.lt
+
+ nano = ts.value
+ if not self.has_break or ignore_breaks:
+ # only one check requried
+ bv = op_left(self.opens_nanos, nano) & op_right(nano, self.closes_nanos)
+ return bv.any()
+
+ break_starts_nanos = self.break_starts_nanos.copy()
+ bv_missing = self.break_starts.isna()
+ close_replacement = self.closes_nanos[bv_missing]
+ break_starts_nanos[bv_missing] = close_replacement
+ break_ends_nanos = self.break_ends_nanos.copy()
+ break_ends_nanos[bv_missing] = close_replacement
+
+ bv_am = op_left(self.opens_nanos, nano) & op_right(nano, break_starts_nanos)
+ bv_pm = op_left(break_ends_nanos, nano) & op_right(nano, self.closes_nanos)
+ return (bv_am | bv_pm).any()
+
+ def next_open(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
+ """Return next open that follows a given minute.
+
+ If `minute` is a session open, the next session's open will be
+ returned.
+
+ Parameters
+ ----------
+ minute
+ Minute for which to get the next open.
+
+ Returns
+ -------
+ pd.Timestamp
+ UTC timestamp of the next open.
+ """
+ if _parse:
+ minute = parse_timestamp(minute, "minute", self)
+ try:
+ idx = next_divider_idx(self.opens_nanos, minute.value)
+ except IndexError:
+ if minute >= self.opens.iloc[-1]:
+ raise ValueError(
+ "Minute cannot be the last open or later (received `minute`"
+ f" parsed as '{minute}'.)"
+ ) from None
+ else:
+ raise
+
+ return pd.Timestamp(self.opens_nanos[idx], tz=UTC)
+
+ def next_close(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
+ """Return next close that follows a given minute.
+
+ If `minute` is a session close, the next session's close will be
+ returned.
+
+ Parameters
+ ----------
+ minute
+ Minute for which to get the next close.
+
+ Returns
+ -------
+ pd.Timestamp
+ UTC timestamp of the next close.
+ """
+ if _parse:
+ minute = parse_timestamp(minute, "minute", self)
+ try:
+ idx = next_divider_idx(self.closes_nanos, minute.value)
+ except IndexError:
+ if minute == self.closes.iloc[-1]:
+ raise ValueError(
+ "Minute cannot be the last close (received `minute` parsed as"
+ f" '{minute}'.)"
+ ) from None
+ else:
+ raise
+ return pd.Timestamp(self.closes_nanos[idx], tz=UTC)
+
+ def previous_open(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
+ """Return previous open that preceeds a given minute.
+
+ If `minute` is a session open, the previous session's open will be
+ returned.
+
+ Parameters
+ ----------
+ minute
+ Minute for which to get the previous open.
+
+ Returns
+ -------
+ pd.Timestamp
+ UTC timestamp of the previous open.
+ """
+ if _parse:
+ minute = parse_timestamp(minute, "minute", self)
+ try:
+ idx = previous_divider_idx(self.opens_nanos, minute.value)
+ except ValueError:
+ if minute == self.opens.iloc[0]:
+ raise ValueError(
+ "Minute cannot be the first open (received `minute` parsed as"
+ f" '{minute}'.)"
+ ) from None
+ else:
+ raise
+
+ return pd.Timestamp(self.opens_nanos[idx], tz=UTC)
+
+ def previous_close(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
+ """Return previous close that preceeds a given minute.
+
+ If `minute` is a session close, the previous session's close will be
+ returned.
+
+ Parameters
+ ----------
+ minute
+ Minute for which to get the previous close.
+
+ Returns
+ -------
+ pd.Timestamp
+ UTC timestamp of the previous close.
+ """
+ if _parse:
+ minute = parse_timestamp(minute, "minute", self)
+ try:
+ idx = previous_divider_idx(self.closes_nanos, minute.value)
+ except ValueError:
+ if minute <= self.closes.iloc[0]:
+ raise ValueError(
+ "Minute cannot be the first close or earlier (received"
+ f" `minute` parsed as '{minute}'.)"
+ ) from None
+ else:
+ raise
+
+ return pd.Timestamp(self.closes_nanos[idx], tz=UTC)
+
+ def next_minute(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
+ """Return trading minute that immediately follows a given minute.
+
+ Parameters
+ ----------
+ minute
+ Minute for which to get next trading minute. Minute can be a
+ trading or a non-trading minute.
+
+ Returns
+ -------
+ pd.Timestamp
+ UTC timestamp of the next minute.
+
+ Raises
+ ------
+ errors.RequestedSessionOutOfBounds
+ If `minute` is the last calendar minute.
+ """
+ if _parse:
+ minute = parse_timestamp(minute, "minute", self)
+ try:
+ idx = next_divider_idx(self.minutes_nanos, minute.value)
+ except IndexError:
+ # dt > last_minute handled via parsing
+ if minute == self.last_minute:
+ raise errors.RequestedMinuteOutOfBounds(self, False) from None
+ return self.minutes[idx]
+
+ def previous_minute(self, minute: Minute, _parse: bool = True) -> pd.Timestamp:
+ """Return trading minute that immediately preceeds a given minute.
+
+ Parameters
+ ----------
+ minute
+ Minute for which to get previous trading minute. Minute can be
+ a trading or a non-trading minute.
+
+ Returns
+ -------
+ pd.Timestamp
+ UTC timestamp of the previous minute.
+
+ Raises
+ ------
+ errors.RequestedSessionOutOfBounds
+ If `minute` is the first calendar minute.
+ """
+ if _parse:
+ minute = parse_timestamp(minute, "minute", self)
+ try:
+ idx = previous_divider_idx(self.minutes_nanos, minute.value)
+ except ValueError:
+ # dt < first_minute handled via parsing
+ if minute == self.first_minute:
+ raise errors.RequestedMinuteOutOfBounds(self, True) from None
+ return self.minutes[idx]
+
+ def minute_to_session(
+ self,
+ minute: Minute,
+ direction: Literal["next", "previous", "none"] = "next",
+ _parse: bool = True,
+ ) -> pd.Timestamp:
+ """Get session corresponding with a trading or break minute.
+
+ Parameters
+ ----------
+ minute
+ Minute for which require corresponding session.
+
+ direction
+ How to resolve session in event that `minute` is not a trading
+ or break minute:
+ "next" (default) - return first session subsequent to
+ `minute`.
+ "previous" - return first session prior to `minute`.
+ "none" - raise ValueError.
+
+ Returns
+ -------
+ pd.Timestamp
+ Corresponding session label.
+
+ Raises
+ ------
+ ValueError
+ If `minute` is not a trading minute and `direction` is "none".
+
+ See Also
+ --------
+ minute_to_past_session
+ minute_to_future_session
+ session_offset
+ """
+ if _parse:
+ minute = parse_timestamp(minute, calendar=self)
+
+ if minute.value < self.minutes_nanos[0]:
+ # Resolve call here.
+ if direction == "next":
+ return self.first_session
+ else:
+ raise ValueError(
+ f"Received `minute` as '{minute}' although this is earlier than the"
+ f" calendar's first trading minute ({self.first_minute}). Consider"
+ " passing `direction` as 'next' to get first session."
+ )
+
+ if minute.value > self.minutes_nanos[-1]:
+ # Resolve call here.
+ if direction == "previous":
+ return self.last_session
+ else:
+ raise ValueError(
+ f"Received `minute` as '{minute}' although this is later than the"
+ f" calendar's last trading minute ({self.last_minute}). Consider"
+ " passing `direction` as 'previous' to get last session."
+ )
+
+ idx = np.searchsorted(self.last_minutes_nanos, minute.value)
+ current_or_next_session = self.schedule.index[idx]
+
+ if direction == "next":
+ return current_or_next_session
+ elif direction == "previous":
+ if not self.is_open_on_minute(minute, ignore_breaks=True, _parse=False):
+ return self.schedule.index[idx - 1]
+ elif direction == "none":
+ if not self.is_open_on_minute(minute, ignore_breaks=True, _parse=False):
+ # if the exchange is closed, blow up
+ raise ValueError(
+ f"`minute` '{minute}' is not a trading minute. Consider passing"
+ " `direction` as 'next' or 'previous'."
+ )
+ else:
+ # invalid direction
+ raise ValueError(f"Invalid direction parameter: {direction}")
+
+ return current_or_next_session
+
+ def minute_to_past_session(
+ self, minute: Minute, count: int = 1, _parse: bool = True
+ ) -> pd.Timestamp:
+ """Get a session that closed before a given minute.
+
+ Parameters
+ ----------
+ minute
+ Minute for which to return a previous session. Can be a
+ trading minute or non-trading minute.
+ Note: if `minute` is a trading minute then returned session
+ will not be the session of which `minute` is a trading minute,
+ but rather a session that closed before `minute`.
+
+ count : default: 1
+ Number of sessions prior to `minute` for which require session.
+
+ Returns
+ -------
+ pd.Timstamp
+ Session that is `count` full sessions before `minute`.
+
+ See Also
+ --------
+ minute_to_session
+ minute_to_future_session
+ session_offset
+ """
+ if _parse:
+ minute = parse_timestamp(minute, calendar=self)
+ if count <= 0:
+ raise ValueError("`count` must be higher than 0.")
+ if self.is_open_on_minute(minute, ignore_breaks=True, _parse=False):
+ current_session = self.minute_to_session(minute, _parse=False)
+ base_session = self.previous_session(current_session, _parse=False)
+ else:
+ base_session = self.minute_to_session(minute, "previous", _parse=False)
+ count -= 1
+ return self.session_offset(base_session, -count, _parse=False)
+
+ def minute_to_future_session(
+ self,
+ minute: Minute,
+ count: int = 1,
+ _parse: bool = True,
+ ) -> pd.Timestamp:
+ """Get a session that opens after a given minute.
+
+ Parameters
+ ----------
+ minute
+ Minute for which to return a future session. Can be a trading
+ minute or non-trading minute.
+ Note: if `minute` is a trading minute then returned session
+ will not be the session of which `minute` is a trading minute,
+ but rather a session that opens after `minute`.
+
+ count : default: 1
+ Number of sessions following `minute` for which require
+ session.
+
+ Returns
+ -------
+ pd.Timstamp
+ Session that is `count` full sessions after `minute`.
+
+ See Also
+ --------
+ minute_to_session
+ minute_to_past_session
+ session_offset
+ """
+ if _parse:
+ minute = parse_timestamp(minute, calendar=self)
+ if count <= 0:
+ raise ValueError("`count` must be higher than 0.")
+ if self.is_open_on_minute(minute, ignore_breaks=True, _parse=False):
+ current_session = self.minute_to_session(minute, _parse=False)
+ base_session = self.next_session(current_session, _parse=False)
+ else:
+ base_session = self.minute_to_session(minute, "next", _parse=False)
+ count -= 1
+ return self.session_offset(base_session, count, _parse=False)
+
+ def minute_to_trading_minute(
+ self,
+ minute: Minute,
+ direction: Literal["next", "previous", "none"] = "none",
+ _parse: bool = True,
+ ) -> pd.Timestamp:
+ """Resolve a minute to a trading minute.
+
+ Differs from `previous_minute` and `next_minute` by returning
+ `minute` unchanged if `minute` is a trading minute.
+
+ Parameters
+ ----------
+ minute
+ Timestamp to be resolved to a trading minute.
+
+ direction:
+ How to resolve `minute` if does not represent a trading minute:
+ 'next' - return trading minute that immediately follows
+ `minute`.
+ 'previous' - return trading minute that immediately
+ preceeds `minute`.
+ 'none' - raise KeyError
+
+ Returns
+ -------
+ pd.Timestamp
+ Returns `minute` if `minute` is a trading minute otherwise
+ first trading minute that, in accordance with `direction`,
+ either immediately follows or preceeds `minute`.
+
+ Raises
+ ------
+ ValueError
+ If `minute` is not a trading minute and `direction` is None.
+
+ See Also
+ --------
+ next_mintue
+ previous_minute
+ """
+ if _parse:
+ minute = parse_timestamp(minute, calendar=self)
+ if self.is_trading_minute(minute, _parse=False):
+ return minute
+ elif direction == "next":
+ return self.next_minute(minute, _parse=False)
+ elif direction == "previous":
+ return self.previous_minute(minute, _parse=False)
+ else:
+ raise ValueError(
+ f"`minute` '{minute}' is not a trading minute. Consider passing"
+ " `direction` as 'next' or 'previous'."
+ )
+
+ def minute_offset(
+ self, minute: TradingMinute, count: int, _parse: bool = True
+ ) -> pd.Timestamp:
+ """Offset a given trading minute by a number of trading minutes.
+
+ Parameters
+ ----------
+ minute
+ Trading minute from which to offset.
+
+ count
+ Number of trading minutes to offset `minute`. Positive to
+ offset forwards, negative to offset backwards.
+
+ Returns
+ -------
+ pd.Timstamp
+ Offset trading minute.
+
+ Raises
+ ------
+ ValueError
+ If offset minute would be either before the calendar's first
+ trading minute or after the calendar's last trading minute.
+ """
+ if _parse:
+ minute = parse_trading_minute(self, minute)
+ idx = self._get_minute_idx(minute) + count
+ if idx >= len(self.minutes_nanos):
+ raise errors.RequestedMinuteOutOfBounds(self, too_early=False)
+ elif idx < 0:
+ raise errors.RequestedMinuteOutOfBounds(self, too_early=True)
+ return self.minutes[idx]
+
+ def minute_offset_by_sessions(
+ self,
+ minute: TradingMinute,
+ count: int = 1,
+ _parse: bool = True,
+ ) -> pd.Timestamp:
+ """Offset trading minute by a given number of sessions.
+
+ If trading minute is not represented in target session (due to a late
+ open for example) then offset minute will be rolled (with respect to
+ the target session):
+ - forwards to first session minute, if offset minute otherwise
+ falls earlier than first session minute.
+ - back to last session minute, if offset minute otherwise falls
+ later than last session minute.
+ - back to last minute before break, if offset otherwise
+ falls in session break.
+
+ Parameters
+ ----------
+ minute
+ Trading minute to be offset.
+
+ count
+ Number of sessions by which to offset trading minute. Negative
+ to offset to an earlier session.
+ """
+ if _parse:
+ minute = parse_trading_minute(self, minute)
+ if not count:
+ return minute
+
+ if count > 0:
+ try:
+ target_session = self.minute_to_future_session(minute, abs(count))
+ except errors.RequestedSessionOutOfBounds:
+ raise errors.RequestedMinuteOutOfBounds(self, too_early=False) from None
+ else:
+ try:
+ target_session = self.minute_to_past_session(minute, abs(count))
+ except errors.RequestedSessionOutOfBounds:
+ raise errors.RequestedMinuteOutOfBounds(self, too_early=True) from None
+
+ base_session = self.minute_to_session(minute)
+ day_offset = (minute.normalize() - base_session.tz_localize(UTC)).days
+
+ minute = target_session.replace(hour=minute.hour, minute=minute.minute)
+ minute = minute.tz_localize(UTC)
+ minute += pd.Timedelta(days=day_offset)
+
+ if self._minute_oob(minute):
+ if minute.value < self.minutes_nanos[0]:
+ errors.RequestedMinuteOutOfBounds(self, too_early=True)
+ if minute.value > self.minutes_nanos[-1]:
+ raise errors.RequestedMinuteOutOfBounds(self, too_early=False)
+
+ if self.is_trading_minute(minute, _parse=False):
+ # this guard is necessary as minute can be for a different session than the
+ # intended if the gap between sessions is less than any difference in the
+ # open or close times (i.e. only relevant if base and target sessions have
+ # different open/close times.
+ if self.minute_to_session(minute, _parse=False) == target_session:
+ return minute
+ first_minute = self.session_first_minute(target_session, _parse=False)
+ if minute < first_minute:
+ return first_minute
+ last_minute = self.session_last_minute(target_session, _parse=False)
+ if minute > last_minute:
+ return last_minute
+ elif self.is_break_minute(minute, _parse=False):
+ return self.session_last_am_minute(target_session, _parse=False)
+ assert False, "offset minute should have resolved!"
+
+ # Methods that evaluate or interrogate a range of minutes.
+
+ def _get_minutes_slice(self, start: Minute, end: Minute, _parse=True) -> slice:
+ """Slice representing a range of trading minutes."""
+ if _parse:
+ start = parse_timestamp(start, "start", self)
+ end = parse_timestamp(end, "end", self)
+ slice_start = self.minutes_nanos.searchsorted(start.value, side="left")
+ slice_end = self.minutes_nanos.searchsorted(end.value, side="right")
+ return slice(slice_start, slice_end)
+
+ def minutes_in_range(
+ self, start: Minute, end: Minute, _parse: bool = True
+ ) -> pd.DatetimeIndex:
+ """Return all trading minutes between given minutes.
+
+ Parameters
+ ----------
+ start
+ Minute representing start of desired range. Can be a trading
+ minute or non-trading minute.
+
+ end
+ Minute representing end of desired range. Can be a trading
+ minute or non-trading minute.
+ """
+ slc = self._get_minutes_slice(start, end, _parse)
+ return self.minutes[slc]
+
+ def minutes_window(
+ self, minute: TradingMinute, count: int, _parse: bool = True
+ ) -> pd.DatetimeIndex:
+ """Return block of given size of consecutive trading minutes.
+
+ Parameters
+ ----------
+ minute
+ Minute representing the first (if `count` positive) or last
+ (if `count` negative) minute of minutes window.
+
+ count
+ Number of mintues to include in window.
+ Positive to return a block of minutes from `minute`
+ Negative to return a block of minutes to `minute`.
+ """
+ if not count:
+ raise ValueError("`count` cannot be 0.")
+ if _parse:
+ minute = parse_trading_minute(self, minute, "minute")
+
+ start_idx = self._get_minute_idx(minute, _parse=False)
+ end_idx = start_idx + count + (-1 if count > 0 else 1)
+
+ if end_idx < 0:
+ raise ValueError(
+ f"Minutes window cannot begin before the calendar's first minute"
+ f" ({self.first_minute}). `count` cannot be lower than"
+ f" {count - end_idx} for `minute` '{minute}'."
+ )
+ elif end_idx >= len(self.minutes_nanos):
+ raise ValueError(
+ f"Minutes window cannot end after the calendar's last minute"
+ f" ({self.last_minute}). `count` cannot be higher than"
+ f" {count - (end_idx - len(self.minutes_nanos) + 1)} for `minute`"
+ f" '{minute}'."
+ )
+ return self.minutes[min(start_idx, end_idx) : max(start_idx, end_idx) + 1]
+
+ def minutes_distance(self, start: Minute, end: Minute, _parse: bool = True) -> int:
+ """Return the number of minutes in a range.
+
+ Parameters
+ ----------
+ start
+ Start of minute range (range inclusive of `start`).
+
+ end
+ End of minute range (range inclusive of `end`).
+
+ Returns
+ -------
+ int
+ Number of minutes in minute range, If `start` is later than
+ `end` then return will be negated.
+ """
+ if _parse:
+ start = parse_timestamp(start, "start", self)
+ end = parse_timestamp(end, "end", self)
+ negate = end < start
+ if negate:
+ start, end = end, start
+ slc = self._get_minutes_slice(start, end, _parse=False)
+ return slc.start - slc.stop if negate else slc.stop - slc.start
+
+ def minutes_to_sessions(self, minutes: pd.DatetimeIndex) -> pd.DatetimeIndex:
+ """Return sessions corresponding to multiple trading minutes.
+
+ For the purpose of this method trading minutes are considered as:
+ - Trading minutes as determined by `self.side`.
+ - All minutes of any breaks.
+
+ Parameters
+ ----------
+ minutes
+ Sorted DatetimeIndex representing market minutes for which to get
+ corresponding sessions.
+
+ Returns
+ -------
+ pd.DatetimeIndex
+ Sessions corresponding to `minutes`.
+
+ Raises
+ ------
+ ValueError
+ If any indice of `minute` is not a trading minute.
+ """
+ if not minutes.is_monotonic_increasing:
+ raise ValueError("`index` must be ordered.")
+ # Find the indices of the previous first session minute and the next
+ # last session minute for each minute.
+ index_nanos = minutes.values.astype(np.int64)
+ first_min_nanos = self.first_minutes_nanos
+ last_min_nanos = self.last_minutes_nanos
+ prev_first_mins_idxs = (
+ first_min_nanos.searchsorted(index_nanos, side="right") - 1
+ )
+ next_last_mins_idxs = last_min_nanos.searchsorted(index_nanos, side="left")
+
+ # If they don't match, the minute is outside the trading day. Barf.
+ mismatches = prev_first_mins_idxs != next_last_mins_idxs
+ if mismatches.any():
+ # Show the first bad minute in the error message.
+ bad_ix = np.flatnonzero(mismatches)[0]
+ example = minutes[bad_ix]
+
+ prev_session_idx = prev_first_mins_idxs[bad_ix]
+ prev_first_min = pd.Timestamp(first_min_nanos[prev_session_idx], tz=UTC)
+ prev_last_min = pd.Timestamp(last_min_nanos[prev_session_idx], tz=UTC)
+ next_first_min = pd.Timestamp(first_min_nanos[prev_session_idx + 1], tz=UTC)
+ next_last_min = pd.Timestamp(last_min_nanos[prev_session_idx + 1], tz=UTC)
+
+ raise ValueError(
+ f"{mismatches.sum()} non-trading minutes in"
+ f" minutes_to_sessions:\nFirst Bad Minute: {example}\n"
+ f"Previous Session: {prev_first_min} -> {prev_last_min}\n"
+ f"Next Session: {next_first_min} -> {next_last_min}"
+ )
+
+ return self.schedule.index[prev_first_mins_idxs]
+
+ # Methods that evaluate or interrogate a range of sessions.
+
+ def _parse_start_end_dates(
+ self, start: Date, end: Date, _parse: bool
+ ) -> tuple[pd.Timestamp, pd.Timestamp]:
+ if not _parse:
+ return start, end
+ return parse_date(start, "start", self), parse_date(end, "end", self)
+
+ def _get_sessions_slice(self, start: Date, end: Date, _parse=True) -> slice:
+ """Slice representing a range of sessions."""
+ start, end = self._parse_start_end_dates(start, end, _parse)
+ slice_start = self.sessions_nanos.searchsorted(start.value, side="left")
+ slice_end = self.sessions_nanos.searchsorted(end.value, side="right")
+ return slice(slice_start, slice_end)
+
+ def sessions_in_range(
+ self, start: Date, end: Date, _parse: bool = True
+ ) -> pd.DatetimeIndex:
+ """Return sessions within a given range.
+
+ Parameters
+ ----------
+ start
+ Start of session range (range inclusive of `start`).
+
+ end
+ End of session range (range inclusive of `end`).
+
+ Returns
+ -------
+ pd.DatetimeIndex
+ Sessions from `start` through `end`.
+ """
+ slc = self._get_sessions_slice(start, end, _parse)
+ return self.sessions[slc]
+
+ def sessions_has_break(self, start: Date, end: Date, _parse: bool = True) -> bool:
+ """Query if at least one session in a session range has a break.
+
+ Parameters
+ ----------
+ start
+ Start of session range (range inclusive of `start`).
+
+ end
+ End of session range (range inclusive of `end`).
+
+ Returns
+ -------
+ bool
+ True if any session in session range has a break, False otherwise.
+ """
+ slc = self._get_sessions_slice(start, end, _parse)
+ return self.break_starts[slc].notna().any()
+
+ def sessions_window(
+ self, session: Session, count: int, _parse: bool = True
+ ) -> pd.DatetimeIndex:
+ """Return block of given size of consecutive sessions.
+
+ Parameters
+ ----------
+ session
+ Session representing the first (if `count` positive) or last
+ (if `count` negative) session of session window.
+
+ count
+ Number of sessions to include in window.
+ Positive to return window of sessions from `session`
+ Negative to return window of sessions to `session`.
+ """
+ if not count:
+ raise ValueError("`count` cannot be 0.")
+ if _parse:
+ session = parse_session(self, session, "session")
+ start_idx = self._get_session_idx(session, _parse=False)
+ end_idx = start_idx + count + (-1 if count > 0 else 1)
+ if end_idx < 0:
+ raise ValueError(
+ f"Sessions window cannot begin before the first calendar session"
+ f" ({self.first_session}). `count` cannot be lower than"
+ f" {count - end_idx} for `session` '{session}'."
+ )
+ elif end_idx >= len(self.sessions):
+ raise ValueError(
+ f"Sessions window cannot end after the last calendar session"
+ f" ({self.last_session}). `count` cannot be higher than"
+ f" {count - (end_idx - len(self.sessions) + 1)} for"
+ f" `session` '{session}'."
+ )
+ return self.sessions[min(start_idx, end_idx) : max(start_idx, end_idx) + 1]
+
+ def sessions_distance(self, start: Date, end: Date, _parse: bool = True) -> int:
+ """Return the number of sessions in a range.
+
+ Parameters
+ ----------
+ start
+ Start of session range (range inclusive of `start`).
+
+ end
+ End of session range (range inclusive of `end`).
+
+ Returns
+ -------
+ int
+ Number of sessions in session range, If `start` is later than
+ `end` then return will be negated.
+ """
+ start, end = self._parse_start_end_dates(start, end, _parse)
+ negate = end < start
+ if negate:
+ start, end = end, start
+ slc = self._get_sessions_slice(start, end, _parse=False)
+ dist = slc.start - slc.stop if negate else slc.stop - slc.start
+ return int(dist) # otherwise returned as `numpy.int64`
+
+ def sessions_minutes(
+ self, start: Date, end: Date, _parse: bool = True
+ ) -> pd.DatetimeIndex:
+ """Return trading minutes over a sessions range.
+
+ Parameters
+ ----------
+ start
+ Start of session range (range inclusive of `start`).
+
+ end
+ End of session range (range inclusive of `end`).
+
+ Returns
+ -------
+ pd.DatetimeIndex
+ Trading minutes for sessions in range.
+ """
+ start, end = self._parse_start_end_dates(start, end, _parse)
+ start = self.date_to_session(start, "next", _parse=False)
+ end = self.date_to_session(end, "previous", _parse=False)
+ first_minute = self.session_first_minute(start)
+ last_minute = self.session_last_minute(end)
+ return self.minutes_in_range(first_minute, last_minute)
+
+ def sessions_minutes_count(
+ self, start: Date, end: Date, _parse: bool = True
+ ) -> int:
+ """Return number of trading minutes in a range of sessions.
+
+ Parameters
+ ----------
+ start
+ Start of session range (range inclusive of `start`).
+
+ end
+ End of session range (range inclusive of `end`).
+
+ Returns
+ -------
+ int
+ Total number of trading minutes in sessions range.
+ """
+ slc = self._get_sessions_slice(start, end, _parse)
+ session_diff = self.last_minutes_nanos[slc] - self.first_minutes_nanos[slc]
+ session_diff += NANOSECONDS_PER_MINUTE
+ break_diff = self.first_pm_minutes_nanos[slc] - self.last_am_minutes_nanos[slc]
+ break_diff[break_diff != 0] -= NANOSECONDS_PER_MINUTE
+ nanos = session_diff - break_diff
+ return (nanos // NANOSECONDS_PER_MINUTE).sum()
+
+ def trading_index(
+ self,
+ start: Date | Minute,
+ end: Date | Minute,
+ period: pd.Timedelta | str,
+ intervals: bool = True,
+ closed: Literal["left", "right", "both", "neither"] = "left",
+ force_close: bool = False,
+ force_break_close: bool = False,
+ force: bool | None = None,
+ curtail_overlaps: bool = False,
+ ignore_breaks: bool = False,
+ align: pd.Timedelta | str = pd.Timedelta(1, "min"),
+ align_pm: pd.Timedelta | bool = True,
+ parse: bool = True,
+ ) -> pd.DatetimeIndex | pd.IntervalIndex:
+ """Create a trading index.
+
+ Create a trading index of given `period` over a given range of
+ dates.
+
+ NB. Which minutes the calendar treats as trading minutes, according
+ to `self.side`, is irrelevant in the evaluation of the trading
+ index.
+
+ NB. Execution time is related to the number of indices created. The
+ longer the range of dates covered and/or the shorter the period
+ (i.e. higher the frequency), the longer the execution. Whilst an
+ index with 4000 indices might be created in a couple of
+ miliseconds, a high frequency index with 2 million indices might
+ take a second or two.
+
+ Parameters
+ ----------
+ start
+ Timestamp representing start of index.
+
+ If `start` is passed as a date then the first indice will be:
+ if `start` is a session, then the first indice of that
+ session (i.e. the left side of the first indice will be
+ the session open).
+ otherwise, the first indice of the nearest session
+ following `start`.
+
+ If `start` is passed as a minute then the first indice will be:
+ if `start` coincides with (the left side of*) an indice,
+ then that indice.
+ otherwise the nearest indice to `start` (with a left side*)
+ that is later than `start`.
+ * if `intervals` is True (default)
+
+ `start` will be interpreted as a date if it is timezone-naive
+ and does not have a time component (or any time component is
+ 00:00). Otherwise `start` will be interpreted as a time.
+
+ If `period` is one day ("1d") then `start` must be passed as
+ a date. The first indice will be either `start`, if `start` is
+ a session, or otherwise the nearest session following `start`.
+
+ end
+ Timestamp representing end of index.
+
+ If `end` is passed as a date then the last indice will be:
+ if `end` is a session, then the last indice of that
+ session (i.e. either the right side of the final indice
+ will be the session close or the final indice will
+ contain the session close).
+ otherwise, the last indice of the nearest session
+ preceeding `end`.
+
+ If `end` is passed as a minute then the last indice will be:
+ if `end` coincides with (the right side of*) an indice,
+ then that indice.
+ otherwise the nearest indice to `end` (with a right side*)
+ that is earlier than `end`.
+ * if `intervals` is True (default)
+
+ `end` will be interpreted as a date if it is timezone-naive
+ and does not have a time component (or any time component is
+ 00:00). Otherwise `start` will be interpreted as a time.
+
+ If `period` is one day ("1d") then `end` must be passed as
+ a date. The last indice will be either `end`, if `end` is
+ a session, or otherwise the nearest session prceeding `end`.
+
+ period
+ If `intervals` is True, the length of each interval. If
+ `intervals` is False, the distance between indices. Period
+ should be passed as a pd.Timedelta or a str that's acceptable
+ as a single input to pd.Timedelta. `period` cannot be greater
+ than 1 day.
+
+ Examples of valid `period` input:
+ pd.Timedelta(minutes=15), pd.Timedelta(minutes=15, hours=2)
+ '15min', '15T', '1H', '4h', '1d', '30s', '2s', '500ms'.
+ Examples of invalid `period` input:
+ '15minutes', '2d'.
+
+ intervals : default: True
+ True to return trading index as a pd.IntervalIndex with indices
+ representing explicit intervals.
+
+ False to return trading index as a pd.DatetimeIndex with
+ indices that implicitely represent a period according to
+ `closed`.
+
+ If `period` is '1d' then trading index will be returned as a
+ pd.DatetimeIndex.
+
+ closed : {"left", "right", "both", "neither"}
+ (ignored if `period` is '1d'.)
+
+ If `intervals` is True, the side that intervals should be
+ closed on. Must be either "left" or "right" (any time during a
+ session must belong to one interval and one interval only).
+
+ If `intervals` is False, the side of each period that an
+ indice should be defined. The first and last indices of each
+ (sub)session will be defined according to:
+ "left" - include left side of first period, do not include
+ right side of last period.
+ "right" - do not include left side of first period, include
+ right side of last period.
+ "both" - include both left side of first period and right
+ side of last period.
+ "neither" - do not include either left side of first period
+ or right side of last period.
+ NB if `period` is not a factor of the (sub)session length then
+ "right" or "both" will result in an indice being defined after
+ the (sub)session close. See `force_close` and
+ `force_break_close`.
+
+ force_close : default: False
+ (ignored if `force` is passed.)
+ (ignored if `period` is '1d')
+ (irrelevant if `intervals` is False and `closed` is "left" or
+ "neither")
+
+ Defines behaviour if right side of a session's last period
+ falls after the session close.
+
+ If True, defines right side of this period as session close.
+
+ If False, defines right side of this period after the session
+ close. In this case the represented period will include a
+ non-trading period.
+
+ force_break_close : default: False
+ (ignored if `force` is passed.)
+ (ignored if `period` is '1d'.)
+ (irrelevant if `intervals` is False and `closed` is "left" or
+ "neither.)
+
+ Defines behaviour if right side of last pre-break period falls
+ after the start of the break.
+
+ If True, defines right side of this period as break start.
+
+ If False, defines right side of this period after the break
+ start. In this case the represented period will include a
+ non-trading period.
+
+ force : optional
+ (ignored if `period` is '1d'.)
+ (irrelevant if `intervals` is False and `closed` is "left" or
+ "neither.)
+
+ Convenience option to set both `force_close` and
+ `force_break_close`. If passed then values passsed to
+ `force_close` and `force_break_close` will be ignored.
+
+ curtail_overlaps : default: False
+ (ignored if `period` is '1d')
+ (irrelevant if (`intervals` is False) or (`force_close` and
+ `force_break_close` are both True).)
+
+ Defines action to take if a period ends after the start of the
+ next period. (This can occur if `period` is longer
+ than a break or the gap between one session's close and the
+ next session's open.)
+
+ If True, the right of the earlier of two overlapping
+ periods will be curtailed to the left of the latter period.
+ (NB consequently the period length will not be constant for
+ all periods.)
+
+ If False, will raise IntervalsOverlapError.
+
+ ignore_breaks : default: False
+ (ignored if `period` is '1d')
+ (irrelevant if no session has a break)
+
+ Defines whether trading index should respect session breaks.
+
+ If False, treat sessions with breaks as comprising independent
+ morning and afternoon subsessions.
+
+ If True, treat all sessions as continuous, ignoring any
+ breaks.
+
+ parse : default: True
+ Determines if `start` and `end` values are parsed. If these
+ arguments are passed as tz-naive pd.Timestamp with no time
+ component then can pass `parse` as False to save around
+ 500µs on the execution.
+
+ align : default: pd.Timedelta(1, "min")
+ Anchor the first indice of each session such that it aligns
+ with the nearest occurrence of a specific fraction of an hour.
+
+ Pass as a pd.Timedelta or a str that's acceptable as a single
+ input to pd.Timedelta. Pass +ve values to shift indices
+ forwards, -ve values to shift indices backwards.
+
+ Valid values are (or equivalent):
+ "2min", "3min", "4min", "5min", "6min", "10min", "12min", "15min", "20min",
+ "30min", "-2min", "-4min", "-5min", "-6min", "-10min", "-12min", "-15min",
+ "-20min", "-30min"
+
+ For example, if `intervals` is True and `period` is '5T' then
+ the first interval of a session with open time as 07:59 would
+ be:
+ 07:59 - 08:04 if `align` is pd.Timedelta(1, "min") (default)
+ 08:00 - 08:05 if `align` is '5T'
+ 07:55 - 08:00 if `align` is '-5T'
+
+ Subsequent indices will be similarly shifted.
+
+ Note: A session's indices will not be shifted if the session
+ open already aligns with `align`. For example, if the open time
+ were 08:00 then the first interval will always have a left side
+ as 08:00 regardless of `align`.
+
+ align_pm : default: True
+ (ignored if `ignore_break` is True)
+ (irrelevant if no session has a break)
+
+ Anchor the first indice of each afternoon subsession such that
+ it aligns with the nearest occurrence of a specific fraction of
+ an hour.
+
+ True: (default) Treat as `align`.
+
+ False: Do not shift post-break indices.
+
+ pd.Timedelta or str: Align post-break indices to the
+ nearest occurence of this fraction of an hour. Valid values
+ as for `align`.
+
+ Returns
+ -------
+ pd.IntervalIndex or pd.DatetimeIndex
+ Trading index.
+
+ If `intervals` is False or `period` is '1d' then returned as a
+ pd.DatetimeIndex.
+ If `intervals` is True (default) returned as pd.IntervalIndex.
+
+ Raises
+ ------
+ exchange_calendars.errors.IntervalsOverlapError
+ If `intervals` is True and right side of one or more indices
+ would fall after the left of the subsequent indice. This can
+ occur if `period` is longer than a break or the gap between one
+ session's close and the next session's open.
+
+ exchange_calendars.errors.IntervalsOverlapError
+ If `intervals` is False and an indice would otherwise fall to
+ the right of the subsequent indice. This can occur if `period`
+ is longer than a break or the gap between one session's close
+ and the next session's open.
+
+ Credit to @Stryder-Git at pandas_market_calendars for showing the
+ way with a vectorised solution to creating trading indices (a
+ variation of which is employed within the underlying _TradingIndex
+ class).
+ """
+ if not isinstance(period, pd.Timedelta):
+ try:
+ period = pd.Timedelta(period)
+ except ValueError:
+ msg = (
+ f"`period` receieved as '{period}' although takes type"
+ " 'pd.Timedelta' or a 'str' that is valid as a single input"
+ " to 'pd.Timedelta'. Examples of valid input: pd.Timestamp('15T'),"
+ " '15min', '15T', '1H', '4h', '1d', '5s', 500ms'."
+ )
+ raise ValueError(msg) from None
+
+ if period > pd.Timedelta(1, "D"):
+ msg = (
+ "`period` cannot be greater than one day although received as"
+ f" '{period}'."
+ )
+ raise ValueError(msg)
+
+ if period == pd.Timedelta(1, "D"):
+ start, end = self._parse_start_end_dates(start, end, parse)
+ return self.sessions_in_range(start, end)
+
+ if intervals and closed in ["both", "neither"]:
+ raise ValueError(
+ f"If `intervals` is True then `closed` cannot be '{closed}'."
+ )
+
+ def get_align(name: Literal["align", "align_pm"], value: Any) -> pd.Timedelta:
+ """Convert value received for an align parameter to Timestamp.
+
+ Raises `ValueError` if value is invalid or not of a valid type.
+
+ Parameters
+ ----------
+ name
+ Parameter name.
+
+ value
+ Value assigned to parameter.
+ """
+ try:
+ value = pd.Timedelta(value)
+ except ValueError:
+ insert = " bool," if name == "align_pm" else ""
+ msg = (
+ f"`{name}` receieved as '{value}' although takes type{insert}"
+ f" 'pd.Timedelta' or a 'str' that is valid as a single input"
+ " to 'pd.Timedelta'. Examples of valid input: pd.Timestamp('5T'),"
+ " '5min', '5T', pd.Timedelta('-5T'), '-5min', '-5T'."
+ )
+ raise ValueError(msg) from None
+
+ ONE_HOUR = pd.Timedelta("1h")
+ if value > ONE_HOUR or value < -ONE_HOUR or not value or (ONE_HOUR % value):
+ raise ValueError(
+ f"`{name}` must be factor of 1H although received '{value}'."
+ )
+
+ if value % pd.Timedelta(1, "min"):
+ raise ValueError(
+ f"`{name}` cannot include a fraction of a minute although received"
+ f" '{value}'."
+ )
+ return value
+
+ align = get_align("align", align)
+
+ if align_pm is False:
+ align_pm = pd.Timedelta(1, "min")
+ else:
+ align_pm = align if align_pm is True else get_align("align_pm", align_pm)
+
+ if force is not None:
+ force_close = force_break_close = force
+
+ # method exposes public methods of _TradingIndex.
+ _trading_index = _TradingIndex(
+ self,
+ start,
+ end,
+ period,
+ closed,
+ force_close,
+ force_break_close,
+ curtail_overlaps,
+ ignore_breaks,
+ align,
+ align_pm,
+ )
+
+ if not intervals:
+ return _trading_index.trading_index()
+ else:
+ return _trading_index.trading_index_intervals()
+
+ # Internal methods called by constructor.
+
+ def _special_dates(
+ self,
+ regular_dates: list[tuple[datetime.time, HolidayCalendar | int]],
+ ad_hoc_dates: list[tuple[datetime.time, pd.DatetimeIndex]],
+ start_date: pd.Timestamp,
+ end_date: pd.Timestamp,
+ ) -> pd.Series:
+ """Evaluate times associated with special dates.
+
+ Parameters
+ ----------
+ regular_dates
+ Regular non-standard times and corresponding HolidayCalendars or Int day-of-week.
+
+ ad_hoc_dates
+ Adhoc non-standard times and corresponding sessions.
+
+ start_date
+ Start of the range over which to evaluate special dates. Must
+ be timezone naive.
+
+ end_date
+ End of the range over which to evaluate special dates. Must be
+ timezone naive.
+
+ Returns
+ -------
+ special_dates: pd.Series
+ Series mapping trading sessions with special times.
+
+ Index is timezone naive.
+ dtype is datetime64[ns, UTC].
+ """
+ # List of Series for regularly-scheduled times.
+ regular = [
+ scheduled_special_times(
+ holiday_calendar,
+ start_date,
+ end_date,
+ time_,
+ self.tz,
+ )
+ for time_, holiday_calendar in regular_dates
+ ]
+
+ # List of Series for ad-hoc times.
+ ad_hoc = []
+ for time_, dti in ad_hoc_dates:
+ dti = dti[(dti >= start_date) & (dti <= end_date)]
+ srs = pd.Series(index=dti, data=days_at_time(dti, time_, self.tz, 0))
+ ad_hoc.append(srs)
+
+ merged = ad_hoc + regular
+ if not merged:
+ # Concat barfs if the input has length 0.
+ return pd.Series(
+ [], index=pd.DatetimeIndex([]), dtype="datetime64[ns, UTC]"
+ )
+
+ result = pd.concat(merged)
+ # where there are multiple occurrences of the same date, keep only the first
+ result = result[~result.index.duplicated(keep="first")]
+ result = result.sort_index()
+ # exclude any special date that coincides with a holiday
+ adhoc_holidays = pd.DatetimeIndex(self.adhoc_holidays)
+ result = result[~result.index.isin(adhoc_holidays)]
+ regular_holidays = self.regular_holidays
+ if regular_holidays is not None:
+ reg_holidays = regular_holidays.holidays(start_date, end_date)
+ if not reg_holidays.empty:
+ result = result[~result.index.isin(reg_holidays)]
+ return result
+
+ def _calculate_special_opens(
+ self, start: pd.Timestamp, end: pd.Timestamp
+ ) -> pd.Series:
+ return self._special_dates(
+ self.special_opens,
+ self.special_opens_adhoc,
+ start,
+ end,
+ )
+
+ def _calculate_special_closes(
+ self, start: pd.Timestamp, end: pd.Timestamp
+ ) -> pd.Series:
+ return self._special_dates(
+ self.special_closes,
+ self.special_closes_adhoc,
+ start,
+ end,
+ )
+
+
+def _check_breaks_match(break_starts_nanos: np.ndarray, break_ends_nanos: np.ndarray):
+ """Checks that break_starts_nanos and break_ends_nanos match."""
+ nats_match = np.equal(NP_NAT == break_starts_nanos, NP_NAT == break_ends_nanos)
+ if not nats_match.all():
+ raise ValueError(
+ f"""
+ Mismatched market breaks
+ Break starts:
+ {break_starts_nanos[~nats_match]}
+ Break ends:
+ {break_ends_nanos[~nats_match]}
+ """
+ )
+
+
+def scheduled_special_times(
+ special_days: HolidayCalendar | int,
+ start: pd.Timestamp,
+ end: pd.Timestamp,
+ time: datetime.time,
+ tz: ZoneInfo,
+) -> pd.Series:
+ """Return map of dates to special times.
+
+ Parameters
+ ----------
+ special_days
+ Describes dates with a special time. Pass as either:
+ HolidayCalendar : calendar with rules describing the dates on
+ which special times apply
+
+ int : integer describing a weekday with a regular special
+ time (0 - Monday, ..., 6 - Sunday).
+
+ start
+ Date from which to evaluate mapping (inclusive of `start`).
+
+ end
+ Date to which to evaluate mapping (inclusive of `end`).
+
+ time
+ Special time for dates described by `special_days`.
+
+ tz
+ The timezone in which to interpret `time`.
+
+ Returns
+ -------
+ pd.Series
+ Series mapping dates to special times.
+
+ Index is timezone naive.
+ dtype is datetime64[ns, UTC].
+ """
+ if isinstance(special_days, int):
+ day_str = "W-" + day_name[special_days].upper()[0:3]
+ days = pd.date_range(start, end, freq=day_str)
+ else:
+ days = special_days.holidays(start, end)
+ if not isinstance(days, pd.DatetimeIndex):
+ # days will be pd.Index if empty
+ days = pd.DatetimeIndex(days)
+ return pd.Series(
+ index=days,
+ data=days_at_time(days, time, tz=tz, day_offset=0),
+ )
+
+
+def _overwrite_special_dates(
+ session_labels: pd.DatetimeIndex,
+ standard_times: pd.DatetimeIndex,
+ special_times: pd.Series,
+) -> None:
+ """Overwrite standard times of a session bound with special times.
+
+ `session_labels` required for alignment.
+ """
+ # Short circuit when nothing to apply.
+ if special_times.empty:
+ return
+
+ len_m, len_oc = len(session_labels), len(standard_times)
+ if len_m != len_oc:
+ raise ValueError(
+ "Found misaligned dates while building calendar.\nExpected"
+ " session_labels to be the same length as open_or_closes but,\n"
+ f"len(session_labels)={len_m}, len(open_or_closes)={len_oc}"
+ )
+
+ # Find the array indices corresponding to each special date.
+ indexer = session_labels.get_indexer(special_times.index)
+
+ # -1 indicates that no corresponding entry was found. If any -1s are
+ # present, then we have special dates that doesn't correspond to any
+ # trading day.
+ if -1 in indexer:
+ bad_dates = list(special_times[indexer == -1])
+ raise ValueError(f"Special dates {bad_dates} are not sessions.")
+
+ # NOTE: This is a slightly dirty hack. We're in-place overwriting the
+ # internal data of an Index, which is conceptually immutable. Since we're
+ # maintaining sorting, this should be ok, but this is a good place to
+ # sanity check if things start going haywire with calendar computations.
+ standard_times.values[indexer] = special_times.values
+
+
+def _remove_breaks_for_special_dates(
+ session_labels: pd.DatetimeIndex,
+ standard_break_times: pd.DatetimeIndex | None,
+ special_times: pd.Series,
+) -> None:
+ """Remove standard break times for sessions with special times."
+
+ Overwrites standard break times with NaT for sessions with speical
+ times. Anticipated that `special_times` will be special times for
+ 'opens' or 'closes'.
+
+ `session_labels` required for alignment.
+ """
+ # Short circuit when we have no breaks
+ if standard_break_times is None:
+ return
+
+ # Short circuit when nothing to apply.
+ if special_times.empty:
+ return
+
+ len_m, len_oc = len(session_labels), len(standard_break_times)
+ if len_m != len_oc:
+ raise ValueError(
+ "Found misaligned dates while building calendar.\n"
+ "Expected session_labels to be the same length as break_starts,\n"
+ f"but len(session_labels)={len_m}, len(break_start_or_end)={len_oc}"
+ )
+
+ # Find the array indices corresponding to each special date.
+ indexer = session_labels.get_indexer(special_times.index)
+
+ # -1 indicates that no corresponding entry was found. If any -1s are
+ # present, then we have special dates that doesn't correspond to any
+ # trading day.
+ if -1 in indexer:
+ bad_dates = list(special_times[indexer == -1])
+ raise ValueError(f"Special dates {bad_dates} are not trading days.")
+
+ # NOTE: This is a slightly dirty hack. We're in-place overwriting the
+ # internal data of an Index, which is conceptually immutable. Since we're
+ # maintaining sorting, this should be ok, but this is a good place to
+ # sanity check if things start going haywire with calendar computations.
+ standard_break_times.values[indexer] = NP_NAT
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_aixk.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_aixk.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0c8cbfa89c634fe7ae4ae7af29cdc1949ce2cf8
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_aixk.py
@@ -0,0 +1,246 @@
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import (
+ Holiday,
+ next_monday,
+ nearest_workday,
+ next_workday,
+)
+
+from .common_holidays import new_years_day, eid_al_adha_first_day
+from .exchange_calendar import (
+ HolidayCalendar,
+ ExchangeCalendar,
+)
+
+
+NewYearsDay = new_years_day()
+
+NewYearHoliday = Holiday(
+ "New Year Holiday",
+ month=1,
+ day=2,
+)
+
+OrthodoxChristmasDay = Holiday(
+ "Orthodox Christmas Day",
+ month=1,
+ day=7,
+)
+
+InternationalWomensDay = Holiday(
+ "International Women's Day",
+ month=3,
+ day=8,
+ observance=nearest_workday,
+)
+
+NauryzHoliday1 = Holiday(
+ "Nauryz Holiday",
+ month=3,
+ day=21,
+ observance=next_monday,
+)
+
+NauryzHoliday2 = Holiday(
+ "Nauryz Holiday",
+ month=3,
+ day=21,
+ observance=lambda dt: next_workday(next_monday(dt)),
+)
+
+NauryzHoliday3 = Holiday(
+ "Nauryz Holiday",
+ month=3,
+ day=21,
+ observance=lambda dt: next_workday(next_workday(next_monday(dt))),
+)
+
+KazakhstanPeopleSolidarityDay = Holiday(
+ "Kazakhstan People Solidarity Day",
+ month=5,
+ day=1,
+ observance=next_monday,
+)
+
+DefendersDay = Holiday(
+ "Defender's Day",
+ month=5,
+ day=7,
+ observance=next_monday,
+ start_date=pd.Timestamp("2013-01-01"),
+)
+
+VictoryDayHoliday = Holiday(
+ "Victory Day Holiday",
+ month=5,
+ day=9,
+ observance=nearest_workday,
+)
+
+CapitalCityDay = Holiday(
+ "Capital City Day",
+ month=7,
+ day=6,
+ observance=next_monday,
+)
+
+ConstitutionDay = Holiday(
+ "Constitution Day",
+ month=8,
+ day=30,
+ observance=next_monday,
+)
+
+RepublicDayHoliday = Holiday(
+ "Republic Day Holiday",
+ month=10,
+ day=24,
+ observance=next_monday,
+ start_date=pd.Timestamp("2022-01-01"),
+)
+
+RepublicDay = Holiday(
+ "Republic Day",
+ month=10,
+ day=25,
+ observance=next_monday,
+ start_date=pd.Timestamp("2022-01-01"),
+)
+
+FirstPresidentDay = Holiday(
+ "First President Day",
+ month=12,
+ day=1,
+ observance=next_monday,
+ start_date=pd.Timestamp("2013-01-01"),
+ end_date="2022",
+)
+
+IndependenceDay = Holiday(
+ "Independence Day",
+ month=12,
+ day=16,
+ observance=next_monday,
+)
+
+IndependenceDayHoliday = Holiday(
+ "Independence Day",
+ month=12,
+ day=17,
+ observance=next_monday,
+ end_date="2022",
+)
+
+
+class AIXKExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Astana International Exchange (XIST).
+ Available here: https://www.aix.kz/trading/trading-calendar/
+
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - New Year Holiday
+ - Orthodox Christmas Day
+ - International Women's Day
+ - Nauryz Holiday
+ - Nauryz Holiday
+ - Nauryz Holiday
+ - Kazakhstan People Solidarity Day
+ - Defender’s Day
+ - Victory Day Holiday
+ - Capital City Day
+ - Capital City Day
+ - Kurban Ait Holiday (Eid-al-Adha)
+ - Constitution Day
+ - Republic Day Holiday
+ - Republic Day
+ - First President Day
+ - Independence Day
+
+ Holidays No Longer Observed:
+ - Independence Day Holiday (until 2021, inclusive)
+ - First President Day (until 2021, inclusive)
+
+ Early Closes:
+ - None
+ """
+
+ name = "AIXK"
+
+ tz = ZoneInfo("Asia/Almaty")
+
+ open_times = ((None, time(11)),)
+
+ close_times = ((None, time(17, 00)),)
+
+ @classmethod
+ def bound_min(cls) -> pd.Timestamp:
+ return pd.Timestamp("2017-01-01")
+
+ def _bound_min_error_msg(self, start: pd.Timestamp) -> str:
+ msg = super()._bound_min_error_msg(start)
+ return msg + f" (The exchange {self.name} was founded in 2017.)"
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ NewYearHoliday,
+ OrthodoxChristmasDay,
+ InternationalWomensDay,
+ NauryzHoliday1,
+ NauryzHoliday2,
+ NauryzHoliday3,
+ KazakhstanPeopleSolidarityDay,
+ DefendersDay,
+ VictoryDayHoliday,
+ CapitalCityDay,
+ ConstitutionDay,
+ RepublicDayHoliday,
+ RepublicDay,
+ FirstPresidentDay,
+ IndependenceDay,
+ IndependenceDayHoliday,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ # It is common in Kazakhstan to have holidays also on days
+ # between regular holiday and weekend
+ misc_holidays = [
+ # Bridge Day between Women's day - Weekend
+ pd.Timestamp("2018-03-09"),
+ # Bridge Day between Weekend - Kazakhstan People Solidarity Day
+ pd.Timestamp("2018-04-30"),
+ # Bridge Day between Defender's Day - Victory Day
+ pd.Timestamp("2018-05-08"),
+ # Bridge Day between Constitution Day - Weekend
+ pd.Timestamp("2018-08-31"),
+ # Bridge Day between New Year's Eve - New Year's day
+ pd.Timestamp("2018-12-31"),
+ # Bridge Day between Victory Day - Weekend
+ pd.Timestamp("2019-05-10"),
+ # Bridge Day between New Year's day - Weekend
+ pd.Timestamp("2020-01-03"),
+ # Bridge Day between Independence day - Weekend
+ pd.Timestamp("2020-12-18"),
+ # Bridge Day between Weekend - Capital City day
+ pd.Timestamp("2021-06-05"),
+ # New Year holiday
+ pd.Timestamp("2022-01-03"),
+ pd.Timestamp("2022-01-04"),
+ # Bridge Day between Weekend - Women's day
+ pd.Timestamp("2022-03-07"),
+ # Defender's day
+ pd.Timestamp("2022-05-10"),
+ # Bridge Day between Weekend - Constitution day
+ pd.Timestamp("2022-08-29"),
+ ]
+ return list(chain(misc_holidays, eid_al_adha_first_day))
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_asex.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_asex.py
new file mode 100644
index 0000000000000000000000000000000000000000..7557eb86600259b8ce559418235d2b03306b424b
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_asex.py
@@ -0,0 +1,161 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time, timedelta
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday
+
+from .common_holidays import (
+ assumption_day,
+ christmas,
+ christmas_eve,
+ epiphany,
+ european_labour_day,
+ new_years_day,
+ orthodox_easter,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+
+NewYearsDay = new_years_day()
+
+Epiphany = epiphany()
+
+OrthodoxAshMonday = orthodox_easter() - timedelta(48)
+
+NationalHoliday1 = Holiday(
+ "Independence Day",
+ month=3,
+ day=25,
+)
+
+OrthodoxGoodFriday = orthodox_easter() - timedelta(2)
+
+OrthodoxEasterMonday = orthodox_easter() + timedelta(1)
+
+LabourDay = european_labour_day()
+
+OrthodoxWhitMonday = orthodox_easter() + timedelta(50)
+
+AssumptionDay = assumption_day()
+
+NationalHoliday2 = Holiday(
+ "Ochi Day",
+ month=10,
+ day=28,
+)
+
+ChristmasEve = christmas_eve(start_date="2009")
+
+ChristmasDay = christmas()
+
+SecondDayOfChristmas = Holiday(
+ "Second Day of Christmas",
+ month=12,
+ day=26,
+)
+
+
+class ASEXExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Athens Stock Exchange (ASEX).
+
+ Open Time: 10:00 AM, EEST
+ Close Time: 5:00 PM, EEST (until 2008-09-29)
+ 5:20 PM, EEST (starting 2008-09-29)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Epiphany (Jan 6)
+ - Orthodox Ash Monday (48 days before Orthodox Easter Sunday)
+ - National Holiday (Mar 25)
+ - Good Friday
+ - Easter Monday
+ - Orthodox Good Friday
+ - Orthodox Easter Monday
+ - Labour Day (May 1)
+ - Orthodox Whit Monday (50 days after Orthodox Easter Sunday)
+ - Assumption Day (Aug 15)
+ - National Holiday (Oct 28)
+ - Christmas Eve
+ - Christmas Day
+ - Second Day of Christmas (Dec 26)
+
+ Early Closes:
+ - None
+ """
+
+ name = "ASEX"
+
+ tz = ZoneInfo("Europe/Athens")
+
+ open_times = ((None, time(10)),)
+
+ close_times = ((None, time(17, 00)), (pd.Timestamp("2008-09-29"), time(17, 20)))
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ Epiphany,
+ NationalHoliday1,
+ GoodFriday,
+ EasterMonday,
+ LabourDay,
+ AssumptionDay,
+ NationalHoliday2,
+ ChristmasEve,
+ ChristmasDay,
+ SecondDayOfChristmas,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ debt_crisis = pd.date_range("2015-06-29", "2015-07-31", freq="B")
+
+ debt_crisis_holidays = [pd.Timestamp(str(date)) for date in debt_crisis]
+
+ misc_adhoc_holidays = [
+ # In 2002, market closed for unknown reason
+ pd.Timestamp("2002-05-07"),
+ # In 2004, Assumption Day fell on a sunday, observed on a Friday
+ pd.Timestamp("2004-08-13"),
+ # In 2008, worker strikes closed the market for 2 days in March
+ pd.Timestamp("2008-03-04"),
+ pd.Timestamp("2008-03-05"),
+ # In 2013, May Day strikes closed the market
+ pd.Timestamp("2013-05-07"),
+ # In 2014, New Year's Eve was observed as a holiday
+ pd.Timestamp("2014-12-31"),
+ # In 2016, Labour Day fell on a Sunday, observed on Tuesday
+ pd.Timestamp("2016-05-03"),
+ ]
+
+ return list(
+ chain(
+ debt_crisis_holidays,
+ misc_adhoc_holidays,
+ # TODO: Investigate making orthodox easter adhocs actual holidays
+ OrthodoxGoodFriday,
+ OrthodoxEasterMonday,
+ OrthodoxWhitMonday,
+ OrthodoxAshMonday,
+ )
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_bvmf.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_bvmf.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc985694bfa02667e052cc54d0c3a56e138f021c
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_bvmf.py
@@ -0,0 +1,225 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import (
+ Day,
+ Easter,
+ GoodFriday,
+ Holiday,
+ previous_friday,
+)
+
+from .common_holidays import corpus_christi
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+# Universal Confraternization (new years day)
+ConfUniversal = Holiday(
+ "Dia da Confraternizacao Universal",
+ month=1,
+ day=1,
+)
+# Sao Paulo city birthday
+AniversarioSaoPaulo = Holiday(
+ "Aniversario de Sao Paulo",
+ month=1,
+ day=25,
+ # in 2022, BVMF was opened on this day
+ end_date="2022-01-01",
+)
+# Carnival Monday
+CarnavalSegunda = Holiday(
+ "Carnaval Segunda", month=1, day=1, offset=[Easter(), Day(-48)]
+)
+# Carnival Tuesday
+CarnavalTerca = Holiday("Carnaval Terca", month=1, day=1, offset=[Easter(), Day(-47)])
+# Ash Wednesday (short day)
+QuartaCinzas = Holiday(
+ "Quarta Cinzas",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(-46)],
+ start_date="2016-01-01",
+)
+# Good Friday
+SextaPaixao = GoodFriday
+# Feast of the Most Holy Body of Christ
+CorpusChristi = corpus_christi()
+# Tiradentes Memorial
+Tiradentes = Holiday(
+ "Tiradentes",
+ month=4,
+ day=21,
+)
+# Labor Day
+DiaTrabalho = Holiday(
+ "Dia Trabalho",
+ month=5,
+ day=1,
+)
+# Constitutionalist Revolution
+Constitucionalista_prepandemic = Holiday(
+ "Constitucionalista pre-pandemia",
+ month=7,
+ day=9,
+ start_date="1998-01-01",
+ end_date="2020-01-01",
+)
+Constitucionalista_pospandemic = Holiday(
+ "Constitucionalista pos-pandemia",
+ month=7,
+ day=9,
+ start_date="2021-01-01",
+ end_date="2022-01-01",
+)
+# Independence Day
+Independencia = Holiday(
+ "Independencia",
+ month=9,
+ day=7,
+)
+# Our Lady of Aparecida
+Aparecida = Holiday(
+ "Nossa Senhora de Aparecida",
+ month=10,
+ day=12,
+)
+# All Souls' Day
+Finados = Holiday(
+ "Dia dos Finados",
+ month=11,
+ day=2,
+)
+# Proclamation of the Republic
+ProclamacaoRepublica = Holiday(
+ "Proclamacao da Republica",
+ month=11,
+ day=15,
+)
+# Day of Black Awareness
+ConscienciaNegra = Holiday(
+ "Dia da Consciencia Negra",
+ month=11,
+ day=20,
+ start_date="2004-01-01",
+ end_date="2022-01-01",
+)
+# Christmas Eve
+VesperaNatal = Holiday(
+ "Vespera Natal",
+ month=12,
+ day=24,
+)
+# Christmas
+Natal = Holiday(
+ "Natal",
+ month=12,
+ day=25,
+)
+# New Year's Eve
+AnoNovo = Holiday(
+ "Ano Novo",
+ month=12,
+ day=31,
+ observance=previous_friday,
+)
+
+
+class BVMFExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for BM&F BOVESPA (BVMF).
+
+ Open Time: 10:00 AM, Brazil/Sao Paulo
+ Close Time:
+ - Until 2019-11-01: 5:00 PM, Brazil/Sao Paulo
+ - Starting from 2019-11-04: 6:00 PM, Brazil/Sao Paulo
+
+ Regularly-Observed Holidays:
+ - Universal Confraternization (New year's day, Jan 1)
+ - Sao Paulo City Anniversary (Jan 25)
+ - Carnaval Monday (48 days before Easter)
+ - Carnaval Tuesday (47 days before Easter)
+ - Ash Wednesday (short day / half day trading) (46 days before Easter)
+ - Passion of the Christ (Good Friday, 2 days before Easter)
+ - Corpus Christi (60 days after Easter)
+ - Tiradentes (April 21)
+ - Labor day (May 1)
+ - Constitutionalist Revolution (July 9 after 1997)
+ - Independence Day (September 7)
+ - Our Lady of Aparecida Feast (October 12)
+ - All Souls' Day (November 2)
+ - Proclamation of the Republic (November 15)
+ - Day of Black Awareness (November 20 after 2004)
+ - Christmas (December 24 and 25)
+ - Business day before New Year's Day
+ - December 29 if NYE falls on a Sunday
+ - December 30 if NYE falls on a Saturday
+ - December 31 if NYE falls on Monday-Friday
+ """
+
+ name = "BVMF"
+
+ tz = ZoneInfo("America/Sao_Paulo")
+
+ regular_late_open = time(13)
+
+ open_times = ((None, time(10)),)
+
+ close_times = (
+ (None, time(17, 0)),
+ (pd.Timestamp("2019-11-04"), time(18, 0)),
+ )
+
+ @property
+ def adhoc_holidays(self):
+ # CopaDoMundo2014 Brazil hosted World Cup and played Croatia (and won 3-1!)
+ return [pd.Timestamp("2014-06-12")]
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ ConfUniversal,
+ AniversarioSaoPaulo,
+ CarnavalSegunda,
+ CarnavalTerca,
+ SextaPaixao,
+ CorpusChristi,
+ Tiradentes,
+ DiaTrabalho,
+ Constitucionalista_prepandemic,
+ Constitucionalista_pospandemic,
+ Independencia,
+ Aparecida,
+ Finados,
+ ProclamacaoRepublica,
+ ConscienciaNegra,
+ VesperaNatal,
+ Natal,
+ AnoNovo,
+ ]
+ )
+
+ @property
+ def special_opens(self):
+ return [
+ (
+ self.regular_late_open,
+ HolidayCalendar([QuartaCinzas]),
+ ),
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_cmes.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_cmes.py
new file mode 100644
index 0000000000000000000000000000000000000000..86661c630d023674c3f61409f5ee39aecac136fc
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_cmes.py
@@ -0,0 +1,111 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import (
+ GoodFriday,
+ USLaborDay,
+ USPresidentsDay,
+ USThanksgivingDay,
+)
+
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+from .us_holidays import (
+ Christmas,
+ ChristmasEveBefore1993,
+ ChristmasEveInOrAfter1993,
+ USBlackFridayInOrAfter1993,
+ USIndependenceDay,
+ USMartinLutherKingJrAfter1998,
+ USMemorialDay,
+ USNationalDaysofMourning,
+ USNewYearsDay,
+)
+
+# Useful resources for making changes to this file:
+# http://www.cmegroup.com/tools-information/holiday-calendar.html
+
+
+class CMESExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Chicago Mercantile Exchange (CMES).
+
+ Open Time: 5:00 PM, America/Chicago
+ Close Time: 5:00 PM, America/Chicago
+
+ Regularly-Observed Holidays:
+ - New Years Day
+ - Good Friday
+ - Christmas
+ """
+
+ name = "CMES"
+
+ tz = ZoneInfo("America/Chicago")
+
+ open_times = ((None, time(17)),)
+
+ close_times = ((None, time(17)),)
+
+ @property
+ def open_offset(self):
+ return -1
+
+ @property
+ def regular_holidays(self):
+ # The CME has different holiday rules depending on the type of
+ # instrument. For example, http://www.cmegroup.com/tools-information/holiday-calendar/files/2016-4th-of-july-holiday-schedule.pdf # noqa
+ # shows that Equity, Interest Rate, FX, Energy, Metals & DME Products
+ # close at 1200 CT on July 4, 2016, while Grain, Oilseed & MGEX
+ # Products and Livestock, Dairy & Lumber products are completely
+ # closed.
+
+ # For now, we will treat the CME as having a single calendar, and just
+ # go with the most conservative hours - and treat July 4 as an early
+ # close at noon.
+ return HolidayCalendar(
+ [
+ USNewYearsDay,
+ GoodFriday,
+ Christmas,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return USNationalDaysofMourning
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ time(12),
+ HolidayCalendar(
+ [
+ USMartinLutherKingJrAfter1998,
+ USPresidentsDay,
+ USMemorialDay,
+ USLaborDay,
+ USIndependenceDay,
+ USThanksgivingDay,
+ USBlackFridayInOrAfter1993,
+ ChristmasEveBefore1993,
+ ChristmasEveInOrAfter1993,
+ ]
+ ),
+ )
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_iepa.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_iepa.py
new file mode 100644
index 0000000000000000000000000000000000000000..2be6bdccca5dfeb2f54be4a9619c6b4be9364ad0
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_iepa.py
@@ -0,0 +1,79 @@
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+from pandas import Timestamp
+from pandas.tseries.holiday import (
+ GoodFriday,
+ USLaborDay,
+ USPresidentsDay,
+ USThanksgivingDay,
+)
+
+from .exchange_calendar import ExchangeCalendar
+from exchange_calendars.exchange_calendar import HolidayCalendar
+from exchange_calendars.us_holidays import (
+ Christmas,
+ USIndependenceDay,
+ USMartinLutherKingJrAfter1998,
+ USMemorialDay,
+ USNationalDaysofMourning,
+ USNewYearsDay,
+)
+
+
+class IEPAExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for ICE US (IEPA).
+
+ Open Time: 8pm, America/New_York
+ Close Time: 6pm, America/New_York
+
+ https://www.theice.com/publicdocs/futures_us/ICE_Futures_US_Regular_Trading_Hours.pdf # noqa
+ """
+
+ name = "IEPA"
+
+ tz = ZoneInfo("America/New_York")
+
+ open_times = ((None, time(20)),)
+
+ close_times = ((None, time(18)),)
+
+ @property
+ def open_offset(self):
+ return -1
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ time(13),
+ HolidayCalendar(
+ [
+ USMartinLutherKingJrAfter1998,
+ USPresidentsDay,
+ USMemorialDay,
+ USIndependenceDay,
+ USLaborDay,
+ USThanksgivingDay,
+ ]
+ ),
+ )
+ ]
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ USNationalDaysofMourning,
+ # ICE was only closed on the first day of the Hurricane Sandy
+ # closings (was not closed on 2012-10-30)
+ [Timestamp("2012-10-29")],
+ )
+ )
+
+ @property
+ def regular_holidays(self):
+ # https://www.theice.com/publicdocs/futures_us/exchange_notices/NewExNot2016Holidays.pdf # noqa
+ return HolidayCalendar([USNewYearsDay, GoodFriday, Christmas])
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xams.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xams.py
new file mode 100644
index 0000000000000000000000000000000000000000..cee282178b908197ed481380a05e4ae7401fe547
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xams.py
@@ -0,0 +1,116 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday
+
+from .common_holidays import (
+ ascension_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import WEEKDAYS, HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+AscensionDay = ascension_day(end_date="2001")
+WhitMonday = whit_monday(end_date="2002")
+
+QueensDay = Holiday(
+ "Queen's Day",
+ month=4,
+ day=30,
+ end_date="2002",
+)
+
+LabourDay = european_labour_day()
+
+ChristmasEve = christmas_eve(days_of_week=WEEKDAYS)
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEveBefore2002 = new_years_eve(end_date="2002")
+NewYearsEveInOrAfter2002 = new_years_eve(
+ start_date="2002",
+ days_of_week=WEEKDAYS,
+)
+
+
+class XAMSExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Euronext Amsterdam exchange, and the primary calendar for
+ the Netherlands.
+
+ Open Time: 9:00 AM, CET (Central European Time)
+ Close Time: 5:30 PM, CET (Central European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Christmas Day
+ - Boxing Day
+
+ Early Closes:
+ - Christmas Eve
+ - New Year's Eve
+
+ Other countries on the Euronext:
+ - Belgium
+ - France
+ - Portugal
+ """
+
+ # Source: https://www.euronext.com/en/calendars-hours
+ regular_early_close = time(14, 5)
+
+ name = "XAMS" # Euronext Amsterdam
+ tz = ZoneInfo("Europe/Amsterdam")
+ open_times = ((None, time(9)),)
+ close_times = ((None, time(17, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ GoodFriday,
+ EasterMonday,
+ AscensionDay,
+ WhitMonday,
+ QueensDay,
+ LabourDay,
+ Christmas,
+ BoxingDay,
+ NewYearsEveBefore2002,
+ ]
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar([ChristmasEve, NewYearsEveInOrAfter2002]),
+ ),
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xasx.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xasx.py
new file mode 100644
index 0000000000000000000000000000000000000000..06b9b23b92e2cb528b5ba8222f67666beaf8d875
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xasx.py
@@ -0,0 +1,246 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+
+from dateutil.relativedelta import MO
+from pandas import DateOffset, Timestamp
+from pandas.tseries.holiday import (
+ EasterMonday,
+ GoodFriday,
+ Holiday,
+ previous_friday,
+ sunday_to_monday,
+ weekend_to_monday,
+)
+from zoneinfo import ZoneInfo
+
+from .common_holidays import (
+ anzac_day,
+ boxing_day,
+ christmas,
+ new_years_day,
+ weekend_boxing_day,
+ weekend_christmas,
+)
+from .exchange_calendar import ExchangeCalendar, HolidayCalendar
+
+NewYearsDay = new_years_day(observance=weekend_to_monday)
+
+# "Celebrating Australia: A history of Australia Day" Elizabeth Kwan
+# https://www.australiaday.org.au/storage/celebratingaustralia.pdf
+# present rule follows the 1994 agreement between the States to
+# synchronize the holiday with weekends mondayized
+AustraliaDay = Holiday(
+ "Australia Day",
+ month=1,
+ day=26,
+ start_date=Timestamp("1994-01-01"),
+ observance=weekend_to_monday,
+)
+
+# prior to 1993 the holiday was observed on the Monday
+# following, or on, the 26th of January
+AustraliaDayPre88 = Holiday(
+ "Australia Day",
+ month=1,
+ day=26,
+ start_date=Timestamp("1960-01-01"),
+ end_date=Timestamp("1987-12-31"),
+ offset=DateOffset(weekday=MO(1)),
+)
+# The 1988 Bi-Centennial celebrations saw an extra holiday
+# and Australia Day observed on the actual date
+AustraliaDay1988 = Holiday(
+ "Australia Day",
+ month=1,
+ day=26,
+ start_date=Timestamp("1988-01-01"),
+ end_date=Timestamp("1988-12-31"),
+)
+# ASX did not close for Australia Day in 1993 since
+# States observed different dates prior to 1994
+AustraliaDayPost88Pre93 = Holiday(
+ "Australia Day",
+ month=1,
+ day=26,
+ start_date=Timestamp("1989-01-01"),
+ end_date=Timestamp("1992-12-31"),
+ offset=DateOffset(weekday=MO(1)),
+)
+
+# Anzac Day was observed on Monday when it fell on a Sunday in
+# 2010 but that does not appear to have been the case previously.
+# ANZAC Day observance was a special case in 2010
+AnzacDayNonMondayized = anzac_day(end_date="2010")
+AnzacDay2010 = anzac_day(
+ observance=sunday_to_monday, start_date="2010", end_date="2011"
+)
+AnzacDay = anzac_day(start_date="2011")
+
+# When Easter Monday and Anzac Day coincided in 2011, Easter Tuesday was
+# also observed as a public holiday. Note that this isn't defined as a
+# rule, because it will happen next in 2095 (and then in 2163), and
+# there isn't a great way to tell how this will be handled at that point.
+EasterTuesday2011AdHoc = Timestamp("2011-04-26")
+
+QueensBirthday = Holiday(
+ "Queen's Birthday",
+ month=6,
+ day=1,
+ end_date="2023",
+ offset=[DateOffset(weekday=MO(2))],
+)
+
+KingsBirthday = Holiday(
+ "Kings's Birthday",
+ month=6,
+ day=1,
+ start_date="2023",
+ offset=[DateOffset(weekday=MO(2))],
+)
+
+# ASX cash markets (but NOT ASX 24!) usually have a couple of early
+# closes for the last trading day before Christmas and also the last day
+# of the Calendar year. There was an exception to this in 2022 (see below).
+#
+# Sources:
+# https://www.asx.com.au/markets/market-resources/trading-hours-calendar/cash-market-trading-hours/trading-calendar
+LastTradingDayBeforeChristmasPre2022 = Holiday(
+ "Last Trading Day Before Christmas",
+ month=12,
+ day=24,
+ start_date="2010",
+ end_date="2022",
+ observance=previous_friday,
+)
+LastTradingDayBeforeChristmasPost2022 = Holiday(
+ "Last Trading Day Before Christmas",
+ month=12,
+ day=24,
+ start_date="2023",
+ observance=previous_friday,
+)
+
+Christmas = christmas()
+WeekendChristmas = weekend_christmas()
+BoxingDay = boxing_day()
+WeekendBoxingDay = weekend_boxing_day()
+
+LastTradingDayOfCalendarYearPre2022 = Holiday(
+ "Last Trading Day Of Calendar Year",
+ month=12,
+ day=31,
+ start_date="2010",
+ end_date="2022",
+ observance=previous_friday,
+)
+LastTradingDayOfCalendarYearPost2022 = Holiday(
+ "Last Trading Day Of Calendar Year",
+ month=12,
+ day=31,
+ start_date="2023",
+ observance=previous_friday,
+)
+
+# additional ad-hoc holidays
+NYEMonday1984AdHoc = Timestamp("1984-12-31")
+NYEMonday1990AdHoc = Timestamp("1990-12-31")
+Bicentennial1988 = Timestamp("1988-01-25")
+Y2KTesting = Timestamp("1999-12-31")
+QueenMourning2022 = Timestamp("2022-09-22")
+
+
+class XASXExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Australian Securities Exchange in Sydney.
+
+ Open Time: 10:00 AM, Australian Eastern Time
+ Close Time: 4:00 PM, Australian Eastern Time
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Australia Day
+ - Good Friday
+ - Easter Monday
+ - Anzac Day
+ - Queen's Birthday
+ - Christmas Day
+ - Boxing Day
+
+ Early Closes:
+ - Last trading day before Christmas
+ - Last trading day of the calendar year
+ """
+
+ regular_early_close = time(14, 10)
+
+ name = "XASX"
+
+ tz = ZoneInfo("Australia/Sydney")
+
+ open_times = ((None, time(10)),) # Zipline compatability (10,1); else (10,0)
+
+ close_times = ((None, time(16)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ AustraliaDay,
+ AustraliaDayPre88,
+ AustraliaDay1988,
+ AustraliaDayPost88Pre93,
+ GoodFriday,
+ EasterMonday,
+ AnzacDayNonMondayized,
+ AnzacDay2010,
+ AnzacDay,
+ QueensBirthday,
+ KingsBirthday,
+ Christmas,
+ WeekendChristmas,
+ BoxingDay,
+ WeekendBoxingDay,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [
+ EasterTuesday2011AdHoc,
+ NYEMonday1984AdHoc,
+ NYEMonday1990AdHoc,
+ Bicentennial1988,
+ Y2KTesting,
+ QueenMourning2022,
+ ]
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [
+ LastTradingDayBeforeChristmasPre2022,
+ LastTradingDayOfCalendarYearPre2022,
+ LastTradingDayBeforeChristmasPost2022,
+ LastTradingDayOfCalendarYearPost2022,
+ ]
+ ),
+ ),
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbkk.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbkk.py
new file mode 100644
index 0000000000000000000000000000000000000000..47d132c2c871c850dcf7718098fbec017545ef81
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbkk.py
@@ -0,0 +1,126 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+from .xbkk_holidays import (
+ ChakriMemorialDay,
+ ChulalongkornDay,
+ CoronationDay2016AndBefore,
+ CoronationDay2019AndAfter,
+ HalfYearHoliday,
+ HMKingsBirthday,
+ HMQueenMothersBirthday,
+ HMQueensBirthday,
+ KingBhumibolsBirthday,
+ LabourDay,
+ NewYearsDay,
+ NewYearsEve,
+ SongkranFestival1,
+ SongkranFestival2,
+ SongkranFestival3,
+ ThailandConstitutionDay,
+ ThePassingOfKingBhumibol,
+ asanha_bucha,
+ asanha_bucha_bridge_days,
+ coronation_bridge_days,
+ makha_bucha,
+ misc_adhoc,
+ new_years_bridge_days,
+ queens_birthday_bridge_days,
+ vesak,
+ vesak_bridge_days,
+)
+
+
+class XBKKExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Stock Exchange of Thailand in Bangkok.
+
+ Open Time: 10:00 AM, Indochina Time (ICT)
+ Close Time: 4:30 PM, Indochina Time (ICT)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Makha Bucha
+ - Chakri Memorial Day
+ - Songkran Festival
+ - Labour Day
+ - Coronation Day
+ - Vesak
+ - Her Majesty The Queen's Birthday
+ - Asanha Bucha
+ - His Majesty The King's Birthday
+ - Her Majesty The Queen Mother's Birthday
+ - The Passing of King Bhumibol
+ - Chulalongkorn Day
+ - King Bhumibol's Birthday
+ - Thailand Constitution Day
+ - New Year's Eve
+
+ Early Closes:
+ - None
+ """
+
+ name = "XBKK"
+
+ tz = ZoneInfo("Asia/Bangkok")
+
+ open_times = ((None, time(10)),)
+
+ close_times = ((None, time(16, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ ChakriMemorialDay,
+ SongkranFestival1,
+ SongkranFestival2,
+ SongkranFestival3,
+ LabourDay,
+ CoronationDay2016AndBefore,
+ CoronationDay2019AndAfter,
+ HMQueensBirthday,
+ HMKingsBirthday,
+ HMQueenMothersBirthday,
+ HalfYearHoliday,
+ ThePassingOfKingBhumibol,
+ ChulalongkornDay,
+ KingBhumibolsBirthday,
+ ThailandConstitutionDay,
+ NewYearsEve,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ makha_bucha,
+ vesak,
+ asanha_bucha,
+ new_years_bridge_days,
+ asanha_bucha_bridge_days,
+ queens_birthday_bridge_days,
+ coronation_bridge_days,
+ vesak_bridge_days,
+ misc_adhoc,
+ ),
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbog.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbog.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b70d386dc456a936060cce7cb0f236f5c721aca
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbog.py
@@ -0,0 +1,195 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import (
+ MO,
+ DateOffset,
+ Easter,
+ GoodFriday,
+ Holiday,
+ previous_friday,
+)
+from pandas.tseries.offsets import Day
+
+from .common_holidays import (
+ christmas,
+ epiphany,
+ european_labour_day,
+ immaculate_conception,
+ maundy_thursday,
+ new_years_day,
+ new_years_eve,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+# Used for "first Monday on or after date"
+next_monday_offset = DateOffset(weekday=MO(1))
+
+NewYearsDay = new_years_day()
+
+Epiphany = epiphany(offset=next_monday_offset)
+
+StJosephsDay = Holiday(
+ "St. Joseph's Day (next Monday)",
+ month=3,
+ day=19,
+ offset=next_monday_offset,
+)
+
+MaundyThursday = maundy_thursday()
+
+LabourDay = european_labour_day()
+
+MondayAfterAscensionDay = Holiday(
+ "Monday After Ascension Day",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(43)],
+)
+
+MondayAfterCorpusChristi = Holiday(
+ "Monday After Corpus Christi",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(64)],
+)
+
+MondayAfterSacredHeart = Holiday(
+ "Monday After Sacred Heart",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(71)],
+)
+
+StPeterAndStPaulDay = Holiday(
+ "St. Peter and St. Paul Day", month=6, day=29, offset=next_monday_offset
+)
+
+ColombiaIndependenceDay = Holiday(
+ "Colombian Independence Day",
+ month=7,
+ day=20,
+)
+
+BattleOfBoyaca = Holiday(
+ "Battle of Boyaca",
+ month=8,
+ day=7,
+)
+
+AssumptionDay = Holiday(
+ "Assumption Day (next Monday)",
+ month=8,
+ day=15,
+ offset=next_monday_offset,
+)
+
+DiaDeLaRaza = Holiday(
+ "Dia de la Raza",
+ month=10,
+ day=12,
+ offset=next_monday_offset,
+)
+
+AllSaintsDay = Holiday(
+ "All Saint's Day (next Monday)",
+ month=11,
+ day=1,
+ offset=next_monday_offset,
+)
+
+CartagenaIndependenceDay = Holiday(
+ "Cartagena Independence Day",
+ month=11,
+ day=11,
+ offset=next_monday_offset,
+)
+
+ImmaculateConception = immaculate_conception()
+
+ChristmasDay = christmas()
+
+LastTradingDay = new_years_eve(observance=previous_friday)
+
+
+class XBOGExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Colombia Stock Exchange (XBOG).
+
+ Open Time: 9:30 AM, EST
+ Close Time: 4:00 PM, EST
+
+ Regularly-Observed Holidays:
+ - New Years Day
+ - Epiphany
+ - St. Joseph's Day (first Monday on/after March 19)
+ - Maundy Thursday (Thursday before Easter)
+ - Good Friday
+ - Labour Day (May 1)
+ - Ascension Day (first Monday >= 39 days after Easter Sunday)
+ - Corpus Christi (first Monday >= 60 days after Easter Sunday)
+ - Sacred Heart (first Monday >= 68 days after Easter Sunday)
+ - Saint Peter and Saint Paul Day (first Monday on or after June 29)
+ - Independence Day (July 20)
+ - Battle of Boyaca (August 7)
+ - Assumption Day (first Monday on or after August 15)
+ - Columbus Day (first Monday on or after October 12)
+ - All Saint's Day (first Monday on or after November 1)
+ - Cartagena Independence Day (November 11)
+ - Immaculate Conception (December 8)
+ - Christmas Day
+
+ Early Closes:
+ - None
+ """
+
+ name = "XBOG"
+
+ # Though Bogota uses Colombia Standard Time, XBOG uses
+ # US Eastern for trading times
+ tz = ZoneInfo("America/New_York")
+
+ open_times = ((None, time(9, 30)),)
+
+ close_times = ((None, time(16)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ Epiphany,
+ StJosephsDay,
+ MaundyThursday,
+ GoodFriday,
+ LabourDay,
+ MondayAfterAscensionDay,
+ MondayAfterCorpusChristi,
+ MondayAfterSacredHeart,
+ StPeterAndStPaulDay,
+ ColombiaIndependenceDay,
+ BattleOfBoyaca,
+ AssumptionDay,
+ DiaDeLaRaza,
+ AllSaintsDay,
+ CartagenaIndependenceDay,
+ ImmaculateConception,
+ ChristmasDay,
+ LastTradingDay,
+ ]
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbom.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbom.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0c6dfad333b7d64785ebde7733d72e5fe4ddf53
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbom.py
@@ -0,0 +1,458 @@
+from datetime import time
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+
+from .precomputed_exchange_calendar import PrecomputedExchangeCalendar
+
+"""
+References for precomputed BSE/NSE holidays:
+ NSE: https://www.nseindia.com/products-services/equity-market-timings-holidays
+ BSE: https://www.bseindia.com/static/markets/marketinfo/listholi.aspx
+ Zerodha: https://zerodha.com/z-connect/category/traders-zone/holidays
+Although NSE/BSE provides only current year's dates, Zerodha provides holidays since 2013.
+"""
+
+precomputed_bse_holidays = pd.to_datetime(
+ [
+ "1997-01-23",
+ "1997-03-07",
+ "1997-03-24",
+ "1997-04-08",
+ "1997-04-14",
+ "1997-04-16",
+ "1997-04-18",
+ "1997-05-01",
+ "1997-05-08",
+ "1997-08-15",
+ "1997-08-18",
+ "1997-08-25",
+ "1997-10-02",
+ "1997-10-28",
+ "1997-10-29",
+ "1997-10-31",
+ "1997-12-25",
+ "1998-04-09",
+ "1998-04-14",
+ "1998-04-28",
+ "1998-12-25",
+ "1999-01-01",
+ "1999-01-20",
+ "1999-01-26",
+ "1999-03-02",
+ "1999-03-18",
+ "1999-03-25",
+ "1999-03-29",
+ "1999-04-02",
+ "1999-04-14",
+ "1999-04-27",
+ "1999-04-30",
+ "1999-09-13",
+ "1999-10-19",
+ "1999-11-08",
+ "1999-11-10",
+ "1999-11-23",
+ "1999-12-31",
+ "2000-01-26",
+ "2000-03-17",
+ "2000-03-20",
+ "2000-04-14",
+ "2000-04-21",
+ "2000-05-01",
+ "2000-08-15",
+ "2000-09-01",
+ "2000-10-02",
+ "2000-12-25",
+ "2001-01-01",
+ "2001-01-26",
+ "2001-03-06",
+ "2001-04-05",
+ "2001-04-13",
+ "2001-05-01",
+ "2001-08-15",
+ "2001-08-22",
+ "2001-10-02",
+ "2001-10-26",
+ "2001-11-16",
+ "2001-11-30",
+ "2001-12-17",
+ "2001-12-25",
+ "2002-03-25",
+ "2002-03-29",
+ "2002-05-01",
+ "2002-08-15",
+ "2002-09-10",
+ "2002-10-02",
+ "2002-10-15",
+ "2002-11-06",
+ "2002-11-19",
+ "2002-12-25",
+ "2003-02-13",
+ "2003-03-14",
+ "2003-03-18",
+ "2003-04-14",
+ "2003-04-18",
+ "2003-05-01",
+ "2003-08-15",
+ "2003-10-02",
+ "2003-11-26",
+ "2003-12-25",
+ "2004-01-01",
+ "2004-01-26",
+ "2004-02-02",
+ "2004-03-02",
+ "2004-04-09",
+ "2004-04-14",
+ "2004-04-26",
+ "2004-10-13",
+ "2004-10-22",
+ "2004-11-15",
+ "2004-11-26",
+ "2005-01-21",
+ "2005-01-26",
+ "2005-03-25",
+ "2005-04-14",
+ "2005-07-28",
+ "2005-08-15",
+ "2005-09-07",
+ "2005-10-12",
+ "2005-11-03",
+ "2005-11-04",
+ "2005-11-15",
+ "2006-01-11",
+ "2006-01-26",
+ "2006-02-09",
+ "2006-03-15",
+ "2006-04-06",
+ "2006-04-11",
+ "2006-04-14",
+ "2006-05-01",
+ "2006-08-15",
+ "2006-10-02",
+ "2006-10-24",
+ "2006-10-25",
+ "2006-12-25",
+ "2007-01-01",
+ "2007-01-26",
+ "2007-01-30",
+ "2007-02-16",
+ "2007-03-27",
+ "2007-04-06",
+ "2007-05-01",
+ "2007-05-02",
+ "2007-08-15",
+ "2007-10-02",
+ "2007-12-21",
+ "2007-12-25",
+ "2008-03-06",
+ "2008-03-20",
+ "2008-03-21",
+ "2008-04-14",
+ "2008-04-18",
+ "2008-05-01",
+ "2008-05-19",
+ "2008-08-15",
+ "2008-09-03",
+ "2008-10-02",
+ "2008-10-09",
+ "2008-10-30",
+ "2008-11-13",
+ "2008-11-27",
+ "2008-12-09",
+ "2008-12-25",
+ "2009-01-08",
+ "2009-01-26",
+ "2009-02-23",
+ "2009-03-10",
+ "2009-03-11",
+ "2009-04-03",
+ "2009-04-07",
+ "2009-04-10",
+ "2009-04-14",
+ "2009-04-30",
+ "2009-05-01",
+ "2009-09-21",
+ "2009-09-28",
+ "2009-10-02",
+ "2009-10-13",
+ "2009-10-19",
+ "2009-11-02",
+ "2009-12-25",
+ "2009-12-28",
+ "2010-01-01",
+ "2010-01-26",
+ "2010-02-12",
+ "2010-03-01",
+ "2010-03-24",
+ "2010-04-02",
+ "2010-04-14",
+ "2010-09-10",
+ "2010-11-17",
+ "2010-12-17",
+ "2011-01-26",
+ "2011-03-02",
+ "2011-04-12",
+ "2011-04-14",
+ "2011-04-22",
+ "2011-08-15",
+ "2011-08-31",
+ "2011-09-01",
+ "2011-10-06",
+ "2011-10-27",
+ "2011-11-07",
+ "2011-11-10",
+ "2011-12-06",
+ "2012-01-26",
+ "2012-02-20",
+ "2012-03-08",
+ "2012-04-05",
+ "2012-04-06",
+ "2012-05-01",
+ "2012-08-15",
+ "2012-08-20",
+ "2012-09-19",
+ "2012-10-02",
+ "2012-10-24",
+ "2012-11-14",
+ "2012-11-28",
+ "2012-12-25",
+ "2013-03-27",
+ "2013-03-29",
+ "2013-04-14",
+ "2013-04-19",
+ "2013-04-24",
+ "2013-05-01",
+ "2013-08-09",
+ "2013-08-15",
+ "2013-09-09",
+ "2013-10-02",
+ "2013-10-13",
+ "2013-10-16",
+ "2013-11-03",
+ "2013-11-04",
+ "2013-11-14",
+ "2013-11-17",
+ "2013-12-25",
+ "2014-01-26",
+ "2014-02-27",
+ "2014-03-17",
+ "2014-04-08",
+ "2014-04-13",
+ "2014-04-14",
+ "2014-04-18",
+ "2014-04-24",
+ "2014-05-01",
+ "2014-07-29",
+ "2014-08-15",
+ "2014-08-29",
+ "2014-10-02",
+ "2014-10-03",
+ "2014-10-06",
+ "2014-10-15",
+ "2014-10-23",
+ "2014-10-24",
+ "2014-11-04",
+ "2014-11-06",
+ "2014-12-25",
+ "2015-01-26",
+ "2015-02-17",
+ "2015-03-06",
+ "2015-03-28",
+ "2015-04-02",
+ "2015-04-03",
+ "2015-04-14",
+ "2015-05-01",
+ "2015-07-18",
+ "2015-08-15",
+ "2015-09-17",
+ "2015-09-25",
+ "2015-10-02",
+ "2015-10-22",
+ "2015-10-24",
+ "2015-11-11",
+ "2015-11-12",
+ "2015-11-25",
+ "2015-12-25",
+ "2016-01-26",
+ "2016-03-07",
+ "2016-03-24",
+ "2016-03-25",
+ "2016-04-14",
+ "2016-04-15",
+ "2016-04-19",
+ "2016-05-01",
+ "2016-07-06",
+ "2016-08-15",
+ "2016-09-05",
+ "2016-09-13",
+ "2016-10-02",
+ "2016-10-11",
+ "2016-10-12",
+ "2016-10-30",
+ "2016-10-31",
+ "2016-11-14",
+ "2016-12-25",
+ "2017-01-26",
+ "2017-02-24",
+ "2017-03-13",
+ "2017-04-04",
+ "2017-04-09",
+ "2017-04-14",
+ "2017-04-14",
+ "2017-05-01",
+ "2017-06-26",
+ "2017-08-15",
+ "2017-08-25",
+ "2017-09-02",
+ "2017-09-30",
+ "2017-10-01",
+ "2017-10-02",
+ "2017-10-19",
+ "2017-10-20",
+ "2017-11-04",
+ "2017-12-25",
+ "2018-01-26",
+ "2018-02-13",
+ "2018-03-02",
+ "2018-03-25",
+ "2018-03-29",
+ "2018-03-30",
+ "2018-04-14",
+ "2018-05-01",
+ "2018-06-16",
+ "2018-08-15",
+ "2018-08-22",
+ "2018-09-13",
+ "2018-09-20",
+ "2018-10-02",
+ "2018-10-18",
+ "2018-11-07",
+ "2018-11-08",
+ "2018-11-23",
+ "2018-12-25",
+ "2019-01-26",
+ "2019-03-04",
+ "2019-03-21",
+ "2019-04-13",
+ "2019-04-14",
+ "2019-04-17",
+ "2019-04-19",
+ "2019-04-29",
+ "2019-05-01",
+ "2019-06-05",
+ "2019-08-12",
+ "2019-08-15",
+ "2019-09-02",
+ "2019-09-10",
+ "2019-10-02",
+ "2019-10-08",
+ "2019-10-21",
+ "2019-10-27",
+ "2019-10-28",
+ "2019-11-12",
+ "2019-12-25",
+ "2020-01-26",
+ "2020-02-21",
+ "2020-03-10",
+ "2020-04-02",
+ "2020-04-06",
+ "2020-04-10",
+ "2020-04-14",
+ "2020-05-01",
+ "2020-05-25",
+ "2020-08-01",
+ "2020-08-15",
+ "2020-08-22",
+ "2020-08-30",
+ "2020-10-02",
+ "2020-10-25",
+ "2020-11-14",
+ "2020-11-16",
+ "2020-11-30",
+ "2020-12-25",
+ "2021-01-26",
+ "2021-03-11",
+ "2021-03-29",
+ "2021-04-02",
+ "2021-04-14",
+ "2021-04-21",
+ "2021-04-25",
+ "2021-05-01",
+ "2021-05-13",
+ "2021-07-21",
+ "2021-08-15",
+ "2021-08-19",
+ "2021-09-10",
+ "2021-10-02",
+ "2021-10-15",
+ "2021-11-04",
+ "2021-11-05",
+ "2021-11-19",
+ "2021-12-25",
+ "2022-01-26",
+ "2022-03-01",
+ "2022-03-18",
+ "2022-04-14",
+ "2022-04-15",
+ "2022-05-03",
+ "2022-08-09",
+ "2022-08-15",
+ "2022-08-31",
+ "2022-10-05",
+ "2022-10-22",
+ "2022-10-24",
+ "2022-10-26",
+ "2022-11-08",
+ "2023-01-26",
+ "2023-03-07",
+ "2023-03-30",
+ "2023-04-04",
+ "2023-04-07",
+ "2023-04-14",
+ "2023-05-01",
+ "2023-06-29",
+ "2023-08-15",
+ "2023-09-19",
+ "2023-10-02",
+ "2023-10-24",
+ "2023-11-14",
+ "2023-11-27",
+ "2023-12-25",
+ "2024-01-26",
+ "2024-03-08",
+ "2024-03-25",
+ "2024-03-29",
+ "2024-04-11",
+ "2024-04-17",
+ "2024-05-01",
+ "2024-06-17",
+ "2024-07-17",
+ "2024-08-15",
+ "2024-10-02",
+ "2024-11-01",
+ "2024-11-15",
+ "2024-12-25"
+ ]
+)
+
+
+class XBOMExchangeCalendar(PrecomputedExchangeCalendar):
+ """
+ Exchange calendar for the Bombay Stock Exchange (BSE, XBOM).
+
+ Open Time: 9:15 AM, Asia/Kolkata
+ Close Time: 3:30 PM, Asia/Kolkata
+
+ Due to the complexity around the BSE holidays, we are hardcoding a list
+ of holidays back to 1997, and forward through 2023. There are no known
+ early closes or late opens.
+ """
+
+ name = "XBOM"
+ tz = ZoneInfo("Asia/Kolkata")
+ open_times = ((None, time(9, 15)),)
+ close_times = ((None, time(15, 30)),)
+
+ @classmethod
+ def precomputed_holidays(cls):
+ return precomputed_bse_holidays
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbru.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbru.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8292811de19d4aa31ab9088a1a66e1a273cb6ad
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbru.py
@@ -0,0 +1,116 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday
+
+from .common_holidays import (
+ ascension_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import WEEKDAYS, HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+AscensionDay = ascension_day(end_date="2001")
+WhitMonday = whit_monday(end_date="2002")
+
+LabourDay = european_labour_day()
+
+BelgiumIndependenceDay = Holiday(
+ "Belgium Independence Day",
+ month=7,
+ day=21,
+ end_date="2002",
+)
+
+ChristmasEve = christmas_eve(days_of_week=WEEKDAYS)
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEveBefore2002 = new_years_eve(end_date="2002")
+NewYearsEveInOrAfter2002 = new_years_eve(
+ start_date="2002",
+ days_of_week=WEEKDAYS,
+)
+
+
+class XBRUExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Euronext Brussels exchange, and the primary calendar for
+ the country of Belgium.
+
+ Open Time: 9:00 AM, CET (Central European Time)
+ Close Time: 5:30 PM, CET (Central European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Christmas Day
+ - Boxing Day
+
+ Early Closes:
+ - Christmas Eve
+ - New Year's Eve
+
+ Other countries on the Euronext:
+ - France
+ - Netherlands
+ - Portugal
+ """
+
+ # Source: https://www.euronext.com/en/calendars-hours
+ regular_early_close = time(14, 5)
+
+ name = "XBRU" # Euronext Brussels
+ tz = ZoneInfo("Europe/Brussels")
+ open_times = ((None, time(9)),)
+ close_times = ((None, time(17, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ GoodFriday,
+ EasterMonday,
+ AscensionDay,
+ WhitMonday,
+ LabourDay,
+ BelgiumIndependenceDay,
+ Christmas,
+ BoxingDay,
+ NewYearsEveBefore2002,
+ ]
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar([ChristmasEve, NewYearsEveInOrAfter2002]),
+ ),
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbse.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbse.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc269c2ff62355d5c4dec80b639b2e4bc83caea9
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbse.py
@@ -0,0 +1,126 @@
+from datetime import time, timedelta
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import Holiday
+
+from .common_holidays import (
+ christmas,
+ european_labour_day,
+ new_years_day,
+ orthodox_easter,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+DayAfterNewYearsDay = Holiday("Day After New Year's Day", month=1, day=2)
+
+RomanianPrincipalitiesUnificationDay = Holiday(
+ "Romanian Principalities Unification Day", month=1, day=24
+)
+
+OrthodoxGoodFriday = orthodox_easter() - timedelta(2)
+
+OrthodoxEasterMonday = orthodox_easter() + timedelta(1)
+
+LabourDay = european_labour_day()
+
+
+ChildrensDay = Holiday(
+ "Children's Day",
+ month=6,
+ day=1,
+)
+
+OrthodoxPentecost = orthodox_easter() + timedelta(49)
+
+DescentOfTheHolySpirit = orthodox_easter() + timedelta(50)
+
+StMarysDay = Holiday(
+ "St. Mary's day",
+ month=8,
+ day=15,
+)
+
+StAndrewsDay = Holiday(
+ "St. Andrew's day",
+ month=11,
+ day=30,
+)
+
+NationalDay = Holiday(
+ "National Day",
+ month=12,
+ day=1,
+)
+
+ChristmasDay = christmas()
+
+SecondDayOfChristmas = Holiday(
+ "Second Day of Christmas",
+ month=12,
+ day=26,
+)
+
+
+class XBSEExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the BUCHAREST Stock Exchange (XBSE).
+
+ Open Time: 10:00 AM, EET
+ Close Time: 5:45 PM, EET
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Day after New Year's Day
+ - Romanian Principalities Unification Day
+ - Orthodox Good Friday
+ - Orthodox Easter
+ - Labour Day
+ - Orthodox Pentecost
+ - Children's Day
+ - Assumption of Virgin Mary
+ - St Andrew's day
+ - Christmas
+ - Day after Christmas
+
+ Early Closes:
+ - None
+ """
+
+ name = "XBSE"
+
+ tz = ZoneInfo("Europe/Bucharest")
+
+ open_times = ((None, time(10)),)
+
+ close_times = ((None, time(17, 45)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ DayAfterNewYearsDay,
+ RomanianPrincipalitiesUnificationDay,
+ LabourDay,
+ ChildrensDay,
+ StMarysDay,
+ StAndrewsDay,
+ NationalDay,
+ ChristmasDay,
+ SecondDayOfChristmas,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ OrthodoxGoodFriday,
+ OrthodoxEasterMonday,
+ OrthodoxPentecost,
+ DescentOfTheHolySpirit,
+ )
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbud.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbud.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c89ede1a9a84fb6b9b5970c053b1789b51e9c9f
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbud.py
@@ -0,0 +1,190 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import datetime
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import Easter, EasterMonday, Holiday
+from pandas.tseries.offsets import Day
+
+from .common_holidays import (
+ all_saints_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import THURSDAY, TUESDAY, HolidayCalendar, ExchangeCalendar
+
+
+ONE_DAY = datetime.timedelta(1)
+
+
+def bridge_mon(dt: datetime.datetime) -> datetime.datetime | None:
+ """Define Monday as holiday if Tuesday is a holiday.
+
+ If a holiday falls on a Tuesday an extra holiday is observed on Monday
+ to bridge the weekend and the official holiday.
+ """
+ return dt - ONE_DAY if dt.weekday() == TUESDAY else None
+
+
+def bridge_fri(dt: datetime.datetime) -> datetime.datetime | None:
+ """Define Friday as holiday if Thrusday is a holiday.
+
+ If a holiday falls on a Thursday an extra holiday is observed on Friday
+ to bridge the weekend and the official holiday.
+ """
+ return dt + ONE_DAY if dt.weekday() == THURSDAY else None
+
+
+NewYearsDayExtraMon = new_years_day(observance=bridge_mon)
+NewYearsDayExtraFri = new_years_day(observance=bridge_fri)
+
+NationalHoliday1 = Holiday("National Day", month=3, day=15)
+NationalHoliday1ExtraMon = Holiday(
+ "National Day extra Monday", month=3, day=15, observance=bridge_mon
+)
+NationalHoliday1ExtraFri = Holiday(
+ "National Day extra Friday", month=3, day=15, observance=bridge_fri
+)
+
+# Need custom start year so can't use pandas GoodFriday
+GoodFriday = Holiday(
+ "Good Friday", month=1, day=1, offset=[Easter(), Day(-2)], start_date="2012"
+)
+
+LabourDayExtraMon = european_labour_day(observance=bridge_mon)
+LabourDayExtraFri = european_labour_day(observance=bridge_fri)
+
+WhitMonday = whit_monday()
+
+StStephensDay = Holiday("St. Stephen's Day", month=8, day=20)
+StStephensDayExtraMon = Holiday(
+ "St. Stephen's Day extra Monday", month=8, day=20, observance=bridge_mon
+)
+StStephensDayExtraFri = Holiday(
+ "St. Stephen's Day extra Friday", month=8, day=20, observance=bridge_fri
+)
+
+NationalHoliday2 = Holiday("National Day", month=10, day=23)
+NationalHoliday2ExtraMon = Holiday(
+ "National Day extra Monday", month=10, day=23, observance=bridge_mon
+)
+NationalHoliday2ExtraFri = Holiday(
+ "National Day extra Friday", month=10, day=23, observance=bridge_fri
+)
+
+AllSaintsDayExtraMon = all_saints_day(observance=bridge_mon)
+AllSaintsDayExtraFri = all_saints_day(observance=bridge_fri)
+
+# Christmas Eve does not follow the four day weekend rule
+ChristmasEve = christmas_eve()
+
+ChristmasDay = christmas()
+
+# XBUD always has a holiday for the second day of Christmas (26th),
+# but starting in 2013 if the 26th falls on a Thursday then the
+# 27th (Friday) is also taken off
+SecondDayOfChristmas = Holiday("Second Day of Christmas", month=12, day=26)
+SecondDayOfChristmasExtraFri = Holiday(
+ "Second Day of Christmas extra Friday",
+ month=12,
+ day=26,
+ start_date="2013",
+ observance=bridge_fri,
+)
+# SecondDayOfChristmas unnecessary to bridge_mon as if second day of christmas
+# is a tuesday then monday will already be a holiday (Chirstmas Day)
+
+
+# Starting in 2011, New Year's Eve is observed as a holiday every year.
+# In some cases pre-2011, the 31st becomes a holiday due to the four day
+# weekend rule (when Jan 1 falls on a Tuesday).
+# Also, when NYE starts being observed as a holiday it does NOT follow
+# the four day weekend rule (no 30ths are holidays)
+NewYearsEve = new_years_eve(start_date="2011")
+
+
+class XBUDExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Budapest Stock Exchange (XBUD).
+
+ Open Time: 9:00 AM, CET
+ Close Time: 5:00 PM, CET
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - National Holiday (Mar 15)
+ - Good Friday
+ - Easter Monday
+ - Labour Day (May 1)
+ - Whit Monday (50 days after Easter Sunday)
+ - St. Stephen's Day (Aug 20)
+ - National Holiday (Oct 23)
+ - All Saint's Day (Nov 1)
+ - Christmas Eve
+ - Christmas Day
+ - Second Day of Christmas (Dec 26)
+ - New Year's Eve
+
+ Early Closes:
+ - None
+ """
+
+ name = "XBUD"
+
+ tz = ZoneInfo("Europe/Budapest")
+
+ open_times = ((None, datetime.time(9)),)
+
+ close_times = ((None, datetime.time(17, 00)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ new_years_day(),
+ NewYearsDayExtraMon,
+ NewYearsDayExtraFri,
+ NationalHoliday1,
+ NationalHoliday1ExtraMon,
+ NationalHoliday1ExtraFri,
+ GoodFriday,
+ EasterMonday,
+ european_labour_day(),
+ LabourDayExtraMon,
+ LabourDayExtraFri,
+ WhitMonday,
+ StStephensDay,
+ StStephensDayExtraMon,
+ StStephensDayExtraFri,
+ NationalHoliday2,
+ NationalHoliday2ExtraMon,
+ NationalHoliday2ExtraFri,
+ all_saints_day(),
+ AllSaintsDayExtraMon,
+ AllSaintsDayExtraFri,
+ ChristmasEve,
+ ChristmasDay,
+ SecondDayOfChristmas,
+ SecondDayOfChristmasExtraFri,
+ NewYearsEve,
+ ]
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbue.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbue.py
new file mode 100644
index 0000000000000000000000000000000000000000..072af9e1f2976976d0067a5f3a9f07825353acc6
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xbue.py
@@ -0,0 +1,369 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import datetime
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import MO, Easter, GoodFriday, Holiday
+from pandas.tseries.offsets import Day
+
+from .common_holidays import (
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ immaculate_conception,
+ maundy_thursday,
+ new_years_day,
+)
+from .exchange_calendar import (
+ MONDAY,
+ TUESDAY,
+ WEDNESDAY,
+ WEEKDAYS,
+ HolidayCalendar,
+ ExchangeCalendar,
+)
+
+
+def nearest_monday(dt: datetime.datetime) -> datetime.datetime:
+ """
+ If a holiday falls on Tuesday or Wednesday, it is observed on the
+ previous Monday. If it falls on Thursday, Friday or a weekend,
+ it is observed on the following Monday.
+ """
+ day = dt.weekday()
+
+ if day in (MONDAY, TUESDAY, WEDNESDAY):
+ return dt - datetime.timedelta(day)
+
+ while dt.weekday() != MONDAY:
+ dt += datetime.timedelta(1)
+
+ return dt
+
+
+def cultural_diversity_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ """
+ Apply the nearest monday rule, and also exclude 2012 (Day of
+ Respect for Cultural Diversity breaks the nearest monday rule
+ in 2012).
+ """
+ hol = nearest_monday(dt)
+ return hol if hol.year != 2012 else None
+
+
+def not_2018(dt: datetime.datetime) -> datetime.datetime | None:
+ """
+ Exclude the year 2018 from the holiday list.
+ """
+ return dt if dt.year != 2018 else None
+
+
+NewYearsDay = new_years_day()
+
+CarnivalMonday = Holiday(
+ "Carnival Monday",
+ month=1,
+ day=1,
+ start_date="2011",
+ offset=[Easter(), -Day(48)],
+)
+
+CarnivalTuesday = Holiday(
+ "Carnival Tuesday",
+ month=1,
+ day=1,
+ start_date="2011",
+ offset=[Easter(), -Day(47)],
+)
+
+TruthAndJusticeMemorialDay = Holiday(
+ "Truth and Justice Memorial Day",
+ month=3,
+ day=24,
+ start_date="2005",
+)
+
+MalvinasDayTo2004 = Holiday(
+ "Malvinas Day (up to 2004)",
+ month=3,
+ day=31,
+ end_date="2005",
+ offset=pd.DateOffset(weekday=MO(1)),
+)
+
+MalvinasDayFrom2005 = Holiday(
+ "Malvinas Day (2005-present)", month=4, day=2, start_date="2005"
+)
+
+MaundyThursday = maundy_thursday()
+
+LabourDay = european_labour_day()
+
+MayDayRevolution = Holiday(
+ "May Day Revolution",
+ month=5,
+ day=25,
+)
+
+MartinMiguelDeGuemesDay = Holiday(
+ "Martin Miguel de Guemes Day",
+ month=6,
+ day=17,
+ start_date="2016",
+)
+
+NationalFlagDayTo2010 = Holiday(
+ "National Flag Day (up to 2010)",
+ month=6,
+ day=1,
+ end_date="2011",
+ offset=pd.DateOffset(weekday=MO(3)),
+)
+
+NationalFlagDayFrom2011 = Holiday(
+ "National Flag Day (2011-present)",
+ month=6,
+ day=20,
+ start_date="2011",
+)
+
+IndependenceDay = Holiday(
+ "Independence Day",
+ month=7,
+ day=9,
+)
+
+SanMartinsDayTo2010 = Holiday(
+ "San Martin's Day",
+ month=8,
+ day=1,
+ end_date="2011",
+ offset=pd.DateOffset(weekday=MO(3)),
+)
+
+SanMartinsDayFrom2012 = Holiday(
+ "San Martin's Day",
+ month=8,
+ day=1,
+ start_date="2012",
+ offset=pd.DateOffset(weekday=MO(3)),
+)
+
+DayOfRespectForCulturalDiversity = Holiday(
+ "Day of Respect for Cultural Diversity",
+ month=10,
+ day=12,
+ observance=cultural_diversity_observance,
+)
+
+BankHoliday = Holiday(
+ "Bank Holiday",
+ month=11,
+ day=6,
+ end_date="2018",
+)
+
+DayOfNationalSovereigntyTo2014 = Holiday(
+ "Day of National Sovereignty (2010-2014)",
+ month=11,
+ day=1,
+ start_date="2010",
+ end_date="2015",
+ offset=pd.DateOffset(weekday=MO(4)),
+)
+
+DayOfNationalSovereigntyFrom2017 = Holiday(
+ "Day of National Sovereignty (2017-present)",
+ month=11,
+ day=17,
+ start_date="2017",
+ offset=pd.DateOffset(weekday=MO(1)),
+)
+
+ImmaculateConception = immaculate_conception()
+
+ChristmasEve = christmas_eve(
+ days_of_week=WEEKDAYS,
+ observance=not_2018,
+)
+
+ChristmasDay = christmas()
+
+NewYearsEve = Holiday(
+ "New Year's Eve",
+ month=12,
+ day=31,
+ days_of_week=WEEKDAYS,
+ observance=not_2018,
+)
+
+
+class XBUEExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Buenos Aires Stock Exchange (XBUE).
+
+ Open Time: 11:00 AM, AST
+ Close Time: 5:00 PM, AST
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Carnival Monday (48 days before Easter)
+ - Carnival Tuesday (47 days before Easter)
+ - Truth and Justice Memorial Day (Mar 24)
+ - Malvinas Day (until 2004 first Monday after Mar 31, 2005-present Apr 2)
+ - Good Friday
+ - Labour Day
+ - May Day Revolution (May 25)
+ - Martin Miguel de Guemes Day (Jun 17, 2016-present)
+ - National Flag Day (until 2010 3rd Monday in Jun, 2011-present Jun 20)
+ - Independence Day (Jul 9)
+ - San Martin's Day (3rd Monday in Aug)
+ - Day of Respect for Cultural Diversity (2nd Monday in Oct)
+ - Bank Holiday (Nov 6)
+ - Day of National Sovereignty (4th Monday in Nov)
+ - Immaculate Conception
+ - Christmas Eve (2005-present)
+ - Christmas Day
+ - Last Trading Day of Year (2005-present)
+
+
+ Early Closes:
+ Note - we are unsure if these are early closes or holidays
+ - Christmas Eve
+ - New Year's Eve
+ """
+
+ name = "XBUE"
+
+ tz = ZoneInfo("America/Argentina/Buenos_Aires")
+
+ open_times = ((None, datetime.time(11)),)
+
+ close_times = ((None, datetime.time(17, 00)),)
+
+ # TODO: Verify early close time
+ regular_early_close = datetime.time(13)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ CarnivalMonday,
+ CarnivalTuesday,
+ TruthAndJusticeMemorialDay,
+ MalvinasDayTo2004,
+ MalvinasDayFrom2005,
+ MaundyThursday,
+ GoodFriday,
+ LabourDay,
+ MayDayRevolution,
+ MartinMiguelDeGuemesDay,
+ NationalFlagDayTo2010,
+ NationalFlagDayFrom2011,
+ IndependenceDay,
+ SanMartinsDayTo2010,
+ SanMartinsDayFrom2012,
+ DayOfRespectForCulturalDiversity,
+ BankHoliday,
+ DayOfNationalSovereigntyTo2014,
+ DayOfNationalSovereigntyFrom2017,
+ ImmaculateConception,
+ ChristmasDay,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ misc_adhocs = [
+ "2009-07-10",
+ "2010-05-24",
+ "2010-10-27",
+ "2012-01-02",
+ "2012-02-27",
+ "2012-09-24",
+ "2013-01-31",
+ "2013-02-20",
+ "2018-11-30",
+ ]
+
+ # There was a string of market closures in January, 2002
+ market_closures_2002_jan = [
+ "2002-01-{:02d}".format(day) for day in range(7, 17)
+ ]
+
+ # There was a string of market closures in April, 2002
+ market_closures_2002_apr = [
+ "2002-04-{:02d}".format(day) for day in range(22, 27)
+ ]
+
+ # There are occasionally "bridge days" that make long weekends when
+ # a holiday falls on a Tuesday/Thursday, but these days are chosen
+ # inconsistently.
+ bridge_days = [
+ "2011-03-25",
+ "2011-12-09",
+ "2012-04-30",
+ "2013-04-01",
+ "2013-06-21",
+ "2014-05-02",
+ "2014-12-26",
+ "2015-03-23",
+ "2015-12-07",
+ "2016-07-08",
+ "2016-12-09",
+ "2018-04-30",
+ "2018-12-24",
+ "2018-12-31",
+ "2019-07-08",
+ "2019-08-19",
+ "2019-10-14",
+ ]
+
+ irregular_observances = [
+ "2012-10-08", # Cultural Diversity Day
+ "2011-08-22", # San Martin's Day
+ "2015-11-27", # Day of National Sovereignty
+ "2016-11-28", # Day of National Sovereignty
+ ]
+
+ return list(
+ chain(
+ misc_adhocs,
+ market_closures_2002_jan,
+ market_closures_2002_apr,
+ bridge_days,
+ irregular_observances,
+ )
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [
+ ChristmasEve,
+ NewYearsEve,
+ ]
+ ),
+ ),
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xcbf.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xcbf.py
new file mode 100644
index 0000000000000000000000000000000000000000..906519090df5bf3a0158b1c5e7787f67ad05fb12
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xcbf.py
@@ -0,0 +1,84 @@
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import (
+ GoodFriday,
+ USLaborDay,
+ USPresidentsDay,
+ USThanksgivingDay,
+)
+
+from .exchange_calendar import ExchangeCalendar
+from exchange_calendars.exchange_calendar import HolidayCalendar
+from exchange_calendars.us_holidays import (
+ Christmas,
+ HurricaneSandyClosings,
+ USBlackFridayInOrAfter1993,
+ USIndependenceDay,
+ USMartinLutherKingJrAfter1998,
+ USMemorialDay,
+ USNationalDaysofMourning,
+ USNewYearsDay,
+ USJuneteenth,
+)
+
+
+class XCBFExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the CBOE Futures Exchange (XCBF).
+
+ http://cfe.cboe.com/aboutcfe/expirationcalendar.aspx
+
+ Open Time: 8:30am, America/Chicago
+ Close Time: 3:15pm, America/Chicago
+
+ (We are ignoring extended trading hours for now)
+ """
+
+ name = "XCBF"
+
+ tz = ZoneInfo("America/Chicago")
+
+ open_times = ((None, time(8, 30)),)
+
+ close_times = ((None, time(15, 15)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ USNewYearsDay,
+ USMartinLutherKingJrAfter1998,
+ USPresidentsDay,
+ GoodFriday,
+ USIndependenceDay,
+ USMemorialDay,
+ USJuneteenth,
+ USLaborDay,
+ USThanksgivingDay,
+ Christmas,
+ ]
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ time(12, 15),
+ HolidayCalendar(
+ [
+ USBlackFridayInOrAfter1993,
+ ]
+ ),
+ )
+ ]
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ HurricaneSandyClosings,
+ USNationalDaysofMourning,
+ )
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xcse.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xcse.py
new file mode 100644
index 0000000000000000000000000000000000000000..805f21b77b5c5cc12d6d4737378aa4bbd6dff4a8
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xcse.py
@@ -0,0 +1,112 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import Easter, EasterMonday, GoodFriday, Holiday
+from pandas.tseries.offsets import Day
+
+from .common_holidays import (
+ ascension_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ maundy_thursday,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+MaundyThursday = maundy_thursday()
+GeneralPrayerDay = Holiday(
+ "General Prayer Day",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(26)],
+ end_date="2024",
+)
+AscensionDay = ascension_day()
+BankHoliday = Holiday(
+ "Bank Holiday",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(40)],
+ start_date="2009",
+)
+WhitMonday = whit_monday()
+
+ConstitutionDay = Holiday("Constitution Day", month=6, day=5)
+
+ChristmasEve = christmas_eve()
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve()
+
+
+class XCSEExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Copenhagen Stock Exchange in Denmark.
+
+ Open Time: 9:00 AM, CET (Central European Time)
+ Close Time: 5:00 PM, CET (Central European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Maundy Thursday
+ - Good Friday
+ - Easter Monday
+ - General Prayer Day
+ - Ascension Day
+ - Bank Holiday
+ - Whit Monday
+ - Constitution Day
+ - Christmas Eve
+ - Christmas Day
+ - Boxing Day
+ - New Year's Eve
+
+ Early Closes:
+ - None
+ """
+
+ name = "XCSE"
+ tz = ZoneInfo("Europe/Copenhagen")
+ open_times = ((None, time(9)),)
+ close_times = ((None, time(17)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ MaundyThursday,
+ GoodFriday,
+ EasterMonday,
+ GeneralPrayerDay,
+ AscensionDay,
+ BankHoliday,
+ WhitMonday,
+ ConstitutionDay,
+ ChristmasEve,
+ Christmas,
+ BoxingDay,
+ NewYearsEve,
+ ]
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xdub.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xdub.py
new file mode 100644
index 0000000000000000000000000000000000000000..a634a6f5686b8c2ae9ed06b71f53e1594cc87ea8
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xdub.py
@@ -0,0 +1,176 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import (
+ MO,
+ DateOffset,
+ EasterMonday,
+ GoodFriday,
+ Holiday,
+ previous_friday,
+ weekend_to_monday,
+)
+
+from .common_holidays import (
+ boxing_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ new_years_day,
+ weekend_boxing_day,
+ weekend_christmas,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day(observance=weekend_to_monday)
+
+StPatricksDay = Holiday(
+ "St. Patrick's Day",
+ month=3,
+ day=17,
+ end_date="2001",
+ observance=weekend_to_monday,
+)
+
+LabourDayTo2009 = european_labour_day(
+ start_date="2008",
+ end_date="2010",
+ observance=weekend_to_monday,
+)
+
+LabourDayFrom2019 = european_labour_day(
+ start_date="2019",
+ observance=weekend_to_monday,
+)
+
+MayBankHoliday = Holiday(
+ "May Bank Holiday",
+ month=5,
+ day=1,
+ end_date="2019",
+ offset=DateOffset(weekday=MO(1)),
+)
+JuneBankHoliday = Holiday(
+ "June Bank Holiday",
+ month=6,
+ day=1,
+ end_date="2019",
+ offset=DateOffset(weekday=MO(1)),
+)
+
+LastTradingDayBeforeChristmas = Holiday(
+ "Last Trading Day Before Christmas",
+ month=12,
+ day=24,
+ start_date="2010",
+ observance=previous_friday,
+)
+
+ChristmasEve = christmas_eve(end_date="2005")
+Christmas = christmas()
+WeekendChristmas = weekend_christmas()
+BoxingDay = boxing_day()
+WeekendBoxingDay = weekend_boxing_day()
+
+LastTradingDayOfCalendarYear = Holiday(
+ "Last Trading Day Of Calendar Year",
+ month=12,
+ day=31,
+ start_date="2010",
+ observance=previous_friday,
+)
+
+# Ad hoc closes.
+March1BadWeather = pd.Timestamp("2018-03-01")
+# Ad hoc holidays.
+March2BadWeather = pd.Timestamp("2018-03-02")
+
+
+class XDUBExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Irish Stock Exchange in Dublin.
+
+ Open Time: 8:00 AM, GMT
+ Close Time: 4:28 PM, GMT
+
+ Regularly-Observed Holidays:
+ - New Years Day
+ - Good Friday
+ - Easter Monday
+ - May Bank Holiday
+ - June Bank Holiday
+ - Christmas Day
+ - St. Stephen's Day (Boxing Day)
+
+ Holidays No Longer Observed:
+ - St. Patrick's Day
+ - Labour Day
+
+ Early Closes:
+ - Christmas Eve
+ - New Year's Eve
+ """
+
+ name = "XDUB"
+ tz = ZoneInfo("Europe/Dublin")
+ open_times = ((None, time(8)),)
+ close_times = ((None, time(16, 28)),)
+ regular_early_close = time(12, 28)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ StPatricksDay,
+ GoodFriday,
+ EasterMonday,
+ LabourDayTo2009,
+ LabourDayFrom2019,
+ MayBankHoliday,
+ JuneBankHoliday,
+ ChristmasEve,
+ Christmas,
+ WeekendChristmas,
+ BoxingDay,
+ WeekendBoxingDay,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [March2BadWeather]
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [
+ LastTradingDayBeforeChristmas,
+ LastTradingDayOfCalendarYear,
+ ]
+ ),
+ ),
+ ]
+
+ @property
+ def special_closes_adhoc(self):
+ return [(self.regular_early_close, pd.DatetimeIndex([March1BadWeather]))]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xetr.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xetr.py
new file mode 100644
index 0000000000000000000000000000000000000000..84e0be2f7b6f51a24eafc9b43ff4d4f73a61a13d
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xetr.py
@@ -0,0 +1,147 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas import Timestamp
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday, previous_workday
+
+from .common_holidays import (
+ boxing_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+# Regular Holidays
+# ----------------
+NewYearsDay = new_years_day()
+
+EuropeanLabourDay = european_labour_day()
+
+# Whit Monday observed in 2007, before it became regularly observed
+# starting in 2015.
+WhitMonday2007AdHoc = Timestamp("2007-05-28")
+
+# Whit Monday and the Day of German Unity have been observed regularly, but in 2022 regular trading took place instead.
+# It's unclear if it will be observed in 2023.
+WhitMondayUntil2022 = whit_monday(start_date="2015-01-01", end_date="2022-01-01")
+
+DayOfGermanUnityUntil2022 = Holiday(
+ "Day of German Unity",
+ month=10,
+ day=3,
+ start_date="2014-01-01",
+ end_date="2022-01-01",
+)
+
+# Reformation Day was a German national holiday in 2017.
+ReformationDay500thAnniversaryAdHoc = Timestamp("2017-10-31")
+
+ChristmasEve = christmas_eve()
+
+Christmas = christmas()
+
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve()
+
+# Early Closes
+# ------------
+# The last weekday before Dec 31 is an early close starting in 2010. Note: this
+# is decided upon separately each year somewhen in December.
+LastWorkingDay = Holiday(
+ "Last Working Day of Year Early Close",
+ month=12,
+ day=31,
+ start_date="2010-01-01",
+ observance=previous_workday,
+)
+
+
+class XETRExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Frankfurt Stock Exchange electronic market
+ (XETR).
+
+ Open Time: 9:00 AM, CET
+ Close Time: 5:30 PM, CET
+
+ Regularly-Observed Holidays:
+ - New Years Day
+ - Good Friday
+ - Easter Monday
+ - Whit Monday
+ - Labour Day
+ - Day of German Unity
+ - Christmas Eve
+ - Christmas Day
+ - Boxing Day
+
+ Early Closes:
+ - Last working day before Dec. 31
+ """
+
+ regular_early_close = time(14, 00)
+
+ name = "XETR"
+
+ tz = ZoneInfo("CET")
+
+ open_times = ((None, time(9)),)
+
+ close_times = ((None, time(17, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ GoodFriday,
+ EasterMonday,
+ EuropeanLabourDay,
+ WhitMondayUntil2022,
+ DayOfGermanUnityUntil2022,
+ ChristmasEve,
+ Christmas,
+ BoxingDay,
+ NewYearsEve,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [
+ WhitMonday2007AdHoc,
+ ReformationDay500thAnniversaryAdHoc,
+ ]
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [
+ LastWorkingDay,
+ ]
+ ),
+ )
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xfra.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xfra.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5e84a9e3a9769a9e8e5f9fd3259a918790002e7
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xfra.py
@@ -0,0 +1,146 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas import Timestamp
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday, previous_workday
+
+from .common_holidays import (
+ boxing_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+# Regular Holidays
+# ----------------
+NewYearsDay = new_years_day()
+
+EuropeanLabourDay = european_labour_day()
+
+# Whit Monday observed in 2007, before it became regularly observed
+# starting in 2015.
+WhitMonday2007AdHoc = Timestamp("2007-05-28")
+
+# Whit Monday and the Day of German Unity have been observed regularly, but in 2022 regular trading took place instead.
+# It's unclear if it will be observed in 2023.
+WhitMondayUntil2022 = whit_monday(start_date="2015-01-01", end_date="2022-01-01")
+
+DayOfGermanUnityUntil2022 = Holiday(
+ "Day of German Unity",
+ month=10,
+ day=3,
+ start_date="2014-01-01",
+ end_date="2022-01-01",
+)
+
+# Reformation Day was a German national holiday in 2017.
+ReformationDay500thAnniversaryAdHoc = Timestamp("2017-10-31")
+
+ChristmasEve = christmas_eve()
+
+Christmas = christmas()
+
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve()
+
+# Early Closes
+# ------------
+# The last weekday before Dec 31 is an early close starting in 2010.
+LastWorkingDay = Holiday(
+ "Last Working Day of Year Early Close",
+ month=12,
+ day=31,
+ start_date="2010-01-01",
+ observance=previous_workday,
+)
+
+
+class XFRAExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Frankfurt Stock Exchange (XFRA).
+
+ Open Time: 9:00 AM, CET
+ Close Time: 5:30 PM, CET
+
+ Regularly-Observed Holidays:
+ - New Years Day
+ - Good Friday
+ - Easter Monday
+ - Whit Monday
+ - Labour Day
+ - Day of German Unity
+ - Christmas Eve
+ - Christmas Day
+ - Boxing Day
+
+ Early Closes:
+ - Last working day before Dec. 31
+ """
+
+ # TODO: verify the early close time
+ regular_early_close = time(12, 30)
+
+ name = "XFRA"
+
+ tz = ZoneInfo("CET")
+
+ open_times = ((None, time(9)),)
+
+ close_times = ((None, time(17, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ GoodFriday,
+ EasterMonday,
+ EuropeanLabourDay,
+ WhitMondayUntil2022,
+ DayOfGermanUnityUntil2022,
+ ChristmasEve,
+ Christmas,
+ BoxingDay,
+ NewYearsEve,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [
+ WhitMonday2007AdHoc,
+ ReformationDay500thAnniversaryAdHoc,
+ ]
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [
+ LastWorkingDay,
+ ]
+ ),
+ )
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xhel.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xhel.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fbd975c37521845becfc83cd0a43d3b2ae93291
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xhel.py
@@ -0,0 +1,100 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday
+
+from .common_holidays import (
+ ascension_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ epiphany,
+ european_labour_day,
+ midsummer_eve,
+ new_years_day,
+ new_years_eve,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+Epiphany = epiphany()
+
+LabourDay = european_labour_day()
+
+AscensionDay = ascension_day()
+
+MidsummerEve = midsummer_eve()
+
+IndependenceDay = Holiday("Finland Independence Day", month=12, day=6)
+
+ChristmasEve = christmas_eve()
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve()
+
+
+class XHELExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Helsinki Stock Exchange in Finland.
+
+ Open Time: 10:00 AM, CET (Eastern European Time)
+ Close Time: 6:30 PM, CET (Eastern European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Epiphany
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Ascension Day
+ - Midsummer Eve
+ - Independence Day
+ - Christmas Eve
+ - Christmas Day
+ - Boxing Day
+ - New Year's Eve
+
+ Early Closes:
+ - None
+ """
+
+ name = "XHEL"
+ tz = ZoneInfo("Europe/Helsinki")
+ open_times = ((None, time(10)),)
+ close_times = ((None, time(18, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ Epiphany,
+ GoodFriday,
+ EasterMonday,
+ LabourDay,
+ AscensionDay,
+ MidsummerEve,
+ IndependenceDay,
+ ChristmasEve,
+ Christmas,
+ BoxingDay,
+ NewYearsEve,
+ ]
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xhkg.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xhkg.py
new file mode 100644
index 0000000000000000000000000000000000000000..35e54637c7b4ca60f41a16fc56f50979b8580591
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xhkg.py
@@ -0,0 +1,463 @@
+# -*- coding: utf-8 -*-
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time, timedelta
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import numpy as np
+import pandas as pd
+import toolz
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday, sunday_to_monday
+from pandas.tseries.offsets import LastWeekOfMonth, WeekOfMonth
+
+from .common_holidays import (
+ boxing_day,
+ christmas,
+ christmas_eve,
+ new_years_day,
+ new_years_eve,
+ weekend_christmas,
+)
+from .lunisolar_holidays import (
+ chinese_buddhas_birthday_dates,
+ chinese_lunar_new_year_dates,
+ double_ninth_festival_dates,
+ dragon_boat_festival_dates,
+ mid_autumn_festival_dates,
+ qingming_festival_dates,
+)
+from .exchange_calendar import (
+ FRIDAY,
+ MONDAY,
+ SATURDAY,
+ SUNDAY,
+ THURSDAY,
+ TUESDAY,
+ WEDNESDAY,
+ HolidayCalendar,
+)
+from .precomputed_exchange_calendar import PrecomputedExchangeCalendar
+from .utils.pandas_utils import vectorized_sunday_to_monday
+
+# Useful resources for making changes to this file:
+# # /etc/lunisolar
+# http://www.math.nus.edu.sg/aslaksen/calendar/cal.pdf
+# https://www.hko.gov.hk/gts/time/calendarinfo.htm
+# - the almanacs on this page are also useful
+
+weekdays = (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY)
+
+
+def process_queen_birthday(dt):
+ # before 1983
+ if dt.year in [1974, 1981]:
+ return dt + pd.DateOffset(weekday=6)
+ elif dt.year < 1983:
+ return sunday_to_monday(dt)
+ # after 1983
+ wom = WeekOfMonth(week=2, weekday=0)
+ if dt.year in [1983, 1988, 1993, 1994]:
+ wom = WeekOfMonth(week=1, weekday=0)
+ if dt.year in [1985]:
+ wom = WeekOfMonth(week=3, weekday=0)
+ return dt + wom
+
+
+LabourDay = Holiday(
+ name="Labour Day", # 劳动节
+ month=5,
+ day=1,
+ observance=sunday_to_monday,
+ start_date=pd.Timestamp("1999-05-01"),
+)
+
+HKRegionEstablishmentDay = Holiday(
+ name="Hong Kong Special Region Establishment Day",
+ month=7,
+ day=1,
+ observance=sunday_to_monday,
+ start_date=pd.Timestamp("1997-07-01"),
+)
+
+NationalDay = Holiday(
+ name="National Day",
+ month=10,
+ day=1,
+ observance=sunday_to_monday,
+ start_date=pd.Timestamp("1997-07-01"),
+)
+
+QueenBirthday = Holiday(
+ name="Queen's Birthday", # 英女王生日 6月
+ month=6,
+ day=10,
+ observance=process_queen_birthday,
+ start_date=pd.Timestamp("1983-01-01"),
+ end_date=pd.Timestamp("1997-06-01"),
+)
+
+QueenBirthday2 = Holiday(
+ name="Queen's Birthday", # 英女王生日 4月
+ month=4,
+ day=21,
+ observance=process_queen_birthday,
+ start_date=pd.Timestamp("1926-04-21"),
+ end_date=pd.Timestamp("1983-01-01"),
+)
+
+CommemoratingAlliedVictory = Holiday(
+ name="Commemorating the allied victory", # 重光纪念日 8月最后一个星期一
+ month=8,
+ day=20,
+ offset=LastWeekOfMonth(weekday=0),
+ start_date=pd.Timestamp("1945-08-30"),
+ end_date=pd.Timestamp("1997-07-01"),
+)
+
+IDontKnow = Holiday(
+ name="I dont know these days, please tell me", # 8月第一个星期一
+ month=7,
+ day=31,
+ offset=WeekOfMonth(week=0, weekday=0),
+ start_date=pd.Timestamp("1960-08-01"),
+ end_date=pd.Timestamp("1983-01-01"),
+)
+
+
+day_after_mid_autumn_festival_dates = mid_autumn_festival_dates + timedelta(1)
+
+HKAdhocClosures = [
+ # I dont know these days
+ pd.Timestamp("1970-07-01"),
+ pd.Timestamp("1971-07-01"),
+ pd.Timestamp("1973-07-02"),
+ pd.Timestamp("1974-07-01"),
+ pd.Timestamp("1975-07-01"),
+ pd.Timestamp("1976-07-01"),
+ pd.Timestamp("1977-07-01"),
+ pd.Timestamp("1979-07-02"),
+ pd.Timestamp("1980-07-01"),
+ pd.Timestamp("1981-07-01"),
+ pd.Timestamp("1982-07-01"),
+ pd.Timestamp("1971-03-22"),
+ pd.Timestamp("1971-12-06"),
+ pd.Timestamp("1971-12-20"),
+ pd.Timestamp("1975-07-28"),
+ pd.Timestamp("1985-07-29"),
+ # Weather related closures
+ pd.Timestamp("1970-07-16"), # 台风Ruby7003
+ pd.Timestamp("1970-09-14"), # 台风Georgia7011
+ pd.Timestamp("1971-07-22"), # 台风Lucy7114
+ pd.Timestamp("1971-08-31"), # 重光纪念日?
+ pd.Timestamp("1973-04-16"), # 股灾休市?
+ pd.Timestamp("1973-07-17"), # 台风Dot7304
+ pd.Timestamp("1974-04-25"), # 英国女王生日
+ pd.Timestamp("1975-10-14"), # 台风Elsie7514
+ pd.Timestamp("1978-07-26"), # 台风Agnes7807
+ pd.Timestamp("1978-07-27"),
+ pd.Timestamp("1979-01-26"), # 春节补假
+ pd.Timestamp("1979-08-02"), # 台风Hope7908
+ pd.Timestamp("1980-05-21"), # 台风Georgia8004
+ pd.Timestamp("1980-07-22"), # 台风Joy8007
+ pd.Timestamp("1981-04-27"), # 英国女王生日
+ pd.Timestamp("1981-07-06"), # 台风Lynn8106
+ pd.Timestamp("1981-07-07"),
+ pd.Timestamp("1981-07-29"), # 查理斯王子与戴安娜婚礼
+ pd.Timestamp("1983-09-09"), # 台风Ellen8309
+ pd.Timestamp("1985-06-24"), # 台风Hal8504
+ pd.Timestamp("1986-04-01"), # 复活节星期一翌日
+ pd.Timestamp("1986-10-22"), # 英女王伊丽莎白二世访港
+ pd.Timestamp("1987-10-20"), # 黑色星期一后,休市4天
+ pd.Timestamp("1987-10-21"),
+ pd.Timestamp("1987-10-22"),
+ pd.Timestamp("1987-10-23"),
+ pd.Timestamp("1988-04-05"), # 清明节翌日
+ # Timestamp('1988-06-13'), # 英国女王生日
+ pd.Timestamp("1991-06-18"), # 英国女王生日翌日
+ pd.Timestamp("1992-07-22"), # 台风Cary9207
+ # pd.Timestamp('1993-06-14'), # 英国女王生日
+ pd.Timestamp("1993-09-17"), # 台风Becky9316
+ pd.Timestamp("1994-06-14"), # 英国女王生日翌日,端午节翌日
+ pd.Timestamp("1997-06-30"), # 英国女王生日
+ pd.Timestamp("1997-07-02"), # 香港回归纪念日翌日
+ pd.Timestamp("1997-08-18"), # 抗战胜利纪念日
+ pd.Timestamp("1997-10-02"), # 国庆节翌日
+ pd.Timestamp("1998-08-17"), # 抗战胜利纪念日
+ pd.Timestamp("1998-10-02"), # 国庆节翌日
+ pd.Timestamp("1999-04-06"), # 清明节翌日
+ pd.Timestamp("1999-09-16"), # 台风约克
+ pd.Timestamp("1999-12-31"), # 千年虫
+ pd.Timestamp("2001-07-06"), # 台风尤特0104
+ pd.Timestamp("2001-07-25"), # 台风玉兔0107
+ # pd.Timestamp(2008-06-25'), # 台风风神0806,上午休市
+ pd.Timestamp("2008-08-06"), # 台风北冕0809
+ pd.Timestamp("2008-08-22"), # 台风鹦鹉0810
+ # pd.Timestamp(2009-09-15'), # 台风巨爵0915,上午休市
+ pd.Timestamp("2010-04-06"), # 清明节翌日
+ pd.Timestamp("2011-09-29"), # 台风纳沙1117
+ # pd.Timestamp(2012-07-24'), # 台风韦森特1208,上午休市
+ pd.Timestamp("2012-10-02"), # 中秋节补假
+ # pd.Timestamp(2013-05-22'), # 暴雨,上午休市
+ pd.Timestamp("2013-08-14"), # 台风尤特1311
+ # pd.Timestamp(2013-09-23'), # 台风天兔1319,上午休市
+ # pd.Timestamp(2014-09-16'), # 台风海鸥1415,上午休市
+ pd.Timestamp("2015-04-07"), # 复活节+清明节补假
+ # pd.Timestamp(2015-07-09'), # 台风莲花1520,期货夜盘休市
+ pd.Timestamp("2015-09-03"), # 抗战70周年纪念
+ # pd.Timestamp(2016-08-01'), # 台风妮妲1604,期货夜盘20:55收市
+ pd.Timestamp("2016-08-02"), # 台风妮妲1604
+ pd.Timestamp("2016-10-21"), # 台风海马1622
+ # pd.Timestamp(2017-06-12'), # 台风苗柏1702,期货夜盘17:35休市
+ pd.Timestamp("2017-08-23"), # 台风天鸽1713
+ pd.Timestamp("2020-10-13"), # 台风浪卡2016
+ pd.Timestamp(
+ "2021-10-13"
+ ), # https://www.hkex.com.hk/News/Market-Communications/2021/2110132news?sc_lang=en
+ # In 2022, the mid-autumn festival falls on a Saturday (2022-09-10),
+ # which means the day after is a Sunday. In 2022, HKSE had a holiday
+ # on the Monday (2022-09-12). In the past they don't seem to have followed
+ # this pattern. We'll have to wait and see before we generalise this into a rule.
+ pd.Timestamp("2022-09-12"),
+ pd.Timestamp("2023-07-17"), # 8号台风泰利, 全天休市 https://www.hkex.com.hk/News/Market-Communications/2023/2307172news?sc_lang=en
+]
+
+
+def boxing_day_obs(dt):
+ if dt.weekday in (MONDAY, TUESDAY):
+ return dt + pd.Timedelta(days=1)
+ return dt
+
+
+class XHKGExchangeCalendar(PrecomputedExchangeCalendar):
+ """
+ Exchange calendar for the Hong Kong Stock Exchange (XHKG).
+
+ Open Time: 9:30 AM, Asia/Hong_Kong
+ Lunch Break: 12:00 PM - 1:00 PM Asia/Hong_Kong
+ Close Time: 4:00 PM, Asia/Hong_Kong
+
+ Regularly-Observed Holidays:
+ - New Years Day (observed on monday when Jan 1 is a Sunday)
+ - Lunar New Year and the following 2 days. If the 3rd day of the lunar year
+ is a Sunday, then the next Monday is a holiday.
+ - Ching Ming Festival
+ - Good Friday
+ - Easter Monday
+ - Buddhas Birthday
+ - Dragon Boat Festival
+ - Chinese National Day (observed on monday when Oct 1 is a Sunday)
+ - Day Following Mid-Autumn Festival
+ - Chung Yeung Festival
+ - Christmas (observed on nearest weekday to December 25)
+ - Day after Christmas is observed
+
+ Regularly-Observed Early Closes:
+ - Lunar New Year's Eve
+ - Christmas Eve
+ - New Year's Eve
+
+
+ Additional Irregularities:
+ - Closes frequently for severe weather.
+
+ See https://www.hkex.com.hk/Services/Trading-hours-and-Severe-Weather-Arrangements/Trading-Hours/Securities-Market?sc_lang=en # noqa
+ """
+
+ name = "XHKG"
+ tz = ZoneInfo("Asia/Hong_Kong")
+
+ open_times = (
+ (None, time(10)),
+ (pd.Timestamp("2011-03-07"), time(9, 30)),
+ )
+ break_start_times = ((None, time(12, 0)),)
+ break_end_times = ((None, time(13, 0)),)
+ close_times = ((None, time(16)),)
+ regular_early_close_times = (
+ (None, time(12, 30)),
+ (pd.Timestamp("2011-03-07"), time(12, 00)),
+ )
+
+ @classmethod
+ def precomputed_holidays(cls):
+ lunisolar_holidays = (
+ chinese_buddhas_birthday_dates,
+ chinese_lunar_new_year_dates,
+ day_after_mid_autumn_festival_dates,
+ double_ninth_festival_dates,
+ dragon_boat_festival_dates,
+ qingming_festival_dates,
+ )
+ return lunisolar_holidays
+
+ @classmethod
+ def _earliest_precomputed_year(cls) -> int:
+ return max(map(np.min, cls.precomputed_holidays())).year
+
+ @classmethod
+ def _latest_precomputed_year(cls) -> int:
+ return min(map(np.max, cls.precomputed_holidays())).year
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ new_years_day(observance=sunday_to_monday),
+ GoodFriday,
+ EasterMonday,
+ LabourDay,
+ HKRegionEstablishmentDay,
+ CommemoratingAlliedVictory,
+ IDontKnow,
+ NationalDay,
+ QueenBirthday,
+ QueenBirthday2,
+ christmas(),
+ weekend_christmas(),
+ boxing_day(observance=boxing_day_obs),
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ # overrides as inherited from PrecomputedExchangeCalendar
+ lunar_new_years_eve = (chinese_lunar_new_year_dates - pd.Timedelta(days=1))[
+ (chinese_lunar_new_year_dates.weekday == SATURDAY)
+ & (chinese_lunar_new_year_dates.year < 2013)
+ ]
+
+ lunar_new_year_2 = chinese_lunar_new_year_dates + pd.Timedelta(days=1)
+ lunar_new_year_3 = chinese_lunar_new_year_dates + pd.Timedelta(days=2)
+ lunar_new_year_4 = (chinese_lunar_new_year_dates + pd.Timedelta(days=3))[
+ # According to the new arrangement under the General Holidays and
+ # Employment Legislation (Substitution of Holidays)(Amendment)
+ # Ordinance 2011, when either Lunar New Year's Day, the second day
+ # of Lunar New Year or the third day of Lunar New Year falls on a
+ # Sunday, the fourth day of Lunar New Year is designated as a
+ # statutory and general holiday in substitution.
+ (
+ (chinese_lunar_new_year_dates.weekday == SUNDAY)
+ | (lunar_new_year_2.weekday == SUNDAY)
+ | (lunar_new_year_3.weekday == SUNDAY)
+ )
+ & (chinese_lunar_new_year_dates.year >= 2013)
+ ]
+
+ qingming_festival = vectorized_sunday_to_monday(
+ qingming_festival_dates,
+ ).values
+ years = qingming_festival.astype("M8[Y]")
+ easter_monday = EasterMonday.dates(years[0], years[-1] + 1)
+ # qingming gets observed one day later if easter monday is on the same
+ # day
+ qingming_festival[qingming_festival == easter_monday] += np.timedelta64(1, "D")
+
+ # if the day after the mid autumn festival is October first, which
+ # conflicts with national day, then national day is observed on the
+ # second, though we don't encode that in the regular holiday, so
+ # instead we pretend that the mid autumn festival would be delayed.
+ mid_autumn_festival = day_after_mid_autumn_festival_dates.values
+ mid_autumn_festival[
+ (day_after_mid_autumn_festival_dates.month == 10)
+ & (day_after_mid_autumn_festival_dates.day == 1)
+ ] += np.timedelta64(1, "D")
+
+ return list(
+ chain(
+ lunar_new_years_eve,
+ chinese_lunar_new_year_dates,
+ lunar_new_year_2,
+ lunar_new_year_3,
+ lunar_new_year_4,
+ qingming_festival,
+ vectorized_sunday_to_monday(chinese_buddhas_birthday_dates),
+ vectorized_sunday_to_monday(dragon_boat_festival_dates),
+ mid_autumn_festival,
+ vectorized_sunday_to_monday(double_ninth_festival_dates),
+ HKAdhocClosures,
+ )
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ # HK changed their early close time
+ (
+ time(12, 30),
+ HolidayCalendar(
+ [
+ new_years_eve(
+ # Market was close for Y2K instead of closing early
+ end_date=pd.Timestamp("1999-12-01"),
+ days_of_week=weekdays,
+ ),
+ new_years_eve(
+ start_date=pd.Timestamp("2000-12-01"),
+ end_date=pd.Timestamp("2011-03-07"),
+ days_of_week=weekdays,
+ ),
+ christmas_eve(
+ end_date=pd.Timestamp("2011-03-07"), days_of_week=weekdays
+ ),
+ ]
+ ),
+ ),
+ (
+ time(12, 00),
+ HolidayCalendar(
+ [
+ new_years_eve(
+ start_date=pd.Timestamp("2011-03-07"),
+ days_of_week=weekdays,
+ ),
+ christmas_eve(
+ start_date=pd.Timestamp("2011-03-07"), days_of_week=weekdays
+ ),
+ ]
+ ),
+ ),
+ ]
+
+ @property
+ def special_closes_adhoc(self):
+ lunar_new_years_eve = (chinese_lunar_new_year_dates - pd.Timedelta(days=1))[
+ np.in1d(
+ chinese_lunar_new_year_dates.weekday,
+ [TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY],
+ )
+ & (chinese_lunar_new_year_dates.year >= 2013)
+ ].values
+
+ def selection(arr, start, end):
+ predicates = []
+ if start is not None:
+ predicates.append(start.asm8 <= arr)
+ if end is not None:
+ predicates.append(arr < end.asm8)
+
+ if not predicates:
+ return arr
+
+ return arr[np.all(predicates, axis=0)]
+
+ return [
+ (time, pd.DatetimeIndex(selection(lunar_new_years_eve, start, end)))
+ for (start, time), (end, _) in toolz.sliding_window(
+ 2,
+ toolz.concatv(self.regular_early_close_times, [(None, None)]),
+ )
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xice.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xice.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1a3c565ec8aa072b0b31c9b2f2a6e92f26a1d30
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xice.py
@@ -0,0 +1,118 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import MO, TH, DateOffset, EasterMonday, GoodFriday, Holiday
+
+from .common_holidays import (
+ ascension_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ maundy_thursday,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+# This falls on the first Thursday after 18 April.
+FirstDayOfSummer = Holiday(
+ "First Day of Summer",
+ month=4,
+ day=19,
+ offset=DateOffset(weekday=TH(1)),
+)
+
+LabourDay = european_labour_day()
+
+MaundyThursday = maundy_thursday()
+AscensionDay = ascension_day()
+WhitMonday = whit_monday()
+
+NationalDay = Holiday("Icelandic Republic Day", month=6, day=17)
+
+# This falls on the first Monday of August.
+CommerceDay = Holiday(
+ "Commerce Day",
+ month=8,
+ day=1,
+ offset=DateOffset(weekday=MO(1)),
+)
+
+ChristmasEve = christmas_eve()
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve()
+
+
+class XICEExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Iceland Exchange.
+
+ Open Time: 9:30 AM, GMT (Greenwich Mean Time)
+ Close Time: 3:30 PM, GMT (Greenwich Mean Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Maundy Thursday
+ - Good Friday
+ - Easter Monday
+ - First Day of Summer
+ - Labour Day
+ - Ascension Day
+ - Whit Monday
+ - National Day
+ - Commerce Day
+ - Christmas Eve
+ - Christmas Day
+ - Boxing Day
+ - New Year's Eve
+
+ Early Closes:
+ - None
+ """
+
+ name = "XICE"
+ tz = ZoneInfo("Atlantic/Reykjavik")
+ open_times = ((None, time(9, 30)),)
+ close_times = ((None, time(15, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ MaundyThursday,
+ GoodFriday,
+ EasterMonday,
+ FirstDayOfSummer,
+ LabourDay,
+ AscensionDay,
+ WhitMonday,
+ NationalDay,
+ CommerceDay,
+ ChristmasEve,
+ Christmas,
+ BoxingDay,
+ NewYearsEve,
+ ]
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xidx.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xidx.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9667a6059975e8658689ccf8131553f4d74c78c
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xidx.py
@@ -0,0 +1,435 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import GoodFriday, Holiday
+
+from .common_holidays import ascension_day, christmas, new_years_day, new_years_eve
+from .lunisolar_holidays import chinese_lunar_new_year_dates
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+
+class XIDXExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Indonesia Stock Exchange (XIDX).
+
+ Open Time: 09:00, Western Indonesian Time (WIB)
+ Close Time: 15:50, Western Indonesian Time (WIB)
+
+ Regularly-Observed Holidays:
+ - New Year's Day(Jan 1)
+ - Good Friday (Friday before Easter)
+ - Labor Day (May 1)
+ - Ascension Day Of Jesus Christ (39 days after Easter, always Thursday)
+ - Pancasila Day (Jun 1)
+ - Independence Day (Aug 17)
+ - Christmas Day (Dec 25)
+ - New Year's Eve (called "Trading Holiday", Dec 31)
+ - Chinese New Year (from Gregorian year 2002 onward)
+ - Islamic New Year
+ - Eid al-Fitr (Festival of Breaking the Fast)
+ - Eid al-Adha (Festival of the Sacrifice)
+ - Isra Mikraj of the Prophet Muhammad
+ - Birth of the Prophet Muhammad
+ - Vesak Day
+ - Hindu Saka New Year (also called Nyepi, or Balinese Day of Silence)
+
+ Election holidays are also observed, as well as additional "common
+ leave" days around many holidays.
+ """
+
+ name = "XIDX"
+
+ tz = ZoneInfo("Asia/Jakarta")
+
+ open_times = ((None, time(9)),)
+
+ close_times = ((None, time(15, 50)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ new_years_day(),
+ GoodFriday,
+ Holiday(
+ "Labor Day",
+ month=5,
+ day=1,
+ start_date="2014-05-01",
+ ),
+ # XXX: The Indonesia Stock Exchange was open on Ascension
+ # Day 2003, but closed the next day. We are not sure why.
+ # (The 2003-05-30 closure is listed in adhoc_holidays.)
+ ascension_day(end_date="2003"),
+ ascension_day(start_date="2004"),
+ Holiday(
+ "Pancasila Day",
+ month=6,
+ day=1,
+ start_date="2017-06-01",
+ ),
+ Holiday(
+ "Independence Day",
+ month=8,
+ day=17,
+ ),
+ # Christmas Eve is not an official Indonesian holiday, but
+ # December 24th and 26th are frequently observed as common
+ # leave. These dates are listed in adhoc_holidays.
+ christmas(),
+ new_years_eve(),
+ ]
+ )
+
+ chinese_new_year = chinese_lunar_new_year_dates[
+ # The Indonesia Stock Exchange did not close for Chinese New
+ # Year in 1998, 1999, or 2001. (It fell on a Saturday in 2000.)
+ chinese_lunar_new_year_dates.year
+ >= 2002
+ ]
+
+ common_leave = pd.to_datetime(
+ [
+ # Indonesia sometimes observes additional "common leave" days
+ # around the usual observed dates of holidays.
+ # Common leave for New Year's Day.
+ "2002-12-30",
+ "2005-12-30",
+ "2009-01-02",
+ "2017-01-02",
+ # Common leave for Chinese New Year.
+ "2008-02-08",
+ # Common leave for Ascension Day.
+ "2003-05-30",
+ "2006-05-26",
+ "2007-05-18",
+ # Common leave for Independence Day.
+ "2003-08-18",
+ "2006-08-18",
+ "2008-08-18",
+ # Common leave for Christmas.
+ "2002-12-24",
+ "2002-12-26",
+ "2003-12-24",
+ "2003-12-26",
+ "2004-12-24",
+ "2005-12-26",
+ "2007-12-24",
+ "2009-12-24",
+ "2010-12-24",
+ "2011-12-26",
+ "2012-12-24",
+ "2013-12-26",
+ "2014-12-26",
+ "2016-12-26",
+ "2017-12-26",
+ "2018-12-24",
+ "2019-12-24",
+ "2020-12-24",
+ ]
+ )
+
+ islamic_new_year = pd.to_datetime(
+ [
+ # Islamic/Hijri/Hijriyah New Year.
+ # Includes common leave.
+ "2002-03-15",
+ "2003-03-03",
+ "2004-02-23",
+ "2005-02-10",
+ "2006-01-31",
+ "2008-01-10", # First Islamic New Year of 2008.
+ "2008-01-11",
+ "2008-12-29", # Second Islamic New Year of 2008.
+ "2009-12-18",
+ "2010-12-07",
+ "2012-11-15",
+ "2012-11-16",
+ "2013-11-05",
+ "2015-10-14",
+ "2017-09-21",
+ "2018-09-11",
+ "2020-08-20",
+ ]
+ )
+
+ eid_al_fitr = pd.to_datetime(
+ [
+ # Eid al-Fitr (Festival of Breaking the Fast).
+ # Includes common leave.
+ "2002-12-05",
+ "2002-12-06",
+ "2002-12-09",
+ "2002-12-10",
+ "2003-11-24",
+ "2003-11-25",
+ "2003-11-26",
+ "2003-11-27",
+ "2003-11-28",
+ "2004-11-15",
+ "2004-11-16",
+ "2004-11-17",
+ "2004-11-18",
+ "2004-11-19",
+ "2005-11-02",
+ "2005-11-03",
+ "2005-11-04",
+ "2005-11-07",
+ "2005-11-08",
+ "2006-10-23",
+ "2006-10-24",
+ "2006-10-25",
+ "2006-10-26",
+ "2006-10-27",
+ "2007-10-12",
+ "2007-10-15",
+ "2007-10-16",
+ "2008-09-30",
+ "2008-10-01",
+ "2008-10-02",
+ "2008-10-03",
+ "2009-09-18",
+ "2009-09-21",
+ "2009-09-22",
+ "2009-09-23",
+ "2010-09-08",
+ "2010-09-09",
+ "2010-09-10",
+ "2010-09-13",
+ "2010-09-14",
+ "2011-08-29",
+ "2011-08-30",
+ "2011-08-31",
+ "2011-09-01",
+ "2011-09-02",
+ "2012-08-20",
+ "2012-08-21",
+ "2012-08-22",
+ "2013-08-05",
+ "2013-08-06",
+ "2013-08-07",
+ "2013-08-08",
+ "2013-08-09",
+ "2014-07-28",
+ "2014-07-29",
+ "2014-07-30",
+ "2014-07-31",
+ "2014-08-01",
+ "2015-07-16",
+ "2015-07-17",
+ "2015-07-20",
+ "2015-07-21",
+ "2016-07-04",
+ "2016-07-05",
+ "2016-07-06",
+ "2016-07-07",
+ "2016-07-08",
+ "2017-06-23",
+ "2017-06-26",
+ "2017-06-27",
+ "2017-06-28",
+ "2017-06-29",
+ "2017-06-30",
+ "2018-06-11",
+ "2018-06-12",
+ "2018-06-13",
+ "2018-06-14",
+ "2018-06-15",
+ "2018-06-18",
+ "2018-06-19",
+ "2019-06-03",
+ "2019-06-04",
+ "2019-06-05",
+ "2019-06-06",
+ "2019-06-07",
+ "2020-05-22",
+ "2020-05-25",
+ "2020-05-26",
+ "2020-05-27",
+ ]
+ )
+
+ eid_al_adha = pd.to_datetime(
+ [
+ # Eid al-Adha (Festival of the Sacrifice).
+ # Includes common leave.
+ "2002-02-22",
+ "2003-02-12",
+ "2004-02-02",
+ "2005-01-21",
+ "2006-01-10",
+ "2006-12-29",
+ # NOTE: Eid al-Adha occured twice in 2006, on Tuesday 01-10 and
+ # Sunday 12-31. The exchange was closed on Friday 2006-12-29 as
+ # a make-up holiday.
+ "2007-12-20",
+ "2007-12-21",
+ "2008-12-08",
+ "2009-11-27",
+ "2009-11-28",
+ "2010-11-17",
+ "2012-10-26",
+ "2013-10-14",
+ "2013-10-15",
+ "2015-09-24",
+ "2016-09-12",
+ "2017-09-01",
+ "2018-08-22",
+ "2020-07-31",
+ ]
+ )
+
+ isra_mikraj = pd.to_datetime(
+ [
+ # Isra and Mi'raj (Ascension of the Prophet Muhammad).
+ # Called "Isra Mikraj" in Indonesia.
+ #
+ # Occurs on 27 Rajab on the Hijri calendar, but the mapping of
+ # Hijri to Gregorian dates varies. For example, in 2018 many
+ # countries observed this holiday on Friday 04-13; but by
+ # Indonesian reckoning it fell on Saturday 04-14 that year.
+ #
+ # See https://www.idx.co.id/en-us/news/trading-holiday/
+ #
+ # Includes common leave.
+ "2002-10-04",
+ "2003-09-22",
+ "2004-09-13",
+ "2005-09-02",
+ "2006-08-21",
+ "2008-07-30",
+ "2009-07-20",
+ "2011-06-29",
+ "2012-05-18",
+ "2013-06-06",
+ "2014-05-27",
+ "2016-05-06",
+ "2017-04-24",
+ "2019-04-03",
+ ]
+ )
+
+ birth_of_prophet_muhammad = pd.to_datetime(
+ [
+ # Birth of the Prophet Muhammad.
+ # Includes common leave.
+ "2003-05-15",
+ "2004-05-03",
+ "2005-04-22",
+ "2006-04-10",
+ "2008-03-20",
+ "2009-03-09",
+ "2010-02-26",
+ "2011-02-15",
+ "2013-01-24",
+ "2014-01-14",
+ "2015-12-24",
+ "2016-12-12",
+ "2017-12-01",
+ "2018-11-20",
+ "2020-10-29",
+ ]
+ )
+
+ vesak_day = pd.to_datetime(
+ [
+ # Vesak Day (Buddha's Birthday).
+ # Sometimes called "Hari Raya Waisak" in Indonesia.
+ # Includes common leave.
+ "2003-05-16",
+ "2004-06-03",
+ "2005-05-24",
+ "2007-06-01",
+ "2008-05-20",
+ "2010-05-28",
+ "2011-05-17",
+ "2014-05-15",
+ "2015-06-02",
+ "2017-05-11",
+ "2018-05-29",
+ "2020-05-07",
+ ]
+ )
+
+ hindu_saka_new_year = pd.to_datetime(
+ [
+ # Hindu Saka New Year (also called Nyepi, or Balinese Day of Silence).
+ # Includes common leave.
+ "2003-04-02",
+ "2004-03-22",
+ "2005-03-11",
+ "2006-03-30",
+ "2006-03-31",
+ "2007-03-19",
+ "2008-03-07",
+ "2009-03-26",
+ "2010-03-16",
+ "2012-03-23",
+ "2013-03-12",
+ "2014-03-31",
+ "2016-03-09",
+ "2017-03-28",
+ "2019-03-07",
+ "2020-03-25",
+ ]
+ )
+
+ spontaneous_closures = pd.to_datetime(
+ [
+ # Trading suspension due to global financial crisis.
+ "2008-10-09",
+ "2008-10-10",
+ ]
+ )
+
+ election_holidays = pd.to_datetime(
+ [
+ # Local and gubernatorial election holidays.
+ "2004-04-05",
+ "2004-07-05",
+ "2004-09-20",
+ "2009-04-09",
+ "2009-07-08",
+ "2014-04-09",
+ "2014-07-09",
+ "2015-12-09",
+ "2017-02-15",
+ "2017-04-19",
+ "2019-04-17",
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ self.chinese_new_year,
+ self.common_leave,
+ self.islamic_new_year,
+ self.eid_al_fitr,
+ self.eid_al_adha,
+ self.isra_mikraj,
+ self.birth_of_prophet_muhammad,
+ self.vesak_day,
+ self.hindu_saka_new_year,
+ self.spontaneous_closures,
+ self.election_holidays,
+ )
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xist.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xist.py
new file mode 100644
index 0000000000000000000000000000000000000000..b84d5c37eab08638ea1a0323ae854665dd1a7de1
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xist.py
@@ -0,0 +1,186 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time, timedelta
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import Holiday
+
+from .common_holidays import (
+ eid_al_adha_first_day,
+ eid_al_fitr_first_day,
+ european_labour_day,
+ new_years_day,
+)
+from .exchange_calendar import WEEKDAYS, WEEKENDS, HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+NationalSovereigntyAndChildrensDay = Holiday(
+ "National Sovereignty and Children's Day",
+ month=4,
+ day=23,
+)
+
+LabourDay = european_labour_day(start_date="2009")
+
+CommemorationOfAttaturkYouthAndSportsDay = Holiday(
+ "Commemoration of Attaturk, Youth and Sports Day",
+ month=5,
+ day=19,
+)
+
+EidAlFitr1 = eid_al_fitr_first_day
+
+EidAlFitr2 = eid_al_fitr_first_day + timedelta(1)
+
+EidAlFitr3 = eid_al_fitr_first_day + timedelta(2)
+
+DemocracyAndNationalUnityDay = Holiday(
+ "Democracy and National Unity Day", month=7, day=15, start_date="2017"
+)
+
+EidAlAdha1 = eid_al_adha_first_day
+
+EidAlAdha2 = eid_al_adha_first_day + timedelta(1)
+
+EidAlAdha3 = eid_al_adha_first_day + timedelta(2)
+
+EidAlAdha4 = eid_al_adha_first_day + timedelta(3)
+
+VictoryDay = Holiday(
+ "Victory Day",
+ month=8,
+ day=30,
+)
+
+RepublicDay = Holiday(
+ "Republic Day",
+ month=10,
+ day=29,
+)
+
+# Early Closes
+DayBeforeEidAlFitr = eid_al_fitr_first_day - timedelta(1)
+
+EidAlFitrHalfDay = [day for day in DayBeforeEidAlFitr if day.weekday() not in WEEKENDS]
+
+DayBeforeEidAlAdha = eid_al_adha_first_day - timedelta(1)
+
+EidAlAdhaHalfDay = [day for day in DayBeforeEidAlAdha if day.weekday() not in WEEKENDS]
+
+RepublicDayHalfDay = Holiday(
+ "Republic Day half day",
+ month=10,
+ day=28,
+ days_of_week=WEEKDAYS,
+)
+
+
+class XISTExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Istanbul Stock Exchange (XIST).
+
+ # Note: Effective as of Nov 14, 2016 according to official website
+ Open Time: 10:00 AM, TRT
+ Close Time: 6:00 PM, TRT
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - National Sovereignty and Children's Day (Apr 23)
+ - Labour Day (May 1)
+ - Commemoration of Attaturk, Youth and Sports Day (May 19)
+ - Eid-ul-Fitr (Islamic Lunar Calendar)
+ - Democracy and National Unity Day (Jul 15)
+ - Eid-al-Adha (first day is a half-day, remaining full holidays)
+ - Victory Day (Aug 30)
+ - Republic Day (Oct 29)
+
+ Early Closes:
+ - First Day of Eid-al-Adha
+ - Republic Day (Oct 28)
+ """
+
+ name = "XIST"
+
+ tz = ZoneInfo("Europe/Istanbul")
+
+ open_times = ((None, time(10)),)
+
+ close_times = ((None, time(18, 00)),)
+
+ regular_early_close = time(12, 30)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ NationalSovereigntyAndChildrensDay,
+ LabourDay,
+ CommemorationOfAttaturkYouthAndSportsDay,
+ DemocracyAndNationalUnityDay,
+ VictoryDay,
+ RepublicDay,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ misc_adhoc = [
+ pd.Timestamp("2002-01-04"), # Market Holiday
+ pd.Timestamp("2003-02-14"), # Eid al Adha extra holiday
+ pd.Timestamp("2003-11-21"), # Terror attacks
+ pd.Timestamp("2003-11-24"), # Eid al Fitr extra holiday
+ pd.Timestamp("2003-11-28"), # Eid al Fitr extra holiday
+ pd.Timestamp("2004-01-23"), # Bad weather
+ pd.Timestamp("2004-12-30"), # Closure for redenomination
+ pd.Timestamp("2004-12-31"), # Closure for redenomination
+ pd.Timestamp("2006-01-13"), # Eid al Adha extra holiday
+ pd.Timestamp("2023-02-08"), # Trade suspension after earthquake
+ pd.Timestamp("2023-02-09"), # Trade suspension after earthquake
+ pd.Timestamp("2023-02-10"), # Trade suspension after earthquake
+ pd.Timestamp("2023-02-13"), # Trade suspension after earthquake
+ pd.Timestamp("2023-02-14"), # Trade suspension after earthquake
+ ]
+
+ return list(
+ chain(
+ misc_adhoc,
+ EidAlFitr1,
+ EidAlFitr2,
+ EidAlFitr3,
+ EidAlAdha1,
+ EidAlAdha2,
+ EidAlAdha3,
+ EidAlAdha4,
+ )
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar([RepublicDayHalfDay]),
+ )
+ ]
+
+ @property
+ def special_closes_adhoc(self):
+ early_close_days = pd.DatetimeIndex(EidAlFitrHalfDay + EidAlAdhaHalfDay)
+ return [(self.regular_early_close, early_close_days)]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xjse.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xjse.py
new file mode 100644
index 0000000000000000000000000000000000000000..139c116cf273d39c78aa9cdc68207f84e2065566
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xjse.py
@@ -0,0 +1,161 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas import Timestamp
+from pandas.tseries.holiday import Easter, GoodFriday, Holiday, sunday_to_monday
+from pandas.tseries.offsets import Day
+
+from .common_holidays import new_years_day
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+
+class XJSEExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Johannesburg Stock Exchange (XJSE).
+
+ Open Time: 09:00, SAST
+ Close Time: 17:00, SAST
+
+ Regularly-Observed Holidays:
+ - New Year's Day (Jan 1)
+ - Human Rights Day (Mar 31)
+ - Good Friday (Friday before Easter)
+ - Family Day (Monday after Easter)
+ - Freedom Day (Apr 27)
+ - Workers' Day (a.k.a. Labour Day, May 1)
+ - Youth Day (Jun 16)
+ - National Women's Day (Aug 19)
+ - Heritage Day (Sep 24)
+ - Day of Reconciliation (Dec 19)
+ - Christmas (Dec 25)
+ - Day of Goodwill (Dec 26)
+
+ If a holiday falls on a Saturday, it is not observed.
+ If a holiday falls on a Sunday, it is observed on Monday.
+
+ If two holiday observations occur on the same trading day, the
+ following trading day may or may not be declared a holiday: if so,
+ it should be added to ``adhoc_holidays``.
+ """
+
+ name = "XJSE"
+
+ tz = ZoneInfo("Africa/Johannesburg")
+
+ open_times = ((None, time(9)),)
+
+ close_times = ((None, time(17, 00)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ new_years_day(
+ observance=sunday_to_monday,
+ ),
+ Holiday(
+ "Human Rights Day",
+ month=3,
+ day=21,
+ observance=sunday_to_monday,
+ ),
+ GoodFriday,
+ Holiday(
+ "Family Day",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(1)],
+ ),
+ Holiday(
+ "Freedom Day",
+ month=4,
+ day=27,
+ observance=sunday_to_monday,
+ ),
+ Holiday(
+ "Workers' Day",
+ month=5,
+ day=1,
+ observance=sunday_to_monday,
+ ),
+ Holiday(
+ "Youth Day",
+ month=6,
+ day=16,
+ observance=sunday_to_monday,
+ ),
+ Holiday(
+ "National Women's Day",
+ month=8,
+ day=9,
+ observance=sunday_to_monday,
+ ),
+ Holiday(
+ "Heritage Day",
+ month=9,
+ day=24,
+ observance=sunday_to_monday,
+ ),
+ Holiday(
+ "Day of Reconciliation",
+ month=12,
+ day=16,
+ observance=sunday_to_monday,
+ ),
+ Holiday(
+ "Christmas",
+ month=12,
+ day=25,
+ observance=sunday_to_monday,
+ ),
+ Holiday(
+ "Day of Goodwill",
+ month=12,
+ day=26,
+ observance=sunday_to_monday,
+ ),
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [
+ Timestamp(date)
+ for date in [
+ # Election holidays
+ "2004-04-14",
+ "2006-03-01",
+ "2009-04-22",
+ "2011-05-18",
+ "2014-05-07",
+ "2016-08-03",
+ "2019-05-08",
+ # In 2008, Human Rights Day fell on the same day as Good
+ # Friday (March 21), so the "Bridge Public Holiday" was
+ # observed on May 2.
+ "2008-05-02",
+ # In 2011 and 2016, Christmas fell on Sunday, which would
+ # ordinarily cause it to be observed on Monday; but Day of
+ # Goodwill fell on Monday, which resulted in only 11
+ # scheduled holidays for the year instead of the usual 12.
+ # In these years, the 27th was declared a bonus holiday: it
+ # may or may not be repeated in 2022 and onward.
+ "2011-12-27",
+ "2016-12-27",
+ ]
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xkar.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xkar.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ea9ef7f9eef33ab1a288070fe7e88dfec379ea0
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xkar.py
@@ -0,0 +1,367 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import Holiday
+
+from .common_holidays import european_labour_day
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+
+class XKARExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Pakistan Stock Exchange (XKAR).
+
+ Frequently abbreviated as 'PSX'; not to be confused with the
+ the NASDAQ OMX PSX exchange, whose market identifier code is 'XPSX'.
+
+ Open Time: 09:32 Monday-Thursday; 09:17 Friday
+ Close Time: 15:30 Monday-Thursday; 16:30 Friday
+
+ Regularly-Observed Holidays:
+ - Kashmir Day (Feb 5)
+ - Pakistan Day (Mar 23)
+ - Labour Day (May 1)
+ - Juma-Tul-Wida (last Friday of Ramadan)
+ - Eil-ul-Fitr (1st-3rd Shawwal)
+ - Eid-ul-Azha (10th-11th Zil-Hajj)
+ - Independence Day (Aug 14)
+ - Ashura (9th & 10th Muharram)
+ - Eid Milad-un-Nabi (12th Rabi-ul-Awal)
+ - Birthday of Quaid-e-Azam & Christmas (Dec 25)
+
+ Formerly-Observed Holidays:
+ - Iqbal Day (Nov 9; ended in 2012)
+
+ Occasional election and bank holidays are also observed.
+ """
+
+ name = "XKAR"
+
+ tz = ZoneInfo("Asia/Karachi")
+
+ # NOTE: The Pakistan Stock Exchange is open from 09:32-15:30
+ # Monday-Thursday, and from 09:17-12:00 AND 14:32-16:30 on Friday
+ # (which is less total trading time); however, the ExchangeCalendar
+ # class does not currently model intra-day closures.
+ #
+ # See https://www.psx.com.pk/psx/exchange/general/trading-hours
+
+ open_times = (
+ (None, time(9, 32)),
+ # TODO: 09:17 on Fridays
+ )
+
+ close_times = (
+ (None, time(15, 30)),
+ # TODO: 16:30 on Fridays
+ )
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ Holiday(
+ "Kashmir Day",
+ month=2,
+ day=5,
+ ),
+ Holiday(
+ "Pakistan Day",
+ month=3,
+ day=23,
+ ),
+ european_labour_day(),
+ Holiday(
+ "Independence Day",
+ month=8,
+ day=14,
+ ),
+ Holiday(
+ "Iqbal Day",
+ month=11,
+ day=9,
+ end_date="2013",
+ ),
+ Holiday(
+ "Birthday of Quaid-e-Azam & Christmas",
+ month=12,
+ day=25,
+ ),
+ ]
+ )
+
+ juma_tul_wida = pd.to_datetime(
+ [
+ # Juma-Tul-Wida (last Friday of Ramadan before Eid-ul-Fitr)
+ "2002-12-06",
+ # '2003-11-21', # NOTE: Apparently not observed in 2003.
+ "2004-11-11", # NOTE: Observed on Thursday instead of Friday (??)
+ "2005-10-28",
+ "2006-10-20",
+ "2007-10-12",
+ "2008-09-26",
+ # '2009-09-18', # NOTE: Apparently not observed in 2009.
+ "2010-09-10",
+ "2011-08-26",
+ "2012-08-17",
+ "2013-08-02",
+ "2014-07-25",
+ "2015-07-17",
+ "2016-07-01",
+ "2017-06-23",
+ "2018-06-08",
+ "2019-05-31",
+ "2020-05-22",
+ ]
+ )
+
+ eid_ul_fitr = pd.to_datetime(
+ [
+ # Eid-ul-Fitr (Festival of Breaking the Fast, 1st-3rd Shawwal).
+ "2002-12-03", # Tuesday (??)
+ "2002-12-05", # Thursday
+ "2003-11-26", # Wednesday
+ "2003-11-27",
+ "2003-11-28",
+ "2004-11-15", # Monday
+ "2004-11-16",
+ "2004-11-17",
+ "2005-11-03", # Thursday
+ "2005-11-04",
+ "2006-10-23", # Monday
+ "2006-10-24",
+ "2006-10-25",
+ "2007-10-10", # Wednesday (??)
+ "2007-10-15", # Monday
+ "2007-10-16",
+ "2008-10-01", # Wednesday
+ "2008-10-02",
+ "2008-10-03",
+ "2009-09-21", # Monday
+ "2009-09-22",
+ "2009-09-23",
+ "2010-09-13", # Monday
+ "2011-08-31", # Wednesday
+ "2011-09-01",
+ "2011-09-02",
+ "2012-08-20", # Monday
+ "2012-08-21",
+ "2012-08-22",
+ "2013-08-08", # Thursday
+ "2013-08-09",
+ "2014-07-29", # Tuesday
+ "2014-07-30",
+ "2014-07-31",
+ "2014-08-01",
+ "2015-07-20", # Monday
+ "2015-07-21",
+ "2016-07-05", # Tuesday
+ "2016-07-06",
+ "2016-07-07",
+ "2016-07-08",
+ "2017-06-26", # Wednesday
+ "2017-06-27",
+ "2017-06-28",
+ "2018-06-15", # Friday
+ "2018-06-18", # Monday
+ "2019-06-04", # Tuesday
+ "2019-06-05",
+ "2019-06-06",
+ "2019-06-07",
+ "2020-05-25", # Monday
+ "2020-05-26",
+ "2020-05-27",
+ ]
+ )
+
+ eid_ul_azha = pd.to_datetime(
+ [
+ # Eid-ul-Azha (Festival of the Sacrifice, 10th-11th Zil-Hajj).
+ "2002-02-25",
+ "2003-02-11",
+ "2003-02-12",
+ "2003-02-13",
+ "2003-02-14",
+ "2004-02-02",
+ "2004-02-03",
+ "2004-02-04",
+ "2005-01-20",
+ "2005-01-21",
+ "2006-01-10",
+ "2006-01-11",
+ "2006-01-12",
+ "2006-01-13",
+ # NOTE: Some countries observed this occurrence of Eid-ul-Azha
+ # at the end of December 2006.
+ "2007-01-01", # NOTE: occurred on New Year's Day.
+ "2007-01-02",
+ "2007-12-20",
+ "2007-12-21",
+ "2008-12-08",
+ "2008-12-09",
+ "2008-12-10",
+ "2008-12-11",
+ "2009-11-27", # Friday
+ "2009-11-30", # Monday
+ "2010-11-17",
+ "2010-11-18",
+ "2010-11-19",
+ "2011-11-07",
+ "2011-11-08",
+ "2012-10-26",
+ "2013-10-15",
+ "2013-10-16",
+ "2013-10-17",
+ "2013-10-18",
+ "2014-10-06",
+ "2014-10-07",
+ "2014-10-08",
+ "2015-09-24",
+ "2015-09-25",
+ "2016-09-12",
+ "2016-09-13",
+ "2016-09-14",
+ "2017-09-01",
+ "2017-09-04",
+ "2018-08-21",
+ "2018-08-22",
+ "2018-08-23",
+ "2019-08-12",
+ "2019-08-13",
+ "2019-08-15",
+ "2020-07-31",
+ ]
+ )
+
+ ashura = pd.to_datetime(
+ [
+ # Ashura (9th & 10th Muharram)
+ "2002-03-25", # Monday make-up?
+ "2003-03-13",
+ "2003-03-14",
+ "2004-03-01",
+ "2004-03-02",
+ "2006-02-08",
+ "2006-02-09",
+ "2009-01-07",
+ "2009-01-08",
+ "2009-12-28",
+ "2010-12-16",
+ "2010-12-17",
+ "2011-12-05",
+ "2011-12-06",
+ "2013-11-14",
+ "2013-11-15",
+ "2014-11-03",
+ "2014-11-04",
+ "2015-10-23",
+ "2016-10-11",
+ "2016-10-12",
+ "2018-09-20",
+ "2018-09-21",
+ "2019-09-09",
+ "2019-09-10",
+ ]
+ )
+
+ eid_milad_un_nabi = pd.to_datetime(
+ [
+ # Eid Milad-un-Nabi a.k.a. Mawlid (12th Rabi-ul-Awal)
+ # Birth of the Prophet Muhammad
+ "2002-05-23",
+ "2003-05-15",
+ "2005-04-22",
+ "2006-04-11",
+ "2008-03-21",
+ "2009-03-10",
+ "2011-02-16",
+ "2013-01-25",
+ "2014-01-14",
+ "2015-12-24",
+ "2016-12-12",
+ "2017-12-01",
+ "2018-11-21",
+ "2020-10-30",
+ ]
+ )
+
+ new_years_day = pd.to_datetime(
+ [
+ # NOTE: New Year's Day is not included in the Pakistan Stock
+ # Exchange's official list of holidays, although the exchange
+ # has been closed on that date a few times.
+ "2002-01-01", # (Tue): closed
+ # 2003-01-01 (Wed): open
+ "2004-01-01", # (Thu): closed
+ # 2005-01-01 (Sat): closed for the weekend
+ # 2006-01-01 (Sun): closed for the weekend
+ # 2007-01-01 (Mon): closed for Eid-ul-Azha
+ # 2008-01-01 (Tue): open
+ # 2009-01-01 (Thu): open
+ "2010-01-01", # (Fri): closed
+ # 2011-01-01 (Sat): closed for the weekend
+ # 2012-01-01 (Sun): closed for the weekend
+ # 2013-01-01 (Tue): open
+ # 2014-01-01 (Wed): open
+ # 2015-01-01 (Thu): open
+ # 2016-01-01 (Fri): open
+ # 2017-01-01 (Sun): closed for the weekend
+ # 2018-01-01 (Mon): open
+ # 2019-01-01 (Tue): open
+ # 2020-01-01 (Wed): open
+ ]
+ )
+
+ miscellaneous_closures = pd.to_datetime(
+ [
+ "2002-02-22", # Friday
+ "2002-10-10", # Election day
+ "2003-04-10", # Thursday
+ "2004-05-03", # Monday (Labour Day make-up?)
+ "2005-08-18", # Thursday
+ "2005-11-01", # Tuesday
+ "2006-04-12", # Wednesday
+ "2006-10-26", # Thursday
+ "2006-10-27", # Friday
+ "2007-01-29", # Monday
+ "2007-01-30", # Tuesday
+ "2007-12-28", # Friday
+ "2008-02-18", # Monday
+ "2011-11-11", # Friday
+ "2011-10-24", # Death of Begum Nusrat Bhutto
+ "2012-10-29", # Birthday of Guru Balmik Sawami Ji
+ "2012-09-21", # Day of Love for the Prophet Muhammad
+ "2018-07-25", # Election day
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ self.new_years_day,
+ self.juma_tul_wida,
+ self.eid_ul_fitr,
+ self.eid_ul_azha,
+ self.ashura,
+ self.eid_milad_un_nabi,
+ self.miscellaneous_closures,
+ )
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xkls.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xkls.py
new file mode 100644
index 0000000000000000000000000000000000000000..609a9cdfb50d021d313274d94a276ee5002c721a
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xkls.py
@@ -0,0 +1,127 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+from .xkls_holidays import (
+ ChineseNewYear,
+ ChineseNewYearDay2,
+ ChineseNewYearsHalfDay,
+ ChristmasDay,
+ Deepavali,
+ EidAlAdha,
+ EidAlFitrDay1,
+ EidAlFitrDay2,
+ EidAlFitrHalfDay,
+ FederalTerritoryDay,
+ LabourDay,
+ MalaysiaDay,
+ MuhammadBirthday,
+ Muharram,
+ NationalDay,
+ NewYearsDay,
+ NuzulAlQuran,
+ Thaipusam,
+ WesakDay,
+ misc_adhoc,
+)
+
+
+class XKLSExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Malaysia Stock Exchange (XKLS).
+
+ Open Time: 9:00 AM, MYT
+ Close Time: 5:00 PM, MYT
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Thaipusam (Tamil Calendar)
+ - Federal Territory Day (Feb 1)
+ - Chinese New Year (2 days)
+ - Labour Day (May 1)
+ - Wesak Day (Chinese Lunar Calendar)
+ - Nuzul Al'Quran (Islamic Lunar Calendar)
+ - Eid al-Fitr (2 days)
+ - Eid al-Adha
+ - National Day (Aug 31)
+ - Muharram (Lunar Calendar)
+ - Malaysia Day (Sep 16)
+ - Deepavali
+ - Prophet Muhammad's Birthday
+ - Christmas Day
+
+ Early Closes:
+ - Chinese New Year's Eve
+ - Eid al-Fitr Eve
+
+ TODO: XKLS takes a two hour lunch break from 12:30-2:30pm, but we are
+ ignoring this for now.
+ """
+
+ name = "XKLS"
+
+ tz = ZoneInfo("Asia/Kuala_Lumpur")
+
+ open_times = ((None, time(9)),)
+
+ close_times = ((None, time(17, 00)),)
+
+ regular_early_close = time(12, 30)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ FederalTerritoryDay,
+ LabourDay,
+ NationalDay,
+ MalaysiaDay,
+ ChristmasDay,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ misc_adhoc,
+ ChineseNewYear,
+ ChineseNewYearDay2,
+ NuzulAlQuran,
+ EidAlFitrDay1,
+ EidAlFitrDay2,
+ EidAlAdha,
+ Muharram,
+ MuhammadBirthday,
+ Deepavali,
+ Thaipusam,
+ WesakDay,
+ )
+ )
+
+ @property
+ def special_closes_adhoc(self):
+ # Regular early closes on Chinese New Years Eve, Eid al-Fitr Eve
+ early_close_days = pd.DatetimeIndex(
+ set(ChineseNewYearsHalfDay + EidAlFitrHalfDay)
+ )
+ return [(self.regular_early_close, early_close_days)]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xkrx.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xkrx.py
new file mode 100644
index 0000000000000000000000000000000000000000..846e79b2c42902d1cebcae7b86e6da3774d6b3b0
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xkrx.py
@@ -0,0 +1,406 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from __future__ import annotations
+
+from datetime import time
+import functools
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import Holiday
+from pandas.tseries.offsets import CustomBusinessDay
+
+from .exchange_calendar import HolidayCalendar
+from .precomputed_exchange_calendar import PrecomputedExchangeCalendar
+from .xkrx_holidays import (
+ krx_regular_holiday_rules,
+ precomputed_krx_holidays,
+ precomputed_csat_days,
+)
+from .pandas_extensions.offsets import MultipleWeekmaskCustomBusinessDay
+from .pandas_extensions.korean_holiday import next_business_day
+
+
+class XKRXExchangeCalendar(PrecomputedExchangeCalendar):
+ """
+ Calendar for the Korea exchange, and the primary calendar for
+ the country of South Korea.
+
+ Open Time: 9:00 AM, KST (Korean Standard Time)
+ Close Time: 3:30 PM, KST (Korean Standard Time)
+
+ NOTE: Korea observes Standard Time year-round.
+
+ Due to the complexity around the Korean holidays, we are hardcoding
+ a list of holidays covering 1986-2019, inclusive.
+
+ Regularly-Observed Holidays:
+ - Seollal (New Year's Day)
+ - Independence Movement Day
+ - Labor Day
+ - Buddha's Birthday
+ - Memorial Day
+ - Provincial Election Day
+ - Liberation Day
+ - Chuseok (Korean Thanksgiving)
+ - National Foundation Day
+ - Christmas Day
+ - End of Year Holiday
+
+ NOTE: Hangeul Day became a national holiday in 2013
+ - Hangeul Proclamation Day
+ """
+
+ name = "XKRX"
+
+ tz = ZoneInfo("Asia/Seoul")
+
+ # KRX schedule change history
+ # https://blog.naver.com/daishin_blog/220724111002
+
+ # 1956-03-03: 0930~1130, 1330~1530
+ # 1978-04-??: 1000~1200, 1330~1530
+ # 1986-04-??: 0940~1200, 1320~1520
+ # 1987-03-??: 0940~1140, 1320~1520
+ # 1995-01-01: 0930~1130, 1300~1500
+ # 1998-12-07: 0900~1200, 1300~1500
+ # 2000-05-22: 0900~1500
+ # 2016-08-01: 0900~1530
+
+ # Break time disappears since 2000-05-22
+ # https://www.donga.com/news/Economy/article/all/20000512/7534650/1
+
+ # Closing time became 30mins late since 2016-08-01
+ # https://biz.chosun.com/site/data/html_dir/2016/07/24/2016072400309.html
+
+ open_times = (
+ (None, time(9, 30)),
+ (pd.Timestamp("1978-04-01"), time(10, 0)),
+ (pd.Timestamp("1986-04-01"), time(9, 40)),
+ (pd.Timestamp("1995-01-01"), time(9, 30)),
+ (pd.Timestamp("1998-12-07"), time(9, 0)),
+ )
+ break_start_times = (
+ (None, time(11, 30)),
+ (pd.Timestamp("1978-04-01"), time(12, 0)),
+ (pd.Timestamp("1987-03-01"), time(11, 40)),
+ (pd.Timestamp("1995-01-01"), time(11, 30)),
+ (pd.Timestamp("1998-12-07"), time(12, 0)),
+ (pd.Timestamp("2000-05-22"), None),
+ )
+ break_end_times = (
+ (None, time(13, 30)),
+ (pd.Timestamp("1986-04-01"), time(13, 20)),
+ (pd.Timestamp("1995-01-01"), time(13, 0)),
+ (pd.Timestamp("2000-05-22"), None),
+ )
+ close_times = (
+ (None, time(15, 30)),
+ (pd.Timestamp("1986-04-01"), time(15, 20)),
+ (pd.Timestamp("1995-01-01"), time(15, 0)),
+ (pd.Timestamp("2016-08-01"), time(15, 30)),
+ )
+
+ # Saterday became holiday since 1998-12-07
+ # https://www.hankyung.com/finance/article/1998080301961
+
+ weekmask = "1111100"
+
+ @property
+ def special_weekmasks(self):
+ """
+ Returns
+ -------
+ list: List of (date, date, str) tuples that represent special
+ weekmasks that applies between dates.
+ """
+ return [
+ (None, pd.Timestamp("1998-12-06"), "1111110"),
+ ]
+
+ @classmethod
+ def precomputed_holidays(cls) -> list[pd.Timestamp]:
+ return precomputed_krx_holidays.tolist()
+
+ @classmethod
+ def _earliest_precomputed_year(cls) -> int:
+ return 1956
+
+ @classmethod
+ def _latest_precomputed_year(cls) -> int:
+ return 2050
+
+ # KRX regular and precomputed adhoc holidays
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(krx_regular_holiday_rules)
+
+ # The first business day of each year:
+ # opening schedule is delayed by an hour.
+
+ @property
+ def special_offsets(self):
+ """
+ Returns
+ -------
+ list: List of (timedelta, timedelta, timedelta, timedelta, AbstractHolidayCalendar) tuples
+ that represent special open, break_start, break_end, close offsets
+ and corresponding HolidayCalendars.
+ """
+ return [
+ (
+ pd.Timedelta(1, unit="h"),
+ None,
+ None,
+ None,
+ HolidayCalendar(
+ [
+ Holiday(
+ "First Business Day of Year",
+ month=1,
+ day=1,
+ observance=next_business_day,
+ )
+ ]
+ ),
+ ),
+ ]
+
+ # Every year's CSAT day, all schedules are delayed by:
+ # before 1998-11-18: 30 minutes
+ # after 1998-11-18: 1 hour
+
+ @property
+ def special_offsets_adhoc(
+ self,
+ ) -> list[
+ tuple[pd.Timedelta, pd.Timedelta, pd.Timedelta, pd.Timedelta, pd.DatetimeIndex]
+ ]:
+ """
+ Returns
+ -------
+ list: List of (timedelta, timedelta, timedelta, timedelta, DatetimeIndex) tuples
+ that represent special open, break_start, break_end, close offsets
+ and corresponding DatetimeIndexes.
+ """
+ return [
+ (
+ pd.Timedelta(30, unit="m"),
+ pd.Timedelta(30, unit="m"),
+ pd.Timedelta(30, unit="m"),
+ pd.Timedelta(30, unit="m"),
+ precomputed_csat_days[
+ precomputed_csat_days.slice_indexer("1993-08-20", "1998-11-17")
+ ],
+ ),
+ (
+ pd.Timedelta(1, unit="h"),
+ pd.Timedelta(1, unit="h"),
+ pd.Timedelta(1, unit="h"),
+ pd.Timedelta(1, unit="h"),
+ precomputed_csat_days[
+ precomputed_csat_days.slice_indexer("1998-11-18", None)
+ ],
+ ),
+ ]
+
+ def _overwrite_special_offsets(
+ self,
+ session_labels: pd.DatetimeIndex,
+ standard_times: pd.DatetimeIndex | None,
+ offsets: tuple[pd.Timedelta, HolidayCalendar],
+ ad_hoc_offsets: tuple[pd.Timedelta, pd.DatetimeIndex],
+ start_date: pd.Timestamp,
+ end_date: pd.Timestamp,
+ strict: bool = False,
+ ):
+ # Short circuit when nothing to apply.
+ if standard_times is None or not len(standard_times):
+ return
+
+ len_m, len_oc = len(session_labels), len(standard_times)
+ if len_m != len_oc:
+ raise ValueError(
+ "Found misaligned dates while building calendar.\nExpected"
+ " session_labels to be the same length as open_or_closes but,\n"
+ f"len(session_labels)={len_m}, len(open_or_closes)={len_oc}"
+ )
+
+ regular = []
+ for offset, calendar in offsets:
+ days = calendar.holidays(start_date, end_date)
+ series = pd.Series(index=days, data=offset)
+ regular.append(series)
+
+ ad_hoc = []
+ for offset, datetimes in ad_hoc_offsets:
+ series = pd.Series(index=datetimes, data=offset)
+ ad_hoc.append(series)
+
+ merged = regular + ad_hoc
+ if not merged:
+ return pd.Series([], dtype="timedelta64[ns]")
+
+ result = pd.concat(merged).sort_index()
+ offsets = result.loc[(result.index >= start_date) & (result.index <= end_date)]
+
+ # Find the array indices corresponding to each special date.
+ indexer = session_labels.get_indexer(offsets.index)
+
+ # -1 indicates that no corresponding entry was found. If any -1s are
+ # present, then we have special dates that doesn't correspond to any
+ # trading day.
+ if -1 in indexer and strict:
+ bad_dates = list(offsets.index[indexer == -1])
+ raise ValueError(f"Special dates {bad_dates} are not trading days.")
+
+ special_opens_or_closes = standard_times[indexer] + offsets
+
+ # Short circuit when nothing to apply.
+ if not len(special_opens_or_closes):
+ return
+
+ # NOTE: This is a slightly dirty hack. We're in-place overwriting the
+ # internal data of an Index, which is conceptually immutable. Since we're
+ # maintaining sorting, this should be ok, but this is a good place to
+ # sanity check if things start going haywire with calendar computations.
+ standard_times.values[indexer] = special_opens_or_closes.values
+
+ def apply_special_offsets(
+ self,
+ session_labels: pd.DatetimeIndex,
+ start: pd.Timestamp,
+ end: pd.Timestamp,
+ ):
+ """Evaluate and overwrite special offsets."""
+ _special_offsets = self.special_offsets
+ _special_offsets_adhoc = self.special_offsets_adhoc
+
+ _special_open_offsets = [
+ (t[0], t[-1]) for t in _special_offsets if t[0] is not None
+ ]
+ _special_open_offsets_adhoc = [
+ (t[0], t[-1]) for t in _special_offsets_adhoc if t[0] is not None
+ ]
+ _special_break_start_offsets = [
+ (t[1], t[-1]) for t in _special_offsets if t[1] is not None
+ ]
+ _special_break_start_offsets_adhoc = [
+ (t[1], t[-1]) for t in _special_offsets_adhoc if t[1] is not None
+ ]
+ _special_break_end_offsets = [
+ (t[2], t[-1]) for t in _special_offsets if t[2] is not None
+ ]
+ _special_break_end_offsets_adhoc = [
+ (t[2], t[-1]) for t in _special_offsets_adhoc if t[2] is not None
+ ]
+ _special_close_offsets = [
+ (t[3], t[-1]) for t in _special_offsets if t[3] is not None
+ ]
+ _special_close_offsets_adhoc = [
+ (t[3], t[-1]) for t in _special_offsets_adhoc if t[3] is not None
+ ]
+
+ self._overwrite_special_offsets(
+ session_labels,
+ self._opens,
+ _special_open_offsets,
+ _special_open_offsets_adhoc,
+ start,
+ end,
+ )
+ self._overwrite_special_offsets(
+ session_labels,
+ self._break_starts,
+ _special_break_start_offsets,
+ _special_break_start_offsets_adhoc,
+ start,
+ end,
+ )
+ self._overwrite_special_offsets(
+ session_labels,
+ self._break_ends,
+ _special_break_end_offsets,
+ _special_break_end_offsets_adhoc,
+ start,
+ end,
+ )
+ self._overwrite_special_offsets(
+ session_labels,
+ self._closes,
+ _special_close_offsets,
+ _special_close_offsets_adhoc,
+ start,
+ end,
+ )
+
+ @functools.cached_property
+ def day(self):
+ if self.special_weekmasks:
+ return MultipleWeekmaskCustomBusinessDay(
+ holidays=self.adhoc_holidays,
+ calendar=self.regular_holidays,
+ weekmask=self.weekmask,
+ weekmasks=self.special_weekmasks,
+ )
+ else:
+ return CustomBusinessDay(
+ holidays=self.adhoc_holidays,
+ calendar=self.regular_holidays,
+ weekmask=self.weekmask,
+ )
+
+
+class PrecomputedXKRXExchangeCalendar(PrecomputedExchangeCalendar):
+ """
+ Calendar for the Korea exchange, and the primary calendar for
+ the country of South Korea.
+
+ Open Time: 9:00 AM, KST (Korean Standard Time)
+ Close Time: 3:30 PM, KST (Korean Standard Time)
+
+ NOTE: Korea observes Standard Time year-round.
+
+ Due to the complexity around the Korean holidays, we are hardcoding
+ a list of holidays covering 1986-2019, inclusive.
+
+ Regularly-Observed Holidays:
+ - Seollal (New Year's Day)
+ - Independence Movement Day
+ - Labor Day
+ - Buddha's Birthday
+ - Memorial Day
+ - Provincial Election Day
+ - Liberation Day
+ - Chuseok (Korean Thanksgiving)
+ - National Foundation Day
+ - Christmas Day
+ - End of Year Holiday
+
+ NOTE: Hangeul Day became a national holiday in 2013
+ - Hangeul Proclamation Day
+ """
+
+ name = "XKRX"
+
+ tz = ZoneInfo("Asia/Seoul")
+
+ open_times = ((None, time(9)),)
+ close_times = ((None, time(15, 30)),)
+
+ @classmethod
+ def precomputed_holidays(cls):
+ return precomputed_krx_holidays
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xlim.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xlim.py
new file mode 100644
index 0000000000000000000000000000000000000000..767558eb62312ea3da9f7a9955855e6b6ee207a8
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xlim.py
@@ -0,0 +1,152 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import GoodFriday, Holiday
+
+from .common_holidays import (
+ all_saints_day,
+ christmas,
+ european_labour_day,
+ immaculate_conception,
+ maundy_thursday,
+ new_years_day,
+ new_years_eve,
+ saint_peter_and_saint_paul_day,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+####################
+# Regular Holidays #
+####################
+NewYearsDay = new_years_day()
+
+MaundyThursday = maundy_thursday()
+
+LabourDay = european_labour_day()
+
+SaintPeterAndSaintPaulDay = saint_peter_and_saint_paul_day()
+
+IndependenceDay1 = Holiday("Independence Day", month=7, day=28)
+IndependenceDay2 = Holiday("Independence Day", month=7, day=29)
+
+SantaRosa = Holiday("Santa Rosa", month=8, day=30)
+
+BattleOfAngamos = Holiday("Battle of Angamos", month=10, day=8)
+
+AllSaintsDay = all_saints_day()
+
+ImmaculateConception = immaculate_conception()
+
+Christmas = christmas()
+
+NewYearsEve = new_years_eve(end_date="2008")
+
+
+##################
+# Adhoc Holidays #
+##################
+ExchangeHolidays = [
+ pd.Timestamp("2009-01-02"),
+ pd.Timestamp("2009-07-27"),
+ pd.Timestamp("2015-07-27"),
+ pd.Timestamp("2015-10-09"),
+]
+
+NationalHolidays = [
+ pd.Timestamp("2015-01-02"),
+]
+
+ASPASummit = [
+ pd.Timestamp("2012-10-01"),
+ pd.Timestamp("2012-10-02"),
+]
+
+APECSummit = [
+ pd.Timestamp("2016-11-17"),
+ pd.Timestamp("2016-11-18"),
+]
+
+EighthSummitOfTheAmericas = [pd.Timestamp("2018-04-13")]
+
+
+class XLIMExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Lima Stock Exchange (Bolsa de Valores de Lima) in Peru.
+
+ Open Time: 9:00 AM, Peruvian Time
+ Close Time: 4:00 PM, Peruvian Time
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Maundy Thursday
+ - Good Friday
+ - Labour Day
+ - Saint Paul and Saint Peter Day
+ - Independence Day
+ - Santa Rosa
+ - Battle of Angamos
+ - All Saints' Day
+ - Immaculate Conception
+ - Christmas Day
+
+ Holidays No Longer Observed:
+ - New Year's Eve
+
+ Early Closes:
+ - None
+ """
+
+ name = "XLIM"
+ tz = ZoneInfo("America/Lima")
+
+ open_times = ((None, time(9)),)
+ close_times = ((None, time(16)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ MaundyThursday,
+ GoodFriday,
+ LabourDay,
+ SaintPeterAndSaintPaulDay,
+ IndependenceDay1,
+ IndependenceDay2,
+ SantaRosa,
+ BattleOfAngamos,
+ AllSaintsDay,
+ ImmaculateConception,
+ Christmas,
+ NewYearsEve,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ ExchangeHolidays,
+ NationalHolidays,
+ ASPASummit,
+ APECSummit,
+ EighthSummitOfTheAmericas,
+ )
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xlis.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xlis.py
new file mode 100644
index 0000000000000000000000000000000000000000..c94988956708005686a92e29a015ea54b8b85402
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xlis.py
@@ -0,0 +1,164 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import Easter, EasterMonday, GoodFriday, Holiday
+from pandas.tseries.offsets import Day
+
+from .common_holidays import (
+ all_saints_day,
+ assumption_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ corpus_christi,
+ european_labour_day,
+ immaculate_conception,
+ new_years_day,
+ new_years_eve,
+)
+from .exchange_calendar import WEEKDAYS, HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+Carnival = Holiday(
+ "Carnival",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(-47)],
+ end_date="2003",
+)
+CorpusChristi = corpus_christi(end_date="2003")
+
+LibertyDay = Holiday(
+ "Liberty Day",
+ month=4,
+ day=25,
+ end_date="2003",
+)
+
+LabourDay = european_labour_day()
+
+PortugalDay = Holiday(
+ "Portugal Day",
+ month=6,
+ day=10,
+ end_date="2003",
+)
+
+SaintAnthonysDay = Holiday(
+ "Saint Anthony's Day",
+ month=6,
+ day=13,
+ end_date="2002",
+)
+
+AssumptionDay = assumption_day(end_date="2003")
+
+RepublicDay = Holiday(
+ "Republic Day",
+ month=10,
+ day=5,
+ end_date="2003",
+)
+
+AllSaintsDay = all_saints_day(end_date="2003")
+
+IndependenceDay = Holiday(
+ "Independence Day",
+ month=12,
+ day=1,
+ end_date="2003",
+)
+
+ImmaculateConception = immaculate_conception(end_date="2003")
+
+ChristmasEveBefore2003 = christmas_eve(end_date="2003")
+ChristmasEve = christmas_eve(start_date="2003", days_of_week=WEEKDAYS)
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve(days_of_week=WEEKDAYS)
+
+
+class XLISExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Euronext Lisbon exchange, and the primary calendar for the
+ country of Portugal.
+
+ Open Time: 8:00 AM, WET (Western European Time)
+ Close Time: 4:30 PM, WET (Western European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Christmas Day
+ - Boxing Day
+
+ Early Closes:
+ - Christmas Eve
+ - New Year's Eve
+
+ Other countries on the Euronext:
+ - Belgium
+ - France
+ - Netherlands
+ """
+
+ # Source: https://www.euronext.com/en/calendars-hours
+ # Converted 14:05 CET to local time zone WET.
+ regular_early_close = time(13, 5)
+
+ name = "XLIS" # Euronext Lisbon
+ tz = ZoneInfo("Europe/Lisbon")
+ open_times = ((None, time(8)),)
+ close_times = ((None, time(16, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ Carnival,
+ GoodFriday,
+ EasterMonday,
+ CorpusChristi,
+ LibertyDay,
+ LabourDay,
+ PortugalDay,
+ SaintAnthonysDay,
+ AssumptionDay,
+ RepublicDay,
+ AllSaintsDay,
+ IndependenceDay,
+ ImmaculateConception,
+ ChristmasEveBefore2003,
+ Christmas,
+ BoxingDay,
+ ]
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar([ChristmasEve, NewYearsEve]),
+ ),
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xlon.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xlon.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e613b496af52eb504c891b6d0ef748c1f229090
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xlon.py
@@ -0,0 +1,266 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import (
+ MO,
+ DateOffset,
+ EasterMonday,
+ GoodFriday,
+ Holiday,
+ previous_friday,
+ weekend_to_monday,
+)
+
+from .common_holidays import (
+ boxing_day,
+ christmas,
+ new_years_day,
+ weekend_boxing_day,
+ weekend_christmas,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+# Regular Holidays
+# ----------------
+# New Year's Day
+LSENewYearsDay = new_years_day(observance=weekend_to_monday)
+
+# Early May bank holiday has two exceptions based on the 50th and 75th
+# anniversary of VE-Day
+# 1995-05-01 Early May bank holiday removed for VE-day 50th anniversary
+# 2020-05-04 Early May bank holiday removed for VE-day 75th anniversary
+
+# Early May bank holiday pre-1995
+MayBank_pre_1995 = Holiday(
+ "Early May Bank Holiday",
+ month=5,
+ offset=DateOffset(weekday=MO(1)),
+ day=1,
+ end_date=pd.Timestamp("1994-12-31"),
+)
+
+# Early May bank holiday post-1995 and pre-2020
+MayBank_post_1995_pre_2020 = Holiday(
+ "Early May Bank Holiday",
+ month=5,
+ offset=DateOffset(weekday=MO(1)),
+ day=1,
+ start_date=pd.Timestamp("1996-01-01"),
+ end_date=pd.Timestamp("2019-12-31"),
+)
+
+# Early May bank holiday post 2020
+MayBank_post_2020 = Holiday(
+ "Early May Bank Holiday",
+ month=5,
+ offset=DateOffset(weekday=MO(1)),
+ day=1,
+ start_date=pd.Timestamp("2021-01-01"),
+)
+
+
+# Spring bank holiday has three exceptions based on the Golden, Diamond & Platinum Jubilee
+# 2002-05-27 Spring bank holiday removed for Golden Jubilee
+# 2012-05-28 Spring bank holiday removed for Diamond Jubilee
+# 2022-05-30 Spring bank holiday moved to 2022-06-02 to be adjacent to the Platinum Jubilee day 2022-06-03
+
+# Spring bank holiday
+SpringBank_pre_2002 = Holiday(
+ "Spring Bank Holiday",
+ month=5,
+ day=31,
+ offset=DateOffset(weekday=MO(-1)),
+ end_date=pd.Timestamp("2001-12-31"),
+)
+
+SpringBank_post_2002_pre_2012 = Holiday(
+ "Spring Bank Holiday",
+ month=5,
+ day=31,
+ offset=DateOffset(weekday=MO(-1)),
+ start_date=pd.Timestamp("2003-01-01"),
+ end_date=pd.Timestamp("2011-12-31"),
+)
+
+SpringBank_post_2012_pre_2022 = Holiday(
+ "Spring Bank Holiday",
+ month=5,
+ day=31,
+ offset=DateOffset(weekday=MO(-1)),
+ start_date=pd.Timestamp("2013-01-01"),
+ end_date=pd.Timestamp("2021-12-31"),
+)
+
+SpringBank_post_2022 = Holiday(
+ "Spring Bank Holiday",
+ month=5,
+ day=31,
+ offset=DateOffset(weekday=MO(-1)),
+ start_date=pd.Timestamp("2023-01-01"),
+)
+
+# Summer bank holiday
+SummerBank = Holiday(
+ "Summer Bank Holiday",
+ month=8,
+ day=31,
+ offset=DateOffset(weekday=MO(-1)),
+)
+
+Christmas = christmas()
+
+WeekendChristmas = weekend_christmas()
+
+BoxingDay = boxing_day()
+
+WeekendBoxingDay = weekend_boxing_day()
+
+# Early Closes
+# ------------
+# If Christmas Eve falls on a weekday, that day is a half day.
+# If it falls on a weekend, the preceding Friday is a half day.
+ChristmasEve = Holiday(
+ "Christmas Eve",
+ month=12,
+ day=24,
+ observance=previous_friday,
+)
+# New Year's eve (or the preceding Friday if it falls on a weekend)
+# is a half day. Except for 1999-12-31, when the Queen declared a
+# bank holiday.
+NewYearsEvePre1999 = Holiday(
+ "New Year's Eve",
+ month=12,
+ day=31,
+ observance=previous_friday,
+ end_date=pd.Timestamp("1999-01-01"),
+)
+NewYearsEvePost2000 = Holiday(
+ "New Year's Eve",
+ month=12,
+ day=31,
+ observance=previous_friday,
+ start_date=pd.Timestamp("2000-01-01"),
+)
+
+
+class XLONExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the London Stock Exchange (XLON).
+
+ Open Time: 8:00 AM, GMT
+ Close Time: 4:30 PM, GMT
+
+ Regularly-Observed Holidays:
+ - New Years Day (observed on first business day on/after)
+ - Good Friday
+ - Easter Monday
+ - Early May Bank Holiday (first Monday in May)
+ - Spring Bank Holiday (last Monday in May)
+ - Summer Bank Holiday (last Monday in May)
+ - Christmas Day
+ - Dec. 27th (if Christmas is on a weekend)
+ - Boxing Day
+ - Dec. 28th (if Boxing Day is on a weekend)
+
+ Early Closes:
+ - Christmas Eve
+ - New Year's Eve
+ """
+
+ regular_early_close = time(12, 30)
+
+ name = "XLON"
+
+ tz = ZoneInfo("Europe/London")
+
+ open_times = ((None, time(8)),)
+
+ close_times = ((None, time(16, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ LSENewYearsDay,
+ GoodFriday,
+ EasterMonday,
+ MayBank_pre_1995,
+ MayBank_post_1995_pre_2020,
+ MayBank_post_2020,
+ SpringBank_pre_2002,
+ SpringBank_post_2002_pre_2012,
+ SpringBank_post_2012_pre_2022,
+ SpringBank_post_2022,
+ SummerBank,
+ Christmas,
+ WeekendChristmas,
+ BoxingDay,
+ WeekendBoxingDay,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [
+ # VE-Day Anniversary
+ pd.Timestamp("1995-05-08"), # 50th Anniversary
+ pd.Timestamp("2020-05-08"), # 75th Anniversary
+ # Queen Elizabeth II Jubilees
+ # Silver Jubilee
+ pd.Timestamp("1977-06-07"),
+ # Golden Jubilee
+ pd.Timestamp("2002-06-03"),
+ pd.Timestamp("2002-06-04"),
+ # Diamond Jubilee
+ pd.Timestamp("2012-06-04"),
+ pd.Timestamp("2012-06-05"),
+ # Platinum Jubilee (moved Spring bank holiday followed by Jubilee day)
+ pd.Timestamp("2022-06-02"),
+ pd.Timestamp("2022-06-03"),
+ # Queen Elizabeth II Funeral
+ pd.Timestamp("2022-09-19"),
+ # Coronation of King Charles III
+ pd.Timestamp("2023-05-08"),
+ # Royal Weddings
+ # Wedding Day of Princess Anne and Mark Phillips
+ pd.Timestamp("1973-11-14"),
+ # Wedding Day of Prince Charles and Diana Spencer
+ pd.Timestamp("1981-07-29"),
+ # Wedding Day of Prince William and Catherine Middleton
+ pd.Timestamp("2011-04-29"),
+ # Miscellaneous
+ # Eve of 3rd Millenium A.D.
+ pd.Timestamp("1999-12-31"),
+ ]
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [
+ ChristmasEve,
+ NewYearsEvePre1999,
+ NewYearsEvePost2000,
+ ]
+ ),
+ )
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmad.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmad.py
new file mode 100644
index 0000000000000000000000000000000000000000..b833dec984c5d8ae14e29c212acffde43a9a58ee
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmad.py
@@ -0,0 +1,155 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday, weekend_to_monday
+
+from .common_holidays import (
+ all_saints_day,
+ assumption_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ epiphany,
+ european_labour_day,
+ immaculate_conception,
+ new_years_day,
+ new_years_eve,
+)
+from .exchange_calendar import WEEKDAYS, HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+Epiphany = epiphany(end_date="2007")
+
+LabourDay = european_labour_day()
+
+AssumptionDay = assumption_day(end_date="2005", observance=weekend_to_monday)
+
+NationalDay = Holiday(
+ "National Day",
+ month=10,
+ day=12,
+ end_date="2005",
+)
+
+AllSaintsDay = all_saints_day(end_date="2005")
+
+ConstitutionDay = Holiday(
+ "Constitution Day",
+ month=12,
+ day=6,
+ end_date="2005",
+)
+
+ImmaculateConception = immaculate_conception(end_date="2005")
+
+ChristmasEveThrough2010 = christmas_eve(end_date="2011")
+ChristmasEveFrom2021 = christmas_eve(start_date="2021")
+ChristmasEveEarlyClose2012To2020 = christmas_eve(
+ start_date="2012",
+ end_date="2021",
+ days_of_week=(WEEKDAYS),
+)
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEveThrough2010 = new_years_eve(end_date="2011")
+NewYearsEveFrom2021 = new_years_eve(start_date="2021")
+NewYearsEveEarlyClose2012To2020 = new_years_eve(
+ start_date="2012",
+ end_date="2021",
+ days_of_week=(WEEKDAYS),
+)
+
+
+class XMADExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Madrid Stock Exchange (Bolsa de Madrid).
+
+ Open Time: 9:00 AM, CET (Central European Time)
+ Close Time: 5:30 PM, CET (Central European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Christmas Eve (apart from when it was observed as an early close)
+ - Christmas Day
+ - Boxing Day
+
+ Holidays No Longer Observed:
+ - Epiphany (until 2006, inclusive)
+ - Assumption Day (until 2004, inclusive)
+ - National Day (until 2004, inclusive)
+ - All Saints Day (until 2004, inclusive)
+ - Constitution Day (until 2004, inclusive)
+ - Immaculate Conception (until 2004, inclusive)
+ - New Year's Eve (until 2010, inclusive)
+
+ Early Closes:
+ - Christmas Eve (2012 to 2020, inclusive)
+ - New Year's Eve (2012 and after)
+ """
+
+ regular_early_close = time(14, 00)
+
+ name = "XMAD"
+
+ tz = ZoneInfo("Europe/Madrid")
+
+ open_times = ((None, time(9)),)
+
+ close_times = ((None, time(17, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ Epiphany,
+ GoodFriday,
+ EasterMonday,
+ LabourDay,
+ AssumptionDay,
+ NationalDay,
+ AllSaintsDay,
+ ConstitutionDay,
+ ImmaculateConception,
+ ChristmasEveThrough2010,
+ ChristmasEveFrom2021,
+ Christmas,
+ BoxingDay,
+ NewYearsEveThrough2010,
+ NewYearsEveFrom2021,
+ ]
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [
+ ChristmasEveEarlyClose2012To2020,
+ NewYearsEveEarlyClose2012To2020,
+ ]
+ ),
+ )
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmex.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmex.py
new file mode 100644
index 0000000000000000000000000000000000000000..619e19ca9769a43a0db4e51ae50634bedc42c234
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmex.py
@@ -0,0 +1,136 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import MO, GoodFriday, Holiday
+from pandas.tseries.offsets import DateOffset
+
+from .common_holidays import (
+ christmas,
+ european_labour_day,
+ maundy_thursday,
+ new_years_day,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+# Starting in 2007 Constitution Day is observed on the first Monday of Feb.
+ConstitutionDay = Holiday("Constitution Day", month=2, day=5, end_date="2007")
+ConstitutionDayObserved = Holiday(
+ "Constitution Day Observed",
+ month=2,
+ day=1,
+ offset=DateOffset(weekday=MO(1)),
+ start_date="2007",
+)
+
+# Starting in 2007 Juarez's Birthay is observed on the third Monday of March.
+JuarezBirthday = Holiday("Juarez's Birthday", month=3, day=21, end_date="2007")
+JuarezBirthdayObserved = Holiday(
+ "Juarez's Birthday Observed",
+ month=3,
+ day=1,
+ offset=DateOffset(weekday=MO(3)),
+ start_date="2007",
+)
+
+MaundyThursday = maundy_thursday()
+
+LabourDay = european_labour_day()
+
+IndependenceDay = Holiday("Independence Day", month=9, day=16)
+
+AllSoulsDay = Holiday("All Souls' Day", month=11, day=2, start_date="2006")
+
+# Starting in 2007 Revolution Day is observed on the third Monday of November.
+RevolutionDay = Holiday("Revolution Day", month=11, day=20, end_date="2007")
+RevolutionDayObserved = Holiday(
+ "Revolution Day Observed",
+ month=11,
+ day=1,
+ offset=DateOffset(weekday=MO(3)),
+ start_date="2007",
+)
+
+BankingHoliday = Holiday("Banking Holiday", month=12, day=12)
+
+Christmas = christmas()
+
+
+class XMEXExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Mexican Stock Exchange (Bolsa Mexicana de Valores) in
+ Mexico City.
+
+ Open Time: 8:30 AM, CT (Central Time)
+ Close Time: 3:00 PM, CT (Central Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Constitution Day
+ - Juarez's Birthday
+ - Maundy Thursday
+ - Good Friday
+ - Labour Day
+ - Independence Day
+ - All Souls' Day
+ - Mexican Revolution
+ - Banking Holiday
+ - Christmas Day
+
+ Holidays No Longer Observed:
+ - None
+
+ Early Closes:
+ - None
+ """
+
+ name = "XMEX"
+ tz = ZoneInfo("America/Mexico_City")
+
+ open_times = ((None, time(8, 30)),)
+ close_times = ((None, time(15)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ ConstitutionDay,
+ ConstitutionDayObserved,
+ JuarezBirthday,
+ JuarezBirthdayObserved,
+ MaundyThursday,
+ GoodFriday,
+ LabourDay,
+ IndependenceDay,
+ AllSoulsDay,
+ RevolutionDay,
+ RevolutionDayObserved,
+ BankingHoliday,
+ Christmas,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [
+ # Bicentennial Celebration.
+ pd.Timestamp("2010-09-17"),
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmil.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmil.py
new file mode 100644
index 0000000000000000000000000000000000000000..96521e33fc1a595b273edda08cf9033a4051c1dd
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmil.py
@@ -0,0 +1,89 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday
+
+from .common_holidays import (
+ boxing_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ new_years_day,
+ new_years_eve,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+LabourDay = european_labour_day()
+
+Ferragosto = Holiday("Ferragosto", month=8, day=15)
+
+ChristmasEve = christmas_eve()
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve()
+
+
+class XMILExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Borsa Italiana in Milan, Italy.
+
+ Open Time: 9:00 AM, CET (Central European Time)
+ Close Time: 5:30 PM, CET (Central European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Ferragosto
+ - Christmas Eve
+ - Christmas Day
+ - Boxing Day
+ - New Year's Eve
+
+ Early Closes:
+ - None
+ """
+
+ name = "XMIL"
+
+ # Rome is the same timezone as Milan.
+ tz = ZoneInfo("Europe/Rome")
+
+ open_times = ((None, time(9)),)
+
+ close_times = ((None, time(17, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ GoodFriday,
+ EasterMonday,
+ LabourDay,
+ Ferragosto,
+ ChristmasEve,
+ Christmas,
+ BoxingDay,
+ NewYearsEve,
+ ]
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmos.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmos.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4b8ca84ef7f1bb163f7d820a49e8f35178c5761
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xmos.py
@@ -0,0 +1,321 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import datetime
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import Holiday, weekend_to_monday
+
+from .common_holidays import european_labour_day, new_years_day, new_years_eve
+from .exchange_calendar import WEEKDAYS, HolidayCalendar, ExchangeCalendar
+
+
+def new_years_eve_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # For some reason New Year's Eve was not a holiday these years.
+ return None if dt.year in [2008, 2009] else weekend_to_monday(dt)
+
+
+def new_years_day_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # New Year's Day did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2022] else weekend_to_monday(dt)
+
+
+def new_years_holiday_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # New Year's Holiday did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2016, 2021, 2022] else weekend_to_monday(dt)
+
+
+def orthodox_christmas_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # Orthodox Christmas did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2012, 2017, 2023, 2024] else weekend_to_monday(dt)
+
+
+def defender_of_fatherland_observance(
+ dt: datetime.datetime,
+) -> datetime.datetime | None:
+ # Defender of the Fatherland Day did not follow the next-non-holiday rule
+ # these years.
+ return None if dt.year in [2013, 2014, 2019] else weekend_to_monday(dt)
+
+
+def victory_day_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # Victory Day did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2021] else weekend_to_monday(dt)
+
+
+def day_of_russia_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # Day of Russia did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2021] else weekend_to_monday(dt)
+
+
+def unity_day_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # Unity Day did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2023] else weekend_to_monday(dt)
+
+
+NewYearsDay = new_years_day(observance=new_years_day_observance)
+NewYearsHoliday = Holiday(
+ "New Year's Holiday",
+ month=1,
+ day=2,
+ observance=new_years_holiday_observance,
+)
+NewYearsHoliday2 = Holiday(
+ "New Year's Holiday",
+ month=1,
+ day=3,
+ start_date="2005",
+ end_date="2012",
+)
+NewYearsHoliday3 = Holiday(
+ "New Year's Holiday",
+ month=1,
+ day=4,
+ start_date="2005",
+ end_date="2012",
+)
+NewYearsHoliday4 = Holiday(
+ "New Year's Holiday",
+ month=1,
+ day=5,
+ start_date="2005",
+ end_date="2012",
+)
+NewYearsHoliday5 = Holiday(
+ "New Year's Holiday",
+ month=1,
+ day=6,
+ start_date="2005",
+ end_date="2012",
+)
+
+OrthodoxChristmas = Holiday(
+ "Orthodox Christmas",
+ month=1,
+ day=7,
+ observance=orthodox_christmas_observance,
+)
+
+DefenderOfTheFatherlandDay = Holiday(
+ "Defender of the Fatherland Day",
+ month=2,
+ day=23,
+ observance=defender_of_fatherland_observance,
+)
+
+WomensDay = Holiday(
+ "Women's Day",
+ month=3,
+ day=8,
+ observance=weekend_to_monday,
+)
+
+LabourDay = european_labour_day(observance=weekend_to_monday)
+
+VictoryDay = Holiday(
+ "Victory Day",
+ month=5,
+ day=9,
+ observance=victory_day_observance,
+)
+
+DayOfRussia = Holiday(
+ "Day of Russia",
+ month=6,
+ day=12,
+ observance=day_of_russia_observance,
+)
+
+UnityDay = Holiday(
+ "Unity Day",
+ month=11,
+ day=4,
+ observance=unity_day_observance,
+ start_date="2005",
+)
+
+NewYearsEve = new_years_eve(
+ observance=new_years_eve_observance,
+ days_of_week=WEEKDAYS,
+)
+
+
+# Adhoc Holidays
+# --------------
+
+# All of the following "extensions" are bridge holidays, meaning they are
+# either a Monday or Friday that is made into a holiday to fill in the gap
+# between a Tuesday or Thursday holiday, respectively. Unfortunately having
+# these bridge days is not consistently the rule, so they are treated as adhoc.
+# This means that in the future there may be manual additions needed here.
+new_years_extensions = [
+ "2003-01-03",
+ "2013-01-03",
+ "2013-01-04",
+ "2014-01-03",
+]
+
+orthodox_christmas_extensions = [
+ "2003-01-06",
+ "2005-01-10",
+ "2008-01-08",
+ "2009-01-08",
+ "2009-01-09",
+ "2010-01-08",
+ "2011-01-10",
+ "2016-01-08",
+]
+
+defender_of_the_fatherland_extensions = [
+ "2006-02-24",
+ "2010-02-22",
+]
+
+womens_day_extensions = [
+ "2005-03-07",
+ "2011-03-07",
+ "2012-03-09",
+ "2022-03-07",
+]
+
+labour_day_extensions = [
+ "2002-05-02",
+ "2002-05-03",
+ "2003-05-02",
+ "2004-05-04",
+ "2007-04-30",
+ "2008-05-02",
+ "2012-04-30",
+ "2015-05-04",
+ "2016-05-03",
+ # LabourDay Holiday extended to Tuesday.
+ "2022-05-03",
+]
+
+victory_day_extensions = [
+ "2002-05-10",
+ "2005-05-10",
+ "2006-05-08",
+ "2017-05-08",
+ # Victory Day Holiday extended to Tuesday.
+ "2022-05-10",
+]
+
+day_of_russia_extensions = [
+ "2003-06-13",
+ "2007-06-11",
+ "2008-06-13",
+ "2012-06-11",
+ "2014-06-13",
+]
+
+unity_day_extensions = [
+ "2008-11-03",
+ "2010-11-05",
+]
+
+misc_adhoc = [
+ # Exchange Holidays.
+ "2002-11-07",
+ "2002-11-08",
+ "2002-12-12",
+ "2002-12-13",
+ "2003-11-07",
+ "2003-12-12",
+ "2004-11-08",
+ "2004-12-13",
+ "2008-09-18",
+ # Trading Suspended.
+ "2008-10-10",
+ "2008-10-27",
+ # Non-Working Days.
+ "2020-06-24",
+ "2020-07-01",
+]
+
+
+class XMOSExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Moscow Stock Exchange.
+
+ Open Time: 10:00 AM, MSK (Moscow Standard Time)
+ Close Time: 6:45 PM, MSK (Moscow Standard Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - New Year's Holiday
+ - Orthodox Christmas Day
+ - Defender of the Fatherland Day
+ - Women's Day
+ - Spring and Labour Day
+ - Victory Day
+ - Day of Russia
+ - Unity Day
+ - New Year's Eve
+
+ Holidays No Longer Observed:
+ - New Year's Holiday Week
+
+ Early Closes:
+ - None
+ """
+
+ name = "XMOS"
+
+ tz = ZoneInfo("Europe/Moscow")
+
+ open_times = ((None, datetime.time(10)),)
+
+ close_times = ((None, datetime.time(18, 45)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ NewYearsHoliday,
+ NewYearsHoliday2,
+ NewYearsHoliday3,
+ NewYearsHoliday4,
+ NewYearsHoliday5,
+ OrthodoxChristmas,
+ DefenderOfTheFatherlandDay,
+ WomensDay,
+ LabourDay,
+ VictoryDay,
+ DayOfRussia,
+ UnityDay,
+ NewYearsEve,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ new_years_extensions,
+ orthodox_christmas_extensions,
+ defender_of_the_fatherland_extensions,
+ womens_day_extensions,
+ labour_day_extensions,
+ victory_day_extensions,
+ day_of_russia_extensions,
+ unity_day_extensions,
+ misc_adhoc,
+ ),
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xnys.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xnys.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8b610282f9337dbf8814ff21aa5da48130c7a6a
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xnys.py
@@ -0,0 +1,258 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+from pandas import DatetimeIndex
+from pandas.tseries.holiday import GoodFriday, USLaborDay
+
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+from .us_holidays import (
+ August45VictoryOverJapan,
+ Christmas,
+ ChristmasBefore1954,
+ ChristmasEveBefore1993,
+ ChristmasEveInOrAfter1993,
+ ChristmasEvesAdhoc,
+ DayAfterChristmasAdhoc,
+ DayAfterIndependenceDayAdhoc,
+ DayBeforeDecorationAdhoc,
+ FirstLunarLandingClosing,
+ FridayAfterIndependenceDayPre2013,
+ HurricaneGloriaClosing,
+ HurricaneSandyClosings,
+ LincolnsBirthDayAdhoc,
+ March33BankHoliday,
+ MonTuesThursBeforeIndependenceDay,
+ NewYorkCityBlackout77,
+ November29BacklogRelief,
+ PaperworkCrisis68,
+ September11Closings,
+ USBlackFridayBefore1993,
+ USBlackFridayInOrAfter1993,
+ USColumbusDayBefore1954,
+ USElectionDay1848to1967,
+ USElectionDay1968to1980,
+ USIndependenceDay,
+ USIndependenceDayBefore1954,
+ USLincolnsBirthDayBefore1954,
+ USMartinLutherKingJrAfter1998,
+ USMemorialDay,
+ USMemorialDay1964to1969,
+ USMemorialDayBefore1964,
+ USJuneteenth,
+ USNationalDaysofMourning,
+ USNewYearsDay,
+ USPresidentsDay,
+ USThanksgivingDay,
+ USThanksgivingDay1939to1941,
+ USThanksgivingDayBefore1939,
+ USVeteransDay1934to1953,
+ USWashingtonsBirthDay1964to1970,
+ USWashingtonsBirthDayBefore1964,
+ WeatherSnowClosing,
+ WednesdayBeforeIndependenceDayPost2013,
+)
+
+# Useful resources for making changes to this file:
+# http://www.nyse.com/pdfs/closings.pdf
+# http://www.stevemorse.org/jcal/whendid.html
+
+
+class XNYSExchangeCalendar(ExchangeCalendar):
+ """
+ Regularly-Observed Holidays:
+ - New Years Day (observed on monday when Jan 1 is a Sunday)
+ - Martin Luther King Jr. Day (3rd Monday in January, only after 1998)
+ - Lincoln's Birthday (February 12th, only before 1954)
+ - Washington's Birthday (February 22nd, before 1971 with rule change in
+ 1964)
+ - Washington's Birthday (aka President's Day, 3rd Monday in February,
+ after 1970)
+ - Good Friday (two days before Easter Sunday)
+ - Memorial Day (May 30th, before 1970, with rule change in 1964)
+ - Memorial Day (last Monday in May, after 1970)
+ - Juneteenth (June 16th, since 2022)
+ - Independence Day (July 4th Sunday to Monday, before 1954)
+ - Independence Day (observed on the nearest weekday to July 4th, after
+ 1953)
+ - Election Day (First Tuesday starting on November 2nd, between 1848 and
+ 1967)
+ - Election Day (Every four years, first Tuesday starting on November 2nd,
+ between 1968 and 1980)
+ - Veterans Day (November 11th, between 1934 and 1953)
+ - Columbus Day (October 12th, before 1954)
+ - Labor Day (first Monday in September)
+ - Thanksgiving (last Thursday in November, before 1939)
+ - Thanksgiving (second to last Thursday in November, between 1939 and 1941)
+ - Thanksgiving (fourth Thursday in November, after 1941)
+ - Christmas (December 25th, Sunday to Monday, before 1954)
+ - Christmas (observed on nearest weekday to December 25, after 1953)
+
+ NOTE: The NYSE does not observe the following US Federal Holidays:
+ - Columbus Day (after 1953)
+ - Veterans Day (after 1953)
+
+ Regularly-Observed Early Closes:
+ - July 3rd (Mondays, Tuesdays, and Thursdays, 1995 onward)
+ - July 5th (Fridays, 1995 onward, except 2013)
+ - Christmas Eve (except on Fridays, when the exchange is closed entirely)
+ - Day After Thanksgiving (aka Black Friday, observed from 1992 onward)
+
+ NOTE: Until 1993, the standard early close time for the NYSE was 2:00 PM.
+ From 1993 onward, it has been 1:00 PM.
+
+ Additional Irregularities:
+ - Closed on 11/1/1929 and 11/29/1929 for backlog relief.
+ - Closed between 3/6/1933 and 3/14/1933 due to bank holiday.
+ - Closed on 8/15/1945 and 8/16/1945 following victory over Japan.
+ - Closed on Christmas Eve in 1945 and 1946.
+ - Closed on December 26th in 1958.
+ - Closed the day before Memorial Day in 1961.
+ - Closed on 11/25/1963 due to John F. Kennedy's death.
+ - Closed for Lincoln's Birthday in 1968.
+ - Closed a number of days between June 12th and December 24th in 1968
+ due to paperwork crisis.
+ - Closed on 4/9/1968 due to Martin Luther King's death.
+ - Closed the day after Independence Day in 1968.
+ - Closed on 2/10/1969 due to weather (snow).
+ - Closed on 3/31/1969 due to Dwight D. Eisenhower's death.
+ - Closed on 7/21/1969 following the first lunar landing.
+ - Closed on 12/28/1972 due to Harry S. Truman's death.
+ - Closed on 1/25/1973 due to Lyndon B. Johnson's death.
+ - Closed on 7/14/1977 due to New York City blackout.
+ - Closed on 9/27/1985 due to Hurricane Gloria.
+ - Closed on 4/27/1994 due to Richard Nixon's death.
+ - Closed from 9/11/2001 to 9/16/2001 due to terrorist attacks in NYC.
+ - Closed on 6/11/2004 due to Ronald Reagan's death.
+ - Closed on 1/2/2007 due to Gerald Ford's death.
+ - Closed on 10/29/2012 and 10/30/2012 due to Hurricane Sandy.
+ - Closed on 12/5/2018 due to George H.W. Bush's death.
+ - Closed at 1:00 PM on Wednesday, July 3rd, 2013
+ - Closed at 1:00 PM on Friday, December 31, 1999
+ - Closed at 1:00 PM on Friday, December 26, 1997
+ - Closed at 1:00 PM on Friday, December 26, 2003
+
+ NOTE: The exchange was **not** closed early on Friday December 26, 2008,
+ nor was it closed on Friday December 26, 2014. The next Thursday Christmas
+ will be in 2025. If someone is still maintaining this code in 2025, then
+ we've done alright...and we should check if it's a half day.
+ """
+
+ regular_early_close = time(13)
+
+ name = "XNYS"
+
+ tz = ZoneInfo("America/New_York")
+
+ open_times = ((None, time(9, 30)),)
+
+ close_times = ((None, time(16)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ USNewYearsDay,
+ USMartinLutherKingJrAfter1998,
+ USLincolnsBirthDayBefore1954,
+ USWashingtonsBirthDayBefore1964,
+ USWashingtonsBirthDay1964to1970,
+ USPresidentsDay,
+ GoodFriday,
+ USMemorialDayBefore1964,
+ USMemorialDay1964to1969,
+ USMemorialDay,
+ USJuneteenth,
+ USIndependenceDayBefore1954,
+ USIndependenceDay,
+ USLaborDay,
+ USThanksgivingDayBefore1939,
+ USThanksgivingDay1939to1941,
+ USThanksgivingDay,
+ USElectionDay1848to1967,
+ USElectionDay1968to1980,
+ USVeteransDay1934to1953,
+ USColumbusDayBefore1954,
+ ChristmasBefore1954,
+ Christmas,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ November29BacklogRelief,
+ March33BankHoliday,
+ August45VictoryOverJapan,
+ ChristmasEvesAdhoc,
+ DayAfterChristmasAdhoc,
+ DayBeforeDecorationAdhoc,
+ LincolnsBirthDayAdhoc,
+ PaperworkCrisis68,
+ DayAfterIndependenceDayAdhoc,
+ WeatherSnowClosing,
+ FirstLunarLandingClosing,
+ September11Closings,
+ NewYorkCityBlackout77,
+ HurricaneGloriaClosing,
+ HurricaneSandyClosings,
+ USNationalDaysofMourning,
+ )
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [
+ MonTuesThursBeforeIndependenceDay,
+ FridayAfterIndependenceDayPre2013,
+ WednesdayBeforeIndependenceDayPost2013,
+ USBlackFridayInOrAfter1993,
+ ChristmasEveInOrAfter1993,
+ ]
+ ),
+ ),
+ (
+ time(14),
+ HolidayCalendar(
+ [
+ ChristmasEveBefore1993,
+ USBlackFridayBefore1993,
+ ]
+ ),
+ ),
+ ]
+
+ @property
+ def special_closes_adhoc(self):
+ return [
+ (
+ self.regular_early_close,
+ DatetimeIndex(
+ [
+ "1997-12-26",
+ "1999-12-31",
+ "2003-12-26",
+ ]
+ ),
+ )
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xnze.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xnze.py
new file mode 100644
index 0000000000000000000000000000000000000000..100100b205e77d07eafdb15fcadfb079a74bb4ab
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xnze.py
@@ -0,0 +1,242 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Useful source for the history of New Zealand public holidays:
+# Nancy Swarbrick, 'Public holidays', Te Ara - the Encyclopedia of New Zealand
+# http://www.TeAra.govt.nz/en/public-holidays/print (accessed 22 December 2019)
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas import Timestamp
+from pandas.tseries.holiday import (
+ MO,
+ DateOffset,
+ EasterMonday,
+ GoodFriday,
+ Holiday,
+ next_monday,
+ next_monday_or_tuesday,
+ previous_workday,
+ weekend_to_monday,
+)
+
+from .common_holidays import anzac_day, boxing_day, christmas, new_years_day
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+# Prior to 2015, Waitangi Day and Anzac Day are not "Mondayized",
+# that is, if they occur on the weekend, there is no make-up.
+MONDAYIZATION_START_DATE = "2015-01-01"
+
+# Regular Holidays
+# ----------------
+NewYearsDay = new_years_day(observance=next_monday)
+
+DayAfterNewYearsDay = Holiday(
+ "Day after New Year's Day",
+ month=1,
+ day=2,
+ observance=next_monday_or_tuesday,
+)
+
+WaitangiDayNonMondayized = Holiday(
+ "Waitangi Day",
+ month=2,
+ day=6,
+ end_date=MONDAYIZATION_START_DATE,
+)
+
+WaitangiDay = Holiday(
+ "Waitangi Day",
+ month=2,
+ day=6,
+ observance=weekend_to_monday,
+ start_date=MONDAYIZATION_START_DATE,
+)
+
+AnzacDayNonMondayized = anzac_day(end_date=MONDAYIZATION_START_DATE)
+
+AnzacDay = anzac_day(
+ observance=weekend_to_monday,
+ start_date=MONDAYIZATION_START_DATE,
+)
+
+QueensBirthday = Holiday(
+ "Queen's Birthday",
+ month=6,
+ day=1,
+ offset=DateOffset(weekday=MO(1)),
+)
+
+LabourDay = Holiday(
+ "Labour Day",
+ month=10,
+ day=1,
+ offset=DateOffset(weekday=MO(4)),
+)
+
+Christmas = christmas(observance=next_monday)
+
+BoxingDay = boxing_day(observance=next_monday_or_tuesday)
+
+
+# Early Closes
+# ------------
+BusinessDayPriorToChristmasDay = Holiday(
+ "Business Day prior to Christmas Day",
+ month=12,
+ day=25,
+ observance=previous_workday,
+ start_date="2011-01-01",
+)
+
+BusinessDayPriorToNewYearsDay = Holiday(
+ "Business Day prior to New Year's Day",
+ month=1,
+ day=1,
+ observance=previous_workday,
+ start_date="2011-01-01",
+)
+
+# Further ad-hoc holidays and closures sourced from gaps in index series
+XMAS22DEC86 = Timestamp("1986-12-22")
+XMAS23DEC86 = Timestamp("1986-12-23")
+XMAS24DEC86 = Timestamp("1986-12-24")
+XMAS29DEC86 = Timestamp("1986-12-29")
+XMAS30DEC86 = Timestamp("1986-12-30")
+XMAS31DEC86 = Timestamp("1986-12-31")
+XMAS24DEC90 = Timestamp("1990-12-24")
+XMAS31DEC90 = Timestamp("1990-12-31")
+XMAS27DEC91 = Timestamp("1991-12-27")
+NYDX03JAN92 = Timestamp("1992-01-03")
+XMAS31DEC99 = Timestamp("1999-12-31")
+QueenMourning2022 = Timestamp("2022-09-26")
+
+# Matariki Day. Is set by Maori Lunar system which fluctuates relative to Gregorian so no set date each year.
+# https://www.mbie.govt.nz/business-and-employment/employment-and-skills/employment-legislation-reviews/matariki/matariki-public-holiday/
+MatarikiDayDates = {}
+MatarikiDayDates["2022"] = Timestamp("2022-06-24")
+MatarikiDayDates["2023"] = Timestamp("2023-07-14")
+MatarikiDayDates["2024"] = Timestamp("2024-06-28")
+MatarikiDayDates["2025"] = Timestamp("2025-06-20")
+MatarikiDayDates["2026"] = Timestamp("2026-07-10")
+MatarikiDayDates["2027"] = Timestamp("2027-06-25")
+MatarikiDayDates["2028"] = Timestamp("2028-07-14")
+MatarikiDayDates["2029"] = Timestamp("2029-07-06")
+MatarikiDayDates["2030"] = Timestamp("2030-06-21")
+MatarikiDayDates["2031"] = Timestamp("2031-07-11")
+MatarikiDayDates["2032"] = Timestamp("2032-07-02")
+MatarikiDayDates["2033"] = Timestamp("2033-06-24")
+MatarikiDayDates["2034"] = Timestamp("2034-07-07")
+MatarikiDayDates["2035"] = Timestamp("2035-06-29")
+MatarikiDayDates["2036"] = Timestamp("2036-07-21")
+MatarikiDayDates["2037"] = Timestamp("2037-07-10")
+MatarikiDayDates["2038"] = Timestamp("2038-06-25")
+MatarikiDayDates["2039"] = Timestamp("2039-07-15")
+MatarikiDayDates["2040"] = Timestamp("2040-07-06")
+MatarikiDayDates["2041"] = Timestamp("2041-07-19")
+MatarikiDayDates["2042"] = Timestamp("2042-07-11")
+MatarikiDayDates["2043"] = Timestamp("2043-07-03")
+MatarikiDayDates["2044"] = Timestamp("2044-06-24")
+MatarikiDayDates["2045"] = Timestamp("2045-07-07")
+MatarikiDayDates["2046"] = Timestamp("2046-06-29")
+MatarikiDayDates["2047"] = Timestamp("2047-07-19")
+MatarikiDayDates["2048"] = Timestamp("2048-07-03")
+MatarikiDayDates["2049"] = Timestamp("2049-06-25")
+
+
+class XNZEExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the New Zealand Exchange (NZX).
+
+ Open Time: 10:00 AM, NZ
+ Close Time: 4:45 PM, NZ
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Day after New Year's Day
+ - Waitangi Day
+ - Good Friday
+ - Easter Monday
+ - Anzac Day
+ - Queen's Birthday
+ - Labour Day
+ - Christmas
+ - Boxing Day
+
+ Early Closes:
+ - Business Day prior to Christmas Day
+ - Business Day prior to New Year's Day
+ """
+
+ regular_early_close = time(12, 45)
+
+ name = "XNZE"
+
+ tz = ZoneInfo("NZ")
+
+ open_times = ((None, time(10)),)
+
+ close_times = ((None, time(16, 45)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ DayAfterNewYearsDay,
+ WaitangiDayNonMondayized,
+ WaitangiDay,
+ GoodFriday,
+ EasterMonday,
+ AnzacDayNonMondayized,
+ AnzacDay,
+ QueensBirthday,
+ LabourDay,
+ Christmas,
+ BoxingDay,
+ ]
+ )
+
+ # add extra ad-hoc holidays
+ @property
+ def adhoc_holidays(self):
+ dates = [
+ XMAS22DEC86,
+ XMAS23DEC86,
+ XMAS24DEC86,
+ XMAS29DEC86,
+ XMAS30DEC86,
+ XMAS31DEC86,
+ XMAS24DEC90,
+ XMAS31DEC90,
+ XMAS27DEC91,
+ NYDX03JAN92,
+ XMAS31DEC99,
+ QueenMourning2022,
+ ]
+ dates += MatarikiDayDates.values()
+ return dates
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [BusinessDayPriorToChristmasDay, BusinessDayPriorToNewYearsDay]
+ ),
+ )
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xosl.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xosl.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ff2978de04e4dd5d2cf1dce4b5fb8882989ad33
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xosl.py
@@ -0,0 +1,105 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday
+
+from .common_holidays import (
+ ascension_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ holy_wednesday,
+ maundy_thursday,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import WEEKDAYS, HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+HolyWednesday = holy_wednesday(start_date="2011", days_of_week=WEEKDAYS)
+MaundyThursday = maundy_thursday()
+AscensionDay = ascension_day()
+WhitMonday = whit_monday()
+
+LabourDay = european_labour_day()
+
+ConstitutionDay = Holiday("Constitution Day", month=5, day=17)
+
+ChristmasEve = christmas_eve()
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve()
+
+
+class XOSLExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Oslo Stock Exchange in Norway.
+
+ Open Time: 9:00 AM, CET (Central European Time)
+ Close Time: 4:20 PM, CET (Central European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Maundy Thursday
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Ascension Day
+ - Constitution Day
+ - Whit Monday
+ - Christmas Eve
+ - Christmas Day
+ - Boxing Day
+ - New Year's Eve
+
+ Early Closes:
+ - Holy Wednesday
+ """
+
+ name = "XOSL"
+ tz = ZoneInfo("Europe/Oslo")
+ open_times = ((None, time(9)),)
+ close_times = ((None, time(16, 20)),)
+ regular_early_close = time(13)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ MaundyThursday,
+ GoodFriday,
+ EasterMonday,
+ LabourDay,
+ AscensionDay,
+ ConstitutionDay,
+ WhitMonday,
+ ChristmasEve,
+ Christmas,
+ BoxingDay,
+ NewYearsEve,
+ ]
+ )
+
+ @property
+ def special_closes(self):
+ return [(self.regular_early_close, HolidayCalendar([HolyWednesday]))]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xpar.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xpar.py
new file mode 100644
index 0000000000000000000000000000000000000000..8325061fd98f58bceb222045cec20c0ceb07f044
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xpar.py
@@ -0,0 +1,113 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday
+
+from .common_holidays import (
+ boxing_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import WEEKDAYS, HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+WhitMonday = whit_monday(end_date="2002")
+
+LabourDay = european_labour_day()
+
+BastilleDay = Holiday(
+ "Bastille Day",
+ month=7,
+ day=14,
+ end_date="2002",
+)
+
+ChristmasEve = christmas_eve(days_of_week=WEEKDAYS)
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEveBefore2002 = new_years_eve(end_date="2002")
+NewYearsEveInOrAfter2002 = new_years_eve(
+ start_date="2002",
+ days_of_week=WEEKDAYS,
+)
+
+
+class XPARExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Euronext Paris exchange, and the primary calendar for the
+ country of France.
+
+ Open Time: 9:00 AM, CET (Central European Time)
+ Close Time: 5:30 PM, CET (Central European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Christmas Day
+ - Boxing Day
+
+ Early Closes:
+ - Christmas Eve
+ - New Year's Eve
+
+ Other countries on the Euronext:
+ - Belgium
+ - Netherlands
+ - Portugal
+ """
+
+ # Source: https://www.euronext.com/en/calendars-hours
+ regular_early_close = time(14, 5)
+
+ name = "XPAR" # Euronext Paris
+ tz = ZoneInfo("Europe/Paris")
+ open_times = ((None, time(9)),)
+ close_times = ((None, time(17, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ GoodFriday,
+ EasterMonday,
+ WhitMonday,
+ LabourDay,
+ BastilleDay,
+ Christmas,
+ BoxingDay,
+ NewYearsEveBefore2002,
+ ]
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar([ChristmasEve, NewYearsEveInOrAfter2002]),
+ ),
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xphs.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xphs.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c4c9a3473cf697d74049b19f16681c05caf1e34
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xphs.py
@@ -0,0 +1,421 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import datetime
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import MO, DateOffset, GoodFriday, Holiday
+
+from .common_holidays import (
+ all_saints_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ maundy_thursday,
+ new_years_day,
+ new_years_eve,
+)
+from .lunisolar_holidays import chinese_lunar_new_year_dates
+from .exchange_calendar import FRIDAY, HolidayCalendar, ExchangeCalendar
+
+
+def only_friday(dt: datetime.datetime) -> datetime.datetime | None:
+ """
+ Only keeps the holidays that fall on a Friday. Useful
+ for defining holidays that add a Friday to make a 4-day weekend
+ when falling on a Thursday.
+ """
+ return dt if dt.weekday() == FRIDAY else None
+
+
+# All pre-2011 holidays are pre-computed, so we define Holidays starting
+# in 2011.
+NewYearsDay = new_years_day(start_date="2011")
+
+# Chinese New Year's only observed after 2011
+ChineseNewYear = chinese_lunar_new_year_dates
+
+ChineseNewYearAfter2011 = ChineseNewYear[ChineseNewYear.year > 2011]
+
+PeoplePowerRevolution = Holiday(
+ "People Power Revolution",
+ month=2,
+ day=25,
+ start_date="2016",
+)
+
+ArawNgKagitingan = Holiday(
+ "Araw Ng Kagitingan",
+ month=4,
+ day=9,
+ start_date="2011",
+)
+
+MaundyThursday = maundy_thursday(start_date="2011")
+
+LabourDay = european_labour_day(start_date="2011")
+
+IndependenceDay = Holiday(
+ "Independence Day",
+ month=6,
+ day=12,
+ start_date="2011",
+)
+
+NinoyAquinoDay = Holiday(
+ "Ninoy Aquino Day",
+ month=8,
+ day=21,
+ start_date="2011",
+)
+
+NationalHeroesDay = Holiday(
+ "National Heroes Day",
+ month=8,
+ day=31,
+ offset=DateOffset(weekday=MO(-1)),
+ start_date="2011",
+)
+
+AllSaintsDay = all_saints_day(start_date="2011")
+
+AllSaintsDayExtra = Holiday(
+ "Friday after All Saint's Day",
+ month=11,
+ day=2,
+ start_date="2011",
+ observance=only_friday,
+)
+
+BonifacioDay = Holiday(
+ "Bonifacio Day",
+ month=11,
+ day=30,
+ start_date="2011",
+)
+
+ChristmasEve = christmas_eve(start_date="2011")
+
+Christmas = christmas(start_date="2011")
+
+RizalDay = Holiday(
+ "Rizal Day",
+ month=12,
+ day=30,
+ start_date="2011",
+)
+
+NewYearsEve = new_years_eve(start_date="2011")
+
+# These dates were initially calculated using the ummalqura Python
+# package (https://pypi.org/project/ummalqura/), and then tweaked
+# to fit Philippines' observance of Eid al-Fitr. Other countries that
+# observe Eid al-Fitr might use slightly different dates
+philippines_eid_al_fitr = pd.to_datetime(
+ [
+ "2011-08-30",
+ "2012-08-20",
+ "2013-08-09",
+ "2014-07-29",
+ "2015-07-17",
+ "2016-07-06",
+ "2017-06-26",
+ "2018-06-15",
+ "2019-06-05",
+ ]
+)
+
+# These dates were initially calculated using the ummalqura Python
+# package (https://pypi.org/project/ummalqura/), and then tweaked
+# to fit Philippines' observance of Eid al-Adha. Other countries that
+# observe Eid al-Adha might use slightly different dates
+philippines_eid_al_adha = pd.to_datetime(
+ [
+ "2011-11-07",
+ "2012-10-26",
+ "2013-10-15",
+ "2014-10-06",
+ "2015-09-25",
+ "2016-09-12",
+ "2017-09-01",
+ "2018-08-21",
+ "2019-08-12",
+ ]
+)
+
+
+class XPHSExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Philippine Stock Exchange (XPHS).
+
+ Open Time: 9:30 AM, PHT
+ Close Time: 3:30 PM, PHT
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Chinese New Year's Day
+ - Araw Ng Kagitingan (Apr 9)
+ - Maundy Thursday (Thurs before Easter)
+ - Good Friday (Friday before Easter)
+ - Labour Day (May 1)
+ - Eid-ul-Fitr (Islamic Lunar Calendar)
+ - Independence Day (Jun 12)
+ - Eid-al-Adha
+ - Ninoy Aquino Day (Aug 21)
+ - National Heroes' Day (last Monday of August)
+ - All Saint's Day (Nov 1)
+ - Bonifacio Day (Nov 30)
+ - Christmas Eve (Dec 24)
+ - Christmas Day (Dec 25)
+ - Rizal Day (Dec 30)
+ - New Year's Eve (Dec 31)
+
+
+ Early Closes:
+ - None
+ """
+
+ name = "XPHS"
+
+ tz = ZoneInfo("Asia/Manila")
+
+ open_times = ((None, datetime.time(9, 30)),)
+
+ close_times = ((None, datetime.time(15, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ PeoplePowerRevolution,
+ ArawNgKagitingan,
+ MaundyThursday,
+ GoodFriday,
+ LabourDay,
+ IndependenceDay,
+ NinoyAquinoDay,
+ NationalHeroesDay,
+ AllSaintsDay,
+ AllSaintsDayExtra,
+ BonifacioDay,
+ ChristmasEve,
+ Christmas,
+ RizalDay,
+ NewYearsEve,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ misc_adhoc = [
+ "2017-04-28",
+ "2017-10-16",
+ "2015-11-18",
+ "2015-11-19",
+ "2013-08-19",
+ "2013-08-20",
+ "2013-10-28",
+ "2011-06-20",
+ # Election Day
+ "2019-05-13",
+ "2018-05-14",
+ "2016-05-09",
+ "2013-05-13",
+ # Typhoon
+ "2017-09-12",
+ "2014-12-08",
+ "2014-09-19",
+ "2014-07-16",
+ "2012-08-07",
+ "2011-09-27",
+ # Pope's Visit
+ "2015-01-15",
+ "2015-01-16",
+ # Christmas Makeups
+ "2017-12-26",
+ "2016-12-26",
+ "2014-12-26",
+ # New Years Makeups
+ "2018-01-02",
+ "2017-01-02",
+ "2015-01-02",
+ # Other Makeups
+ "2017-10-31", # All Saint's Makeup
+ "2016-10-31", # All Saint's Makeup
+ "2011-10-31", # All Saint's Makeup
+ ]
+
+ # Before 2011, there are a few holidays that follow makeup day
+ # rules that are inconsistent/challenging to model. Starting
+ # in 2011, the rules become much more consistent. For convenience
+ # we are hardcoding pre-2011 holidays and defining holidays in
+ # 2011-present
+ pre_2011_holidays = [
+ "2002-01-01",
+ "2002-02-25",
+ "2002-03-28",
+ "2002-03-29",
+ "2002-04-08",
+ "2002-05-01",
+ "2002-06-12",
+ "2002-07-15",
+ "2002-10-31",
+ "2002-11-01",
+ "2002-12-06",
+ "2002-12-24",
+ "2002-12-25",
+ "2002-12-30",
+ "2002-12-31",
+ "2003-01-01",
+ "2003-02-25",
+ "2003-04-07",
+ "2003-04-17",
+ "2003-04-18",
+ "2003-05-01",
+ "2003-05-02",
+ "2003-06-13",
+ "2003-08-22",
+ "2003-11-26",
+ "2003-12-24",
+ "2003-12-25",
+ "2003-12-26",
+ "2003-12-31",
+ "2004-01-01",
+ "2004-01-02",
+ "2004-02-25",
+ "2004-04-07",
+ "2004-04-08",
+ "2004-04-09",
+ "2004-05-10",
+ "2004-11-01",
+ "2004-11-15",
+ "2004-11-29",
+ "2004-12-03",
+ "2004-12-24",
+ "2004-12-27",
+ "2004-12-30",
+ "2004-12-31",
+ "2005-02-25",
+ "2005-03-23",
+ "2005-03-24",
+ "2005-03-25",
+ "2005-05-02",
+ "2005-06-13",
+ "2005-07-25",
+ "2005-08-29",
+ "2005-10-31",
+ "2005-11-01",
+ "2005-11-04",
+ "2005-11-28",
+ "2005-12-26",
+ "2005-12-30",
+ "2006-04-13",
+ "2006-04-14",
+ "2006-05-01",
+ "2006-06-12",
+ "2006-07-24",
+ "2006-08-21",
+ "2006-09-28",
+ "2006-09-29",
+ "2006-10-24",
+ "2006-11-01",
+ "2006-12-01",
+ "2006-12-25",
+ "2006-12-26",
+ "2007-01-01",
+ "2007-04-05",
+ "2007-04-06",
+ "2007-04-09",
+ "2007-05-01",
+ "2007-05-14",
+ "2007-06-11",
+ "2007-08-20",
+ "2007-08-27",
+ "2007-10-12",
+ "2007-10-29",
+ "2007-11-01",
+ "2007-11-02",
+ "2007-11-30",
+ "2007-12-24",
+ "2007-12-25",
+ "2007-12-31",
+ "2008-01-01",
+ "2008-02-25",
+ "2008-03-20",
+ "2008-03-21",
+ "2008-04-07",
+ "2008-05-01",
+ "2008-06-09",
+ "2008-08-18",
+ "2008-08-25",
+ "2008-10-01",
+ "2008-12-01",
+ "2008-12-25",
+ "2008-12-26",
+ "2008-12-29",
+ "2008-12-30",
+ "2008-12-31",
+ "2009-01-01",
+ "2009-01-02",
+ "2009-04-06",
+ "2009-04-09",
+ "2009-04-10",
+ "2009-05-01",
+ "2009-06-12",
+ "2009-07-17",
+ "2009-08-05",
+ "2009-08-21",
+ "2009-08-31",
+ "2009-09-07",
+ "2009-09-21",
+ "2009-11-02",
+ "2009-11-30",
+ "2009-12-24",
+ "2009-12-25",
+ "2009-12-30",
+ "2009-12-31",
+ "2010-01-01",
+ "2010-04-01",
+ "2010-04-02",
+ "2010-04-09",
+ "2010-05-03",
+ "2010-05-10",
+ "2010-06-14",
+ "2010-06-30",
+ "2010-08-30",
+ "2010-09-10",
+ "2010-10-25",
+ "2010-11-01",
+ "2010-11-16",
+ "2010-11-29",
+ "2010-12-24",
+ "2010-12-27",
+ "2010-12-31",
+ ]
+
+ return list(
+ chain(
+ misc_adhoc,
+ pre_2011_holidays,
+ ChineseNewYearAfter2011,
+ philippines_eid_al_adha,
+ philippines_eid_al_fitr,
+ )
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xpra.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xpra.py
new file mode 100644
index 0000000000000000000000000000000000000000..27027e56b7a473ecd961313ccff89892873cc2f4
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xpra.py
@@ -0,0 +1,154 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import Easter, EasterMonday, Holiday
+from pandas.tseries.offsets import Day
+
+from .common_holidays import (
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ new_years_day,
+ new_years_eve,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+# Need custom start year so can't use pandas GoodFriday
+GoodFriday = Holiday(
+ "Good Friday", month=1, day=1, offset=[Easter(), Day(-2)], start_date="2013"
+)
+
+LabourDay = european_labour_day()
+
+LiberationDay = Holiday(
+ "Liberation Day",
+ month=5,
+ day=8,
+)
+
+SaintsCyrilAndMethodiusDay = Holiday(
+ "Saints Cyril and Methodius Day",
+ month=7,
+ day=5,
+)
+
+JanHusDay = Holiday(
+ "Jan Hus Day",
+ month=7,
+ day=6,
+)
+
+CzechStatehoodDay = Holiday(
+ "Czech Statehood Day",
+ month=9,
+ day=28,
+)
+
+IndependenceDay = Holiday(
+ "Independence Day",
+ month=10,
+ day=28,
+)
+
+StruggleForFreedomAndDemocracyDay = Holiday(
+ "Struggle for Freedom and Democracy Day",
+ month=11,
+ day=17,
+)
+
+ChristmasEve = christmas_eve()
+
+ChristmasDay = christmas()
+
+SecondDayOfChristmas = Holiday(
+ "Second Day of Christmas",
+ month=12,
+ day=26,
+)
+
+ExchangeHoliday = new_years_eve()
+
+
+class XPRAExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Prague Stock Exchange (XPRA).
+
+ Open Time: 9:00 AM, CET
+ Close Time: 4:20 PM, CET
+
+ Regularly-Observed Holidays:
+ - New Years Day
+ - Good Friday
+ - Easter Monday
+ - Labour Day (May 1)
+ - Liberation Day (May 8)
+ - Saints Cyril and Methodius Day (Jul 5)
+ - Jan Hus Day (Jul 6)
+ - Czech Statehood Day (Sep 28)
+ - Independence Day (Oct 28)
+ - Struggle for Freedom and Democracy Day (Nov 17)
+ - Christmas Eve
+ - Christmas Day
+ - Second Day of Christmas (Dec 26)
+ - Exchange Holiday (Dec 31)
+
+ Early Closes:
+ - None
+ """
+
+ name = "XPRA"
+
+ tz = ZoneInfo("Europe/Prague")
+
+ open_times = ((None, time(9)),)
+
+ close_times = ((None, time(16, 20)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ GoodFriday,
+ EasterMonday,
+ LabourDay,
+ LiberationDay,
+ SaintsCyrilAndMethodiusDay,
+ JanHusDay,
+ CzechStatehoodDay,
+ IndependenceDay,
+ StruggleForFreedomAndDemocracyDay,
+ ChristmasEve,
+ ChristmasDay,
+ SecondDayOfChristmas,
+ ExchangeHoliday,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [
+ # Extreme Flooding
+ pd.Timestamp("2002-08-14"),
+ # Restoration of the Czech Independence Day
+ pd.Timestamp("2004-01-02"),
+ pd.Timestamp("2005-01-03"),
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xsau.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xsau.py
new file mode 100644
index 0000000000000000000000000000000000000000..9df30eabd38f9846611fb03dc37520136e478634
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xsau.py
@@ -0,0 +1,114 @@
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import Holiday
+
+from exchange_calendars.exchange_calendar import ExchangeCalendar, HolidayCalendar
+
+SaudiFoundingDay = Holiday("Saudi Founding Day", month=2, day=22)
+
+NationalDayOfSaudiArabia = Holiday("National Day of Saudi Arabia", month=9, day=23)
+
+EidAlAdhaHoliday = pd.to_datetime(
+ [
+ "2023-06-27",
+ "2023-06-28",
+ "2023-06-29",
+ "2023-06-30",
+ "2023-07-01",
+ "2023-07-02",
+ "2022-07-07",
+ "2022-07-08",
+ "2022-07-09",
+ "2022-07-10",
+ "2022-07-11",
+ "2022-07-12",
+ "2022-07-13",
+ "2021-07-16",
+ "2021-07-17",
+ "2021-07-18",
+ "2021-07-19",
+ "2021-07-20",
+ "2021-07-21",
+ "2021-07-22",
+ ]
+)
+
+EidAlFiterHoliday = pd.to_datetime(
+ [
+ "2023-04-18",
+ "2023-04-19",
+ "2023-04-20",
+ "2023-04-21",
+ "2023-04-22",
+ "2023-04-23",
+ "2023-04-24",
+ "2023-04-25",
+ "2022-04-28",
+ "2022-04-29",
+ "2022-04-30",
+ "2022-05-01",
+ "2022-05-02",
+ "2022-05-03",
+ "2022-05-04",
+ "2022-05-05",
+ "2022-05-06",
+ "2022-05-07",
+ "2022-05-08",
+ "2021-05-13",
+ "2021-05-14",
+ "2021-05-15",
+ "2021-05-16",
+ ]
+)
+
+
+class XSAUExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Saudi Exchange (XSAU)
+ Available here: https://www.saudiexchange.sa/wps/portal/saudiexchange/rules-guidance/capital-market-overview/trading-cycle-and-times
+ """
+
+ name = "XSAU"
+
+ tz = ZoneInfo("Asia/Riyadh")
+
+ open_times = ((None, time(10)),)
+
+ close_times = ((None, time(15)),)
+
+ @classmethod
+ def bound_min(cls) -> pd.Timestamp:
+ return pd.Timestamp("2021-01-01")
+
+ def _bound_min_error_msg(self, start: pd.Timestamp) -> str:
+ msg = super()._bound_min_error_msg(start)
+ return (
+ msg
+ + f"(The exchange {self.name} does not have complete holidays prior to 2021.)"
+ )
+
+ @classmethod
+ def bound_max(cls) -> pd.Timestamp:
+ return pd.Timestamp("2023-12-31")
+
+ def _bound_max_error_msg(self, end: pd.Timestamp) -> str:
+ msg = super()._bound_min_error_msg(end)
+ return (
+ msg
+ + f"(The exchange {self.name} does not have complete holidays beyond 2023.)"
+ )
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar([SaudiFoundingDay, NationalDayOfSaudiArabia])
+
+ @property
+ def weekmask(self):
+ return "1111001"
+
+ @property
+ def adhoc_holidays(self):
+ return list(chain(EidAlAdhaHoliday, EidAlFiterHoliday))
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xses.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xses.py
new file mode 100644
index 0000000000000000000000000000000000000000..4753a622163c41faa4cbab96ebdaf671affb3e3c
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xses.py
@@ -0,0 +1,431 @@
+from datetime import time
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+
+from .precomputed_exchange_calendar import PrecomputedExchangeCalendar
+
+precomputed_ses_holidays = pd.to_datetime(
+ [
+ "1986-01-01",
+ "1986-02-10",
+ "1986-02-11",
+ "1986-03-28",
+ "1986-05-01",
+ "1986-05-23",
+ "1986-06-09",
+ "1986-12-25",
+ "1987-01-01",
+ "1987-01-29",
+ "1987-01-30",
+ "1987-05-01",
+ "1987-05-12",
+ "1987-05-29",
+ "1987-08-05",
+ "1987-08-10",
+ "1987-10-21",
+ "1987-12-25",
+ "1988-01-01",
+ "1988-02-17",
+ "1988-02-18",
+ "1988-04-01",
+ "1988-05-02",
+ "1988-05-17",
+ "1988-05-30",
+ "1988-07-25",
+ "1988-08-09",
+ "1988-11-08",
+ "1988-12-26",
+ "1989-01-02",
+ "1989-02-06",
+ "1989-02-07",
+ "1989-03-24",
+ "1989-05-01",
+ "1989-05-08",
+ "1989-05-19",
+ "1989-07-13",
+ "1989-08-09",
+ "1989-12-25",
+ "1990-01-01",
+ "1990-04-13",
+ "1990-04-26",
+ "1990-05-01",
+ "1990-05-09",
+ "1990-07-03",
+ "1990-08-09",
+ "1990-12-25",
+ "1991-01-01",
+ "1991-01-15",
+ "1991-03-29",
+ "1991-04-16",
+ "1991-05-01",
+ "1991-05-28",
+ "1991-06-24",
+ "1991-08-09",
+ "1991-11-05",
+ "1991-12-24",
+ "1991-12-25",
+ "1991-12-31",
+ "1992-01-01",
+ "1992-02-04",
+ "1992-02-05",
+ "1992-04-06",
+ "1992-04-17",
+ "1992-05-01",
+ "1992-06-11",
+ "1992-08-10",
+ "1992-12-25",
+ "1993-01-01",
+ "1993-01-25",
+ "1993-03-25",
+ "1993-04-09",
+ "1993-05-06",
+ "1993-06-01",
+ "1993-08-09",
+ "1994-01-10",
+ "1994-01-11",
+ "1994-02-01",
+ "1994-02-11",
+ "1994-03-14",
+ "1994-04-01",
+ "1994-05-02",
+ "1994-05-25",
+ "1994-08-09",
+ "1994-10-13",
+ "1994-11-02",
+ "1994-12-26",
+ "1995-01-02",
+ "1995-01-31",
+ "1995-02-01",
+ "1995-03-03",
+ "1995-04-14",
+ "1995-05-01",
+ "1995-05-10",
+ "1995-05-15",
+ "1995-08-09",
+ "1995-10-23",
+ "1995-12-25",
+ "1996-01-01",
+ "1996-02-19",
+ "1996-02-20",
+ "1996-02-21",
+ "1996-04-05",
+ "1996-05-01",
+ "1996-05-31",
+ "1996-08-09",
+ "1996-12-25",
+ "1997-01-01",
+ "1997-02-07",
+ "1997-02-10",
+ "1997-03-28",
+ "1997-04-18",
+ "1997-05-01",
+ "1997-05-21",
+ "1997-12-25",
+ "1998-01-01",
+ "1998-01-28",
+ "1998-01-29",
+ "1998-01-30",
+ "1998-04-07",
+ "1998-04-10",
+ "1998-05-01",
+ "1998-05-11",
+ "1998-08-10",
+ "1998-10-19",
+ "1998-12-25",
+ "1999-01-01",
+ "1999-01-19",
+ "1999-02-16",
+ "1999-02-17",
+ "1999-03-29",
+ "1999-04-02",
+ "1999-08-09",
+ "1999-11-08",
+ "1999-12-31",
+ "2000-02-07",
+ "2000-03-16",
+ "2000-04-21",
+ "2000-05-01",
+ "2000-05-18",
+ "2000-08-09",
+ "2000-10-26",
+ "2000-12-25",
+ "2000-12-27",
+ "2001-01-01",
+ "2001-01-24",
+ "2001-01-25",
+ "2001-03-06",
+ "2001-04-13",
+ "2001-05-01",
+ "2001-05-07",
+ "2001-08-09",
+ "2001-11-14",
+ "2001-12-17",
+ "2001-12-25",
+ "2002-01-01",
+ "2002-02-12",
+ "2002-02-13",
+ "2002-03-29",
+ "2002-05-01",
+ "2002-05-27",
+ "2002-08-09",
+ "2002-11-04",
+ "2002-12-06",
+ "2002-12-25",
+ "2003-01-01",
+ "2003-02-03",
+ "2003-02-12",
+ "2003-04-18",
+ "2003-05-01",
+ "2003-05-15",
+ "2003-10-24",
+ "2003-11-25",
+ "2003-12-25",
+ "2004-01-01",
+ "2004-01-22",
+ "2004-01-23",
+ "2004-02-02",
+ "2004-04-09",
+ "2004-06-02",
+ "2004-08-09",
+ "2004-11-11",
+ "2004-11-15",
+ "2005-01-21",
+ "2005-02-09",
+ "2005-02-10",
+ "2005-03-25",
+ "2005-05-02",
+ "2005-05-23",
+ "2005-08-09",
+ "2005-11-01",
+ "2005-11-03",
+ "2005-12-26",
+ "2006-01-02",
+ "2006-01-10",
+ "2006-01-30",
+ "2006-01-31",
+ "2006-04-14",
+ "2006-05-01",
+ "2006-05-12",
+ "2006-08-09",
+ "2006-10-24",
+ "2006-12-25",
+ "2007-01-01",
+ "2007-01-02",
+ "2007-02-19",
+ "2007-02-20",
+ "2007-04-06",
+ "2007-05-01",
+ "2007-05-31",
+ "2007-08-09",
+ "2007-11-08",
+ "2007-12-20",
+ "2007-12-25",
+ "2008-01-01",
+ "2008-02-07",
+ "2008-02-08",
+ "2008-03-21",
+ "2008-05-01",
+ "2008-05-19",
+ "2008-10-01",
+ "2008-10-27",
+ "2008-12-08",
+ "2008-12-25",
+ "2009-01-01",
+ "2009-01-26",
+ "2009-01-27",
+ "2009-04-10",
+ "2009-05-01",
+ "2009-08-10",
+ "2009-09-21",
+ "2009-11-27",
+ "2009-12-25",
+ "2010-01-01",
+ "2010-02-15",
+ "2010-02-16",
+ "2010-04-02",
+ "2010-05-28",
+ "2010-08-09",
+ "2010-09-10",
+ "2010-11-05",
+ "2010-11-17",
+ "2011-02-03",
+ "2011-02-04",
+ "2011-04-22",
+ "2011-05-02",
+ "2011-05-17",
+ "2011-08-09",
+ "2011-08-30",
+ "2011-10-26",
+ "2011-11-07",
+ "2011-12-26",
+ "2012-01-02",
+ "2012-01-23",
+ "2012-01-24",
+ "2012-04-06",
+ "2012-05-01",
+ "2012-08-09",
+ "2012-08-20",
+ "2012-10-26",
+ "2012-11-13",
+ "2012-12-25",
+ "2013-01-01",
+ "2013-02-11",
+ "2013-02-12",
+ "2013-03-29",
+ "2013-05-01",
+ "2013-05-24",
+ "2013-08-08",
+ "2013-08-09",
+ "2013-10-15",
+ "2013-12-25",
+ "2014-01-01",
+ "2014-01-31",
+ "2014-04-18",
+ "2014-05-01",
+ "2014-05-13",
+ "2014-07-28",
+ "2014-10-06",
+ "2014-10-22",
+ "2014-12-25",
+ "2015-01-01",
+ "2015-02-19",
+ "2015-02-20",
+ "2015-04-03",
+ "2015-05-01",
+ "2015-06-01",
+ "2015-07-17",
+ "2015-08-07",
+ "2015-08-10",
+ "2015-09-11",
+ "2015-09-24",
+ "2015-11-10",
+ "2015-12-25",
+ "2016-01-01",
+ "2016-02-08",
+ "2016-02-09",
+ "2016-03-25",
+ "2016-05-02",
+ "2016-07-06",
+ "2016-08-09",
+ "2016-09-12",
+ "2016-12-26",
+ "2017-01-02",
+ "2017-01-30",
+ "2017-04-14",
+ "2017-05-01",
+ "2017-05-10",
+ "2017-06-26",
+ "2017-08-09",
+ "2017-09-01",
+ "2017-10-18",
+ "2017-12-25",
+ "2018-01-01",
+ "2018-02-16",
+ "2018-03-30",
+ "2018-05-01",
+ "2018-05-29",
+ "2018-06-15",
+ "2018-08-09",
+ "2018-08-22",
+ "2018-11-06",
+ "2018-12-25",
+ "2019-01-01",
+ "2019-02-05",
+ "2019-02-06",
+ "2019-04-19",
+ "2019-05-01",
+ "2019-05-20",
+ "2019-06-05",
+ "2019-08-09",
+ "2019-08-12",
+ "2019-10-28",
+ "2019-12-25",
+ "2020-01-01",
+ "2020-01-27",
+ "2020-04-10",
+ "2020-05-01",
+ "2020-05-07",
+ "2020-05-25",
+ "2020-07-10",
+ "2020-07-31",
+ "2020-08-10",
+ "2020-12-25",
+ "2021-01-01", # New Year's Day
+ "2021-02-12", # Chinese New Year TODO: 2021-02-11 is half day
+ "2021-02-13", # Chinese New Year
+ "2021-04-02", # Good Friday
+ "2021-05-01", # Labour Day
+ "2021-05-13", # Hari Raya Puasa
+ "2021-05-26", # Vesak Day
+ "2021-07-20", # Hari Raya Haji
+ "2021-08-09", # National Day
+ "2021-11-04", # Deepavali
+ "2021-12-25", # Christmas Day. TODO: 2021-12-24 and 2021-12-31 are half days
+ # TODO: Eve of Chinese New Year (2022-01-31) is a half day
+ "2022-02-01", # Chinese New Year
+ "2022-02-02", # Chinese New Year
+ "2022-04-15", # Good Friday
+ "2022-05-02", # Labour Day (in lieu)
+ "2022-05-03", # Hari Raya Puasa
+ "2022-05-16", # Vesak Day (in lieu)
+ "2022-07-11", # Hari Raya Haji (in lieu)
+ "2022-08-09", # National Day
+ "2022-10-24", # Deepavali
+ "2022-12-26", # Christmas Day (in lieu)
+ "2023-01-02", # New Year's Day (in lieu)
+ "2023-01-23", # Chinese New Year
+ "2023-01-24", # Chinese New Year
+ "2023-04-07", # Good Friday
+ # Hari Raya Puasa is on 2023-04-22 (Saturday), and not rolled forward
+ "2023-05-01", # Labour Day
+ "2023-06-02", # Vesak Day
+ "2023-06-29", # Hari Raya Haji
+ "2023-08-09", # National Day
+ "2023-09-01", # Polling Day
+ "2023-11-13", # Deepavali (in lieu)
+ "2023-12-25", # Christmas Day
+ "2024-01-01", # New Year's Day
+ "2024-02-12", # Chinese New Year (in lieu)
+ "2024-03-29", # Good Friday
+ "2024-04-10", # Hari Raya Puasa
+ "2024-05-01", # Labour Day
+ "2024-05-22", # Vesak Day
+ "2024-06-17", # Hari Raya Haji
+ "2024-08-09", # National Day
+ "2024-10-31", # Deepavali
+ "2024-12-25", # Christmas Day
+ ]
+)
+
+
+class XSESExchangeCalendar(PrecomputedExchangeCalendar):
+ """
+ Exchange calendar for the Singapore Stock Exchange (XSES, SGX).
+
+ Open time: 9:00 Asia/Singapore
+ Close time: 17:00 Asia/Singapore
+
+ NOTE: For now, we are skipping the intra-day break from 12:00 to 13:00.
+
+ Due to the complexity around the Singaporean holidays, we are hardcoding
+ a list of holidays covering 1986-2021, inclusive.
+
+ TODO: There are a handful of half-days (day before Chinese New Year,
+ Christmas Eve, etc.). We will add those later.
+
+ References
+ ----------
+ Accessed 2021-06-11 for 2021 holidays:
+ https://www.sgx.com/securities/trading#Trading%20Hours%20&%20Opening/Closing%20Routine
+ https://www.mom.gov.sg/employment-practices/public-holidays
+ """
+
+ name = "XSES"
+ tz = ZoneInfo("Asia/Singapore")
+ open_times = ((None, time(9)),)
+ close_times = ((None, time(17, 0)),)
+
+ @classmethod
+ def precomputed_holidays(cls):
+ return precomputed_ses_holidays
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xsgo.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xsgo.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6e236ec8763f39a034511893d1ff04f5820c8b3
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xsgo.py
@@ -0,0 +1,278 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import datetime
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import Easter, GoodFriday, Holiday
+from pandas.tseries.offsets import Day
+
+from .common_holidays import (
+ all_saints_day,
+ assumption_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ immaculate_conception,
+ maundy_thursday,
+ new_years_day,
+ new_years_eve,
+ saint_peter_and_saint_paul_day,
+)
+from .exchange_calendar import (
+ FRIDAY,
+ MONDAY,
+ THURSDAY,
+ TUESDAY,
+ WEDNESDAY,
+ WEEKDAYS,
+ HolidayCalendar,
+ ExchangeCalendar,
+)
+
+
+def nearest_monday(dt: datetime.datetime) -> datetime.datetime:
+ """
+ If the holiday falls on a Saturday, Sunday or Monday then the date is
+ unchanged (Sat/Sun observances are not made up), otherwise use the closest
+ Monday to the date.
+ """
+ day = dt.weekday()
+
+ if day in (TUESDAY, WEDNESDAY, THURSDAY):
+ return dt - datetime.timedelta(day - MONDAY)
+ elif day == FRIDAY:
+ return dt + datetime.timedelta(3)
+ return dt
+
+
+def tuesday_and_wednesday_to_friday(dt: datetime.datetime):
+ """
+ If Evangelical Church Day (Halloween) falls on a Tuesday, it is observed
+ the preceding Friday. If it falls on a Wednesday, it is observed the next
+ Friday. If it falls on Thu, Fri, Sat, Sun, or Mon the date is unchanged.
+ """
+ day = dt.weekday()
+
+ if day == TUESDAY:
+ return dt - datetime.timedelta(4)
+ elif day == WEDNESDAY:
+ return dt + datetime.timedelta(2)
+ return dt
+
+
+def not_2010(dt: datetime.datetime) -> datetime.datetime | None:
+ """
+ In 2010 Independence Day fell on a Saturday. Normally this would mean that
+ Friday is a half day, but instead it is a full day off, so we need to
+ exclude it from the usual half day rules.
+ """
+ return None if dt.year == 2010 else dt
+
+
+NewYearsDay = new_years_day()
+
+MaundyThursday = maundy_thursday()
+MondayPriorToCorpusChristi = Holiday(
+ "Monday Prior to Corpus Christi",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(57)],
+ end_date="2008",
+)
+
+LabourDay = european_labour_day()
+
+NavyDay = Holiday("Navy Day", month=5, day=21)
+
+SaintPeterAndSaintPaulDay = saint_peter_and_saint_paul_day(
+ observance=nearest_monday,
+)
+
+OurLadyOfMountCarmelDay = Holiday(
+ "Our Lady of Mount Carmel's Day",
+ month=7,
+ day=16,
+ start_date="2008",
+)
+
+AssumptionDay = assumption_day()
+
+PublicHolidayMonday = Holiday(
+ "Public Holiday Preceeding a Tuesday Independence Day",
+ month=9,
+ day=17,
+ start_date="2003",
+ days_of_week=(MONDAY,),
+)
+DayBeforeIndependenceDay = Holiday(
+ "Day Before Independence Day",
+ month=9,
+ day=17,
+ observance=not_2010,
+ days_of_week=(TUESDAY, WEDNESDAY, THURSDAY, FRIDAY),
+)
+IndependenceDay = Holiday("Independence Day", month=9, day=18)
+ArmyDay = Holiday("Army Day", month=9, day=19)
+PublicHolidayFriday = Holiday(
+ "Public Holiday Following a Thursday Army Day",
+ month=9,
+ day=20,
+ start_date="2003",
+ days_of_week=(FRIDAY,),
+)
+
+DiaDeLaRaza = Holiday(
+ "Dia de la Raza",
+ month=10,
+ day=12,
+ observance=nearest_monday,
+)
+
+EvangelicalChurchDay = Holiday(
+ "Evangelical Church Day",
+ month=10,
+ day=31,
+ observance=tuesday_and_wednesday_to_friday,
+ start_date="2008",
+)
+AllSaintsDay = all_saints_day()
+
+ImmaculateConception = immaculate_conception()
+
+ChristmasEve = christmas_eve(days_of_week=WEEKDAYS)
+Christmas = christmas()
+
+DayBeforeBankHoliday = Holiday(
+ "Day Before Bank Holiday",
+ month=12,
+ day=30,
+ days_of_week=WEEKDAYS,
+)
+BankHoliday = new_years_eve()
+
+
+class XSGOExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Santiago Stock Exchange (Bolsa de Comercio de Santiago) in
+ Chile.
+
+ Open Time: 9:30 AM, CLT/CLST (Chile Standard Time/Chile Summer Time)
+ Close Time: 4:00 PM, CLT (March to October)
+ 5:00 PM, CLST (November to February)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Good Friday
+ - Corpus Christi (until 2007, inclusive)
+ - Labour Day
+ - Navy Day
+ - Saint Peter and Saint Paul Day
+ - Feast Day of Our Lady of Mount Carmel (starting 2008)
+ - Assumption Day
+ - Independence Day
+ - Army Day
+ - Dia de la Raza
+ - Evangelical Church Day
+ - All Saints' Day
+ - Immaculate Conception
+ - Christmas Day
+ - Bank Holiday
+
+ Holidays No Longer Observed:
+ - N/A
+
+ Early Closes:
+ - Maundy Thursday
+ - Day before Independence Day
+ - Christmas Eve
+ - Day before Bank Holiday
+ """
+
+ name = "XSGO"
+ tz = ZoneInfo("America/Santiago")
+
+ open_times = ((None, datetime.time(9, 30)),)
+ early_close_1230 = datetime.time(12, 30)
+ early_close_130 = datetime.time(13, 30)
+
+ @property
+ def close_times(self):
+ # The equity market close time changes twice per year. In March it
+ # changes to 4:00PM for winter and in November it changes to 5PM for
+ # summer.
+ return tuple(self._starting_dates_and_close_times())
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ GoodFriday,
+ MondayPriorToCorpusChristi,
+ LabourDay,
+ NavyDay,
+ SaintPeterAndSaintPaulDay,
+ OurLadyOfMountCarmelDay,
+ AssumptionDay,
+ PublicHolidayMonday,
+ IndependenceDay,
+ ArmyDay,
+ PublicHolidayFriday,
+ DiaDeLaRaza,
+ EvangelicalChurchDay,
+ AllSaintsDay,
+ ImmaculateConception,
+ Christmas,
+ BankHoliday,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [
+ # Bicentennial Celebration.
+ pd.Timestamp("2010-09-17"),
+ pd.Timestamp("2010-09-20"),
+ # New Year's Day Observed. It is unclear why this happened only for
+ # this one year.
+ pd.Timestamp("2017-01-02"),
+ # Census Day.
+ pd.Timestamp("2017-04-19"),
+ # Pope Visit.
+ pd.Timestamp("2018-01-16"),
+ ]
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.early_close_1230,
+ HolidayCalendar([ChristmasEve, DayBeforeBankHoliday]),
+ ),
+ (
+ self.early_close_130,
+ HolidayCalendar([MaundyThursday, DayBeforeIndependenceDay]),
+ ),
+ ]
+
+ def _starting_dates_and_close_times(self):
+ yield ((None, datetime.time(17)))
+ for year in range(1980, 2050):
+ yield (pd.Timestamp("{}-03-01".format(year)), datetime.time(16))
+ yield (pd.Timestamp("{}-11-01".format(year)), datetime.time(17))
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xshg.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xshg.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6f7e877998a6fdf33d1928a246cdf601dd94156
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xshg.py
@@ -0,0 +1,619 @@
+from datetime import time
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+
+from .precomputed_exchange_calendar import PrecomputedExchangeCalendar
+
+precomputed_shanghai_holidays = pd.to_datetime(
+ [
+ "1991-01-01",
+ "1991-02-15",
+ "1991-02-18",
+ "1991-05-01",
+ "1991-10-01",
+ "1991-10-02",
+ "1992-01-01",
+ "1992-02-04",
+ "1992-02-05",
+ "1992-02-06",
+ "1992-05-01",
+ "1992-10-01",
+ "1992-10-02",
+ "1993-01-01",
+ "1993-01-25",
+ "1993-01-26",
+ "1993-10-01",
+ "1994-02-07",
+ "1994-02-08",
+ "1994-02-09",
+ "1994-02-10",
+ "1994-02-11",
+ "1994-05-02",
+ "1994-10-03",
+ "1994-10-04",
+ "1995-01-02",
+ "1995-01-30",
+ "1995-01-31",
+ "1995-02-01",
+ "1995-02-02",
+ "1995-02-03",
+ "1995-05-01",
+ "1995-10-02",
+ "1995-10-03",
+ "1996-01-01",
+ "1996-02-19",
+ "1996-02-20",
+ "1996-02-21",
+ "1996-02-22",
+ "1996-02-23",
+ "1996-02-26",
+ "1996-02-27",
+ "1996-02-28",
+ "1996-02-29",
+ "1996-03-01",
+ "1996-05-01",
+ "1996-09-30",
+ "1996-10-01",
+ "1996-10-02",
+ "1997-01-01",
+ "1997-02-03",
+ "1997-02-04",
+ "1997-02-05",
+ "1997-02-06",
+ "1997-02-07",
+ "1997-02-10",
+ "1997-02-11",
+ "1997-02-12",
+ "1997-02-13",
+ "1997-02-14",
+ "1997-05-01",
+ "1997-05-02",
+ "1997-06-30",
+ "1997-07-01",
+ "1997-10-01",
+ "1997-10-02",
+ "1997-10-03",
+ "1998-01-01",
+ "1998-01-02",
+ "1998-01-26",
+ "1998-01-27",
+ "1998-01-28",
+ "1998-01-29",
+ "1998-01-30",
+ "1998-02-02",
+ "1998-02-03",
+ "1998-02-04",
+ "1998-02-05",
+ "1998-02-06",
+ "1998-05-01",
+ "1998-10-01",
+ "1998-10-02",
+ "1999-01-01",
+ "1999-02-10",
+ "1999-02-11",
+ "1999-02-12",
+ "1999-02-15",
+ "1999-02-16",
+ "1999-02-17",
+ "1999-02-18",
+ "1999-02-19",
+ "1999-02-22",
+ "1999-02-23",
+ "1999-02-24",
+ "1999-02-25",
+ "1999-02-26",
+ "1999-05-03",
+ "1999-10-01",
+ "1999-10-04",
+ "1999-10-05",
+ "1999-10-06",
+ "1999-10-07",
+ "1999-12-20",
+ "1999-12-31",
+ "2000-01-03",
+ "2000-01-31",
+ "2000-02-01",
+ "2000-02-02",
+ "2000-02-03",
+ "2000-02-04",
+ "2000-02-07",
+ "2000-02-08",
+ "2000-02-09",
+ "2000-02-10",
+ "2000-02-11",
+ "2000-05-01",
+ "2000-05-02",
+ "2000-05-03",
+ "2000-05-04",
+ "2000-05-05",
+ "2000-10-02",
+ "2000-10-03",
+ "2000-10-04",
+ "2000-10-05",
+ "2000-10-06",
+ "2001-01-01",
+ "2001-01-22",
+ "2001-01-23",
+ "2001-01-24",
+ "2001-01-25",
+ "2001-01-26",
+ "2001-01-29",
+ "2001-01-30",
+ "2001-01-31",
+ "2001-02-01",
+ "2001-02-02",
+ "2001-05-01",
+ "2001-05-02",
+ "2001-05-03",
+ "2001-05-04",
+ "2001-05-07",
+ "2001-10-01",
+ "2001-10-02",
+ "2001-10-03",
+ "2001-10-04",
+ "2001-10-05",
+ "2002-01-01",
+ "2002-01-02",
+ "2002-01-03",
+ "2002-02-11",
+ "2002-02-12",
+ "2002-02-13",
+ "2002-02-14",
+ "2002-02-15",
+ "2002-02-18",
+ "2002-02-19",
+ "2002-02-20",
+ "2002-02-21",
+ "2002-02-22",
+ "2002-05-01",
+ "2002-05-02",
+ "2002-05-03",
+ "2002-05-06",
+ "2002-05-07",
+ "2002-09-30",
+ "2002-10-01",
+ "2002-10-02",
+ "2002-10-03",
+ "2002-10-04",
+ "2002-10-07",
+ "2003-01-01",
+ "2003-01-30",
+ "2003-01-31",
+ "2003-02-03",
+ "2003-02-04",
+ "2003-02-05",
+ "2003-02-06",
+ "2003-02-07",
+ "2003-05-01",
+ "2003-05-02",
+ "2003-05-05",
+ "2003-05-06",
+ "2003-05-07",
+ "2003-05-08",
+ "2003-05-09",
+ "2003-10-01",
+ "2003-10-02",
+ "2003-10-03",
+ "2003-10-06",
+ "2003-10-07",
+ "2004-01-01",
+ "2004-01-19",
+ "2004-01-20",
+ "2004-01-21",
+ "2004-01-22",
+ "2004-01-23",
+ "2004-01-26",
+ "2004-01-27",
+ "2004-01-28",
+ "2004-05-03",
+ "2004-05-04",
+ "2004-05-05",
+ "2004-05-06",
+ "2004-05-07",
+ "2004-10-01",
+ "2004-10-04",
+ "2004-10-05",
+ "2004-10-06",
+ "2004-10-07",
+ "2005-01-03",
+ "2005-02-07",
+ "2005-02-08",
+ "2005-02-09",
+ "2005-02-10",
+ "2005-02-11",
+ "2005-02-14",
+ "2005-02-15",
+ "2005-05-02",
+ "2005-05-03",
+ "2005-05-04",
+ "2005-05-05",
+ "2005-05-06",
+ "2005-10-03",
+ "2005-10-04",
+ "2005-10-05",
+ "2005-10-06",
+ "2005-10-07",
+ "2006-01-02",
+ "2006-01-03",
+ "2006-01-26",
+ "2006-01-27",
+ "2006-01-30",
+ "2006-01-31",
+ "2006-02-01",
+ "2006-02-02",
+ "2006-02-03",
+ "2006-05-01",
+ "2006-05-02",
+ "2006-05-03",
+ "2006-05-04",
+ "2006-05-05",
+ "2006-10-02",
+ "2006-10-03",
+ "2006-10-04",
+ "2006-10-05",
+ "2006-10-06",
+ "2007-01-01",
+ "2007-01-02",
+ "2007-01-03",
+ "2007-02-19",
+ "2007-02-20",
+ "2007-02-21",
+ "2007-02-22",
+ "2007-02-23",
+ "2007-05-01",
+ "2007-05-02",
+ "2007-05-03",
+ "2007-05-04",
+ "2007-05-07",
+ "2007-10-01",
+ "2007-10-02",
+ "2007-10-03",
+ "2007-10-04",
+ "2007-10-05",
+ "2007-12-31",
+ "2008-01-01",
+ "2008-02-06",
+ "2008-02-07",
+ "2008-02-08",
+ "2008-02-11",
+ "2008-02-12",
+ "2008-04-04",
+ "2008-05-01",
+ "2008-05-02",
+ "2008-06-09",
+ "2008-09-15",
+ "2008-09-29",
+ "2008-09-30",
+ "2008-10-01",
+ "2008-10-02",
+ "2008-10-03",
+ "2009-01-01",
+ "2009-01-02",
+ "2009-01-26",
+ "2009-01-27",
+ "2009-01-28",
+ "2009-01-29",
+ "2009-01-30",
+ "2009-04-06",
+ "2009-05-01",
+ "2009-05-28",
+ "2009-05-29",
+ "2009-10-01",
+ "2009-10-02",
+ "2009-10-05",
+ "2009-10-06",
+ "2009-10-07",
+ "2009-10-08",
+ "2010-01-01",
+ "2010-02-15",
+ "2010-02-16",
+ "2010-02-17",
+ "2010-02-18",
+ "2010-02-19",
+ "2010-04-05",
+ "2010-05-03",
+ "2010-06-14",
+ "2010-06-15",
+ "2010-06-16",
+ "2010-09-22",
+ "2010-09-23",
+ "2010-09-24",
+ "2010-10-01",
+ "2010-10-04",
+ "2010-10-05",
+ "2010-10-06",
+ "2010-10-07",
+ "2011-01-03",
+ "2011-02-02",
+ "2011-02-03",
+ "2011-02-04",
+ "2011-02-07",
+ "2011-02-08",
+ "2011-04-04",
+ "2011-04-05",
+ "2011-05-02",
+ "2011-06-06",
+ "2011-09-12",
+ "2011-10-03",
+ "2011-10-04",
+ "2011-10-05",
+ "2011-10-06",
+ "2011-10-07",
+ "2012-01-02",
+ "2012-01-03",
+ "2012-01-23",
+ "2012-01-24",
+ "2012-01-25",
+ "2012-01-26",
+ "2012-01-27",
+ "2012-04-02",
+ "2012-04-03",
+ "2012-04-04",
+ "2012-04-30",
+ "2012-05-01",
+ "2012-06-22",
+ "2012-10-01",
+ "2012-10-02",
+ "2012-10-03",
+ "2012-10-04",
+ "2012-10-05",
+ "2013-01-01",
+ "2013-01-02",
+ "2013-01-03",
+ "2013-02-11",
+ "2013-02-12",
+ "2013-02-13",
+ "2013-02-14",
+ "2013-02-15",
+ "2013-04-04",
+ "2013-04-05",
+ "2013-04-29",
+ "2013-04-30",
+ "2013-05-01",
+ "2013-06-10",
+ "2013-06-11",
+ "2013-06-12",
+ "2013-09-19",
+ "2013-09-20",
+ "2013-10-01",
+ "2013-10-02",
+ "2013-10-03",
+ "2013-10-04",
+ "2013-10-07",
+ "2014-01-01",
+ "2014-01-31",
+ "2014-02-03",
+ "2014-02-04",
+ "2014-02-05",
+ "2014-02-06",
+ "2014-04-07",
+ "2014-05-01",
+ "2014-05-02",
+ "2014-06-02",
+ "2014-09-08",
+ "2014-10-01",
+ "2014-10-02",
+ "2014-10-03",
+ "2014-10-06",
+ "2014-10-07",
+ "2015-01-01",
+ "2015-01-02",
+ "2015-02-18",
+ "2015-02-19",
+ "2015-02-20",
+ "2015-02-23",
+ "2015-02-24",
+ "2015-04-06",
+ "2015-05-01",
+ "2015-06-22",
+ "2015-09-03",
+ "2015-09-04",
+ "2015-10-01",
+ "2015-10-02",
+ "2015-10-05",
+ "2015-10-06",
+ "2015-10-07",
+ "2016-01-01",
+ "2016-02-08",
+ "2016-02-09",
+ "2016-02-10",
+ "2016-02-11",
+ "2016-02-12",
+ "2016-04-04",
+ "2016-05-02",
+ "2016-06-09",
+ "2016-06-10",
+ "2016-09-15",
+ "2016-09-16",
+ "2016-10-03",
+ "2016-10-04",
+ "2016-10-05",
+ "2016-10-06",
+ "2016-10-07",
+ "2017-01-02",
+ "2017-01-27",
+ "2017-01-30",
+ "2017-01-31",
+ "2017-02-01",
+ "2017-02-02",
+ "2017-04-03",
+ "2017-04-04",
+ "2017-05-01",
+ "2017-05-29",
+ "2017-05-30",
+ "2017-10-02",
+ "2017-10-03",
+ "2017-10-04",
+ "2017-10-05",
+ "2017-10-06",
+ "2018-01-01",
+ "2018-02-15",
+ "2018-02-16",
+ "2018-02-19",
+ "2018-02-20",
+ "2018-02-21",
+ "2018-04-05",
+ "2018-04-06",
+ "2018-04-30",
+ "2018-05-01",
+ "2018-06-18",
+ "2018-09-24",
+ "2018-10-01",
+ "2018-10-02",
+ "2018-10-03",
+ "2018-10-04",
+ "2018-10-05",
+ "2018-12-31",
+ "2019-01-01",
+ "2019-02-04",
+ "2019-02-05",
+ "2019-02-06",
+ "2019-02-07",
+ "2019-02-08",
+ "2019-04-05",
+ "2019-05-01",
+ "2019-05-02",
+ "2019-05-03",
+ "2019-06-07",
+ "2019-09-13",
+ "2019-10-01",
+ "2019-10-02",
+ "2019-10-03",
+ "2019-10-04",
+ "2019-10-07",
+ "2020-01-01",
+ "2020-01-24",
+ "2020-01-27",
+ "2020-01-28",
+ "2020-01-29",
+ "2020-01-30",
+ "2020-01-31", # http://english.sse.com.cn/news/newsrelease/c/4993503.shtml
+ "2020-04-06",
+ "2020-05-01",
+ "2020-05-04",
+ "2020-05-05",
+ "2020-06-25",
+ "2020-06-26",
+ "2020-10-01",
+ "2020-10-02",
+ "2020-10-05",
+ "2020-10-06",
+ "2020-10-07",
+ "2020-10-08",
+ "2021-01-01",
+ "2021-02-11",
+ "2021-02-12",
+ "2021-02-15",
+ "2021-02-16",
+ "2021-02-17",
+ "2021-04-05",
+ "2021-05-03",
+ "2021-05-04",
+ "2021-05-05",
+ "2021-06-14",
+ "2021-09-20",
+ "2021-09-21",
+ "2021-10-01",
+ "2021-10-04",
+ "2021-10-05",
+ "2021-10-06",
+ "2021-10-07",
+ "2022-01-03",
+ "2022-01-31",
+ "2022-02-01",
+ "2022-02-02",
+ "2022-02-03",
+ "2022-02-04",
+ "2022-04-04",
+ "2022-04-05",
+ "2022-05-02",
+ "2022-05-03",
+ "2022-05-04",
+ "2022-06-03",
+ "2022-09-12",
+ "2022-10-03",
+ "2022-10-04",
+ "2022-10-05",
+ "2022-10-06",
+ "2022-10-07",
+ "2023-01-02",
+ "2023-01-23",
+ "2023-01-24",
+ "2023-01-25",
+ "2023-01-26",
+ "2023-01-27",
+ "2023-04-05",
+ "2023-05-01",
+ "2023-05-02",
+ "2023-05-03",
+ "2023-06-22",
+ "2023-06-23",
+ "2023-09-29",
+ "2023-10-02",
+ "2023-10-03",
+ "2023-10-04",
+ "2023-10-05",
+ "2023-10-06",
+ "2024-01-01", # 2024 holidays https://www.gov.cn/zhengce/content/202310/content_6911527.htm
+ "2024-02-09", # http://english.sse.com.cn/start/trading/schedule/
+ "2024-02-12",
+ "2024-02-13",
+ "2024-02-14",
+ "2024-02-15",
+ "2024-02-16",
+ "2024-04-04",
+ "2024-04-05",
+ "2024-05-01",
+ "2024-05-02",
+ "2024-05-03",
+ "2024-06-10",
+ "2024-09-16",
+ "2024-09-17",
+ "2024-10-01",
+ "2024-10-02",
+ "2024-10-03",
+ "2024-10-04",
+ "2024-10-07",
+ "2025-01-01",
+ "2025-01-29",
+ "2025-01-30",
+ "2025-01-31",
+ "2025-02-03",
+ "2025-04-04",
+ "2025-05-01",
+ "2025-10-01",
+ "2025-10-02",
+ "2025-10-03",
+ "2025-10-04",
+ ]
+)
+
+
+class XSHGExchangeCalendar(PrecomputedExchangeCalendar):
+ """
+ Exchange calendar for the Shanghai Stock Exchange (XSHG, XSSC, SSE).
+
+ Open time: 9:30 Asia/Shanghai
+ Lunch break: 11:30 - 13:00 Asia/Shanghai
+ Close time: 15:00 Asia/Shanghai
+
+ Due to the complexity around the Shanghai exchange holidays, we are
+ hardcoding a list of holidays covering 1999-2025, inclusive. There are
+ no known early closes or late opens.
+ """
+
+ name = "XSHG"
+ tz = ZoneInfo("Asia/Shanghai")
+ open_times = ((None, time(9, 30)),)
+ break_start_times = ((None, time(11, 30)),)
+ break_end_times = ((None, time(13, 0)),)
+ close_times = ((None, time(15, 0)),)
+
+ @classmethod
+ def precomputed_holidays(cls):
+ return precomputed_shanghai_holidays
+
+ @classmethod
+ def bound_min(cls) -> pd.Timestamp:
+ return pd.Timestamp("1990-12-03")
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xsto.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xsto.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fc85ca633a6455a0a67bd627d1a3c101f9637da
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xsto.py
@@ -0,0 +1,164 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import (
+ FR,
+ DateOffset,
+ Easter,
+ EasterMonday,
+ GoodFriday,
+ Holiday,
+)
+from pandas.tseries.offsets import Day
+
+from .common_holidays import (
+ ascension_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ epiphany,
+ european_labour_day,
+ maundy_thursday,
+ midsummer_eve,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import WEEKDAYS, HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+DayBeforeEpiphany = Holiday(
+ "Day Before Epiphany",
+ month=1,
+ day=5,
+ days_of_week=WEEKDAYS,
+)
+Epiphany = epiphany()
+
+DayBeforeLabourDay = Holiday(
+ "Day Before Labour Day",
+ month=4,
+ day=30,
+ days_of_week=WEEKDAYS,
+)
+LabourDay = european_labour_day()
+
+MaundyThursday = maundy_thursday(days_of_week=WEEKDAYS)
+DayBeforeAscensionDay = Holiday(
+ "Day Before Ascension Day",
+ month=1,
+ day=1,
+ offset=[Easter(), Day(38)],
+)
+AscensionDay = ascension_day()
+WhitMonday = whit_monday(end_date="2005")
+
+NationalDay = Holiday("Sweden National Day", month=6, day=6, start_date="2004")
+
+MidsummerEve = midsummer_eve()
+
+# This falls on the Friday between October 30th and November 5th.
+AllSaintsEve = Holiday(
+ "All Saints' Eve",
+ month=10,
+ day=30,
+ offset=DateOffset(weekday=FR(1)),
+)
+
+ChristmasEve = christmas_eve()
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve()
+
+
+class XSTOExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Stockholm Stock Exchange in Sweden.
+
+ Open Time: 9:00 AM, CET (Central European Time)
+ Close Time: 5:30 PM, CET (Central European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Epiphany
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Ascension Day
+ - National Day
+ - Midsummer Eve
+ - Christmas Eve
+ - Christmas Day
+ - Boxing Day
+ - New Year's Eve
+
+ Holidays No Longer Observed:
+ - Whit Monday
+
+ Early Closes:
+ - Day before Epiphany
+ - Maundy Thursday
+ - Day before Labour Day
+ - Day before Ascension Day
+ - All Saints' Eve
+ """
+
+ name = "XSTO"
+ tz = ZoneInfo("Europe/Stockholm")
+ open_times = ((None, time(9, 0)),)
+ close_times = ((None, time(17, 30)),)
+ regular_early_close = time(13)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ Epiphany,
+ GoodFriday,
+ EasterMonday,
+ LabourDay,
+ AscensionDay,
+ WhitMonday,
+ NationalDay,
+ MidsummerEve,
+ ChristmasEve,
+ Christmas,
+ BoxingDay,
+ NewYearsEve,
+ ]
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [
+ DayBeforeEpiphany,
+ MaundyThursday,
+ DayBeforeLabourDay,
+ DayBeforeAscensionDay,
+ AllSaintsEve,
+ ]
+ ),
+ ),
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xswx.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xswx.py
new file mode 100644
index 0000000000000000000000000000000000000000..d994917070bd9b45b88d14553ca53253f765c5cb
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xswx.py
@@ -0,0 +1,107 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday
+
+from .common_holidays import (
+ ascension_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ european_labour_day,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+# Regular Holidays
+# ----------------
+NewYearsDay = new_years_day()
+
+BerchtoldsDay = Holiday(
+ "Berchtold's Day",
+ month=1,
+ day=2,
+)
+
+EuropeanLabourDay = european_labour_day()
+
+AscensionDay = ascension_day()
+
+WhitMonday = whit_monday()
+
+SwissNationalDay = Holiday("Swiss National Day", month=8, day=1)
+
+ChristmasEve = christmas_eve()
+
+Christmas = christmas()
+
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve()
+
+
+class XSWXExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Swiss Exchange (XSWX)
+
+ Open Time: 8:00 AM, CET, CEST in summer
+ Close Time: 5:30 PM, CET, CEST in summer
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Berchtold's Day
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Ascension Day
+ - Whit Monday
+ - Swiss National Day
+ - Christmas Eve
+ - Christmas Day
+ - Boxing Day
+ - New Year's Eve
+ """
+
+ name = "XSWX"
+
+ tz = ZoneInfo("Europe/Zurich")
+
+ open_times = ((None, time(9, 0)),)
+
+ close_times = ((None, time(17, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ BerchtoldsDay,
+ EasterMonday,
+ GoodFriday,
+ EuropeanLabourDay,
+ AscensionDay,
+ WhitMonday,
+ SwissNationalDay,
+ ChristmasEve,
+ Christmas,
+ BoxingDay,
+ NewYearsEve,
+ ]
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtae.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtae.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e8c25e0645fe7b58833710667543326e8b404a3
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtae.py
@@ -0,0 +1,175 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+
+from .tase_holidays import (
+ FastDay,
+ IndependenceDay,
+ MemorialDay,
+ NewYear,
+ NewYear2,
+ NewYearsEve,
+ Passover,
+ Passover2,
+ PassoverInterimDay1,
+ PassoverInterimDay2,
+ PassoverInterimDay3,
+ PassoverInterimDay4,
+ SukkothInterimDay1,
+ SukkothInterimDay2,
+ SukkothInterimDay3,
+ SukkothInterimDay4,
+ SukkothInterimDay5,
+ Passover2Eve,
+ PassoverEve,
+ Pentecost,
+ PentecostEve,
+ Purim,
+ SimchatTorah,
+ SimchatTorahEve,
+ Sukkoth,
+ SukkothEve,
+ YomKippur,
+ YomKippurEve,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar, SUNDAY
+
+# All holidays are defined as ad-hoc holidays for each year since there is
+# currently no support for Hebrew calendar holiday rules in pandas.
+
+HOLIDAY_EARLY_CLOSE = time(14, 15)
+SUNDAY_CLOSE = time(15, 40)
+
+
+class XTAEExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for TASE Stock Exchange.
+
+ Open/close times are continuous trading times valid Mon-Thu for Shares
+ Group A. Trading schedule differs on Sundays.
+
+ Open Time: 9:59 AM, Asia/Tel_Aviv (randomly between 9:59 and 10:00).
+ Close Time: 5:15 PM, Asia/Tel_Aviv (randomly between 5:14 and 5:15).
+ Sunday close time: 3:40pm, Asia/Tel_Aviv (randomly between 3:39 and 3:40)
+
+ Regularly-Observed Holidays (not necessarily in order):
+ - Purim
+ - Passover Eve
+ - Passover
+ - Passover II Eve
+ - Passover II
+ - Memorial Day
+ - Independence Day
+ - Pentecost Eve
+ - Pentecost
+ - Tisha B'Av
+ - New Year's Eve
+ - New Year
+ - New Year II
+ - Yom Kippur Eve
+ - Yom Kippur
+ - Sukkoth Eve
+ - Sukkoth
+ - Simchat Torah Eve
+ - Simchat Torah
+
+ Note these dates are only checked against 2019-2023.
+
+ https://info.tase.co.il/eng/about_tase/corporate/pages/vacation_schedule.aspx
+
+ Daylight Saving Time in Israel comes into effect on the Friday before the
+ last Sunday in March, and lasts until the last Sunday in October. During the
+ Daylight Saving time period the clock will be UTC+3, and UTC+2 for the rest
+ of the year.
+ """ # noqa
+
+ name = "XTAE"
+
+ tz = ZoneInfo("Asia/Tel_Aviv")
+
+ open_times = ((None, time(9, 59)),)
+
+ close_times = ((None, time(17, 15)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ Purim,
+ PassoverEve,
+ Passover,
+ Passover2Eve,
+ Passover2,
+ MemorialDay,
+ IndependenceDay,
+ PentecostEve,
+ Pentecost,
+ FastDay,
+ NewYearsEve,
+ NewYear,
+ NewYear2,
+ YomKippurEve,
+ YomKippur,
+ SukkothEve,
+ Sukkoth,
+ SimchatTorahEve,
+ SimchatTorah,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [
+ # Election days:
+ # - 2019
+ pd.Timestamp("2019-04-09"),
+ pd.Timestamp("2019-09-17"),
+ # - 2020
+ pd.Timestamp("2020-03-02"),
+ # - 2021
+ pd.Timestamp("2021-03-23"),
+ # - 2022
+ pd.Timestamp("2022-11-01"),
+ ]
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ HOLIDAY_EARLY_CLOSE,
+ HolidayCalendar(
+ [
+ PassoverInterimDay1,
+ PassoverInterimDay2,
+ PassoverInterimDay3,
+ PassoverInterimDay4,
+ SukkothInterimDay1,
+ SukkothInterimDay2,
+ SukkothInterimDay3,
+ SukkothInterimDay4,
+ SukkothInterimDay5,
+ ]
+ ),
+ ),
+ (SUNDAY_CLOSE, SUNDAY),
+ ]
+
+ @property
+ def weekmask(self):
+ return "1111001"
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtai.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtai.py
new file mode 100644
index 0000000000000000000000000000000000000000..e39675c827ecf2b47c4513bd557f2a5db404494d
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtai.py
@@ -0,0 +1,388 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import datetime
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import (
+ Holiday,
+ nearest_workday,
+ next_monday,
+ previous_friday,
+)
+
+from .common_holidays import european_labour_day, new_years_day
+from .lunisolar_holidays import (
+ chinese_lunar_new_year_dates,
+ dragon_boat_festival_dates,
+ mid_autumn_festival_dates,
+ qingming_festival_dates,
+)
+from .exchange_calendar import (
+ MONDAY,
+ TUESDAY,
+ THURSDAY,
+ FRIDAY,
+ SATURDAY,
+ SUNDAY,
+ HolidayCalendar,
+ ExchangeCalendar,
+)
+
+
+ONE_DAY = datetime.timedelta(1)
+
+
+def before_chinese_new_year_offset(holidays):
+ """
+ For Holidays that come before Chinese New Year, we subtract a day
+ and then move any weekends to previous friday.
+ """
+ return pd.to_datetime(holidays.map(lambda d: previous_friday(d)))
+
+
+def chinese_new_year_offset(holidays):
+ """
+ For Holidays on or after Chinese New Year, we add a day
+ and then move any weekends to next monday.
+ """
+ return pd.to_datetime(holidays.map(lambda d: next_monday(d)))
+
+
+def nearest_workday_after_2013(dt: datetime.datetime) -> datetime.datetime:
+ """
+ Nearest workday starting in 2014.
+ """
+ return nearest_workday(dt) if dt.year > 2013 else dt
+
+
+def manual_nearest_workday(holidays):
+ """
+ Nearest workday observance rule for Chinese lunar calendar holidays.
+ The nearest workday rule seems to start in 2014 for these holidays.
+ """
+ return pd.to_datetime(holidays.map(lambda d: nearest_workday_after_2013(d)))
+
+
+def manual_extra_days(holidays):
+ """
+ Four day weekend makeup days for Chinese lunar calendar holidays.
+ The four day weekend rule seem to start in 2007 for these holidays.
+ """
+ friday_extras = [
+ d + ONE_DAY for d in holidays if d.weekday() == THURSDAY and d.year > 2006
+ ]
+
+ monday_extras = [
+ d - ONE_DAY for d in holidays if d.weekday() == TUESDAY and d.year > 2006
+ ]
+
+ return pd.to_datetime(friday_extras + monday_extras)
+
+
+def weekend_makeup(dt: datetime.datetime) -> datetime.datetime:
+ """Makeup holiday falling on weekend to nearest workday.
+
+ This function attempts to implement what seems to be the Taiwan holiday
+ observance rule since 2013.
+ """
+ if dt.year < 2014:
+ return dt
+ if dt.weekday() == SUNDAY:
+ dt += ONE_DAY
+ elif dt.weekday() == SATURDAY:
+ dt -= ONE_DAY
+ return dt
+
+
+def bridge_mon(dt: datetime.datetime) -> datetime.datetime | None:
+ """Define Monday as holiday if Tuesday is a holiday.
+
+ This function attempts to implement what seems to be the Taiwan holiday
+ observance rule since 2013.
+
+ Notes
+ -----
+ If a holiday falls on a Tuesday an extra holiday is observed on Monday
+ to bridge the weekend and the official holiday.
+ """
+ dt -= ONE_DAY
+ return dt if (dt.weekday() == MONDAY and dt.year > 2013) else None
+
+
+def bridge_fri(dt: datetime.datetime) -> datetime.datetime | None:
+ """Define Friday as holiday if Thursday is a holiday.
+
+ This function attempts to implement what seems to be the Taiwan holiday
+ observance rule since 2013.
+
+ Notes
+ -----
+ If a holiday falls on a Thursday an extra holiday is observed on Friday
+ to bridge the weekend and the official holiday.
+ """
+ dt += ONE_DAY
+ return dt if (dt.weekday() == FRIDAY and dt.year > 2013) else None
+
+
+NewYearsDay = new_years_day(observance=weekend_makeup)
+NewYearsDayExtraMon = new_years_day(observance=bridge_mon)
+NewYearsDayExtraFri = new_years_day(observance=bridge_fri)
+
+
+PeaceMemorialDay = Holiday(
+ "Peace Memorial Day", month=2, day=28, observance=weekend_makeup
+)
+PeaceMemorialDayExtraMon = Holiday(
+ "Peace Memorial Day extra Monday", month=2, day=28, observance=bridge_mon
+)
+PeaceMemorialDayExtraFri = Holiday(
+ "Peace Memorial Day extra Friday", month=2, day=28, observance=bridge_fri
+)
+
+
+WomenAndChildrensDay = Holiday(
+ "Women and Children's Day",
+ month=4,
+ day=4,
+ start_date="2011",
+ observance=weekend_makeup,
+)
+WomenAndChildrensDayExtraMon = Holiday(
+ "Women and Children's Day extra Monday",
+ month=4,
+ day=4,
+ start_date="2011",
+ observance=bridge_mon,
+)
+WomenAndChildrensDayExtraFri = Holiday(
+ "Women and Children's Day extra Friday",
+ month=4,
+ day=4,
+ start_date="2011",
+ observance=bridge_fri,
+)
+
+
+LabourDay = european_labour_day(observance=nearest_workday_after_2013)
+
+NationalDay = Holiday(
+ "National Day of the Republic of China",
+ month=10,
+ day=10,
+ observance=weekend_makeup,
+)
+NationalDayExtraMon = Holiday(
+ "National Day of the Republic of China extra Monday",
+ month=10,
+ day=10,
+ observance=bridge_mon,
+)
+NationalDayExtraFri = Holiday(
+ "National Day of the Republic of China extra Friday",
+ month=10,
+ day=10,
+ observance=bridge_fri,
+)
+
+
+chinese_new_year = chinese_new_year_offset(chinese_lunar_new_year_dates)
+
+chinese_new_years_eve = before_chinese_new_year_offset(
+ chinese_new_year - ONE_DAY,
+)
+
+chinese_new_years_eve_2 = before_chinese_new_year_offset(
+ chinese_new_years_eve - ONE_DAY,
+)
+
+chinese_new_year_2 = chinese_new_year_offset(
+ chinese_new_year + ONE_DAY,
+)
+
+chinese_new_year_3 = chinese_new_year_offset(
+ chinese_new_year_2 + ONE_DAY,
+)
+
+tomb_sweeping_day = manual_nearest_workday(qingming_festival_dates)
+
+tomb_sweeping_day_extras = manual_extra_days(tomb_sweeping_day)
+
+dragon_boat_festival = manual_nearest_workday(dragon_boat_festival_dates)
+
+dragon_boat_festival_extras = manual_extra_days(dragon_boat_festival)
+
+mid_autumn_festival = manual_nearest_workday(
+ mid_autumn_festival_dates,
+)
+
+mid_autumn_festival_extras = manual_extra_days(mid_autumn_festival)
+
+# Taiwan takes multiple days off before and after chinese new year,
+# and sometimes it is unclear precisely which days will be holidays.
+chinese_new_year_extras = pd.to_datetime(
+ [
+ "2002-02-07",
+ "2002-02-15",
+ "2003-01-29",
+ "2004-01-19",
+ "2005-02-04",
+ "2006-02-02",
+ "2007-02-22",
+ "2007-02-23",
+ "2008-02-04",
+ "2009-01-29",
+ "2009-01-30",
+ "2010-02-18",
+ "2010-02-19",
+ "2011-01-31",
+ "2012-01-26",
+ "2012-01-27",
+ "2013-02-14",
+ "2013-02-15",
+ "2014-01-28",
+ "2015-02-16",
+ "2016-02-11",
+ "2016-02-12",
+ "2017-01-25",
+ "2018-02-13",
+ "2019-01-31",
+ "2019-02-08",
+ "2020-01-21",
+ "2020-01-22",
+ "2021-02-08",
+ "2021-02-09",
+ "2022-01-27",
+ "2023-01-26",
+ "2023-01-27",
+ ]
+)
+
+# Some abnormal observances of regularly observed holidays.
+extra_holidays = pd.to_datetime(
+ [
+ "2021-04-02", # Women And Childrens Day
+ "2020-04-02", # Tomb Sweeping Day
+ "2016-04-05", # Tomb Sweeping Day
+ "2012-12-31", # New Year's Eve
+ "2012-02-27", # Peace Memorial Day
+ "2009-01-02", # New Year's Day
+ "2006-10-09", # National Day
+ "2005-09-01", # Bank Holiday
+ ]
+)
+
+typhoons = pd.to_datetime(
+ [
+ "2019-09-30",
+ "2019-08-09",
+ "2016-09-28",
+ "2016-09-27",
+ "2016-07-08",
+ "2015-09-29",
+ "2015-07-10",
+ "2014-07-23",
+ "2013-08-21",
+ "2012-08-02",
+ "2009-08-07",
+ "2008-09-29",
+ "2008-07-28",
+ "2007-09-18",
+ "2005-08-05",
+ "2005-07-18",
+ "2004-10-25",
+ "2004-08-25",
+ "2004-08-24",
+ "2002-09-06",
+ ]
+)
+
+
+class XTAIExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Taiwan Stock Exchange Corporation (XTAI).
+
+ Open Time: 9:00 AM, CST
+ Close Time: 1:30 PM, CST
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Chinese New Year's Eve
+ - Chinese New Year
+ - Peace Memorial Day (Feb 28)
+ - Women and Children's Day (Apr 4)
+ - Tomb Sweeping Day (Lunar Calendar)
+ - Labour Day (May 1)
+ - Dragon Boat Festival (Lunar Calendar)
+ - Mid-Autumn Festival (Lunar Calendar)
+ - National Day of the Republic of China (Oct 10)
+
+
+ Early Closes:
+ - None
+ """
+
+ name = "XTAI"
+
+ tz = ZoneInfo("Asia/Taipei")
+
+ open_times = ((None, datetime.time(9)),)
+
+ close_times = ((None, datetime.time(13, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ NewYearsDayExtraMon,
+ NewYearsDayExtraFri,
+ PeaceMemorialDay,
+ PeaceMemorialDayExtraMon,
+ PeaceMemorialDayExtraFri,
+ WomenAndChildrensDay,
+ WomenAndChildrensDayExtraMon,
+ WomenAndChildrensDayExtraFri,
+ LabourDay,
+ NationalDay,
+ NationalDayExtraMon,
+ NationalDayExtraFri,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ extra_holidays,
+ typhoons,
+ chinese_new_years_eve,
+ chinese_new_years_eve_2,
+ chinese_new_year,
+ chinese_new_year_2,
+ chinese_new_year_3,
+ chinese_new_year_extras,
+ tomb_sweeping_day,
+ tomb_sweeping_day_extras,
+ dragon_boat_festival,
+ dragon_boat_festival_extras,
+ mid_autumn_festival,
+ mid_autumn_festival_extras,
+ )
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtks.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtks.py
new file mode 100644
index 0000000000000000000000000000000000000000..d04802d2970191681a0667722377b5ae67ccaeb3
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtks.py
@@ -0,0 +1,145 @@
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+from .xtks_holidays import (
+ AutumnalEquinoxes,
+ ChildrensDay,
+ CitizensHolidayGoldenWeek,
+ CitizensHolidaySilverWeek,
+ ComingOfAgeDay2000Onwards,
+ ComingOfAgeDayThrough1999,
+ ConstitutionMemorialDay,
+ CultureDay,
+ EmperorAkihitoBirthday,
+ EmperorNaruhitoBirthday,
+ EquityTradingSystemFailure,
+ GreeneryDay2007Onwards,
+ GreeneryDayThrough2006,
+ HealthAndSportsDay2000OnwardsThrough2019,
+ HealthAndSportsDay2020,
+ HealthAndSportsDay2021,
+ HealthAndSportsDay2022Onwards,
+ HealthAndSportsDayThrough1999,
+ LaborThanksgivingDay,
+ MarineDay2003OnwardsThrough2019,
+ MarineDay2020,
+ MarineDay2021,
+ MarineDay2022Onwards,
+ MarineDayThrough2002,
+ Misc2019Holidays,
+ MountainDay2020,
+ MountainDay2021,
+ MountainDay2022Onwards,
+ MountainDayThrough2019,
+ NationalFoundationDay,
+ NewYearsHolidayDec31,
+ NewYearsHolidayJan1,
+ NewYearsHolidayJan2,
+ NewYearsHolidayJan3,
+ RespectForTheAgedDay2003Onwards,
+ RespectForTheAgedDayThrough2002,
+ ShowaDay,
+ VernalEquinoxes,
+)
+
+
+class XTKSExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Tokyo Stock Exchange
+
+ First session: 9:00am - 11:30am
+ Lunch Break: 11:30am - 12:30pm
+ Second session: 12:30pm - 3:00pm
+
+ Regularly-Observed Holidays (see xtks_holidays.py for more info):
+ - New Year's Holidays (Dec. 31 - Jan. 3)
+ - Coming of Age Day (second Monday of January)
+ - National Foundation Day (Feb. 11)
+ - Vernal Equinox (usually Mar 20-22)
+ - Greenery Day (Apr. 29 2000-2006, May 4 2007-present)
+ - Showa Day (Apr. 29 2007-present)
+ - Constitution Memorial Day (May 3)
+ - Citizen's Holiday (May 4 2000-2006, later replaced by Greenery Day)
+ - Children's Day (May 5)
+ - Marine Day (July 20 2000-2002, third Monday of July 2003-present)
+ - Respect for the Aged Day (Sep. 15 2000-2002, third Monday
+ of Sep. 2003-present)
+ - Autumnal Equinox (usually Sept. 22-24)
+ - Health-Sports Day (second Monday of October)
+ - Culture Day (November 3)
+ - Labor Thanksgiving Day (Nov. 23)
+ - Emperor's Birthday (Dec. 23)
+
+ Additional Irregularities:
+ - Closed on October 1, 2020 due to equity trading system failure
+ """
+
+ name = "XTKS"
+
+ tz = ZoneInfo("Asia/Tokyo")
+
+ open_times = ((None, time(9)),)
+ break_start_times = ((None, time(11, 30)),)
+ break_end_times = ((None, time(12, 30)),)
+ close_times = ((None, time(15)),)
+
+ @classmethod
+ def bound_min(cls) -> pd.Timestamp:
+ # not tracking holiday info farther back than 1997
+ return pd.Timestamp("1997-01-01")
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsHolidayDec31,
+ NewYearsHolidayJan1,
+ NewYearsHolidayJan2,
+ NewYearsHolidayJan3,
+ ComingOfAgeDayThrough1999,
+ ComingOfAgeDay2000Onwards,
+ NationalFoundationDay,
+ GreeneryDayThrough2006,
+ ShowaDay,
+ ConstitutionMemorialDay,
+ GreeneryDay2007Onwards,
+ CitizensHolidayGoldenWeek,
+ ChildrensDay,
+ MarineDayThrough2002,
+ MarineDay2003OnwardsThrough2019,
+ MarineDay2020,
+ MarineDay2021,
+ MarineDay2022Onwards,
+ MountainDayThrough2019,
+ MountainDay2020,
+ MountainDay2021,
+ MountainDay2022Onwards,
+ RespectForTheAgedDayThrough2002,
+ RespectForTheAgedDay2003Onwards,
+ HealthAndSportsDayThrough1999,
+ HealthAndSportsDay2000OnwardsThrough2019,
+ HealthAndSportsDay2020,
+ HealthAndSportsDay2021,
+ HealthAndSportsDay2022Onwards,
+ CultureDay,
+ LaborThanksgivingDay,
+ EmperorAkihitoBirthday,
+ EmperorNaruhitoBirthday,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ VernalEquinoxes,
+ AutumnalEquinoxes,
+ CitizensHolidaySilverWeek,
+ Misc2019Holidays,
+ EquityTradingSystemFailure,
+ )
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtse.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtse.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1c24edf8b30765d9ac052f0b75f2373d0d85cda
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xtse.py
@@ -0,0 +1,167 @@
+from datetime import time
+from itertools import chain
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import (
+ MO,
+ DateOffset,
+ GoodFriday,
+ Holiday,
+ weekend_to_monday,
+)
+
+from .common_holidays import (
+ boxing_day,
+ christmas,
+ new_years_day,
+ weekend_boxing_day,
+ weekend_christmas,
+)
+from .exchange_calendar import (
+ FRIDAY,
+ MONDAY,
+ THURSDAY,
+ TUESDAY,
+ WEDNESDAY,
+ HolidayCalendar,
+ ExchangeCalendar,
+)
+
+# New Year's Day
+XTSENewYearsDay = new_years_day(observance=weekend_to_monday)
+
+# Ontario Family Day
+FamilyDay = Holiday(
+ "Family Day",
+ month=2,
+ day=1,
+ offset=DateOffset(weekday=MO(3)),
+ start_date="2008-01-01",
+)
+# Victoria Day
+VictoriaDay = Holiday(
+ "Victoria Day",
+ month=5,
+ day=24,
+ offset=DateOffset(weekday=MO(-1)),
+)
+# Canada Day
+CanadaDay = Holiday(
+ "Canada Day",
+ month=7,
+ day=1,
+ observance=weekend_to_monday,
+)
+# Civic Holiday
+CivicHoliday = Holiday(
+ "Civic Holiday",
+ month=8,
+ day=1,
+ offset=DateOffset(weekday=MO(1)),
+)
+# Labor Day
+LaborDay = Holiday(
+ "Labor Day",
+ month=9,
+ day=1,
+ offset=DateOffset(weekday=MO(1)),
+)
+# Canadian Thanksgiving
+CanadianThanksgiving = Holiday(
+ "Canadian Thanksgiving",
+ month=10,
+ day=1,
+ offset=DateOffset(weekday=MO(2)),
+)
+
+ChristmasEveEarlyClose2010Onwards = Holiday(
+ "Christmas Eve Early Close",
+ month=12,
+ day=24,
+ days_of_week=(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY),
+ start_date=pd.Timestamp("2010-01-01"),
+)
+
+Christmas = christmas()
+
+WeekendChristmas = weekend_christmas()
+
+BoxingDay = boxing_day()
+
+WeekendBoxingDay = weekend_boxing_day()
+
+September11ClosingsCanada = pd.date_range("2001-09-11", "2001-09-12")
+
+
+class XTSEExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Toronto Stock Exchange (XTSE).
+
+ Open Time: 9:30 AM, EST
+ Close Time: 4:00 PM, EST
+
+ Regularly-Observed Holidays:
+ - New Years Day (observed on first business day on/after)
+ - Family Day (Third Monday in February, starting in 2008)
+ - Good Friday
+ - Victoria Day (Monday before May 25th)
+ - Canada Day (July 1st, observed first business day after)
+ - Civic Holiday (First Monday in August)
+ - Labor Day (First Monday in September)
+ - Thanksgiving (Second Monday in October)
+ - Christmas Day
+ - Dec. 26th if Christmas is on a Sunday
+ - Dec. 27th if Christmas is on a weekend
+ - Boxing Day
+ - Dec. 27th if Christmas is on a Sunday
+ - Dec. 28th if Boxing Day is on a weekend
+
+ Early closes:
+ - Starting in 2010, if Christmas Eve falls on a weekday, the market
+ closes at 1:00 pm that day. If it falls on a weekend, there is no
+ early close.
+ """
+
+ regular_early_close = time(13)
+
+ name = "XTSE"
+
+ tz = ZoneInfo("America/Toronto")
+
+ open_times = ((None, time(9, 30)),)
+
+ close_times = ((None, time(16)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ XTSENewYearsDay,
+ FamilyDay,
+ GoodFriday,
+ VictoriaDay,
+ CanadaDay,
+ CivicHoliday,
+ LaborDay,
+ CanadianThanksgiving,
+ Christmas,
+ WeekendChristmas,
+ BoxingDay,
+ WeekendBoxingDay,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ # NOTE: change the name of this property
+ return list(chain(September11ClosingsCanada))
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar([ChristmasEveEarlyClose2010Onwards]),
+ )
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xwar.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xwar.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b79527f4f8dfebce0b789ba96f98d6d965db9b5
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xwar.py
@@ -0,0 +1,149 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import datetime
+from zoneinfo import ZoneInfo
+
+import pandas as pd
+from pandas.tseries.holiday import EasterMonday, GoodFriday, Holiday
+
+from .common_holidays import (
+ all_saints_day,
+ boxing_day,
+ christmas,
+ christmas_eve,
+ corpus_christi,
+ epiphany,
+ european_labour_day,
+ new_years_day,
+ new_years_eve,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+
+def not_2004(dt: datetime.datetime) -> datetime.datetime | None:
+ """
+ Christmas Eve is a holiday every year except for whatever reason it was a
+ trading day in 2004.
+ """
+ return dt if dt.year != 2004 else None
+
+
+NewYearsDay = new_years_day()
+
+Epiphany = epiphany(start_date="2011")
+
+LabourDay = european_labour_day()
+
+May3ConstitutionDay = Holiday(
+ "Celabration of Declaration of the Constitution of 3 May",
+ month=5,
+ day=3,
+)
+
+CorpusChristi = corpus_christi()
+
+ArmedForcesDay = Holiday(
+ "Armed Forces Day",
+ month=8,
+ day=15,
+)
+
+AllSaintsDay = all_saints_day()
+
+IndependenceDay = Holiday(
+ "National Independence Day",
+ month=11,
+ day=11,
+)
+
+ChristmasEve = christmas_eve(observance=not_2004)
+Christmas = christmas()
+BoxingDay = boxing_day()
+
+NewYearsEve = new_years_eve(start_date="2011")
+
+
+class XWARExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Warsaw Stock Exchange (WSE).
+
+ Open Time: 9:00 AM, Central European Time (CET)
+ Close Time: 5:00 PM, Central European Time (CET)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Epiphany
+ - Good Friday
+ - Easter Monday
+ - Labour Day
+ - Constitution Day
+ - Corpus Christi
+ - Armed Forces Day
+ - All Saints' Day
+ - Independence Day
+ - Christmas Eve
+ - Christmas Day
+ - Boxing Day
+ - New Year's Eve
+
+ Holidays No Longer Observed:
+ - None
+
+ Early Closes:
+ - None
+ """
+
+ name = "XWAR"
+
+ tz = ZoneInfo("Europe/Warsaw")
+
+ open_times = ((None, datetime.time(9)),)
+ close_times = ((None, datetime.time(17)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ Epiphany,
+ GoodFriday,
+ EasterMonday,
+ LabourDay,
+ May3ConstitutionDay,
+ CorpusChristi,
+ ArmedForcesDay,
+ AllSaintsDay,
+ IndependenceDay,
+ ChristmasEve,
+ Christmas,
+ BoxingDay,
+ NewYearsEve,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return [
+ pd.Timestamp("2005-04-08"), # Pope's Funeral.
+ pd.Timestamp("2007-12-31"), # New Year's Eve (adhoc).
+ pd.Timestamp("2008-05-02"), # Exchange Holiday.
+ pd.Timestamp("2009-01-02"), # Exchange Holiday.
+ pd.Timestamp("2013-04-16"), # Exchange Holiday.
+ pd.Timestamp("2018-01-02"), # Exchange Holiday.
+ pd.Timestamp("2018-11-12"), # Independence Holiday.
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xwbo.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xwbo.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c34671f343482d6f388b62aec3a113de1b15d6c
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/exchange_calendar_xwbo.py
@@ -0,0 +1,166 @@
+#
+# Copyright 2018 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from datetime import time
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.holiday import (
+ EasterMonday,
+ GoodFriday,
+ Holiday,
+ previous_friday,
+ previous_workday,
+)
+
+from .common_holidays import (
+ all_saints_day,
+ ascension_day,
+ assumption_day,
+ christmas,
+ christmas_eve,
+ corpus_christi,
+ epiphany,
+ european_labour_day,
+ immaculate_conception,
+ new_years_day,
+ new_years_eve,
+ whit_monday,
+)
+from .exchange_calendar import HolidayCalendar, ExchangeCalendar
+
+NewYearsDay = new_years_day()
+
+Epiphany = epiphany(end_date="2019")
+
+AscensionDay = ascension_day(end_date="2019")
+WhitMonday = whit_monday(end_date="2023")
+CorpusChristi = corpus_christi(end_date="2019")
+
+LabourDay = european_labour_day()
+
+AssumptionDay = assumption_day(end_date="2019")
+
+NationalHoliday = Holiday("National Holiday", month=10, day=26)
+
+AllSaintsDay = all_saints_day(end_date="2019")
+
+ImmaculateConception = immaculate_conception(end_date="2019")
+
+ChristmasEve = christmas_eve()
+Christmas = christmas()
+
+SaintStephensDay = Holiday("Saint Stephen's Day", month=12, day=26)
+
+# Prior to 2016, when New Year's Eve fell on the weekend, it was observed
+# on the preceding Friday. In 2016 and after, it is not made up.
+NewYearsEveThrough2015 = new_years_eve(
+ observance=previous_friday,
+ end_date="2016",
+)
+NewYearsEve2016Onwards = new_years_eve(start_date="2016")
+
+# Early Closes
+# ------------
+# The last weekday before Dec 31 is an early close starting in 2017. Note: this
+# is decided upon separately each year somewhen in November/December.
+# Official announcements can be found at
+#
+# https://www.wienerborse.at/en/news/vienna-stock-exchange-news-list/
+#
+# when searching for "Last trading day".
+LastWorkingDay = Holiday(
+ "Last Working Day of Year Early Close",
+ month=12,
+ day=31,
+ start_date="2017-01-01",
+ observance=previous_workday,
+)
+
+
+class XWBOExchangeCalendar(ExchangeCalendar):
+ """
+ Calendar for the Wiener Borse AG exchange in Vienna, Austria.
+
+ Open Time: 9:00 AM, CET (Central European Time)
+ Close Time: 5:30 PM, CET (Central European Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - Epiphany
+ - Good Friday
+ - Easter Monday
+ - Ascension Day
+ - Whit Monday
+ - Corpus Christi
+ - Labour Day
+ - Assumption Day
+ - National Holiday
+ - All Saints Day
+ - Immaculate Conception
+ - Christmas Eve
+ - Christmas Day
+ - St. Stephen's Day
+ - New Year's Eve
+
+ Early Closes:
+ - Last working day before Dec. 31
+ """
+
+ regular_early_close = time(14, 15)
+
+ name = "XWBO"
+
+ tz = ZoneInfo("Europe/Vienna")
+
+ open_times = ((None, time(9)),)
+
+ close_times = ((None, time(17, 30)),)
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ Epiphany,
+ GoodFriday,
+ EasterMonday,
+ AscensionDay,
+ WhitMonday,
+ CorpusChristi,
+ LabourDay,
+ AssumptionDay,
+ NationalHoliday,
+ AllSaintsDay,
+ ImmaculateConception,
+ ChristmasEve,
+ Christmas,
+ SaintStephensDay,
+ NewYearsEveThrough2015,
+ NewYearsEve2016Onwards,
+ ]
+ )
+
+ @property
+ def special_closes(self):
+ return [
+ (
+ self.regular_early_close,
+ HolidayCalendar(
+ [
+ LastWorkingDay,
+ ]
+ ),
+ )
+ ]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/lunisolar_holidays.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/lunisolar_holidays.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6002e7b04b7ced256755614d0b2e7032ebe5ff8
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/lunisolar_holidays.py
@@ -0,0 +1,620 @@
+"""Lunisolar calendar calculations.
+
+See exchange_calendars/etc/lunisolar for code to calculate
+"""
+
+import pandas as pd
+
+# Precomputed Chinese Lunar Year dates.
+# Also called Spring Festival
+#
+# See Also
+# --------
+# exchange_calendars/etc/lunisolar chinese-new-year
+chinese_lunar_new_year_dates = pd.DatetimeIndex(
+ [
+ "1960-01-28",
+ "1961-02-15",
+ "1962-02-05",
+ "1963-01-25",
+ "1964-02-13",
+ "1965-02-02",
+ "1966-01-21",
+ "1967-02-09",
+ "1968-01-30",
+ "1969-02-17",
+ "1970-02-06",
+ "1971-01-27",
+ "1972-02-15",
+ "1973-02-03",
+ "1974-01-23",
+ "1975-02-11",
+ "1976-01-31",
+ "1977-02-18",
+ "1978-02-07",
+ "1979-01-28",
+ "1980-02-16",
+ "1981-02-05",
+ "1982-01-25",
+ "1983-02-13",
+ "1984-02-02",
+ "1985-02-20",
+ "1986-02-09",
+ "1987-01-29",
+ "1988-02-17",
+ "1989-02-06",
+ "1990-01-27",
+ "1991-02-15",
+ "1992-02-04",
+ "1993-01-23",
+ "1994-02-10",
+ "1995-01-31",
+ "1996-02-19",
+ "1997-02-07",
+ "1998-01-28",
+ "1999-02-16",
+ "2000-02-05",
+ "2001-01-24",
+ "2002-02-12",
+ "2003-02-01",
+ "2004-01-22",
+ "2005-02-09",
+ "2006-01-29",
+ "2007-02-18",
+ "2008-02-07",
+ "2009-01-26",
+ "2010-02-14",
+ "2011-02-03",
+ "2012-01-23",
+ "2013-02-10",
+ "2014-01-31",
+ "2015-02-19",
+ "2016-02-08",
+ "2017-01-28",
+ "2018-02-16",
+ "2019-02-05",
+ "2020-01-25",
+ "2021-02-12",
+ "2022-02-01",
+ "2023-01-22",
+ "2024-02-10",
+ "2025-01-29",
+ "2026-02-17",
+ "2027-02-06",
+ "2028-01-26",
+ "2029-02-13",
+ "2030-02-03",
+ "2031-01-23",
+ "2032-02-11",
+ "2033-01-31",
+ "2034-02-19",
+ "2035-02-08",
+ "2036-01-28",
+ "2037-02-15",
+ "2038-02-04",
+ "2039-01-24",
+ "2040-02-12",
+ "2041-02-01",
+ "2042-01-22",
+ "2043-02-10",
+ "2044-01-30",
+ "2045-02-17",
+ "2046-02-06",
+ "2047-01-26",
+ "2048-02-14",
+ "2049-02-02",
+ ]
+)
+
+# Precomputed Qingming Festival dates.
+# Also called Tomb-sweeping Day
+#
+# See Also
+# --------
+# exchange_calendars/etc/lunisolar qingming-festival
+qingming_festival_dates = pd.DatetimeIndex(
+ [
+ "1960-04-05",
+ "1961-04-05",
+ "1962-04-05",
+ "1963-04-05",
+ "1964-04-05",
+ "1965-04-05",
+ "1966-04-05",
+ "1967-04-05",
+ "1968-04-05",
+ "1969-04-05",
+ "1970-04-05",
+ "1971-04-05",
+ "1972-04-05",
+ "1973-04-05",
+ "1974-04-05",
+ "1975-04-05",
+ "1976-04-04",
+ "1977-04-05",
+ "1978-04-05",
+ "1979-04-05",
+ "1980-04-04",
+ "1981-04-05",
+ "1982-04-05",
+ "1983-04-05",
+ "1984-04-04",
+ "1985-04-05",
+ "1986-04-05",
+ "1987-04-05",
+ "1988-04-04",
+ "1989-04-05",
+ "1990-04-05",
+ "1991-04-05",
+ "1992-04-04",
+ "1993-04-05",
+ "1994-04-05",
+ "1995-04-05",
+ "1996-04-04",
+ "1997-04-05",
+ "1998-04-05",
+ "1999-04-05",
+ "2000-04-04",
+ "2001-04-05",
+ "2002-04-05",
+ "2003-04-05",
+ "2004-04-04",
+ "2005-04-05",
+ "2006-04-05",
+ "2007-04-05",
+ "2008-04-04",
+ "2009-04-04",
+ "2010-04-05",
+ "2011-04-05",
+ "2012-04-04",
+ "2013-04-04",
+ "2014-04-05",
+ "2015-04-05",
+ "2016-04-04",
+ "2017-04-04",
+ "2018-04-05",
+ "2019-04-05",
+ "2020-04-04",
+ "2021-04-04",
+ "2022-04-05",
+ "2023-04-05",
+ "2024-04-04",
+ "2025-04-04",
+ "2026-04-05",
+ "2027-04-05",
+ "2028-04-04",
+ "2029-04-04",
+ "2030-04-05",
+ "2031-04-05",
+ "2032-04-04",
+ "2033-04-04",
+ "2034-04-05",
+ "2035-04-05",
+ "2036-04-04",
+ "2037-04-04",
+ "2038-04-05",
+ "2039-04-05",
+ "2040-04-04",
+ "2041-04-04",
+ "2042-04-04",
+ "2043-04-05",
+ "2044-04-04",
+ "2045-04-04",
+ "2046-04-04",
+ "2047-04-05",
+ "2048-04-04",
+ "2049-04-04",
+ ]
+)
+
+# Precomputed Buddha's Birthday dates on the Chinese Lunisolar Calendar.
+# Also called Buddha Shakyamuni day
+#
+# See Also
+# --------
+# exchange_calendars/etc/lunisolar china-buddhas-birthday
+#
+# Notes
+# -----
+# The holiday "Buddha's Birthday" is celebrated in many countries, though
+# different calendars are used. This function is for Buddha's Birthday on
+# the Chinese Lunisolar Calendar, where it is the 8th day of the 4th month.
+chinese_buddhas_birthday_dates = pd.DatetimeIndex(
+ [
+ "1959-05-15",
+ "1960-05-03",
+ "1961-05-22",
+ "1962-05-11",
+ "1963-05-01",
+ "1964-05-19",
+ "1965-05-08",
+ "1966-05-27",
+ "1967-05-16",
+ "1968-05-04",
+ "1969-05-23",
+ "1970-05-12",
+ "1971-05-02",
+ "1972-05-20",
+ "1973-05-10",
+ "1974-04-29",
+ "1975-05-18",
+ "1976-05-06",
+ "1977-05-25",
+ "1978-05-14",
+ "1979-05-03",
+ "1980-05-21",
+ "1981-05-11",
+ "1982-05-01",
+ "1983-05-20",
+ "1984-05-08",
+ "1985-05-27",
+ "1986-05-16",
+ "1987-05-05",
+ "1988-05-23",
+ "1989-05-12",
+ "1990-05-02",
+ "1991-05-21",
+ "1992-05-10",
+ "1993-05-28",
+ "1994-05-18",
+ "1995-05-07",
+ "1996-05-24",
+ "1997-05-14",
+ "1998-05-03",
+ "1999-05-22",
+ "2000-05-11",
+ "2001-04-30",
+ "2002-05-19",
+ "2003-05-08",
+ "2004-05-26",
+ "2005-05-15",
+ "2006-05-05",
+ "2007-05-24",
+ "2008-05-12",
+ "2009-05-02",
+ "2010-05-21",
+ "2011-05-10",
+ "2012-04-28",
+ "2013-05-17",
+ "2014-05-06",
+ "2015-05-25",
+ "2016-05-14",
+ "2017-05-03",
+ "2018-05-22",
+ "2019-05-12",
+ "2020-04-30",
+ "2021-05-19",
+ "2022-05-08",
+ "2023-05-26",
+ "2024-05-15",
+ "2025-05-05",
+ "2026-05-24",
+ "2027-05-13",
+ "2028-05-02",
+ "2029-05-20",
+ "2030-05-09",
+ "2031-05-28",
+ "2032-05-16",
+ "2033-05-06",
+ "2034-04-26",
+ "2035-05-15",
+ "2036-05-03",
+ "2037-05-22",
+ "2038-05-11",
+ "2039-04-30",
+ "2040-05-18",
+ "2041-05-07",
+ "2042-05-26",
+ "2043-05-16",
+ "2044-05-05",
+ "2045-05-24",
+ "2046-05-13",
+ "2047-05-02",
+ "2048-05-20",
+ "2049-05-09",
+ ]
+)
+
+# Precomputed Dragon Boat (Tuen Ng Festival) dates.
+# Also called "Duanwu"
+#
+# See Also
+# --------
+# exchange_calendars/etc/lunisolar dragon-boat-festival
+dragon_boat_festival_dates = pd.DatetimeIndex(
+ [
+ "1960-05-29",
+ "1961-06-17",
+ "1962-06-06",
+ "1963-06-25",
+ "1964-06-14",
+ "1965-06-04",
+ "1966-06-23",
+ "1967-06-12",
+ "1968-05-31",
+ "1969-06-19",
+ "1970-06-08",
+ "1971-05-28",
+ "1972-06-15",
+ "1973-06-05",
+ "1974-06-24",
+ "1975-06-14",
+ "1976-06-02",
+ "1977-06-21",
+ "1978-06-10",
+ "1979-05-30",
+ "1980-06-17",
+ "1981-06-06",
+ "1982-06-25",
+ "1983-06-15",
+ "1984-06-04",
+ "1985-06-22",
+ "1986-06-11",
+ "1987-06-01",
+ "1988-06-18",
+ "1989-06-08",
+ "1990-05-28",
+ "1991-06-16",
+ "1992-06-05",
+ "1993-06-24",
+ "1994-06-13",
+ "1995-06-02",
+ "1996-06-20",
+ "1997-06-09",
+ "1998-05-30",
+ "1999-06-18",
+ "2000-06-06",
+ "2001-06-25",
+ "2002-06-15",
+ "2003-06-04",
+ "2004-06-22",
+ "2005-06-11",
+ "2006-05-31",
+ "2007-06-19",
+ "2008-06-08",
+ "2009-05-28",
+ "2010-06-16",
+ "2011-06-06",
+ "2012-06-23",
+ "2013-06-12",
+ "2014-06-02",
+ "2015-06-20",
+ "2016-06-09",
+ "2017-05-30",
+ "2018-06-18",
+ "2019-06-07",
+ "2020-06-25",
+ "2021-06-14",
+ "2022-06-03",
+ "2023-06-22",
+ "2024-06-10",
+ "2025-05-31",
+ "2026-06-19",
+ "2027-06-09",
+ "2028-05-28",
+ "2029-06-16",
+ "2030-06-05",
+ "2031-06-24",
+ "2032-06-12",
+ "2033-06-01",
+ "2034-05-22",
+ "2035-06-10",
+ "2036-05-30",
+ "2037-06-18",
+ "2038-06-07",
+ "2039-05-27",
+ "2040-06-14",
+ "2041-06-03",
+ "2042-06-22",
+ "2043-06-11",
+ "2044-05-31",
+ "2045-06-19",
+ "2046-06-08",
+ "2047-05-29",
+ "2048-06-15",
+ "2049-06-04",
+ ]
+)
+
+
+# Precomputed Day after the Mid-Autumn Festival
+# Also called "Zhongqiu"
+#
+# See Also
+# --------
+# exchange_calendars/etc/lunisolar mid-autumn-festival
+mid_autumn_festival_dates = pd.DatetimeIndex(
+ [
+ "1960-10-05",
+ "1961-09-24",
+ "1962-09-13",
+ "1963-10-02",
+ "1964-09-20",
+ "1965-09-10",
+ "1966-09-29",
+ "1967-09-18",
+ "1968-10-06",
+ "1969-09-26",
+ "1970-09-15",
+ "1971-10-03",
+ "1972-09-22",
+ "1973-09-11",
+ "1974-09-30",
+ "1975-09-20",
+ "1976-09-08",
+ "1977-09-27",
+ "1978-09-17",
+ "1979-10-05",
+ "1980-09-23",
+ "1981-09-12",
+ "1982-10-01",
+ "1983-09-21",
+ "1984-09-10",
+ "1985-09-29",
+ "1986-09-18",
+ "1987-10-07",
+ "1988-09-25",
+ "1989-09-14",
+ "1990-10-03",
+ "1991-09-22",
+ "1992-09-11",
+ "1993-09-30",
+ "1994-09-20",
+ "1995-09-09",
+ "1996-09-27",
+ "1997-09-16",
+ "1998-10-05",
+ "1999-09-24",
+ "2000-09-12",
+ "2001-10-01",
+ "2002-09-21",
+ "2003-09-11",
+ "2004-09-28",
+ "2005-09-18",
+ "2006-10-06",
+ "2007-09-25",
+ "2008-09-14",
+ "2009-10-03",
+ "2010-09-22",
+ "2011-09-12",
+ "2012-09-30",
+ "2013-09-19",
+ "2014-09-08",
+ "2015-09-27",
+ "2016-09-15",
+ "2017-10-04",
+ "2018-09-24",
+ "2019-09-13",
+ "2020-10-01",
+ "2021-09-21",
+ "2022-09-10",
+ "2023-09-29",
+ "2024-09-17",
+ "2025-10-06",
+ "2026-09-25",
+ "2027-09-15",
+ "2028-10-03",
+ "2029-09-22",
+ "2030-09-12",
+ "2031-10-01",
+ "2032-09-19",
+ "2033-09-08",
+ "2034-08-28",
+ "2035-09-16",
+ "2036-10-04",
+ "2037-09-24",
+ "2038-09-13",
+ "2039-10-02",
+ "2040-09-20",
+ "2041-09-10",
+ "2042-09-28",
+ "2043-09-17",
+ "2044-10-05",
+ "2045-09-25",
+ "2046-09-15",
+ "2047-10-04",
+ "2048-09-22",
+ "2049-09-11",
+ ]
+)
+
+# Precomputed Double Ninth Festival (Chung Yeung Festival) dates.
+#
+# See Also
+# --------
+# exchange_calendars/etc/lunisolar double-ninth-festival
+double_ninth_festival_dates = pd.DatetimeIndex(
+ [
+ "1959-10-10",
+ "1960-10-28",
+ "1961-10-18",
+ "1962-10-07",
+ "1963-10-25",
+ "1964-10-14",
+ "1965-10-03",
+ "1966-10-22",
+ "1967-10-12",
+ "1968-10-30",
+ "1969-10-19",
+ "1970-10-08",
+ "1971-10-27",
+ "1972-10-15",
+ "1973-10-04",
+ "1974-10-23",
+ "1975-10-13",
+ "1976-10-31",
+ "1977-10-21",
+ "1978-10-10",
+ "1979-10-29",
+ "1980-10-17",
+ "1981-10-06",
+ "1982-10-25",
+ "1983-10-14",
+ "1984-10-03",
+ "1985-10-22",
+ "1986-10-12",
+ "1987-10-31",
+ "1988-10-19",
+ "1989-10-08",
+ "1990-10-26",
+ "1991-10-16",
+ "1992-10-04",
+ "1993-10-23",
+ "1994-10-13",
+ "1995-11-01",
+ "1996-10-20",
+ "1997-10-10",
+ "1998-10-28",
+ "1999-10-17",
+ "2000-10-06",
+ "2001-10-25",
+ "2002-10-14",
+ "2003-10-04",
+ "2004-10-22",
+ "2005-10-11",
+ "2006-10-30",
+ "2007-10-19",
+ "2008-10-07",
+ "2009-10-26",
+ "2010-10-16",
+ "2011-10-05",
+ "2012-10-23",
+ "2013-10-13",
+ "2014-10-02",
+ "2015-10-21",
+ "2016-10-09",
+ "2017-10-28",
+ "2018-10-17",
+ "2019-10-07",
+ "2020-10-25",
+ "2021-10-14",
+ "2022-10-04",
+ "2023-10-23",
+ "2024-10-11",
+ "2025-10-29",
+ "2026-10-18",
+ "2027-10-08",
+ "2028-10-26",
+ "2029-10-16",
+ "2030-10-05",
+ "2031-10-24",
+ "2032-10-12",
+ "2033-10-01",
+ "2034-09-21",
+ "2035-10-09",
+ "2036-10-27",
+ "2037-10-17",
+ "2038-10-07",
+ "2039-10-26",
+ "2040-10-14",
+ "2041-10-03",
+ "2042-10-22",
+ "2043-10-11",
+ "2044-10-29",
+ "2045-10-18",
+ "2046-10-08",
+ "2047-10-27",
+ "2048-10-16",
+ "2049-10-05",
+ ]
+)
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/__init__.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/holiday.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/holiday.py
new file mode 100644
index 0000000000000000000000000000000000000000..48da603fbb8ad6e41a4791abf4724c03e49f442e
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/holiday.py
@@ -0,0 +1,193 @@
+# https://github.com/pandas-dev/pandas/blob/master/pandas/tseries/holiday.py
+
+import warnings
+
+from pandas.tseries.holiday import (
+ Holiday as PandasHoliday,
+ AbstractHolidayCalendar as PandasAbstractHolidayCalendar,
+)
+from pandas.tseries.offsets import BaseOffset
+from pandas import (
+ DatetimeIndex,
+ Series,
+ Timestamp,
+)
+from pandas.errors import PerformanceWarning
+
+from .offsets import _is_normalized
+
+
+class Holiday(PandasHoliday):
+ """
+ This extension allows to have both offset and observance while the original
+ Holiday does not. The order of application is offset => observance.
+ """
+
+ def __init__(
+ self,
+ name,
+ year=None,
+ month=None,
+ day=None,
+ offset=None,
+ observance=None,
+ start_date=None,
+ end_date=None,
+ days_of_week=None,
+ tz=None,
+ ):
+ super().__init__(
+ name,
+ year,
+ month,
+ day,
+ None,
+ None,
+ start_date,
+ end_date,
+ days_of_week,
+ )
+ self.offset = offset
+ self.observance = observance
+ self.tz = tz
+ if self.start_date is not None:
+ if self.tz is None and self.start_date.tz is not None:
+ self.tz = start_date.tz
+ if self.start_date.tz is None and self.tz is not None:
+ self.start_date = self.start_date.tz_localize(self.tz)
+ assert self.tz == self.start_date.tz
+ if self.end_date is not None:
+ if self.tz is None and self.end_date.tz is not None:
+ self.tz = end_date.tz
+ if self.end_date.tz is None and self.tz is not None:
+ self.end_date = self.end_date.tz_localize(self.tz)
+ assert self.tz == self.end_date.tz
+ if self.start_date is not None and self.end_date is not None:
+ assert self.start_date.tz == self.end_date.tz
+
+ def __repr__(self) -> str:
+ info = ""
+ if self.year is not None:
+ info += f"year={self.year}, "
+ info += f"month={self.month}, day={self.day}"
+
+ if self.offset is not None:
+ info += f", offset={self.offset}"
+
+ if self.observance is not None:
+ info += f", observance={self.observance}"
+
+ repr = f"{self.__class__.__name__}: {self.name} ({info})"
+ return repr
+
+ def dates(self, start_date, end_date, return_name=False):
+ start_date = Timestamp(start_date)
+ end_date = Timestamp(end_date)
+ assert start_date.tz == self.tz
+ assert _is_normalized(start_date)
+ assert end_date.tz == self.tz
+ assert _is_normalized(end_date)
+ return super().dates(start_date, end_date, return_name=return_name)
+
+ def _apply_offset(self, dates):
+ if self.offset is not None:
+ if not isinstance(self.offset, list):
+ offsets = [self.offset]
+ else:
+ offsets = self.offset
+ for offset in offsets:
+ # If we are adding a non-vectorized value
+ # ignore the PerformanceWarnings:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", PerformanceWarning)
+ dates += offset
+ return dates
+
+ def _apply_observance(self, dates):
+ if self.observance is not None:
+ if not isinstance(self.observance, list):
+ observances = [self.observance]
+ else:
+ observances = self.observance
+ for observance in observances:
+ if isinstance(observance, BaseOffset):
+ offset = observance
+
+ def f(d):
+ return d + offset
+
+ observance = f
+ dates = dates.map(observance)
+ return dates
+
+ def _apply_rule(self, dates, apply_offset=True, apply_observance=True):
+ if apply_offset:
+ dates = self._apply_offset(dates)
+ if apply_observance:
+ dates = self._apply_observance(dates)
+ return dates
+
+
+def combine(pre_holidays):
+ combined = Series(index=DatetimeIndex([]), dtype=object)
+ for holidays in pre_holidays:
+ combined = combined.combine_first(holidays)
+ return combined
+
+
+class AbstractHolidayCalendar(PandasAbstractHolidayCalendar):
+ """
+ This extension allows to have overlaps between calculated holidays while
+ the original AbstractHolidayCalendar does not.
+ """
+
+ def holidays(self, start=None, end=None, return_name=False):
+ """
+ Returns a curve with holidays between start_date and end_date
+ Parameters
+ ----------
+ start : starting date, datetime-like, optional
+ end : ending date, datetime-like, optional
+ return_name : bool, optional
+ If True, return a series that has dates and holiday names.
+ False will only return a DatetimeIndex of dates.
+ Returns
+ -------
+ DatetimeIndex of holidays
+ """
+ if self.rules is None:
+ raise Exception(
+ f"Holiday Calendar {self.name} does not have any rules specified"
+ )
+
+ if start is None:
+ start = AbstractHolidayCalendar.start_date
+
+ if end is None:
+ end = AbstractHolidayCalendar.end_date
+
+ start = Timestamp(start)
+ end = Timestamp(end)
+
+ # If we don't have a cache or the dates are outside the prior cache, we
+ # get them again
+ if self._cache is None or start < self._cache[0] or end > self._cache[1]:
+ pre_holidays = [
+ rule.dates(start, end, return_name=True) for rule in self.rules
+ ]
+ if pre_holidays:
+ # This line's behavior is changed to use custom combine()
+ # function instead of the original concat() function
+ holidays = combine(pre_holidays)
+ else:
+ holidays = Series(index=DatetimeIndex([]), dtype=object)
+
+ self._cache = (start, end, holidays.sort_index())
+
+ holidays = self._cache[2]
+ holidays = holidays[start:end]
+
+ if return_name:
+ return holidays
+ else:
+ return holidays.index
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/korean_holiday.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/korean_holiday.py
new file mode 100644
index 0000000000000000000000000000000000000000..cad1b9ac92210b1aa156900178fe404bf304c195
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/korean_holiday.py
@@ -0,0 +1,238 @@
+import datetime
+import pandas as pd
+from zoneinfo import ZoneInfo
+
+from pandas.tseries.offsets import Day
+from korean_lunar_calendar import KoreanLunarCalendar
+
+from .holiday import Holiday
+from .offsets import _is_normalized
+
+
+def is_naive(dt):
+ return dt.tzinfo is None
+
+
+class KoreanHoliday(Holiday):
+ _timezone = ZoneInfo("Asia/Seoul")
+ _local_timezone = datetime.datetime.now().astimezone().tzinfo
+
+ _computed_holidays = pd.Series([], index=pd.DatetimeIndex([]), dtype=object)
+ _alternate_holidays_cache = pd.Series(
+ pd.DatetimeIndex([]),
+ index=pd.DatetimeIndex([]),
+ )
+
+ def _apply_rule(
+ self, dates, apply_offset=True, apply_observance=True, register_holidays=True
+ ):
+ dates = super()._apply_rule(dates, apply_offset, apply_observance)
+ if register_holidays:
+ for date in dates:
+ assert is_naive(date)
+ assert _is_normalized(date)
+ if date not in KoreanHoliday._computed_holidays.index:
+ KoreanHoliday._computed_holidays[date] = self
+ return dates
+
+
+def to_korean_datetime(dt):
+ dt = pd.to_datetime(dt)
+ if dt.tz is None:
+ dt = dt.tz_localize(KoreanHoliday._local_timezone)
+ dt = dt.tz_convert(KoreanHoliday._timezone)
+ return dt
+
+
+def is_saturday(dt):
+ return dt.weekday() == 5
+
+
+def is_sunday(dt):
+ return dt.weekday() == 6
+
+
+def is_holiday_saturday(dt):
+ is_holiday_since = pd.Timestamp("1998-12-07")
+ return dt >= is_holiday_since.tz_localize(dt.tzinfo) and is_saturday(dt)
+
+
+def is_already_korean_holiday(dt):
+ dt = pd.Timestamp(dt).tz_localize(None).normalize()
+ return dt in KoreanHoliday._computed_holidays
+
+
+original_alternative_holiday_since = pd.Timestamp(
+ "2014-01-01"
+) # alternative holidays have been applied since year 2014
+revised_alternative_holiday_since = pd.Timestamp(
+ "2021-08-04"
+) # and expanded since 2021-08-04
+
+
+def alternative_holiday_func(dt, is_already_holiday, since):
+ if dt >= since:
+ dt = pd.Timestamp(dt)
+ dt_tzinfo = dt.tzinfo
+ key_dt = dt.tz_localize(None).normalize()
+ time_offset = dt.tz_localize(None) - key_dt
+ if key_dt not in KoreanHoliday._alternate_holidays_cache.index:
+ while is_already_holiday(dt):
+ dt += Day(1)
+ value_dt = dt.tz_localize(None).normalize()
+ KoreanHoliday._alternate_holidays_cache[key_dt] = value_dt
+ dt = KoreanHoliday._alternate_holidays_cache[key_dt]
+ dt = dt + time_offset
+ dt = dt.tz_localize(dt_tzinfo)
+ return dt
+
+
+def is_already_holiday(dt):
+ return is_holiday_saturday(dt) or is_sunday(dt) or is_already_korean_holiday(dt)
+
+
+def is_already_holiday_for_alternative_holiday_including_saturday(dt):
+ # originally since 2014
+ # 1. Children's Day
+ # added since 2021-08-04
+ # 2. Independence Movement Day
+ # 3. National Liberation Day
+ # 4. Korean National Foundation Day
+ # 5. Hangul Proclamation Day
+ return is_saturday(dt) or is_sunday(dt) or is_already_korean_holiday(dt)
+
+
+def is_already_holiday_for_alternative_holiday_without_saturday(dt):
+ # originally since 2014
+ # 1. Seollal
+ # 2. Chuseok
+ return is_sunday(dt) or is_already_korean_holiday(dt)
+
+
+def alternative_holiday_for_seollal_and_chuseok(dt):
+ return alternative_holiday_func(
+ dt,
+ is_already_holiday_for_alternative_holiday_without_saturday,
+ original_alternative_holiday_since,
+ )
+
+
+def alternative_holiday_for_childrens_day(dt):
+ return alternative_holiday_func(
+ dt,
+ is_already_holiday_for_alternative_holiday_including_saturday,
+ original_alternative_holiday_since,
+ )
+
+
+def alternative_holiday(dt):
+ return alternative_holiday_func(
+ dt,
+ is_already_holiday_for_alternative_holiday_including_saturday,
+ revised_alternative_holiday_since,
+ )
+
+
+def next_business_day(dt):
+ while is_already_holiday(dt):
+ dt += Day(1)
+ return dt
+
+
+def last_business_day(dt):
+ while is_already_holiday(dt):
+ dt -= Day(1)
+ return dt
+
+
+class KoreanSolarHoliday(KoreanHoliday):
+ pass
+
+
+def korean_lunar_to_solar(year, month, day, is_intercalation=False):
+ calendar = KoreanLunarCalendar()
+ is_valid = calendar.setLunarDate(year, month, day, is_intercalation)
+ if not is_valid:
+ raise ValueError(
+ "Invalid date for lunar date: (year=%r, month=%r, day=%r, is_intercalation=%r)"
+ % (year, month, day, is_intercalation)
+ )
+ return (calendar.solarYear, calendar.solarMonth, calendar.solarDay)
+
+
+def korean_lunar_to_solar_datetime(dt, is_intercalation=False):
+ year, month, day = korean_lunar_to_solar(
+ dt.year, dt.month, dt.day, is_intercalation=is_intercalation
+ )
+ return dt.replace(year, month, day)
+
+
+def korean_solar_to_lunar(year, month, day):
+ calendar = KoreanLunarCalendar()
+ is_valid = calendar.setSolarDate(year, month, day)
+ if not is_valid:
+ raise ValueError(
+ "Invalid date for solar date: (year=%r, month=%r, day=%r)"
+ % (year, month, day)
+ )
+ return (calendar.lunarYear, calendar.lunarMonth, calendar.lunarDay)
+
+
+def korean_solar_to_lunar_datetime(dt, round_down: bool):
+ """This method sets the year, month and day fields on a pd.Timestamp to the equivalent lunar ones.
+
+ The problem is that not all lunar calendar dates can be stored in a Gregorian date.
+ For example, 2022-03-31 (Gregorian) corresponds to 2022-02-29 (Korean lunar). The latter
+ is not a valid Gregorian date. So, we introduce a rounding flag. If round_down is True,
+ then this method will decrement the solar date until the lunar date happens to be a valid
+ Gregorian one. If round_down is False, then the solar date will be incremented analogously.
+ """
+ while True:
+ year, month, day = korean_solar_to_lunar(dt.year, dt.month, dt.day)
+ try:
+ datetime.date(year, month, day)
+ return dt.replace(year, month, day)
+ except ValueError:
+ dt += datetime.timedelta(days=-1 if round_down else 1)
+
+
+class KoreanLunarHoliday(KoreanHoliday):
+ _max_solar_end_date = pd.to_datetime(
+ str(KoreanLunarCalendar.KOREAN_SOLAR_MAX_VALUE), format="%Y%m%d"
+ )
+ _max_lunar_end_date = pd.to_datetime(
+ str(KoreanLunarCalendar.KOREAN_LUNAR_MAX_VALUE), format="%Y%m%d"
+ )
+
+ def _reference_dates(self, start_date, end_date, strict=False):
+ solar_start_date = start_date
+ solar_end_date = end_date
+
+ # Restrict date range to fall into supported range of korean_lunar_calendar library
+ if solar_end_date > self._max_solar_end_date:
+ if not strict and solar_start_date < self._max_solar_end_date:
+ solar_end_date = self._max_solar_end_date
+ else:
+ raise ValueError(
+ "Cannot support date range after %r, but %r ~ %r given"
+ % (self._max_solar_end_date, start_date, end_date)
+ )
+
+ # Get lunar reference dates
+ lunar_start_date = korean_solar_to_lunar_datetime(
+ solar_start_date, round_down=True
+ )
+ lunar_end_date = korean_solar_to_lunar_datetime(
+ solar_end_date, round_down=False
+ )
+ dates = super()._reference_dates(lunar_start_date, lunar_end_date)
+
+ # Still restrict date range to fall into supported range of korean_lunar_calendar library
+ dates = dates[dates <= self._max_lunar_end_date]
+
+ # Convert lunar dates to solar dates
+ dates = dates.to_series()
+ dates = dates.map(korean_lunar_to_solar_datetime)
+ dates = pd.DatetimeIndex(dates)
+
+ return dates[(dates >= start_date) & (dates < end_date)]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/offsets.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/offsets.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef8626a14244eaee5145e563ac7456a969a05b71
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/pandas_extensions/offsets.py
@@ -0,0 +1,306 @@
+# https://github.com/pandas-dev/pandas/blob/master/pandas/tseries/offsets.py
+# https://github.com/pandas-dev/pandas/blob/master/pandas/_libs/tslibs/offsets.pyx
+
+from datetime import datetime, timedelta
+
+import toolz
+import numpy as np
+import pandas as pd
+
+from pandas.tseries.offsets import CustomBusinessDay
+from pandas._libs.tslibs.offsets import apply_wraps
+
+
+class CompositeCustomBusinessDay(CustomBusinessDay):
+
+ _prefix = "C"
+ _attributes = tuple(
+ [
+ "n",
+ "normalize",
+ "weekmask",
+ "holidays",
+ "calendar",
+ "offset",
+ "business_days",
+ ]
+ )
+
+ def __init__(
+ self,
+ n=1,
+ normalize=False,
+ weekmask="Mon Tue Wed Thu Fri",
+ holidays=None,
+ calendar=None,
+ offset=timedelta(0),
+ business_days=None,
+ ):
+ CustomBusinessDay.__init__(
+ self, n, normalize, weekmask, holidays, calendar, offset
+ )
+ self.business_days = business_days
+
+ def __setstate__(self, state):
+ self.business_days = state.pop("business_days")
+ CustomBusinessDay.__setstate__(self, state)
+
+ @property
+ def business_days(self):
+ """
+ Returns list of tuples of (start_date, end_date, custom_business_day)
+ which overrides default behavior for the given interval, which starts
+ from start_date to end_date, inclusive in both sides.
+ """
+ return tuple(self._business_days)
+
+ @business_days.setter
+ def business_days(self, business_days):
+ self._business_days = []
+ self._business_days_index = pd.IntervalIndex([], closed="both")
+ self._business_days_all_index = pd.IntervalIndex([], closed="both")
+ if business_days is not None:
+ self._business_days = business_days
+ business_days_intervals = []
+ for start_date, end_date, _ in self._business_days:
+ if start_date is None:
+ start_date = pd.Timestamp.min
+ else:
+ start_date = pd.Timestamp(start_date)
+ if end_date is None:
+ end_date = pd.Timestamp.max
+ else:
+ end_date = pd.Timestamp(end_date)
+ interval = pd.Interval(start_date, end_date, closed="both")
+ business_days_intervals.append(interval)
+ self._business_days_index = pd.IntervalIndex(
+ business_days_intervals, closed="both"
+ )
+ business_days_all_intervals = []
+ right = self._business_days_index[0]
+ if pd.Timestamp.min < right.left:
+ interval = pd.Interval(
+ pd.Timestamp.min, right.left - pd.Timedelta(1, unit="D")
+ )
+ business_days_all_intervals.append(interval)
+ business_days_all_intervals.append(right)
+ for left, right in toolz.sliding_window(
+ 2, toolz.concatv(self._business_days_index)
+ ):
+ if right.left - left.right > pd.Timestamp(1, unit="D"):
+ interval = pd.Interval(
+ left.right + pd.Timedelta(1, unit="D"),
+ right.left - pd.Timedelta(1, unit="D"),
+ )
+ business_days_all_intervals.append(interval)
+ business_days_all_intervals.append(right)
+ left = self._business_days_index[-1]
+ if left.right < pd.Timestamp.max:
+ interval = pd.Interval(
+ left.right + pd.Timedelta(1, unit="D"), pd.Timestamp.max
+ )
+ business_days_all_intervals.append(interval)
+ self._business_days_all_index = pd.IntervalIndex(
+ business_days_all_intervals, closed="both"
+ )
+
+ def _as_custom_business_day(self):
+ return CustomBusinessDay(
+ self.n,
+ self.normalize,
+ self.weekmask,
+ self.holidays,
+ self.calendar,
+ self.offset,
+ )
+
+ def _custom_business_day_for(
+ self, other, n=None, is_edge=False, with_interval=False
+ ):
+ loc = self._business_days_all_index.get_loc(other)
+ if is_edge and n is not None:
+ loc += np.sign(n)
+ interval = self._business_days_all_index[loc]
+ try:
+ loc = self._business_days_index.get_loc(interval.left)
+ except KeyError:
+ bday = self._as_custom_business_day()
+ else:
+ bday = self._business_days[loc][-1]
+ if n is not None:
+ bday = bday.base * n
+ if with_interval:
+ return bday, interval
+ else:
+ return bday
+
+ def _moved(self, from_date, to_date, bday):
+ return np.busday_count(
+ np.datetime64(from_date.date()),
+ np.datetime64(to_date.date()),
+ busdaycal=bday.calendar,
+ )
+
+ @apply_wraps
+ def _apply(self, other):
+ if isinstance(other, datetime):
+ moved = 0
+ remaining = self.n - moved
+ bday, interval = self._custom_business_day_for(
+ other, remaining, with_interval=True
+ )
+ result = bday + other
+ while not interval.left <= result <= interval.right:
+ previous_other = other
+ if result < interval.left:
+ other = interval.left
+ elif result > interval.right:
+ other = interval.right
+ else:
+ raise RuntimeError("Should not reach here")
+ moved += self._moved(previous_other, other, bday)
+ remaining = self.n - moved
+ if remaining == 0:
+ break
+ bday, interval = self._custom_business_day_for(
+ other, remaining, is_edge=True, with_interval=True
+ )
+ result = bday.apply(other)
+ return result
+ else:
+ return super().apply(other)
+
+ # backwards compat
+ apply = _apply
+
+ def is_on_offset(self, dt):
+ if self.normalize and not _is_normalized(dt):
+ return False
+ day64 = _to_dt64D(dt)
+ bday = self._custom_business_day_for(day64)
+ return np.is_busday(day64, busdaycal=bday.calendar)
+
+
+def _is_normalized(dt):
+ if dt.hour != 0 or dt.minute != 0 or dt.second != 0 or dt.microsecond != 0:
+ # Regardless of whether dt is datetime vs Timestamp
+ return False
+ if isinstance(dt, pd.Timestamp):
+ return dt.nanosecond == 0
+ return True
+
+
+def _to_dt64D(dt):
+ # Currently
+ # > np.datetime64(dt.datetime(2013,5,1),dtype='datetime64[D]')
+ # numpy.datetime64('2013-05-01T02:00:00.000000+0200')
+ # Thus astype is needed to cast datetime to datetime64[D]
+ if getattr(dt, "tzinfo", None) is not None:
+ # Get the nanosecond timestamp,
+ # equiv `Timestamp(dt).value` or `dt.timestamp() * 10**9`
+ dt = pd.Timestamp(dt).value
+ dt = np.int64(dt).astype("datetime64[ns]")
+ else:
+ dt = np.datetime64(dt)
+ if dt.dtype.name != "datetime64[D]":
+ dt = dt.astype("datetime64[D]")
+ return dt
+
+
+def _get_calendar(weekmask, holidays, calendar):
+ """
+ Generate busdaycalendar
+ """
+ if isinstance(calendar, np.busdaycalendar):
+ if not holidays:
+ holidays = tuple(calendar.holidays)
+ elif not isinstance(holidays, tuple):
+ holidays = tuple(holidays)
+ else:
+ # Trust that calendar.holidays and holidays are
+ # consistent
+ pass
+ # Update weekmask if applicable (added)
+ calendar = np.busdaycalendar(weekmask, holidays)
+ return calendar, holidays
+
+ if holidays is None:
+ holidays = []
+ # Handle non list holidays also (added)
+ if isinstance(holidays, pd.DatetimeIndex):
+ holidays = holidays.tolist()
+ try:
+ holidays = holidays + calendar.holidays().tolist()
+ except AttributeError:
+ pass
+ holidays = [_to_dt64D(dt) for dt in holidays]
+ holidays = tuple(sorted(holidays))
+
+ kwargs = {"weekmask": weekmask}
+ if holidays:
+ kwargs["holidays"] = holidays
+
+ busdaycalendar = np.busdaycalendar(**kwargs)
+ return busdaycalendar, holidays
+
+
+class MultipleWeekmaskCustomBusinessDay(CompositeCustomBusinessDay):
+
+ _prefix = "C"
+ _attributes = tuple(
+ [
+ "n",
+ "normalize",
+ "weekmask",
+ "holidays",
+ "calendar",
+ "offset",
+ "business_days",
+ "weekmasks",
+ ]
+ )
+
+ def __init__(
+ self,
+ n=1,
+ normalize=False,
+ weekmask="Mon Tue Wed Thu Fri",
+ holidays=None,
+ calendar=None,
+ offset=timedelta(0),
+ business_days=None,
+ weekmasks=None,
+ ):
+ self._weekmasks = weekmasks
+ if business_days is None and weekmasks is not None:
+ calendars = [
+ _get_calendar(weekmask=weekmask, holidays=holidays, calendar=calendar)
+ for _start_date, _end_date, weekmask in weekmasks
+ ]
+ business_days = [
+ (
+ start_date,
+ end_date,
+ CustomBusinessDay(
+ n, normalize, weekmask, holidays, calendar, offset
+ ),
+ )
+ for (start_date, end_date, weekmask), (calendar, holidays) in zip(
+ weekmasks, calendars
+ )
+ ]
+ CompositeCustomBusinessDay.__init__(
+ self, n, normalize, weekmask, holidays, calendar, offset, business_days
+ )
+
+ def __setstate__(self, state):
+ self.weekmasks = state.pop("weekmasks")
+ CompositeCustomBusinessDay.__setstate__(self, state)
+
+ @property
+ def weekmasks(self):
+ return tuple(self._weekmasks)
+
+ @weekmasks.setter
+ def weekmasks(self, weekmasks):
+ self._weekmasks = weekmasks
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/precomputed_exchange_calendar.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/precomputed_exchange_calendar.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d937ce51941bc50b95ab151605b87fd3e78ee75
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/precomputed_exchange_calendar.py
@@ -0,0 +1,56 @@
+from __future__ import annotations
+from abc import abstractmethod
+
+import numpy as np
+import pandas as pd
+
+from .exchange_calendar import ExchangeCalendar
+
+
+class PrecomputedExchangeCalendar(ExchangeCalendar):
+ """
+ Used to model an exchange calendar whose holidays inlcude holidays that
+ are precomputed and hardcoded.
+ """
+
+ @abstractmethod
+ def precomputed_holidays(cls) -> pd.DatetimeIndex | list[pd.Timestamp]:
+ """Precomputed holidays.
+
+ Subclass should implement as a classmethod.
+ """
+ raise NotImplementedError()
+
+ @property
+ def adhoc_holidays(self) -> pd.DatetimeIndex | list[pd.Timestamp]:
+ return self.precomputed_holidays()
+
+ @classmethod
+ def _earliest_precomputed_year(cls) -> int:
+ return np.min(cls.precomputed_holidays()).year
+
+ @classmethod
+ def _latest_precomputed_year(cls) -> int:
+ return np.max(cls.precomputed_holidays()).year
+
+ @classmethod
+ def bound_min(cls) -> pd.Timestamp:
+ return pd.Timestamp(f"{cls._earliest_precomputed_year()}-01-01")
+
+ @classmethod
+ def bound_max(cls) -> pd.Timestamp:
+ return pd.Timestamp(f"{cls._latest_precomputed_year()}-12-31")
+
+ def _bound_min_error_msg(self, start: pd.Timestamp) -> str:
+ return (
+ f"The {self.name} holidays are only recorded back to the year"
+ f" {self._earliest_precomputed_year()}, cannot instantiate the"
+ f" {self.name} calendar from {start}."
+ )
+
+ def _bound_max_error_msg(self, end: pd.Timestamp) -> str:
+ return (
+ f"The {self.name} holidays are only recorded to the year"
+ f" {self._latest_precomputed_year()}, cannot instantiate the"
+ f" {self.name} calendar through to {end}."
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/tase_holidays.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/tase_holidays.py
new file mode 100644
index 0000000000000000000000000000000000000000..998c726d608ed420abc40f9c2cd6fe98d099f517
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/tase_holidays.py
@@ -0,0 +1,423 @@
+from datetime import date, datetime
+
+import pandas as pd
+from pandas._libs.tslibs.conversion import localize_pydatetime
+from pandas.tseries.holiday import Day, Holiday
+from pandas.tseries.offsets import Easter
+from pyluach import dates, hebrewcal
+
+try:
+ from pandas._libs.tslibs.offsets import apply_wraps
+except ImportError:
+ from pandas.tseries.offsets import apply_wraps
+
+# Auxiliary functions to get Hebrew dates for holidays observed by TASE for a
+# given Hebrew calendar year. These are just the raw dates with no adjustments
+# applied.
+#
+# Note: pyluach uses the biblical month numbering scheme where the year is
+# incremented when moving from the month of Elul (6) to Tishrei (7). See also
+# https://en.wikipedia.org/wiki/Hebrew_calendar.
+
+
+def _purim(year):
+ """
+ Return the Hebrew date for Purim in the given Hebrew year.
+ """
+ # Purim is observed in Adar (12), or Adar II (13) if in a leap year.
+ return dates.HebrewDate(year.year, 13 if year.leap else 12, 14)
+
+
+def _passover(year):
+ """
+ Return the Hebrew date for the first day of Passover in the given Hebrew
+ year.
+ """
+ return dates.HebrewDate(year.year, 1, 15)
+
+
+def _memorial_day(year):
+ """
+ Return the Hebrew date for Memorial Day in the given Hebrew year.
+
+ If either Memorial Day (MD) or Independence Day (ID) were to interfere with Sabbat,
+ including night before, then they are shifted forward or backward to avoid Sabbat.
+ ID always celebrated day after MD.
+ Wiki: https://en.wikipedia.org/wiki/Yom_HaZikaron#Timing
+ Better explanation: https://ph.yhb.org.il/en/05-04-09
+ """
+ d = dates.HebrewDate(year.year, 2, 4)
+ if d.weekday() == 1:
+ # MD on Sunday => shift forward to Monday
+ d = dates.HebrewDate(year.year, 2, 5)
+ elif d.weekday() == 6:
+ # MD on Friday => ID on Sabbat => shift back 2 days
+ d = dates.HebrewDate(year.year, 2, 2)
+ elif d.weekday() == 5:
+ # MD on Thursday => ID night before Sabbat => shift back 1 day
+ d = dates.HebrewDate(year.year, 2, 3)
+
+ return d
+
+
+def _pentecost(year):
+ """
+ Return the Hebrew date for Pentecost in the given Hebrew year.
+ """
+ return dates.HebrewDate(year.year, 3, 6)
+
+
+def _fast_day(year):
+ """
+ Return the Hebrew date for Tisha B'Av in the given Hebrew year.
+ """
+ return dates.HebrewDate(year.year, 5, 9)
+
+
+def _new_year(year):
+ """
+ Return the Hebrew date for the first day of a new year in the given Hebrew
+ year.
+ """
+ return dates.HebrewDate(year.year, 7, 1)
+
+
+def _yom_kippur(year):
+ """
+ Return the Hebrew date for Yom Kippur in the given Hebrew year.
+ """
+ return dates.HebrewDate(year.year, 7, 10)
+
+
+def _sukkoth(year):
+ """
+ Return the Hebrew date for Sukkoth in the given Hebrew year.
+ """
+ return dates.HebrewDate(year.year, 7, 15)
+
+
+def _simchat_torah(year):
+ """
+ Return the Hebrew date for Simchat Torah in the given Hebrew year.
+ """
+ return dates.HebrewDate(year.year, 7, 22)
+
+
+def _hebrew_year(year):
+ """
+ Return the Hebrew calendar year that corresponds to 1st January of the
+ given Gregorian calendar year.
+
+ 1st January of any Gregorian calendar year, say x, always falls into the
+ month of Tevet (10) or Shevat (11) of some Hebrew year f(x). Also, we have
+ f(x+1) = f(x) + 1, so that any year in the Gregorian calendar always
+ overlaps with two consecutive years in the Hebrew calendar and vice versa.
+ """
+ return hebrewcal.Year(dates.GregorianDate(year, 1, 1).to_heb().year)
+
+
+# Auxilliary functions to calculate Gregorian dates for holidays observed by
+# TASE for a given Gregorian calendar year. Adjustments are also applied.
+
+
+def purim(year):
+ """
+ Return the Gregorian date for Purim in the given Gregorian calendar year.
+ """
+ return _purim(_hebrew_year(year)).to_greg()
+
+
+def passover(year):
+ """
+ Return the Gregorian date for the first day of Passover in the given
+ Gregorian calendar year.
+ """
+ return _passover(_hebrew_year(year)).to_greg()
+
+
+def memorial_day(year):
+ """
+ Return the Gregorian date for Memorial Day in the given Gregorian calendar
+ year.
+ """
+
+ # Regular Memorial Day date.
+ d = _memorial_day(_hebrew_year(year)).to_greg()
+
+ # Reschedule to avoid Sabbath desecration, maybe.
+ if d.weekday() == 5:
+ # Falls on a Thursday, so Independency Day falls on the Friday.
+ # Moved down by one day.
+ return d - 1
+ elif d.weekday() == 6:
+ # Falls on a Friday, so Independence Day falls on the Saturday.
+ # Moved down by two days.
+ return d - 2
+ elif d.weekday() == 7:
+ # Falls on a Saturday, therefore moved up by one day.
+ return d + 1
+ else:
+ return d
+
+
+def pentecost(year):
+ """
+ Return the Gregorian date for Pentecost in the given Gregorian calendar
+ year.
+ """
+ return _pentecost(_hebrew_year(year)).to_greg()
+
+
+def fast_day(year):
+ """
+ Return the Gregorian date for Tisha B'Av in the given Gregorian calendar
+ year.
+ """
+ d = _fast_day(_hebrew_year(year)).to_greg()
+
+ # Reschedule if it falls on Sabbath (Saturday), maybe.
+ if d.weekday() == 7:
+ # Falls on a Saturday, therefore moved up by one day.
+ return d + 1
+ else:
+ return d
+
+
+def new_year(year):
+ """
+ Return the Gregorian date for the first day of a new year in the given
+ Gregorian calendar year.
+ """
+ return _new_year(_hebrew_year(year + 1)).to_greg()
+
+
+def yom_kippur(year):
+ """
+ Return the Gregorian date for Yom Kippur in the given Gregorian calendar
+ year.
+ """
+ return _yom_kippur(_hebrew_year(year + 1)).to_greg()
+
+
+def sukkoth(year):
+ """
+ Return the Gregorian date for Sukkoth in the given Gregorian calendar year.
+ """
+ return _sukkoth(_hebrew_year(year + 1)).to_greg()
+
+
+def simchat_torah(year):
+ """
+ Return the Gregorian date for Simchat Torah in the given Gregorian calendar
+ year.
+ """
+ return _simchat_torah(_hebrew_year(year + 1)).to_greg()
+
+
+def _is_normalized(dt):
+ if dt.hour != 0 or dt.minute != 0 or dt.second != 0 or dt.microsecond != 0:
+ # Regardless of whether dt is datetime vs Timestamp
+ return False
+ if isinstance(dt, pd.Timestamp):
+ return dt.nanosecond == 0
+ return True
+
+
+class _HolidayOffset(Easter):
+ """
+ Auxiliary class for DateOffset instances for the different holidays.
+ """
+
+ @property
+ def holiday(self):
+ """
+ Return the Gregorian date for the holiday in a given Gregorian calendar
+ year.
+ """
+ pass
+
+ @apply_wraps
+ def _apply(self, other):
+ current = self.holiday(other.year).to_pydate()
+ current = datetime(current.year, current.month, current.day)
+ current = localize_pydatetime(current, other.tzinfo)
+
+ n = self.n
+ if n >= 0 and other < current:
+ n -= 1
+ elif n < 0 and other > current:
+ n += 1
+ # TODO: Why does this handle the 0 case the opposite of others?
+
+ # NOTE: self.holiday a dates.GregorianDate so we have to convert to
+ # type of other
+ new = self.holiday(other.year + n).to_pydate()
+ new = datetime(
+ new.year,
+ new.month,
+ new.day,
+ other.hour,
+ other.minute,
+ other.second,
+ other.microsecond,
+ )
+ return new
+
+ # backwards compat
+ apply = _apply
+
+ def is_on_offset(self, dt):
+ if self.normalize and not _is_normalized(dt):
+ return False
+ return date(dt.year, dt.month, dt.day) == self.holiday(dt.year).to_pydate()
+
+
+# DateOffset subclasses for holidays observed by TASE.
+
+
+class _Purim(_HolidayOffset):
+ @property
+ def holiday(self):
+ return purim
+
+
+class _Passover(_HolidayOffset):
+ @property
+ def holiday(self):
+ return passover
+
+
+class _MemorialDay(_HolidayOffset):
+ @property
+ def holiday(self):
+ return memorial_day
+
+
+class _Pentecost(_HolidayOffset):
+ @property
+ def holiday(self):
+ return pentecost
+
+
+class _FastDay(_HolidayOffset):
+ @property
+ def holiday(self):
+ return fast_day
+
+
+class _NewYear(_HolidayOffset):
+ @property
+ def holiday(self):
+ return new_year
+
+
+class _YomKippur(_HolidayOffset):
+ @property
+ def holiday(self):
+ return yom_kippur
+
+
+class _Sukkoth(_HolidayOffset):
+ @property
+ def holiday(self):
+ return sukkoth
+
+
+class _SimchatTorah(_HolidayOffset):
+ @property
+ def holiday(self):
+ return simchat_torah
+
+
+# Holiday instances for holidays observed by TASE.
+Purim = Holiday("Purim", month=1, day=1, offset=[_Purim()])
+PassoverEve = Holiday("Passover Eve", month=1, day=1, offset=[_Passover(), Day(-1)])
+Passover = Holiday("Passover", month=1, day=1, offset=[_Passover()])
+Passover2Eve = Holiday("Passover II Eve", month=1, day=1, offset=[_Passover(), Day(5)])
+Passover2 = Holiday("Passover II", month=1, day=1, offset=[_Passover(), Day(6)])
+PentecostEve = Holiday("Pentecost Eve", month=1, day=1, offset=[_Pentecost(), Day(-1)])
+Pentecost = Holiday("Pentecost", month=1, day=1, offset=[_Pentecost()])
+FastDay = Holiday("Tisha B'Av", month=1, day=1, offset=[_FastDay()])
+MemorialDay = Holiday("Memorial Day", month=1, day=1, offset=[_MemorialDay()])
+IndependenceDay = Holiday(
+ "Independence Day", month=1, day=1, offset=[_MemorialDay(), Day(1)]
+)
+NewYearsEve = Holiday("New Year's Eve", month=1, day=1, offset=[_NewYear(), Day(-1)])
+NewYear = Holiday("New Year", month=1, day=1, offset=[_NewYear()])
+NewYear2 = Holiday("New Year II", month=1, day=1, offset=[_NewYear(), Day(1)])
+YomKippurEve = Holiday("Yom Kippur Eve", month=1, day=1, offset=[_YomKippur(), Day(-1)])
+YomKippur = Holiday("Yom Kippur", month=1, day=1, offset=[_YomKippur()])
+SukkothEve = Holiday("Sukkoth Eve", month=1, day=1, offset=[_Sukkoth(), Day(-1)])
+Sukkoth = Holiday("Sukkoth", month=1, day=1, offset=[_Sukkoth()])
+SimchatTorahEve = Holiday(
+ "Simchat Torah Eve", month=1, day=1, offset=[_SimchatTorah(), Day(-1)]
+)
+SimchatTorah = Holiday("Simchat Torah", month=1, day=1, offset=[_SimchatTorah()])
+
+# Sukkoth interim days - the 3 days following Sukkoth
+SukkothInterimDay1 = Holiday(
+ "Sukkoth Interim Day",
+ month=1,
+ day=1,
+ offset=[_Sukkoth(), Day(1)],
+ days_of_week=(0, 1, 2, 3, 6)
+)
+SukkothInterimDay2 = Holiday(
+ "Sukkoth Interim Day",
+ month=1,
+ day=1,
+ offset=[_Sukkoth(), Day(2)],
+ days_of_week=(0, 1, 2, 3, 6)
+)
+SukkothInterimDay3 = Holiday(
+ "Sukkoth Interim Day",
+ month=1,
+ day=1,
+ offset=[_Sukkoth(), Day(3)],
+ days_of_week=(0, 1, 2, 3, 6)
+)
+SukkothInterimDay4 = Holiday(
+ "Sukkoth Interim Day",
+ month=1,
+ day=1,
+ offset=[_Sukkoth(), Day(4)],
+ days_of_week=(0, 1, 2, 3, 6)
+)
+SukkothInterimDay5 = Holiday(
+ "Sukkoth Interim Day",
+ month=1,
+ day=1,
+ offset=[_Sukkoth(), Day(5)],
+ days_of_week=(0, 1, 2, 3, 6)
+)
+
+# Passover interim days are the days between beginning and end of passover. Any otherwise regular business day in that
+# period becomes an early close day.
+PassoverInterimDay1 = Holiday(
+ "Passover Interim Day",
+ month=1,
+ day=1,
+ offset=[_Passover(), Day(1)],
+ days_of_week=(0, 1, 2, 3, 6),
+)
+PassoverInterimDay2 = Holiday(
+ "Passover Interim Day",
+ month=1,
+ day=1,
+ offset=[_Passover(), Day(2)],
+ days_of_week=(0, 1, 2, 3, 6),
+)
+PassoverInterimDay3 = Holiday(
+ "Passover Interim Day",
+ month=1,
+ day=1,
+ offset=[_Passover(), Day(3)],
+ days_of_week=(0, 1, 2, 3, 6),
+)
+PassoverInterimDay4 = Holiday(
+ "Passover Interim Day",
+ month=1,
+ day=1,
+ offset=[_Passover(), Day(4)],
+ days_of_week=(0, 1, 2, 3, 6),
+)
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/us_futures_calendar.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/us_futures_calendar.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca74803b3e81e60e86f996304ebf2aa543ca6d99
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/us_futures_calendar.py
@@ -0,0 +1,90 @@
+from datetime import time
+from zoneinfo import ZoneInfo
+
+import numpy as np
+import pandas as pd
+from pandas.tseries.holiday import GoodFriday
+
+from exchange_calendars.calendar_helpers import UTC
+from exchange_calendars.exchange_calendar import ExchangeCalendar, HolidayCalendar
+from exchange_calendars.us_holidays import Christmas, USNewYearsDay
+
+
+# Number of hours of offset between the open and close times dictated by this
+# calendar versus the 6:31am to 5:00pm times over which we want to simulate
+# futures algos.
+FUTURES_OPEN_TIME_OFFSET = 12.5
+FUTURES_CLOSE_TIME_OFFSET = -1
+
+
+class QuantopianUSFuturesCalendar(ExchangeCalendar):
+ """Synthetic calendar for trading US futures.
+
+ This calendar is a superset of all of the US futures exchange
+ calendars provided by Zipline (CFE, CME, ICE), and is intended for
+ trading across all of these exchanges.
+
+ Notes
+ -----
+ Open Time: 6:00 PM, America/New_York
+ Close Time: 6:00 PM, America/New_York
+
+ Regularly-Observed Holidays:
+ - New Years Day
+ - Good Friday
+ - Christmas
+
+ In order to align the hours of each session, we ignore the Sunday
+ CME Pre-Open hour (5-6pm).
+ """
+
+ name = "us_futures"
+ tz = ZoneInfo("America/New_York")
+ open_times = ((None, time(18)),)
+ close_times = ((None, time(18)),)
+ open_offset = -1
+
+ def execution_time_from_open(self, open_dates):
+ return open_dates + pd.Timedelta(hours=FUTURES_OPEN_TIME_OFFSET)
+
+ def execution_time_from_close(self, close_dates):
+ return close_dates + pd.Timedelta(hours=FUTURES_CLOSE_TIME_OFFSET)
+
+ def execution_minutes_for_session(
+ self, session_label: pd.DatetimeIndex
+ ) -> pd.DatetimeIndex:
+ """
+ Given a session label, return the execution minutes for that session.
+
+ Parameters
+ ----------
+ session_label
+ A session label whose session's minutes are desired.
+
+ Returns
+ -------
+ pd.DateTimeIndex
+ All the execution minutes for the given session.
+ """
+ start = self.execution_time_from_open(self.session_first_minute(session_label))
+ end = self.execution_time_from_close(self.session_last_minute(session_label))
+ return self.minutes_in_range(start=start, end=end)
+
+ def execution_minutes_for_sessions_in_range(self, start, stop):
+ minutes = self.execution_minutes_for_session
+ return pd.DatetimeIndex(
+ np.concatenate(
+ [minutes(session) for session in self.sessions_in_range(start, stop)]
+ ),
+ tz=UTC,
+ )
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ USNewYearsDay,
+ GoodFriday,
+ Christmas,
+ ]
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/us_holidays.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/us_holidays.py
new file mode 100644
index 0000000000000000000000000000000000000000..b905b0a4c42b879040a470aa2f5f7c62495dbae7
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/us_holidays.py
@@ -0,0 +1,375 @@
+"""
+US Holidays
+
+Many historical holidays were derived from the pdf at
+etc/NYSE-Historical-Closings.pdf. Originally posted at
+http://s3.amazonaws.com/armstrongeconomics-wp/2013/07/NYSE-Closings.pdf # noqa
+
+These were originally added in
+https://github.com/rsheftel/pandas_market_calendars/pull/30
+"""
+
+from dateutil.relativedelta import MO, TH, TU
+from pandas import DateOffset, Timestamp
+from pandas.tseries.holiday import Holiday, nearest_workday, sunday_to_monday
+from pandas.tseries.offsets import Day
+
+from .common_holidays import new_years_day
+from .exchange_calendar import FRIDAY, MONDAY, THURSDAY, TUESDAY, WEDNESDAY
+
+
+def following_tuesday_every_four_years_observance(dt):
+ return dt + DateOffset(years=(4 - (dt.year % 4)) % 4, weekday=TU(1))
+
+
+# Holidays
+
+# These have the same definition, but are used in different places because the
+# NYSE closed at 2:00 PM on Christmas Eve until 1993.
+ChristmasEveBefore1993 = Holiday(
+ "Christmas Eve",
+ month=12,
+ day=24,
+ end_date=Timestamp("1993-01-01"),
+ # When Christmas is a Saturday, the 24th is a full holiday.
+ days_of_week=(MONDAY, TUESDAY, WEDNESDAY, THURSDAY),
+)
+ChristmasEveInOrAfter1993 = Holiday(
+ "Christmas Eve",
+ month=12,
+ day=24,
+ start_date=Timestamp("1993-01-01"),
+ # When Christmas is a Saturday, the 24th is a full holiday.
+ days_of_week=(MONDAY, TUESDAY, WEDNESDAY, THURSDAY),
+)
+USNewYearsDay = new_years_day(
+ # When Jan 1 is a Sunday, US markets observe the subsequent Monday.
+ # When Jan 1 is a Saturday (as in 2005 and 2011), no holiday is observed.
+ observance=sunday_to_monday
+)
+USMartinLutherKingJrAfter1998 = Holiday(
+ "Dr. Martin Luther King Jr. Day",
+ month=1,
+ day=1,
+ # The US markets didn't observe MLK day as a holiday until 1998.
+ start_date=Timestamp("1998-01-01"),
+ offset=DateOffset(weekday=MO(3)),
+)
+USLincolnsBirthDayBefore1954 = Holiday(
+ "Lincoln's Birthday",
+ month=2,
+ day=12,
+ start_date=Timestamp("1874-01-01"),
+ end_date=Timestamp("1953-12-31"),
+ observance=sunday_to_monday,
+)
+USWashingtonsBirthDayBefore1964 = Holiday(
+ "Washington's Birthday",
+ month=2,
+ day=22,
+ start_date=Timestamp("1880-01-01"),
+ end_date=Timestamp("1963-12-31"),
+ observance=sunday_to_monday,
+)
+USWashingtonsBirthDay1964to1970 = Holiday(
+ "Washington's Birthday",
+ month=2,
+ day=22,
+ start_date=Timestamp("1964-01-01"),
+ end_date=Timestamp("1970-12-31"),
+ observance=nearest_workday,
+)
+USPresidentsDay = Holiday(
+ "President's Day",
+ start_date=Timestamp("1971-01-01"),
+ month=2,
+ day=1,
+ offset=DateOffset(weekday=MO(3)),
+)
+
+USThanksgivingDayBefore1939 = Holiday(
+ "Thanksgiving Before 1939",
+ start_date=Timestamp("1864-01-01"),
+ end_date=Timestamp("1938-12-31"),
+ month=11,
+ day=30,
+ offset=DateOffset(weekday=TH(-1)),
+)
+
+USThanksgivingDay1939to1941 = Holiday(
+ "Thanksgiving 1939 to 1941",
+ start_date=Timestamp("1939-01-01"),
+ end_date=Timestamp("1941-12-31"),
+ month=11,
+ day=30,
+ offset=DateOffset(weekday=TH(-2)),
+)
+USThanksgivingDay = Holiday(
+ "Thanksgiving",
+ start_date=Timestamp("1942-01-01"),
+ month=11,
+ day=1,
+ offset=DateOffset(weekday=TH(4)),
+)
+
+USMemorialDayBefore1964 = Holiday(
+ "Memorial Day",
+ month=5,
+ day=30,
+ end_date=Timestamp("1963-12-31"),
+ observance=sunday_to_monday,
+)
+USMemorialDay1964to1969 = Holiday(
+ "Memorial Day",
+ month=5,
+ day=30,
+ start_date=Timestamp("1964-01-01"),
+ end_date=Timestamp("1969-12-31"),
+ observance=nearest_workday,
+)
+USMemorialDay = Holiday(
+ # NOTE: The definition for Memorial Day is incorrect as of pandas 0.16.0.
+ # See https://github.com/pydata/pandas/issues/9760.
+ "Memorial Day",
+ month=5,
+ day=25,
+ start_date=Timestamp("1971-01-01"),
+ offset=DateOffset(weekday=MO(1)),
+)
+USJuneteenth = Holiday(
+ "Juneteenth National Independence Day",
+ month=6,
+ day=19,
+ start_date=Timestamp("2022-01-01"),
+ observance=nearest_workday
+)
+USIndependenceDayBefore1954 = Holiday(
+ "July 4th",
+ month=7,
+ day=4,
+ end_date=Timestamp("1953-12-31"),
+ observance=sunday_to_monday,
+)
+USIndependenceDay = Holiday(
+ "July 4th",
+ month=7,
+ day=4,
+ start_date=Timestamp("1954-01-01"),
+ observance=nearest_workday,
+)
+
+USElectionDay1848to1967 = Holiday(
+ "Election Day",
+ month=11,
+ day=2,
+ start_date=Timestamp("1848-1-1"),
+ end_date=Timestamp("1967-12-31"),
+ offset=DateOffset(weekday=TU(1)),
+)
+USElectionDay1968to1980 = Holiday(
+ "Election Day",
+ month=11,
+ day=2,
+ start_date=Timestamp("1968-01-01"),
+ end_date=Timestamp("1980-12-31"),
+ observance=following_tuesday_every_four_years_observance,
+)
+USVeteransDay1934to1953 = Holiday(
+ "Veteran Day",
+ month=11,
+ day=11,
+ start_date=Timestamp("1934-1-1"),
+ end_date=Timestamp("1953-12-31"),
+ observance=sunday_to_monday,
+)
+USColumbusDayBefore1954 = Holiday(
+ "Columbus Day",
+ month=10,
+ day=12,
+ end_date=Timestamp("1953-12-31"),
+ observance=sunday_to_monday,
+)
+ChristmasBefore1954 = Holiday(
+ "Christmas",
+ month=12,
+ day=25,
+ end_date=Timestamp("1953-12-31"),
+ observance=sunday_to_monday,
+)
+Christmas = Holiday(
+ "Christmas",
+ month=12,
+ day=25,
+ start_date=Timestamp("1954-01-01"),
+ observance=nearest_workday,
+)
+
+# Early Closes
+
+MonTuesThursBeforeIndependenceDay = Holiday(
+ # When July 4th is a Tuesday, Wednesday, or Friday, the previous day is a
+ # half day.
+ "Mondays, Tuesdays, and Thursdays Before Independence Day",
+ month=7,
+ day=3,
+ days_of_week=(MONDAY, TUESDAY, THURSDAY),
+ start_date=Timestamp("1995-01-01"),
+)
+FridayAfterIndependenceDayPre2013 = Holiday(
+ # When July 4th is a Thursday, the next day is a half day prior to 2013.
+ # Since 2013 the early close is on Wednesday and Friday is a full day
+ "Fridays after Independence Day prior to 2013",
+ month=7,
+ day=5,
+ days_of_week=(FRIDAY,),
+ start_date=Timestamp("1995-01-01"),
+ end_date=Timestamp("2013-01-01"),
+)
+WednesdayBeforeIndependenceDayPost2013 = Holiday(
+ # When July 4th is a Thursday, the next day is a half day prior to 2013.
+ # Since 2013 the early close is on Wednesday and Friday is a full day
+ "Wednesdays Before Independence Day including and after 2013",
+ month=7,
+ day=3,
+ days_of_week=(WEDNESDAY,),
+ start_date=Timestamp("2013-01-01"),
+)
+USBlackFridayBefore1993 = Holiday(
+ "Black Friday",
+ month=11,
+ day=1,
+ # Black Friday was not observed until 1992.
+ start_date=Timestamp("1992-01-01"),
+ end_date=Timestamp("1993-01-01"),
+ offset=[DateOffset(weekday=TH(4)), Day(1)],
+)
+USBlackFridayInOrAfter1993 = Holiday(
+ "Black Friday",
+ month=11,
+ day=1,
+ start_date=Timestamp("1993-01-01"),
+ offset=[DateOffset(weekday=TH(4)), Day(1)],
+)
+BattleOfGettysburg = Holiday(
+ # All of the floor traders in Chicago were sent to PA
+ "Markets were closed during the battle of Gettysburg",
+ month=7,
+ day=(1, 2, 3),
+ start_date=Timestamp("1863-07-01"),
+ end_date=Timestamp("1863-07-03"),
+)
+
+# Adhoc and other closings
+# use list for consistency in returning ad-hoc dates
+
+
+November29BacklogRelief = [
+ Timestamp("1929-11-01"),
+ Timestamp("1929-11-29"),
+]
+
+March33BankHoliday = [
+ Timestamp("1933-03-06"),
+ Timestamp("1933-03-07"),
+ Timestamp("1933-03-08"),
+ Timestamp("1933-03-09"),
+ Timestamp("1933-03-10"),
+ Timestamp("1933-03-13"),
+ Timestamp("1933-03-14"),
+]
+
+August45VictoryOverJapan = [
+ Timestamp("1945-08-15"),
+ Timestamp("1945-08-16"),
+]
+
+
+ChristmasEvesAdhoc = [
+ Timestamp("1945-12-24"),
+ Timestamp("1956-12-24"),
+]
+
+DayAfterChristmasAdhoc = [Timestamp("1958-12-26")]
+
+DayBeforeDecorationAdhoc = [Timestamp("1961-05-29")]
+
+LincolnsBirthDayAdhoc = [Timestamp("1968-02-12")]
+
+PaperworkCrisis68 = [
+ Timestamp("1968-06-12"),
+ Timestamp("1968-06-19"),
+ Timestamp("1968-06-26"),
+ Timestamp("1968-07-10"),
+ Timestamp("1968-07-17"),
+ Timestamp("1968-07-24"),
+ Timestamp("1968-07-31"),
+ Timestamp("1968-08-07"),
+ Timestamp("1968-08-14"),
+ Timestamp("1968-08-21"),
+ Timestamp("1968-08-28"),
+ Timestamp("1968-09-11"),
+ Timestamp("1968-09-18"),
+ Timestamp("1968-09-25"),
+ Timestamp("1968-10-02"),
+ Timestamp("1968-10-09"),
+ Timestamp("1968-10-16"),
+ Timestamp("1968-10-23"),
+ Timestamp("1968-10-30"),
+ Timestamp("1968-11-11"),
+ Timestamp("1968-11-20"),
+ Timestamp("1968-12-04"),
+ Timestamp("1968-12-11"),
+ Timestamp("1968-12-18"),
+ Timestamp("1968-12-25"),
+]
+
+DayAfterIndependenceDayAdhoc = [Timestamp("1968-07-05")]
+
+WeatherSnowClosing = [Timestamp("1969-02-10")]
+
+FirstLunarLandingClosing = [Timestamp("1969-07-21")]
+
+NewYorkCityBlackout77 = [Timestamp("1977-07-14")]
+
+
+# http://en.wikipedia.org/wiki/Aftermath_of_the_September_11_attacks
+September11Closings = [
+ Timestamp("2001-09-11"),
+ Timestamp("2001-09-12"),
+ Timestamp("2001-09-13"),
+ Timestamp("2001-09-14"),
+]
+
+# http://en.wikipedia.org/wiki/Hurricane_sandy
+HurricaneSandyClosings = [
+ Timestamp("2012-10-29"),
+ Timestamp("2012-10-30"),
+]
+
+# add Hurricane Gloria closing
+HurricaneGloriaClosing = [Timestamp("1985-09-27")]
+
+
+# National Days of Mourning
+# - President John F. Kennedy - November 25, 1963
+# - Martin Luther King - April 9, 1968
+# - President Dwight D. Eisenhower - March 31, 1969
+# - President Harry S. Truman - December 28, 1972
+# - President Lyndon B. Johnson - January 25, 1973
+# - President Richard Nixon - April 27, 1994
+# - President Ronald W. Reagan - June 11, 2004
+# - President Gerald R. Ford - Jan 2, 2007
+# - President George H.W. Bush - Dec 5, 2018
+# added Truman and Johnson to go back to 1970
+# http://s3.amazonaws.com/armstrongeconomics-wp/2013/07/NYSE-Closings.pdf
+USNationalDaysofMourning = [
+ Timestamp("1963-11-25"),
+ Timestamp("1968-04-09"),
+ Timestamp("1969-03-31"),
+ Timestamp("1972-12-28"),
+ Timestamp("1973-01-25"),
+ Timestamp("1994-04-27"),
+ Timestamp("2004-06-11"),
+ Timestamp("2007-01-02"),
+ Timestamp("2018-12-05"),
+]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/utils/__init__.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/utils/pandas_utils.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/utils/pandas_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2942f9f93f48c9a631a5ada37002906096c3cf58
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/utils/pandas_utils.py
@@ -0,0 +1,155 @@
+from __future__ import annotations
+
+import datetime
+from zoneinfo import ZoneInfo
+
+import numpy as np
+import pandas as pd
+
+from exchange_calendars.calendar_helpers import UTC
+
+
+def days_at_time(
+ dates: pd.DatetimeIndex,
+ time: datetime.time | None,
+ tz: ZoneInfo,
+ day_offset: int,
+) -> pd.DatetimeIndex:
+ """Return UTC DatetimeIndex of given dates at a given time.
+
+ Parameters
+ ----------
+ dates
+ Dates or date (timezone naive with no time component).
+
+ time
+ The time to apply as an offset to each day in `dates`.
+
+ tz
+ The timezone in which to interpret `time`.
+
+ day_offset
+ Number of days by which to offset each date in `dates`.
+
+ Returns
+ -------
+ pd.DatetimeIndex
+ DatetimeIndex comprising Timestamp evaluted from `dates` and `time`
+ with `dates` offset by `day_offset` and `time` interpreted as having
+ timezone `tz`. DatetimeIndex has UTC timezone.
+
+ Examples
+ --------
+ In the example below, the times switch from 13:45 to 12:45 UTC because
+ March 13th is the daylight savings transition for America/New_York. All
+ the times are still 8:45 when interpreted in America/New_York.
+
+ >>> import pandas as pd; import datetime; import pprint
+ >>> dts = pd.date_range('2016-03-12', '2016-03-14')
+ >>> dts_845 = days_at_time(dts, datetime.time(8, 45), 'America/New_York', 0)
+ >>> pprint.pprint([str(dt) for dt in dts_845])
+ ['2016-03-12 13:45:00+00:00',
+ '2016-03-13 12:45:00+00:00',
+ '2016-03-14 12:45:00+00:00']
+ """
+ if time is None:
+ return pd.DatetimeIndex([None for _ in dates]).tz_localize(UTC)
+
+ if len(dates) == 0:
+ return dates.tz_localize(UTC)
+
+ # Offset days without tz to avoid timezone issues.
+ delta = pd.Timedelta(
+ days=day_offset,
+ hours=time.hour,
+ minutes=time.minute,
+ seconds=time.second,
+ )
+ return (dates + delta).tz_localize(tz).tz_convert(UTC)
+
+
+def vectorized_sunday_to_monday(dtix):
+ """A vectorized implementation of
+ :func:`pandas.tseries.holiday.sunday_to_monday`.
+
+ Parameters
+ ----------
+ dtix : pd.DatetimeIndex
+ The index to shift sundays to mondays.
+
+ Returns
+ -------
+ sundays_as_mondays : pd.DatetimeIndex
+ ``dtix`` with all sundays moved to the next monday.
+ """
+ values = dtix.values.copy()
+ values[dtix.weekday == 6] += np.timedelta64(1, "D")
+ return pd.DatetimeIndex(values)
+
+
+def longest_run(ser: pd.Series) -> pd.Index:
+ """Get the longest run of consecutive True values in a Series.
+
+ Function can be used to find the longest run of values that meet a
+ condition.
+
+ Parameters
+ ----------
+ ser
+ pd.Series of bool dtype.
+ Index should reflect values against which a condition was
+ assessed.
+ Values should reflect whether corresponding index value
+ met the condition.
+
+ Return
+ ------
+ pd.Index
+ Slice of `ser` index that corresponds with the longest run of
+ consecutive True values.
+
+ Examples
+ --------
+ >>> arr = np.arange(0, 88)
+ >>> ser = pd.Series(arr, index=arr)
+ >>> bv = (
+ ... ((ser >= 10) & (ser < 16))
+ ... | ((ser >= 30) & (ser <= 40))
+ ... | ((ser >= 55) & (ser < 61))
+ ... )
+ >>> longest_run(bv)
+ Index([30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40], dtype='int32')
+ >>> pd.testing.assert_index_equal(longest_run(bv), ser.index[30:41])
+ """
+ # group Trues by only adding to sum when value False.
+ trues_grouped = (~ser).cumsum()[ser] # and only take True Values
+ group_sizes = trues_grouped.value_counts() # count each run
+ max_run_size = group_sizes.max()
+ max_run_group_id = group_sizes[group_sizes == max_run_size].index[0]
+ run = trues_grouped[trues_grouped == max_run_group_id].index
+ return run
+
+
+def indexes_union(indexes: list[pd.Index]) -> pd.Index:
+ """Return union of multiple pd.Index objects.
+
+ Parameters
+ ----------
+ indexes
+ Index objects to be joined. All indexes must be of same dtype.
+
+ Examples
+ --------
+ >>> index1 = pd.date_range('2021-05-01 12:20', periods=2, freq='1h')
+ >>> index2 = pd.date_range('2021-05-02 17:10', periods=2, freq='22min')
+ >>> index3 = pd.date_range('2021-05-03', periods=2, freq='1D')
+ >>> indexes_union([index1, index2, index3])
+ DatetimeIndex(['2021-05-01 12:20:00', '2021-05-01 13:20:00',
+ '2021-05-02 17:10:00', '2021-05-02 17:32:00',
+ '2021-05-03 00:00:00', '2021-05-04 00:00:00'],
+ dtype='datetime64[ns]', freq=None)
+ """
+ index = indexes[0]
+ for indx in indexes[1:]:
+ index = index.union(indx)
+ return index
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/weekday_calendar.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/weekday_calendar.py
new file mode 100644
index 0000000000000000000000000000000000000000..9878f3124cf4e3577062c117bdf8954bbf39a060
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/weekday_calendar.py
@@ -0,0 +1,17 @@
+from datetime import time
+
+from exchange_calendars.calendar_helpers import UTC
+from .exchange_calendar import ExchangeCalendar
+
+
+class WeekdayCalendar(ExchangeCalendar):
+ """
+ A ExchangeCalendar for an exchange that is open every minute of every
+ weekday.
+ """
+
+ name = "24/5"
+ tz = UTC
+ open_times = ((None, time(0)),)
+ close_times = ((None, time(0)),)
+ close_offset = 1
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xbkk_holidays.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xbkk_holidays.py
new file mode 100644
index 0000000000000000000000000000000000000000..90a8b2ad47ed027d64b5ae1495400c58256cc1cc
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xbkk_holidays.py
@@ -0,0 +1,325 @@
+from __future__ import annotations
+
+import datetime
+
+import pandas as pd
+from pandas.tseries.holiday import (
+ Holiday,
+ next_monday_or_tuesday,
+ sunday_to_monday,
+ weekend_to_monday,
+)
+
+from .common_holidays import european_labour_day, new_years_day, new_years_eve
+from .exchange_calendar import MONDAY, SUNDAY
+
+
+def new_years_eve_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # New Year's Eve is a holiday every year except for 2003 for some reason.
+ return weekend_to_monday(dt) if dt.year != 2003 else None
+
+
+def new_years_day_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # There was no extra observance of New Year's Day in 2006.
+ return next_monday_or_tuesday(dt) if dt.year != 2006 else None
+
+
+def songkran_festival_last_day_observance(dt: datetime.datetime) -> datetime.datetime:
+ """
+ This function is similar to the pandas function `next_monday_or_tuesday`
+ except it does not observe Saturday holidays on Monday.
+ """
+ if dt.weekday() == SUNDAY or dt.weekday() == MONDAY:
+ return dt + datetime.timedelta(days=1)
+ return dt
+
+
+NewYearsDay = new_years_day(observance=new_years_day_observance)
+
+ChakriMemorialDay = Holiday(
+ "Chakri Memorial Day",
+ month=4,
+ day=6,
+ observance=weekend_to_monday,
+)
+
+# Thai New Year. This does not follow the usual observe-next-trading-day rule.
+SongkranFestival1 = Holiday("Songkran Festival", month=4, day=13)
+SongkranFestival2 = Holiday(
+ "Songkran Festival",
+ month=4,
+ day=14,
+ observance=sunday_to_monday,
+)
+SongkranFestival3 = Holiday(
+ "Songkran Festival",
+ month=4,
+ day=15,
+ observance=songkran_festival_last_day_observance,
+)
+
+LabourDay = european_labour_day(observance=weekend_to_monday)
+
+CoronationDay2016AndBefore = Holiday(
+ "Coronation Day For King #9",
+ month=5,
+ day=5,
+ observance=weekend_to_monday,
+ end_date="2017",
+)
+CoronationDay2019AndAfter = Holiday(
+ "Coronation Day For King #10",
+ month=5,
+ day=4,
+ observance=weekend_to_monday,
+ start_date="2019",
+)
+
+HMQueensBirthday = Holiday(
+ "Her Majesty The Queen's Birthday",
+ month=6,
+ day=3,
+ observance=weekend_to_monday,
+ start_date="2019",
+)
+HMKingsBirthday = Holiday(
+ "His Majesty The King's Birthday",
+ month=7,
+ day=28,
+ observance=weekend_to_monday,
+ start_date="2017",
+)
+HMQueenMothersBirthday = Holiday(
+ "Her Majesty The Queen Mother's Birthday",
+ month=8,
+ day=12,
+ observance=weekend_to_monday,
+)
+
+# This holiday was historically used as a "catch up" day for the exchange, so
+# it does not need to follow the usual observe-next-trading-day rule.
+HalfYearHoliday = Holiday(
+ "Half Year Holiday",
+ month=7,
+ day=1,
+ start_date="2002",
+ end_date="2017",
+)
+
+ThePassingOfKingBhumibol = Holiday(
+ "The Passing of King Bhumibol",
+ month=10,
+ day=13,
+ observance=weekend_to_monday,
+ start_date="2017",
+)
+
+ChulalongkornDay = Holiday(
+ "Chulalongkorn Day",
+ month=10,
+ day=23,
+ observance=weekend_to_monday,
+)
+
+KingBhumibolsBirthday = Holiday(
+ "King Bhumibol's Birthday",
+ month=12,
+ day=5,
+ observance=weekend_to_monday,
+)
+
+ThailandConstitutionDay = Holiday(
+ "Thailand Constitution Day",
+ month=12,
+ day=10,
+ observance=weekend_to_monday,
+)
+
+NewYearsEve = new_years_eve(observance=new_years_eve_observance)
+
+# Adhoc Holidays
+# --------------
+
+new_years_bridge_days = [
+ pd.Timestamp("2002-12-30"),
+ pd.Timestamp("2004-01-02"),
+ pd.Timestamp("2009-01-02"),
+ pd.Timestamp("2013-12-30"),
+ pd.Timestamp("2015-01-02"),
+]
+
+asanha_bucha_bridge_days = [
+ pd.Timestamp("2009-07-06"),
+ pd.Timestamp("2016-07-18"),
+]
+
+queens_birthday_bridge_days = [
+ pd.Timestamp("2010-08-13"),
+ pd.Timestamp("2014-08-11"),
+]
+
+coronation_bridge_days = [
+ pd.Timestamp("2015-05-04"),
+ pd.Timestamp("2016-05-06"),
+]
+
+vesak_bridge_days = [
+ pd.Timestamp("2011-05-16"),
+]
+
+misc_adhoc = [
+ pd.Timestamp("2006-04-19"), # Special Holiday
+ pd.Timestamp("2006-06-12"), # Special Holiday
+ pd.Timestamp("2006-06-13"), # Special Holiday
+ pd.Timestamp("2006-09-20"), # Exchange Holiday
+ pd.Timestamp("2007-12-24"), # Exchange Holiday
+ pd.Timestamp("2010-05-20"), # Closure Due to Security Concerns
+ pd.Timestamp("2010-05-21"), # Closure Due to Security Concerns
+ pd.Timestamp("2012-04-09"), # Bank Holiday
+ pd.Timestamp("2017-10-26"), # Cremation of King Bhumibol
+]
+
+# Lunar Holidays
+# --------------
+
+# Makha Bucha (also known as Magha Puja) is celebrated on the day of the Full
+# Moon of Magha in the Buddhist calendar. This falls sometime between February
+# and March.
+makha_bucha = pd.to_datetime(
+ [
+ "1981-02-18",
+ "1982-02-08",
+ "1983-02-27",
+ "1984-02-16",
+ "1985-03-06",
+ "1986-02-24",
+ "1987-02-13",
+ "1988-03-03",
+ "1989-02-20",
+ "1990-02-09",
+ "1991-02-28",
+ "1992-02-18",
+ "1993-03-08",
+ "1994-02-25",
+ "1995-02-15",
+ "1996-03-05",
+ "1997-02-22",
+ "1998-02-11",
+ "1999-03-02",
+ "2000-02-19",
+ "2001-02-08",
+ "2002-02-26",
+ "2003-02-17",
+ "2004-03-05",
+ "2005-02-23",
+ "2006-02-13",
+ "2007-03-05",
+ "2008-02-21",
+ "2009-02-09",
+ "2010-03-01",
+ "2011-02-18",
+ "2012-03-07",
+ "2013-02-25",
+ "2014-02-14",
+ "2015-03-04",
+ "2016-02-22",
+ "2017-02-13",
+ "2018-03-01",
+ "2019-02-19",
+ "2020-02-10",
+ ]
+)
+
+# Vesak (also known as Buddha Day) is celebrated on the day of the Full Moon of
+# Visakha in the Buddhist calendar. This typically falls in May.
+vesak = pd.to_datetime(
+ [
+ "1981-05-18",
+ "1982-05-07",
+ "1983-05-26",
+ "1984-05-15",
+ "1985-06-02",
+ "1986-05-23",
+ "1987-05-13",
+ "1988-05-31",
+ "1989-05-20",
+ "1990-05-09",
+ "1991-05-28",
+ "1992-05-16",
+ "1993-06-04",
+ "1994-05-24",
+ "1995-05-14",
+ "1996-06-01",
+ "1997-05-22",
+ "1998-05-11",
+ "1999-05-30",
+ "2000-05-18",
+ "2001-05-07",
+ "2002-05-27",
+ "2003-05-15",
+ "2004-06-02",
+ "2005-05-23",
+ "2006-05-12",
+ "2007-05-31",
+ "2008-05-19",
+ "2009-05-08",
+ "2010-05-28",
+ "2011-05-17",
+ "2012-06-04",
+ "2013-05-24",
+ "2014-05-13",
+ "2015-06-01",
+ "2016-05-20",
+ "2017-05-10",
+ "2018-05-29",
+ "2019-05-20",
+ "2020-05-06",
+ ]
+)
+
+# Asanha Bucha (also known as Asalha Puja) is celebrated on the day of the Full
+# Moon of Asadha in the Buddhist calendar. This typically falls in July.
+asanha_bucha = pd.to_datetime(
+ [
+ "1981-07-17",
+ "1982-07-06",
+ "1983-07-24",
+ "1984-07-12",
+ "1985-07-31",
+ "1986-07-21",
+ "1987-07-10",
+ "1988-07-28",
+ "1989-07-18",
+ "1990-07-07",
+ "1991-07-26",
+ "1992-07-14",
+ "1993-08-02",
+ "1994-07-22",
+ "1995-07-12",
+ "1996-07-30",
+ "1997-07-19",
+ "1998-07-09",
+ "1999-07-28",
+ "2000-07-16",
+ "2001-07-05",
+ "2002-07-25",
+ "2003-07-14",
+ "2004-08-02",
+ "2005-07-22",
+ "2006-07-11",
+ "2007-07-30",
+ "2008-07-17",
+ "2009-07-07",
+ "2010-07-26",
+ "2011-07-15",
+ "2012-08-02",
+ "2013-07-22",
+ "2014-07-11",
+ "2015-07-30",
+ "2016-07-19",
+ "2017-07-10",
+ "2018-07-27",
+ "2019-07-16",
+ "2020-07-06",
+ ]
+)
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xkls_holidays.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xkls_holidays.py
new file mode 100644
index 0000000000000000000000000000000000000000..a51080902d4197464c18ba7b96c69760711100ae
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xkls_holidays.py
@@ -0,0 +1,534 @@
+from datetime import timedelta
+
+import pandas as pd
+from pandas.tseries.holiday import Holiday, sunday_to_monday
+
+from .common_holidays import christmas, european_labour_day, new_years_day
+from .lunisolar_holidays import chinese_lunar_new_year_dates
+from .exchange_calendar import WEEKENDS
+
+# In Malaysia, Nuzul Al'Quran is the 17th day of Ramadan
+# Starts 2014
+malaysia_nuzul_al_quran = pd.to_datetime(
+ [
+ "2014-07-15",
+ "2015-07-04",
+ "2016-06-22",
+ "2017-06-12",
+ "2018-06-02",
+ "2019-05-22",
+ "2020-05-10",
+ "2021-04-29",
+ "2022-04-19",
+ "2023-04-08",
+ "2024-03-27",
+ "2025-03-17",
+ "2026-03-06",
+ "2027-02-24",
+ "2028-02-13",
+ "2029-02-01",
+ "2030-01-21",
+ "2031-01-11",
+ "2031-12-31",
+ "2032-12-20",
+ "2033-12-09",
+ "2034-11-28",
+ "2035-11-17",
+ "2036-11-05",
+ "2037-10-26",
+ "2038-10-16",
+ "2039-10-05",
+ "2040-09-23",
+ "2041-09-13",
+ "2042-09-02",
+ "2043-08-22",
+ "2044-08-11",
+ "2045-07-31",
+ "2046-07-21",
+ "2047-07-10",
+ "2048-06-28",
+ "2049-06-18",
+ ]
+)
+
+# Muharram is New Year's Day for the Islamic Lunar Calendar
+muharram = pd.to_datetime(
+ [
+ "1980-11-09",
+ "1981-10-28",
+ "1982-10-18",
+ "1983-10-07",
+ "1984-09-26",
+ "1985-09-15",
+ "1986-09-05",
+ "1987-08-25",
+ "1988-08-13",
+ "1989-08-02",
+ "1990-07-23",
+ "1991-07-12",
+ "1992-07-01",
+ "1993-06-21",
+ "1994-06-10",
+ "1995-05-30",
+ "1996-05-18",
+ "1997-05-07",
+ "1998-04-27",
+ "1999-04-17",
+ "2000-04-06",
+ "2001-03-26",
+ "2002-03-15",
+ "2003-03-04",
+ "2004-02-22",
+ "2005-02-11",
+ "2006-02-01",
+ "2007-01-20",
+ "2008-01-10",
+ "2008-12-29",
+ "2009-12-18",
+ "2010-12-07",
+ "2011-11-27",
+ "2012-11-15",
+ "2013-11-05",
+ "2014-10-25",
+ "2015-10-14",
+ "2016-10-02",
+ "2017-09-22",
+ "2018-09-11",
+ "2019-09-01",
+ "2020-08-20",
+ "2021-08-10",
+ "2022-07-30",
+ "2023-07-19",
+ "2024-07-07",
+ "2025-06-26",
+ "2026-06-16",
+ "2027-06-06",
+ "2028-05-25",
+ "2029-05-14",
+ "2030-05-03",
+ "2031-04-23",
+ "2032-04-11",
+ "2033-04-01",
+ "2034-03-21",
+ "2035-03-11",
+ "2036-02-28",
+ "2037-02-16",
+ "2038-02-05",
+ "2039-01-26",
+ "2040-01-15",
+ "2041-01-04",
+ "2041-12-24",
+ "2042-12-14",
+ "2043-12-03",
+ "2044-11-21",
+ "2045-11-10",
+ "2046-10-31",
+ "2047-10-20",
+ "2048-10-09",
+ ]
+)
+
+# Prophet Muhammad's Birthday (Mawlid) is observed as the 12th day of
+# the 3rd month in the Islamic Lunar Calendar
+muhammad_birthday = pd.to_datetime(
+ [
+ "1981-01-18",
+ "1982-01-07",
+ "1982-12-27",
+ "1983-12-16",
+ "1984-12-04",
+ "1985-11-24",
+ "1986-11-14",
+ "1987-11-03",
+ "1988-10-22",
+ "1989-10-11",
+ "1990-10-01",
+ "1991-09-20",
+ "1992-09-09",
+ "1993-08-29",
+ "1994-08-19",
+ "1995-08-08",
+ "1996-07-27",
+ "1997-07-16",
+ "1998-07-06",
+ "1999-06-26",
+ "2000-06-14",
+ "2001-06-04",
+ "2002-05-27",
+ "2003-05-14",
+ "2004-05-03",
+ "2005-04-21",
+ "2006-04-11",
+ "2007-03-31",
+ "2008-03-20",
+ "2009-03-09",
+ "2010-02-26",
+ "2011-02-15",
+ "2012-02-06",
+ "2013-01-24",
+ "2014-01-14",
+ "2015-12-24",
+ "2016-12-11",
+ "2017-12-01",
+ "2018-11-20",
+ "2019-11-09",
+ "2020-10-29",
+ "2021-10-19",
+ "2022-10-09",
+ "2023-09-28",
+ "2024-09-15",
+ "2025-09-04",
+ "2026-08-25",
+ "2027-08-14",
+ "2028-08-03",
+ "2029-07-24",
+ "2030-07-13",
+ "2031-07-02",
+ "2032-06-20",
+ "2033-06-09",
+ "2034-05-30",
+ "2035-05-20",
+ "2036-05-08",
+ "2037-04-28",
+ "2038-04-17",
+ "2039-04-06",
+ "2040-03-25",
+ "2041-03-15",
+ "2042-03-04",
+ "2043-02-22",
+ "2044-02-11",
+ "2045-01-30",
+ "2046-01-19",
+ "2047-01-08",
+ "2047-12-29",
+ "2048-12-18",
+ ]
+)
+
+# Malaysia's observances of Eid al-Fitr
+malaysia_eid_al_fitr_first_day = pd.to_datetime(
+ [
+ "1981-08-01",
+ "1982-07-21",
+ "1983-07-11",
+ "1984-06-30",
+ "1985-06-19",
+ "1986-06-08",
+ "1987-05-28",
+ "1988-05-16",
+ "1989-05-06",
+ "1990-04-26",
+ "1991-04-15",
+ "1992-04-04",
+ "1993-03-24",
+ "1994-03-13",
+ "1995-03-02",
+ "1996-02-19",
+ "1997-02-08",
+ "1998-01-29",
+ "1999-01-18",
+ "2000-01-08",
+ "2000-12-27",
+ "2001-12-16",
+ "2002-12-05",
+ "2003-11-25",
+ "2004-11-14",
+ "2005-11-03",
+ "2006-10-23",
+ "2007-10-13",
+ "2008-10-01",
+ "2009-09-20",
+ "2010-09-10",
+ "2011-08-30",
+ "2012-08-19",
+ "2013-08-08",
+ "2014-07-28",
+ "2015-07-17",
+ "2016-07-06",
+ "2017-06-25",
+ "2018-06-15",
+ "2019-06-05",
+ "2020-05-24",
+ "2021-05-13",
+ "2022-05-03",
+ "2023-04-22",
+ "2024-04-10",
+ "2025-03-30",
+ "2026-03-20",
+ "2027-03-09",
+ "2028-02-26",
+ "2029-02-14",
+ "2030-02-04",
+ "2031-01-24",
+ "2032-01-14",
+ "2033-01-02",
+ "2033-12-23",
+ "2034-12-12",
+ "2035-12-01",
+ "2036-11-19",
+ "2037-11-08",
+ "2038-10-29",
+ "2039-10-19",
+ "2040-10-07",
+ "2041-09-26",
+ "2042-09-15",
+ "2043-09-04",
+ "2044-08-24",
+ "2045-08-14",
+ "2046-08-03",
+ "2047-07-24",
+ "2048-07-12",
+ "2049-07-01",
+ ]
+)
+
+# Malaysia's observances of Eid al-Adha
+malaysia_eid_al_adha = pd.to_datetime(
+ [
+ "1981-10-08",
+ "1982-09-27",
+ "1983-09-17",
+ "1984-09-05",
+ "1985-08-26",
+ "1986-08-15",
+ "1987-08-04",
+ "1988-07-23",
+ "1989-07-13",
+ "1990-07-02",
+ "1991-06-22",
+ "1992-06-11",
+ "1993-05-31",
+ "1994-05-20",
+ "1995-05-09",
+ "1996-04-27",
+ "1997-04-17",
+ "1998-04-07",
+ "1999-03-27",
+ "2000-03-16",
+ "2001-03-05",
+ "2002-02-23",
+ "2003-02-12",
+ "2004-02-03",
+ "2005-01-21",
+ "2006-01-10",
+ "2007-01-02",
+ "2007-12-20",
+ "2008-12-08",
+ "2009-11-27",
+ "2010-11-17",
+ "2011-11-06",
+ "2012-10-26",
+ "2013-10-15",
+ "2014-10-05",
+ "2015-09-24",
+ "2016-09-12",
+ "2017-09-01",
+ "2018-08-22",
+ "2019-08-11",
+ "2020-07-31",
+ "2021-07-20",
+ "2022-07-10",
+ "2023-06-29",
+ "2024-06-16",
+ "2025-06-06",
+ "2026-05-27",
+ "2027-05-16",
+ "2028-05-05",
+ "2029-04-24",
+ "2030-04-13",
+ "2031-04-02",
+ "2032-03-22",
+ "2033-03-11",
+ "2034-03-01",
+ "2035-02-18",
+ "2036-02-07",
+ "2037-01-26",
+ "2038-01-16",
+ "2039-01-05",
+ "2039-12-26",
+ "2040-12-14",
+ "2041-12-04",
+ "2042-11-23",
+ "2043-11-12",
+ "2044-10-31",
+ "2045-10-21",
+ "2046-10-10",
+ "2047-09-30",
+ "2048-09-19",
+ "2049-09-08",
+ ]
+)
+
+# Malaysia's observances of Deepavali (Hindu Lunar Calendar)
+deepavali = pd.to_datetime(
+ [
+ "2002-11-04",
+ "2003-10-24",
+ "2004-11-11",
+ "2004-11-12",
+ "2005-11-01",
+ "2007-11-08",
+ "2008-10-27",
+ "2010-11-05",
+ "2011-10-26",
+ "2012-11-13",
+ "2014-10-22",
+ "2015-11-10",
+ "2017-10-18",
+ "2018-11-06",
+ "2019-10-28",
+ "2020-11-14",
+ "2021-11-04",
+ "2022-10-24",
+ "2023-11-13",
+ "2024-10-31",
+ ]
+)
+
+# Malaysia's observances of Thaipusam (Tamil Calendar)
+thaipusam = pd.to_datetime(
+ [
+ "2008-01-23",
+ "2009-02-09",
+ "2010-01-30",
+ "2011-01-20",
+ "2012-02-07",
+ "2013-01-28",
+ "2014-01-17",
+ "2015-02-03",
+ "2016-01-25",
+ "2017-02-09",
+ "2018-01-31",
+ "2019-01-21",
+ "2020-02-08",
+ "2021-01-28",
+ "2022-01-18",
+ "2023-02-04",
+ "2024-01-25",
+ ]
+)
+
+# Malaysia's observances of Wesak Day (Chinese Lunar Calendar)
+# source: https://publicholidays.com.my/wesak-day/
+wesak_day = pd.to_datetime(
+ [
+ "2003-05-15",
+ "2004-05-04",
+ "2005-05-23",
+ "2006-05-12",
+ "2007-05-02",
+ "2008-05-19",
+ "2010-05-28",
+ "2011-05-17",
+ "2013-05-24",
+ "2014-05-13",
+ "2015-05-04",
+ "2017-05-10",
+ "2018-05-29",
+ "2019-05-20",
+ "2020-05-07",
+ "2021-05-26",
+ "2022-05-15",
+ "2023-05-04",
+ "2024-05-22"
+ ]
+)
+
+misc_adhoc = pd.to_datetime(
+ [
+ "2024-06-03", # Yang di-Pertuan Agong's Birthday
+ "2023-06-05", # Yang di-Pertuan Agong's Birthday
+ "2023-04-21", # Special Public Holiday's announced by Anwar
+ "2022-06-06", # Yang di-Pertuan Agong's Birthday
+ "2021-06-07", # Yang di-Pertuan Agong's Birthday
+ "2020-06-08", # Yang di-Pertuan Agong's Birthday
+ "2019-09-09", # Yang di-Pertuan Agong's Birthday
+ "2019-07-30", # Installation of Yang di-Pertuan Agong
+ "2018-09-10", # Yang di-Pertuan Agong's Birthday
+ "2018-05-11", # Special Holiday (probably post election holiday?)
+ "2018-05-10", # Special Holiday (same as above)
+ "2018-05-09", # Election Day
+ "2017-09-04", # Public Holiday for success in Sea Games
+ "2017-04-24", # Installation of Yang di-Pertuan Agong
+ "2014-02-03", # 2nd Day Chinese New Year (made up on Tues?)
+ "2012-04-11", # Installation of Yang di-Pertuan Agong
+ "2011-09-01", # Eid al-Fitr extra day
+ "2010-12-31", # New Year's Eve Observed
+ "2008-07-03", # Trading suspended
+ "2007-04-26", # Installation of Yang di-Pertuan Agong
+ "2006-10-25", # Eid al-Fitr extra day
+ "2006-02-02", # Federal Territory Day made up b.c. Muharram
+ "2004-01-21", # Chinese New Year extra day
+ "2003-11-24", # Eid al-Fitr extra day
+ "2003-02-04", # Chinese New Year extra day
+ "2003-01-31", # Chinese New Year extra day
+ "2002-04-25", # Installation of Yang di-Pertuan Agong
+ "2002-02-11", # Chinese New Year extra day
+ ]
+)
+
+
+NewYearsDay = new_years_day(observance=sunday_to_monday)
+
+Thaipusam = thaipusam
+
+FederalTerritoryDay = Holiday(
+ "Federal Territory Day",
+ month=2,
+ day=1,
+ observance=sunday_to_monday,
+)
+
+ChineseNewYear = pd.to_datetime(
+ chinese_lunar_new_year_dates.map(lambda d: sunday_to_monday(d))
+)
+
+ChineseNewYearDay2 = (ChineseNewYear + timedelta(1)).map(lambda d: sunday_to_monday(d))
+
+LabourDay = european_labour_day(observance=sunday_to_monday)
+
+WesakDay = wesak_day
+
+NuzulAlQuran = malaysia_nuzul_al_quran.map(lambda d: sunday_to_monday(d))
+
+EidAlFitrDay1 = pd.to_datetime(
+ malaysia_eid_al_fitr_first_day.map(lambda d: sunday_to_monday(d))
+)
+
+EidAlFitrDay2 = (EidAlFitrDay1 + timedelta(1)).map(lambda d: sunday_to_monday(d))
+
+EidAlAdha = malaysia_eid_al_adha.map(lambda d: sunday_to_monday(d))
+
+NationalDay = Holiday(
+ "National Day",
+ month=8,
+ day=31,
+ observance=sunday_to_monday,
+)
+
+Muharram = muharram.map(lambda d: sunday_to_monday(d))
+
+MalaysiaDay = Holiday(
+ "Malaysia Day",
+ month=9,
+ day=16,
+ start_date="2010",
+ observance=sunday_to_monday,
+)
+
+Deepavali = deepavali
+
+MuhammadBirthday = muhammad_birthday.map(lambda d: sunday_to_monday(d))
+
+ChristmasDay = christmas(observance=sunday_to_monday)
+
+# Early closes - Chinese New Year's Eve and Eid al-Fitr Eve
+ChineseNewYearsEve = ChineseNewYear - timedelta(1)
+
+ChineseNewYearsHalfDay = [
+ day for day in ChineseNewYearsEve if day.weekday() not in WEEKENDS
+]
+
+EidAlFitrEve = EidAlFitrDay1 - timedelta(1)
+
+EidAlFitrHalfDay = [day for day in EidAlFitrEve if day.weekday() not in WEEKENDS]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xkrx_holidays.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xkrx_holidays.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f5051e02b426d39b82fce1b3fce3306e690ed43
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xkrx_holidays.py
@@ -0,0 +1,1337 @@
+import pandas as pd
+
+from pandas.tseries.offsets import Day
+
+from .pandas_extensions.holiday import Holiday
+from .pandas_extensions.korean_holiday import (
+ KoreanSolarHoliday,
+ KoreanLunarHoliday,
+ alternative_holiday,
+ alternative_holiday_for_seollal_and_chuseok,
+ alternative_holiday_for_childrens_day,
+ last_business_day,
+)
+
+# Original precomputed KRX holidays
+# that had been maintained formerly in exchange_calendar_xkrx.py.
+original_precomputed_krx_holidays = pd.DatetimeIndex(
+ [
+ "1986-01-01",
+ "1986-01-02",
+ "1986-01-03",
+ "1986-03-10",
+ "1986-05-05",
+ "1986-05-16",
+ "1986-06-06",
+ "1986-07-17",
+ "1986-08-15",
+ "1986-09-18",
+ "1986-10-01",
+ "1986-10-03",
+ "1986-10-09",
+ "1986-12-25",
+ "1986-12-29",
+ "1986-12-30",
+ "1986-12-31",
+ "1987-01-01",
+ "1987-01-02",
+ "1987-01-29",
+ "1987-03-10",
+ "1987-05-05",
+ "1987-07-17",
+ "1987-10-01",
+ "1987-10-07",
+ "1987-10-08",
+ "1987-10-09",
+ "1987-12-25",
+ "1987-12-28",
+ "1987-12-29",
+ "1987-12-30",
+ "1987-12-31",
+ "1988-01-01",
+ "1988-02-18",
+ "1988-03-01",
+ "1988-03-10",
+ "1988-04-05",
+ "1988-05-05",
+ "1988-05-23",
+ "1988-06-06",
+ "1988-08-15",
+ "1988-09-26",
+ "1988-10-03",
+ "1988-12-27",
+ "1988-12-28",
+ "1988-12-29",
+ "1988-12-30",
+ "1989-01-02",
+ "1989-01-03",
+ "1989-02-06",
+ "1989-03-01",
+ "1989-03-10",
+ "1989-04-05",
+ "1989-05-05",
+ "1989-05-12",
+ "1989-06-06",
+ "1989-07-17",
+ "1989-08-15",
+ "1989-09-14",
+ "1989-09-15",
+ "1989-10-12",
+ "1989-12-25",
+ "1990-01-01",
+ "1990-01-02",
+ "1990-01-26",
+ "1990-03-01",
+ "1990-04-05",
+ "1990-05-02",
+ "1990-06-06",
+ "1990-07-17",
+ "1990-08-15",
+ "1990-10-01",
+ "1990-10-02",
+ "1990-10-03",
+ "1990-10-04",
+ "1990-10-09",
+ "1990-12-25",
+ "1990-12-27",
+ "1990-12-28",
+ "1990-12-31",
+ "1991-01-02",
+ "1991-02-14",
+ "1991-02-15",
+ "1991-03-01",
+ "1991-04-05",
+ "1991-05-21",
+ "1991-06-06",
+ "1991-07-17",
+ "1991-08-15",
+ "1991-09-23",
+ "1991-10-03",
+ "1991-12-25",
+ "1991-12-27",
+ "1991-12-30",
+ "1991-12-31",
+ "1992-01-01",
+ "1992-01-02",
+ "1992-02-03",
+ "1992-02-04",
+ "1992-02-05",
+ "1992-03-10",
+ "1992-05-05",
+ "1992-07-17",
+ "1992-09-10",
+ "1992-09-11",
+ "1992-12-25",
+ "1992-12-28",
+ "1992-12-29",
+ "1992-12-30",
+ "1992-12-31",
+ "1993-01-01",
+ "1993-01-22",
+ "1993-03-01",
+ "1993-03-10",
+ "1993-04-05",
+ "1993-05-05",
+ "1993-05-28",
+ "1993-07-07",
+ "1993-09-29",
+ "1993-09-30",
+ "1993-10-01",
+ "1994-01-03",
+ "1994-02-09",
+ "1994-02-10",
+ "1994-02-11",
+ "1994-02-14",
+ "1994-03-01",
+ "1994-04-05",
+ "1994-05-05",
+ "1994-05-18",
+ "1994-05-20",
+ "1994-06-06",
+ "1994-08-15",
+ "1994-09-19",
+ "1994-09-20",
+ "1994-09-21",
+ "1994-10-03",
+ "1994-12-29",
+ "1994-12-30",
+ "1995-01-02",
+ "1995-01-30",
+ "1995-01-31",
+ "1995-02-01",
+ "1995-03-01",
+ "1995-04-05",
+ "1995-05-01",
+ "1995-05-05",
+ "1995-06-06",
+ "1995-07-17",
+ "1995-08-15",
+ "1995-09-08",
+ "1995-10-03",
+ "1995-12-25",
+ "1995-12-29",
+ "1996-01-01",
+ "1996-01-02",
+ "1996-02-19",
+ "1996-02-20",
+ "1996-03-01",
+ "1996-04-05",
+ "1996-05-01",
+ "1996-05-24",
+ "1996-06-06",
+ "1996-07-17",
+ "1996-08-15",
+ "1996-09-26",
+ "1996-09-27",
+ "1996-10-03",
+ "1996-12-25",
+ "1996-12-30",
+ "1996-12-31",
+ "1997-01-01",
+ "1997-02-07",
+ "1997-05-01",
+ "1997-05-05",
+ "1997-05-14",
+ "1997-06-06",
+ "1997-07-17",
+ "1997-08-15",
+ "1997-09-15",
+ "1997-09-16",
+ "1997-09-17",
+ "1997-10-03",
+ "1997-12-18",
+ "1997-12-25",
+ "1997-12-30",
+ "1997-12-31",
+ "1998-01-01",
+ "1998-01-02",
+ "1998-01-27",
+ "1998-01-28",
+ "1998-01-29",
+ "1998-05-01",
+ "1998-05-05",
+ "1998-07-17",
+ "1998-10-05",
+ "1998-10-06",
+ "1998-12-25",
+ "1998-12-29",
+ "1998-12-30",
+ "1998-12-31",
+ "1999-01-01",
+ "1999-02-15",
+ "1999-02-16",
+ "1999-02-17",
+ "1999-03-01",
+ "1999-04-05",
+ "1999-05-05",
+ "1999-09-23",
+ "1999-09-24",
+ "1999-12-29",
+ "1999-12-30",
+ "1999-12-31",
+ "2000-01-03",
+ "2000-02-04",
+ "2000-03-01",
+ "2000-04-05",
+ "2000-04-13",
+ "2000-05-01",
+ "2000-05-05",
+ "2000-05-11",
+ "2000-06-06",
+ "2000-07-17",
+ "2000-08-15",
+ "2000-09-11",
+ "2000-09-12",
+ "2000-09-13",
+ "2000-10-03",
+ "2000-12-25",
+ "2000-12-27",
+ "2000-12-28",
+ "2000-12-29",
+ "2001-01-01",
+ "2001-01-23",
+ "2001-01-24",
+ "2001-01-25",
+ "2001-03-01",
+ "2001-04-05",
+ "2001-05-01",
+ "2001-06-06",
+ "2001-07-17",
+ "2001-08-15",
+ "2001-10-01",
+ "2001-10-02",
+ "2001-10-03",
+ "2001-12-25",
+ "2001-12-31",
+ "2002-01-01",
+ "2002-02-11",
+ "2002-02-12",
+ "2002-02-13",
+ "2002-03-01",
+ "2002-04-05",
+ "2002-05-01",
+ "2002-06-06",
+ "2002-06-13",
+ "2002-07-01",
+ "2002-07-17",
+ "2002-08-15",
+ "2002-09-20",
+ "2002-10-03",
+ "2002-12-19",
+ "2002-12-25",
+ "2002-12-31",
+ "2003-01-01",
+ "2003-01-31",
+ "2003-05-01",
+ "2003-05-05",
+ "2003-05-08",
+ "2003-06-06",
+ "2003-07-17",
+ "2003-08-15",
+ "2003-09-10",
+ "2003-09-11",
+ "2003-09-12",
+ "2003-10-03",
+ "2003-12-25",
+ "2003-12-31",
+ "2004-01-01",
+ "2004-01-21",
+ "2004-01-22",
+ "2004-01-23",
+ "2004-03-01",
+ "2004-04-05",
+ "2004-04-15",
+ "2004-05-05",
+ "2004-05-26",
+ "2004-09-27",
+ "2004-09-28",
+ "2004-09-29",
+ "2004-12-31",
+ "2005-02-08",
+ "2005-02-09",
+ "2005-02-10",
+ "2005-03-01",
+ "2005-04-05",
+ "2005-05-05",
+ "2005-06-06",
+ "2005-08-15",
+ "2005-09-19",
+ "2005-10-03",
+ "2005-12-30",
+ "2006-01-30",
+ "2006-03-01",
+ "2006-05-01",
+ "2006-05-05",
+ "2006-05-31",
+ "2006-06-06",
+ "2006-07-17",
+ "2006-08-15",
+ "2006-10-03",
+ "2006-10-05",
+ "2006-10-06",
+ "2006-12-25",
+ "2006-12-29",
+ "2007-01-01",
+ "2007-02-19",
+ "2007-03-01",
+ "2007-05-01",
+ "2007-05-24",
+ "2007-06-06",
+ "2007-07-17",
+ "2007-08-15",
+ "2007-09-24",
+ "2007-09-25",
+ "2007-09-26",
+ "2007-10-03",
+ "2007-12-19",
+ "2007-12-25",
+ "2007-12-31",
+ "2008-01-01",
+ "2008-02-06",
+ "2008-02-07",
+ "2008-02-08",
+ "2008-04-09",
+ "2008-05-01",
+ "2008-05-05",
+ "2008-05-12",
+ "2008-06-06",
+ "2008-08-15",
+ "2008-09-15",
+ "2008-10-03",
+ "2008-12-25",
+ "2008-12-31",
+ "2009-01-01",
+ "2009-01-26",
+ "2009-01-27",
+ "2009-05-01",
+ "2009-05-05",
+ "2009-10-02",
+ "2009-12-25",
+ "2009-12-31",
+ "2010-01-01",
+ "2010-02-15",
+ "2010-03-01",
+ "2010-05-05",
+ "2010-05-21",
+ "2010-06-02",
+ "2010-09-21",
+ "2010-09-22",
+ "2010-09-23",
+ "2010-12-31",
+ "2011-02-02",
+ "2011-02-03",
+ "2011-02-04",
+ "2011-03-01",
+ "2011-05-05",
+ "2011-05-10",
+ "2011-06-06",
+ "2011-08-15",
+ "2011-09-12",
+ "2011-09-13",
+ "2011-10-03",
+ "2011-12-30",
+ "2012-01-23",
+ "2012-01-24",
+ "2012-03-01",
+ "2012-04-11",
+ "2012-05-01",
+ "2012-05-28",
+ "2012-06-06",
+ "2012-08-15",
+ "2012-10-01",
+ "2012-10-03",
+ "2012-12-19",
+ "2012-12-25",
+ "2012-12-31",
+ "2013-01-01",
+ "2013-02-11",
+ "2013-03-01",
+ "2013-05-01",
+ "2013-05-17",
+ "2013-06-06",
+ "2013-08-15",
+ "2013-09-18",
+ "2013-09-19",
+ "2013-09-20",
+ "2013-10-03",
+ "2013-10-09",
+ "2013-12-25",
+ "2013-12-31",
+ "2014-01-01",
+ "2014-01-30",
+ "2014-01-31",
+ "2014-05-01",
+ "2014-05-05",
+ "2014-05-06",
+ "2014-06-04",
+ "2014-06-06",
+ "2014-08-15",
+ "2014-09-08",
+ "2014-09-09",
+ "2014-09-10",
+ "2014-10-03",
+ "2014-10-09",
+ "2014-12-25",
+ "2014-12-31",
+ "2015-01-01",
+ "2015-02-18",
+ "2015-02-19",
+ "2015-02-20",
+ "2015-05-01",
+ "2015-05-05",
+ "2015-05-25",
+ "2015-08-14",
+ "2015-09-28",
+ "2015-09-29",
+ "2015-10-09",
+ "2015-12-25",
+ "2015-12-31",
+ "2016-01-01",
+ "2016-02-08",
+ "2016-02-09",
+ "2016-02-10",
+ "2016-03-01",
+ "2016-04-13",
+ "2016-05-05",
+ "2016-05-06",
+ "2016-06-06",
+ "2016-08-15",
+ "2016-09-14",
+ "2016-09-15",
+ "2016-09-16",
+ "2016-10-03",
+ "2016-12-30",
+ "2017-01-27",
+ "2017-01-30",
+ "2017-03-01",
+ "2017-05-01",
+ "2017-05-03",
+ "2017-05-05",
+ "2017-05-09",
+ "2017-06-06",
+ "2017-08-15",
+ "2017-10-02",
+ "2017-10-03",
+ "2017-10-04",
+ "2017-10-05",
+ "2017-10-06",
+ "2017-10-09",
+ "2017-12-25",
+ "2017-12-29",
+ "2018-01-01",
+ "2018-02-15",
+ "2018-02-16",
+ "2018-03-01",
+ "2018-05-01",
+ "2018-05-07",
+ "2018-05-22",
+ "2018-06-06",
+ "2018-06-13",
+ "2018-08-15",
+ "2018-09-24",
+ "2018-09-25",
+ "2018-09-26",
+ "2018-10-03",
+ "2018-10-09",
+ "2018-12-25",
+ "2018-12-31",
+ "2019-01-01",
+ "2019-02-04",
+ "2019-02-05",
+ "2019-02-06",
+ "2019-03-01",
+ "2019-05-01",
+ "2019-05-06",
+ "2019-06-06",
+ "2019-08-15",
+ "2019-09-12",
+ "2019-09-13",
+ "2019-10-03",
+ "2019-10-09",
+ "2019-12-25",
+ "2019-12-31",
+ "2020-01-01",
+ "2020-01-24",
+ "2020-01-27",
+ "2020-04-15",
+ "2020-04-30",
+ "2020-05-01",
+ "2020-05-05",
+ "2020-08-17",
+ "2020-09-30",
+ "2020-10-01",
+ "2020-10-02",
+ "2020-10-09",
+ "2020-12-25",
+ "2020-12-31",
+ "2021-01-01",
+ "2021-02-11",
+ "2021-02-12",
+ "2021-03-01",
+ "2021-05-05",
+ "2021-05-19",
+ "2021-09-20",
+ "2021-09-21",
+ "2021-09-22",
+ "2021-12-31",
+ ]
+)
+
+
+# Automatically generated holidays using /etc/update_xkrx_holidays.py script.
+# Note that there are some missing holidays compared to the original holidays.
+dumped_precomputed_krx_holidays = pd.DatetimeIndex(
+ [
+ "1975-02-12",
+ "1975-03-10",
+ "1975-05-05",
+ "1975-06-06",
+ "1975-07-17",
+ "1975-08-15",
+ "1975-10-03",
+ "1975-10-09",
+ "1975-10-24",
+ "1975-12-25",
+ "1975-12-29",
+ "1975-12-30",
+ "1975-12-31",
+ "1976-01-01",
+ "1976-01-02",
+ "1976-03-01",
+ "1976-03-10",
+ "1976-04-05",
+ "1976-05-05",
+ "1976-05-06",
+ "1976-09-08",
+ "1976-10-01",
+ "1976-12-29",
+ "1976-12-30",
+ "1976-12-31",
+ "1977-01-03",
+ "1977-03-01",
+ "1977-03-10",
+ "1977-04-05",
+ "1977-05-05",
+ "1977-05-25",
+ "1977-06-06",
+ "1977-08-15",
+ "1977-09-27",
+ "1977-10-03",
+ "1977-12-26",
+ "1977-12-27",
+ "1977-12-28",
+ "1977-12-29",
+ "1977-12-30",
+ "1978-01-02",
+ "1978-01-03",
+ "1978-03-01",
+ "1978-03-10",
+ "1978-04-05",
+ "1978-05-05",
+ "1978-05-18",
+ "1978-06-06",
+ "1978-07-17",
+ "1978-08-15",
+ "1978-10-03",
+ "1978-10-09",
+ "1978-12-12",
+ "1978-12-25",
+ "1978-12-26",
+ "1978-12-27",
+ "1978-12-28",
+ "1978-12-29",
+ "1979-01-01",
+ "1979-01-02",
+ "1979-01-03",
+ "1979-03-01",
+ "1979-04-05",
+ "1979-05-03",
+ "1979-06-06",
+ "1979-07-17",
+ "1979-08-15",
+ "1979-10-01",
+ "1979-10-03",
+ "1979-10-05",
+ "1979-10-09",
+ "1979-12-21",
+ "1979-12-25",
+ "1979-12-26",
+ "1979-12-27",
+ "1979-12-28",
+ "1979-12-31",
+ "1980-01-01",
+ "1980-01-02",
+ "1980-01-03",
+ "1980-03-10",
+ "1980-05-05",
+ "1980-05-21",
+ "1980-06-06",
+ "1980-07-17",
+ "1980-08-15",
+ "1980-09-01",
+ "1980-09-23",
+ "1980-10-01",
+ "1980-10-03",
+ "1980-10-09",
+ "1980-10-22",
+ "1980-12-25",
+ "1980-12-26",
+ "1980-12-29",
+ "1980-12-30",
+ "1980-12-31",
+ "1981-01-01",
+ "1981-01-02",
+ "1981-02-11",
+ "1981-03-03",
+ "1981-03-10",
+ "1981-03-25",
+ "1981-05-05",
+ "1981-05-11",
+ "1981-07-17",
+ "1981-10-01",
+ "1981-10-09",
+ "1981-12-25",
+ "1981-12-28",
+ "1981-12-29",
+ "1981-12-30",
+ "1981-12-31",
+ "1982-01-01",
+ "1982-03-01",
+ "1982-03-10",
+ "1982-04-05",
+ "1982-05-05",
+ "1982-10-01",
+ "1982-12-27",
+ "1982-12-28",
+ "1982-12-29",
+ "1982-12-30",
+ "1982-12-31",
+ "1983-01-03",
+ "1983-03-01",
+ "1983-03-10",
+ "1983-04-05",
+ "1983-05-05",
+ "1983-05-20",
+ "1983-06-06",
+ "1983-08-15",
+ "1983-09-21",
+ "1983-10-03",
+ "1983-12-26",
+ "1983-12-27",
+ "1983-12-28",
+ "1983-12-29",
+ "1983-12-30",
+ "1984-01-02",
+ "1984-01-03",
+ "1984-03-01",
+ "1984-04-05",
+ "1984-05-08",
+ "1984-06-06",
+ "1984-07-17",
+ "1984-08-15",
+ "1984-09-10",
+ "1984-10-01",
+ "1984-10-03",
+ "1984-10-09",
+ "1984-12-25",
+ "1984-12-26",
+ "1984-12-27",
+ "1984-12-28",
+ "1984-12-31",
+ "1985-01-01",
+ "1985-01-02",
+ "1985-01-03",
+ "1985-02-12",
+ "1985-02-20",
+ "1985-03-01",
+ "1985-04-05",
+ "1985-05-27",
+ "1985-06-06",
+ "1985-07-17",
+ "1985-08-15",
+ "1985-10-01",
+ "1985-10-03",
+ "1985-10-09",
+ "1985-12-25",
+ "1985-12-27",
+ "1985-12-30",
+ "1985-12-31",
+ "1986-01-01",
+ "1986-01-02",
+ "1986-01-03",
+ "1986-03-10",
+ "1986-05-05",
+ "1986-05-16",
+ "1986-06-06",
+ "1986-07-17",
+ "1986-08-15",
+ "1986-09-18",
+ "1986-09-19",
+ "1986-10-01",
+ "1986-10-03",
+ "1986-10-09",
+ "1986-12-25",
+ "1986-12-29",
+ "1986-12-30",
+ "1986-12-31",
+ "1987-01-01",
+ "1987-01-02",
+ "1987-01-29",
+ "1987-03-10",
+ "1987-05-05",
+ "1987-07-17",
+ "1987-10-01",
+ "1987-10-07",
+ "1987-10-08",
+ "1987-10-09",
+ "1987-10-27",
+ "1987-12-16",
+ "1987-12-25",
+ "1987-12-28",
+ "1987-12-29",
+ "1987-12-30",
+ "1987-12-31",
+ "1988-01-01",
+ "1988-02-18",
+ "1988-02-25",
+ "1988-03-01",
+ "1988-03-10",
+ "1988-04-05",
+ "1988-04-26",
+ "1988-05-05",
+ "1988-05-23",
+ "1988-06-06",
+ "1988-08-15",
+ "1988-09-26",
+ "1988-10-03",
+ "1988-12-27",
+ "1988-12-28",
+ "1988-12-29",
+ "1988-12-30",
+ "1989-01-02",
+ "1989-01-03",
+ "1989-02-06",
+ "1989-02-07",
+ "1989-03-01",
+ "1989-03-10",
+ "1989-04-05",
+ "1989-05-05",
+ "1989-05-12",
+ "1989-06-06",
+ "1989-07-17",
+ "1989-08-15",
+ "1989-09-13",
+ "1989-09-14",
+ "1989-09-15",
+ "1989-10-02",
+ "1989-10-03",
+ "1989-10-09",
+ "1989-12-25",
+ "1989-12-27",
+ "1989-12-28",
+ "1989-12-29",
+ "1990-01-01",
+ "1990-01-02",
+ "1990-01-26",
+ "1990-03-01",
+ "1990-04-05",
+ "1990-05-02",
+ "1990-06-06",
+ "1990-07-17",
+ "1990-08-15",
+ "1990-10-01",
+ "1990-10-02",
+ "1990-10-03",
+ "1990-10-04",
+ "1990-10-09",
+ "1990-12-25",
+ "1990-12-27",
+ "1990-12-28",
+ "1990-12-31",
+ "1991-01-01",
+ "1991-01-02",
+ "1991-02-14",
+ "1991-02-15",
+ "1991-03-01",
+ "1991-03-26",
+ "1991-04-05",
+ "1991-05-21",
+ "1991-06-06",
+ "1991-06-20",
+ "1991-07-17",
+ "1991-08-15",
+ "1991-09-23",
+ "1991-10-03",
+ "1991-12-25",
+ "1991-12-27",
+ "1991-12-30",
+ "1991-12-31",
+ "1992-01-01",
+ "1992-01-02",
+ "1992-02-03",
+ "1992-02-04",
+ "1992-02-05",
+ "1992-03-10",
+ "1992-03-24",
+ "1992-05-05",
+ "1992-07-17",
+ "1992-09-10",
+ "1992-09-11",
+ "1992-12-18",
+ "1992-12-25",
+ "1992-12-29",
+ "1992-12-30",
+ "1992-12-31",
+ "1993-01-01",
+ "1993-01-22",
+ "1993-03-01",
+ "1993-03-10",
+ "1993-04-05",
+ "1993-05-05",
+ "1993-05-28",
+ "1993-09-29",
+ "1993-09-30",
+ "1993-10-01",
+ "1993-12-29",
+ "1993-12-30",
+ "1993-12-31",
+ "1994-02-09",
+ "1994-02-10",
+ "1994-02-11",
+ "1994-03-01",
+ "1994-04-05",
+ "1994-05-05",
+ "1994-05-18",
+ "1994-06-06",
+ "1994-08-15",
+ "1994-09-19",
+ "1994-09-20",
+ "1994-09-21",
+ "1994-10-03",
+ "1995-01-02",
+ "1996-01-01",
+ "1996-01-02",
+ "1997-01-01",
+ "1997-01-02",
+ "1997-12-29",
+ "1997-12-30",
+ "1997-12-31",
+ "1998-01-01",
+ "1998-01-02",
+ "1998-12-29",
+ "1998-12-30",
+ "1998-12-31",
+ "1999-01-01",
+ "1999-12-29",
+ "1999-12-30",
+ "1999-12-31",
+ "2000-01-03",
+ "2000-12-27",
+ "2000-12-28",
+ "2000-12-29",
+ "2001-01-01",
+ "2001-12-31",
+ "2002-01-01",
+ "2002-12-31",
+ "2003-01-01",
+ "2003-12-31",
+ "2004-01-01",
+ "2004-12-31",
+ "2005-12-30",
+ "2006-12-29",
+ "2007-01-01",
+ "2007-12-31",
+ "2008-01-01",
+ "2008-04-09",
+ "2008-05-05",
+ "2008-05-12",
+ "2008-08-15",
+ "2008-09-15",
+ "2008-10-03",
+ "2008-12-25",
+ "2008-12-31",
+ "2009-01-01",
+ "2009-01-26",
+ "2009-01-27",
+ "2009-05-01",
+ "2009-05-05",
+ "2009-10-02",
+ "2009-12-25",
+ "2009-12-31",
+ "2010-01-01",
+ "2010-02-15",
+ "2010-03-01",
+ "2010-05-05",
+ "2010-05-21",
+ "2010-06-02",
+ "2010-09-21",
+ "2010-09-22",
+ "2010-09-23",
+ "2010-12-31",
+ "2011-02-02",
+ "2011-02-03",
+ "2011-02-04",
+ "2011-03-01",
+ "2011-05-05",
+ "2011-05-10",
+ "2011-06-06",
+ "2011-08-15",
+ "2011-09-12",
+ "2011-09-13",
+ "2011-10-03",
+ "2011-12-30",
+ "2012-01-23",
+ "2012-01-24",
+ "2012-03-01",
+ "2012-04-11",
+ "2012-05-01",
+ "2012-05-28",
+ "2012-06-06",
+ "2012-08-15",
+ "2012-10-01",
+ "2012-10-03",
+ "2012-12-19",
+ "2012-12-25",
+ "2012-12-31",
+ "2013-01-01",
+ "2013-02-11",
+ "2013-03-01",
+ "2013-05-01",
+ "2013-05-17",
+ "2013-06-06",
+ "2013-08-15",
+ "2013-09-18",
+ "2013-09-19",
+ "2013-09-20",
+ "2013-10-03",
+ "2013-10-09",
+ "2013-12-25",
+ "2013-12-31",
+ "2014-01-01",
+ "2014-01-30",
+ "2014-01-31",
+ "2014-05-01",
+ "2014-05-05",
+ "2014-05-06",
+ "2014-06-04",
+ "2014-06-06",
+ "2014-08-15",
+ "2014-09-08",
+ "2014-09-09",
+ "2014-09-10",
+ "2014-10-03",
+ "2014-10-09",
+ "2014-12-25",
+ "2014-12-31",
+ "2015-01-01",
+ "2015-02-18",
+ "2015-02-19",
+ "2015-02-20",
+ "2015-05-01",
+ "2015-05-05",
+ "2015-05-25",
+ "2015-08-14",
+ "2015-09-28",
+ "2015-09-29",
+ "2015-10-09",
+ "2015-12-25",
+ "2015-12-31",
+ "2016-01-01",
+ "2016-02-08",
+ "2016-02-09",
+ "2016-02-10",
+ "2016-03-01",
+ "2016-04-13",
+ "2016-05-05",
+ "2016-05-06",
+ "2016-06-06",
+ "2016-08-15",
+ "2016-09-14",
+ "2016-09-15",
+ "2016-09-16",
+ "2016-10-03",
+ "2016-12-30",
+ "2017-01-27",
+ "2017-01-30",
+ "2017-03-01",
+ "2017-05-01",
+ "2017-05-03",
+ "2017-05-05",
+ "2017-05-09",
+ "2017-06-06",
+ "2017-08-15",
+ "2017-10-02",
+ "2017-10-03",
+ "2017-10-04",
+ "2017-10-05",
+ "2017-10-06",
+ "2017-10-09",
+ "2017-12-25",
+ "2017-12-29",
+ "2018-01-01",
+ "2018-02-15",
+ "2018-02-16",
+ "2018-03-01",
+ "2018-05-01",
+ "2018-05-07",
+ "2018-05-22",
+ "2018-06-06",
+ "2018-06-13",
+ "2018-08-15",
+ "2018-09-24",
+ "2018-09-25",
+ "2018-09-26",
+ "2018-10-03",
+ "2018-10-09",
+ "2018-12-25",
+ "2018-12-31",
+ "2019-01-01",
+ "2019-02-04",
+ "2019-02-05",
+ "2019-02-06",
+ "2019-03-01",
+ "2019-05-01",
+ "2019-05-06",
+ "2019-06-06",
+ "2019-08-15",
+ "2019-09-12",
+ "2019-09-13",
+ "2019-10-03",
+ "2019-10-09",
+ "2019-12-25",
+ "2019-12-31",
+ "2020-01-01",
+ "2020-01-24",
+ "2020-01-27",
+ "2020-04-15",
+ "2020-04-30",
+ "2020-05-01",
+ "2020-05-05",
+ "2020-08-17",
+ "2020-09-30",
+ "2020-10-01",
+ "2020-10-02",
+ "2020-10-09",
+ "2020-12-25",
+ "2020-12-31",
+ "2021-01-01",
+ "2021-02-11",
+ "2021-02-12",
+ "2021-03-01",
+ "2021-05-05",
+ "2021-05-19",
+ "2021-08-16",
+ "2021-09-20",
+ "2021-09-21",
+ "2021-09-22",
+ "2021-10-04",
+ "2021-10-11",
+ "2021-12-31",
+ "2022-01-31",
+ "2022-02-01",
+ "2022-02-02",
+ "2022-03-01",
+ "2022-03-09",
+ "2022-05-05",
+ "2022-06-01",
+ "2022-06-06",
+ "2022-08-15",
+ "2022-09-09",
+ "2022-09-12",
+ "2022-10-03",
+ "2022-10-10",
+ "2022-12-30",
+ ]
+)
+
+# This index contains holidays that were manually copied from the exchange website
+# (https://global.krx.co.kr/contents/GLB/05/0501/0501110000/GLB0501110000.jsp)
+manually_added_holidays = pd.DatetimeIndex(
+ [
+ "2023-05-29", # Buddha's birthday holiday in lieu
+ "2023-10-02", # Extra day for Chuseok holiday
+ ]
+)
+
+
+# Merging two holidays to get full precomputed holidays list.
+precomputed_krx_holidays = original_precomputed_krx_holidays.union(
+ dumped_precomputed_krx_holidays
+).union(manually_added_holidays)
+
+
+# Korean regular holidays
+NewYearsDay = KoreanSolarHoliday(
+ "New Years Day", month=1, day=1
+) # New years day previously had 2 additional following holidays
+NewYearsDayAfter = KoreanSolarHoliday(
+ "New Years Day (+1 day)",
+ month=1,
+ day=1,
+ offset=Day(1),
+ end_date=pd.Timestamp("1998-12-31"),
+) # This was also removed since 1999
+NewYearsDayAfterAfter = KoreanSolarHoliday(
+ "New Years Day (+2 day)",
+ month=1,
+ day=1,
+ offset=Day(2),
+ end_date=pd.Timestamp("1989-12-31"),
+) # The last additional holiday was removed after Seollal gained additional before/after holidays in 1989
+SeollalBefore = KoreanLunarHoliday(
+ "Seollal (New Year's Day by the lunar) (-1 day)",
+ month=1,
+ day=1,
+ offset=Day(-1),
+ observance=alternative_holiday_for_seollal_and_chuseok,
+ start_date=pd.Timestamp("1989-01-01"),
+) # Seollal gained additional before/after holidays since 1989
+Seollal = KoreanLunarHoliday(
+ "Seollal (New Year's Day by the lunar)",
+ month=1,
+ day=1,
+ observance=alternative_holiday_for_seollal_and_chuseok,
+ start_date=pd.Timestamp("1985-01-01"),
+) # Seollal newly became holiday since 1985
+SeollalAfter = KoreanLunarHoliday(
+ "Seollal (New Year's Day by the lunar) (+1 day)",
+ month=1,
+ day=1,
+ offset=Day(1),
+ observance=alternative_holiday_for_seollal_and_chuseok,
+ start_date=pd.Timestamp("1989-01-01"),
+) # Seollal gained additional before/after holidays since 1989
+IndependenceMovementDay = KoreanSolarHoliday(
+ "Independence Movement Day", month=3, day=1, observance=alternative_holiday
+)
+ArborDay = KoreanSolarHoliday(
+ "Arbor Day",
+ month=4,
+ day=5,
+ start_date=pd.Timestamp("1948-01-01"),
+ end_date=pd.Timestamp("2005-12-31"),
+) # Arbor day was holiday from 1948 to 2005
+BuddhasBirthday = KoreanLunarHoliday("Buddha's Birthday", month=4, day=8)
+OldLaborDay = KoreanSolarHoliday(
+ "Labor Day", month=3, day=10, end_date=pd.Timestamp("1993-12-31")
+)
+LoborDay = KoreanSolarHoliday(
+ "Labor Day", month=5, day=1, start_date=pd.Timestamp("1994-01-01")
+) # Labor day changed it's day from 03/10 to 05/01 since 1994
+ChildrensDay = KoreanSolarHoliday(
+ "Children's Day", month=5, day=5, observance=alternative_holiday_for_childrens_day
+)
+MemorialDay = KoreanSolarHoliday("Memorial Day", month=6, day=6)
+ConstitutionDay = KoreanSolarHoliday(
+ "Constitution Day",
+ month=7,
+ day=17,
+ start_date=pd.Timestamp("1949-10-01"),
+ end_date=pd.Timestamp("2007-12-31"),
+) # Constitution day was holiday from 1949 to 2007
+NationalLiberationDay = KoreanSolarHoliday(
+ "National Liberation Day", month=8, day=15, observance=alternative_holiday
+)
+ChuseokBefore = KoreanLunarHoliday(
+ "Chuseok (Korean Thanksgiving Day) (-1 day)",
+ month=8,
+ day=15,
+ offset=Day(-1),
+ observance=alternative_holiday_for_seollal_and_chuseok,
+ start_date=pd.Timestamp("1989-01-01"),
+) # Chuseok gained additional before holiday since 1989, along with Seollal
+Chuseok = KoreanLunarHoliday(
+ "Chuseok (Korean Thanksgiving Day)",
+ month=8,
+ day=15,
+ observance=alternative_holiday_for_seollal_and_chuseok,
+ start_date=pd.Timestamp("1949-01-01"),
+) # Chuseok originally had no before/after holidays
+ChuseokAfter = KoreanLunarHoliday(
+ "Chuseok (Korean Thanksgiving Day) (+1 day)",
+ month=8,
+ day=15,
+ offset=Day(1),
+ observance=alternative_holiday_for_seollal_and_chuseok,
+ start_date=pd.Timestamp("1986-01-01"),
+) # Chuseok gained additional following holiday since 1986
+ArmedForcesDay = KoreanSolarHoliday(
+ "Armed Forces Day",
+ month=10,
+ day=1,
+ start_date=pd.Timestamp("1976-01-01"),
+ end_date=pd.Timestamp("1990-12-31"),
+) # Armed forces day was holiday from 1976 to 1990
+KoreanNationalFoundationDay = KoreanSolarHoliday(
+ "Korean National Foundation Day", month=10, day=3, observance=alternative_holiday
+)
+OldHangulProclamationDay = KoreanSolarHoliday(
+ "Hangul Proclamation Day",
+ month=10,
+ day=9,
+ start_date=pd.Timestamp("1949-01-01"),
+ end_date=pd.Timestamp("1990-12-31"),
+) # Hangul Day was once excluded from national holidays in 1991
+HangulProclamationDay = KoreanSolarHoliday(
+ "Hangul Proclamation Day",
+ month=10,
+ day=9,
+ start_date=pd.Timestamp("2013-01-01"),
+ observance=alternative_holiday,
+) # Hangeul Day became national holiday again in 2013
+Christmas = KoreanSolarHoliday("Christmas", month=12, day=25)
+
+# KRX specific additional regular holiday
+# should not be a KoreanSolarHoliday in order to prevent this day being registered
+# into computed national holiday cache for the alternative holiday behavior.
+EndOfYearHoliday = Holiday(
+ "End of Year Holiday", month=12, day=31, observance=last_business_day
+)
+
+# Holidays that cannot apply alternative holiday rule
+korean_regular_holiday_rules_without_alternative_holiday_rule = [
+ NewYearsDay,
+ NewYearsDayAfter,
+ NewYearsDayAfterAfter,
+ IndependenceMovementDay,
+ ArborDay,
+ BuddhasBirthday,
+ OldLaborDay,
+ LoborDay,
+ MemorialDay,
+ ConstitutionDay,
+ NationalLiberationDay,
+ ArmedForcesDay,
+ KoreanNationalFoundationDay,
+ OldHangulProclamationDay,
+ HangulProclamationDay,
+ Christmas,
+]
+
+# Holidays that can apply alternative holiday rule
+korean_regular_holiday_rules_with_alternative_holiday_rule = [
+ Seollal,
+ SeollalAfter,
+ SeollalBefore,
+ ChildrensDay,
+ Chuseok,
+ ChuseokAfter,
+ ChuseokBefore,
+]
+
+# Here we are trying to calculate non alternative holidays first
+# and then calculate the alternative holidays later
+korean_regular_holiday_rules = (
+ korean_regular_holiday_rules_without_alternative_holiday_rule
+ + korean_regular_holiday_rules_with_alternative_holiday_rule
+)
+
+# Additional regular holidays for KRX
+krx_additional_regular_holiday_rules = [
+ EndOfYearHoliday,
+]
+
+# Add additional regular holidays for KRX to get full KRX regular holidays
+krx_regular_holiday_rules = (
+ korean_regular_holiday_rules + krx_additional_regular_holiday_rules
+)
+
+
+# Historical CSAT days
+# Theses are used for special offsets (30 minutes or 1 hour delay in schedule)
+# https://ko.wikipedia.org/wiki/%EC%97%B0%EB%8F%84%EB%B3%84_%EB%8C%80%ED%95%99%EC%88%98%ED%95%99%EB%8A%A5%EB%A0%A5%EC%8B%9C%ED%97%98
+
+precomputed_csat_days = pd.DatetimeIndex(
+ [
+ "1993-08-20", # https://www.hankyung.com/news/article/1993081702291 0940~1140, 1320~1520 => 1010~1210, 1350~1550
+ "1993-11-16", # https://www.hankyung.com/news/article/1993111501631 0940~1140, 1320~1520 => 1010~1210, 1350~1550
+ "1994-11-23", # https://www.hankyung.com/finance/article/1994111800041 0940~1140, 1320~1520 => 1010~1210, 1350~1550
+ "1995-11-22", # https://www.hankyung.com/finance/article/1995112200021 0930~1130, 1300~1500 => 1000~1200, 1330~1530
+ "1996-11-13", # https://www.hankyung.com/finance/article/1996111200331 0930~1130, 1300~1500 => 1000~1200, 1330~1530
+ "1997-11-19", # https://www.hankyung.com/finance/article/1997111800541 0930~1130, 1300~1500 => 1000~1200, 1330~1530
+ "1998-11-18", # https://www.mk.co.kr/news/home/view/1998/11/75869/ 0930~1130, 1300~1500 => 1000~1200, 1330~1530 all schedules are delayed by 30 minutes until here
+ "1999-11-17", # https://www.hankyung.com/finance/article/1999111600091 0900~1200, 1300~1500 => 1000~1300, 1400~1600 all schedules are delayed by 1 hour from here
+ "2000-11-15", # https://www.hankyung.com/finance/article/2000111459041 0900~1500 => 1000~1600
+ "2001-11-07", # https://www.mk.co.kr/news/home/view/2001/11/298983/ 0900~1500 => 1000~1600
+ "2002-11-06", # https://www.hankyung.com/finance/article/2002110544321 0900~1500 => 1000~1600
+ "2003-11-05", # https://www.mk.co.kr/news/home/view/2002/11/330688/ 0900~1500 => 1000~1600
+ "2004-11-17", # https://www.hankyung.com/finance/article/2004111549731 0900~1500 => 1000~1600
+ "2005-11-23", # https://www.hankyung.com/finance/article/2005112005501 0900~1500 => 1000~1600
+ "2006-11-16", # https://www.donga.com/news/Economy/article/all/20061110/8371660/1 0900~1500 => 1000~1600
+ "2007-11-15", # https://www.hankyung.com/finance/article/2007111206081 0900~1500 => 1000~1600
+ "2008-11-13", # https://www.hankyung.com/society/article/2008110954461 0900~1500 => 1000~1600
+ "2009-11-12", # https://www.hankyung.com/society/article/2009110960321 0900~1500 => 1000~1600
+ "2010-11-18", # https://www.hankyung.com/finance/article/2010111790801 0900~1500 => 1000~1600
+ "2011-11-10", # https://www.hankyung.com/finance/article/2011110889221 0900~1500 => 1000~1600
+ "2012-11-08", # https://www.hankyung.com/finance/article/2012110157181 0900~1500 => 1000~1600
+ "2013-11-07", # https://www.hankyung.com/finance/article/2013110789257 0900~1500 => 1000~1600
+ "2014-11-13", # http://biz.newdaily.co.kr/site/data/html/2014/11/13/2014111310007.html 0900~1500 => 1000~1600
+ "2015-11-12", # https://www.hankyung.com/society/article/2015111160647 0900~1500 => 1000~1600
+ "2016-11-17", # https://biz.chosun.com/site/data/html_dir/2016/11/03/2016110301285.html 0900~1530 => 1000~1630
+ "2017-11-16", # https://biz.chosun.com/site/data/html_dir/2017/11/15/2017111503718.html 0900~1530 => 1000~1630
+ "2017-11-23", # https://www.hankyung.com/finance/article/2017112301477 0900~1530 => 1000~1630
+ "2018-11-15", # https://www.hankyung.com/finance/article/2018110526741 0900~1530 => 1000~1630
+ "2019-11-14", # https://www.hankyung.com/finance/article/2019110435331 0900~1530 => 1000~1630
+ "2020-12-03", # https://www.hankyung.com/finance/article/2020112799257 0900~1530 => 1000~1630
+ ]
+)
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xtks_holidays.py b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xtks_holidays.py
new file mode 100644
index 0000000000000000000000000000000000000000..d2d2fa73d90a4f5f937bf7ea90c13970d141aa26
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/exchange_calendars/xtks_holidays.py
@@ -0,0 +1,386 @@
+from datetime import timedelta
+
+from dateutil.relativedelta import MO
+from pandas import DateOffset, Timestamp
+from pandas.tseries.holiday import Holiday, sunday_to_monday
+
+from .common_holidays import new_years_day
+from .exchange_calendar import SUNDAY
+
+
+def sunday_to_tuesday(dt):
+ """
+ If holiday falls on Sunday, use Tuesday instead.
+ """
+ if dt.weekday() == SUNDAY:
+ return dt + timedelta(2)
+ return dt
+
+
+def sunday_to_wednesday(dt):
+ """
+ If holiday falls on Sunday, use Wednesday instead.
+ """
+ if dt.weekday() == SUNDAY:
+ return dt + timedelta(3)
+ return dt
+
+
+NewYearsHolidayJan1 = new_years_day()
+
+NewYearsHolidayJan2 = Holiday(
+ "New Year's Holiday (Jan 2)",
+ month=1,
+ day=2,
+)
+NewYearsHolidayJan3 = Holiday(
+ "New Year's Holiday (Jan 3)",
+ month=1,
+ day=3,
+)
+
+# https://en.wikipedia.org/wiki/Coming_of_Age_Day
+ComingOfAgeDayThrough1999 = Holiday(
+ "Coming of Age Day (through 1999)",
+ month=1,
+ day=15,
+ start_date="1948-01-01",
+ end_date="2000-01-01",
+ observance=sunday_to_monday,
+)
+ComingOfAgeDay2000Onwards = Holiday(
+ "Coming of Age Day (2000 onwards)",
+ month=1,
+ day=1,
+ offset=DateOffset(weekday=MO(2)),
+ start_date="2000-01-01",
+)
+
+NationalFoundationDay = Holiday(
+ "National Foundation Day",
+ month=2,
+ day=11,
+ observance=sunday_to_monday,
+)
+
+# The dates on which the vernal/autumnal equinox will be observed
+# are announced on the first weekday of February of the previous
+# year, so we treat them as ad-hoc holidays, even though they
+# occur every year. For more info, see:
+# https://en.wikipedia.org/wiki/Public_holidays_in_Japan#cite_note-3
+# See:
+# https://www.timeanddate.com/holidays/japan/
+# https://www.timeanddate.com/holidays/japan/spring-equinox
+VernalEquinoxes = [
+ Timestamp("1997-03-20"),
+ Timestamp("1998-03-21"),
+ Timestamp("1999-03-22"),
+ Timestamp("2000-03-20"),
+ Timestamp("2001-03-20"),
+ Timestamp("2002-03-21"),
+ Timestamp("2003-03-21"),
+ Timestamp("2004-03-20"),
+ Timestamp("2005-03-21"),
+ Timestamp("2006-03-21"),
+ Timestamp("2007-03-21"),
+ Timestamp("2008-03-20"),
+ Timestamp("2009-03-20"),
+ Timestamp("2010-03-22"),
+ Timestamp("2011-03-21"),
+ Timestamp("2012-03-20"),
+ Timestamp("2013-03-20"),
+ Timestamp("2014-03-21"),
+ Timestamp("2015-03-21"),
+ Timestamp("2016-03-21"),
+ Timestamp("2017-03-20"),
+ Timestamp("2018-03-21"),
+ Timestamp("2019-03-21"),
+ Timestamp("2020-03-20"),
+ Timestamp("2021-03-20"),
+ Timestamp("2022-03-21"),
+ Timestamp("2023-03-21"),
+ Timestamp("2024-03-20"),
+]
+
+# The Golden Week holidays (late April - early May) are listed in reverse
+# chronological order because earlier holidays must be aware of later holidays
+# so that that if an earlier holiday (Constitution Memorial Day, Greenery Day)
+# falls on a Sunday, that holiday can be observed on the next non-holiday
+# weekday.
+# Clash with GreeneryDay and ConstitutionMemorialDay
+ChildrensDay = Holiday(
+ "Children's Day",
+ month=5,
+ day=5,
+ observance=sunday_to_monday,
+)
+
+# From 1986-2006, the day between Constitution Memorial Day and Children's
+# Day was an unnamed citizen's holiday because it was between two holidays.
+# In 2007, Greenery Day was moved from April 29 to May 4, replacing the
+# unnamed citizen's holiday. For more info, see:
+# https://en.wikipedia.org/wiki/Golden_Week_(Japan)
+# Clash with ChildrensDay and ConstitutionMemorialDay
+GreeneryDay2007Onwards = Holiday(
+ "Greenery Day",
+ month=5,
+ day=4,
+ start_date="2007-01-01",
+ observance=sunday_to_tuesday,
+)
+
+CitizensHolidayGoldenWeek = Holiday(
+ "Citizen's Holiday Golden Week",
+ month=5,
+ day=4,
+ end_date="2007-01-01",
+ observance=sunday_to_monday,
+)
+
+# In 2007, April 29 was changed from Greenery Day to Showa Day,
+# and Greenery Day was moved to May 4.
+GreeneryDayThrough2006 = Holiday(
+ "Greenery Day",
+ month=4,
+ day=29,
+ end_date="2007-01-01",
+ observance=sunday_to_monday,
+)
+
+ShowaDay = Holiday(
+ "Showa Day",
+ month=4,
+ day=29,
+ start_date="2007-01-01",
+ observance=sunday_to_monday,
+)
+
+# Clash with ChildrensDay
+ConstitutionMemorialDay = Holiday(
+ "Constitution Memorial Day",
+ month=5,
+ day=3,
+ observance=sunday_to_wednesday,
+)
+
+MarineDayThrough2002 = Holiday(
+ "Marine Day (through 2002)",
+ month=7,
+ day=20,
+ end_date="2003-01-01",
+ observance=sunday_to_monday,
+)
+
+MarineDay2003OnwardsThrough2019 = Holiday(
+ "Marine Day (2003 - 2019)",
+ month=7,
+ day=1,
+ offset=DateOffset(weekday=MO(3)),
+ start_date="2003-01-01",
+ end_date="2020-01-01",
+)
+
+# Changed due to Tokyo Olympics
+MarineDay2020 = Holiday(
+ "Marine Day (2020)",
+ month=7,
+ day=23,
+ year=2020,
+)
+
+MarineDay2021 = Holiday(
+ "Marine Day (2021)",
+ month=7,
+ day=22,
+ year=2021,
+)
+
+MarineDay2022Onwards = Holiday(
+ "Marine Day (2022 onwards)",
+ month=7,
+ day=1,
+ offset=DateOffset(weekday=MO(3)),
+ start_date="2022-01-01",
+)
+
+MountainDayThrough2019 = Holiday(
+ "Mountain Day (through 2019)",
+ month=8,
+ day=11,
+ start_date="2016-01-01",
+ end_date="2020-01-01",
+ observance=sunday_to_monday,
+)
+
+# Changed due to Tokyo Olympics
+MountainDay2020 = Holiday(
+ "Mountain Day (2020)",
+ month=8,
+ day=10,
+ year=2020,
+)
+
+MountainDay2021 = Holiday(
+ "Mountain Day (2021)",
+ month=8,
+ day=9,
+ year=2021,
+)
+
+MountainDay2022Onwards = Holiday(
+ "Mountain Day (2022 onwards)",
+ month=8,
+ day=11,
+ start_date="2022-01-01",
+ observance=sunday_to_monday,
+)
+
+# See note on equinoxes above VernalEquinoxes
+AutumnalEquinoxes = [
+ Timestamp("1997-09-23"),
+ Timestamp("1998-09-23"),
+ Timestamp("1999-09-23"),
+ Timestamp("2000-09-23"),
+ Timestamp("2001-09-24"),
+ Timestamp("2002-09-23"),
+ Timestamp("2003-09-23"),
+ Timestamp("2004-09-23"),
+ Timestamp("2005-09-23"),
+ Timestamp("2006-09-23"),
+ Timestamp("2007-09-24"),
+ Timestamp("2008-09-23"),
+ Timestamp("2009-09-23"),
+ Timestamp("2010-09-23"),
+ Timestamp("2011-09-23"),
+ Timestamp("2012-09-22"),
+ Timestamp("2013-09-23"),
+ Timestamp("2014-09-23"),
+ Timestamp("2015-09-23"),
+ Timestamp("2016-09-22"),
+ Timestamp("2017-09-23"),
+ Timestamp("2018-09-24"),
+ Timestamp("2019-09-23"),
+ Timestamp("2020-09-22"),
+ Timestamp("2021-09-23"),
+ Timestamp("2022-09-23"),
+ Timestamp("2023-09-23"),
+ Timestamp("2024-09-23"),
+]
+
+# If the Autumnal Equinox falls on a Wednesday, the Tuesday before
+# it is a holiday because it will be sandwiched between Respect for
+# the Aged Day and the Autumnal Equinox. For more info, see:
+# https://en.wikipedia.org/wiki/Silver_Week
+CitizensHolidaySilverWeek = [
+ Timestamp("2009-09-22"),
+ Timestamp("2015-09-22"),
+]
+
+RespectForTheAgedDayThrough2002 = Holiday(
+ "Respect for the Aged Day (through 2002)",
+ month=9,
+ day=15,
+ end_date="2003-01-01",
+ observance=sunday_to_monday,
+)
+
+RespectForTheAgedDay2003Onwards = Holiday(
+ "Respect for the Aged Day (2003 onwards)",
+ month=9,
+ day=1,
+ offset=DateOffset(weekday=MO(3)),
+ start_date="2003-01-01",
+)
+
+# https://en.wikipedia.org/wiki/Health_and_Sports_Day
+HealthAndSportsDayThrough1999 = Holiday(
+ "Heakth and Sports Day (through 1999)",
+ month=10,
+ day=10,
+ start_date="1966-01-01",
+ end_date="2000-01-01",
+ observance=sunday_to_monday,
+)
+
+HealthAndSportsDay2000OnwardsThrough2019 = Holiday(
+ "Health and Sports Day (2000 - 2019)",
+ month=10,
+ day=1,
+ offset=DateOffset(weekday=MO(2)),
+ start_date="2000-01-01",
+ end_date="2020-01-01",
+)
+
+# Changed due to Tokyo Olympics
+HealthAndSportsDay2020 = Holiday(
+ "Health and Sports Day (2020)",
+ month=7,
+ day=24,
+ year=2020,
+)
+
+HealthAndSportsDay2021 = Holiday(
+ "Health and Sports Day (2021)",
+ month=7,
+ day=23,
+ year=2021,
+)
+
+HealthAndSportsDay2022Onwards = Holiday(
+ "Health and Sports Day (2022 onwards)",
+ month=10,
+ day=1,
+ offset=DateOffset(weekday=MO(2)),
+ start_date="2022-01-01",
+)
+
+CultureDay = Holiday(
+ "Culture Day",
+ month=11,
+ day=3,
+ observance=sunday_to_monday,
+)
+
+LaborThanksgivingDay = Holiday(
+ "Labor Thanksgiving Day",
+ month=11,
+ day=23,
+ observance=sunday_to_monday,
+)
+
+# Emperor Akihito is due to retire on 30 April 2019, meaning the holiday
+# will not be observed in 2019, and its next celebration will be on the
+# birthday of Crown Prince Naruhito (23 February 2020).
+EmperorAkihitoBirthday = Holiday(
+ "Emperor Akihito's Birthday",
+ month=12,
+ day=23,
+ end_date="2019-04-30",
+ observance=sunday_to_monday,
+)
+
+EmperorNaruhitoBirthday = Holiday(
+ "Emperor Naruhito's Birthday",
+ month=2,
+ day=23,
+ start_date="2019-04-30",
+ observance=sunday_to_monday,
+)
+
+NewYearsHolidayDec31 = Holiday(
+ "New Year's Holiday (Dec 31)",
+ month=12,
+ day=31,
+)
+
+Misc2019Holidays = [
+ Timestamp("2019-04-30"), # Abdication Day
+ Timestamp("2019-05-01"), # Accession Day
+ Timestamp("2019-05-02"), # Citizen's Holiday
+ Timestamp("2019-10-22"), # Enthronement Ceremony
+]
+
+EquityTradingSystemFailure = [
+ # https://www.jpx.co.jp/english/corporate/news/news-releases/0060/20201019-01.html
+ Timestamp("2020-10-01"),
+]
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/pyproject.toml b/tasks/tasksmith-ca08ab4caec6/environment/source/pyproject.toml
new file mode 100644
index 0000000000000000000000000000000000000000..d98121a68eaa0d1df4280e2b76303373e23458c9
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/pyproject.toml
@@ -0,0 +1,66 @@
+[build-system]
+requires = ["setuptools>=43.0.0", "wheel", "setuptools_scm[toml]>=6.2"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "exchange_calendars"
+description = "Calendars for securities exchanges"
+authors = [
+ {email = "gerrymanoim@gmail.com"},
+ {name = "Gerry Manoim"}
+]
+readme = "README.md"
+license = {file = "LICENSE"}
+keywords = ["finance", "security", "calendar", "exchange"]
+requires-python = "~=3.9"
+classifiers = [
+ "Development Status :: 4 - Beta",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 3",
+ "Programming Language :: Python :: 3.9",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "License :: OSI Approved :: Apache Software License",
+ "Intended Audience :: Science/Research",
+ "Topic :: Scientific/Engineering",
+ "Topic :: Scientific/Engineering :: Mathematics",
+ "Operating System :: OS Independent",
+]
+dependencies = [
+ "numpy<2",
+ "pandas>=1.5",
+ "pyluach",
+ "toolz",
+ "tzdata",
+ "korean_lunar_calendar",
+]
+dynamic = ["version"]
+
+[project.optional-dependencies]
+dev = [
+ "flake8",
+ "hypothesis",
+ "pytest",
+ "pytest-benchmark",
+ "pytest-xdist",
+ "pip-tools",
+]
+
+[project.scripts]
+ecal = "exchange_calendars.ecal:main"
+
+[project.urls]
+homepage = "https://github.com/gerrymanoim/exchange_calendars"
+documentation = "https://github.com/gerrymanoim/exchange_calendars/tree/master/docs"
+"Issue Tracker" = "https://github.com/gerrymanoim/exchange_calendars/issues"
+"Source Code" = "https://github.com/gerrymanoim/exchange_calendars"
+
+[tool.setuptools.packages.find]
+include = ["exchange_calendars", "exchange_calendars.*"]
+
+[tool.setuptools_scm]
+write_to = "exchange_calendars/_version.py"
+
+[tool.black]
+line-length = 88
+target-version = ['py39', 'py310', 'py311']
diff --git a/tasks/tasksmith-ca08ab4caec6/environment/source/setup.cfg b/tasks/tasksmith-ca08ab4caec6/environment/source/setup.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..eeae2a734425ab9ee1e0888909c53ce8992e4997
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/environment/source/setup.cfg
@@ -0,0 +1,31 @@
+[tool:pytest]
+addopts = -v --doctest-modules --durations=15
+
+testpaths =
+ tests
+ exchange_calendars/utils/pandas_utils.py
+
+[isort]
+multi_line_output = 3
+include_trailing_comma = True
+force_grid_wrap = 0
+use_parentheses = True
+ensure_newline_before_comments = True
+line_length = 88
+
+[flake8]
+max-line-length = 88
+ignore = E203, E501, W503
+exclude =
+ .git,
+ __pycache__,
+ versioneer.py,
+ exchange_calendars/_version.py
+
+[mypy]
+warn_unreachable = True
+warn_redundant_casts = True
+warn_unused_ignores = True
+strict_equality = True
+show_error_codes = True
+ignore_missing_imports = True
diff --git a/tasks/tasksmith-ca08ab4caec6/instruction.md b/tasks/tasksmith-ca08ab4caec6/instruction.md
new file mode 100644
index 0000000000000000000000000000000000000000..908de5ef8feb960ef6f7e75487075c43a99eb2d7
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/instruction.md
@@ -0,0 +1,19 @@
+Add working-weekend support to the XMOS (Moscow Exchange) calendar.
+
+The Moscow Exchange occasionally designates specific Saturdays or Sundays as trading days to compensate for extended holiday breaks. These "working weekends" have no fixed recurrence rule and must be listed explicitly.
+
+**Required changes:**
+
+1. **`XMOSExchangeCalendar.special_weekmasks` property** – Add a property that returns a list of `(start_date, end_date, weekmask_string)` tuples (where dates are `pd.Timestamp` and the weekmask is a 7-character string of `"0"`/`"1"` for Mon–Sun). Each tuple identifies a date range and the weekday pattern that applies within it. For example, `"1111110"` means Mon–Sat are business days; `"1111101"` means Mon–Fri + Sun. The list covers historical working-weekend events from 1999 through 2024, including entries such as:
+ - `(pd.Timestamp("1999-01-04"), pd.Timestamp("1999-01-10"), "1111101")` – Sunday 1999-01-10 is a session
+ - `(pd.Timestamp("2024-04-22"), pd.Timestamp("2024-04-28"), "1111110")` – Saturday 2024-04-27 is a session
+
+2. **`XMOSExchangeCalendar.day` cached property** – Override `day` to return a `MultipleWeekmaskCustomBusinessDay` (from `exchange_calendars.pandas_extensions.offsets`) when `special_weekmasks` is non-empty, passing `holidays`, `calendar`, `weekmask`, and `weekmasks=self.special_weekmasks`. This makes the working-weekend dates appear as valid sessions.
+
+3. **Bug fixes in `exchange_calendars/pandas_extensions/offsets.py`** – Two arithmetic/API bugs affect `MultipleWeekmaskCustomBusinessDay` (and also `CompositeCustomBusinessDay`) when multiple weekmask intervals are configured:
+ - In the gap-detection loop, the subtraction `right.left - left.right` produces a `Timedelta`, which cannot be directly compared to `pd.Timestamp(1, unit="D")`. Convert the timedelta's `.days` to a `pd.Timestamp` before comparing.
+ - In `_apply`, `bday.apply(other)` raises a deprecation error in recent pandas; use `bday._apply(other)` instead.
+
+After these changes the XMOS calendar's sessions on historically designated working Saturdays/Sundays (e.g. 1999-01-10, 2000-05-06, 2024-04-27, 2024-11-02, 2024-12-28) must appear as open sessions with normal open/close times. The XKRX calendar, which also uses `MultipleWeekmaskCustomBusinessDay`, must continue to work correctly.
+
+Work in `/workspace`. Submit your fix in Python source files under `exchange_calendars`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files.
diff --git a/tasks/tasksmith-ca08ab4caec6/solution/reference/exchange_calendars/exchange_calendar_xmos.py b/tasks/tasksmith-ca08ab4caec6/solution/reference/exchange_calendars/exchange_calendar_xmos.py
new file mode 100644
index 0000000000000000000000000000000000000000..00002ac32a20c9ecaac55a4b6916ea917ae038bc
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/solution/reference/exchange_calendars/exchange_calendar_xmos.py
@@ -0,0 +1,398 @@
+#
+# Copyright 2019 Quantopian, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import datetime
+from itertools import chain
+from zoneinfo import ZoneInfo
+import pandas as pd
+import functools
+
+from pandas.tseries.holiday import Holiday, weekend_to_monday
+from pandas.tseries.offsets import CustomBusinessDay
+
+from .common_holidays import european_labour_day, new_years_day, new_years_eve
+from .exchange_calendar import WEEKDAYS, HolidayCalendar, ExchangeCalendar
+from .pandas_extensions.offsets import MultipleWeekmaskCustomBusinessDay
+
+
+def new_years_eve_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # For some reason New Year's Eve was not a holiday these years.
+ return None if dt.year in [2008, 2009] else weekend_to_monday(dt)
+
+
+def new_years_day_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # New Year's Day did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2022] else weekend_to_monday(dt)
+
+
+def new_years_holiday_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # New Year's Holiday did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2016, 2021, 2022] else weekend_to_monday(dt)
+
+
+def orthodox_christmas_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # Orthodox Christmas did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2012, 2017, 2023, 2024] else weekend_to_monday(dt)
+
+
+def defender_of_fatherland_observance(
+ dt: datetime.datetime,
+) -> datetime.datetime | None:
+ # Defender of the Fatherland Day did not follow the next-non-holiday rule
+ # these years.
+ return None if dt.year in [2013, 2014, 2019] else weekend_to_monday(dt)
+
+
+def victory_day_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # Victory Day did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2021] else weekend_to_monday(dt)
+
+
+def day_of_russia_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # Day of Russia did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2021] else weekend_to_monday(dt)
+
+
+def unity_day_observance(dt: datetime.datetime) -> datetime.datetime | None:
+ # Unity Day did not follow the next-non-holiday rule these years.
+ return None if dt.year in [2023] else weekend_to_monday(dt)
+
+
+NewYearsDay = new_years_day(observance=new_years_day_observance)
+NewYearsHoliday = Holiday(
+ "New Year's Holiday",
+ month=1,
+ day=2,
+ observance=new_years_holiday_observance,
+)
+NewYearsHoliday2 = Holiday(
+ "New Year's Holiday",
+ month=1,
+ day=3,
+ start_date="2005",
+ end_date="2012",
+)
+NewYearsHoliday3 = Holiday(
+ "New Year's Holiday",
+ month=1,
+ day=4,
+ start_date="2005",
+ end_date="2012",
+)
+NewYearsHoliday4 = Holiday(
+ "New Year's Holiday",
+ month=1,
+ day=5,
+ start_date="2005",
+ end_date="2012",
+)
+NewYearsHoliday5 = Holiday(
+ "New Year's Holiday",
+ month=1,
+ day=6,
+ start_date="2005",
+ end_date="2012",
+)
+
+OrthodoxChristmas = Holiday(
+ "Orthodox Christmas",
+ month=1,
+ day=7,
+ observance=orthodox_christmas_observance,
+)
+
+DefenderOfTheFatherlandDay = Holiday(
+ "Defender of the Fatherland Day",
+ month=2,
+ day=23,
+ observance=defender_of_fatherland_observance,
+)
+
+WomensDay = Holiday(
+ "Women's Day",
+ month=3,
+ day=8,
+ observance=weekend_to_monday,
+)
+
+LabourDay = european_labour_day(observance=weekend_to_monday)
+
+VictoryDay = Holiday(
+ "Victory Day",
+ month=5,
+ day=9,
+ observance=victory_day_observance,
+)
+
+DayOfRussia = Holiday(
+ "Day of Russia",
+ month=6,
+ day=12,
+ observance=day_of_russia_observance,
+)
+
+UnityDay = Holiday(
+ "Unity Day",
+ month=11,
+ day=4,
+ observance=unity_day_observance,
+ start_date="2005",
+)
+
+NewYearsEve = new_years_eve(
+ observance=new_years_eve_observance,
+ days_of_week=WEEKDAYS,
+)
+
+
+# Adhoc Holidays
+# --------------
+
+# All of the following "extensions" are bridge holidays, meaning they are
+# either a Monday or Friday that is made into a holiday to fill in the gap
+# between a Tuesday or Thursday holiday, respectively. Unfortunately having
+# these bridge days is not consistently the rule, so they are treated as adhoc.
+# This means that in the future there may be manual additions needed here.
+new_years_extensions = [
+ "2003-01-03",
+ "2013-01-03",
+ "2013-01-04",
+ "2014-01-03",
+]
+
+orthodox_christmas_extensions = [
+ "2003-01-06",
+ "2005-01-10",
+ "2008-01-08",
+ "2009-01-08",
+ "2009-01-09",
+ "2010-01-08",
+ "2011-01-10",
+ "2016-01-08",
+]
+
+defender_of_the_fatherland_extensions = [
+ "2006-02-24",
+ "2010-02-22",
+]
+
+womens_day_extensions = [
+ "2005-03-07",
+ "2011-03-07",
+ "2012-03-09",
+ "2022-03-07",
+]
+
+labour_day_extensions = [
+ "2002-05-02",
+ "2002-05-03",
+ "2003-05-02",
+ "2004-05-04",
+ "2007-04-30",
+ "2008-05-02",
+ "2012-04-30",
+ "2015-05-04",
+ "2016-05-03",
+ # LabourDay Holiday extended to Tuesday.
+ "2022-05-03",
+]
+
+victory_day_extensions = [
+ "2002-05-10",
+ "2005-05-10",
+ "2006-05-08",
+ "2017-05-08",
+ # Victory Day Holiday extended to Tuesday.
+ "2022-05-10",
+]
+
+day_of_russia_extensions = [
+ "2003-06-13",
+ "2007-06-11",
+ "2008-06-13",
+ "2012-06-11",
+ "2014-06-13",
+]
+
+unity_day_extensions = [
+ "2008-11-03",
+ "2010-11-05",
+]
+
+misc_adhoc = [
+ # Exchange Holidays.
+ "2002-11-07",
+ "2002-11-08",
+ "2002-12-12",
+ "2002-12-13",
+ "2003-11-07",
+ "2003-12-12",
+ "2004-11-08",
+ "2004-12-13",
+ "2008-09-18",
+ # Trading Suspended.
+ "2008-10-10",
+ "2008-10-27",
+ # Non-Working Days.
+ "2020-06-24",
+ "2020-07-01",
+]
+
+
+class XMOSExchangeCalendar(ExchangeCalendar):
+ """
+ Exchange calendar for the Moscow Stock Exchange.
+
+ Open Time: 10:00 AM, MSK (Moscow Standard Time)
+ Close Time: 6:45 PM, MSK (Moscow Standard Time)
+
+ Regularly-Observed Holidays:
+ - New Year's Day
+ - New Year's Holiday
+ - Orthodox Christmas Day
+ - Defender of the Fatherland Day
+ - Women's Day
+ - Spring and Labour Day
+ - Victory Day
+ - Day of Russia
+ - Unity Day
+ - New Year's Eve
+
+ Holidays No Longer Observed:
+ - New Year's Holiday Week
+
+ Early Closes:
+ - None
+ """
+
+ name = "XMOS"
+
+ tz = ZoneInfo("Europe/Moscow")
+
+ open_times = ((None, datetime.time(10)),)
+
+ close_times = ((None, datetime.time(18, 45)),)
+
+ @property
+ def special_weekmasks(self):
+ """
+ Returns
+ -------
+ list: List of (date, date, str) tuples that represent special
+ weekmasks that applies between dates.
+ """
+ return [
+ # For 1999-2011 years next url was used to obtain data for
+ # IMOEX close values in order to check if there are any Sat or Sun:
+ # https://iss.moex.com/iss/history/engines/stock/markets/index/securities/IMOEX
+ (pd.Timestamp("1999-01-04"), pd.Timestamp("1999-01-10"), "1111101"),
+ (pd.Timestamp("2000-05-01"), pd.Timestamp("2000-05-07"), "1111110"),
+ (pd.Timestamp("2000-10-30"), pd.Timestamp("2000-11-05"), "1111110"),
+ (pd.Timestamp("2000-12-04"), pd.Timestamp("2000-12-10"), "1111110"),
+ (pd.Timestamp("2001-03-05"), pd.Timestamp("2001-03-11"), "1111101"),
+ (pd.Timestamp("2001-04-23"), pd.Timestamp("2001-04-29"), "1111110"),
+ (pd.Timestamp("2001-06-04"), pd.Timestamp("2001-06-10"), "1111110"),
+ (pd.Timestamp("2001-12-24"), pd.Timestamp("2001-12-30"), "1111110"),
+ (pd.Timestamp("2002-04-22"), pd.Timestamp("2002-04-28"), "1111110"),
+ (pd.Timestamp("2002-05-13"), pd.Timestamp("2002-05-19"), "1111110"),
+ (pd.Timestamp("2002-11-04"), pd.Timestamp("2002-11-10"), "1111101"),
+ (pd.Timestamp("2002-12-09"), pd.Timestamp("2002-12-15"), "1111101"),
+ (pd.Timestamp("2002-12-30"), pd.Timestamp("2003-01-05"), "1111111"),
+ (pd.Timestamp("2003-06-16"), pd.Timestamp("2003-06-22"), "1111110"),
+ (pd.Timestamp("2005-02-28"), pd.Timestamp("2005-03-06"), "1111110"),
+ (pd.Timestamp("2005-05-09"), pd.Timestamp("2005-05-15"), "1111110"),
+ (pd.Timestamp("2006-02-20"), pd.Timestamp("2006-02-26"), "1111101"),
+ (pd.Timestamp("2006-05-01"), pd.Timestamp("2006-05-07"), "1111110"),
+ (pd.Timestamp("2007-04-23"), pd.Timestamp("2007-04-29"), "1111110"),
+ (pd.Timestamp("2007-06-04"), pd.Timestamp("2007-06-10"), "1111110"),
+ (pd.Timestamp("2008-04-28"), pd.Timestamp("2008-05-04"), "1111101"),
+ (pd.Timestamp("2008-06-02"), pd.Timestamp("2008-06-08"), "1111110"),
+ (pd.Timestamp("2008-10-27"), pd.Timestamp("2008-11-02"), "1111110"),
+ (pd.Timestamp("2009-01-05"), pd.Timestamp("2009-01-11"), "1111101"),
+ (pd.Timestamp("2010-02-22"), pd.Timestamp("2010-02-28"), "1111110"),
+ (pd.Timestamp("2010-11-08"), pd.Timestamp("2010-11-14"), "1111110"),
+ (pd.Timestamp("2011-02-28"), pd.Timestamp("2011-03-06"), "1111110"),
+ # For 2012 year https://www.moex.com/a254
+ (pd.Timestamp("2012-03-05"), pd.Timestamp("2012-03-11"), "1111101"),
+ (pd.Timestamp("2012-04-23"), pd.Timestamp("2012-05-13"), "1111110"),
+ (pd.Timestamp("2012-06-04"), pd.Timestamp("2012-06-10"), "1111110"),
+ # For 2016 year https://www.moex.com/a3367
+ (pd.Timestamp("2016-02-15"), pd.Timestamp("2016-02-21"), "1111110"),
+ # For 2018 year https://www.moex.com/a4187
+ (pd.Timestamp("2018-04-23"), pd.Timestamp("2018-04-29"), "1111110"),
+ (pd.Timestamp("2018-06-04"), pd.Timestamp("2018-06-10"), "1111110"),
+ (pd.Timestamp("2018-12-24"), pd.Timestamp("2018-12-30"), "1111110"),
+ # For 2021 year https://www.moex.com/n30445
+ (pd.Timestamp("2021-02-15"), pd.Timestamp("2021-02-21"), "1111110"),
+ # For 2024 year https://www.moex.com/n64121
+ (pd.Timestamp("2024-04-22"), pd.Timestamp("2024-04-28"), "1111110"),
+ (pd.Timestamp("2024-10-28"), pd.Timestamp("2024-11-03"), "1111110"),
+ (pd.Timestamp("2024-12-23"), pd.Timestamp("2024-12-29"), "1111110"),
+ ]
+
+ @property
+ def regular_holidays(self):
+ return HolidayCalendar(
+ [
+ NewYearsDay,
+ NewYearsHoliday,
+ NewYearsHoliday2,
+ NewYearsHoliday3,
+ NewYearsHoliday4,
+ NewYearsHoliday5,
+ OrthodoxChristmas,
+ DefenderOfTheFatherlandDay,
+ WomensDay,
+ LabourDay,
+ VictoryDay,
+ DayOfRussia,
+ UnityDay,
+ NewYearsEve,
+ ]
+ )
+
+ @property
+ def adhoc_holidays(self):
+ return list(
+ chain(
+ new_years_extensions,
+ orthodox_christmas_extensions,
+ defender_of_the_fatherland_extensions,
+ womens_day_extensions,
+ labour_day_extensions,
+ victory_day_extensions,
+ day_of_russia_extensions,
+ unity_day_extensions,
+ misc_adhoc,
+ ),
+ )
+
+ @functools.cached_property
+ def day(self):
+ if self.special_weekmasks:
+ return MultipleWeekmaskCustomBusinessDay(
+ holidays=self.adhoc_holidays,
+ calendar=self.regular_holidays,
+ weekmask=self.weekmask,
+ weekmasks=self.special_weekmasks,
+ )
+ else:
+ return CustomBusinessDay(
+ holidays=self.adhoc_holidays,
+ calendar=self.regular_holidays,
+ weekmask=self.weekmask,
+ )
diff --git a/tasks/tasksmith-ca08ab4caec6/solution/reference/exchange_calendars/pandas_extensions/offsets.py b/tasks/tasksmith-ca08ab4caec6/solution/reference/exchange_calendars/pandas_extensions/offsets.py
new file mode 100644
index 0000000000000000000000000000000000000000..cac2e4a31d7bbbdbd45c3bdd3ecbac697837867f
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/solution/reference/exchange_calendars/pandas_extensions/offsets.py
@@ -0,0 +1,307 @@
+# https://github.com/pandas-dev/pandas/blob/master/pandas/tseries/offsets.py
+# https://github.com/pandas-dev/pandas/blob/master/pandas/_libs/tslibs/offsets.pyx
+
+from datetime import datetime, timedelta
+
+import toolz
+import numpy as np
+import pandas as pd
+
+from pandas.tseries.offsets import CustomBusinessDay
+from pandas._libs.tslibs.offsets import apply_wraps
+
+
+class CompositeCustomBusinessDay(CustomBusinessDay):
+
+ _prefix = "C"
+ _attributes = tuple(
+ [
+ "n",
+ "normalize",
+ "weekmask",
+ "holidays",
+ "calendar",
+ "offset",
+ "business_days",
+ ]
+ )
+
+ def __init__(
+ self,
+ n=1,
+ normalize=False,
+ weekmask="Mon Tue Wed Thu Fri",
+ holidays=None,
+ calendar=None,
+ offset=timedelta(0),
+ business_days=None,
+ ):
+ CustomBusinessDay.__init__(
+ self, n, normalize, weekmask, holidays, calendar, offset
+ )
+ self.business_days = business_days
+
+ def __setstate__(self, state):
+ self.business_days = state.pop("business_days")
+ CustomBusinessDay.__setstate__(self, state)
+
+ @property
+ def business_days(self):
+ """
+ Returns list of tuples of (start_date, end_date, custom_business_day)
+ which overrides default behavior for the given interval, which starts
+ from start_date to end_date, inclusive in both sides.
+ """
+ return tuple(self._business_days)
+
+ @business_days.setter
+ def business_days(self, business_days):
+ self._business_days = []
+ self._business_days_index = pd.IntervalIndex([], closed="both")
+ self._business_days_all_index = pd.IntervalIndex([], closed="both")
+ if business_days is not None:
+ self._business_days = business_days
+ business_days_intervals = []
+ for start_date, end_date, _ in self._business_days:
+ if start_date is None:
+ start_date = pd.Timestamp.min
+ else:
+ start_date = pd.Timestamp(start_date)
+ if end_date is None:
+ end_date = pd.Timestamp.max
+ else:
+ end_date = pd.Timestamp(end_date)
+ interval = pd.Interval(start_date, end_date, closed="both")
+ business_days_intervals.append(interval)
+ self._business_days_index = pd.IntervalIndex(
+ business_days_intervals, closed="both"
+ )
+ business_days_all_intervals = []
+ right = self._business_days_index[0]
+ if pd.Timestamp.min < right.left:
+ interval = pd.Interval(
+ pd.Timestamp.min, right.left - pd.Timedelta(1, unit="D")
+ )
+ business_days_all_intervals.append(interval)
+ business_days_all_intervals.append(right)
+ for left, right in toolz.sliding_window(
+ 2, toolz.concatv(self._business_days_index)
+ ):
+ if pd.Timestamp((right.left - left.right).days,
+ unit="D") > pd.Timestamp(1, unit="D"):
+ interval = pd.Interval(
+ left.right + pd.Timedelta(1, unit="D"),
+ right.left - pd.Timedelta(1, unit="D"),
+ )
+ business_days_all_intervals.append(interval)
+ business_days_all_intervals.append(right)
+ left = self._business_days_index[-1]
+ if left.right < pd.Timestamp.max:
+ interval = pd.Interval(
+ left.right + pd.Timedelta(1, unit="D"), pd.Timestamp.max
+ )
+ business_days_all_intervals.append(interval)
+ self._business_days_all_index = pd.IntervalIndex(
+ business_days_all_intervals, closed="both"
+ )
+
+ def _as_custom_business_day(self):
+ return CustomBusinessDay(
+ self.n,
+ self.normalize,
+ self.weekmask,
+ self.holidays,
+ self.calendar,
+ self.offset,
+ )
+
+ def _custom_business_day_for(
+ self, other, n=None, is_edge=False, with_interval=False
+ ):
+ loc = self._business_days_all_index.get_loc(other)
+ if is_edge and n is not None:
+ loc += np.sign(n)
+ interval = self._business_days_all_index[loc]
+ try:
+ loc = self._business_days_index.get_loc(interval.left)
+ except KeyError:
+ bday = self._as_custom_business_day()
+ else:
+ bday = self._business_days[loc][-1]
+ if n is not None:
+ bday = bday.base * n
+ if with_interval:
+ return bday, interval
+ else:
+ return bday
+
+ def _moved(self, from_date, to_date, bday):
+ return np.busday_count(
+ np.datetime64(from_date.date()),
+ np.datetime64(to_date.date()),
+ busdaycal=bday.calendar,
+ )
+
+ @apply_wraps
+ def _apply(self, other):
+ if isinstance(other, datetime):
+ moved = 0
+ remaining = self.n - moved
+ bday, interval = self._custom_business_day_for(
+ other, remaining, with_interval=True
+ )
+ result = bday + other
+ while not interval.left <= result <= interval.right:
+ previous_other = other
+ if result < interval.left:
+ other = interval.left
+ elif result > interval.right:
+ other = interval.right
+ else:
+ raise RuntimeError("Should not reach here")
+ moved += self._moved(previous_other, other, bday)
+ remaining = self.n - moved
+ if remaining == 0:
+ break
+ bday, interval = self._custom_business_day_for(
+ other, remaining, is_edge=True, with_interval=True
+ )
+ result = bday._apply(other)
+ return result
+ else:
+ return super().apply(other)
+
+ # backwards compat
+ apply = _apply
+
+ def is_on_offset(self, dt):
+ if self.normalize and not _is_normalized(dt):
+ return False
+ day64 = _to_dt64D(dt)
+ bday = self._custom_business_day_for(day64)
+ return np.is_busday(day64, busdaycal=bday.calendar)
+
+
+def _is_normalized(dt):
+ if dt.hour != 0 or dt.minute != 0 or dt.second != 0 or dt.microsecond != 0:
+ # Regardless of whether dt is datetime vs Timestamp
+ return False
+ if isinstance(dt, pd.Timestamp):
+ return dt.nanosecond == 0
+ return True
+
+
+def _to_dt64D(dt):
+ # Currently
+ # > np.datetime64(dt.datetime(2013,5,1),dtype='datetime64[D]')
+ # numpy.datetime64('2013-05-01T02:00:00.000000+0200')
+ # Thus astype is needed to cast datetime to datetime64[D]
+ if getattr(dt, "tzinfo", None) is not None:
+ # Get the nanosecond timestamp,
+ # equiv `Timestamp(dt).value` or `dt.timestamp() * 10**9`
+ dt = pd.Timestamp(dt).value
+ dt = np.int64(dt).astype("datetime64[ns]")
+ else:
+ dt = np.datetime64(dt)
+ if dt.dtype.name != "datetime64[D]":
+ dt = dt.astype("datetime64[D]")
+ return dt
+
+
+def _get_calendar(weekmask, holidays, calendar):
+ """
+ Generate busdaycalendar
+ """
+ if isinstance(calendar, np.busdaycalendar):
+ if not holidays:
+ holidays = tuple(calendar.holidays)
+ elif not isinstance(holidays, tuple):
+ holidays = tuple(holidays)
+ else:
+ # Trust that calendar.holidays and holidays are
+ # consistent
+ pass
+ # Update weekmask if applicable (added)
+ calendar = np.busdaycalendar(weekmask, holidays)
+ return calendar, holidays
+
+ if holidays is None:
+ holidays = []
+ # Handle non list holidays also (added)
+ if isinstance(holidays, pd.DatetimeIndex):
+ holidays = holidays.tolist()
+ try:
+ holidays = holidays + calendar.holidays().tolist()
+ except AttributeError:
+ pass
+ holidays = [_to_dt64D(dt) for dt in holidays]
+ holidays = tuple(sorted(holidays))
+
+ kwargs = {"weekmask": weekmask}
+ if holidays:
+ kwargs["holidays"] = holidays
+
+ busdaycalendar = np.busdaycalendar(**kwargs)
+ return busdaycalendar, holidays
+
+
+class MultipleWeekmaskCustomBusinessDay(CompositeCustomBusinessDay):
+
+ _prefix = "C"
+ _attributes = tuple(
+ [
+ "n",
+ "normalize",
+ "weekmask",
+ "holidays",
+ "calendar",
+ "offset",
+ "business_days",
+ "weekmasks",
+ ]
+ )
+
+ def __init__(
+ self,
+ n=1,
+ normalize=False,
+ weekmask="Mon Tue Wed Thu Fri",
+ holidays=None,
+ calendar=None,
+ offset=timedelta(0),
+ business_days=None,
+ weekmasks=None,
+ ):
+ self._weekmasks = weekmasks
+ if business_days is None and weekmasks is not None:
+ calendars = [
+ _get_calendar(weekmask=weekmask, holidays=holidays, calendar=calendar)
+ for _start_date, _end_date, weekmask in weekmasks
+ ]
+ business_days = [
+ (
+ start_date,
+ end_date,
+ CustomBusinessDay(
+ n, normalize, weekmask, holidays, calendar, offset
+ ),
+ )
+ for (start_date, end_date, weekmask), (calendar, holidays) in zip(
+ weekmasks, calendars
+ )
+ ]
+ CompositeCustomBusinessDay.__init__(
+ self, n, normalize, weekmask, holidays, calendar, offset, business_days
+ )
+
+ def __setstate__(self, state):
+ self.weekmasks = state.pop("weekmasks")
+ CompositeCustomBusinessDay.__setstate__(self, state)
+
+ @property
+ def weekmasks(self):
+ return tuple(self._weekmasks)
+
+ @weekmasks.setter
+ def weekmasks(self, weekmasks):
+ self._weekmasks = weekmasks
diff --git a/tasks/tasksmith-ca08ab4caec6/solution/solve.sh b/tasks/tasksmith-ca08ab4caec6/solution/solve.sh
new file mode 100644
index 0000000000000000000000000000000000000000..7dc1fdec268bc6bbb4dcb0599a980bdd3eb08c0f
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/solution/solve.sh
@@ -0,0 +1,6 @@
+#!/bin/sh
+set -eu
+mkdir -p -- /workspace/exchange_calendars
+cp /solution/reference/exchange_calendars/exchange_calendar_xmos.py /workspace/exchange_calendars/exchange_calendar_xmos.py
+mkdir -p -- /workspace/exchange_calendars/pandas_extensions
+cp /solution/reference/exchange_calendars/pandas_extensions/offsets.py /workspace/exchange_calendars/pandas_extensions/offsets.py
diff --git a/tasks/tasksmith-ca08ab4caec6/task.toml b/tasks/tasksmith-ca08ab4caec6/task.toml
new file mode 100644
index 0000000000000000000000000000000000000000..9da49a2e42ee7b02ab4903aea9ce73f84146d264
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/task.toml
@@ -0,0 +1,498 @@
+schema_version = "1.3"
+
+[task]
+name = "repo2rlenv/tasksmith-ca08ab4caec6"
+
+[metadata.repo2env]
+recipe = "tasksmith"
+recipe_version = "1"
+source_url = "https://github.com/gerrymanoim/exchange_calendars/pull/376"
+source_head = "87552747277ecf7405df8ed44da703f3009c4bca"
+source_base = "9f0f724099a623ba424c6c3813f6f13c10e18c86"
+workspace_strategy = "head_minus_source_patch"
+source_diff_sha256 = "55cfab37c30d1602ba8fb73614dff622ebb7dfe1be2dc83169db31756367b8d0"
+acceptance_profile = "practical-generation-v1"
+upstream_test_policy = "retain"
+reward_kinds = [
+ "test_execution",
+]
+quality_status = "exported"
+fail_to_pass_count = 94
+pass_to_pass_count = 191
+tracked_files = [
+ "environment/Dockerfile",
+ "environment/source/.devcontainer/Dockerfile",
+ "environment/source/.devcontainer/base.Dockerfile",
+ "environment/source/.devcontainer/devcontainer.json",
+ "environment/source/.devcontainer/library-scripts/README.md",
+ "environment/source/.devcontainer/library-scripts/common-debian.sh",
+ "environment/source/.devcontainer/library-scripts/node-debian.sh",
+ "environment/source/.devcontainer/library-scripts/python-debian.sh",
+ "environment/source/.gitattributes",
+ "environment/source/.github/dependabot.yml",
+ "environment/source/.github/pull_request_template.md",
+ "environment/source/.github/release-drafter-config.yml",
+ "environment/source/.github/workflows/benchmark.yml",
+ "environment/source/.github/workflows/labeler.yml",
+ "environment/source/.github/workflows/main.yml",
+ "environment/source/.github/workflows/master-merge.yml",
+ "environment/source/.github/workflows/release.yml",
+ "environment/source/.gitignore",
+ "environment/source/.pre-commit-config.yaml",
+ "environment/source/Dockerfile",
+ "environment/source/LICENSE",
+ "environment/source/MANIFEST.in",
+ "environment/source/README.md",
+ "environment/source/docs/changes_archive.md",
+ "environment/source/docs/tutorials/calendar_methods.ipynb",
+ "environment/source/docs/tutorials/calendar_properties.ipynb",
+ "environment/source/docs/tutorials/minutes.ipynb",
+ "environment/source/docs/tutorials/sessions.ipynb",
+ "environment/source/docs/tutorials/trading_index.ipynb",
+ "environment/source/etc/NYSE-Historical-Closings.pdf",
+ "environment/source/etc/bench.py",
+ "environment/source/etc/check_holidays.py",
+ "environment/source/etc/ecal",
+ "environment/source/etc/factory_bounds.py",
+ "environment/source/etc/lunisolar",
+ "environment/source/etc/make_exchange_calendar_test_csv.py",
+ "environment/source/etc/requirements.txt",
+ "environment/source/etc/requirements_dev.txt",
+ "environment/source/etc/requirements_lunisolar.txt",
+ "environment/source/etc/requirements_minpandas.txt",
+ "environment/source/etc/requirements_update_xkrx_holidays.txt",
+ "environment/source/etc/update_xkrx_holidays.py",
+ "environment/source/exchange_calendars/__init__.py",
+ "environment/source/exchange_calendars/_version.py",
+ "environment/source/exchange_calendars/always_open.py",
+ "environment/source/exchange_calendars/calendar_helpers.py",
+ "environment/source/exchange_calendars/calendar_utils.py",
+ "environment/source/exchange_calendars/common_holidays.py",
+ "environment/source/exchange_calendars/ecal.py",
+ "environment/source/exchange_calendars/errors.py",
+ "environment/source/exchange_calendars/exchange_calendar.py",
+ "environment/source/exchange_calendars/exchange_calendar_aixk.py",
+ "environment/source/exchange_calendars/exchange_calendar_asex.py",
+ "environment/source/exchange_calendars/exchange_calendar_bvmf.py",
+ "environment/source/exchange_calendars/exchange_calendar_cmes.py",
+ "environment/source/exchange_calendars/exchange_calendar_iepa.py",
+ "environment/source/exchange_calendars/exchange_calendar_xams.py",
+ "environment/source/exchange_calendars/exchange_calendar_xasx.py",
+ "environment/source/exchange_calendars/exchange_calendar_xbkk.py",
+ "environment/source/exchange_calendars/exchange_calendar_xbog.py",
+ "environment/source/exchange_calendars/exchange_calendar_xbom.py",
+ "environment/source/exchange_calendars/exchange_calendar_xbru.py",
+ "environment/source/exchange_calendars/exchange_calendar_xbse.py",
+ "environment/source/exchange_calendars/exchange_calendar_xbud.py",
+ "environment/source/exchange_calendars/exchange_calendar_xbue.py",
+ "environment/source/exchange_calendars/exchange_calendar_xcbf.py",
+ "environment/source/exchange_calendars/exchange_calendar_xcse.py",
+ "environment/source/exchange_calendars/exchange_calendar_xdub.py",
+ "environment/source/exchange_calendars/exchange_calendar_xetr.py",
+ "environment/source/exchange_calendars/exchange_calendar_xfra.py",
+ "environment/source/exchange_calendars/exchange_calendar_xhel.py",
+ "environment/source/exchange_calendars/exchange_calendar_xhkg.py",
+ "environment/source/exchange_calendars/exchange_calendar_xice.py",
+ "environment/source/exchange_calendars/exchange_calendar_xidx.py",
+ "environment/source/exchange_calendars/exchange_calendar_xist.py",
+ "environment/source/exchange_calendars/exchange_calendar_xjse.py",
+ "environment/source/exchange_calendars/exchange_calendar_xkar.py",
+ "environment/source/exchange_calendars/exchange_calendar_xkls.py",
+ "environment/source/exchange_calendars/exchange_calendar_xkrx.py",
+ "environment/source/exchange_calendars/exchange_calendar_xlim.py",
+ "environment/source/exchange_calendars/exchange_calendar_xlis.py",
+ "environment/source/exchange_calendars/exchange_calendar_xlon.py",
+ "environment/source/exchange_calendars/exchange_calendar_xmad.py",
+ "environment/source/exchange_calendars/exchange_calendar_xmex.py",
+ "environment/source/exchange_calendars/exchange_calendar_xmil.py",
+ "environment/source/exchange_calendars/exchange_calendar_xmos.py",
+ "environment/source/exchange_calendars/exchange_calendar_xnys.py",
+ "environment/source/exchange_calendars/exchange_calendar_xnze.py",
+ "environment/source/exchange_calendars/exchange_calendar_xosl.py",
+ "environment/source/exchange_calendars/exchange_calendar_xpar.py",
+ "environment/source/exchange_calendars/exchange_calendar_xphs.py",
+ "environment/source/exchange_calendars/exchange_calendar_xpra.py",
+ "environment/source/exchange_calendars/exchange_calendar_xsau.py",
+ "environment/source/exchange_calendars/exchange_calendar_xses.py",
+ "environment/source/exchange_calendars/exchange_calendar_xsgo.py",
+ "environment/source/exchange_calendars/exchange_calendar_xshg.py",
+ "environment/source/exchange_calendars/exchange_calendar_xsto.py",
+ "environment/source/exchange_calendars/exchange_calendar_xswx.py",
+ "environment/source/exchange_calendars/exchange_calendar_xtae.py",
+ "environment/source/exchange_calendars/exchange_calendar_xtai.py",
+ "environment/source/exchange_calendars/exchange_calendar_xtks.py",
+ "environment/source/exchange_calendars/exchange_calendar_xtse.py",
+ "environment/source/exchange_calendars/exchange_calendar_xwar.py",
+ "environment/source/exchange_calendars/exchange_calendar_xwbo.py",
+ "environment/source/exchange_calendars/lunisolar_holidays.py",
+ "environment/source/exchange_calendars/pandas_extensions/__init__.py",
+ "environment/source/exchange_calendars/pandas_extensions/holiday.py",
+ "environment/source/exchange_calendars/pandas_extensions/korean_holiday.py",
+ "environment/source/exchange_calendars/pandas_extensions/offsets.py",
+ "environment/source/exchange_calendars/precomputed_exchange_calendar.py",
+ "environment/source/exchange_calendars/tase_holidays.py",
+ "environment/source/exchange_calendars/us_futures_calendar.py",
+ "environment/source/exchange_calendars/us_holidays.py",
+ "environment/source/exchange_calendars/utils/__init__.py",
+ "environment/source/exchange_calendars/utils/pandas_utils.py",
+ "environment/source/exchange_calendars/weekday_calendar.py",
+ "environment/source/exchange_calendars/xbkk_holidays.py",
+ "environment/source/exchange_calendars/xkls_holidays.py",
+ "environment/source/exchange_calendars/xkrx_holidays.py",
+ "environment/source/exchange_calendars/xtks_holidays.py",
+ "environment/source/pyproject.toml",
+ "environment/source/setup.cfg",
+ "solution/reference/exchange_calendars/exchange_calendar_xmos.py",
+ "solution/reference/exchange_calendars/pandas_extensions/offsets.py",
+ "solution/solve.sh",
+ "tests/Dockerfile",
+ "tests/contract.json",
+ "tests/grade.py",
+ "tests/source/.devcontainer/Dockerfile",
+ "tests/source/.devcontainer/base.Dockerfile",
+ "tests/source/.devcontainer/devcontainer.json",
+ "tests/source/.devcontainer/library-scripts/README.md",
+ "tests/source/.devcontainer/library-scripts/common-debian.sh",
+ "tests/source/.devcontainer/library-scripts/node-debian.sh",
+ "tests/source/.devcontainer/library-scripts/python-debian.sh",
+ "tests/source/.gitattributes",
+ "tests/source/.github/dependabot.yml",
+ "tests/source/.github/pull_request_template.md",
+ "tests/source/.github/release-drafter-config.yml",
+ "tests/source/.github/workflows/benchmark.yml",
+ "tests/source/.github/workflows/labeler.yml",
+ "tests/source/.github/workflows/main.yml",
+ "tests/source/.github/workflows/master-merge.yml",
+ "tests/source/.github/workflows/release.yml",
+ "tests/source/.gitignore",
+ "tests/source/.pre-commit-config.yaml",
+ "tests/source/Dockerfile",
+ "tests/source/LICENSE",
+ "tests/source/MANIFEST.in",
+ "tests/source/README.md",
+ "tests/source/docs/changes_archive.md",
+ "tests/source/docs/tutorials/calendar_methods.ipynb",
+ "tests/source/docs/tutorials/calendar_properties.ipynb",
+ "tests/source/docs/tutorials/minutes.ipynb",
+ "tests/source/docs/tutorials/sessions.ipynb",
+ "tests/source/docs/tutorials/trading_index.ipynb",
+ "tests/source/etc/NYSE-Historical-Closings.pdf",
+ "tests/source/etc/bench.py",
+ "tests/source/etc/check_holidays.py",
+ "tests/source/etc/ecal",
+ "tests/source/etc/factory_bounds.py",
+ "tests/source/etc/lunisolar",
+ "tests/source/etc/make_exchange_calendar_test_csv.py",
+ "tests/source/etc/requirements.txt",
+ "tests/source/etc/requirements_dev.txt",
+ "tests/source/etc/requirements_lunisolar.txt",
+ "tests/source/etc/requirements_minpandas.txt",
+ "tests/source/etc/requirements_update_xkrx_holidays.txt",
+ "tests/source/etc/update_xkrx_holidays.py",
+ "tests/source/exchange_calendars/__init__.py",
+ "tests/source/exchange_calendars/_version.py",
+ "tests/source/exchange_calendars/always_open.py",
+ "tests/source/exchange_calendars/calendar_helpers.py",
+ "tests/source/exchange_calendars/calendar_utils.py",
+ "tests/source/exchange_calendars/common_holidays.py",
+ "tests/source/exchange_calendars/ecal.py",
+ "tests/source/exchange_calendars/errors.py",
+ "tests/source/exchange_calendars/exchange_calendar.py",
+ "tests/source/exchange_calendars/exchange_calendar_aixk.py",
+ "tests/source/exchange_calendars/exchange_calendar_asex.py",
+ "tests/source/exchange_calendars/exchange_calendar_bvmf.py",
+ "tests/source/exchange_calendars/exchange_calendar_cmes.py",
+ "tests/source/exchange_calendars/exchange_calendar_iepa.py",
+ "tests/source/exchange_calendars/exchange_calendar_xams.py",
+ "tests/source/exchange_calendars/exchange_calendar_xasx.py",
+ "tests/source/exchange_calendars/exchange_calendar_xbkk.py",
+ "tests/source/exchange_calendars/exchange_calendar_xbog.py",
+ "tests/source/exchange_calendars/exchange_calendar_xbom.py",
+ "tests/source/exchange_calendars/exchange_calendar_xbru.py",
+ "tests/source/exchange_calendars/exchange_calendar_xbse.py",
+ "tests/source/exchange_calendars/exchange_calendar_xbud.py",
+ "tests/source/exchange_calendars/exchange_calendar_xbue.py",
+ "tests/source/exchange_calendars/exchange_calendar_xcbf.py",
+ "tests/source/exchange_calendars/exchange_calendar_xcse.py",
+ "tests/source/exchange_calendars/exchange_calendar_xdub.py",
+ "tests/source/exchange_calendars/exchange_calendar_xetr.py",
+ "tests/source/exchange_calendars/exchange_calendar_xfra.py",
+ "tests/source/exchange_calendars/exchange_calendar_xhel.py",
+ "tests/source/exchange_calendars/exchange_calendar_xhkg.py",
+ "tests/source/exchange_calendars/exchange_calendar_xice.py",
+ "tests/source/exchange_calendars/exchange_calendar_xidx.py",
+ "tests/source/exchange_calendars/exchange_calendar_xist.py",
+ "tests/source/exchange_calendars/exchange_calendar_xjse.py",
+ "tests/source/exchange_calendars/exchange_calendar_xkar.py",
+ "tests/source/exchange_calendars/exchange_calendar_xkls.py",
+ "tests/source/exchange_calendars/exchange_calendar_xkrx.py",
+ "tests/source/exchange_calendars/exchange_calendar_xlim.py",
+ "tests/source/exchange_calendars/exchange_calendar_xlis.py",
+ "tests/source/exchange_calendars/exchange_calendar_xlon.py",
+ "tests/source/exchange_calendars/exchange_calendar_xmad.py",
+ "tests/source/exchange_calendars/exchange_calendar_xmex.py",
+ "tests/source/exchange_calendars/exchange_calendar_xmil.py",
+ "tests/source/exchange_calendars/exchange_calendar_xmos.py",
+ "tests/source/exchange_calendars/exchange_calendar_xnys.py",
+ "tests/source/exchange_calendars/exchange_calendar_xnze.py",
+ "tests/source/exchange_calendars/exchange_calendar_xosl.py",
+ "tests/source/exchange_calendars/exchange_calendar_xpar.py",
+ "tests/source/exchange_calendars/exchange_calendar_xphs.py",
+ "tests/source/exchange_calendars/exchange_calendar_xpra.py",
+ "tests/source/exchange_calendars/exchange_calendar_xsau.py",
+ "tests/source/exchange_calendars/exchange_calendar_xses.py",
+ "tests/source/exchange_calendars/exchange_calendar_xsgo.py",
+ "tests/source/exchange_calendars/exchange_calendar_xshg.py",
+ "tests/source/exchange_calendars/exchange_calendar_xsto.py",
+ "tests/source/exchange_calendars/exchange_calendar_xswx.py",
+ "tests/source/exchange_calendars/exchange_calendar_xtae.py",
+ "tests/source/exchange_calendars/exchange_calendar_xtai.py",
+ "tests/source/exchange_calendars/exchange_calendar_xtks.py",
+ "tests/source/exchange_calendars/exchange_calendar_xtse.py",
+ "tests/source/exchange_calendars/exchange_calendar_xwar.py",
+ "tests/source/exchange_calendars/exchange_calendar_xwbo.py",
+ "tests/source/exchange_calendars/lunisolar_holidays.py",
+ "tests/source/exchange_calendars/pandas_extensions/__init__.py",
+ "tests/source/exchange_calendars/pandas_extensions/holiday.py",
+ "tests/source/exchange_calendars/pandas_extensions/korean_holiday.py",
+ "tests/source/exchange_calendars/pandas_extensions/offsets.py",
+ "tests/source/exchange_calendars/precomputed_exchange_calendar.py",
+ "tests/source/exchange_calendars/tase_holidays.py",
+ "tests/source/exchange_calendars/us_futures_calendar.py",
+ "tests/source/exchange_calendars/us_holidays.py",
+ "tests/source/exchange_calendars/utils/__init__.py",
+ "tests/source/exchange_calendars/utils/pandas_utils.py",
+ "tests/source/exchange_calendars/weekday_calendar.py",
+ "tests/source/exchange_calendars/xbkk_holidays.py",
+ "tests/source/exchange_calendars/xkls_holidays.py",
+ "tests/source/exchange_calendars/xkrx_holidays.py",
+ "tests/source/exchange_calendars/xtks_holidays.py",
+ "tests/source/pyproject.toml",
+ "tests/source/setup.cfg",
+ "tests/source/tests/__init__.py",
+ "tests/source/tests/resources/24-5.csv",
+ "tests/source/tests/resources/24-7.csv",
+ "tests/source/tests/resources/aixk.csv",
+ "tests/source/tests/resources/asex.csv",
+ "tests/source/tests/resources/bvmf.csv",
+ "tests/source/tests/resources/cmes.csv",
+ "tests/source/tests/resources/iepa.csv",
+ "tests/source/tests/resources/test.csv",
+ "tests/source/tests/resources/xams.csv",
+ "tests/source/tests/resources/xasx.csv",
+ "tests/source/tests/resources/xbkk.csv",
+ "tests/source/tests/resources/xbog.csv",
+ "tests/source/tests/resources/xbom.csv",
+ "tests/source/tests/resources/xbru.csv",
+ "tests/source/tests/resources/xbse.csv",
+ "tests/source/tests/resources/xbud.csv",
+ "tests/source/tests/resources/xbue.csv",
+ "tests/source/tests/resources/xcbf.csv",
+ "tests/source/tests/resources/xcse.csv",
+ "tests/source/tests/resources/xdub.csv",
+ "tests/source/tests/resources/xetr.csv",
+ "tests/source/tests/resources/xfra.csv",
+ "tests/source/tests/resources/xhel.csv",
+ "tests/source/tests/resources/xhkg.csv",
+ "tests/source/tests/resources/xice.csv",
+ "tests/source/tests/resources/xidx.csv",
+ "tests/source/tests/resources/xist.csv",
+ "tests/source/tests/resources/xjse.csv",
+ "tests/source/tests/resources/xkar.csv",
+ "tests/source/tests/resources/xkls.csv",
+ "tests/source/tests/resources/xkrx.csv",
+ "tests/source/tests/resources/xlim.csv",
+ "tests/source/tests/resources/xlis.csv",
+ "tests/source/tests/resources/xlon.csv",
+ "tests/source/tests/resources/xmad.csv",
+ "tests/source/tests/resources/xmex.csv",
+ "tests/source/tests/resources/xmil.csv",
+ "tests/source/tests/resources/xmos.csv",
+ "tests/source/tests/resources/xnys.csv",
+ "tests/source/tests/resources/xnze.csv",
+ "tests/source/tests/resources/xosl.csv",
+ "tests/source/tests/resources/xpar.csv",
+ "tests/source/tests/resources/xphs.csv",
+ "tests/source/tests/resources/xpra.csv",
+ "tests/source/tests/resources/xsau.csv",
+ "tests/source/tests/resources/xses.csv",
+ "tests/source/tests/resources/xsgo.csv",
+ "tests/source/tests/resources/xshg.csv",
+ "tests/source/tests/resources/xsto.csv",
+ "tests/source/tests/resources/xswx.csv",
+ "tests/source/tests/resources/xtae.csv",
+ "tests/source/tests/resources/xtai.csv",
+ "tests/source/tests/resources/xtks.csv",
+ "tests/source/tests/resources/xtse.csv",
+ "tests/source/tests/resources/xwar.csv",
+ "tests/source/tests/resources/xwbo.csv",
+ "tests/source/tests/test_aixk_calendar.py",
+ "tests/source/tests/test_always_open.py",
+ "tests/source/tests/test_asex_calendar.py",
+ "tests/source/tests/test_bvmf_calendar.py",
+ "tests/source/tests/test_calendar_dispatcher.py",
+ "tests/source/tests/test_calendar_helpers.py",
+ "tests/source/tests/test_cmes_calendar.py",
+ "tests/source/tests/test_exchange_calendar.py",
+ "tests/source/tests/test_iepa_calendar.py",
+ "tests/source/tests/test_utils.py",
+ "tests/source/tests/test_weekday_calendar.py",
+ "tests/source/tests/test_xams_calendar.py",
+ "tests/source/tests/test_xasx_calendar.py",
+ "tests/source/tests/test_xbkk_calendar.py",
+ "tests/source/tests/test_xbog_calendar.py",
+ "tests/source/tests/test_xbom_calendar.py",
+ "tests/source/tests/test_xbru_calendar.py",
+ "tests/source/tests/test_xbse_calendar.py",
+ "tests/source/tests/test_xbud_calendar.py",
+ "tests/source/tests/test_xbue_calendar.py",
+ "tests/source/tests/test_xcbf_calendar.py",
+ "tests/source/tests/test_xcse_calendar.py",
+ "tests/source/tests/test_xdub_calendar.py",
+ "tests/source/tests/test_xetr_calendar.py",
+ "tests/source/tests/test_xfra_calendar.py",
+ "tests/source/tests/test_xhel_calendar.py",
+ "tests/source/tests/test_xhkg_calendar.py",
+ "tests/source/tests/test_xice_calendar.py",
+ "tests/source/tests/test_xidx_calendar.py",
+ "tests/source/tests/test_xist_calendar.py",
+ "tests/source/tests/test_xjse_calendar.py",
+ "tests/source/tests/test_xkar_calendar.py",
+ "tests/source/tests/test_xkls_calendar.py",
+ "tests/source/tests/test_xkrx_calendar.py",
+ "tests/source/tests/test_xlim_calendar.py",
+ "tests/source/tests/test_xlis_calendar.py",
+ "tests/source/tests/test_xlon_calendar.py",
+ "tests/source/tests/test_xmad_calendar.py",
+ "tests/source/tests/test_xmex_calendar.py",
+ "tests/source/tests/test_xmil_calendar.py",
+ "tests/source/tests/test_xmos_calendar.py",
+ "tests/source/tests/test_xnys_calendar.py",
+ "tests/source/tests/test_xnze_calendar.py",
+ "tests/source/tests/test_xosl_calendar.py",
+ "tests/source/tests/test_xpar_calendar.py",
+ "tests/source/tests/test_xphs_calendar.py",
+ "tests/source/tests/test_xpra_calendar.py",
+ "tests/source/tests/test_xsau_calendar.py",
+ "tests/source/tests/test_xses_calendar.py",
+ "tests/source/tests/test_xsgo_calendar.py",
+ "tests/source/tests/test_xshg_calendar.py",
+ "tests/source/tests/test_xsto_calendar.py",
+ "tests/source/tests/test_xswx_calendar.py",
+ "tests/source/tests/test_xtae_calendar.py",
+ "tests/source/tests/test_xtai_calendar.py",
+ "tests/source/tests/test_xtks_calendar.py",
+ "tests/source/tests/test_xtse_calendar.py",
+ "tests/source/tests/test_xwar_calendar.py",
+ "tests/source/tests/test_xwbo_calendar.py",
+ "tests/test.sh",
+ "tests/test_driver.py",
+ "tests/test_results.py",
+]
+executable_files = [
+ "environment/source/.devcontainer/library-scripts/common-debian.sh",
+ "environment/source/.devcontainer/library-scripts/node-debian.sh",
+ "environment/source/.devcontainer/library-scripts/python-debian.sh",
+ "environment/source/etc/ecal",
+ "environment/source/etc/lunisolar",
+ "solution/solve.sh",
+ "tests/source/.devcontainer/library-scripts/common-debian.sh",
+ "tests/source/.devcontainer/library-scripts/node-debian.sh",
+ "tests/source/.devcontainer/library-scripts/python-debian.sh",
+ "tests/source/etc/ecal",
+ "tests/source/etc/lunisolar",
+ "tests/test.sh",
+]
+bundle_hash = "sha256:fdc138c19a73529e9c581213968a1dfd36cd083149c6808c27c95634e60838d7"
+
+[metadata.repo2env.evaluation]
+schema_version = "1"
+status = "verified"
+stage = "complete"
+reason_codes = [
+ "quality_verified",
+]
+detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile."
+checked_at = "2026-11-20T11:32:32.735165Z"
+provenance = "unknown"
+subject_bundle_hash = "sha256:fdc138c19a73529e9c581213968a1dfd36cd083149c6808c27c95634e60838d7"
+profile = "evidence-review-v2"
+source_task_path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b1183ee59290/candidates/ca08ab4caec6/quality/revisions/r0/tasksmith-ca08ab4caec6"
+source_task_toml_sha256 = "e0eab9871cfa7db06a0747a13d95f9231f8c7b943b7f467ceebc52adef40c00d"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "quality_result"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b1183ee59290/candidates/ca08ab4caec6/quality/result.json"
+sha256 = "314d2bd350edce5bfd0a8939b7b2d8f9a47d5b5af3674071c4ea00868b43c2e1"
+subject_bundle_hash = "sha256:fdc138c19a73529e9c581213968a1dfd36cd083149c6808c27c95634e60838d7"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "baseline"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b1183ee59290/candidates/ca08ab4caec6/quality/trials/r0-baseline/tsbatch-195cc094e760-b1183ee59290-q-ca08ab4c-r0-baseline/tasksmith-ca08ab4caec6__82Ruoag/result.json"
+sha256 = "d3a5d022453c705fa53e5301487c21d4ce6d55781aac9f34005190384d1616fb"
+subject_bundle_hash = "sha256:fdc138c19a73529e9c581213968a1dfd36cd083149c6808c27c95634e60838d7"
+harbor_task_checksum = "86667f3b426b69223033ef7ecfd13cacfbf85f9614e870440fc4f5b6396229af"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "oracle"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b1183ee59290/candidates/ca08ab4caec6/quality/trials/r0-oracle/tsbatch-195cc094e760-b1183ee59290-q-ca08ab4c-r0-oracle/tasksmith-ca08ab4caec6__SwtFNE5/result.json"
+sha256 = "47addf38c185afbe1ff424e111dd8f08f2745a9824d3e133f5aa81819e486f5a"
+subject_bundle_hash = "sha256:fdc138c19a73529e9c581213968a1dfd36cd083149c6808c27c95634e60838d7"
+harbor_task_checksum = "86667f3b426b69223033ef7ecfd13cacfbf85f9614e870440fc4f5b6396229af"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "probe"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b1183ee59290/candidates/ca08ab4caec6/quality/trials/r0-probe0/tsbatch-195cc094e760-b1183ee59290-q-ca08ab4c-r0-probe0/tasksmith-ca08ab4caec6__Ry9DYWz/result.json"
+sha256 = "b470cb081a4f937ea7c2edb7bc53b6be3a2b193cc363470768874e43d7d600ca"
+subject_bundle_hash = "sha256:79506f11c39aed754209cda6d2c93024c49895af83e394422c432e8616e86754"
+harbor_task_checksum = "18384c582b709cefb3457a3c7630d855ff60fb13cec59821ba6f17de72c9f0b6"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "probe"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b1183ee59290/candidates/ca08ab4caec6/quality/trials/r0-probe1/tsbatch-195cc094e760-b1183ee59290-q-ca08ab4c-r0-probe1/tasksmith-ca08ab4caec6__CX8jwP6/result.json"
+sha256 = "c50108b423d6dbaab082746672625583e40b55016d4a74fdf9c4432fca0c9135"
+subject_bundle_hash = "sha256:890a5f4dfa69732222b9da0a405b7d2b9192139fffbbf79df9ccaddd0adb537d"
+harbor_task_checksum = "4018cd8b7cbd33acc5d8b6be0f926f32c53193bec2b54e3dc7667550accec8ad"
+
+[[metadata.repo2env.evaluation.evidence]]
+kind = "rollout"
+path = "/Users/ben/.t3/projects/harness-adapters-data/runs/apex-agents-gap/phase2/batch/candidates/b1183ee59290/candidates/ca08ab4caec6/quality/trials/r0-rollout/tsbatch-195cc094e760-b1183ee59290-q-ca08ab4c-r0-rollout/tasksmith-ca08ab4caec6__FJ9zgCm/result.json"
+sha256 = "2dd0dfec79984018232bd431301ff6e18d1e68607a22e061889c475942d5f19a"
+subject_bundle_hash = "sha256:fdc138c19a73529e9c581213968a1dfd36cd083149c6808c27c95634e60838d7"
+harbor_task_checksum = "86667f3b426b69223033ef7ecfd13cacfbf85f9614e870440fc4f5b6396229af"
+
+[metadata.repo2env.quality_requirements]
+probe_focus = [
+ "general",
+]
+
+[environment]
+docker_image = "ghcr.io/younesbelkada/hat@sha256:806e01670c58d63125316ad0bd11d78fc6a9bd8ac5a97173abd63b7a2e05e44d"
+cpus = 1
+memory_mb = 2048
+build_timeout_sec = 600
+network_mode = "no-network"
+
+[agent]
+timeout_sec = 600
+user = "learner"
+network_mode = "no-network"
+
+[verifier]
+timeout_sec = 210
+user = "root"
+network_mode = "no-network"
+environment_mode = "separate"
+
+[verifier.environment]
+network_mode = "no-network"
+cpus = 2
+memory_mb = 2048
+
+[[artifacts]]
+source = "/workspace/exchange_calendars"
+exclude = [
+ "__pycache__",
+ "*.pyc",
+ ".pytest_cache",
+]
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/Dockerfile b/tasks/tasksmith-ca08ab4caec6/tests/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..d6207bbe0af6bd6ffa4a7efeee71b8d05178d9b6
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/Dockerfile
@@ -0,0 +1,10 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir numpy==1.26.4 pandas==2.2.0 pyluach==2.2.0 python-dateutil==2.8.2 pytz==2024.1 six==1.16.0 toolz==0.12.1 tzdata==2024.1 korean-lunar-calendar==0.3.1 pytest==8.0.0 'setuptools>=43.0.0' 'setuptools_scm[toml]>=6.2' wheel==0.42.0
+COPY source /workspace
+RUN SETUPTOOLS_SCM_PRETEND_VERSION=0.0.1 python -m pip install --no-cache-dir --no-deps --no-build-isolation -e .
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
+RUN useradd -m -u 1001 grader
+COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/
+RUN chmod 755 /tests && chmod 644 /tests/*
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/contract.json b/tasks/tasksmith-ca08ab4caec6/tests/contract.json
new file mode 100644
index 0000000000000000000000000000000000000000..10548055f1498bfd6c64bf716f6f428512a97238
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/contract.json
@@ -0,0 +1 @@
+{"expected_passes": ["tests.test_xmos_calendar.TestXMOSCalendar::test_calculated_against_csv", "tests.test_xmos_calendar.TestXMOSCalendar::test_date_to_session", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_open_at_time[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_open_at_time[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_open_at_time[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_open_at_time[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_session", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_trading_minute[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_trading_minute[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_trading_minute[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_trading_minute[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_offset[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_offset[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_offset[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_offset[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_offset_by_sessions[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_offset_by_sessions[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_offset_by_sessions[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_offset_by_sessions[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_future_session[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_future_session[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_future_session[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_future_session[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_past_session[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_past_session[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_past_session[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_past_session[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[both-next]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[both-none]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[both-previous]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[left-next]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[left-none]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[left-previous]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[neither-next]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[neither-none]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[neither-previous]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[right-next]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[right-none]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_session[right-previous]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_distance[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_distance[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_distance[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_distance[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_in_range[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_in_range[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_in_range[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_in_range[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_properties[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_properties[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_properties[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_properties[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_to_sessions[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_to_sessions[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_to_sessions[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_to_sessions[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_window[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_window[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_window[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minutes_window[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_next_prev_session", "tests.test_xmos_calendar.TestXMOSCalendar::test_opens_closes_break_starts_ends", "tests.test_xmos_calendar.TestXMOSCalendar::test_prev_next_minute[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_prev_next_minute[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_prev_next_minute[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_prev_next_minute[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_prev_next_open_close", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_has_break", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_minute_methods[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_minute_methods[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_minute_methods[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_minute_methods[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_minutes[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_minutes[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_minutes[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_minutes[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_offset", "tests.test_xmos_calendar.TestXMOSCalendar::test_session_open_close_break_start_end", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_distance", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_in_range", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_minutes[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_minutes[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_minutes[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_minutes[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_minutes_count[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_minutes_count[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_minutes_count[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_minutes_count[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_window", "tests.test_xmos_calendar.TestXMOSCalendar::test_trading_index", "tests.test_xkrx_calendar.TestXKRXCalendar::test_adhoc_holidays_sample", "tests.test_xkrx_calendar.TestXKRXCalendar::test_adhoc_holidays_specification", "tests.test_xkrx_calendar.TestXKRXCalendar::test_base_integrity", "tests.test_xkrx_calendar.TestXKRXCalendar::test_bound_max", "tests.test_xkrx_calendar.TestXKRXCalendar::test_bound_min", "tests.test_xkrx_calendar.TestXKRXCalendar::test_calculated_against_csv", "tests.test_xkrx_calendar.TestXKRXCalendar::test_calendar_bounds_properties[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_calendar_bounds_properties[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_calendar_bounds_properties[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_calendar_bounds_properties[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_date_to_session", "tests.test_xkrx_calendar.TestXKRXCalendar::test_daylight_savings", "tests.test_xkrx_calendar.TestXKRXCalendar::test_deprecated", "tests.test_xkrx_calendar.TestXKRXCalendar::test_early_closes", "tests.test_xkrx_calendar.TestXKRXCalendar::test_early_closes_sample", "tests.test_xkrx_calendar.TestXKRXCalendar::test_early_closes_sample_time", "tests.test_xkrx_calendar.TestXKRXCalendar::test_early_closes_weekdays", "tests.test_xkrx_calendar.TestXKRXCalendar::test_early_closes_weekdays_time", "tests.test_xkrx_calendar.TestXKRXCalendar::test_feb_29_2022_in_lunar_calendar", "tests.test_xkrx_calendar.TestXKRXCalendar::test_has_break", "tests.test_xkrx_calendar.TestXKRXCalendar::test_historical_regular_holidays_fall_into_precomputed_holidays", "tests.test_xkrx_calendar.TestXKRXCalendar::test_invalid_input", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_break_minute[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_break_minute[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_break_minute[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_break_minute[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_open_at_time[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_open_at_time[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_open_at_time[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_open_at_time[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_open_on_minute[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_open_on_minute[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_open_on_minute[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_open_on_minute[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_session", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_trading_minute[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_trading_minute[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_trading_minute[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_is_trading_minute[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_late_opens_sample", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_offset[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_offset[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_offset[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_offset[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_offset_by_sessions[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_offset_by_sessions[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_offset_by_sessions[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_offset_by_sessions[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_future_session[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_future_session[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_future_session[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_future_session[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_past_session[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_past_session[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_past_session[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_past_session[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[both-next]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[both-none]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[both-previous]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[left-next]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[left-none]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[left-previous]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[neither-next]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[neither-none]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[neither-previous]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[right-next]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[right-none]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_session[right-previous]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[both-next]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[both-none]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[both-previous]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[left-next]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[left-none]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[left-previous]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[neither-next]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[neither-none]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[neither-previous]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[right-next]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[right-none]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minute_to_trading_minute[right-previous]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_distance[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_distance[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_distance[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_distance[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_in_range[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_in_range[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_in_range[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_in_range[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_properties[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_properties[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_properties[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_properties[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_to_sessions[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_to_sessions[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_to_sessions[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_to_sessions[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_window[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_window[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_window[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_minutes_window[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_next_prev_session", "tests.test_xkrx_calendar.TestXKRXCalendar::test_non_early_closes_sample", "tests.test_xkrx_calendar.TestXKRXCalendar::test_non_early_closes_sample_time", "tests.test_xkrx_calendar.TestXKRXCalendar::test_non_holidays_sample", "tests.test_xkrx_calendar.TestXKRXCalendar::test_opens_closes_break_starts_ends", "tests.test_xkrx_calendar.TestXKRXCalendar::test_prev_next_minute[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_prev_next_minute[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_prev_next_minute[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_prev_next_minute[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_prev_next_open_close", "tests.test_xkrx_calendar.TestXKRXCalendar::test_regular_holidays_sample", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sanity_check_session_lengths", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_has_break", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_minute_methods[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_minute_methods[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_minute_methods[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_minute_methods[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_minutes[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_minutes[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_minutes[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_minutes[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_offset", "tests.test_xkrx_calendar.TestXKRXCalendar::test_session_open_close_break_start_end", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_distance", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_has_break", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_in_range", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_minutes[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_minutes[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_minutes[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_minutes[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_minutes_count[both]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_minutes_count[left]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_minutes_count[neither]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_minutes_count[right]", "tests.test_xkrx_calendar.TestXKRXCalendar::test_sessions_window", "tests.test_xkrx_calendar.TestXKRXCalendar::test_start_end", "tests.test_xkrx_calendar.TestXKRXCalendar::test_testbase_integrity", "tests.test_xkrx_calendar.TestXKRXCalendar::test_trading_index", "tests.test_xmos_calendar.TestXMOSCalendar::test_adhoc_holidays_sample", "tests.test_xmos_calendar.TestXMOSCalendar::test_adhoc_holidays_specification", "tests.test_xmos_calendar.TestXMOSCalendar::test_base_integrity", "tests.test_xmos_calendar.TestXMOSCalendar::test_bound_max", "tests.test_xmos_calendar.TestXMOSCalendar::test_bound_min", "tests.test_xmos_calendar.TestXMOSCalendar::test_calendar_bounds_properties[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_calendar_bounds_properties[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_calendar_bounds_properties[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_calendar_bounds_properties[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_daylight_savings", "tests.test_xmos_calendar.TestXMOSCalendar::test_deprecated", "tests.test_xmos_calendar.TestXMOSCalendar::test_early_closes", "tests.test_xmos_calendar.TestXMOSCalendar::test_early_closes_sample", "tests.test_xmos_calendar.TestXMOSCalendar::test_early_closes_sample_time", "tests.test_xmos_calendar.TestXMOSCalendar::test_early_closes_weekdays", "tests.test_xmos_calendar.TestXMOSCalendar::test_early_closes_weekdays_time", "tests.test_xmos_calendar.TestXMOSCalendar::test_has_break", "tests.test_xmos_calendar.TestXMOSCalendar::test_invalid_input", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_break_minute[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_break_minute[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_break_minute[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_break_minute[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_open_on_minute[both]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_open_on_minute[left]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_open_on_minute[neither]", "tests.test_xmos_calendar.TestXMOSCalendar::test_is_open_on_minute[right]", "tests.test_xmos_calendar.TestXMOSCalendar::test_late_opens", "tests.test_xmos_calendar.TestXMOSCalendar::test_late_opens_sample", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[both-next]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[both-none]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[both-previous]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[left-next]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[left-none]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[left-previous]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[neither-next]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[neither-none]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[neither-previous]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[right-next]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[right-none]", "tests.test_xmos_calendar.TestXMOSCalendar::test_minute_to_trading_minute[right-previous]", "tests.test_xmos_calendar.TestXMOSCalendar::test_non_early_closes_sample", "tests.test_xmos_calendar.TestXMOSCalendar::test_non_early_closes_sample_time", "tests.test_xmos_calendar.TestXMOSCalendar::test_non_holidays_sample", "tests.test_xmos_calendar.TestXMOSCalendar::test_regular_holidays_sample", "tests.test_xmos_calendar.TestXMOSCalendar::test_sanity_check_session_lengths", "tests.test_xmos_calendar.TestXMOSCalendar::test_sessions_has_break", "tests.test_xmos_calendar.TestXMOSCalendar::test_start_end", "tests.test_xmos_calendar.TestXMOSCalendar::test_testbase_integrity"], "immutable_assets": {}, "optional_files": [], "pytest_args": ["-p", "no:doctest"], "submitted_files": ["exchange_calendars/__init__.py", "exchange_calendars/_version.py", "exchange_calendars/always_open.py", "exchange_calendars/calendar_helpers.py", "exchange_calendars/calendar_utils.py", "exchange_calendars/common_holidays.py", "exchange_calendars/ecal.py", "exchange_calendars/errors.py", "exchange_calendars/exchange_calendar.py", "exchange_calendars/exchange_calendar_aixk.py", "exchange_calendars/exchange_calendar_asex.py", "exchange_calendars/exchange_calendar_bvmf.py", "exchange_calendars/exchange_calendar_cmes.py", "exchange_calendars/exchange_calendar_iepa.py", "exchange_calendars/exchange_calendar_xams.py", "exchange_calendars/exchange_calendar_xasx.py", "exchange_calendars/exchange_calendar_xbkk.py", "exchange_calendars/exchange_calendar_xbog.py", "exchange_calendars/exchange_calendar_xbom.py", "exchange_calendars/exchange_calendar_xbru.py", "exchange_calendars/exchange_calendar_xbse.py", "exchange_calendars/exchange_calendar_xbud.py", "exchange_calendars/exchange_calendar_xbue.py", "exchange_calendars/exchange_calendar_xcbf.py", "exchange_calendars/exchange_calendar_xcse.py", "exchange_calendars/exchange_calendar_xdub.py", "exchange_calendars/exchange_calendar_xetr.py", "exchange_calendars/exchange_calendar_xfra.py", "exchange_calendars/exchange_calendar_xhel.py", "exchange_calendars/exchange_calendar_xhkg.py", "exchange_calendars/exchange_calendar_xice.py", "exchange_calendars/exchange_calendar_xidx.py", "exchange_calendars/exchange_calendar_xist.py", "exchange_calendars/exchange_calendar_xjse.py", "exchange_calendars/exchange_calendar_xkar.py", "exchange_calendars/exchange_calendar_xkls.py", "exchange_calendars/exchange_calendar_xkrx.py", "exchange_calendars/exchange_calendar_xlim.py", "exchange_calendars/exchange_calendar_xlis.py", "exchange_calendars/exchange_calendar_xlon.py", "exchange_calendars/exchange_calendar_xmad.py", "exchange_calendars/exchange_calendar_xmex.py", "exchange_calendars/exchange_calendar_xmil.py", "exchange_calendars/exchange_calendar_xmos.py", "exchange_calendars/exchange_calendar_xnys.py", "exchange_calendars/exchange_calendar_xnze.py", "exchange_calendars/exchange_calendar_xosl.py", "exchange_calendars/exchange_calendar_xpar.py", "exchange_calendars/exchange_calendar_xphs.py", "exchange_calendars/exchange_calendar_xpra.py", "exchange_calendars/exchange_calendar_xsau.py", "exchange_calendars/exchange_calendar_xses.py", "exchange_calendars/exchange_calendar_xsgo.py", "exchange_calendars/exchange_calendar_xshg.py", "exchange_calendars/exchange_calendar_xsto.py", "exchange_calendars/exchange_calendar_xswx.py", "exchange_calendars/exchange_calendar_xtae.py", "exchange_calendars/exchange_calendar_xtai.py", "exchange_calendars/exchange_calendar_xtks.py", "exchange_calendars/exchange_calendar_xtse.py", "exchange_calendars/exchange_calendar_xwar.py", "exchange_calendars/exchange_calendar_xwbo.py", "exchange_calendars/lunisolar_holidays.py", "exchange_calendars/pandas_extensions/__init__.py", "exchange_calendars/pandas_extensions/holiday.py", "exchange_calendars/pandas_extensions/korean_holiday.py", "exchange_calendars/pandas_extensions/offsets.py", "exchange_calendars/precomputed_exchange_calendar.py", "exchange_calendars/tase_holidays.py", "exchange_calendars/us_futures_calendar.py", "exchange_calendars/us_holidays.py", "exchange_calendars/utils/__init__.py", "exchange_calendars/utils/pandas_utils.py", "exchange_calendars/weekday_calendar.py", "exchange_calendars/xbkk_holidays.py", "exchange_calendars/xkls_holidays.py", "exchange_calendars/xkrx_holidays.py", "exchange_calendars/xtks_holidays.py"], "submitted_roots": ["exchange_calendars"], "test_paths": ["tests/test_xmos_calendar.py", "tests/test_xkrx_calendar.py"], "timeout_sec": 180}
\ No newline at end of file
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/grade.py b/tasks/tasksmith-ca08ab4caec6/tests/grade.py
new file mode 100644
index 0000000000000000000000000000000000000000..a803a55bfcc142c8279645ea59cea90b2a90918a
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/grade.py
@@ -0,0 +1,196 @@
+"""Standalone trusted entry point; copied into each separate verifier image.
+
+No Repo2RLEnv installation is needed to grade an exported task. Submitted Python
+runs as an unprivileged user; this parent owns the result parser and reward file.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import os
+import signal
+import stat
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+
+def child_environment(temporary: str) -> dict[str, str]:
+ """Preserve prepared runtime assets without inheriting controller credentials."""
+ return {
+ **{
+ key: os.environ[key]
+ for key in (
+ "LD_LIBRARY_PATH",
+ "CUDA_VISIBLE_DEVICES",
+ "NVIDIA_VISIBLE_DEVICES",
+ "NVIDIA_DRIVER_CAPABILITIES",
+ "NCCL_SOCKET_IFNAME",
+ "GLOO_SOCKET_IFNAME",
+ "HF_HOME",
+ "HF_HUB_CACHE",
+ "HF_HUB_OFFLINE",
+ "TRANSFORMERS_OFFLINE",
+ "HF_DATASETS_OFFLINE",
+ )
+ if key in os.environ
+ },
+ "PATH": str(Path(sys.executable).parent) + ":/usr/local/bin:/usr/bin:/bin",
+ "HOME": temporary,
+ "PYTHONDONTWRITEBYTECODE": "1",
+ "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1",
+ }
+
+
+def validate_submission(workspace: Path, contract: dict) -> None:
+ """Validate private staging and remove inert backups before importing Python."""
+ submitted = set(contract["submitted_files"])
+ backups: set[str] = set()
+ optional = submitted & set(contract.get("optional_files", []))
+ paths = submitted - optional
+ for relative in optional:
+ path = workspace / relative
+ if any(component.is_symlink() for component in (path, *path.parents)):
+ raise ValueError("Submitted source contains a symlink")
+ # Added standalone modules may be absent in the baseline. If supplied,
+ # apply the same regular-file and size checks as every required module.
+ if path.exists():
+ paths.add(relative)
+ roots = contract.get("submitted_roots", [])
+ immutable = contract.get("immutable_assets", {})
+ paths.update(immutable)
+ for relative in roots:
+ root = workspace / relative
+ if root.is_symlink() or not root.is_dir():
+ raise ValueError("Submitted source root is missing or linked")
+ for path in root.rglob("*"):
+ if path.is_symlink():
+ raise ValueError("Submitted source contains a symlink")
+ if path.is_dir():
+ continue
+ name = path.relative_to(workspace).as_posix()
+ if path.suffix != ".py" and name not in immutable:
+ if name not in submitted and path.name.endswith((".py.bak", ".py~")):
+ backups.add(name)
+ else:
+ raise ValueError("Only Python source files may be added")
+ paths.add(name)
+ for relative in sorted(paths):
+ path = workspace / relative
+ for component in (path, *path.parents):
+ if component.is_symlink():
+ raise ValueError("Submitted source contains a symlink")
+ if (
+ not path.is_file()
+ or not stat.S_ISREG(path.stat().st_mode)
+ or path.stat().st_size > 8 * 1024 * 1024
+ ):
+ raise ValueError("Submitted source is not a bounded regular file")
+ if (
+ relative in immutable
+ and hashlib.sha256(path.read_bytes()).hexdigest() != immutable[relative]
+ ):
+ raise ValueError("Non-Python source assets must remain unchanged")
+ if relative not in backups:
+ # os.chown doesn't exist on Windows. This module only ever runs for
+ # real inside the Linux verifier container (every other path here
+ # is an absolute container path); the guard exists so the tests
+ # that call validate_submission() directly can run on a Windows
+ # host without touching real container-only ownership semantics.
+ if sys.platform != "win32":
+ os.chown(path, 0, 0)
+ path.chmod(0o644)
+ # Only the verifier's collected copy is cleaned. The learner workspace and
+ # archived submission retain their bytes. Validate every path first so a
+ # backup cannot bypass linked, oversized, required, or immutable file checks.
+ for relative in sorted(backups):
+ (workspace / relative).unlink()
+
+
+def main() -> None:
+ directory = Path("/tests")
+ parser_spec = importlib.util.spec_from_file_location(
+ "test_results", directory / "test_results.py"
+ )
+ parser = importlib.util.module_from_spec(parser_spec)
+ sys.modules[parser_spec.name] = parser
+ parser_spec.loader.exec_module(parser)
+ contract = json.loads((directory / "contract.json").read_text())
+ logs = Path("/logs/verifier")
+ logs.mkdir(parents=True, exist_ok=True)
+ logs.chmod(0o755)
+ reward = logs / "reward.txt"
+ reward.write_text("0\n")
+ reward.chmod(0o644)
+ try:
+ validate_submission(Path("/workspace"), contract)
+ except (ValueError, OSError) as exc:
+ (logs / "result.json").write_text(json.dumps({"passed": False, "reason": str(exc)}))
+ return
+ with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary:
+ working = Path(temporary)
+ if sys.platform != "win32": # os.chown doesn't exist on Windows; see above
+ os.chown(working, 1001, 1001)
+ working.chmod(0o700)
+ report = working / "results.xml"
+ command = [
+ sys.executable,
+ "-I",
+ "/tests/test_driver.py",
+ *contract["test_paths"],
+ *contract.get("pytest_args", []),
+ "-q",
+ "--tb=short",
+ "-p",
+ "no:cacheprovider",
+ f"--junitxml={report}",
+ ]
+ with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr:
+ process = subprocess.Popen(
+ command,
+ cwd="/workspace",
+ stdout=stdout,
+ stderr=stderr,
+ user=1001,
+ group=1001,
+ extra_groups=[],
+ start_new_session=True,
+ env=child_environment(temporary),
+ )
+ try:
+ code = process.wait(timeout=contract["timeout_sec"])
+ finally:
+ # Terminate descendants too: they must not keep modifying the
+ # child-owned report while the trusted parent checks it.
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024:
+ (logs / "result.json").write_text(
+ json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"})
+ )
+ return
+ text = report.read_text()
+ (logs / "results.xml").write_text(text)
+ try:
+ parsed = parser.parse_junit(text, returncode=code)
+ except ValueError as exc:
+ (logs / "result.json").write_text(
+ json.dumps({"passed": False, "returncode": code, "reason": str(exc)})
+ )
+ return
+ expected = set(contract["expected_passes"])
+ passed = code == 0 and bool(expected) and parsed.passed == expected
+ (logs / "result.json").write_text(
+ json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses})
+ )
+ reward.write_text("1\n" if passed else "0\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/Dockerfile b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..c6068a3c078240eb4ede52a64fab6490cb0a743b
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/Dockerfile
@@ -0,0 +1,21 @@
+# [Choice] Python version: 3, 3.8, 3.7, 3.6
+ARG VARIANT=3
+FROM mcr.microsoft.com/vscode/devcontainers/python:${VARIANT}
+
+# [Option] Install Node.js
+ARG INSTALL_NODE="true"
+ARG NODE_VERSION="lts/*"
+RUN if [ "${INSTALL_NODE}" = "true" ]; then su vscode -c "source /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION} 2>&1"; fi
+
+# [Optional] If your pip requirements rarely change, uncomment this section to add them to the image.
+COPY etc/requirements_locked.txt /tmp/pip-tmp/
+RUN pip3 --disable-pip-version-check --no-cache-dir install ipython \
+ && pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements_locked.txt \
+ && rm -rf /tmp/pip-tmp
+
+# [Optional] Uncomment this section to install additional OS packages.
+# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
+# && apt-get -y install --no-install-recommends
+
+# [Optional] Uncomment this line to install global node packages.
+# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/base.Dockerfile b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/base.Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..cf7768fc40a2410a36cfaa11b32ddd7c3843b372
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/base.Dockerfile
@@ -0,0 +1,50 @@
+# [Choice] Python version: 3, 3.8, 3.7, 3.6
+ARG VARIANT=3
+FROM python:${VARIANT}
+
+# [Option] Install zsh
+ARG INSTALL_ZSH="true"
+# [Option] Upgrade OS packages to their latest versions
+ARG UPGRADE_PACKAGES="true"
+
+# Install needed packages and setup non-root user. Use a separate RUN statement to add your own dependencies.
+ARG USERNAME=vscode
+ARG USER_UID=1000
+ARG USER_GID=$USER_UID
+COPY .devcontainer/library-scripts/common-debian.sh /tmp/library-scripts/
+RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
+ # Remove imagemagick due to https://security-tracker.debian.org/tracker/CVE-2019-10131
+ && apt-get purge -y imagemagick imagemagick-6-common \
+ # Install common packages, non-root user
+ && bash /tmp/library-scripts/common-debian.sh "${INSTALL_ZSH}" "${USERNAME}" "${USER_UID}" "${USER_GID}" "${UPGRADE_PACKAGES}" \
+ && apt-get autoremove -y && apt-get clean -y && rm -rf /var/lib/apt/lists/* /tmp/library-scripts
+
+# Setup default python tools in a venv via pipx to avoid conflicts
+ENV PIPX_HOME=/usr/local/py-utils \
+ PIPX_BIN_DIR=/usr/local/py-utils/bin
+ENV PATH=${PATH}:${PIPX_BIN_DIR}
+COPY .devcontainer/library-scripts/python-debian.sh /tmp/library-scripts/
+RUN bash /tmp/library-scripts/python-debian.sh "none" "/usr/local" "${PIPX_HOME}" "${USERNAME}" "false" \
+ && apt-get clean -y && rm -rf /tmp/library-scripts
+
+# [Option] Install Node.js
+ARG INSTALL_NODE="true"
+ARG NODE_VERSION="none"
+ENV NVM_DIR=/usr/local/share/nvm
+ENV NVM_SYMLINK_CURRENT=true \
+ PATH=${NVM_DIR}/current/bin:${PATH}
+COPY .devcontainer/library-scripts/node-debian.sh /tmp/library-scripts/
+RUN if [ "$INSTALL_NODE" = "true" ]; then bash /tmp/library-scripts/node-debian.sh "${NVM_DIR}" "${NODE_VERSION}" "${USERNAME}"; fi \
+ && apt-get clean -y && rm -rf /var/lib/apt/lists/* /tmp/library-scripts
+
+# [Optional] If your pip requirements rarely change, uncomment this section to add them to the image.
+# COPY requirements.txt /tmp/pip-tmp/
+# RUN pip3 --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \
+# && rm -rf /tmp/pip-tmp
+
+# [Optional] Uncomment this section to install additional OS packages.
+# RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \
+# && apt-get -y install --no-install-recommends
+
+# [Optional] Uncomment this line to install global node packages.
+# RUN su vscode -c "source /usr/local/share/nvm/nvm.sh && npm install -g " 2>&1
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/devcontainer.json b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/devcontainer.json
new file mode 100644
index 0000000000000000000000000000000000000000..a02f7fb41a38b0ae51e5197c95a0ea76381df102
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/devcontainer.json
@@ -0,0 +1,45 @@
+{
+ "name": "Python 3",
+ "build": {
+ "dockerfile": "Dockerfile",
+ "context": "..",
+ "args": {
+ // Update 'VARIANT' to pick a Python version: 3, 3.6, 3.7, 3.8
+ "VARIANT": "3.9",
+ // Options
+ "INSTALL_NODE": "false",
+ "NODE_VERSION": "lts/*"
+ }
+ },
+
+ // Set *default* container specific settings.json values on container create.
+ "settings": {
+ "terminal.integrated.shell.linux": "/bin/bash",
+ "python.pythonPath": "/usr/local/bin/python",
+ "python.linting.enabled": true,
+ "python.linting.pylintEnabled": true,
+ "python.formatting.autopep8Path": "/usr/local/py-utils/bin/autopep8",
+ "python.formatting.blackPath": "/usr/local/py-utils/bin/black",
+ "python.formatting.yapfPath": "/usr/local/py-utils/bin/yapf",
+ "python.linting.banditPath": "/usr/local/py-utils/bin/bandit",
+ "python.linting.flake8Path": "/usr/local/py-utils/bin/flake8",
+ "python.linting.mypyPath": "/usr/local/py-utils/bin/mypy",
+ "python.linting.pycodestylePath": "/usr/local/py-utils/bin/pycodestyle",
+ "python.linting.pydocstylePath": "/usr/local/py-utils/bin/pydocstyle",
+ "python.linting.pylintPath": "/usr/local/py-utils/bin/pylint"
+ },
+
+ // Add the IDs of extensions you want installed when the container is created.
+ "extensions": [
+ "ms-python.python"
+ ],
+
+ // Use 'forwardPorts' to make a list of ports inside the container available locally.
+ // "forwardPorts": [],
+
+ // Use 'postCreateCommand' to run commands after the container is created.
+ "postCreateCommand": "pip3 install --user -e .[dev]",
+
+ // Uncomment to connect as a non-root user. See https://aka.ms/vscode-remote/containers/non-root.
+ // "remoteUser": "vscode"
+}
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/README.md b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..844dfe8f617472ea3b2d04bacb77e1e1ef68b1fd
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/README.md
@@ -0,0 +1,5 @@
+# Warning: Folder contents may be replaced
+
+The contents of this folder will be automatically replaced with a file of the same name in the [vscode-dev-containers](https://github.com/microsoft/vscode-dev-containers) repository's [script-library folder](https://github.com/microsoft/vscode-dev-containers/tree/master/script-library) whenever the repository is packaged.
+
+To retain your edits, move the file to a different location. You may also delete the files if they are not needed.
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/common-debian.sh b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/common-debian.sh
new file mode 100644
index 0000000000000000000000000000000000000000..2eae386dc42061babad0e2f87955641343c8f792
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/common-debian.sh
@@ -0,0 +1,326 @@
+#!/usr/bin/env bash
+#-------------------------------------------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
+#-------------------------------------------------------------------------------------------------------------
+#
+# Docs: https://github.com/microsoft/vscode-dev-containers/blob/master/script-library/docs/common.md
+#
+# Syntax: ./common-debian.sh [install zsh flag] [username] [user UID] [user GID] [upgrade packages flag] [install Oh My *! flag]
+
+INSTALL_ZSH=${1:-"true"}
+USERNAME=${2:-"automatic"}
+USER_UID=${3:-"automatic"}
+USER_GID=${4:-"automatic"}
+UPGRADE_PACKAGES=${5:-"true"}
+INSTALL_OH_MYS=${6:-"true"}
+
+set -e
+
+if [ "$(id -u)" -ne 0 ]; then
+ echo -e 'Script must be run as root. Use sudo, su, or add "USER root" to your Dockerfile before running this script.'
+ exit 1
+fi
+
+# If in automatic mode, determine if a user already exists, if not use vscode
+if [ "${USERNAME}" = "auto" ] || [ "${USERNAME}" = "automatic" ]; then
+ USERNAME=""
+ POSSIBLE_USERS=("vscode" "node" "codespace" "$(awk -v val=1000 -F ":" '$3==val{print $1}' /etc/passwd)")
+ for CURRENT_USER in ${POSSIBLE_USERS[@]}; do
+ if id -u ${CURRENT_USER} > /dev/null 2>&1; then
+ USERNAME=${CURRENT_USER}
+ break
+ fi
+ done
+ if [ "${USERNAME}" = "" ]; then
+ USERNAME=vscode
+ fi
+elif [ "${USERNAME}" = "none" ]; then
+ USERNAME=root
+ USER_UID=0
+ USER_GID=0
+fi
+
+# Load markers to see which steps have already run
+MARKER_FILE="/usr/local/etc/vscode-dev-containers/common"
+if [ -f "${MARKER_FILE}" ]; then
+ echo "Marker file found:"
+ cat "${MARKER_FILE}"
+ source "${MARKER_FILE}"
+fi
+
+# Ensure apt is in non-interactive to avoid prompts
+export DEBIAN_FRONTEND=noninteractive
+
+# Function to call apt-get if needed
+apt-get-update-if-needed()
+{
+ if [ ! -d "/var/lib/apt/lists" ] || [ "$(ls /var/lib/apt/lists/ | wc -l)" = "0" ]; then
+ echo "Running apt-get update..."
+ apt-get update
+ else
+ echo "Skipping apt-get update."
+ fi
+}
+
+# Run install apt-utils to avoid debconf warning then verify presence of other common developer tools and dependencies
+if [ "${PACKAGES_ALREADY_INSTALLED}" != "true" ]; then
+ apt-get-update-if-needed
+
+ PACKAGE_LIST="apt-utils \
+ git \
+ openssh-client \
+ gnupg2 \
+ iproute2 \
+ procps \
+ lsof \
+ htop \
+ net-tools \
+ psmisc \
+ curl \
+ wget \
+ rsync \
+ ca-certificates \
+ unzip \
+ zip \
+ nano \
+ vim-tiny \
+ less \
+ jq \
+ lsb-release \
+ apt-transport-https \
+ dialog \
+ libc6 \
+ libgcc1 \
+ libgssapi-krb5-2 \
+ libicu[0-9][0-9] \
+ liblttng-ust0 \
+ libstdc++6 \
+ zlib1g \
+ locales \
+ sudo \
+ ncdu \
+ man-db"
+
+ # Install libssl1.1 if available
+ if [[ ! -z $(apt-cache --names-only search ^libssl1.1$) ]]; then
+ PACKAGE_LIST="${PACKAGE_LIST} libssl1.1"
+ fi
+
+ # Install appropriate version of libssl1.0.x if available
+ LIBSSL=$(dpkg-query -f '${db:Status-Abbrev}\t${binary:Package}\n' -W 'libssl1\.0\.?' 2>&1 || echo '')
+ if [ "$(echo "$LIBSSL" | grep -o 'libssl1\.0\.[0-9]:' | uniq | sort | wc -l)" -eq 0 ]; then
+ if [[ ! -z $(apt-cache --names-only search ^libssl1.0.2$) ]]; then
+ # Debian 9
+ PACKAGE_LIST="${PACKAGE_LIST} libssl1.0.2"
+ elif [[ ! -z $(apt-cache --names-only search ^libssl1.0.0$) ]]; then
+ # Ubuntu 18.04, 16.04, earlier
+ PACKAGE_LIST="${PACKAGE_LIST} libssl1.0.0"
+ fi
+ fi
+
+ echo "Packages to verify are installed: ${PACKAGE_LIST}"
+ apt-get -y install --no-install-recommends ${PACKAGE_LIST} 2> >( grep -v 'debconf: delaying package configuration, since apt-utils is not installed' >&2 )
+
+ PACKAGES_ALREADY_INSTALLED="true"
+fi
+
+# Get to latest versions of all packages
+if [ "${UPGRADE_PACKAGES}" = "true" ]; then
+ apt-get-update-if-needed
+ apt-get -y upgrade --no-install-recommends
+ apt-get autoremove -y
+fi
+
+# Ensure at least the en_US.UTF-8 UTF-8 locale is available.
+# Common need for both applications and things like the agnoster ZSH theme.
+if [ "${LOCALE_ALREADY_SET}" != "true" ] && ! grep -o -E '^\s*en_US.UTF-8\s+UTF-8' /etc/locale.gen > /dev/null; then
+ echo "en_US.UTF-8 UTF-8" >> /etc/locale.gen
+ locale-gen
+ LOCALE_ALREADY_SET="true"
+fi
+
+# Create or update a non-root user to match UID/GID.
+if id -u ${USERNAME} > /dev/null 2>&1; then
+ # User exists, update if needed
+ if [ "${USER_GID}" != "automatic" ] && [ "$USER_GID" != "$(id -G $USERNAME)" ]; then
+ groupmod --gid $USER_GID $USERNAME
+ usermod --gid $USER_GID $USERNAME
+ fi
+ if [ "${USER_UID}" != "automatic" ] && [ "$USER_UID" != "$(id -u $USERNAME)" ]; then
+ usermod --uid $USER_UID $USERNAME
+ fi
+else
+ # Create user
+ if [ "${USER_GID}" = "automatic" ]; then
+ groupadd $USERNAME
+ else
+ groupadd --gid $USER_GID $USERNAME
+ fi
+ if [ "${USER_UID}" = "automatic" ]; then
+ useradd -s /bin/bash --gid $USERNAME -m $USERNAME
+ else
+ useradd -s /bin/bash --uid $USER_UID --gid $USERNAME -m $USERNAME
+ fi
+fi
+
+# Add add sudo support for non-root user
+if [ "${USERNAME}" != "root" ] && [ "${EXISTING_NON_ROOT_USER}" != "${USERNAME}" ]; then
+ echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME
+ chmod 0440 /etc/sudoers.d/$USERNAME
+ EXISTING_NON_ROOT_USER="${USERNAME}"
+fi
+
+# ** Shell customization section **
+if [ "${USERNAME}" = "root" ]; then
+ USER_RC_PATH="/root"
+else
+ USER_RC_PATH="/home/${USERNAME}"
+fi
+
+# .bashrc/.zshrc snippet
+RC_SNIPPET="$(cat << EOF
+export USER=\$(whoami)
+
+export PATH=\$PATH:\$HOME/.local/bin
+EOF
+)"
+
+# code shim, it fallbacks to code-insiders if code is not available
+cat << 'EOF' > /usr/local/bin/code
+#!/bin/sh
+
+get_in_path_except_current() {
+ which -a "$1" | grep -v "$0" | head -1
+}
+
+code="$(get_in_path_except_current code)"
+
+if [ -n "$code" ]; then
+ exec "$code" "$@"
+elif [ "$(command -v code-insiders)" ]; then
+ exec code-insiders "$@"
+else
+ echo "code or code-insiders is not installed" >&2
+ exit 127
+fi
+EOF
+chmod +x /usr/local/bin/code
+
+# Codespaces themes - partly inspired by https://github.com/ohmyzsh/ohmyzsh/blob/master/themes/robbyrussell.zsh-theme
+CODESPACES_BASH="$(cat \
+<&1
+ echo -e "$(cat "${TEMPLATE}")\nDISABLE_AUTO_UPDATE=true\nDISABLE_UPDATE_PROMPT=true" > ${USER_RC_FILE}
+ if [ "${OH_MY}" = "bash" ]; then
+ sed -i -e 's/OSH_THEME=.*/OSH_THEME="codespaces"/g' ${USER_RC_FILE}
+ mkdir -p ${OH_MY_INSTALL_DIR}/custom/themes/codespaces
+ echo "${CODESPACES_BASH}" > ${OH_MY_INSTALL_DIR}/custom/themes/codespaces/codespaces.theme.sh
+ else
+ sed -i -e 's/ZSH_THEME=.*/ZSH_THEME="codespaces"/g' ${USER_RC_FILE}
+ mkdir -p ${OH_MY_INSTALL_DIR}/custom/themes
+ echo "${CODESPACES_ZSH}" > ${OH_MY_INSTALL_DIR}/custom/themes/codespaces.zsh-theme
+ fi
+ # Shrink git while still enabling updates
+ cd ${OH_MY_INSTALL_DIR}
+ git repack -a -d -f --depth=1 --window=1
+
+ if [ "${USERNAME}" != "root" ]; then
+ cp -rf ${USER_RC_FILE} ${OH_MY_INSTALL_DIR} /root
+ chown -R ${USERNAME}:${USERNAME} ${USER_RC_PATH}
+ fi
+}
+
+if [ "${RC_SNIPPET_ALREADY_ADDED}" != "true" ]; then
+ echo "${RC_SNIPPET}" >> /etc/bash.bashrc
+ RC_SNIPPET_ALREADY_ADDED="true"
+fi
+install-oh-my bash bashrc.osh-template https://github.com/ohmybash/oh-my-bash
+
+# Optionally install and configure zsh and Oh My Zsh!
+if [ "${INSTALL_ZSH}" = "true" ]; then
+ if ! type zsh > /dev/null 2>&1; then
+ apt-get-update-if-needed
+ apt-get install -y zsh
+ fi
+ if [ "${ZSH_ALREADY_INSTALLED}" != "true" ]; then
+ echo "${RC_SNIPPET}" >> /etc/zsh/zshrc
+ ZSH_ALREADY_INSTALLED="true"
+ fi
+ install-oh-my zsh zshrc.zsh-template https://github.com/ohmyzsh/ohmyzsh
+fi
+
+# Write marker file
+mkdir -p "$(dirname "${MARKER_FILE}")"
+echo -e "\
+ PACKAGES_ALREADY_INSTALLED=${PACKAGES_ALREADY_INSTALLED}\n\
+ LOCALE_ALREADY_SET=${LOCALE_ALREADY_SET}\n\
+ EXISTING_NON_ROOT_USER=${EXISTING_NON_ROOT_USER}\n\
+ RC_SNIPPET_ALREADY_ADDED=${RC_SNIPPET_ALREADY_ADDED}\n\
+ ZSH_ALREADY_INSTALLED=${ZSH_ALREADY_INSTALLED}" > "${MARKER_FILE}"
+
+echo "Done!"
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/node-debian.sh b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/node-debian.sh
new file mode 100644
index 0000000000000000000000000000000000000000..b8b3af9b0dad4cda4c0600690b63689672fb93c8
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/node-debian.sh
@@ -0,0 +1,119 @@
+#!/bin/bash
+#-------------------------------------------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
+#-------------------------------------------------------------------------------------------------------------
+#
+# Docs: https://github.com/microsoft/vscode-dev-containers/blob/master/script-library/docs/node.md
+#
+# Syntax: ./node-debian.sh [directory to install nvm] [node version to install (use "none" to skip)] [non-root user] [Update rc files flag]
+
+export NVM_DIR=${1:-"/usr/local/share/nvm"}
+export NODE_VERSION=${2:-"lts/*"}
+USERNAME=${3:-"automatic"}
+UPDATE_RC=${4:-"true"}
+
+set -e
+
+if [ "$(id -u)" -ne 0 ]; then
+ echo -e 'Script must be run as root. Use sudo, su, or add "USER root" to your Dockerfile before running this script.'
+ exit 1
+fi
+
+# Determine the appropriate non-root user
+if [ "${USERNAME}" = "auto" ] || [ "${USERNAME}" = "automatic" ]; then
+ USERNAME=""
+ POSSIBLE_USERS=("vscode" "node" "codespace" "$(awk -v val=1000 -F ":" '$3==val{print $1}' /etc/passwd)")
+ for CURRENT_USER in ${POSSIBLE_USERS[@]}; do
+ if id -u ${CURRENT_USER} > /dev/null 2>&1; then
+ USERNAME=${CURRENT_USER}
+ break
+ fi
+ done
+ if [ "${USERNAME}" = "" ]; then
+ USERNAME=root
+ fi
+elif [ "${USERNAME}" = "none" ] || ! id -u ${USERNAME} > /dev/null 2>&1; then
+ USERNAME=root
+fi
+
+if [ "${NODE_VERSION}" = "none" ]; then
+ export NODE_VERSION=
+fi
+
+# Ensure apt is in non-interactive to avoid prompts
+export DEBIAN_FRONTEND=noninteractive
+
+# Install curl, apt-transport-https, tar, or gpg if missing
+if ! dpkg -s apt-transport-https curl ca-certificates tar > /dev/null 2>&1 || ! type gpg > /dev/null 2>&1; then
+ if [ ! -d "/var/lib/apt/lists" ] || [ "$(ls /var/lib/apt/lists/ | wc -l)" = "0" ]; then
+ apt-get update
+ fi
+ apt-get -y install --no-install-recommends apt-transport-https curl ca-certificates tar gnupg2
+fi
+
+# Install yarn
+if type yarn > /dev/null 2>&1; then
+ echo "Yarn already installed."
+else
+ curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | (OUT=$(apt-key add - 2>&1) || echo $OUT)
+ echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list
+ apt-get update
+ apt-get -y install --no-install-recommends yarn
+fi
+
+# Install the specified node version if NVM directory already exists, then exit
+if [ -d "${NVM_DIR}" ]; then
+ echo "NVM already installed."
+ if [ "${NODE_VERSION}" != "" ]; then
+ su ${USERNAME} -c "source $NVM_DIR/nvm.sh && nvm install ${NODE_VERSION} && nvm clear-cache"
+ fi
+ exit 0
+fi
+
+
+# Run NVM installer as non-root if needed
+mkdir -p ${NVM_DIR}
+chown ${USERNAME} ${NVM_DIR}
+su ${USERNAME} -c "$(cat << EOF
+ set -e
+
+ # Do not update profile - we'll do this manually
+ export PROFILE=/dev/null
+
+ curl -so- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
+ source ${NVM_DIR}/nvm.sh
+ if [ "${NODE_VERSION}" != "" ]; then
+ nvm alias default ${NODE_VERSION}
+ fi
+ nvm clear-cache
+EOF
+)" 2>&1
+
+if [ "${UPDATE_RC}" = "true" ]; then
+ echo "Updating /etc/bash.bashrc and /etc/zsh/zshrc with NVM scripts..."
+(cat < /dev/null 2>&1; then
+ echo "Fixing permissions of \"\$NVM_DIR\"..."
+ sudoIf chown -R ${USERNAME}:root \$NVM_DIR
+ else
+ echo "Warning: NVM directory is not owned by ${USERNAME} and sudo is not installed. Unable to correct permissions."
+ fi
+fi
+[ -s "\$NVM_DIR/nvm.sh" ] && . "\$NVM_DIR/nvm.sh"
+[ -s "\$NVM_DIR/bash_completion" ] && . "\$NVM_DIR/bash_completion"
+EOF
+) | tee -a /etc/bash.bashrc >> /etc/zsh/zshrc
+fi
+
+echo "Done!"
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/python-debian.sh b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/python-debian.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3f96a6dbb72b0839bb4a2f0ee39e20aadcf328f4
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.devcontainer/library-scripts/python-debian.sh
@@ -0,0 +1,134 @@
+#!/usr/bin/env bash
+#-------------------------------------------------------------------------------------------------------------
+# Copyright (c) Microsoft Corporation. All rights reserved.
+# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.
+#-------------------------------------------------------------------------------------------------------------
+#
+# Docs: https://github.com/microsoft/vscode-dev-containers/blob/master/script-library/docs/python.md
+#
+# Syntax: ./python-debian.sh [Python Version] [Python intall path] [PIPX_HOME] [non-root user] [Update rc files flag] [install tools]
+
+PYTHON_VERSION=${1:-"3.8.3"}
+PYTHON_INSTALL_PATH=${2:-"/usr/local/python${PYTHON_VERSION}"}
+export PIPX_HOME=${3:-"/usr/local/py-utils"}
+USERNAME=${4:-"automatic"}
+UPDATE_RC=${5:-"true"}
+INSTALL_PYTHON_TOOLS=${6:-"true"}
+
+set -e
+
+if [ "$(id -u)" -ne 0 ]; then
+ echo -e 'Script must be run as root. Use sudo, su, or add "USER root" to your Dockerfile before running this script.'
+ exit 1
+fi
+
+# Determine the appropriate non-root user
+if [ "${USERNAME}" = "auto" ] || [ "${USERNAME}" = "automatic" ]; then
+ USERNAME=""
+ POSSIBLE_USERS=("vscode" "node" "codespace" "$(awk -v val=1000 -F ":" '$3==val{print $1}' /etc/passwd)")
+ for CURRENT_USER in ${POSSIBLE_USERS[@]}; do
+ if id -u ${CURRENT_USER} > /dev/null 2>&1; then
+ USERNAME=${CURRENT_USER}
+ break
+ fi
+ done
+ if [ "${USERNAME}" = "" ]; then
+ USERNAME=root
+ fi
+elif [ "${USERNAME}" = "none" ] || ! id -u ${USERNAME} > /dev/null 2>&1; then
+ USERNAME=root
+fi
+
+function updaterc() {
+ if [ "${UPDATE_RC}" = "true" ]; then
+ echo "Updating /etc/bash.bashrc and /etc/zsh/zshrc..."
+ echo -e "$1" | tee -a /etc/bash.bashrc >> /etc/zsh/zshrc
+ fi
+}
+
+export DEBIAN_FRONTEND=noninteractive
+
+# Install python from source if needed
+if [ "${PYTHON_VERSION}" != "none" ]; then
+
+ if [ -d "${PYTHON_INSTALL_PATH}" ]; then
+ echo "Path ${PYTHON_INSTALL_PATH} already exists. Assuming Python already installed."
+ else
+ echo "Building Python ${PYTHON_VERSION} from source..."
+ # Install prereqs if missing
+ PREREQ_PKGS="curl ca-certificates tar make build-essential libffi-dev \
+ libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
+ libncurses5-dev libncursesw5-dev xz-utils tk-dev"
+ if ! dpkg -s ${PREREQ_PKGS} > /dev/null 2>&1; then
+ if [ ! -d "/var/lib/apt/lists" ] || [ "$(ls /var/lib/apt/lists/ | wc -l)" = "0" ]; then
+ apt-get update
+ fi
+ apt-get -y install --no-install-recommends ${PREREQ_PKGS}
+ fi
+
+ # Download and build from src
+ mkdir -p /tmp/python-src "${PYTHON_INSTALL_PATH}"
+ cd /tmp/python-src
+ curl -sSL -o /tmp/python-dl.tgz "https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tgz"
+ tar -xzf /tmp/python-dl.tgz -C "/tmp/python-src" --strip-components=1
+ ./configure --prefix="${PYTHON_INSTALL_PATH}" --enable-optimizations --with-ensurepip=install
+ make -j 8
+ make install
+ rm -rf /tmp/python-dl.tgz /tmp/python-src
+ cd /tmp
+ chown -R ${USERNAME} "${PYTHON_INSTALL_PATH}"
+ ln -s ${PYTHON_INSTALL_PATH}/bin/python3 ${PYTHON_INSTALL_PATH}/bin/python
+ ln -s ${PYTHON_INSTALL_PATH}/bin/pip3 ${PYTHON_INSTALL_PATH}/bin/pip
+ ln -s ${PYTHON_INSTALL_PATH}/bin/idle3 ${PYTHON_INSTALL_PATH}/bin/idle
+ ln -s ${PYTHON_INSTALL_PATH}/bin/pydoc3 ${PYTHON_INSTALL_PATH}/bin/pydoc
+ ln -s ${PYTHON_INSTALL_PATH}/bin/python3-config ${PYTHON_INSTALL_PATH}/bin/python-config
+ updaterc "export PATH=${PYTHON_INSTALL_PATH}/bin:\${PATH}"
+ fi
+fi
+
+# If not installing python tools, exit
+if [ "${INSTALL_PYTHON_TOOLS}" != "true" ]; then
+ echo "Done!"
+ exit 0;
+fi
+
+DEFAULT_UTILS="\
+ pylint \
+ flake8 \
+ autopep8 \
+ black \
+ yapf \
+ mypy \
+ pydocstyle \
+ pycodestyle \
+ bandit \
+ pipenv \
+ virtualenv"
+
+
+export PIPX_BIN_DIR=${PIPX_HOME}/bin
+export PATH=${PYTHON_INSTALL_PATH}/bin:${PIPX_BIN_DIR}:${PATH}
+
+# Update pip
+echo "Updating pip..."
+python3 -m pip install --no-cache-dir --upgrade pip
+
+# Install tools
+mkdir -p ${PIPX_BIN_DIR}
+chown -R ${USERNAME} ${PIPX_HOME} ${PIPX_BIN_DIR}
+su ${USERNAME} -c "$(cat << EOF
+ set -e
+ echo "Installing Python tools..."
+ export PIPX_HOME=${PIPX_HOME}
+ export PIPX_BIN_DIR=${PIPX_BIN_DIR}
+ export PYTHONUSERBASE=/tmp/pip-tmp
+ export PIP_CACHE_DIR=/tmp/pip-tmp/cache
+ export PATH=${PATH}
+ pip3 install --disable-pip-version-check --no-warn-script-location --no-cache-dir --user pipx
+ /tmp/pip-tmp/bin/pipx install --pip-args=--no-cache-dir pipx
+ echo "${DEFAULT_UTILS}" | xargs -n 1 /tmp/pip-tmp/bin/pipx install --system-site-packages --pip-args '--no-cache-dir --force-reinstall'
+ chown -R ${USERNAME} ${PIPX_HOME}
+ rm -rf /tmp/pip-tmp
+EOF
+)"
+updaterc "export PIPX_HOME=${PIPX_HOME}\nexport PIPX_BIN_DIR=${PIPX_BIN_DIR}\nexport PATH=\${PATH}:\${PIPX_BIN_DIR}"
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.gitattributes b/tasks/tasksmith-ca08ab4caec6/tests/source/.gitattributes
new file mode 100644
index 0000000000000000000000000000000000000000..5f626113be937577844b38c0836b30239684191c
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.gitattributes
@@ -0,0 +1,2 @@
+calendars/_version.py export-subst
+exchange_calendars/_version.py export-subst
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.github/dependabot.yml b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/dependabot.yml
new file mode 100644
index 0000000000000000000000000000000000000000..0ee0601d391e0e4556f91c2f4dd2cc6595b436a3
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/dependabot.yml
@@ -0,0 +1,16 @@
+# To get started with Dependabot version updates, you'll need to specify which
+# package ecosystems to update and where the package manifests are located.
+# Please see the documentation for all configuration options:
+# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
+
+version: 2
+updates:
+ - package-ecosystem: "github-actions" # See documentation for possible values
+ directory: "/" # Location of package manifests
+ schedule:
+ interval: "daily"
+ # reverted because dependabot can't ignore files
+ # - package-ecosystem: "pip" # See documentation for possible values
+ # directory: "/etc" # Location of package manifests
+ # schedule:
+ # interval: "daily"
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.github/pull_request_template.md b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/pull_request_template.md
new file mode 100644
index 0000000000000000000000000000000000000000..a77479ac45666a33a1dac06ed31f121b76bfd9cb
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/pull_request_template.md
@@ -0,0 +1,22 @@
+**Workflow to add a new Exchange Calendar**
+
+It's recommended that whilst working through the process reference be made to existing calendar and test classes.
+
+- [ ] Add calendar module `exchange_calendars/exchange_calendar_{Exchange MIC}.py`. Module should contain a subclass of the abstract base class `ExchangeCalendar` (in `exchange_calendars/exchange_calendar.py`).
+ - [ ] Name subclass `{Exchange MIC}ExchangeCalendar`.
+ - [ ] Override methods and properties as required, being guided by ExchangeCalendar documentation and in-code comments. All abstract properties must be overriden.
+ - [ ] Include references / links for holidays and timings (either to class documentation or as comments).
+- [ ] Import calendar class to `exchange_calendars/calendar_utils.py` and add class to `_default_calendar_factories`.
+- [ ] Add calendar test module `tests/test_{Exchange MIC}_calendar.py` Module should contain a subclass of the test base class `ExchangeCalendarTestBase` (in `tests/test_exchange_calendars.py`).
+ - [ ] Name subclass `Test{Exchange MIC}Calendar`.
+ - [ ] Override fixtures as required, being guided by ExchangeCalendarTestBase documentation and in-code comments. The `calendar_cls` and `max_session_hours` fixtures must be overriden.
+- [ ] Add a .csv file containing expected timings to `tests/resources/{Exchange MIC}.csv`. This file be generated by executing `python etc/make_exchange_calendar_test_csv.py {Exchange MIC}`. See script's documentation.
+- [ ] Add new exchange to Calendars table of README.md.
+- [ ] PR it!
+
+**Workflow to modify an existing Exchange Calendar**
+
+- [ ] Modify calendar class as required.
+- [ ] Modify the test resources file (e.g `tests/resources/{Exchange MIC}.csv`), either manually or by executing `python etc/make_exchange_calendar_test_csv.py {Exchange MIC}`.
+- [ ] Check if any of the fixtures in `tests/test_{Exchange MIC}_calendar.py` need updating to reflect your changes.
+- [ ] Add references to any new/modified holidays in `exchange_calendars/exchange_calendar_{Exchange MIC}.py`.
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.github/release-drafter-config.yml b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/release-drafter-config.yml
new file mode 100644
index 0000000000000000000000000000000000000000..6a8daf15d5777feb7e55ab946a63669d3e7726d2
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/release-drafter-config.yml
@@ -0,0 +1,48 @@
+name-template: '$NEXT_PATCH_VERSION 🌈'
+tag-template: '$NEXT_PATCH_VERSION'
+categories:
+ - title: 'API Changes'
+ labels:
+ - 'api'
+ - title: 'Benchmark Changes'
+ labels:
+ - 'bench'
+ - title: 'Build Changes'
+ labels:
+ - 'build'
+ - title: 'Bug Fixes'
+ labels:
+ - 'bug'
+ - title: 'Calendar Updates'
+ labels:
+ - 'calendar update'
+ - title: 'Deprecation'
+ labels:
+ - 'deprecation'
+ - title: 'Development Enhancements'
+ labels:
+ - 'development'
+ - title: 'Documentation Updates'
+ labels:
+ - 'documentation'
+ - title: 'Enhancements'
+ labels:
+ - 'enhancement'
+ - title: 'Maintenance'
+ labels:
+ - 'maintenance'
+ - title: 'Reverts'
+ labels:
+ - 'revert'
+ - title: 'Style Changes'
+ labels:
+ - 'style'
+ - title: 'Test Changes'
+ labels:
+ - 'test'
+ - title: 'Release Changes'
+ labels:
+ - 'release'
+template: |
+ # What’s Changed
+ $CHANGES
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/benchmark.yml b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/benchmark.yml
new file mode 100644
index 0000000000000000000000000000000000000000..580d0beaa5f6f8dff8c6aee6081c85d51a896ab5
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/benchmark.yml
@@ -0,0 +1,41 @@
+name: Benchmark
+
+on:
+ push:
+ branches:
+ - master
+ pull_request:
+ branches:
+ - master
+jobs:
+ benchmark:
+ name: Performance regression check
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ - name: Install dependencies
+ run: |
+ pip install -e .[dev] -c etc/requirements_dev.txt
+ - name: Run benchmark
+ run: |
+ pytest etc/bench.py --benchmark-json output.json
+ - name: Download previous benchmark data
+ uses: actions/cache@v4.0.0
+ with:
+ path: ./cache
+ key: ${{ runner.os }}-benchmark
+ - name: Store benchmark result
+ uses: rhysd/github-action-benchmark@v1
+ with:
+ tool: 'pytest'
+ output-file-path: output.json
+ external-data-json-path: ./cache/benchmark-data.json
+ fail-on-alert: true
+ # GitHub API token to make a commit comment
+ github-token: ${{ secrets.GITHUB_TOKEN }}
+ # Enable alert commit comment
+ comment-on-alert: true
+ alert-threshold: "150%"
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/labeler.yml b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/labeler.yml
new file mode 100644
index 0000000000000000000000000000000000000000..99db967b383bea61c19624ecc8b5eddb97a50c0e
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/labeler.yml
@@ -0,0 +1,13 @@
+name: "Pull Request Labeler"
+on:
+ pull_request_target:
+ types: [opened, synchronize, reopened, edited]
+
+jobs:
+ pr-labeler:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Label the PR
+ uses: gerrymanoim/pr-prefix-labeler@v3
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/main.yml b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/main.yml
new file mode 100644
index 0000000000000000000000000000000000000000..8c3fc713c54139acc94b8b9b79aa66d69ee524cb
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/main.yml
@@ -0,0 +1,43 @@
+name: CI
+
+on:
+ push:
+ branches:
+ - master
+ pull_request:
+ branches:
+ - master
+
+jobs:
+ build-and-test:
+
+ runs-on: ${{ matrix.os }}
+ strategy:
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ python-version: ["3.9", "3.11"]
+ include:
+ - python-version: "3.9"
+ requirements_file: requirements_dev.txt
+ - python-version: "3.11"
+ requirements_file: requirements_minpandas.txt
+
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python-version }}
+ cache: 'pip'
+ cache-dependency-path: 'etc/${{matrix.requirements_file}}'
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install -r etc/${{matrix.requirements_file}}
+ pip install -e .
+ - name: Lint with flake8
+ run: |
+ flake8
+ - name: Test with pytest
+ run: |
+ pytest tests -n auto --dist loadscope
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/master-merge.yml b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/master-merge.yml
new file mode 100644
index 0000000000000000000000000000000000000000..858ed4ff76dc7cdedd1f5cf76c04e35015772511
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/master-merge.yml
@@ -0,0 +1,18 @@
+name: On Master Merge
+
+on:
+ push:
+ branches:
+ - master
+
+jobs:
+ draft-release-publish:
+ name: Draft a new release
+ runs-on: ubuntu-latest
+ steps:
+ # Drafts your next Release notes as Pull Requests are merged into "master"
+ - uses: release-drafter/release-drafter@v6
+ with:
+ config-name: release-drafter-config.yml
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/release.yml b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/release.yml
new file mode 100644
index 0000000000000000000000000000000000000000..6879f95255e7a6f96596f921e6fb8dceda283b02
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.github/workflows/release.yml
@@ -0,0 +1,61 @@
+name: Publish Python 🐍 distributions 📦 to PyPI
+on:
+ release:
+ types: [published]
+
+jobs:
+ build-n-publish:
+ name: Build and publish Python 🐍 distributions 📦 to TestPyPI
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up Python 3.11
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+
+ - name: Install build dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install build
+
+ - name: Build package
+ run: python -m build
+
+ - name: Publish distribution 📦 to Test PyPI
+ uses: pypa/gh-action-pypi-publish@release/v1
+ with:
+ user: __token__
+ password: ${{ secrets.test_pypi_password }}
+ repository-url: https://test.pypi.org/legacy/
+ skip-existing: true
+
+ - name: Install from testpypi and import
+ shell: bash
+ run: |
+ sleep 5
+ while [ "${{ github.ref_name }}" != $(pip index versions -i https://test.pypi.org/simple --pre exchange_calendars | cut -d'(' -f2 | cut -d')' -f1 | sed 1q) ];\
+ do echo "waiting for package to appear in test index, sleeping 5s"; sleep 5s; echo "woken up"; done
+ pip install --index-url https://test.pypi.org/simple exchange_calendars==${{ github.ref_name }} --no-deps
+ pip install -r etc/requirements.txt
+ python -c 'import exchange_calendars;print(exchange_calendars.__version__)'
+
+ - name: Clean pip
+ run: |
+ pip uninstall -y exchange_calendars
+ pip cache purge
+
+ - name: Publish distribution 📦 to PyPI
+ uses: pypa/gh-action-pypi-publish@release/v1
+ with:
+ user: __token__
+ password: ${{ secrets.pypi_password }}
+
+ - name: Install and import
+ shell: bash
+ run: |
+ sleep 5
+ while [ "${{ github.ref_name }}" != $(pip index versions -i https://pypi.org/simple --pre exchange_calendars | cut -d'(' -f2 | cut -d')' -f1 | sed 1q) ];\
+ do echo "waiting for package to appear in index, sleeping 5s"; sleep 5s; echo "woken up"; done
+ pip install --index-url https://pypi.org/simple exchange_calendars==${{ github.ref_name }}
+ python -c 'import exchange_calendars;print(exchange_calendars.__version__)'
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.gitignore b/tasks/tasksmith-ca08ab4caec6/tests/source/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..ad6661106ed936ecc6f309b9df9a8af89d9dac57
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.gitignore
@@ -0,0 +1,150 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+_version.py
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+*.py,cover
+.hypothesis/
+.pytest_cache/
+cover/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+.pybuilder/
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+# For a library or package, you might want to ignore these files since the code is
+# intended to run in multiple environments; otherwise, check them in:
+# .python-version
+
+# pipenv
+# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+# However, in case of collaboration, if having platform-specific dependencies or dependencies
+# having no cross-platform support, pipenv may install dependencies that don't work, or not
+# install all needed dependencies.
+#Pipfile.lock
+
+# PEP 582; used by e.g. github.com/David-OConnor/pyflow
+__pypackages__/
+
+# Celery stuff
+celerybeat-schedule
+celerybeat.pid
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv*
+env/
+venv*/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# pytype static type analyzer
+.pytype/
+
+# Cython debug symbols
+cython_debug/
+
+.ipynb_checkpoints/
+
+etc/lunar-ecliptic-longitude/*
+etc/solar-ecliptic-longitude/*
+
+# Vscode
+.vscode
+
+# not intended for inclusion to public project
+/_local
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/.pre-commit-config.yaml b/tasks/tasksmith-ca08ab4caec6/tests/source/.pre-commit-config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..9e1c16f14d941233ec96625d903a1404604f344e
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/.pre-commit-config.yaml
@@ -0,0 +1,16 @@
+repos:
+- repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v4.2.0
+ hooks:
+ - id: check-yaml
+ - id: end-of-file-fixer
+ - id: trailing-whitespace
+- repo: https://github.com/pycqa/flake8
+ rev: 6.1.0
+ hooks:
+ - id: flake8
+- repo: https://github.com/psf/black
+ rev: 23.7.0
+ hooks:
+ - id: black
+ language_version: python
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/Dockerfile b/tasks/tasksmith-ca08ab4caec6/tests/source/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..f1e89412bdb693174057f3408eeee8e62a9f75aa
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/Dockerfile
@@ -0,0 +1,8 @@
+FROM python:3.12-slim
+WORKDIR /workspace
+RUN python -m pip install --no-cache-dir numpy==1.26.4 pandas==2.2.0 pyluach==2.2.0 python-dateutil==2.8.2 pytz==2024.1 six==1.16.0 toolz==0.12.1 tzdata==2024.1 korean-lunar-calendar==0.3.1 pytest==8.0.0 'setuptools>=43.0.0' 'setuptools_scm[toml]>=6.2' wheel==0.42.0
+COPY . /workspace
+RUN SETUPTOOLS_SCM_PRETEND_VERSION=0.0.1 python -m pip install --no-cache-dir --no-deps --no-build-isolation -e .
+RUN rm -rf /workspace/.git /root/.cache/pip
+ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
+ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/LICENSE b/tasks/tasksmith-ca08ab4caec6/tests/source/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..a49122d9e24358e10888c8ff540a1c3348dcc11d
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2018 Quantopian, Inc.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/MANIFEST.in b/tasks/tasksmith-ca08ab4caec6/tests/source/MANIFEST.in
new file mode 100644
index 0000000000000000000000000000000000000000..fc96be859608915652aef6f676976a20bf25f7a4
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/MANIFEST.in
@@ -0,0 +1,2 @@
+recursive-exclude .devcontainer *
+recursive-exclude .github *
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/README.md b/tasks/tasksmith-ca08ab4caec6/tests/source/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..18e2aa96ec2af9334c1745a6c020ea52ea842f05
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/README.md
@@ -0,0 +1,332 @@
+# exchange_calendars
+
+[](https://pypi.org/project/exchange-calendars/)   [](https://github.com/psf/black)
+
+A Python library for defining and querying calendars for security exchanges.
+
+Calendars for more than [50 exchanges](#Calendars) available out-the-box! If you still can't find the calendar you're looking for, [create a new one](#How-can-I-create-a-new-calendar)!
+
+## Installation
+
+```bash
+$ pip install exchange_calendars
+```
+
+## Quick Start
+
+```python
+import exchange_calendars as xcals
+```
+
+Get a list of available calendars:
+
+```python
+>>> xcals.get_calendar_names(include_aliases=False)[5:10]
+['CMES', 'IEPA', 'XAMS', 'XASX', 'XBKK']
+```
+
+Get a calendar:
+
+```python
+>>> xnys = xcals.get_calendar("XNYS") # New York Stock Exchange
+>>> xhkg = xcals.get_calendar("XHKG") # Hong Kong Stock Exchange
+```
+Query the schedule:
+
+```python
+>>> xhkg.schedule.loc["2021-12-29":"2022-01-04"]
+```
+
+
+
+
+
+
+
+
+
+
open
break_start
break_end
close
2021-12-29
2021-12-29 01:30:00+00:00
2021-12-29 04:00:00+00:00
2021-12-29 05:00:00+00:00
2021-12-29 08:00:00+00:00
2021-12-30
2021-12-30 01:30:00+00:00
2021-12-30 04:00:00+00:00
2021-12-30 05:00:00+00:00
2021-12-30 08:00:00+00:00
2021-12-31
2021-12-31 01:30:00+00:00
NaT
NaT
2021-12-31 04:00:00+00:00
2022-01-03
2022-01-03 01:30:00+00:00
2022-01-03 04:00:00+00:00
2022-01-03 05:00:00+00:00
2022-01-03 08:00:00+00:00
2022-01-04
2022-01-04 01:30:00+00:00
2022-01-04 04:00:00+00:00
2022-01-04 05:00:00+00:00
2022-01-04 08:00:00+00:00
+
+
+### Working with **sessions**
+```python
+>>> xnys.is_session("2022-01-01")
+False
+
+>>> xnys.sessions_in_range("2022-01-01", "2022-01-11")
+DatetimeIndex(['2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06',
+ '2022-01-07', '2022-01-10', '2022-01-11'],
+ dtype='datetime64[ns]', freq='C')
+
+>>> xnys.sessions_window("2022-01-03", 7)
+DatetimeIndex(['2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06',
+ '2022-01-07', '2022-01-10', '2022-01-11'],
+ dtype='datetime64[ns]', freq='C')
+
+>>> xnys.date_to_session("2022-01-01", direction="next")
+Timestamp('2022-01-03 00:00:00', freq='C')
+
+>>> xnys.previous_session("2022-01-11")
+Timestamp('2022-01-10 00:00:00', freq='C')
+
+>>> xhkg.trading_index(
+... "2021-12-30", "2021-12-31", period="90min", force=True
+... )
+IntervalIndex([[2021-12-30 01:30:00, 2021-12-30 03:00:00), [2021-12-30 03:00:00, 2021-12-30 04:00:00), [2021-12-30 05:00:00, 2021-12-30 06:30:00), [2021-12-30 06:30:00, 2021-12-30 08:00:00), [2021-12-31 01:30:00, 2021-12-31 03:00:00), [2021-12-31 03:00:00, 2021-12-31 04:00:00)], dtype='interval[datetime64[ns, UTC], left]')
+```
+See the [sessions tutorial](docs/tutorials/sessions.ipynb) for a deeper dive into sessions.
+
+### Working with **minutes**
+```python
+>>> xhkg.session_minutes("2022-01-03")
+DatetimeIndex(['2022-01-03 01:30:00+00:00', '2022-01-03 01:31:00+00:00',
+ '2022-01-03 01:32:00+00:00', '2022-01-03 01:33:00+00:00',
+ '2022-01-03 01:34:00+00:00', '2022-01-03 01:35:00+00:00',
+ '2022-01-03 01:36:00+00:00', '2022-01-03 01:37:00+00:00',
+ '2022-01-03 01:38:00+00:00', '2022-01-03 01:39:00+00:00',
+ ...
+ '2022-01-03 07:50:00+00:00', '2022-01-03 07:51:00+00:00',
+ '2022-01-03 07:52:00+00:00', '2022-01-03 07:53:00+00:00',
+ '2022-01-03 07:54:00+00:00', '2022-01-03 07:55:00+00:00',
+ '2022-01-03 07:56:00+00:00', '2022-01-03 07:57:00+00:00',
+ '2022-01-03 07:58:00+00:00', '2022-01-03 07:59:00+00:00'],
+ dtype='datetime64[ns, UTC]', length=330, freq=None)
+
+>>> mins = [ "2022-01-03 " + tm for tm in ["01:29", "01:30", "04:20", "07:59", "08:00"] ]
+>>> [ xhkg.is_trading_minute(minute) for minute in mins ]
+[False, True, False, True, False] # by default minutes are closed on the left side
+
+>>> xhkg.is_break_minute("2022-01-03 04:20")
+True
+
+>>> xhkg.previous_close("2022-01-03 08:10")
+Timestamp('2022-01-03 08:00:00+0000', tz='UTC')
+
+>>> xhkg.previous_minute("2022-01-03 08:10")
+Timestamp('2022-01-03 07:59:00+0000', tz='UTC')
+```
+Check out the [minutes tutorial](docs/tutorials/minutes.ipynb) for a deeper dive that includes an explanation of the concept of 'minutes' and how the "side" option determines which minutes are treated as trading minutes.
+
+## Tutorials
+* [sessions.ipynb](docs/tutorials/sessions.ipynb) - all things [sessions](#Working-with-sessions).
+* [minutes.ipynb](docs/tutorials/minutes.ipynb) - all things [minutes](#Working-with-minutes). Don't miss this one!
+* [calendar_properties.ipynb](docs/tutorials/calendar_properties.ipynb) - calendar constrution and a walk through the schedule and all other calendar properties.
+* [calendar_methods.ipynb](docs/tutorials/calendar_methods.ipynb) - a walk through all the methods available to interrogate a calendar.
+* [trading_index.ipynb](docs/tutorials/trading_index.ipynb) - a method that warrants a tutorial all of its own.
+
+Hopefully you'll find that `exchange_calendars` has the method you need to get the information you want. If it doesn't, either [PR](https://github.com/gerrymanoim/exchange_calendars/pulls) it or [raise an issue](https://github.com/gerrymanoim/exchange_calendars/issues) and let us know!
+
+## Command Line Usage
+Print a unix-cal like calendar straight from the command line (holidays are indicated by brackets)...
+
+```bash
+ecal XNYS 2020
+```
+ 2020
+ January February March
+ Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
+ [ 1] 2 3 [ 4] [ 1]
+ [ 5] 6 7 8 9 10 [11] [ 2] 3 4 5 6 7 [ 8] [ 1] 2 3 4 5 6 [ 7]
+ [12] 13 14 15 16 17 [18] [ 9] 10 11 12 13 14 [15] [ 8] 9 10 11 12 13 [14]
+ [19][20] 21 22 23 24 [25] [16][17] 18 19 20 21 [22] [15] 16 17 18 19 20 [21]
+ [26] 27 28 29 30 31 [23] 24 25 26 27 28 [29] [22] 23 24 25 26 27 [28]
+ [29] 30 31
+
+ April May June
+ Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
+ 1 2 3 [ 4] 1 [ 2] 1 2 3 4 5 [ 6]
+ [ 5] 6 7 8 9 [10][11] [ 3] 4 5 6 7 8 [ 9] [ 7] 8 9 10 11 12 [13]
+ [12] 13 14 15 16 17 [18] [10] 11 12 13 14 15 [16] [14] 15 16 17 18 19 [20]
+ [19] 20 21 22 23 24 [25] [17] 18 19 20 21 22 [23] [21] 22 23 24 25 26 [27]
+ [26] 27 28 29 30 [24][25] 26 27 28 29 [30] [28] 29 30
+ [31]
+
+ July August September
+ Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
+ 1 2 [ 3][ 4] [ 1] 1 2 3 4 [ 5]
+ [ 5] 6 7 8 9 10 [11] [ 2] 3 4 5 6 7 [ 8] [ 6][ 7] 8 9 10 11 [12]
+ [12] 13 14 15 16 17 [18] [ 9] 10 11 12 13 14 [15] [13] 14 15 16 17 18 [19]
+ [19] 20 21 22 23 24 [25] [16] 17 18 19 20 21 [22] [20] 21 22 23 24 25 [26]
+ [26] 27 28 29 30 31 [23] 24 25 26 27 28 [29] [27] 28 29 30
+ [30] 31
+
+ October November December
+ Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
+ 1 2 [ 3] 1 2 3 4 [ 5]
+ [ 4] 5 6 7 8 9 [10] [ 1] 2 3 4 5 6 [ 7] [ 6] 7 8 9 10 11 [12]
+ [11] 12 13 14 15 16 [17] [ 8] 9 10 11 12 13 [14] [13] 14 15 16 17 18 [19]
+ [18] 19 20 21 22 23 [24] [15] 16 17 18 19 20 [21] [20] 21 22 23 24 [25][26]
+ [25] 26 27 28 29 30 [31] [22] 23 24 25 [26] 27 [28] [27] 28 29 30 31
+ [29] 30
+
+```bash
+ecal XNYS 1 2020
+```
+
+ January 2020
+ Su Mo Tu We Th Fr Sa
+ [ 1] 2 3 [ 4]
+ [ 5] 6 7 8 9 10 [11]
+ [12] 13 14 15 16 17 [18]
+ [19][20] 21 22 23 24 [25]
+ [26] 27 28 29 30 31
+
+## Frequently Asked Questions
+
+### **How can I create a new calendar?**
+
+First off, make sure the calendar you're after hasn't already been defined; exchange calendars comes with over [50 pre-defined calendars](#Calendars), including major security exchanges.
+
+If you can't find what you're after, a custom calendar can be created as a subclass of [ExchangeCalendar](exchange_calendars/exchange_calendar.py). [This workflow](.github/pull_request_template.md) describes the process to add a new calendar to `exchange_calendars`. Just follow the relevant parts.
+
+To access the new calendar via `get_calendar` call either `xcals.register_calendar` or `xcals.register_calendar_type` to register, respectively, a specific calendar instance or a calendar factory (i.e. the subclass).
+
+### **Can I contribute a new calendar to exchange calendars?**
+
+Yes please! The workflow can be found [here](.github/pull_request_template.md).
+
+### **`` is missing a holiday, has a wrong time, should have a break etc...**
+
+**All** of the exchange calendars are maintained by user contributions. If a calendar you care about needs revising, please open a [PR](https://github.com/gerrymanoim/exchange_calendars/pulls) - that's how this thing works! (Never contributed to a project before and it all seems a bit daunting? Check [this out](https://github.com/firstcontributions/first-contributions/blob/main/README.md) and don't look back!)
+
+You'll find the workflow to modify an existing calendar [here](.github/pull_request_template.md).
+
+### **What times are considered open and closed?**
+
+`exchange_calendars` attempts to be broadly useful by considering an exchange to be open only during periods of regular trading. During any pre-trading, post-trading or auction period the exchange is treated as closed. An exchange is also treated as closed during any observed lunch break.
+
+See the [minutes tutorial](docs/tutorials/minutes.ipynb) for a detailed explanation of which minutes an exchange is considered open over. If you previously used `trading_calendars`, or `exchange_calendars` prior to release 3.4, then this is the place to look for answers to questions of how the definition of trading minutes has changed over time (and is now stable and flexible!).
+
+## Calendars
+
+| Exchange | ISO Code | Country | Version Added | Exchange Website (English) |
+|---------------------------------|----------| -------------- |---------------| ------------------------------------------------------------ |
+| New York Stock Exchange | XNYS | USA | 1.0 | https://www.nyse.com/index |
+| CBOE Futures | XCBF | USA | 1.0 | https://markets.cboe.com/us/futures/overview/ |
+| Chicago Mercantile Exchange | CMES | USA | 1.0 | https://www.cmegroup.com/ |
+| ICE US | IEPA | USA | 1.0 | https://www.theice.com/index |
+| Toronto Stock Exchange | XTSE | Canada | 1.0 | https://www.tsx.com/ |
+| BMF Bovespa | BVMF | Brazil | 1.0 | http://www.b3.com.br/en_us/ |
+| London Stock Exchange | XLON | England | 1.0 | https://www.londonstockexchange.com/ |
+| Euronext Amsterdam | XAMS | Netherlands | 1.2 | https://www.euronext.com/en/regulation/amsterdam |
+| Euronext Brussels | XBRU | Belgium | 1.2 | https://www.euronext.com/en/regulation/brussels |
+| Euronext Lisbon | XLIS | Portugal | 1.2 | https://www.euronext.com/en/regulation/lisbon |
+| Euronext Paris | XPAR | France | 1.2 | https://www.euronext.com/en/regulation/paris |
+| Frankfurt Stock Exchange | XFRA | Germany | 1.2 | http://en.boerse-frankfurt.de/ |
+| SIX Swiss Exchange | XSWX | Switzerland | 1.2 | https://www.six-group.com/en/home.html |
+| Tokyo Stock Exchange | XTKS | Japan | 1.2 | https://www.jpx.co.jp/english/ |
+| Australian Securities Exchange | XASX | Australia | 1.3 | https://www.asx.com.au/ |
+| Bolsa de Madrid | XMAD | Spain | 1.3 | https://www.bolsamadrid.es |
+| Borsa Italiana | XMIL | Italy | 1.3 | https://www.borsaitaliana.it |
+| New Zealand Exchange | XNZE | New Zealand | 1.3 | https://www.nzx.com/ |
+| Wiener Borse | XWBO | Austria | 1.3 | https://www.wienerborse.at/en/ |
+| Hong Kong Stock Exchange | XHKG | Hong Kong | 1.3 | https://www.hkex.com.hk/?sc_lang=en |
+| Copenhagen Stock Exchange | XCSE | Denmark | 1.4 | http://www.nasdaqomxnordic.com/ |
+| Helsinki Stock Exchange | XHEL | Finland | 1.4 | http://www.nasdaqomxnordic.com/ |
+| Stockholm Stock Exchange | XSTO | Sweden | 1.4 | http://www.nasdaqomxnordic.com/ |
+| Oslo Stock Exchange | XOSL | Norway | 1.4 | https://www.oslobors.no/ob_eng/ |
+| Irish Stock Exchange | XDUB | Ireland | 1.4 | http://www.ise.ie/ |
+| Bombay Stock Exchange | XBOM | India | 1.5 | https://www.bseindia.com |
+| Singapore Exchange | XSES | Singapore | 1.5 | https://www.sgx.com |
+| Shanghai Stock Exchange | XSHG | China | 1.5 | http://english.sse.com.cn |
+| Korea Exchange | XKRX | South Korea | 1.6 | http://global.krx.co.kr |
+| Iceland Stock Exchange | XICE | Iceland | 1.7 | http://www.nasdaqomxnordic.com/ |
+| Poland Stock Exchange | XWAR | Poland | 1.9 | http://www.gpw.pl |
+| Santiago Stock Exchange | XSGO | Chile | 1.9 | https://www.bolsadesantiago.com/ |
+| Colombia Securities Exchange | XBOG | Colombia | 1.9 | https://www.bvc.com.co/nueva/https://www.bvc.com.co/nueva/ |
+| Mexican Stock Exchange | XMEX | Mexico | 1.9 | https://www.bmv.com.mx |
+| Lima Stock Exchange | XLIM | Peru | 1.9 | https://www.bvl.com.pe |
+| Prague Stock Exchange | XPRA | Czech Republic | 1.9 | https://www.pse.cz/en/ |
+| Budapest Stock Exchange | XBUD | Hungary | 1.10 | https://bse.hu/ |
+| Athens Stock Exchange | ASEX | Greece | 1.10 | http://www.helex.gr/ |
+| Istanbul Stock Exchange | XIST | Turkey | 1.10 | https://www.borsaistanbul.com/en/ |
+| Johannesburg Stock Exchange | XJSE | South Africa | 1.10 | https://www.jse.co.za/z |
+| Malaysia Stock Exchange | XKLS | Malaysia | 1.11 | http://www.bursamalaysia.com/market/ |
+| Moscow Exchange | XMOS | Russia | 1.11 | https://www.moex.com/en/ |
+| Philippine Stock Exchange | XPHS | Philippines | 1.11 | https://www.pse.com.ph/ |
+| Stock Exchange of Thailand | XBKK | Thailand | 1.11 | https://www.set.or.th/set/mainpage.do?language=en&country=US |
+| Indonesia Stock Exchange | XIDX | Indonesia | 1.11 | https://www.idx.co.id/ |
+| Taiwan Stock Exchange Corp. | XTAI | Taiwan | 1.11 | https://www.twse.com.tw/en/ |
+| Buenos Aires Stock Exchange | XBUE | Argentina | 1.11 | https://www.bcba.sba.com.ar/ |
+| Pakistan Stock Exchange | XKAR | Pakistan | 1.11 | https://www.psx.com.pk/ |
+| Xetra | XETR | Germany | 2.1 | https://www.xetra.com/ |
+| Tel Aviv Stock Exchange | XTAE | Israel | 2.1 | https://www.tase.co.il/ |
+| Astana International Exchange | AIXK | Kazakhstan | 3.2 | https://www.aix.kz/ |
+| Bucharest Stock Exchange | XBSE | Romania | 3.2 | https://www.bvb.ro/ |
+| Saudi Stock Exchange | XSAU | Saudi Arabia | 4.2 | https://www.saudiexchange.sa/ |
+
+> Note that exchange calendars are defined by their [ISO-10383](https://www.iso20022.org/10383/iso-10383-market-identifier-codes) market identifier code.
+
+## [`market-prices`](https://github.com/maread99/market_prices)
+Much of the post v3 development of `exchange_calendars` has been driven by the [`market_prices`](https://github.com/maread99/market_prices) library. Check it out if you like the idea of using `exchange_calendars` to create meaningful OHLCV datasets. It works out-the-box with freely available data!
+
+## Deprecations and Renaming
+
+### Methods renamed in version 4.0.3 and removed in 4.3
+| Previous name | New name |
+| ------------- | -------- |
+| bound_start | bound_min |
+| bound_end | bound_max |
+
+### Methods deprecated in 4.0 and removed in 4.3
+| Deprecated method | Reason |
+| ----------------- | ------ |
+| sessions_closes | use `.closes[start:end]` |
+| sessions_opens | use `.opens[start:end]` |
+
+### Methods with a parameter renamed in 4.0
+| Method
+| ------
+| is_session |
+| is_open_on_minute |
+| minutes_in_range |
+| minutes_window |
+| next_close |
+| next_minute |
+| next_open |
+| previous_close |
+| previous_minute |
+| previous_open |
+| session_break_end |
+| session_break_start |
+| session_close |
+| session_open |
+| sessions_in_range |
+| sessions_window |
+
+### Methods renamed in version 3.4 and removed in 4.0
+| Previous name | New name |
+| ------------- | -------- |
+| all_minutes | minutes |
+| all_minutes_nanos | minutes_nanos |
+| all_sessions | sessions |
+| break_start_and_end_for_session | session_break_start_end |
+| date_to_session_label | date_to_session |
+| first_trading_minute | first_minute |
+| first_trading_session | first_session |
+| has_breaks | sessions_has_break |
+| last_trading_minute | last_minute |
+| last_trading_session | last_session |
+| next_session_label | next_session |
+| open_and_close_for_session | session_open_close |
+| previous_session_label | previous_session |
+| market_break_ends_nanos | break_ends_nanos |
+| market_break_starts_nanos | break_starts_nanos |
+| market_closes_nanos | closes_nanos |
+| market_opens_nanos | opens_nanos |
+| minute_index_to_session_labels | minutes_to_sessions |
+| minute_to_session_label | minute_to_session |
+| minutes_count_for_sessions_in_range | sessions_minutes_count |
+| minutes_for_session | session_minutes |
+| minutes_for_sessions_in_range | sessions_minutes |
+| session_closes_in_range | sessions_closes |
+| session_distance | sessions_distance |
+| session_opens_in_range | sessions_opens |
+
+### Other methods deprecated in 3.4 and removed in 4.0
+| Removed Method
+| -----------------
+| execution_minute_for_session
+| execution_minute_for_sessions_in_range
+| execution_time_from_close
+| execution_time_from_open
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/docs/changes_archive.md b/tasks/tasksmith-ca08ab4caec6/tests/source/docs/changes_archive.md
new file mode 100644
index 0000000000000000000000000000000000000000..699f545da4875dd44ab213d5988cb5fccaeaeb7b
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/docs/changes_archive.md
@@ -0,0 +1,47 @@
+**NOTE**: This file is NOT a comprehensive changes log but rather an archive of sections temporarily included to the README to advise of significant changes.
+
+## **v4 released** (June 2022)
+
+**The earliest stable version of v4 is 4.0.1** (not 4.0).
+
+### What's changed?
+
+Version 4.0.1 completes the transition to a more consistent interface across the package. The most significant changes are:
+
+* **Sessions are now timezone-naive** (previously UTC).
+* Schedule columns now have timezone set as UTC (whilst the times have always been defined in terms of UTC, previously the dtype was timezone-naive).
+* The following schedule columns were renamed:
+ * 'market_open' renamed as 'open'.
+ * 'market_close' renamed as 'close'.
+* Default calendar 'side' for all calendars is now "left" (previously "right" for 24-hour calendars and "both" for all others). This **changes the minutes that are considered trading minutes by default** (see [minutes tutorial](docs/tutorials/minutes.ipynb) for an explanation of trading minutes).
+* The 'count' parameter of `sessions_window` and `minutes_window` methods now reflects the window length (previously window length + 1).
+* New `is_open_at_time` calendar method to evaluate if an exchange is open as at a specific instance (as opposed to over an evaluated minute).
+* The minimum Python version supported is now 3.8 (previously 3.7).
+* Parameters have been renamed for some methods (list [here](#Methods-with-a-parameter-renamed-in-40))
+* The following methods have been deprecated:
+ * `sessions_opens` (use `.opens[start:end]`)
+ * `sessions_closes` (use `.closes[start:end]`)
+* Methods deprecated in 3.4 have been removed (lists [here](#Methods-renamed-in-version-34-and-removed-in-40) and [here](#Other-methods-deprecated-in-34-and-removed-in-40))
+
+See the [4.0 release todo](https://github.com/gerrymanoim/exchange_calendars/issues/61) for a full list of changes and corresponding PRs.
+
+Please offer any feedback at the [v4 discussion](https://github.com/gerrymanoim/exchange_calendars/discussions/202).
+
+## **Changes in 3.4** (released October 2021)
+The 3.4 release introduced notable new features and documentation, including:
+
+* [Tutorials](#Tutorials). Five of them!
+* New calendar methods [#71](https://github.com/gerrymanoim/exchange_calendars/pull/71) (see [calendar_methods.ipynb](docs/tutorials/calendar_methods.ipynb) for usage), including:
+ * trading_index (tutorial [trading_index.ipynb](docs/tutorials/trading_index.ipynb))
+ * is_trading_minute
+ * is_break_minute
+ * minute_offset
+ * session_offset
+ * minute_offset_by_sessions
+* Calendar's now have a `side` parameter to determine which of the open, close, break-start and break-end minutes are treated as trading minutes [#71](https://github.com/gerrymanoim/exchange_calendars/pull/71).
+* 24 hour calendars are now truly 24 hours (open/close times are no longer one minute later/earlier than the actual open/close) [#71](https://github.com/gerrymanoim/exchange_calendars/pull/71).
+* Some calendar methods have been renamed to improve consistency (table of changes [here](#Methods-renamed-in-version-34)) [#85](https://github.com/gerrymanoim/exchange_calendars/issues/85). The previous names will continue to be available until version 4.0. NOTE: Some newly named methods have also made changes to parameter names, for example from `session_label` to `session` and from `start_session_label` to `start`.
+* Under-the-bonnet work has sped up many methods.
+* A test suite overhaul ([#71](https://github.com/gerrymanoim/exchange_calendars/pull/71), [#92](https://github.com/gerrymanoim/exchange_calendars/pull/92), [#96](https://github.com/gerrymanoim/exchange_calendars/pull/96)) has made it simpler to define and test calendars.
+
+Please offer any feedback at the [3.4 discussion](https://github.com/gerrymanoim/exchange_calendars/discussions/107).
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/docs/tutorials/calendar_methods.ipynb b/tasks/tasksmith-ca08ab4caec6/tests/source/docs/tutorials/calendar_methods.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..1476baba42dc04c327221a7d81d7f757569d4f1c
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/docs/tutorials/calendar_methods.ipynb
@@ -0,0 +1,3422 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Calendar methods\n",
+ "\n",
+ "This tutorial offers a walk through of all the `ExchangeCalendar` methods (for properties see the [calendar properties](./calendar_properties.ipynb) tutorial).\n",
+ "\n",
+ "The following sections cover methods according to the nature of the argument(s) they take:\n",
+ "* [Methods that query a Date](#Methods-that-query-a-Date) \n",
+ "* [Methods that query a Session](#Methods-that-query-a-Session) \n",
+ "* [Methods that query a Minute](#Methods-that-query-a-Minute) \n",
+ "* [Methods that query multiple TradingMinute](#Methods-that-query-multiple-TradingMinute) \n",
+ "* [Methods that query a range of dates](#Methods-that-query-a-range-of-dates)\n",
+ "* [Methods that query a time](#Methods-that-query-a-time)\n",
+ "\n",
+ "The following sections cover methods that evaluate an index of trading minutes or sessions:\n",
+ "* [Methods that evaluate an index of contiguous trading minutes](#Methods-that-evaluate-an-index-of-contiguous-trading-minutes)\n",
+ "* [Methods that evaluate an index of contiguous sessions](#Methods-that-evaluate-an-index-of-contiguous-sessions)\n",
+ "\n",
+ "`Date` and `Session` refer to types for 'session' parameters (see [sessions.ipynb](./sessions.ipynb) for a tutorial on how to work with sessions).\n",
+ "\n",
+ "`Minute` and `TradingMinute` refer to types for 'minute' parameters (see [minutes.ipynb](./minutes.ipynb) for a tutorial on how to work with mintues)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# setup\n",
+ "import exchange_calendars as xcals\n",
+ "import pandas as pd\n",
+ "\n",
+ "one_minute = pd.Timedelta(1, \"T\")\n",
+ "\n",
+ "nys = xcals.get_calendar(\"XNYS\") # New York Stock Exchange\n",
+ "hkg = xcals.get_calendar(\"XHKG\") # Hong Kong Stock Exchange"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Methods that query a Date"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The argument of methods in this section takes a `Date` type."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
open
\n",
+ "
break_start
\n",
+ "
break_end
\n",
+ "
close
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
2021-12-31
\n",
+ "
2021-12-31 14:30:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2021-12-31 21:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2022-01-03
\n",
+ "
2022-01-03 14:30:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2022-01-03 21:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2022-01-04
\n",
+ "
2022-01-04 14:30:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2022-01-04 21:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " open break_start break_end \\\n",
+ "2021-12-31 2021-12-31 14:30:00+00:00 NaT NaT \n",
+ "2022-01-03 2022-01-03 14:30:00+00:00 NaT NaT \n",
+ "2022-01-04 2022-01-04 14:30:00+00:00 NaT NaT \n",
+ "\n",
+ " close \n",
+ "2021-12-31 2021-12-31 21:00:00+00:00 \n",
+ "2022-01-03 2022-01-03 21:00:00+00:00 \n",
+ "2022-01-04 2022-01-04 21:00:00+00:00 "
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# for reference, all times are UTC\n",
+ "nys.schedule.loc[\"2021-12-31\":\"2022-01-04\"]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**`is_session`** queries if a date represents a session."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "(False, True)"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.is_session(\"2022-01-01\"), nys.is_session(\"2022-01-04\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**`date_to_session`** will return the the passed `date` if `date` represents a session, or otherwise the nearest session in the passed `direction`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2022-01-04 00:00:00')"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# date is a session so `direction` is ignored\n",
+ "nys.date_to_session(\"2022-01-04\", direction=\"next\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2022-01-03 00:00:00', freq='C')"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.date_to_session(\"2022-01-01\", direction=\"next\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2021-12-31 00:00:00', freq='C')"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.date_to_session(\"2022-01-01\", direction=\"previous\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A ValueError is raised if `direction` is not passed and `date` is not a session."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nys.date_to_session(\"2022-01-01\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "ValueError Traceback (most recent call last)\n",
+ "Input In [7], in ()\n",
+ "----> 1 nys.date_to_session(\"2022-01-01\")\n",
+ "\n",
+ "ValueError: `date` '2022-01-01 00:00:00' does not represent a session. Consider passing a `direction`.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Methods that query a Session\n",
+ "\n",
+ "The argument of methods in this section takes a `Session` type.\n",
+ "\n",
+ "The following methods can be used to return the **open, close** and **break times** of a session..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " open break_start \\\n",
+ "2021-06-15 2021-06-15 01:30:00+00:00 2021-06-15 04:00:00+00:00 \n",
+ "\n",
+ " break_end close \n",
+ "2021-06-15 2021-06-15 05:00:00+00:00 2021-06-15 08:00:00+00:00 "
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_left = xcals.get_calendar(\"XHKG\")\n",
+ "hkg_left.schedule.loc[[\"2021-06-15\"]]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**NB** open, close, and break times are **independent of a calendar's `side`**. These properties reflect times corresponding with the start and end of regular trading periods."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# the default side is \"left\", such that the open is a trading minute...\n",
+ "hkg_left.is_trading_minute(\"2021-06-15 01:30\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# ...and so is the break_end (i.e. the open of the afternoon subsession)...\n",
+ "hkg_left.is_trading_minute(\"2021-06-15 05:00\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# but the close is not a trading minute\n",
+ "hkg_left.is_trading_minute(\"2021-06-15 08:00\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# and neither is the break_start (i.e. the close of the morning subsession)...\n",
+ "hkg_left.is_trading_minute(\"2021-06-15 04:00\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[False, False, True, True]"
+ ]
+ },
+ "execution_count": 11,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# everything's reversed when `side` is \"right\"...\n",
+ "hkg_right = xcals.get_calendar(\"XHKG\", side=\"right\")\n",
+ "times = [\"01:30\", \"05:00\", \"08:00\", \"04:00\"]\n",
+ "[ hkg_right.is_trading_minute(\"2021-06-15 \" + tm) for tm in times ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[True, True, True, True]"
+ ]
+ },
+ "execution_count": 12,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# everything's True when `side` is \"both\"...\n",
+ "hkg_both = xcals.get_calendar(\"XHKG\", side=\"both\")\n",
+ "[ hkg_both.is_trading_minute(\"2021-06-15 \" + tm) for tm in times ]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 13,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[False, False, False, False]"
+ ]
+ },
+ "execution_count": 13,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# and False when `side` is \"neither\".\n",
+ "hkg_neither = xcals.get_calendar(\"XHKG\", side=\"neither\")\n",
+ "[ hkg_neither.is_trading_minute(\"2021-06-15 \" + tm) for tm in times ]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The effect of the calendar's side can be seen in all methods that interrogate or evaluate trading minutes. For example, note the effect of different sides on the minutes associated with the XHKG session \"2021-06-15\":"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 14,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-06-15 01:30:00+00:00', '2021-06-15 01:31:00+00:00',\n",
+ " '2021-06-15 01:32:00+00:00', '2021-06-15 01:33:00+00:00',\n",
+ " '2021-06-15 01:34:00+00:00', '2021-06-15 01:35:00+00:00',\n",
+ " '2021-06-15 01:36:00+00:00', '2021-06-15 01:37:00+00:00',\n",
+ " '2021-06-15 01:38:00+00:00', '2021-06-15 01:39:00+00:00',\n",
+ " ...\n",
+ " '2021-06-15 07:50:00+00:00', '2021-06-15 07:51:00+00:00',\n",
+ " '2021-06-15 07:52:00+00:00', '2021-06-15 07:53:00+00:00',\n",
+ " '2021-06-15 07:54:00+00:00', '2021-06-15 07:55:00+00:00',\n",
+ " '2021-06-15 07:56:00+00:00', '2021-06-15 07:57:00+00:00',\n",
+ " '2021-06-15 07:58:00+00:00', '2021-06-15 07:59:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', length=330, freq=None)"
+ ]
+ },
+ "execution_count": 14,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "session = \"2021-06-15\"\n",
+ "hkg_left.session_minutes(session)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 15,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-06-15 01:31:00+00:00', '2021-06-15 01:32:00+00:00',\n",
+ " '2021-06-15 01:33:00+00:00', '2021-06-15 01:34:00+00:00',\n",
+ " '2021-06-15 01:35:00+00:00', '2021-06-15 01:36:00+00:00',\n",
+ " '2021-06-15 01:37:00+00:00', '2021-06-15 01:38:00+00:00',\n",
+ " '2021-06-15 01:39:00+00:00', '2021-06-15 01:40:00+00:00',\n",
+ " ...\n",
+ " '2021-06-15 07:51:00+00:00', '2021-06-15 07:52:00+00:00',\n",
+ " '2021-06-15 07:53:00+00:00', '2021-06-15 07:54:00+00:00',\n",
+ " '2021-06-15 07:55:00+00:00', '2021-06-15 07:56:00+00:00',\n",
+ " '2021-06-15 07:57:00+00:00', '2021-06-15 07:58:00+00:00',\n",
+ " '2021-06-15 07:59:00+00:00', '2021-06-15 08:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', length=330, freq=None)"
+ ]
+ },
+ "execution_count": 15,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_right.session_minutes(session)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 16,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-06-15 01:30:00+00:00', '2021-06-15 01:31:00+00:00',\n",
+ " '2021-06-15 01:32:00+00:00', '2021-06-15 01:33:00+00:00',\n",
+ " '2021-06-15 01:34:00+00:00', '2021-06-15 01:35:00+00:00',\n",
+ " '2021-06-15 01:36:00+00:00', '2021-06-15 01:37:00+00:00',\n",
+ " '2021-06-15 01:38:00+00:00', '2021-06-15 01:39:00+00:00',\n",
+ " ...\n",
+ " '2021-06-15 07:51:00+00:00', '2021-06-15 07:52:00+00:00',\n",
+ " '2021-06-15 07:53:00+00:00', '2021-06-15 07:54:00+00:00',\n",
+ " '2021-06-15 07:55:00+00:00', '2021-06-15 07:56:00+00:00',\n",
+ " '2021-06-15 07:57:00+00:00', '2021-06-15 07:58:00+00:00',\n",
+ " '2021-06-15 07:59:00+00:00', '2021-06-15 08:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', length=332, freq=None)"
+ ]
+ },
+ "execution_count": 16,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_both.session_minutes(session)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**NOTE:** as a consequence of treating both sides of the session as open, the number of minutes associated with the session is 332, which is two higher than the session duration (330 minutes). This is because both the open and close are treated as trading minutes (+1) and both the break-start and break-open are treated as trading minutes (another +1). NB For calendars/sessions without a break, the difference is +1."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 17,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-06-15 01:31:00+00:00', '2021-06-15 01:32:00+00:00',\n",
+ " '2021-06-15 01:33:00+00:00', '2021-06-15 01:34:00+00:00',\n",
+ " '2021-06-15 01:35:00+00:00', '2021-06-15 01:36:00+00:00',\n",
+ " '2021-06-15 01:37:00+00:00', '2021-06-15 01:38:00+00:00',\n",
+ " '2021-06-15 01:39:00+00:00', '2021-06-15 01:40:00+00:00',\n",
+ " ...\n",
+ " '2021-06-15 07:50:00+00:00', '2021-06-15 07:51:00+00:00',\n",
+ " '2021-06-15 07:52:00+00:00', '2021-06-15 07:53:00+00:00',\n",
+ " '2021-06-15 07:54:00+00:00', '2021-06-15 07:55:00+00:00',\n",
+ " '2021-06-15 07:56:00+00:00', '2021-06-15 07:57:00+00:00',\n",
+ " '2021-06-15 07:58:00+00:00', '2021-06-15 07:59:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', length=328, freq=None)"
+ ]
+ },
+ "execution_count": 17,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_neither.session_minutes(session)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**NOTE** for the \"neither\" side the situation is reversed and the number of minutes associated with the session is two less than the session duration (or -1 for calendars/sessions that do not have a break).\n",
+ "\n",
+ "These discrepancies will make themselves known in all methods that evaluate or interrogate minutes. **If you are not aware of how trading minutes are evaluated, you might get output that you weren't expecting...**"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 18,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "[330, 330, 332, 328]"
+ ]
+ },
+ "execution_count": 18,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "calendars = [hkg_left, hkg_right, hkg_both, hkg_neither]\n",
+ "[ cal.sessions_minutes_count(session, session) for cal in calendars ]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**NOTE**: the default side is **\"left\"**..."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Has it always been this way?\n",
+ "\n",
+ "No.\n",
+ "\n",
+ "The original `trading_calendars` package did not have a side option and treated trading minutes as if side were \"right\". This behaviour came about as a result of defining the open time as one minute later than the true open.\n",
+ "\n",
+ "When support for `trading_calendars` ended `exchange_calendars` came into being. With the initial release 3.0 the opportunity was taken to amend open times to reflect the true open times. Trading minutes continued to be evaluated as previously which had the effect of treating trading minutes as if side were \"both\".\n",
+ "\n",
+ "In release 3.4 the `ExchangeCalendar` side option was implemented to provide users with flexibility over how to treat trading minutes. In order to best preserve behaviour since release 3.0, the default side was \"right\" for the few 24-hour calendars and \"both\" for all others.\n",
+ "\n",
+ "In release 4.0 the default side was set to \"left\" for all calendars. This is not expected to change going forwards."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Can a `minute` parameter have a 'second' component?\n",
+ "\n",
+ "Depends on the `side`...\n",
+ "\n",
+ "#### 'left' and 'right'\n",
+ "\n",
+ "Only if a calenar's side is either \"left\" or \"right\" can `minute` be passed with a second (or milisecond...) component. This is because only these sides allow for a minute timestamp to represent a specific sixty seconds...\n",
+ "\n",
+ "Consider the minute timestamp **\"2021-06-12 15:30:00\"**:\n",
+ "* If the side is \"left\" then this timestamp will sit on the left side of the sixty seconds that it represents, that's to say it will represent the period from **\"2021-06-12 15:30:00\" through \"2021-06-12 15:30:59\"**. Indeed it will represent the period through to the instance before \"2021-06-12 15:31:00\", but it will NOT include \"2021-06-12 15:31:00\".\n",
+ "* If the side is \"right\" then the timestamp will sit on the right of the sixty seconds it represents, that's to say it will represent the period from the instance after \"2021-06-12 15:30:00\" through \"2021-06-12 15:31:00\". It will NOT include \"2021-06-12 15:30:00\" but will include \"2021-06-12 15:31:00\".\n",
+ "\n",
+ "Thought of in this way it becomes clear why an exchange that closes at 16.00 is considered open at \"16:00\" when side is \"right\" but closed when the side is \"left\"...\n",
+ "* when the side is \"right\" the timestamp \"16:00\" refers to the sixty seconds from (but not including) 15:59 through 16:00, i.e. the last minute of the trading day during which the exchange was very much open.\n",
+ "* when the side is \"left\" the timestamp \"16:00\" refers to the sixty seconds from 16:00 to (but not including) 16:01, i.e the first minute after the close when the exchange was very much closed.\n",
+ "\n",
+ "When a `minute` parameter is receieved with a time component more specific than a minute then the corresponding minute timestamp is evaluated by simply rounding up or down if the `side` is \"right\" or \"left\" respectively."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 19,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2021-06-15 05:26:00+0000', tz='UTC')"
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_left.next_minute(\"2021-06-15 05:25:30\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2021-06-15 05:27:00+0000', tz='UTC')"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_right.next_minute(\"2021-06-15 05:25:30\")\n",
+ "# passed argument is represented by the trading minute \"05:26\", hence next_minute is..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 21,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg_left.is_open_on_minute(\"2021-06-15 07:59:59\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### 'both' and 'neither'\n",
+ "\n",
+ "If the calendar's `side` is either \"both\" or \"neither\" then the sixty second period that a minute timestamp refers to is ambiguous. Looked at the other way around, it's ambiguous which minute timestamp represents any specific second. In order to avoid this ambiguity, if the calendar's side is \"both\" or \"neither\" then any `minute` parameter must be received with a time component no more specific than a minute. To the contrary, a ValueError is raised..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "hkg_both.is_open_on_minute(\"2021-06-15 07:59:59\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "ValueError Traceback (most recent call last)\n",
+ "Input In [22], in ()\n",
+ "----> 1 hkg_both.is_open_on_minute(\"2021-06-15 07:59:59\")\n",
+ "\n",
+ "ValueError: `timestamp` cannot have a non-zero second (or more accurate) component for `side` 'both'. `timestamp` parsed as '2021-06-15 07:59:59+00:00'.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `minute` timezone"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "`exchange_calendars` will always return minutes in terms of UTC. However, a `minute` parameter can take a timestamp of any timezone (`exchange_calendars` just parses it to UTC). Consider a session of the New York Stock Exchange:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
open
\n",
+ "
break_start
\n",
+ "
break_end
\n",
+ "
close
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
2021-06-15
\n",
+ "
2021-06-15 13:30:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2021-06-15 20:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " open break_start break_end \\\n",
+ "2021-06-15 2021-06-15 13:30:00+00:00 NaT NaT \n",
+ "\n",
+ " close \n",
+ "2021-06-15 2021-06-15 20:00:00+00:00 "
+ ]
+ },
+ "execution_count": 23,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys = xcals.get_calendar(\"XNYS\", side=\"left\")\n",
+ "nys.schedule.loc[[\"2021-06-15\"]]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 24,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.is_open_on_minute(pd.Timestamp(\"2021-06-15 09:35\"))\n",
+ "# NB tz-naive input is assumed as UTC"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.is_open_on_minute(pd.Timestamp(\"2021-06-15 09:35\", tz=nys.tz))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2021-06-15 13:36:00+0000', tz='UTC')"
+ ]
+ },
+ "execution_count": 26,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.next_minute(pd.Timestamp(\"2021-06-15 09:35\", tz=nys.tz))"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 27,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Timestamp('2021-06-15 09:36:00-0400', tz='America/New_York')"
+ ]
+ },
+ "execution_count": 27,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys.next_minute(pd.Timestamp(\"2021-06-15 09:35\", tz=nys.tz)).tz_convert(nys.tz)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `minute` bounds"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Nearly all methods that have a `minute` parameter will require that `minute` is received as an object representing a minute that's no earlier than the calendar's first trading minute and no later than the calendar's last trading minute (this is always the case for a `minute` annotated with `TradingMinute`)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nys.is_open_on_minute(nys.first_minute - pd.Timedelta(1, \"T\"))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "MinuteOutOfBounds Traceback (most recent call last)\n",
+ "Input In [28], in ()\n",
+ "----> 1 nys.is_open_on_minute(nys.first_minute - pd.Timedelta(1, \"T\"))\n",
+ "\n",
+ "MinuteOutOfBounds: Parameter `minute` receieved as '2002-06-10 13:29:00+00:00' although cannot be earlier than the first trading minute of calendar 'XNYS' ('2002-06-10 13:30:00+00:00').\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "nys.next_open(nys.last_minute + pd.Timedelta(1, \"T\"))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "MinuteOutOfBounds Traceback (most recent call last)\n",
+ "Input In [29], in ()\n",
+ "----> 1 nys.next_open(nys.last_minute + pd.Timedelta(1, \"T\"))\n",
+ "\n",
+ "MinuteOutOfBounds: Parameter `minute` receieved as '2023-06-09 20:00:00+00:00' although cannot be later than the last trading minute of calendar 'XNYS' ('2023-06-09 19:59:00+00:00').\n",
+ "```"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python38 xcals",
+ "language": "python",
+ "name": "py38_xcals"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.8.10"
+ },
+ "widgets": {
+ "application/vnd.jupyter.widget-state+json": {
+ "state": {},
+ "version_major": 2,
+ "version_minor": 0
+ }
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/docs/tutorials/sessions.ipynb b/tasks/tasksmith-ca08ab4caec6/tests/source/docs/tutorials/sessions.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..3facaf7578261f01729b365607414b5bf5ec5ecb
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/docs/tutorials/sessions.ipynb
@@ -0,0 +1,666 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Sessions tutorial"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# setup\n",
+ "from datetime import datetime\n",
+ "\n",
+ "import exchange_calendars as xcals\n",
+ "import pandas as pd"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In `exchange_calendars` a 'session' is a timezone-naive timestamp that represents a date on which an exchange is open..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2022-01-03', '2022-01-04', '2022-01-05', '2022-01-06',\n",
+ " '2022-01-07', '2022-01-10', '2022-01-11', '2022-01-12',\n",
+ " '2022-01-13'],\n",
+ " dtype='datetime64[ns]', freq='C')"
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "nys = xcals.get_calendar(\"XNYS\") # New York Stock Exchange\n",
+ "nys.sessions_in_range(\"2022-01-01\", \"2022-01-13\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The calendar stores in a `schedule` the open and close times for each session. If a session has a lunch break then the break-start and break-end times are also stored. All these times are defined in terms of UTC."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
open
\n",
+ "
break_start
\n",
+ "
break_end
\n",
+ "
close
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
2002-06-10
\n",
+ "
2002-06-10 02:00:00+00:00
\n",
+ "
2002-06-10 04:00:00+00:00
\n",
+ "
2002-06-10 05:00:00+00:00
\n",
+ "
2002-06-10 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-11
\n",
+ "
2002-06-11 02:00:00+00:00
\n",
+ "
2002-06-11 04:00:00+00:00
\n",
+ "
2002-06-11 05:00:00+00:00
\n",
+ "
2002-06-11 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-12
\n",
+ "
2002-06-12 02:00:00+00:00
\n",
+ "
2002-06-12 04:00:00+00:00
\n",
+ "
2002-06-12 05:00:00+00:00
\n",
+ "
2002-06-12 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-13
\n",
+ "
2002-06-13 02:00:00+00:00
\n",
+ "
2002-06-13 04:00:00+00:00
\n",
+ "
2002-06-13 05:00:00+00:00
\n",
+ "
2002-06-13 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-14
\n",
+ "
2002-06-14 02:00:00+00:00
\n",
+ "
2002-06-14 04:00:00+00:00
\n",
+ "
2002-06-14 05:00:00+00:00
\n",
+ "
2002-06-14 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-05
\n",
+ "
2023-06-05 01:30:00+00:00
\n",
+ "
2023-06-05 04:00:00+00:00
\n",
+ "
2023-06-05 05:00:00+00:00
\n",
+ "
2023-06-05 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-06
\n",
+ "
2023-06-06 01:30:00+00:00
\n",
+ "
2023-06-06 04:00:00+00:00
\n",
+ "
2023-06-06 05:00:00+00:00
\n",
+ "
2023-06-06 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-07
\n",
+ "
2023-06-07 01:30:00+00:00
\n",
+ "
2023-06-07 04:00:00+00:00
\n",
+ "
2023-06-07 05:00:00+00:00
\n",
+ "
2023-06-07 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-08
\n",
+ "
2023-06-08 01:30:00+00:00
\n",
+ "
2023-06-08 04:00:00+00:00
\n",
+ "
2023-06-08 05:00:00+00:00
\n",
+ "
2023-06-08 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-09
\n",
+ "
2023-06-09 01:30:00+00:00
\n",
+ "
2023-06-09 04:00:00+00:00
\n",
+ "
2023-06-09 05:00:00+00:00
\n",
+ "
2023-06-09 08:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
5184 rows × 4 columns
\n",
+ "
"
+ ],
+ "text/plain": [
+ " open break_start \\\n",
+ "2002-06-10 2002-06-10 02:00:00+00:00 2002-06-10 04:00:00+00:00 \n",
+ "2002-06-11 2002-06-11 02:00:00+00:00 2002-06-11 04:00:00+00:00 \n",
+ "2002-06-12 2002-06-12 02:00:00+00:00 2002-06-12 04:00:00+00:00 \n",
+ "2002-06-13 2002-06-13 02:00:00+00:00 2002-06-13 04:00:00+00:00 \n",
+ "2002-06-14 2002-06-14 02:00:00+00:00 2002-06-14 04:00:00+00:00 \n",
+ "... ... ... \n",
+ "2023-06-05 2023-06-05 01:30:00+00:00 2023-06-05 04:00:00+00:00 \n",
+ "2023-06-06 2023-06-06 01:30:00+00:00 2023-06-06 04:00:00+00:00 \n",
+ "2023-06-07 2023-06-07 01:30:00+00:00 2023-06-07 04:00:00+00:00 \n",
+ "2023-06-08 2023-06-08 01:30:00+00:00 2023-06-08 04:00:00+00:00 \n",
+ "2023-06-09 2023-06-09 01:30:00+00:00 2023-06-09 04:00:00+00:00 \n",
+ "\n",
+ " break_end close \n",
+ "2002-06-10 2002-06-10 05:00:00+00:00 2002-06-10 08:00:00+00:00 \n",
+ "2002-06-11 2002-06-11 05:00:00+00:00 2002-06-11 08:00:00+00:00 \n",
+ "2002-06-12 2002-06-12 05:00:00+00:00 2002-06-12 08:00:00+00:00 \n",
+ "2002-06-13 2002-06-13 05:00:00+00:00 2002-06-13 08:00:00+00:00 \n",
+ "2002-06-14 2002-06-14 05:00:00+00:00 2002-06-14 08:00:00+00:00 \n",
+ "... ... ... \n",
+ "2023-06-05 2023-06-05 05:00:00+00:00 2023-06-05 08:00:00+00:00 \n",
+ "2023-06-06 2023-06-06 05:00:00+00:00 2023-06-06 08:00:00+00:00 \n",
+ "2023-06-07 2023-06-07 05:00:00+00:00 2023-06-07 08:00:00+00:00 \n",
+ "2023-06-08 2023-06-08 05:00:00+00:00 2023-06-08 08:00:00+00:00 \n",
+ "2023-06-09 2023-06-09 05:00:00+00:00 2023-06-09 08:00:00+00:00 \n",
+ "\n",
+ "[5184 rows x 4 columns]"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg = xcals.get_calendar(\"XHKG\") # Hong Kong Stock Exchange\n",
+ "hkg.schedule"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Each session is associated with a set of contiguous trading minutes (or two sets if the sesson has a lunch break)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "session=Timestamp('2023-06-09 00:00:00', freq='C')\n",
+ "\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2023-06-09 01:30:00+00:00', '2023-06-09 01:31:00+00:00',\n",
+ " '2023-06-09 01:32:00+00:00', '2023-06-09 01:33:00+00:00',\n",
+ " '2023-06-09 01:34:00+00:00', '2023-06-09 01:35:00+00:00',\n",
+ " '2023-06-09 01:36:00+00:00', '2023-06-09 01:37:00+00:00',\n",
+ " '2023-06-09 01:38:00+00:00', '2023-06-09 01:39:00+00:00',\n",
+ " ...\n",
+ " '2023-06-09 07:50:00+00:00', '2023-06-09 07:51:00+00:00',\n",
+ " '2023-06-09 07:52:00+00:00', '2023-06-09 07:53:00+00:00',\n",
+ " '2023-06-09 07:54:00+00:00', '2023-06-09 07:55:00+00:00',\n",
+ " '2023-06-09 07:56:00+00:00', '2023-06-09 07:57:00+00:00',\n",
+ " '2023-06-09 07:58:00+00:00', '2023-06-09 07:59:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', length=330, freq=None)"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "session = hkg.schedule.index[-1]\n",
+ "print(f\"{session=}\\n\") # for reference\n",
+ "\n",
+ "hkg.session_minutes(session)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "See the [minutes.ipynb](./minutes.ipynb) tutorial for an explanation of how trading minutes for a session are evaluated according to the \"side\" option."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "A timestamp representing a 'session' takes the date in which **most of the session falls** (based on UTC open/close times). Almost all calendars' have sessions that fall fully within a single date. The schedule above shows this is the case for XHKG.\n",
+ "\n",
+ "A few calendars have sessions that fall over two dates..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
open
\n",
+ "
break_start
\n",
+ "
break_end
\n",
+ "
close
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
2002-06-10
\n",
+ "
2002-06-09 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2002-06-10 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-11
\n",
+ "
2002-06-10 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2002-06-11 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-12
\n",
+ "
2002-06-11 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2002-06-12 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-13
\n",
+ "
2002-06-12 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2002-06-13 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2002-06-14
\n",
+ "
2002-06-13 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2002-06-14 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
...
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-05
\n",
+ "
2023-06-04 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2023-06-05 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-06
\n",
+ "
2023-06-05 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2023-06-06 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-07
\n",
+ "
2023-06-06 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2023-06-07 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-08
\n",
+ "
2023-06-07 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2023-06-08 22:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2023-06-09
\n",
+ "
2023-06-08 22:00:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2023-06-09 22:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
5417 rows × 4 columns
\n",
+ "
"
+ ],
+ "text/plain": [
+ " open break_start break_end \\\n",
+ "2002-06-10 2002-06-09 22:00:00+00:00 NaT NaT \n",
+ "2002-06-11 2002-06-10 22:00:00+00:00 NaT NaT \n",
+ "2002-06-12 2002-06-11 22:00:00+00:00 NaT NaT \n",
+ "2002-06-13 2002-06-12 22:00:00+00:00 NaT NaT \n",
+ "2002-06-14 2002-06-13 22:00:00+00:00 NaT NaT \n",
+ "... ... ... ... \n",
+ "2023-06-05 2023-06-04 22:00:00+00:00 NaT NaT \n",
+ "2023-06-06 2023-06-05 22:00:00+00:00 NaT NaT \n",
+ "2023-06-07 2023-06-06 22:00:00+00:00 NaT NaT \n",
+ "2023-06-08 2023-06-07 22:00:00+00:00 NaT NaT \n",
+ "2023-06-09 2023-06-08 22:00:00+00:00 NaT NaT \n",
+ "\n",
+ " close \n",
+ "2002-06-10 2002-06-10 22:00:00+00:00 \n",
+ "2002-06-11 2002-06-11 22:00:00+00:00 \n",
+ "2002-06-12 2002-06-12 22:00:00+00:00 \n",
+ "2002-06-13 2002-06-13 22:00:00+00:00 \n",
+ "2002-06-14 2002-06-14 22:00:00+00:00 \n",
+ "... ... \n",
+ "2023-06-05 2023-06-05 22:00:00+00:00 \n",
+ "2023-06-06 2023-06-06 22:00:00+00:00 \n",
+ "2023-06-07 2023-06-07 22:00:00+00:00 \n",
+ "2023-06-08 2023-06-08 22:00:00+00:00 \n",
+ "2023-06-09 2023-06-09 22:00:00+00:00 \n",
+ "\n",
+ "[5417 rows x 4 columns]"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "cmes = xcals.get_calendar(\"CMES\")\n",
+ "cmes.schedule"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note how the sessions take their value as the date in which most of the session falls, NOT the date of the open."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `session` parameter\n",
+ "Methods that require a single session to be specified take a `session` parameter. Those that act on a range of sessions take `start` and `end` parameters.\n",
+ "\n",
+ "These parameters can take a `Date` or a `Session` type, defined as:\n",
+ "\n",
+ "```python\n",
+ "Date = typing.Union[pd.Timestamp, str, int, float, datetime.datetime]\n",
+ "Session = Date\n",
+ "```\n",
+ "In short, a `session` parameter can take any type that can be passed as a single argument to pd.Timestamp(). For example, the argument of `next_session` takes a `Session` type and any of the following inputs are valid:\n",
+ ""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "inputs = [\n",
+ " \"2021-06-15\",\n",
+ " pd.Timestamp(\"2021-06-15\"),\n",
+ " datetime(2021, 6, 15),\n",
+ " 1623715200000000000,\n",
+ "]\n",
+ "lon = xcals.get_calendar(\"XLON\")\n",
+ "for input_ in inputs:\n",
+ " assert lon.next_session(input_) == pd.Timestamp('2021-06-16')"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The difference between `Date` and `Session` is that whilst an object passed to a parameter annotated `Date` can represent any date, an object passed to a parameter annotated `Session` must represent an actual calendar session.\n",
+ "\n",
+ "For example, the arguments of `sessions_in_range` take a `Date` type, such that the following is valid even though it can be seen that neither of the values passed represent sessions."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2022-01-04', '2022-01-05', '2022-01-06', '2022-01-07'], dtype='datetime64[ns]', freq='C')"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "lon.sessions_in_range(\"2022-01-01\", \"2022-01-09\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "However, passing a date that is not a session to an argument that takes a `Session` will raise a `NotSessionError`..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "lon.session_open(\"2022-01-09\")\n",
+ "# run cell for full traceback"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "NotSessionError Traceback (most recent call last)\n",
+ "Input In [8], in ()\n",
+ "----> 1 lon.session_open(\"2022-01-09\")\n",
+ "\n",
+ "NotSessionError: Parameter `session` takes a session although received input that parsed to '2022-01-09 00:00:00' which is not a session of calendar 'XLON'.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "To find out **which type a `session` parameter takes**, simply refer to the annotated types in the method signature:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "tags": []
+ },
+ "outputs": [],
+ "source": [
+ "lon.session_open?\n",
+ "# run cell for full method doc"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "Signature: lon.session_open(session: 'Session', _parse: 'bool' = True) -> 'pd.Timestamp'\n",
+ "Docstring: Return open time for a given session.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "#### Invalid `session` input"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "##### **Time components** \n",
+ "A `session` parameter cannot include a time component..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "lon.session_open(\"2021-01-07 12:20\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "ValueError Traceback (most recent call last)\n",
+ "Input In [10], in ()\n",
+ "----> 1 lon.session_open(\"2021-01-07 12:20\")\n",
+ "\n",
+ "ValueError: Parameter `session` parsed as '2021-01-07 12:20:00' although a Date must have a time component of 00:00.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "##### **Timezone**\n",
+ "A `session` parameter cannot have a timezone..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "session = pd.Timestamp(\"2021-01-07\", tz=\"UTC\")\n",
+ "lon.session_close(session)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "ValueError Traceback (most recent call last)\n",
+ "Input In [11], in ()\n",
+ " 1 session = pd.Timestamp(\"2021-01-07\", tz=\"UTC\")\n",
+ "----> 2 lon.session_close(session)\n",
+ "\n",
+ "ValueError: Parameter `session` received with timezone defined as 'UTC' although a Date must be timezone naive.\n",
+ "```"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python38 xcals",
+ "language": "python",
+ "name": "py38_xcals"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.8.10"
+ },
+ "widgets": {
+ "application/vnd.jupyter.widget-state+json": {
+ "state": {},
+ "version_major": 2,
+ "version_minor": 0
+ }
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 4
+}
diff --git a/tasks/tasksmith-ca08ab4caec6/tests/source/docs/tutorials/trading_index.ipynb b/tasks/tasksmith-ca08ab4caec6/tests/source/docs/tutorials/trading_index.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..a5b0a8a0be91fff5eb49b0667d362c6e4a9fa5b5
--- /dev/null
+++ b/tasks/tasksmith-ca08ab4caec6/tests/source/docs/tutorials/trading_index.ipynb
@@ -0,0 +1,4072 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# `trading_index`\n",
+ "\n",
+ "This tutorial shows all the ins and outs of the calendars' `trading_index` method. (For other calendar methods see the [calendar_methods.ipynb](./calendar_methods.ipynb) tutorial.)\n",
+ "\n",
+ "The [What does it do?](#What-does-it-do?) section explains basic usage. The following sections then explore the method's arguments and options:\n",
+ "\n",
+ "* [`intervals`](#intervals)\n",
+ "* [`period`](#period)\n",
+ "* [`closed`](#closed)\n",
+ "* [`force_close`, `force_break_close` and `force`](#force_close,-force_break_close-and-force)\n",
+ "* [`ignore_breaks`](#ignore_breaks)\n",
+ "* [`align` and `align_pm`](#align-and-align_pm)\n",
+ "* [`start` and `end` as times](#start-and-end-as-times)\n",
+ "\n",
+ "The final section covers [overlapping indices](#Overlapping-indices)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "# setup\n",
+ "from zoneinfo import ZoneInfo\n",
+ "\n",
+ "import exchange_calendars as xcals\n",
+ "import pandas as pd\n",
+ "\n",
+ "hkg = xcals.get_calendar(\"XHKG\") # Hong Kong Stock Exchange\n",
+ "start = \"2021-12-23\"\n",
+ "end = \"2021-12-28\""
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
open
\n",
+ "
break_start
\n",
+ "
break_end
\n",
+ "
close
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
2021-12-23
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 04:00:00+00:00
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 08:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2021-12-24
\n",
+ "
2021-12-24 01:30:00+00:00
\n",
+ "
NaT
\n",
+ "
NaT
\n",
+ "
2021-12-24 04:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
2021-12-28
\n",
+ "
2021-12-28 01:30:00+00:00
\n",
+ "
2021-12-28 04:00:00+00:00
\n",
+ "
2021-12-28 05:00:00+00:00
\n",
+ "
2021-12-28 08:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " open break_start \\\n",
+ "2021-12-23 2021-12-23 01:30:00+00:00 2021-12-23 04:00:00+00:00 \n",
+ "2021-12-24 2021-12-24 01:30:00+00:00 NaT \n",
+ "2021-12-28 2021-12-28 01:30:00+00:00 2021-12-28 04:00:00+00:00 \n",
+ "\n",
+ " break_end close \n",
+ "2021-12-23 2021-12-23 05:00:00+00:00 2021-12-23 08:00:00+00:00 \n",
+ "2021-12-24 NaT 2021-12-24 04:00:00+00:00 \n",
+ "2021-12-28 2021-12-28 05:00:00+00:00 2021-12-28 08:00:00+00:00 "
+ ]
+ },
+ "execution_count": 2,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# for reference\n",
+ "schedule = hkg.schedule.loc[start:end]\n",
+ "schedule"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### What does it do?\n",
+ "\n",
+ "`trading_index` creates a trading index at a given period over a range of sessions."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 01:30:00+00:00', '2021-12-23 02:00:00+00:00',\n",
+ " '2021-12-23 02:30:00+00:00', '2021-12-23 03:00:00+00:00',\n",
+ " '2021-12-23 03:30:00+00:00', '2021-12-23 05:00:00+00:00',\n",
+ " '2021-12-23 05:30:00+00:00', '2021-12-23 06:00:00+00:00',\n",
+ " '2021-12-23 06:30:00+00:00', '2021-12-23 07:00:00+00:00',\n",
+ " '2021-12-23 07:30:00+00:00', '2021-12-24 01:30:00+00:00',\n",
+ " '2021-12-24 02:00:00+00:00', '2021-12-24 02:30:00+00:00',\n",
+ " '2021-12-24 03:00:00+00:00', '2021-12-24 03:30:00+00:00',\n",
+ " '2021-12-28 01:30:00+00:00', '2021-12-28 02:00:00+00:00',\n",
+ " '2021-12-28 02:30:00+00:00', '2021-12-28 03:00:00+00:00',\n",
+ " '2021-12-28 03:30:00+00:00', '2021-12-28 05:00:00+00:00',\n",
+ " '2021-12-28 05:30:00+00:00', '2021-12-28 06:00:00+00:00',\n",
+ " '2021-12-28 06:30:00+00:00', '2021-12-28 07:00:00+00:00',\n",
+ " '2021-12-28 07:30:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 3,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start, end, \"30min\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Or over a single session, if `start` and `end` are passed as the same session."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 01:30:00+00:00', '2021-12-23 02:00:00+00:00',\n",
+ " '2021-12-23 02:30:00+00:00', '2021-12-23 03:00:00+00:00',\n",
+ " '2021-12-23 03:30:00+00:00', '2021-12-23 05:00:00+00:00',\n",
+ " '2021-12-23 05:30:00+00:00', '2021-12-23 06:00:00+00:00',\n",
+ " '2021-12-23 06:30:00+00:00', '2021-12-23 07:00:00+00:00',\n",
+ " '2021-12-23 07:30:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 4,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start=start, end=start, period=\"30min\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Or between times, if `start` and `end` are passed as times (as opposed to dates)."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 02:30:00+00:00', '2021-12-23 03:00:00+00:00',\n",
+ " '2021-12-23 03:30:00+00:00', '2021-12-23 05:00:00+00:00',\n",
+ " '2021-12-23 05:30:00+00:00', '2021-12-23 06:00:00+00:00',\n",
+ " '2021-12-23 06:30:00+00:00', '2021-12-23 07:00:00+00:00',\n",
+ " '2021-12-23 07:30:00+00:00', '2021-12-24 01:30:00+00:00',\n",
+ " '2021-12-24 02:00:00+00:00', '2021-12-24 02:30:00+00:00',\n",
+ " '2021-12-24 03:00:00+00:00', '2021-12-24 03:30:00+00:00',\n",
+ " '2021-12-28 01:30:00+00:00', '2021-12-28 02:00:00+00:00',\n",
+ " '2021-12-28 02:30:00+00:00', '2021-12-28 03:00:00+00:00',\n",
+ " '2021-12-28 03:30:00+00:00', '2021-12-28 05:00:00+00:00',\n",
+ " '2021-12-28 05:30:00+00:00', '2021-12-28 06:00:00+00:00',\n",
+ " '2021-12-28 06:30:00+00:00', '2021-12-28 07:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "start_min = \"2021-12-23 02:30\"\n",
+ "end_min = \"2021-12-28 07:00\"\n",
+ "hkg.trading_index(start=start_min, end=end_min, period=\"30min\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note that `start` can be passed as a time and `end` as a date, or vice-versa."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 6,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 02:30:00+00:00', '2021-12-23 03:00:00+00:00',\n",
+ " '2021-12-23 03:30:00+00:00', '2021-12-23 05:00:00+00:00',\n",
+ " '2021-12-23 05:30:00+00:00', '2021-12-23 06:00:00+00:00',\n",
+ " '2021-12-23 06:30:00+00:00', '2021-12-23 07:00:00+00:00',\n",
+ " '2021-12-23 07:30:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 6,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start=start_min, end=start, period=\"30min\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "See the '[`start` and `end` as times](#start-and-end-as-times)' section for further notes on how the first and last indices are defined when `start` and/or `end` are passed as times."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `intervals`\n",
+ "\n",
+ "By passing `intervals` as `False` the index can be output as a `DatetimeIndex`, as shown above. Although by default the index is output as an `IntervalIndex`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 7,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "IntervalIndex([[2021-12-23 01:30:00, 2021-12-23 02:00:00), [2021-12-23 02:00:00, 2021-12-23 02:30:00), [2021-12-23 02:30:00, 2021-12-23 03:00:00), [2021-12-23 03:00:00, 2021-12-23 03:30:00), [2021-12-23 03:30:00, 2021-12-23 04:00:00) ... [2021-12-23 05:30:00, 2021-12-23 06:00:00), [2021-12-23 06:00:00, 2021-12-23 06:30:00), [2021-12-23 06:30:00, 2021-12-23 07:00:00), [2021-12-23 07:00:00, 2021-12-23 07:30:00), [2021-12-23 07:30:00, 2021-12-23 08:00:00)], dtype='interval[datetime64[ns, UTC], left]')"
+ ]
+ },
+ "execution_count": 7,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index = hkg.trading_index(start, start, \"30min\")\n",
+ "index"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Let's make that a bit more readable by setting it to the index of a `DataFrame`, and have columns showing the index's left and right sides."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 8,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 01:30:00, 2021-12-23 02:00:00)
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 02:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 02:00:00, 2021-12-23 02:30:00)
\n",
+ "
2021-12-23 02:00:00+00:00
\n",
+ "
2021-12-23 02:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 02:30:00, 2021-12-23 03:00:00)
\n",
+ "
2021-12-23 02:30:00+00:00
\n",
+ "
2021-12-23 03:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:00:00, 2021-12-23 03:30:00)
\n",
+ "
2021-12-23 03:00:00+00:00
\n",
+ "
2021-12-23 03:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:30:00, 2021-12-23 04:00:00)
\n",
+ "
2021-12-23 03:30:00+00:00
\n",
+ "
2021-12-23 04:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 05:30:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 05:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:30:00, 2021-12-23 06:00:00)
\n",
+ "
2021-12-23 05:30:00+00:00
\n",
+ "
2021-12-23 06:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:00:00, 2021-12-23 06:30:00)
\n",
+ "
2021-12-23 06:00:00+00:00
\n",
+ "
2021-12-23 06:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:30:00, 2021-12-23 07:00:00)
\n",
+ "
2021-12-23 06:30:00+00:00
\n",
+ "
2021-12-23 07:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 07:00:00, 2021-12-23 07:30:00)
\n",
+ "
2021-12-23 07:00:00+00:00
\n",
+ "
2021-12-23 07:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 07:30:00, 2021-12-23 08:00:00)
\n",
+ "
2021-12-23 07:30:00+00:00
\n",
+ "
2021-12-23 08:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 02:00:00) 2021-12-23 01:30:00+00:00 \n",
+ "[2021-12-23 02:00:00, 2021-12-23 02:30:00) 2021-12-23 02:00:00+00:00 \n",
+ "[2021-12-23 02:30:00, 2021-12-23 03:00:00) 2021-12-23 02:30:00+00:00 \n",
+ "[2021-12-23 03:00:00, 2021-12-23 03:30:00) 2021-12-23 03:00:00+00:00 \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 03:30:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:00:00+00:00 \n",
+ "[2021-12-23 06:30:00, 2021-12-23 07:00:00) 2021-12-23 06:30:00+00:00 \n",
+ "[2021-12-23 07:00:00, 2021-12-23 07:30:00) 2021-12-23 07:00:00+00:00 \n",
+ "[2021-12-23 07:30:00, 2021-12-23 08:00:00) 2021-12-23 07:30:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 02:00:00) 2021-12-23 02:00:00+00:00 \n",
+ "[2021-12-23 02:00:00, 2021-12-23 02:30:00) 2021-12-23 02:30:00+00:00 \n",
+ "[2021-12-23 02:30:00, 2021-12-23 03:00:00) 2021-12-23 03:00:00+00:00 \n",
+ "[2021-12-23 03:00:00, 2021-12-23 03:30:00) 2021-12-23 03:30:00+00:00 \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 04:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 06:00:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:30:00+00:00 \n",
+ "[2021-12-23 06:30:00, 2021-12-23 07:00:00) 2021-12-23 07:00:00+00:00 \n",
+ "[2021-12-23 07:00:00, 2021-12-23 07:30:00) 2021-12-23 07:30:00+00:00 \n",
+ "[2021-12-23 07:30:00, 2021-12-23 08:00:00) 2021-12-23 08:00:00+00:00 "
+ ]
+ },
+ "execution_count": 8,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "def show_as_df(index: pd.IntervalIndex) -> pd.DataFrame:\n",
+ " index.name = \"IntervalIndex\"\n",
+ " return pd.DataFrame(\n",
+ " dict(left_side=index.left, right_side=index.right),\n",
+ " index=index\n",
+ " )\n",
+ "\n",
+ "show_as_df(index)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `period`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The trading index represents sessions and subsessions as a number of discrete periods of a given length.\n",
+ "\n",
+ "When output as an `IntervalIndex` each indice represents a discrete period."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 9,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Interval('2021-12-23 01:30:00', '2021-12-23 02:00:00', closed='left')"
+ ]
+ },
+ "execution_count": 9,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index[0]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The length of each period for the example above is 30 minutes."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 10,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "TimedeltaIndex(['0 days 00:30:00', '0 days 00:30:00', '0 days 00:30:00',\n",
+ " '0 days 00:30:00', '0 days 00:30:00', '0 days 00:30:00',\n",
+ " '0 days 00:30:00', '0 days 00:30:00', '0 days 00:30:00',\n",
+ " '0 days 00:30:00', '0 days 00:30:00'],\n",
+ " dtype='timedelta64[ns]', freq=None)"
+ ]
+ },
+ "execution_count": 10,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index.length"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "The period length is defined by the `period` argument which can be passed as the third positional argument or as a keyword argument. `period` can take either a `pd.Timedelta` or a string representing a pandas frequency. All the following are valid inputs representing a period length of 1 hour."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 11,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "periods = [\n",
+ " pd.Timedelta(hours=1),\n",
+ " pd.Timedelta(1, \"H\"),\n",
+ " pd.Timedelta(60, \"min\"),\n",
+ " pd.Timedelta(60, \"T\"),\n",
+ " \"1H\",\n",
+ " \"1h\",\n",
+ " \"60T\",\n",
+ " \"60min\",\n",
+ " \"3600s\" \n",
+ "]\n",
+ "\n",
+ "indexes = [ hkg.trading_index(start, start, period) for period in periods ]\n",
+ "for i, index in enumerate(indexes):\n",
+ " pd.testing.assert_index_equal(index, indexes[0])"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 12,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " open break_start \\\n",
+ "2021-12-23 2021-12-23 01:30:00+00:00 2021-12-23 04:00:00+00:00 \n",
+ "\n",
+ " break_end close \n",
+ "2021-12-23 2021-12-23 05:00:00+00:00 2021-12-23 08:00:00+00:00 "
+ ]
+ },
+ "execution_count": 19,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# recall\n",
+ "schedule.iloc[[0]]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Hong Kong has a lunch break. The trading index covers the morning subsession starting with the open, and then the afternoon subsession starting with the break-end. The hour and a half represents the difference between the last indice of the morning subsession and the first indice of the afternoon subsession. (See [`ignore_breaks`](#ignore_breaks) for how to treat sessions as continuous.)\n",
+ "\n",
+ "Ok, fine, but why hasn't the index included indices for 04:00 or 08:00? That's because it's `closed` on the \"left\" (by default)..."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `closed`\n",
+ "\n",
+ "The `closed` parameter has a different effect depending on whether the index is being output as an `IntervalIndex` (default) or `DatetimeIndex` (i.e. `intervals=False`).\n",
+ "\n",
+ "If the index is being output as an `IntervalIndex` then `closed` can take either \"left\" (default) or \"right\". This value is simply passed through to the `closed` parameter of the `IntervalIndex` (to define the side on which all the intervals should be closed). In this case `closed` has no other effect.\n",
+ "\n",
+ "If the index is being output as an `DatetimeIndex` then `closed` can take either \"left\", \"right\", \"both\" or \"neither\". In this case `closed` determines **the side of each implied period that an indice should be defined on**. The consequence of each value is best understood by considering whether or not the left side of the first implied period and/or the right side of last implied period are included as indices:\n",
+ "* \"left\" (default) - include left side of first period, do not include right side of last period.\n",
+ "* \"right\" - do not include left side of first period, include right side of last period.\n",
+ "* \"both\" - include both left side of first period and right side of last period.\n",
+ "* \"neither\" - do not include either left side of first period or right side of last period.\n",
+ "\n",
+ "So, going back to the prior example, passing `closed` as right will include the 04:00 and 08:00 indices."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 20,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 02:00:00+00:00', '2021-12-23 02:30:00+00:00',\n",
+ " '2021-12-23 03:00:00+00:00', '2021-12-23 03:30:00+00:00',\n",
+ " '2021-12-23 04:00:00+00:00', '2021-12-23 05:30:00+00:00',\n",
+ " '2021-12-23 06:00:00+00:00', '2021-12-23 06:30:00+00:00',\n",
+ " '2021-12-23 07:00:00+00:00', '2021-12-23 07:30:00+00:00',\n",
+ " '2021-12-23 08:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 20,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start, start, \"30min\", closed=\"right\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Although now that only the right sides of the implied periods are being defined - the open (01:30) and start of the afternoon subsession (05:00) are not included...\n",
+ "\n",
+ "`closed` can be passed as \"both\" to include both the left and the right side of each implied interval."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 21,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 01:30:00+00:00', '2021-12-23 02:00:00+00:00',\n",
+ " '2021-12-23 02:30:00+00:00', '2021-12-23 03:00:00+00:00',\n",
+ " '2021-12-23 03:30:00+00:00', '2021-12-23 04:00:00+00:00',\n",
+ " '2021-12-23 05:00:00+00:00', '2021-12-23 05:30:00+00:00',\n",
+ " '2021-12-23 06:00:00+00:00', '2021-12-23 06:30:00+00:00',\n",
+ " '2021-12-23 07:00:00+00:00', '2021-12-23 07:30:00+00:00',\n",
+ " '2021-12-23 08:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 21,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start, start, \"30min\", closed=\"both\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "And if you have a use case where you don't require either the left side of a (sub)session's first period or the right side of its last one, then you're after \"neither\"."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 22,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 02:00:00+00:00', '2021-12-23 02:30:00+00:00',\n",
+ " '2021-12-23 03:00:00+00:00', '2021-12-23 03:30:00+00:00',\n",
+ " '2021-12-23 05:30:00+00:00', '2021-12-23 06:00:00+00:00',\n",
+ " '2021-12-23 06:30:00+00:00', '2021-12-23 07:00:00+00:00',\n",
+ " '2021-12-23 07:30:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 22,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "hkg.trading_index(start, start, \"30min\", closed=\"neither\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `force_close`, `force_break_close` and `force`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Have a look at this."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 23,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " open break_start \\\n",
+ "2021-12-23 2021-12-23 01:30:00+00:00 2021-12-23 04:00:00+00:00 \n",
+ "\n",
+ " break_end close \n",
+ "2021-12-23 2021-12-23 05:00:00+00:00 2021-12-23 08:00:00+00:00 "
+ ]
+ },
+ "execution_count": 24,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "# for reference\n",
+ "schedule.iloc[[0]]"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 25,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "Interval('2021-12-23 02:50:00', '2021-12-23 04:10:00', closed='left')"
+ ]
+ },
+ "execution_count": 25,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index[1]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "It can be seen that whilst this indice represents, like all the others, a period of 80 minutes, only the first 70 minutes of these actually represent a trading period, with the last 10 minutes, from 04:00 to 04:10, falling within the subsequent break.\n",
+ "\n",
+ "Similarly, it can be see that the last indice includes a full hour (08:00 - 09:00) that falls after the close.\n",
+ "\n",
+ "**The final indice of a (sub)session will always include a non-trading period whenever the period length is not a factor of the (sub)session duration.**\n",
+ "\n",
+ "The `force_close` and `force_break_close` options are provided to force the right side of the final period to, respectively, the session / morning subsession close."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 26,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:20:00, 2021-12-23 01:40:00) 2021-12-23 01:20:00+00:00 \n",
+ "[2021-12-23 01:40:00, 2021-12-23 02:00:00) 2021-12-23 01:40:00+00:00 \n",
+ "[2021-12-23 02:00:00, 2021-12-23 02:20:00) 2021-12-23 02:00:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:20:00, 2021-12-23 01:40:00) 2021-12-23 01:40:00+00:00 \n",
+ "[2021-12-23 01:40:00, 2021-12-23 02:00:00) 2021-12-23 02:00:00+00:00 \n",
+ "[2021-12-23 02:00:00, 2021-12-23 02:20:00) 2021-12-23 02:20:00+00:00 "
+ ]
+ },
+ "execution_count": 43,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index = hkg.trading_index(start, start, \"20T\", align=\"-20T\")\n",
+ "show_as_df(index)[:3]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Where a calendar observes a break, by default the start of both the morning and afternoon subsessions will be anchored, independently, according to `align`. Alternatively `align_pm` can be passed to anchor the start of the afternoon subsessions:\n",
+ "* to a different alignment, by passing as a `str` or `Timedelta`.\n",
+ "* to the break-end (i.e. the afternoon subsession open), by passing as `False`"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `start` and `end` as times"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "When `start` and `end` are passed as times, how the first and last indices are defined depends on whether the index is returned as an `IntervalIndex` or a `DatetimeIndex`.\n",
+ "\n",
+ "When returning an `IntervalIndex` (`intervals=True`):\n",
+ "* The first indice will be:\n",
+ " * if `start` coincides with the left side of an indice, then that indice.\n",
+ " * otherwise the nearest indice to `start` with a left side that is later than `start`.\n",
+ "\n",
+ "* The last indice will be:\n",
+ " * if `end` coincides with the right side of an indice, then that indice.\n",
+ " * otherwise the nearest indice to `end` with a right side that is earlier than `end`.\n",
+ "\n",
+ "In the following example the `start` and `end` times coincide with, respectively, the left and right side of indices."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 44,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "start_min = pd.Timestamp(\"2021-12-23 03:00\")\n",
+ "end_min = pd.Timestamp(\"2021-12-23 07:00\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 45,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 03:30:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:00:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 04:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 06:00:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:30:00+00:00 "
+ ]
+ },
+ "execution_count": 46,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "one_min = pd.Timedelta(1, \"T\")\n",
+ "index = hkg.trading_index(start_min + one_min, end_min - one_min, \"30T\", intervals=True)\n",
+ "show_as_df(index)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "In short, when returning an `IntervalIndex`:\n",
+ "* the first indice will never include a period that falls before `start`.\n",
+ "* the last indice will never include a period that falls after `end`.\n",
+ "\n",
+ "The same is not true for when a `DatetimeIndex` is returned. In this case the first and last indices are defined without consideration to the periods that the indices may represent.\n",
+ "\n",
+ "When returning an `DatetimeIndex`:\n",
+ "* The first indice will be either `start`, if start is an indice, or otherwise the nearest indice that follows `start`. \n",
+ "* The last indice will be either `end`, if end is an indice, or otherwise the nearest indice that preceeds `end`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 47,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "start_min=Timestamp('2021-12-23 03:00:00')\tend_min=Timestamp('2021-12-23 07:00:00')\n"
+ ]
+ },
+ {
+ "data": {
+ "text/plain": [
+ "DatetimeIndex(['2021-12-23 03:00:00+00:00', '2021-12-23 03:30:00+00:00',\n",
+ " '2021-12-23 05:00:00+00:00', '2021-12-23 05:30:00+00:00',\n",
+ " '2021-12-23 06:00:00+00:00', '2021-12-23 06:30:00+00:00',\n",
+ " '2021-12-23 07:00:00+00:00'],\n",
+ " dtype='datetime64[ns, UTC]', freq=None)"
+ ]
+ },
+ "execution_count": 47,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "print(f\"{start_min=}\\t{end_min=}\") # for reference\n",
+ "hkg.trading_index(start_min, end_min, \"30T\", closed=\"left\", intervals=False)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Note the different interpretation of what `end` represents. Here the `end` indice is included even though it represents a period (07:00 - 07:30) that falls after `end_min`. If intervals=True then the analogous indice is excluded."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 48,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 03:00:00, 2021-12-23 03:30:00)
\n",
+ "
2021-12-23 03:00:00+00:00
\n",
+ "
2021-12-23 03:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:30:00, 2021-12-23 04:00:00)
\n",
+ "
2021-12-23 03:30:00+00:00
\n",
+ "
2021-12-23 04:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 05:30:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 05:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:30:00, 2021-12-23 06:00:00)
\n",
+ "
2021-12-23 05:30:00+00:00
\n",
+ "
2021-12-23 06:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:00:00, 2021-12-23 06:30:00)
\n",
+ "
2021-12-23 06:00:00+00:00
\n",
+ "
2021-12-23 06:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:30:00, 2021-12-23 07:00:00)
\n",
+ "
2021-12-23 06:30:00+00:00
\n",
+ "
2021-12-23 07:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 03:00:00, 2021-12-23 03:30:00) 2021-12-23 03:00:00+00:00 \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 03:30:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:00:00+00:00 \n",
+ "[2021-12-23 06:30:00, 2021-12-23 07:00:00) 2021-12-23 06:30:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 03:00:00, 2021-12-23 03:30:00) 2021-12-23 03:30:00+00:00 \n",
+ "[2021-12-23 03:30:00, 2021-12-23 04:00:00) 2021-12-23 04:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 05:30:00) 2021-12-23 05:30:00+00:00 \n",
+ "[2021-12-23 05:30:00, 2021-12-23 06:00:00) 2021-12-23 06:00:00+00:00 \n",
+ "[2021-12-23 06:00:00, 2021-12-23 06:30:00) 2021-12-23 06:30:00+00:00 \n",
+ "[2021-12-23 06:30:00, 2021-12-23 07:00:00) 2021-12-23 07:00:00+00:00 "
+ ]
+ },
+ "execution_count": 48,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index = hkg.trading_index(start_min, end_min, \"30T\", closed=\"left\", intervals=True)\n",
+ "show_as_df(index)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Final point on passing `start` and/or `end` as times:\n",
+ "\n",
+ "* **If the period is one day then `start` and/or `end` cannot be passed as times.**"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### `Overlapping indices`\n",
+ "\n",
+ "Now, if you've been playing with `trading_index` as you've worked through this tutorial and you've managed to get this far without raising an error, then you just haven't been trying hard enough..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 49,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "IntervalIndex([[2021-12-23 01:30:00, 2021-12-23 03:15:00), [2021-12-23 03:15:00, 2021-12-23 05:00:00), [2021-12-23 05:00:00, 2021-12-23 06:45:00), [2021-12-23 06:45:00, 2021-12-23 08:30:00)], dtype='interval[datetime64[ns, UTC], left]')"
+ ]
+ },
+ "execution_count": 49,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "period_105 = hkg.trading_index(start, start, \"105T\")\n",
+ "period_105"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Just one more minute..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "period_106 = hkg.trading_index(start, start, \"106T\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "```\n",
+ "---------------------------------------------------------------------------\n",
+ "IntervalsOverlapError Traceback (most recent call last)\n",
+ "Input In [50], in ()\n",
+ "----> 1 period_106 = hkg.trading_index(start, start, \"106T\")\n",
+ "\n",
+ "IntervalsOverlapError: Unable to create trading index as intervals would overlap. This can occur when the frequency is longer than a break or the gap between one session's close and the next session's open (as reduced by any alignment). To shorten intervals that would otherwise overlap either pass `curtail_overlaps` as True or pass `force_close` and/or `force_break_close` as True.\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "What happened? The error message pretty much explains it. Lets have a better look at the index with the 105 minutes period."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 51,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 01:30:00, 2021-12-23 03:15:00)
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 03:15:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:15:00, 2021-12-23 05:00:00)
\n",
+ "
2021-12-23 03:15:00+00:00
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 06:45:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 06:45:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:45:00, 2021-12-23 08:30:00)
\n",
+ "
2021-12-23 06:45:00+00:00
\n",
+ "
2021-12-23 08:30:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:15:00) 2021-12-23 01:30:00+00:00 \n",
+ "[2021-12-23 03:15:00, 2021-12-23 05:00:00) 2021-12-23 03:15:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:45:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 06:45:00, 2021-12-23 08:30:00) 2021-12-23 06:45:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:15:00) 2021-12-23 03:15:00+00:00 \n",
+ "[2021-12-23 03:15:00, 2021-12-23 05:00:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:45:00) 2021-12-23 06:45:00+00:00 \n",
+ "[2021-12-23 06:45:00, 2021-12-23 08:30:00) 2021-12-23 08:30:00+00:00 "
+ ]
+ },
+ "execution_count": 51,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "show_as_df(period_105)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "See how the right side of the second indice (the last indice of the morning subsession) has bumped right up against the left side of the third indice (the first indice of the afternoon subsession). The indices don't overlap because all the intervals are all `closed` on the \"left\" (by default), so the exact timestamp '2021-12-23 05:00:00' is present in the third indice..."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 52,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "True"
+ ]
+ },
+ "execution_count": 52,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "pd.Timestamp('2021-12-23 05:00:00', tz=ZoneInfo(\"UTC\")) in period_105[2]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "...but not the second."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 53,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "False"
+ ]
+ },
+ "execution_count": 53,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "pd.Timestamp('2021-12-23 05:00:00', tz=ZoneInfo(\"UTC\")) in period_105[1]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "However, add just one more minute to the period length and these indices overlap, hence the `IntervalsOverlapError`. As noted in the error message, the overlap can be prevented by forcing close on the break."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 54,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 01:30:00, 2021-12-23 03:16:00)
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 03:16:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:16:00, 2021-12-23 04:00:00)
\n",
+ "
2021-12-23 03:16:00+00:00
\n",
+ "
2021-12-23 04:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 06:46:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 06:46:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:46:00, 2021-12-23 08:32:00)
\n",
+ "
2021-12-23 06:46:00+00:00
\n",
+ "
2021-12-23 08:32:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:16:00) 2021-12-23 01:30:00+00:00 \n",
+ "[2021-12-23 03:16:00, 2021-12-23 04:00:00) 2021-12-23 03:16:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:46:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 06:46:00, 2021-12-23 08:32:00) 2021-12-23 06:46:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:16:00) 2021-12-23 03:16:00+00:00 \n",
+ "[2021-12-23 03:16:00, 2021-12-23 04:00:00) 2021-12-23 04:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:46:00) 2021-12-23 06:46:00+00:00 \n",
+ "[2021-12-23 06:46:00, 2021-12-23 08:32:00) 2021-12-23 08:32:00+00:00 "
+ ]
+ },
+ "execution_count": 54,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "show_as_df(hkg.trading_index(start, start, \"106T\", force_break_close=True))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Or, `curtail_overlaps` can be passed as True to curtail overlapping indices. This has the effect of curtailing the right side of the earlier of the overlapping indices to the left side of the latter."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 55,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 01:30:00, 2021-12-23 03:21:00)
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 03:21:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 03:21:00, 2021-12-23 05:00:00)
\n",
+ "
2021-12-23 03:21:00+00:00
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 06:51:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 06:51:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 06:51:00, 2021-12-23 08:42:00)
\n",
+ "
2021-12-23 06:51:00+00:00
\n",
+ "
2021-12-23 08:42:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:21:00) 2021-12-23 01:30:00+00:00 \n",
+ "[2021-12-23 03:21:00, 2021-12-23 05:00:00) 2021-12-23 03:21:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:51:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 06:51:00, 2021-12-23 08:42:00) 2021-12-23 06:51:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 03:21:00) 2021-12-23 03:21:00+00:00 \n",
+ "[2021-12-23 03:21:00, 2021-12-23 05:00:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 06:51:00) 2021-12-23 06:51:00+00:00 \n",
+ "[2021-12-23 06:51:00, 2021-12-23 08:42:00) 2021-12-23 08:42:00+00:00 "
+ ]
+ },
+ "execution_count": 55,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index = hkg.trading_index(start, start, \"111T\", curtail_overlaps=True)\n",
+ "show_as_df(index)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Obviously this has the same effect as forcing the close in so much as the lengths of some indices will now be less than the passed `period`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 56,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/plain": [
+ "TimedeltaIndex(['0 days 01:51:00', '0 days 01:39:00', '0 days 01:51:00',\n",
+ " '0 days 01:51:00'],\n",
+ " dtype='timedelta64[ns]', freq=None)"
+ ]
+ },
+ "execution_count": 56,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "index.length"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "**NB** that `curtail_overlaps` is only available if outputing as an `IntervalIndex` (if `intervals=False` then `curtail_overlaps` has no effect).\n",
+ "\n",
+ "Another option, not noted by the error message, can be to _increase_ the period. "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 57,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "
\n",
+ "\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
\n",
+ "
left_side
\n",
+ "
right_side
\n",
+ "
\n",
+ "
\n",
+ "
IntervalIndex
\n",
+ "
\n",
+ "
\n",
+ "
\n",
+ " \n",
+ " \n",
+ "
\n",
+ "
[2021-12-23 01:30:00, 2021-12-23 04:00:00)
\n",
+ "
2021-12-23 01:30:00+00:00
\n",
+ "
2021-12-23 04:00:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 05:00:00, 2021-12-23 07:30:00)
\n",
+ "
2021-12-23 05:00:00+00:00
\n",
+ "
2021-12-23 07:30:00+00:00
\n",
+ "
\n",
+ "
\n",
+ "
[2021-12-23 07:30:00, 2021-12-23 10:00:00)
\n",
+ "
2021-12-23 07:30:00+00:00
\n",
+ "
2021-12-23 10:00:00+00:00
\n",
+ "
\n",
+ " \n",
+ "
\n",
+ "
"
+ ],
+ "text/plain": [
+ " left_side \\\n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 04:00:00) 2021-12-23 01:30:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 07:30:00) 2021-12-23 05:00:00+00:00 \n",
+ "[2021-12-23 07:30:00, 2021-12-23 10:00:00) 2021-12-23 07:30:00+00:00 \n",
+ "\n",
+ " right_side \n",
+ "IntervalIndex \n",
+ "[2021-12-23 01:30:00, 2021-12-23 04:00:00) 2021-12-23 04:00:00+00:00 \n",
+ "[2021-12-23 05:00:00, 2021-12-23 07:30:00) 2021-12-23 07:30:00+00:00 \n",
+ "[2021-12-23 07:30:00, 2021-12-23 10:00:00) 2021-12-23 10:00:00+00:00 "
+ ]
+ },
+ "execution_count": 57,
+ "metadata": {},
+ "output_type": "execute_result"
+ }
+ ],
+ "source": [
+ "show_as_df(hkg.trading_index(start, start, \"150T\"))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "(I'll leave it to you to work out what happened there.)\n",
+ "\n",
+ "The possibility for overlaps are not limited to calendars with lunch breaks. Overlaps can also occur when the right side of the last indice of one session falls later than the left side of the first indice of the next session (as adjusted for any alignment). For a 24 hour calendar, like CMES, this will occur whenever the period is not a factor of 24 hours."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 58,
+ "metadata": {},
+ "outputs": [
+ {
+ "data": {
+ "text/html": [
+ "