Danil Annenkov
email: danil.annenkov@inria.fr

Martin Elsman

Certified Compilation of Financial Contracts

Keywords: • Theory of computation → Program verification, Logic and verification, • Software and its engineering → Correctness, Domain specific languages, Source code generation, financial contracts, contract languages, domain-specific languages, certified programming, software correctness, Coq

HAL is

Background and Motivation

New technologies are emerging that have potential for seriously disrupting the financial sector. In particular, blockchain technologies, such as Bitcoins [START_REF] Nakamoto | Bitcoin: A peer-to-peer electronic cash system[END_REF] and the Ethereum Smart Contract peer-to-peer platform [START_REF] Wood | Ethereum: A secure decentralised generalised transaction ledger[END_REF], have entered the realm of the global financial market and it becomes essential to ask to which degree users can trust that the underlying implementations are really behaving according to the specified properties. Unfortunately, the answers are not clear and errors may result in irreversible high-impact events.

Contract description languages and payoff languages are used in large scale financial applications [START_REF] Lexifi | Contract description language (MLFi)[END_REF][START_REF] Simcorp | XpressInstruments solutions. Company whitepaper[END_REF], although formalisation of such languages in proof assistants and certified compilation schemes are much less explored.

The work presented here builds on a series of previous work on specifying financial contracts [START_REF] Andersen | Compositional specification of commercial contracts[END_REF][START_REF] Arnold | An algebraic specification of a language for describing financial products[END_REF][START_REF] Frankau | Commercial uses: Going functional on exotic trades[END_REF][START_REF] Hvitved | A tracebased model for multiparty contracts[END_REF][START_REF] Simon | Composing contracts: an adventure in financial engineering (functional pearl)[END_REF] and in particular on a certified financial contract management engine and its associated contract DSL [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF]. This framework allows for expressing a wide variety of financial contracts (a fundamental notion in financial software) and for reasoning about their functional properties (e.g., horizon and causality). As in the previous work, the contract DSL that we consider is equipped with a denotational semantics, which is independent of stochastic aspects and depends only on an external environment ExtEnv : N × Label → R + B, which maps observables (e.g., the price of a stock on a particular day) to values. As the first contribution of this work, we present a certified compilation scheme that compiles a contract into a payoff function, which aggregates all cashflows in the contract, after discounting them according to some model. The result represents a single "snapshot" value of the contract. The payoff language is inspired by traditional payoff languages and is well suited for integration with Monte Carlo simulation techniques for pricing. It is essentially a small expression language featuring arithmetic and boolean operators, a limited form of a looping construct, and enriched with notation for looking up observables in the external environment. We show that compilation from the contract DSL to the payoff language preserves the cashflow semantics.

The contract language described in [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF], deals with concrete contracts, such as a one year European call option on the AAPL (Apple) stock with strike price $100. The lack of genericity means that each time a new contract is created (even a very similar one), the contract management engine needs to compile the contract into the payoff language and further into a target language for embedding into the pricing engine. As our second contribution, we introduce the notion of a financial instrument, which allows for templating of contracts and which can be turned into a concrete contract by instantiating template variables with particular values. For example, an European call option instrument has template parameters such as maturity (the end date of the contract), strike, and the underlying asset that the option is based on. Compiling such a template once allows the engine to reuse compiled code, giving various parameter values as input to the pricing engine.

Moreover, an inherent property of contracts is that they evolve over time. This property is precisely captured by a contract reduction semantics. Each day, a contract becomes a new "smaller" contract, thus, for pricing purposes, contracts need to be recompiled at each time step, resulting in a dramatic compilation time overhead. As a third contribution, we introduce a mechanism allowing for avoiding recompilation in relation to contract evolution. A payoff expression can be parameterised over the current time so that evaluating the payoff code at time 𝑡 gives us the same result (up to discounting) as first advancing the contract to time 𝑡, then compiling it to the payoff code, and then evaluating the result. Most of the payoff languages used in real-world applications require synchronization of the contract and the payoff code once a contract evolves [START_REF] Lexifi | Structuring, Pricing, and Processing Complex Financial Products with MLFi[END_REF]Contract State and Pricing Synchronization]. In some cases, however, as we mentioned earlier, it is important to capture the reduction semantics in the payoff language as well. Our result allows for using a single compilation procedure for both use cases: compiling a contract upfront and synchronizing at each time step.

The contract analyses and the contract transformation procedures form a core code base, which financial software crucially depends on. A certified programming approach using the Coq proof assistant allows us to prove the above desirable properties and to extract certified executable code.

We summarize the contributions of this paper as follows:

• We present an extended domain-specific language for expressing financial contracts, called CL, based on the work by [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF]. The extended contract language features contract templates, also called instruments. The extension allows for parameterisation of contracts with respect to temporal parameters. • Inspired by traditional payoff languages, we develop a payoff intermediate language, which we demonstrate is well-suited for the integration with Monte Carlo simulation techniques. • We use the Coq proof assistant to develop a certified compilation procedure of contract templates into a parameterised payoff intermediate language.

• We further parameterise the compiled payoff expressions with the notion of "current time" allowing for capturing the evolution of contracts with the passage of time. • We develop the proof of an extended soundness theorem in the Coq proof assistant. The theorem establishes a correspondence between the time-parameterised compilation scheme and the contract reduction semantics. • We demonstrate how the parametric payoff code allows for better performance due to avoiding recompilation with the change of parameters.

The Contract Language

The contract language that we consider follows the style of [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF] and is a declarative contract language that allows for expressing contractual agreements among parties regarding immediate and future cash flows between the parties. Contracts may refer to observable values and cash flows may thereby depend on the development of such observables, which may include stock prices, interest rates, and decisions made by parties.

We assume a countably infinite set of program variables, ranged over by v. Moreover, we use n, i, f , and b to range over natural numbers, integers, floating point numbers, and booleans. We use 𝑝 to range over parties and 𝑎 to range over assert symbols (e.g., EUR, USD, and so on). The contract language is given in Figure 1; it follows closely the contract language of [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF], but is extended with template variables. Expressions (𝑒 ∈ Exp) may contain observables, which are interpreted in an external environment. A contract may be empty (zero), a transfer of one unit (for simplicity) (transfer), a scaled contract (scale), a translation of a contract into the future (translate), the composition of two contracts (both), or a generalized conditional ifWithin(𝑐𝑜𝑛𝑑, 𝑡, 𝑐1, 𝑐2), which checks the condition cond repeatedly during the period given by 𝑡 and evaluates to 𝑐1 if cond = true or to 𝑐2 if cond never evaluates to true during the period 𝑡.

The main difference between the original version of the contract language and the version presented here is the introduction of template expressions (t), which, for instance, allows us to write contract templates with the contract maturity as a parameter. This feature requires refined reasoning about the temporal properties of contracts, such as causality. Certain constructs in the original contract language, such as translate(𝑛, 𝑐) and ifWithin(cond, 𝑛, 𝑐1, 𝑐2), are designed such that basic properties of the contract language, including the property of causality, are straightforward to reason about. In particular, the displacement numbers 𝑛 in the above constructs are constant positive numbers. For templating, we refine the constructs to support template expressions in place of positive constants. One of the consequences of adding template variables is that the semantics of contracts now depends also on mappings of template variables in a template environment TEnv : Var → N, which is also the case for many temporal properties of contracts. For example, the type system for ensuring causality of contracts [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF] and the concept of horizon are now parameterized by template environments.

Let us consider a few examples of contracts written in English and expressed in CL.

Example 1. A European option is a contract that gives the owner the right, but not the obligation, to buy or sell an underlying security at a specific price, known as the strike price, on the option's expiration date (investopedia.com).

