Skip to content

Commit

Permalink
Fix localcontext example to use separate `with statements.
Browse files Browse the repository at this point in the history
  • Loading branch information
brocla authored and BethanyG committed Mar 22, 2024
1 parent a094c4a commit 5d25828
Show file tree
Hide file tree
Showing 4 changed files with 706 additions and 688 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@



# This example shows parens around two `localcontext` context mangers.
# This example shows parens around a `localcontext` context mangers.
# Uses two styles of parens.
"""Calculate the fixed interest rate."""

from decimal import ROUND_DOWN, ROUND_UP, Decimal, localcontext
Expand All @@ -27,15 +28,18 @@ def calc_fixed_rate(spot_price: pd.Series, position_duration: Decimal) -> pd.Ser
# Position duration (in seconds) in terms of fraction of year
# This div should round up
# This replicates div up in fixed point
with (localcontext() as ctx_time,
localcontext() as ctx_rate):
ctx_time.prec = 18
ctx_time.rounding = ROUND_UP

ctx_rate.prec = 12
ctx_rate.rounding = ROUND_DOWN

with (localcontext() as ctx):
ctx.prec = 18
ctx.rounding = ROUND_UP
annualized_time = position_duration / Decimal(60 * 60 * 24 * 365)

# Pandas is smart enough to be able to broadcast with internal Decimal types at runtime
# We keep things in 18 precision here
with (
localcontext() as ctx
):
ctx.prec = 18
ctx.rounding = ROUND_DOWN
fixed_rate = (1 - spot_price) / (spot_price * annualized_time) # type: ignore
return fixed_rate

Expand Down
29 changes: 14 additions & 15 deletions test/example-parencontext-normalization/mapping.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,18 @@
"placeholder_1": "calc_fixed_rate",
"placeholder_2": "spot_price",
"placeholder_3": "position_duration",
"placeholder_4": "ctx_time",
"placeholder_5": "ctx_rate",
"placeholder_6": "prec",
"placeholder_7": "rounding",
"placeholder_8": "annualized_time",
"placeholder_9": "fixed_rate",
"placeholder_10": "main",
"placeholder_11": "args",
"placeholder_12": "in_file",
"placeholder_13": "mode",
"placeholder_14": "out_file",
"placeholder_15": "records",
"placeholder_16": "record",
"placeholder_17": "parse_args",
"placeholder_18": "parser"
"placeholder_4": "ctx",
"placeholder_5": "prec",
"placeholder_6": "rounding",
"placeholder_7": "annualized_time",
"placeholder_8": "fixed_rate",
"placeholder_9": "main",
"placeholder_10": "args",
"placeholder_11": "in_file",
"placeholder_12": "mode",
"placeholder_13": "out_file",
"placeholder_14": "records",
"placeholder_15": "record",
"placeholder_16": "parse_args",
"placeholder_17": "parser"
}
Loading

0 comments on commit 5d25828

Please sign in to comment.