Let us take the expiration date to be 90 days into the future and set the strike at USD 100. In CL, we can implement the European option contract with the above parameters as follows: This possibility for parameterisation plays well with how users would interact with a contract management system. Contract templates could be exposed to users as so-called instruments, which a user can instantiate to contracts by supplying concrete values for parameters.

We extend the denotational semantics from [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF] to accommodate the idea of template expressions. The semantics for the expression sublanguage stays unchanged, since such expressions do not contain template expressions. That is, the semantics for an expression 𝑒 ∈ Exp in Figure 1 is given by the partial function ℰ 𝑒 : Γ × Env ⇀ 𝜏 . On the other hand, we modify the semantic function for contacts by adding a template environment as an argument:

𝒞 𝑐 : Γ × Env × TEnv ⇀ Trace Trace = N → Trans Trans = Party × Party × Asset → R
As the original contract semantics, it depends on the external environment Env : N × Label → R ∪ B and variable assignments that map each free variable of type 𝜏 to a value in 𝜏 with Real = R and Bool = B. Given a typing environment Γ, the set of variable assignments in Γ, written Γ , is the set of all partial mappings 𝛾 from variable names to R ∪ B such that 𝛾(𝑥) ∈ 𝜏 iff 𝑥 : 𝜏 ∈ Γ. The typing rules also remain the same for expressions and for contracts.

The semantics for template expressions 𝒯 𝑡 : TEnv → N is defined as follows:

𝒯 𝑛 𝛿 = 𝑛 𝒯 𝑣 𝛿 = 𝛿(𝑣)
We modify the semantics of contract constructors that depend on template expressions in such a way that the corresponding template expression is evaluated using 𝒯 -. For example for the translate constructor, we have 𝒞 translate(𝑡, 𝑐) 𝛾,𝜌,𝛿 = delay(𝒯 𝑇 𝛿 , 𝒞 𝑐 𝛾,𝜌,𝛿 )

Where delay : N × Trace → Trace is an operation that delays a given trace by a number of time steps (see [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF]Figure 4]).

We define an instantiation function that takes a contract and a template environment containing values for template variables, and produces another contract that does not contain template variables by replacing all occurrences of template variables with corresponding values from the template environment.

Definition 1 (Instantiation function).

inst :

Contr × TEnv → Contr inst(zero, 𝛿) = zero inst(let 𝑒 in 𝑐, 𝛿) = inst(𝑐, 𝛿) inst(transfer(𝑝1, 𝑝2, a), 𝛿) = transfer(𝑝1, 𝑝2, a) inst(scale(𝑒, 𝑐), 𝛿) = inst(𝑐, 𝛿) inst(translate(𝑡, 𝑐), 𝛿) = translate(𝒯 𝑡 𝛿 , inst(𝑐, 𝛿)) inst(both(𝑐1, 𝑐2), 𝛿) = both(inst(𝑐1, 𝛿), inst(𝑐2, 𝛿)) inst(ifWithin(𝑒, 𝑡, 𝑐1, 𝑐2), 𝛿) = ifWithin(𝑒, 𝒯 𝑡 𝛿 , inst(𝑐1, 𝛿), inst(𝑐2, 𝛿))
We further define an inductive predicate that holds only for contract expressions without template variables (Figure 2). We call such contracts template-closed.

It is straightforward to establish the following fact.

Lemma The reduction semantics of the contract language presented in [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF] remains the same, although, we make additional assumption that the contract expression is closed with respect to template variables.

The Payoff Intermediate Language

The contract language allows for capturing different aspects of financial contracts. We consider a particular use case for the contract language, where one wants to calculate an estimated price of a contract according to some stochastic model by performing simulations. Simulations is often implemented using Monte Carlo techniques, for instance, by evaluating a contract price at current time for randomly generated possible market scenarios and discounting the outcome according to some model. A software component that implements such a procedure is called a pricing engine and aims to be very efficient in performing large amount of calculations by exploiting the parallelism [START_REF] Andreetta | FinPar: A parallel financial benchmark[END_REF]. For this use case, one has to take the following aspects into account:

• Contracts should be represented as simple functions that take prices of assets involved in the contract (randomly generated by a pricing engine) and return one value corresponding to the aggregated outcome of the contract. • The resulting value of the contract should be discounted according to a given discount function.

One way of achieving this would be to implement an interpreter for the contract language as part of a pricing engine. Although this approach is quite general, interpreting a contract in the process of pricing will cause significant performance overhead. Moreover, it will be harder to reason about correctness of the interpreter, since it could require non-trivial encoding in languages targeting GPGPU devices. For that reason we take another approach: translating a contract from CL to an intermediate representation and, eventually, to a function in the pricing engine implementation language. We call this intermediate representation a payoff language and expressions in this language we call payoff expressions.

We would like the payoff language to contain fewer domainspecific features and being closer to a subset of some general purpose language, making a mapping from the payoff language to a target language straightforward. We demonstrate how payoff expressions can be translated to Haskell and Futhark [START_REF] Henriksen | Size slicing: a hybrid approach to size inference in Futhark[END_REF][START_REF] Henriksen | Futhark: Purely functional gpuprogramming with nested parallelism and in-place array updates[END_REF] in Section 6.

il ::= now | model(𝑙, 𝑡) | if(il, il, il) | loopif(il, il, il, 𝑡) | payoff(𝑡, 𝑝, 𝑝) | unop(il) | binop(il, il) unop ::= neg | not binop ::= add | mult | sub | lt | and | or | . . . 𝑡 ::= 𝑛 | 𝑖 | 𝑣 | tplus(𝑡, 𝑡)
The payoff language is an expression language (il ∈ ILExpr) with binary and unary operations, extended with conditionals and generalized conditionals loopif, behaving similarly to ifWithin. Template expressions (𝑡 ∈ TExprZ) in this language are extensions of the template expressions of the contract language with integer literals and addition.

The semantics of payoff expressions is given in Figure 3. We use the notation 𝒫 = (𝜌, 𝛿, 𝑡0, 𝑡, 𝑑, 𝑝1, 𝑝2) for the vector of arguments to the semantic function. The following notation

𝒫[𝑡0 := 𝑡 ′ 0 ] = (𝜌, 𝛿, 𝑡 ′ 0 , 𝑡, 𝑑, 𝑝1, 𝑝2
) is used to show that the respective argument in the vector receives a certain value. The semantics depends on environments 𝜌 ∈ Env and 𝛿 ∈ TEnv similarly to the semantics of the contract language. Payoff expressions can evaluate to a value of type N, R, or B (in contrast to the contract language for which the semantics is given in terms of traces.). We add N to the semantic domain, because we need to interpret the now construct, which represents the "current time" parameter and template expressions 𝑡 𝑒 . The semantics also depends on a discount function 𝑑 : N → R. The 𝑡0 ∈ N parameter is used to add relative time shifts introduced by the semantics of loopif; 𝑡 is a current time, which will be important later, when we introduce a mechanism to cut payoffs before a certain point in time.

The semantics for unary and binary operations is a straightforward mapping to corresponding arithmetic and logical operations, provided that the arguments have appropriate types. For example, add (𝑣1, 𝑣2)

= 𝑣1 + 𝑣2, if 𝑣1, 𝑣2 ∈ R.
The semantic function ℐℒ -considers only payoffs between two parties 𝑝1 and 𝑝2, which are given as the last two parameters. More precisely, it considers payoffs from party 𝑝1 to party 𝑝2 as positive and as negative, if payoffs go in the opposite direction. Another way of defining the semantics could be a bilateral view on payoffs. In this case only cashflows to or from one fixed party to any other party are considered. Then, the semantics for the payoff construct would be defined as follows:

ℐℒ payoff(𝑡, 𝑝 ′ 1 , 𝑝 ′ 2 ) 𝜌,𝛿,𝑡 0 ,𝑡,𝑑,𝑝 = ⎧ ⎨ ⎩ 𝑑(𝒯 𝑡 𝛿 ) if 𝑝 ′ 2 = 𝑝 -𝑑(𝒯 𝑡 𝛿 ) if 𝑝 ′ 1 = 𝑝 0 otherwise ℐℒ 𝑖𝑙 : Env × TEnv × N × N × (N → R) × Party × Party ⇀ N ∪ R ∪ B 𝒫 = (𝜌, 𝛿, 𝑡0, 𝑡, 𝑑, 𝑝1, 𝑝2) ℐℒ 𝑡 𝑒 𝒫 = 𝒯 𝑡 𝑒 𝛿 + 𝑡0 ℐℒ 𝑢𝑛𝑜𝑝(𝑖𝑙) 𝒫 = 𝑢𝑛𝑜𝑝 (ℐℒ 𝑖𝑙 𝒫 ) ℐℒ 𝑏𝑖𝑛𝑜𝑝(𝑖𝑙0, 𝑖𝑙1) 𝒫 = 𝑏𝑖𝑛𝑜𝑝 (ℐℒ 𝑖𝑙0 𝒫 , ℐℒ 𝑖𝑙1 𝒫 ) ℐℒ model(𝑙, 𝑡 𝑒 ) 𝒫 = 𝜌(𝑙, 𝒯 𝑡 𝑒 𝛿 + 𝑡0) ℐℒ now 𝒫 = 𝑡 ℐℒ 𝑖𝑓 (𝑖𝑙0, 𝑖𝑙1, 𝑖𝑙2) 𝒫 = { ℐℒ 𝑖𝑙1 𝒫 , if ℐℒ 𝑖𝑙0 𝒫 = 𝑡𝑟𝑢𝑒 ℐℒ 𝑖𝑙2, 𝒫 , if ℐℒ 𝑖𝑙0 𝒫 = 𝑓 𝑎𝑙𝑠𝑒 ℐℒ payoff(𝑡 𝑒 , 𝑝 ′ 1 , 𝑝 ′ 2 ) 𝒫 = ⎧ ⎨ ⎩ 𝑑(𝒯 𝑡 𝑒 𝛿 ) if 𝑝 ′ 1 = 𝑝1, 𝑝 ′ 2 = 𝑝2 -𝑑(𝒯 𝑡 𝑒 𝛿 ) if 𝑝 ′ 1 = 𝑝2, 𝑝 ′ 2 = 𝑝1 0 otherwise ℐℒ loopif(𝑖𝑙0, 𝑖𝑙1, 𝑖𝑙2, 𝑡 𝑒 ) 𝒫 = 𝑖𝑡𝑒𝑟(𝒯 𝑡 𝑒 𝛿 , 𝑡0), 𝑤ℎ𝑒𝑟𝑒 𝑖𝑡𝑒𝑟(𝑛, 𝑡 ′ 0 ) = ⎧ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎨ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎪ ⎩ ℐℒ 𝑖𝑙1 𝒫[𝑡 0 :=𝑡 ′ 0 ] , if ℐℒ 𝑖𝑙0 𝒫[𝑡 0 :=𝑡 ′ 0 ] = 𝑡𝑟𝑢𝑒 ℐℒ 𝑖𝑙2 𝒫[𝑡 0 :=𝑡 ′ 0 ] , if ℐℒ 𝑖𝑙0 𝒫[𝑡 0 :=𝑡 ′ 0 ] = 𝑓 𝑎𝑙𝑠𝑒 ∧ 𝑛 = 0 𝑖𝑡𝑒𝑟(𝑛 -1)(𝑡 ′ + 1), if ℐℒ 𝑖𝑙0 𝒫[𝑡 0 :=𝑡 ′ 0 ] = 𝑓 𝑎𝑙𝑠𝑒 ∧ 𝑖 > 0

Compiling Contracts to Payoffs

The contract language consist of two levels, namely constructors to build contracts (𝑐 ∈ Contr) and expressions used in some of these constructors (scale, ifWithin, etc.). We compile both levels into a single payoff language. The compilation functions 𝜏e -: Expr × TExprZ ⇀ ILExpr and 𝜏c -: Contr × TExprZ ⇀ ILExpr are recursively defined on the syntax of expressions and contracts, respectively, taking the starting time 𝑡0 ∈ TExprZ as a parameter.

𝜏e cond(𝑏, 𝑒0, 𝑒1]) 𝑡 0 = if(𝜏e 𝑏 𝑡 0 , 𝜏e 𝑒0 𝑡 0 , 𝜏e 𝑒1 𝑡 0 ) 𝜏e obs(𝑙, 𝑖) 𝑡 0 = model(𝑙, tplus(𝑡0, 𝑖)) 𝜏c transfer(𝑝1, 𝑝2, 𝑎) 𝑡 0 = payoff(𝑡0, 𝑝1, 𝑝2) 𝜏c scale(𝑒, 𝑐) 𝑡 0 = mult(𝜏e 𝑒 𝑡 0 , 𝜏c 𝑐 𝑡 0 ) 𝜏c zero 𝑡 0 = 0 𝜏c translate(𝑡, 𝑐) 𝑡 0 = 𝜏c 𝑐 tplus(𝑡 0 ,𝑡) 𝜏c both(𝑐0, 𝑐1) 𝑡 0 = add(𝜏c 𝑐0 𝑡 0 , 𝜏c 𝑐1 𝑡 0 ) 𝜏c ifWithin(𝑒, 𝑡, 𝑐1, 𝑐2) 𝑡 0 = loopif(𝜏e 𝑒 𝑡 0 , 𝜏c 𝑐0 𝑡 0 , 𝜏c 𝑐1 𝑡 0 , 𝑡) tplus(𝑡1, 𝑡2) = { 𝑡1 + 𝑡2 if 𝑡1, 𝑡2 are numerals tplus(𝑡1, 𝑡2) otherwise
The important point to notice here is that all relative time shifts in an expression in CL are accumulated to the 𝑡0 parameter. The resulting payoff expression only contains lookups in the external environment where time is given explicitly, and does not depend on nesting of time shifts as it was in the case of translate(𝑡, 𝑐) in CL. Such a representation allows for a more straightforward evaluation model. 2 We also would like to emphasise that acc and let constructs are not supported by our compilation procedure. On the supported subset of the contract language, the compilation functions 𝜏e 𝑒 , and 𝜏c 𝑐 are total. We use the smart constructor tplus that adds two integer literals whenever it is possible or returns a syntactic addition expression. This use of smart constructors is useful not only for optimisation purposes; it also allows us to overcome some difficulties in formalisation (see Remark 1 in Section 5).

Example 3. We consider the following contract (t0 and t1 denote template variables): the party "you" transfer to the party "me" 100 USD in t0 days in the future, and after t1 more days "you" transfers to "me" an amount equal to the difference between the current price of the AAPL stock and 100 USD, provided that the price of AAPL is higher then 100 USD (we use infix notation for arithmetic operations to make code more readable). To be able to reason about soundness of the compilation process, one needs to make a connection between the semantics of the two languages. For the expression sublanguage of CL (𝑒 ∈ Exp) we can just compare the values that the original expression and the compiled expression evaluates to. In case of the contract language (𝑐 ∈ Contr) the situation is different, since the semantics of a contract is given in terms of a Trace, and an expression in the payoff intermediate language evaluates to a single value. However, we know that the compiled expression represents the sum of the contract cashflows after discounting.

We assume a function HOR : TEnv × Contr → N that returns a conservative upper bound on the length of a contract. We often write 𝜏e 𝑒 0 = il, or 𝜏c 𝑐 0 = il to emphasise that the compilation function returns some result. The value environment Γ is not relevant for the present development and we will omit it. The compilation function satisfies the following properties:

∑ hor 𝛿 (𝑐) 𝑡=0 𝑑(𝑡) × tr(𝑡)(𝑝1, 𝑝2) = ℐℒ il 𝜌,𝛿,0,0,𝑑,𝑝 1 ,𝑝 2
Theorem 4 makes an assumption that the compiled expression evaluates to some value. We do not develop a type system for our payoff language to ensure this property. Instead, we show that it is sufficient for a contract to be well-typed to ensure that the compiled expression always evaluates to some value (for details, we refer the reader to the typing rules for the contract language in [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF]).

Theorem 5 (Total semantics for compiled contracts). Assume parties 𝑝1 and 𝑝2 and discount function 𝑑 : N → R, well-typed external environment 𝜌 ∈ Env, template environment 𝛿 ∈ TEnv, and typing context Γ. The following two properties hold:

(i) for any 𝑒 ∈ Exp, 𝑡0 ∈ TExprZ, 𝑡 ′ 0 ∈ N, if Γ ⊢ 𝑒 : 𝜏 𝜏e 𝑒 𝑡 0 = 𝑖𝑙, then ∃𝑣, ℐℒ il 𝜌,𝛿,𝑡 ′ 0 ,0,𝑑,𝑝 1 ,𝑝 2 = 𝑣, and 𝑣 ∈ 𝜏 (ii) for any 𝑐 ∈ Contr, 𝑡0 𝑡 ′ 0 , if Γ ⊢ 𝑐 and 𝜏c 𝑐 𝑡 0 = 𝑖𝑙, then
∃𝑣, ℐℒ il 𝜌,𝛿,𝑡 ′ 0 ,0,𝑑,𝑝 1 ,𝑝 2 = 𝑣, and 𝑣 ∈ R Notice that Theorem 5 holds for any 𝑡0 ∈ TExprZ and 𝑡 ′ 0 ∈ N. These parameters do not affect totality of the semantics and can be arbitrary, since we assume that the external environment is total. Theorems 4 and 5 together ensure that our compilation procedure produces a payoff expression that evaluates to a value reflecting the aggregated price of a contract after discounting.

Avoiding recompilation

To avoid recompilation of a contract when time moves forward, we define a function cutPayoff(). This function is defined recursively on the syntax of intermediate language expressions. cutPayoff :

ILExpr → ILExpr cutPayoff(now) = now cutPayoff(model(𝑙, 𝑡)) = model(𝑙, 𝑡) cutPayoff(unop(il)) = unop(cutPayoff(il)) cutPayoff(payoff(𝑡, 𝑝1, 𝑝2)) = if(𝑡 < now, 0, payoff(𝑡, 𝑝1, 𝑝2)) cutPayoff(binop(il1, il2)) = binop(cutPayoff(il1), cutPayoff(il2)) cutPayoff(if(il1, il2, il3)) = if(cutPayoff(il1), cutPayoff(il2), cutPayoff(il3))
The most important case is the case for payoff. The function wraps payoff with a condition guarding whether this payoff affects the resulting value. For the remaining cases, the function recurses on subexpressions and returns otherwise unmodified expressions. Each payoff in the payoff expression is now guarded by the condition, comparing the time of the particular payoff with now. Notice that the templates variables t0 and t1 are mapped to concrete values in the template environment.

To be able to state a soundness property for the cutPayoff() function we again need to find a way to connect it to the semantics of CL. Since cutPayoff() deals with the dynamic behavior of the contract with respect to time, it seems natural to formulate the soundness property in this case in terms of contract reduction ([4, Figure 10]). The semantics of the payoff language takes the "current time" 𝑡 as a parameter. We should be able to connect the 𝑡 parameter to the step of contract reduction.

Theorem 7 (Contract compilation soudness wrt. contract reduction). We assume parties 𝑝1, 𝑝2, discount function 𝑑 : N → R. For any well-typed and template-closed contract 𝑐, i.e., we assume Γ ⊢ 𝑐, and 𝒯𝒞(𝑐), an external environment 𝜌 ′ ∈ Env extending a partial external environment 𝜌 ∈ Envp, if 𝑐 steps to some 𝑐 ′ by the reduction relation 𝑐 𝑇 =⇒𝜌 𝑐 ′ , for some transfer 𝑇 ∈ Trans, such that 𝒞 𝑐 ′ (𝜌 ′ /1),∅ = trace, and 𝜏c 𝑐 0 = 𝑖𝑙, then

hor 𝛿 (𝑐 ′ ) ∑ 𝑡 ′ =0 𝑑(𝑡 ′ + 1) × trace(𝑡 ′ ) = ℐℒ cutPayoff(𝑖𝑙) 𝜌 ′ ,∅,0,1,𝑑,𝑝 1 ,𝑝 2
where 𝜌 ′ /1 denotes the external environment 𝜌 advanced by one time step:

𝜌 ′ /1 = 𝜆(𝑙, 𝑖). 𝜌 ′ (𝑙, 𝑖 + 1), 𝑙 ∈ Label, 𝑖 ∈ Z
From the contract pricing perspective, the partial external environment 𝜌 contains historical data (e.g., historical stock quotes) and the extended environment 𝜌 ′ is a union of the two environments 𝜌 and 𝜌 ′′ , where 𝜌 ′′ contains simulated data, produced by means of simulation in the pricing engine (e.g., using Monte Carlo techniques).

Avoiding recompilation can significantly improve performance especially on GPGPU devices. On the other hand, additional conditionals are introduced, which results in a number of additional checks at run-time. We have investigated the influence on performance of these additional conditions for certain contracts. The results of experiments are given in Section 6.2.

One also might be interested in the following property. The following two ways of using our compilation procedure give identical results:

• first reduce a contract (move time forward), compile it to a payoff expression, then evaluate the payoff expression; • first compile a contract to a payoff expression, apply cutPayoff() to the payoff expression, and then evaluate, specifying the appropriate value for the "current time" parameter.

Let us introduce some notation first. We fix the well-typed external environment 𝜌, the partial environment 𝜌 ′ , which is historically complete (𝜌 ′ (𝑙, 𝑖) is defined for all labels 𝑙 and 𝑖 ≤ 0), and a discount function 𝑑 : N → R. Next, we assume that contracts are well-typed, and closed with respect to template variables, the compilation function is applied to supported constructs only, and that the reduction function, corresponding to the reduction relation, is total on 𝜌 ′ (see [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF]Theorem 11]). This gives us the following total functions:

𝑟𝑒𝑑 𝜌 ′ : Contr → Contr 𝜏c -0 : Contr → ILExpr
These functions correspond to the contract reduction function and the contract compilation function. We also define an evaluation function for compiled payoff expressions as a shortcut for the payoff expression semantics.

evalAt-: N → ILExpr × Env × Disc → R + B evalAt𝑡(𝑒, 𝜌, 𝑑) = ℐℒ 𝑒 𝜌,∅,0,𝑡,𝑑,𝑝 1 ,𝑝 2
for some parties 𝑝1 and 𝑝2. We know by Theorem 5 that evalAt is total on payoff expressions produced by the compilation function from well-typed contracts.

We summarise the property by depicting it as a commuting diagram.

Theorem 8. The following diagram commutes:

Contr Contr ILExpr ILExpr R red 𝜌 ′ cutPayoff ∘ 𝜏c -0 𝜏c -0 evalAt 1 (-,𝜌,𝑑) evalAt 0 (-,𝜌/1,𝑑/1)
Here we write 𝜌/1 and 𝑑/1 for shifted one step external environment and discount function, respectively.

The above diagram gives rise to the following equation:

evalAt1(-, 𝜌, 𝑑) ∘ cutPayoff ∘ 𝜏c -0 = evalAt0(-, 𝜌/1, 𝑑/1) ∘ 𝜏c -0 ∘ red 𝜌 ′
This property shows that our implementation can be used in two different ways. Either a contract is compiled upfront with cutPayoff() or a contract is reduced, at each time of interest, to another contract, which is then compiled to a payoff expression for evaluation. The second use case allows for more flexibility for users. For example, one can develop a system where users define contracts directly in terms of CL working in a specialised IDE. The first case allows for compiling upfront a set of predefined financial instruments (or contract templates) avoiding recompilation when time moves forward. Adding a new instrument is possible, but requires recompilation. The statements of Theorems 7 and 8 generalise in the obvious way to 𝑛-step reduction (by replacing one-step reduction with 𝑛-step reduction, replacing environment shifts from 𝜌/1 to 𝜌/𝑛, and evaluating the compiled payoff expression at 𝑡 = 𝑛 instead of 𝑡 = 1). The crucial step for proving these generalised theorems is to use the following theorem. Theorem 9 expresses soundness of 𝑛-step cutPayoff() evaluation without explicitly mentioning contract reduction and leads to a better proof structure in the Coq formalisation. Intuitively, this theorem says that the sum of the trace starting at 𝑛 instead of zero is exactly the value we obtain after evaluating cutPayoff(𝑖𝑙) at current time 𝑡 = 𝑛.

Theorem 9 combined with the properties of 𝑛-step reduction gives us the proofs of Theorems 7 and 8. Our Coq development (see Section 5) contains a full formalisation of these generalised theorems.

Formalisation in Coq

Our formalisation in Coq3 extends the previous work [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF] by introducing the concept of template expressions and by developing a certified compilation technique for translating contracts to payoff expressions. The required modifications to the denotational semantics have been presented in Section 2. These modifications required us to propagate changes to all the proofs affected by the change of syntax and semantics. We start this section with a description of the original formalisation, and then continue with modifications and additions made by the authors of this work.

The formalisation described in [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF] uses an extrinsic encoding of CL. That means that syntax is represented using Coq's inductive data types, and a typing relation on these raw terms are given separately. For example, the type of the expression sublanguage is defined as follows. One of the design choices in the definition of Exp is to make the constructor of operations OpE take "code" for an operation and the list of arguments. Such an implementation makes adding new operations somewhat easier. Although, we would like to point out that this definition is a nested inductive definition (see [START_REF] Chlipala | Certified Programming with Dependent Types: A Pragmatic Introduction to the Coq Proof Assistant[END_REF]Section 3.8]). In such cases Coq cannot automatically derive a strong enough induction principle, which means that it needs to be defined manually. In the case of Exp it is not hard to see, that one needs to add a generalised induction hypothesis in case of OpE, saying that some predicate holds for all elements in the argument list.

Although the extrinsic encoding requires more work in terms of proving, it has a big advantage for code extraction, since simple inductive data types are easier to use in the Haskell wrapper for CL.

One of the consequences of this encoding is that semantic functions for contracts Contr and expressions Exp are partial, since they are defined on raw terms which may not be welltyped. This partiality is implemented with the Option type, which is equivalent to Haskell's Maybe. To structure the usage of these partial functions, we define the Option monad and use monadic binding of some properties of bind and the lifting functions. These properties include cases for which an expression evaluates to some value.

bind_some : forall (A B : Type) (x : option A) (v : B) (f : A → option B), x >>= f = Some v → exists x' : A, x = Some x' ∧ f x' = Some v Similar lemmas were proved for other functions related to the Option type. To simplify the work with the Option monad, the implementation defines tactics in the Ltac language (part of Coq's infrastructure). The tactics option_inv and option_inv_auto use properties of operations like bind and liftM to invert hypotheses like e = Some v, where 𝑒 contains the aforementioned functions. The implementation uses some tactics from [START_REF] Pierce | Software Foundations. Electronic textbook[END_REF]. Particularly, the tryfalse tactic is widely used. It tries to resolve the current goal by looking for contradictions in assumptions, which conveniently removes impossible cases.

The original formalisation of the contract language has been modified by introducing the type of template expressions Parameter TVar : Set. Inductive TExpr : Set := Tvar (t : TVar) | Tnum (n : nat).

We keep the type of variables abstract and do not impose any restrictions on it. Although one could add decidability of equality for TVar, if required, we do not compare template variables in our formalisation. We modify the definition of the type of contracts Contr such that constructors of expressions related to temporal aspects now accept TExpr instead of nat (If corresponds to ifWithin):

Translate : TExpr → Contr → Contr If : Exp → TExpr → Contr → Contr → Contr.
We leave the other constructors unmodified.

Similarly to how we define an external environment, we define a template environment as a function type TEnv := TVar → nat. Such a definition allows for easier modification of existing code base in comparison with partial mappings. According to the definitions in Section 2, we modify the semantic function for contracts, and the symbolic horizon function, to take an additional parameter of type TEnv. Propagation of these changes was not very problematic and almost mechanical. Because the first attempt to parameterise the reduction relation with a template environment led to some problems, we decided to define the reduction relation only for template-closed contracts. In most cases it is sufficient to instantiate a contract, containing template variables using the instantiation function (Definition 1), and then reduce it to a new contract. Although instantiation requires a template environment containing all the mappings for template variables mentioned in the contract, we do not consider this a big limitation.

The definition of the payoff intermediate language (following Section 4) also uses an extrinsic encoding to represent raw terms as an inductive data type. We define one type for the payoff language expressions ILExpr, since there is no such separation as in CL on contracts and expressions. The definition of template expressions used in the definition of ILExpr is an extended version of the definition of template expressions TExpr used in the contract language definition. Notice that we use two different types of template expressions ILTExpr and ILTExprZ. The former extends the definition of TExpr with the addition operation, and the latter extends it further with integer literals and with the corresponding addition operation (recall that template expressions used in CL can be either natural number literals or variables). The reason why we have to extend TExpr with addition is that we want to accumulate time shifts introduced by Translate in one expression using (syntactic) addition. In the expression sublanguage of CL, observables can refer to the past by negative time indices. For that reason we introduce the ILTExprZ type.

The full definition of syntax for the payoff intermediate language in our Coq formalisation looks as follows: Notice that we use template expressions, which could represent negative numbers (ILTExprZ) in the constructor ILModel. This constructor corresponds to observable values in the contract language and allows for negative time indices corresponding to access of historical data.

We could have generalised our formalisation to deal with different types of template variables and added a simple type system on top of the template expression language, but we decided to keep our implementation simple, since the main goal was to demonstrate that it is possible to extend the original contract language to contract templates with temporal variables.

All the theorems and lemmas described in the paper are completely formalised in our Coq development. We use a limited amount of proof automation in the soundness proofs. The proof automation is used mainly in the proofs related to compilation of the contract expression sublanguage, since compilation is straightforward and proofs are relatively easily to automate. Moreover, without the proof automation, one would have to consider a large number of very similar cases leading to code duplication. In addition to option_inv_auto mentioned above, we use a tactic that helps to get rid of cases where expressions (a source expression in Exp and a target expression in ILEpxr) evaluate to values of different types (denoted by the corresponding constructor). Here the Val and IVal types correspond to values of the contract expression sublanguage and the payoff expression language respectively. The tryfalse tactic searches for the contradictions in the goal (see [START_REF] Pierce | Software Foundations. Electronic textbook[END_REF]).

Another tactic that significantly reduces the complexity of the proofs is the omega tactic from Coq's standard library. This tactic implements a decision procedure for expressions in Presburger arithmetic. That is, goals can be equations or inequations of integers, or natural numbers with addition and multiplication by a constant. The tactic uses assumptions from the current context to solve the goal automatically.

The principle we use in the organisation of the proofs is to use proof automation to solve the most trivial and tedious goals and to be more explicit about the proof structure in cases requiring more sophisticated reasoning.

Remark 1. The first version of the soundness proof was developed for the original contract language without template expressions. The proof was somewhat easier, since the aggregation of nested time shifts introduced by translate(𝑛, 𝑐) constructs during compilation was implemented as addition of natural numbers, corresponding to time shifts. In the presence of template expressions, the compilation function builds a syntactic expression using the tplus constructor. There are some places in proofs where it was crucial to use associativity of addition to prove the goal, but this does not work for template expressions. For example, tplus(tplus(𝑡1, 𝑡2), 𝑡3) is not equal to tplus(𝑡1, tplus(𝑡2, 𝑡3)), because these expressions represent different syntactic trees, although semantically equivalent. Instead of restating proofs in terms of this semantic equivalence (significantly complicating the proofs), we used the following approach. The compilation function uses the smart constructor tplus instead of just plain construction of the template expression. This allowed us to recover the property we needed to complete the soundness proof without altering too much of its structure.

There are a number of aspects that introduce complications to the development of proofs of the compilation properties.

• Accumulation of relative time shifts during compilation.

To obtain a general enough induction hypothesis we have to generalise our lemmas to take as parameter an initial time t0. The same holds for the semantics of loopif, since there is an additional parameter in the semantics to implement iterative behavior. • Presence of template expressions. The complications we faced due to template expressions are described in Remark 1. We have resolved these complications with smart constructors, but template expressions still add some overhead. • Conversion between types of numbers. We use integers and natural numbers (nat and Z type from the standard library of Coq). In some places, including the semantics of template expressions, we use a conversion from natural numbers to integers. This conversion makes automation with the omega tactic more complicated, because it requires first to use the properties of conversion, which is harder to automate. With the accumulation aspect, conversions add even more overhead. • We use the definition of contract horizon in the statement of the soundness theorems, which leads to additional case analysis in proofs.

Code Extraction

The Coq proof assistant allows for extracting Coq functions into programs in some functional languages [START_REF] Letouzey | Extraction in Coq: An overview[END_REF]. The implementation described in [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF] supports code extraction of the contract type checker and contract manipulation functions into the Haskell programming language. We extend the code extraction part of the implementation with features related to contract templates and contract compilation. Particularly, we extract Haskell implementations of the following functions:

• inst_contr function that instantiates a given contract according to given template environment; • fromExp function for compiling the contract expression sublanguage; • fromContr function for compiling contract language constructs; • cutPayoff function for parameterising a payoff expression with the "current time". • ILsem semantic function for payoff expressions, which can be used as an interpreter.

For supporting templates, we have updated the Haskell front end and exposed the full contract language in a convenient form. We have kept the original versions of extended combinators, such as translate and within without changes and added translateT and withinT combinators, which support template variables.

Our implementation contains an extended collection of contract examples, examples of contract compilation, and evaluation of resulting payoff expressions.

Code Generation

To exemplify how the payoff language can be used to produce a payoff function in a subset of some general purpose language, we have implemented a code generation procedure to Haskell and Futhark, as illustrated in the following diagram:

Futhark CL Payoff Language
Haskell We make use of the code extraction mechanism described in Section 5.1 to obtain a certified compilation function, which we use to translate expressions in CL to expressions in the payoff language.

The Haskell Backend

The code generation procedure is (almost) a one-to-one mapping of the payoff language constructs to Haskell expressions. One primitive, which we could not map directly to Haskell build-in functions was the loopif construct. We have solved this issue by implementing loopif as a higher-order function in Haskell. The implementation essentially follows the definition of the semantics of loopif in Coq:

loopif :: Int → Int → (Int → Bool) → (Int → a) → (Int → a) → a loopif n t0 b e1 e2 = let b' = b t0 in case b' of True → e1 t0 False → case n of 0 → e2 t0 _ → loopif (n-1) (t0+1) b e1 e2
The resulting payoff function has the following signature: The external environment and the template environment are represented using Haskell's Data.Map, and Map.! is an infix notation for the lookup function. To obtain the code above we apply a simple optimisation, replacing the loopif with zero as the first argument with the regular if. One could also add more optimisations to our Coq implementation along with proofs of soundness.

A module declaring the payoff function can be used as an ordinary Haskell module as a part of the development requiring the payoff functions. For example, it could be used in the context of the FinPar benchmark [START_REF] Andreetta | FinPar: A parallel financial benchmark[END_REF], which contains a Haskell implementation of pricing among other routines. Moreover, the cutPayoff() function can be used to obtain a parameterised version of a payoff function in Haskell, allowing us to reproduce the contract reduction behavior.

The Futhark Backend

Futhark is a data-parallel functional language for programming nested, regular programs to be executed efficiently on a GPU [START_REF] Henriksen | Size slicing: a hybrid approach to size inference in Futhark[END_REF][START_REF] Henriksen | Futhark: Purely functional gpuprogramming with nested parallelism and in-place array updates[END_REF]. The language has a rich core language, which provides a number of second-order functional array combinators, such as map, reduce, filter, and scan, but it also provides seemingly imperative features, including sequential loops and array updates, which are based on a uniqueness type system that allows for an efficient implementation of functional array updates. On top of the core language, Futhark is enriched with a higher-order module language, for which constructs are compiled away at compile time due to a static interpretation technique.

Generating code for Futhark is quite similar to the code generation approach described for Haskell. With the Futhark backend, however, the aim is to integrate generated payoff functions with an efficient parallel Monte Carlo based pricing engine, which is achieved by making the pricing engine a parameterised module that takes as argument a module containing a payoff-function.

Regarding the particular Futhark payoff function generation, the implementation differs from the Haskell implementation in two ways, namely (i) with respect to the representation of the loopif construct and (ii) with respect to external environment access.

The first difference is related to the fact that Futhark does not support recursive functions, but instead includes various iteration constructs. The payoff language loopif construct is therefore compiled into a Futhark while loop construct. For example, consider the following payoff expression (corresponding to a simple contract with a barrier): The ext variable is a two-dimensional array containing model data (the first index corresponds to time and the second corresponds to an observable), tenv is an array with template parameter values, and disc is an array containing discount factors (indexed by time). The second difference, which is related to the way we work with the model data environment, is concerned with translation of environment indexing to the form used in the FinPar pricing code. For example, we translate time indices 100 and 200 in the following payoff expression payoff(100,X,Y) + payoff(200,X,Y) to 0 and 1 respectively. This reindexing corresponds to the order in which time indices appear in a payoff expression.

The output of the generation procedure is a Futhark module that can be directly passed to the parameterised Futhark pricing engine module. A key feature of the implemented template mechanism combined with the cutPayoff() functionality is that the code base needs to be compiled into efficient GPU code only when new instruments are introduced; the generated payoff expressions are generic with respect to the time at which the price is calculated.

Table 1 shows the timings for pricing three different financial contracts using the FinPar Monte Carlo pricing engine [START_REF] Andreetta | FinPar: A parallel financial benchmark[END_REF]. The contracts include a vanilla European call option, which allows a holder at some time 𝑡 to purchase a particular stock at a predetermined price, and a discrete barrier option, which forces a holder to exercise the option before maturity if any of three particular underlying stocks at certain dates cross certain barrier levels. Finally, the contracts include a double vanilla European option, which allows a holder to exercise any of two European options on two different underlying stocks. The three contracts cover well the possible scope of supported contracts, including the support for dealing with multiple underlyings and multiple measurement days. Moreover, the contracts are instances of real financial contracts appearing in real financial portfolios.

The experiments were executed on a commodity MacBook Pro laptop with a 2.7GHz Intel i7 CPU and an AMD Radeon Pro 460 GPU using futhark-bench, which was configured to report the average runtime of five different runs. Pricing of the Vanilla option is based on 8388608 individual Monte Carlo simulation paths, whereas pricing of the two other contracts is based on 1048576 individual paths. The Fut-C column shows timings for executables generated using futhark-c, the CPU sequential-code compiler for Futhark. The Fut-OpCL and the Fut-OpCL-Cut columns show timings for executables generated with futhark-opencl and with the Fut-OpCL-Cut column providing timings for the case where the cutPayoff() functionality allows for pricing of the contract at different times during the contract's lifetime. The experiments show that for the vanilla European option, a speedup of roughly 310 was achieved comparing the Futhark program compiled into C (and further into x86 machine code) with a version compiled into OpenCL using Futhark's OpenCL backend.

There are a number of observations to draw from the benchmark results. First, notice that the speedup obtained from using the commodity GPU instead of the laptop CPU ranges from a factor of 27 to a factor of 317. 4 Second, notice that the introduction of the cutPayoff() function in the Fut-OpCL-Cut column has neglectable impact on performance. We can therefore conclude that, at least for the contracts represented by the three examples, the template feature makes it possible to avoid recompilation of pricing code and that the generalisation can have a dramatical positive effect on the performance of risk calculations, each of which often consists of thousands of pricing tasks.

Related Work

There is a large body of work related to using domain specific languages for specifying and managing financial contracts [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF][START_REF] Hvitved | A survey of formal languages for contracts[END_REF][START_REF] Hvitved | A tracebased model for multiparty contracts[END_REF][START_REF] Lexifi | Contract description language (MLFi)[END_REF][START_REF] Peyton | How to write a financial contract[END_REF][START_REF] Simon | Composing contracts: an adventure in financial engineering (functional pearl)[END_REF][START_REF] Simcorp | XpressInstruments solutions. Company whitepaper[END_REF] and for specifying financial contract payoff expressions [START_REF] Frankau | Commercial uses: Going functional on exotic trades[END_REF]. Only parts of this work investigate the certification aspects of the devised solutions [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF]. Compared to the previous work, the present work considers how declarative certified contracts can be compiled into generic payoff functions for efficient use in a practical pricing framework. Another line of related work investigates the possibility of implementing financial contracts on distributed ledgers such as blockchains [START_REF] Egelund-Müller | Automated execution of financial contracts on blockchains[END_REF]. Included in this work is work on establishing a certified foundation for executing programs (also called smart contracts) on such architectures [START_REF] Russell | Simplicity: A new language for blockchains[END_REF].

Finally, there is a large body of related work on developing techniques for certifying implementations of programming languages, including the seminal work on CompCert [START_REF] Leroy | Formal certification of a compiler back-end, or: programming a compiler with a proof assistant[END_REF], a fully certified compiler for the C programming language and the verified LLVM project [START_REF] Zhao | Formalizing the llvm intermediate representation for verified program transformations[END_REF], which aims at providing a pluggable toolkit for composing certified LLVM [START_REF] Lattner | Llvm: A compilation framework for lifelong program analysis & transformation[END_REF] compiler phases.

Conclusion

This work extends the certified contract management system of [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF] with template expressions, which allows for drastic performance improvements and reusability in terms of the concept of instruments (i.e., contract templates). We consider a practical application of the declarative contract specifications in the context of contract valuation (i.e., pricing). For the purposes of interacting with pricing engines, we introduce a language for payoff expressions (the payoff intermediate language). We have developed a formalisation of the payoff intermediate language and a certified compilation procedure in Coq. Our approach uses an extrinsic encoding, which allows us to make use of Coq's code extraction feature for obtaining a correct implementation of the compiler function that translates expressions in CL to payoff expressions. We have introduced a parameterisation technique for payoff expressions allowing for capturing contract development over time. The developed technique is consistent with the notion of contract reduction from [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF].

A number of important properties, including soundness of the translation from CL to the payoff language have been proved in Coq. We have exemplified how the payoff intermediate language can be used to generate code in a target language by mapping payoff expressions to a subset of Haskell and Futhark. We have conducted performance measurements with the generated Futhark code in the context of an efficient parallel pricing engine and shown that, for three types of contracts included in the experiment, the template scheme does not significantly influence performance. On the contrary, the template scheme allows for avoiding recompilation caused by changes to an instrument's parameters and by simplification of a contract due to the passage of time.

There are number of possibilities for future work. First, some work is needed for the payoff intermediate language to support the expression-level accumulation functionality from [START_REF] Bahr | Certified symbolic management of financial multi-party contracts[END_REF]. As part of a solution, one may consider generalising the somewhat ad-hoc loopif construct and, instead, provide a more general language construct for iteration, which could involve compiling ifWithin to a combination of iteration and conditions (resulting in simpler target code generation).

Second, the representation of traces as functions N → Trans is equivalent to infinite streams of transfers. It would be interesting to explore this idea of using streams further, since observable values also can be naturally represented as streams.

Finally, a possibility for future work is to formalise further the infrastructure for working with external environment representations. For instance, the reindexing scheme used in our Futhark backend for accessing the external environment is currently considered trusted code in the same way as the Futhark pretty printing.

𝑐∈

  Contr ::= zero | transfer(𝑝1, 𝑝2, 𝑎) | scale(𝑒, 𝑐) | translate(𝑡, 𝑐) | ifWithin(𝑒, 𝑡, 𝑐1, 𝑐2) | both(𝑐, 𝑐) 𝑒 ∈ Exp ::= 𝑜𝑝(𝑒1, 𝑒2, . . . , 𝑒𝑛) | obs(𝑙, 𝑖) | 𝑓 | 𝑏 𝑡 ∈ TExp ::= 𝑛 | 𝑣 𝑜𝑝 ∈ Op ::= add | sub | mult | lt | neg | cond | . . .

Figure 1 :

 1 Figure 1: Syntax of contracts, contracts expressions, and template expressions.

Figure 3 :

 3 Figure 3: Semantics of payoff expressions.

Theorem 4 (

 4 Soundness). Assume parties 𝑝1 and 𝑝2 and discount function 𝑑 : N → R, environments 𝜌 ∈ Env, and 𝛿 ∈ TEnv. (i) If 𝜏e 𝑒 0 = il and ℰ 𝑒 𝜌,𝛿 = 𝑣1 and ℐℒ il 𝜌,𝛿,0,0,𝑑,𝑝 1 ,𝑝 2 = 𝑣2 then 𝑣1 = 𝑣2. (ii) If 𝜏c 𝑐 0 = il and 𝒞 𝑐 𝜌,𝛿 = tr, where tr : N → Party × Party → R then

Example 6 .

 6 Let us consider Example 3 again and apply the cutPayoff() function to the expression e: cutPayoff(e) = (100.0 * disc(t0) * if(t0 < now, 0, payoff(you,me)) + if (model(AAPL,t0+t1) > 100.0, (model(AAPL,t0+t1) -100.0) * disc(t0+t1) * if(t1+t0 < now, 0, payoff(you,me)), 0.0)

Theorem 9 (

 9 Soundness of cutPayoff() for 𝑛 time steps). Assume parties 𝑝1 and 𝑝2, a discount function 𝑑 : N → R, and a well-typed external environment 𝜌 ∈ Env. For any well-typed and template-closed contact 𝑐 at a time step 𝑛 ∈ N, if 𝜏c 𝑐 0 = il and 𝒞 𝑐 𝜌,∅ = tr then ∑ hor 𝛿 (𝑐) 𝑡=𝑛 𝑑(𝑡) × tr(𝑡)(𝑝1, 𝑝2) = ℐℒ cutPayoff(𝑖𝑙) 𝜌,∅,0,𝑛,𝑑,𝑝 1 ,𝑝 2

  Inductive Exp : Set := OpE (op : Op) (args : list Exp) | Obs (l : ObsLabel) (i : Z) | VarE (v : Var) | Acc (f : Exp) (d : nat) (e : Exp).

  bind : forall A B : Type, option A → (A → option B) → option B to compose calls of partial functions together. The functions liftM: forall A B : Type, (A → B) → option A → option B liftM2 : forall A B C : Type, (A → B → C) → option A → option B → option C liftM3 : forall A B C D : Type, (A → B → C → D) → option A → option B → option C → option D allow for a total function of one, two, or three arguments to be lifted to the Option type. The implementation includes poofs generating Haskell and Futhark code along with the pricing engine implementation in Futhark for benchmarking.

  Inductive ILTExpr : Set := ILTplus (e1 : ILTExpr) (e2 : ILTExpr) | ILTexpr (e : TExpr). Inductive ILTExprZ : Set := ILTplusZ (e1 : ILTExprZ) (e2 : ILTExprZ) | ILTexprZ (e : ILTExpr) | ILTnumZ (z : Z).

  Inductive ILExpr : Set := | ILIf : ILExpr → ILExpr → ILExpr → ILExpr | ILFloat : R → ILExpr | ILNat : nat → ILExpr | ILBool : bool → ILExpr | ILtexpr : ILTExpr → ILExpr | ILNow : ILExpr | ILModel : ObsLabel → ILTExprZ → ILExpr | ILUnExpr : ILUnOp → ILExpr → ILExpr | ILBinExpr : ILBinOp → ILExpr → ILExpr → ILExpr | ILLoopIf : ILExpr → ILExpr → ILExpr → TExpr → ILExpr | ILPayoff : ILTExpr → Party → Party → ILExpr.

  Ltac destruct_vals := repeat (match goal with | [x : Val |-_] ⇒ destruct x; tryfalse | [x : ILVal |-_] ⇒ destruct x; tryfalse end).

payoff : :

 : Map. Map ([ Char], Int) Double → Map.Map [Char] Int → Int → Party → Party → Double That is, the function takes as parameters an external environment, a template environment, the current time, and two parties. The payoff function calls the payoffInternal function, which takes an additional parameter-an initial value for the loopif function, which serves as a loop counter. Example 10. We apply the code generation procedure to the expression e from Example 3. Here is the result of code generation: module Examples.PayoffFunction where import qualified Data.Map as Map import BaseTypes import Examples.BasePayoff payoffInternal ext tenv t0 t_now p1 p2 = (100.0 * (if (X== p1 && Y== p2) then 1 else if (X== p2 && Y== p1) then -1 else 0)) + (if ((100.0 < (ext Map.! ("AAPL",(0 + (tenv Map.! "t1") + (tenv Map.! "t0") + 0+ t0))))) then (((( ext Map.! ("AAPL",(0 + (tenv Map.! "t1") + (tenv Map.! "t0") + 0+ t0))) * 100.0) * (if (X== p1 && Y== p2) then 1 else if (X== p2 && Y== p1) then -1 else 0))) else 0.0) payoff ext tenv t_now p1 p2 = payoffInternal ext tenv 0 t_now p1 p2

  loopif(model("AAPL", 0) <= 4000.0, 0.0, 2000.0 * payoff(0,X,Y), t)This payoff expression is translated into the following fragment of Futhark code: let payoffInternal(ext : [][] f32, tenv : [] i32, disc : [] f32, t0 : i32, t_now : i32) : f32 = let t0 = loop t0 = t0 while (!( ext[ t0,0] <= 4000.0) && (t0 < tenv[0])) do t0+1 in if (ext[ t0,0] <= 4000.0) then 0.0 else (2000.0 * disc[ t0]) let payoff ext tenv t_now = payoffInternal(ext,tenv,0,t_now)

  Example 2. A Three month FX swap for which the payment schedule has been settled is easily expressed in CL:

	translate(90,
	if(obs(AAPL,0) > 100.0,
	scale(obs(AAPL,0) -100.0, transfer(you, me, USD)),
	zero))

scale(1.000.000, both( all[translate(22, transfer(me, you, EUR)), translate(52, transfer(me, you, EUR)), translate(83, transfer(me, you, EUR))], scale(7.21, all[translate(22, transfer(you, me, DKK)), translate(52, transfer(you, me, DKK)), translate(83, transfer(you, me, DKK))])))

Figure 2: Template-closed contracts.

  template environments 𝛿 and 𝛿 ′ , external environment 𝜌, and any value environment 𝛾, the contract 𝑐 and inst(𝑐, 𝛿) are semantically equivalent. That is, 𝒞 𝑐 𝛾,𝜌,𝛿 = 𝒞 inst(𝑐, 𝛿) 𝛾,𝜌,𝛿 ′ .

			𝒯𝒞(𝑐)
		𝒯𝒞(𝑐)
	𝒯𝒞(zero)	𝒯𝒞(let 𝑒 in 𝑐)	𝒯𝒞(transfer(𝑝1, 𝑝2, a))
		𝒯𝒞(𝑐)	𝑛 is a numeral	𝒯𝒞(𝑐)
	𝒯𝒞(scale(𝑒, 𝑐))		translate(𝑛, 𝑐)
	𝒯𝒞(𝑐1)	𝒯𝒞(𝑐2)	𝑛 is a numeral	𝒯𝒞(𝑐1)	𝒯𝒞(𝑐2)
	𝒯𝒞(both(𝑐1, 𝑐2))	𝒯𝒞(ifWithin(𝑒, 𝑛, 𝑐1, 𝑐2))
	Lemma 2 (Instantiation soundness). For any con-
	tract 𝑐,
						1. For any contract 𝑐 and template environment
						𝛿, application of the instantiation function gives a template-
						closed contract:
						𝒯𝒞(inst(𝑐, 𝛿))

  As one can see, all nested occurrences of the translate construct were accumulated from top to bottom. That is, in the if case, we calculate payoffs and lookup for values of the AAPL stock at time (t0+t1).

	c =
	translate(t0,
	both(scale(100.0, transfer(you,me)),
	translate(t1,
	if(obs(AAPL,0) > 100.0,
	scale(obs(AAPL,0) -100.0, transfer(you, me)),
	zero)))
	This contract compiles to the following code in the payoff
	intermediate language:
	e =
	(100.0 * payoff(t0,you,me)) +
	if (model(AAPL,t0+t1) > 100.0,
	(model(AAPL,t0+t1) -100.0) * payoff(t0+t1,you,me),
	0.0)

Table 1 : Price timings in milliseconds. The measure- ments show the time it takes to price three dif- ferent financial contracts using the FinPar Monte Carlo based generic pricing. The Fut-C column spec- ifies sequential performance and the Fut-OpCL and the Fut-OpCL-Cut specify parallel performance with the Fut-OpCL-Cut column showing timings with the

 1 cutPayoff() functionality enabled.

		Fut-C Fut-OpCL Fut-OpCL-Cut
	Vanilla option 6,779.4ms	21.4ms	21.7ms
	Barrier option 1,521.7ms	54.7ms	55.1ms
	Double option	983.0ms	12.4ms	12.3ms

In our implementation, we focus on contract templates allowing for template expressions to represent temporal parameters, such as maturity. Other parameters, such as a strike, can be expressed as constant observable values.

The loopif construct still introduces relative time shifts similarly to ifWithin. This makes code generation in a target language less trivial. Potentially, it is possible to decompose loopif into an iteration and a conditional expression. Also, in the case when number of iterations of loopif is a number and not a template variable, it is possible to completely unroll loopif into nested conditional expressions, making all the indexing into the external environment explicit.

The formalisation presented in this paper is available online: https:// github.com/annenkov/contracts. The repository includes the backends

The multi-underlying nature of the non-vanilla contracts results in smaller speedups relative to the vanilla case due to the complexity and the sequential dependencies involved in dealing with correlations between underlyings.

Acknowledgments

This research has been partially supported by the Danish Strategic Research Council, Program Committee for Strategic Growth Technologies, for the research center "HIPERFIT: Functional High Performance Computing for Financial Information Technology" (http://hiperfit.dk) under contract number 10-092299 and by the CoqHoTT ERC Grant 637339. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the authors and do not necessarily reflect the views of the Danish Strategic Research Council.