Showing posts with label XmlSerializer. Show all posts
Showing posts with label XmlSerializer. Show all posts

Friday, May 11, 2018

C++/CLI Interoperability : Using QuantLib in C#, part II


This post is just a recap, which summarizes the content of two previous posts, published in here and here. It is presenting one possible solution for processing XML-based transactions by using QuantLib C++ native library, via C++/CLI wrapper in C# client. In order to implement the scheme presented here, all instructions given in those above-mentioned posts should be followed carefully.

Pipeline


Even the fanciest restaurant needs to have dedicated staff to visit fresh market and peel potatoes, in order to have everything ready for head chef to prepare delicious late night dinners for us. Similarly, having a "state-of-the-art" analytics library (such as QuantLib) available for calculations is still only "halfway home", since all required data inputs (ex. transactions) need to be constructed beforehand. It is highly preferred for this part of the process to be performed in a way, that maximum re-configurability would be maintained, while manual labour would be completely avoided.

In a nutshell, this post will present, how to go from having several XML transaction configuration files (such as the one example presented below) in a directory

<ZeroCouponBond>
  <transactionType>ZeroCouponBond</transactionType>
  <transactionID>DBS.1057</transactionID>
  <faceAmount>1000000</faceAmount>
  <tradeDate>2018-05-07T00:00:00</tradeDate>
  <settlementDate>2018-05-09T00:00:00</settlementDate>
  <maturityDate>2048-12-16T00:00:00</maturityDate>
  <calendar>SINGAPORE.SGX</calendar>
  <paymentConvention>MODIFIEDFOLLOWING</paymentConvention>
</ZeroCouponBond>

to have all these transactions constructed and processed through QuantLib. Console print below is showing 31 such constructed and processed dummy zero-coupon bond transactions.























C# project


Client

The story here goes roughly as follows. Create QuantLib::FlatForward [Wrapper.QlFlatForward] curve and QuantLib::DiscountingBondEngine [Wrapper.QlDiscountingBondEngine] instances by using C++/CLI wrapper classes. After this, all transactions will be created by Builder.TransactionsBuilder from specific directory, by using XML de-serialization. Instances of QuantLib::ZeroCouponBond [Wrapper.QlZeroCouponBond] objects will be created and paired with existing pricing engine (DiscountingBondEngine). Finally, PV for each transaction will be processed by pricing engine and resulting PV attribute will be stored back to transaction. Resulting information will also being printed back to console.

namespace Client {
    
    using Wrapper;
    using Builder;
    using Library;

    static class Program {
        static void Main(string[] args) {

            try {

                // use C++/CLI wrapper : create QuantLib::FlatForward as discounting curve
                double riskFreeRate = 0.015;
                string dayCounter = "ACTUAL360";
                DateTime settlementDate = new DateTime(2018, 5, 9);
                QlFlatForward discountingCurve = new QlFlatForward(riskFreeRate, dayCounter, settlementDate);

                // use C++/CLI wrapper : create QuantLib::DiscountingBondEngine for pricing
                QlDiscountingBondEngine pricer = new QlDiscountingBondEngine(discountingCurve);

                // use builder to create transactions from directory
                var transactions = TransactionsBuilder.Build();

                // use C++/CLI wrapper : create QuantLib::ZeroCouponBond instruments to list
                var zeroCouponBonds = transactions
                    .Where(t => t.transactionType == "ZeroCouponBond")
                    .Select(t => new QlZeroCouponBond(
                        t.faceAmount, 
                        t.tradeDate, 
                        t.settlementDate,
                        t.maturityDate, 
                        t.calendar, 
                        t.paymentConvention))
                    .ToList<QlZeroCouponBond>();

                // use C++/CLI wrapper : pair created bonds with pricing engine
                zeroCouponBonds.ForEach(z => z.SetPricingEngine(pricer));

                // use C++/CLI wrapper : assign processed pv attributes to transactions
                for(int i = 0; i < zeroCouponBonds.Count; i++) {
                    transactions[i].PV = zeroCouponBonds[i].PV();
                }

                // print information on transactions
                transactions.ForEach(t => {
                    string message = String.Format("ID:{0, -15} Maturity:{1, -15} PV:{2, -10}", 
                        t.transactionID,
                        t.maturityDate.ToShortDateString(),
                        String.Format("{0:0,0}", t.PV));
                    Console.WriteLine(message);
                });

                zeroCouponBonds.ForEach(z => GC.SuppressFinalize(z));
                GC.SuppressFinalize(discountingCurve);
                GC.SuppressFinalize(pricer);

            } 
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
    }

}

Library


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
 
namespace Library {

    // abstract base class for all transaction types
    // storing only properties common for all transactions
    public abstract class Transaction {

        // no de-serialization for pv attribute
        private double pv;
        public double PV { get { return pv; } set { pv = value; } }

        public string transactionType;
        public string transactionID;

        // default ctor, required for serialization
        public Transaction() {
        }

        // parameter ctor
        public Transaction(string transactionType, string transactionID) {
            this.transactionType = transactionType;
            this.transactionID = transactionID;
        }

    }

    // class for hosting zero-coupon bond term sheet information
    public class ZeroCouponBond : Transaction {

        public double faceAmount;
        public DateTime tradeDate;
        public DateTime settlementDate;
        public DateTime maturityDate;
        public string calendar;
        public string paymentConvention;

        public ZeroCouponBond()
            : base() {
            // required ctor for serialization
        }

        public ZeroCouponBond(string transactionType, string transactionID,
            double faceAmount, DateTime tradeDate, DateTime settlementDate,
            DateTime maturityDate, string calendar, string paymentConvention)
            : base(transactionType, transactionID) {

            this.faceAmount = faceAmount;
            this.tradeDate = tradeDate;
            this.settlementDate = settlementDate;
            this.maturityDate = maturityDate;
            this.calendar = calendar;
            this.paymentConvention = paymentConvention;
        }

    }

}

Builder

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;

namespace Builder {

    public static class SerializerFactory {
        // create generic de-serializer instance from a given transaction type string
        public static dynamic Create(string transactionType) {
            // note : required type string ("Namespace.Classname") is received without namespace string
            Type t = typeof(TransactionSerializer<>).MakeGenericType(Type.GetType(String.Format("Library.{0}", transactionType)));
            return Assembly.GetAssembly(t).CreateInstance(t.FullName);
        }
    }

    // de-serialize given xml file to transaction of type T
    public class TransactionSerializer<T> {
        public T Create(string transactionFilePathName) {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            FileStream stream = File.OpenRead(transactionFilePathName);
            return (T)serializer.Deserialize(stream);
        }
    }

    public static class TransactionsBuilder {

        // return list of transaction instances, de-serialized from xml files 
        public static List<dynamic> Build() {

            // create configurations
            // NOTE : use environmental variable in path construction
            string configurationsFilePathName =
                Path.Combine(Environment.GetEnvironmentVariable("CONFIGURATIONS").ToString(), "configurations.xml");
            XmlDocument configurations = new XmlDocument();
            configurations.Load(configurationsFilePathName);
            string transactionsDirectory =
                configurations.SelectSingleNode("Configurations/TransactionsFilePathName").InnerText.ToString();

            // create transaction file names and empty list for storing transaction instances
            string[] transactionFiles = Directory.GetFiles(transactionsDirectory);
            List<dynamic> transactions = new List<dynamic>();

            // loop through transaction file names
            foreach(string transactionFile in transactionFiles) {

                // create transaction xml file
                XmlDocument transactionXMLDocument = new XmlDocument();
                transactionXMLDocument.Load(transactionFile);

                // investigate transaction type inside file
                string transactionType = (transactionXMLDocument.DocumentElement)["transactionType"].InnerText.ToString();

                // use factory class for creating correct de-serializer
                dynamic factory = SerializerFactory.Create(transactionType);

                // use de-serializer to create transaction instance
                dynamic transaction = factory.Create(transactionFile);
                transactions.Add(transaction);
            }
            return transactions;
        }

    }
}



C++/CLI project


Header file

Note, that in this C++/CLI example project it is assumed, that DiscountingBondEngine is always used for pricing ZeroCouponBond. Moreover, it is assumed, that pricing engine is always using FlatForward term structure for valuation purposes. Needless to say, these assumptions are used here purely for brevity reasons. It is possible to create class hierarchies in C++/CLI wrapper for instruments, pricing engines and term structures. Such scheme would then enable the usage of more realistic valuation scheme, in which client (C# program) would be able to select desired type for valuation curve and pricing engine for some specific instrument.

Moreover, there is currently only one constructor implementation given for each of the classes. In reality, there are always several ways to create these objects (curve, engine, instrument) in QuantLib.

Finally, there is QuantLibConversion namespace, which offers set of static functions for handling different type conversions between C# types and QuantLib types. Needless to say, there are several ways to implement such type conversion scheme, but (IMHO) implementing TypeConverter would have been a bit overkill for this purpose.

// Wrapper.h
#include "QuantLibLibrary.h"
using namespace System;

namespace Wrapper {

 // class for wrapping native QuantLib::FlatForward
 public ref class QlFlatForward {
 public:
  FlatForward* curve_;

  QlFlatForward(double riskFreeRate, String^ dayCounter, DateTime settlementDate);
  ~QlFlatForward();
  !QlFlatForward();
 };


 // class for wrapping native QuantLib::DiscountingBondEngine
 public ref class QlDiscountingBondEngine {
 public:
  DiscountingBondEngine* pricer_;

  QlDiscountingBondEngine(QlFlatForward^ flatForward);
  ~QlDiscountingBondEngine();
  !QlDiscountingBondEngine();
 };


 // class for wrapping native QuantLib::ZeroCouponBond
 public ref class QlZeroCouponBond {
 public:
  ZeroCouponBond* bond_;

  QlZeroCouponBond(double faceAmount,
   DateTime transactionDate,
   DateTime settlementDate,
   DateTime maturityDate,
   String^ calendar,
   String^ paymentConvention);
  ~QlZeroCouponBond();
  !QlZeroCouponBond();

  double PV();
  void SetPricingEngine(QlDiscountingBondEngine^ engine);

 };


}


namespace QuantLibConversions {
 
 // one static class for all QuantLib-related type conversions
 public ref class Convert abstract sealed {
 public:

  // convert System.String to QuantLib.DayCounter class
  static DayCounter ToDayCounter(String^ dayCounterString);

  // convert System.DateTime to QuantLib.Date class
  static Date ToDate(DateTime dateTime);

  // convert System.String to QuantLib.Calendar class
  static Calendar ToCalendar(String^ calendarString);

  // convert System.String to QuantLib.BusinessDayConvention enumerator
  static BusinessDayConvention ToBusinessDayConvention(String^ businessDayConventionString);

 };

}

Implementation file

// Wrapper.cpp
#pragma once
#include "Wrapper.h"

namespace Wrapper {
 using Ql = QuantLibConversions::Convert;


 // implementations for yield curve class
 QlFlatForward::QlFlatForward(double riskFreeRate, String^ dayCounter, DateTime settlementDate) {

  DayCounter dayCounter_ = Ql::ToDayCounter(dayCounter);
  Date settlementDate_ = Ql::ToDate(settlementDate);
  Handle<Quote> riskFreeRateHandle_(boost::make_shared<SimpleQuote>(riskFreeRate));
  curve_ = new FlatForward(settlementDate_, riskFreeRateHandle_, dayCounter_);
 }

 QlFlatForward::~QlFlatForward() {
  this->!QlFlatForward();
 }

 QlFlatForward::!QlFlatForward() {
  delete curve_;
 }



 // implementations for zero bond class
 QlZeroCouponBond::QlZeroCouponBond(double faceAmount,
  DateTime transactionDate,
  DateTime settlementDate,
  DateTime maturityDate,
  String^ calendar,
  String^ paymentConvention) {

  Date transactionDate_ = Ql::ToDate(transactionDate);
  Date settlementDate_ = Ql::ToDate(settlementDate);
  Date maturityDate_ = Ql::ToDate(maturityDate);

  Calendar calendar_ = Ql::ToCalendar(calendar);
  BusinessDayConvention paymentConvention_ = Ql::ToBusinessDayConvention(paymentConvention);
  Natural settlementDays_ = settlementDate_ - transactionDate_;
  bond_ = new ZeroCouponBond(settlementDays_, calendar_, faceAmount, maturityDate_, paymentConvention_);
 }

 QlZeroCouponBond::~QlZeroCouponBond() {
  this->!QlZeroCouponBond();
 }

 QlZeroCouponBond::!QlZeroCouponBond() {
  delete bond_;
 }

 double QlZeroCouponBond::PV() {
  return bond_->NPV();
 }

 void QlZeroCouponBond::SetPricingEngine(QlDiscountingBondEngine^ engine) {
  bond_->setPricingEngine(static_cast<boost::shared_ptr<DiscountingBondEngine>>(engine->pricer_));
 }



 // implementations for zero pricer class
 QlDiscountingBondEngine::QlDiscountingBondEngine(QlFlatForward^ flatForward) {
  
  Handle<YieldTermStructure> discountCurveHandle(static_cast<boost::shared_ptr<FlatForward>>(flatForward->curve_));
  pricer_ = new DiscountingBondEngine(discountCurveHandle);
  Settings::instance().evaluationDate() = flatForward->curve_->referenceDate();
 }

 QlDiscountingBondEngine::~QlDiscountingBondEngine() {
  this->!QlDiscountingBondEngine();
 }

 QlDiscountingBondEngine::!QlDiscountingBondEngine() {
  delete pricer_;
 }


}


namespace QuantLibConversions {

 DayCounter Convert::ToDayCounter(String^ dayCounterString) {
  if (dayCounterString->ToUpper() == "ACTUAL360") return Actual360();
  if (dayCounterString->ToUpper() == "THIRTY360") return Thirty360();
  if (dayCounterString->ToUpper() == "ACTUALACTUAL") return ActualActual();
  if (dayCounterString->ToUpper() == "BUSINESS252") return Business252();
  if (dayCounterString->ToUpper() == "ACTUAL365NOLEAP") return Actual365NoLeap();
  if (dayCounterString->ToUpper() == "ACTUAL365FIXED") return Actual365Fixed();
  // requested day counter not found, throw exception
  throw gcnew System::Exception("undefined daycounter");
 }

 Date Convert::ToDate(DateTime dateTime) {
  // Date constructor using Excel dateserial
  return Date(dateTime.ToOADate());
 }

 Calendar Convert::ToCalendar(String^ calendarString) {
  if (calendarString->ToUpper() == "ARGENTINA.MERVAL") return Argentina(Argentina::Market::Merval);
  if (calendarString->ToUpper() == "AUSTRALIA") return Australia();
  if (calendarString->ToUpper() == "BRAZIL.EXCHANGE") return Brazil(Brazil::Market::Exchange);
  if (calendarString->ToUpper() == "BRAZIL.SETTLEMENT") return Brazil(Brazil::Market::Settlement);
  if (calendarString->ToUpper() == "CANADA.SETTLEMENT") return Canada(Canada::Market::Settlement);
  if (calendarString->ToUpper() == "CANADA.TSX") return Canada(Canada::Market::TSX);
  if (calendarString->ToUpper() == "CHINA.IB") return China(China::Market::IB);
  if (calendarString->ToUpper() == "CHINA.SSE") return China(China::Market::SSE);
  if (calendarString->ToUpper() == "CZECHREPUBLIC.PSE") return CzechRepublic(CzechRepublic::Market::PSE);
  if (calendarString->ToUpper() == "DENMARK") return Denmark();
  if (calendarString->ToUpper() == "FINLAND") return Finland();
  if (calendarString->ToUpper() == "GERMANY.SETTLEMENT") return Germany(Germany::Market::Settlement);
  if (calendarString->ToUpper() == "GERMANY.FRANKFURTSTOCKEXCHANGE") return Germany(Germany::Market::FrankfurtStockExchange);
  if (calendarString->ToUpper() == "GERMANY.XETRA") return Germany(Germany::Market::Xetra);
  if (calendarString->ToUpper() == "GERMANY.EUREX") return Germany(Germany::Market::Eurex);
  if (calendarString->ToUpper() == "GERMANY.EUWAX") return Germany(Germany::Market::Euwax);
  if (calendarString->ToUpper() == "HONGKONG.HKEX") return HongKong(HongKong::Market::HKEx);
  if (calendarString->ToUpper() == "INDIA.NSE") return India(India::Market::NSE);
  if (calendarString->ToUpper() == "INDONESIA.BEJ") return Indonesia(Indonesia::Market::BEJ);
  if (calendarString->ToUpper() == "INDONESIA.IDX") return Indonesia(Indonesia::Market::IDX);
  if (calendarString->ToUpper() == "INDONESIA.JSX") return Indonesia(Indonesia::Market::JSX);
  if (calendarString->ToUpper() == "ISRAEL.SETTLEMENT") return Israel(Israel::Market::Settlement);
  if (calendarString->ToUpper() == "ISRAEL.TASE") return Israel(Israel::Market::TASE);
  if (calendarString->ToUpper() == "ITALY.EXCHANGE") return Italy(Italy::Market::Exchange);
  if (calendarString->ToUpper() == "ITALY.SETTLEMENT") return Italy(Italy::Market::Settlement);
  if (calendarString->ToUpper() == "JAPAN") return Japan();
  if (calendarString->ToUpper() == "MEXICO.BMV") return Mexico(Mexico::Market::BMV);
  if (calendarString->ToUpper() == "NEWZEALAND") return NewZealand();
  if (calendarString->ToUpper() == "NORWAY") return Norway();
  if (calendarString->ToUpper() == "POLAND") return Poland();
  if (calendarString->ToUpper() == "ROMANIA") return Romania();
  if (calendarString->ToUpper() == "RUSSIA.MOEX") return Russia(Russia::Market::MOEX);
  if (calendarString->ToUpper() == "RUSSIA.SETTLEMENT") return Russia(Russia::Market::Settlement);
  if (calendarString->ToUpper() == "SAUDIARABIA.TADAWUL") return SaudiArabia(SaudiArabia::Market::Tadawul);
  if (calendarString->ToUpper() == "SINGAPORE.SGX") return Singapore(Singapore::Market::SGX);
  if (calendarString->ToUpper() == "SLOVAKIA.BSSE") return Slovakia(Slovakia::Market::BSSE);
  if (calendarString->ToUpper() == "SOUTHAFRICA") return SouthAfrica();
  if (calendarString->ToUpper() == "SOUTHKOREA.KRX") return SouthKorea(SouthKorea::Market::KRX);
  if (calendarString->ToUpper() == "SOUTHKOREA.SETTLEMENT") return SouthKorea(SouthKorea::Market::Settlement);
  if (calendarString->ToUpper() == "SWEDEN") return Sweden();
  if (calendarString->ToUpper() == "SWITZERLAND") return Switzerland();
  if (calendarString->ToUpper() == "TAIWAN.TSEC") return Taiwan(Taiwan::Market::TSEC);
  if (calendarString->ToUpper() == "TARGET") return TARGET();
  if (calendarString->ToUpper() == "TURKEY") return Turkey();
  if (calendarString->ToUpper() == "UKRAINE.USE") return Ukraine(Ukraine::Market::USE);
  if (calendarString->ToUpper() == "UNITEDKINGDOM.EXCHANGE") return UnitedKingdom(UnitedKingdom::Market::Exchange);
  if (calendarString->ToUpper() == "UNITEDKINGDOM.METALS") return UnitedKingdom(UnitedKingdom::Market::Metals);
  if (calendarString->ToUpper() == "UNITEDKINGDOM.SETTLEMENT") return UnitedKingdom(UnitedKingdom::Market::Settlement);
  if (calendarString->ToUpper() == "UNITEDSTATES.GOVERNMENTBOND") return UnitedStates(UnitedStates::Market::GovernmentBond);
  if (calendarString->ToUpper() == "UNITEDSTATES.LIBORIMPACT") return UnitedStates(UnitedStates::Market::LiborImpact);
  if (calendarString->ToUpper() == "UNITEDSTATES.NERC") return UnitedStates(UnitedStates::Market::NERC);
  if (calendarString->ToUpper() == "UNITEDSTATES.NYSE") return UnitedStates(UnitedStates::Market::NYSE);
  if (calendarString->ToUpper() == "UNITEDSTATES.SETTLEMENT") return UnitedStates(UnitedStates::Market::Settlement);
  // requested calendar not found, throw exception
  throw gcnew System::Exception("undefined calendar");
 }

 BusinessDayConvention Convert::ToBusinessDayConvention(String^ businessDayConventionString) {
  if (businessDayConventionString->ToUpper() == "FOLLOWING") return BusinessDayConvention::Following;
  if (businessDayConventionString->ToUpper() == "HALFMONTHMODIFIEDFOLLOWING") return BusinessDayConvention::HalfMonthModifiedFollowing;
  if (businessDayConventionString->ToUpper() == "MODIFIEDFOLLOWING") return BusinessDayConvention::ModifiedFollowing;
  if (businessDayConventionString->ToUpper() == "MODIFIEDPRECEDING") return BusinessDayConvention::ModifiedPreceding;
  if (businessDayConventionString->ToUpper() == "NEAREST") return BusinessDayConvention::Nearest;
  if (businessDayConventionString->ToUpper() == "PRECEDING") return BusinessDayConvention::Preceding;
  if (businessDayConventionString->ToUpper() == "UNADJUSTED") return BusinessDayConvention::Unadjusted;
  // requested business day convention not found, throw exception
  throw gcnew System::Exception("undefined business day convention");
 }

}

As always, thanks for reading this blog.
-Mike

Saturday, April 28, 2018

C# : Building Transactions from XML files

In my previous post, I presented the following Main program for creating just one set of transaction parameters for a zero-coupon bond, to be delivered further for QuantLib C++/CLI wrapper class.

using System;

namespace Client {

    static class ZeroCouponBond {
        static void Main() {
            try {

                // create transaction parameters
                double riskFreeRate = 0.01;
                double faceAmount = 1000000.0;
                DateTime transactionDate = new DateTime(2018, 4, 16);
                DateTime maturityDate = new DateTime(2020, 4, 16);
                string calendar = "TARGET";
                string daycounter = "ACT360";
                int settlementDays = 2;
                
                // use C++/CLI wrapper : create bond, request pv
                QuantLibCppWrapper.MJZeroCouponBondWrapper zero = new QuantLibCppWrapper.MJZeroCouponBondWrapper(
                    riskFreeRate, faceAmount, transactionDate, maturityDate, calendar, daycounter, settlementDays);
                double PV = zero.PV();
                Console.WriteLine(PV.ToString());
                GC.SuppressFinalize(zero);
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
    }
}

Needless to say, in real life we would need to have a bit more flexible system for creating transaction data. In this post, I am opening one possible scheme for creating transaction data for any type of transaction directly from XML files, using de-serialization. A notable issue in this scheme is, that client program does not implement any kind of pricing model, since the valuation part has completely been outsourced for C++/CLI QuantLib wrapper class (or to some other pricing library). Client program is only creating and hosting transaction-related data and sending calls for wrapper class, when requesting PV for a specific transaction.

UML


The following class diagram is roughly presenting the scheme for building transactions.


In order to create transaction instances, Client program (Main) is using TransactionsBuilder class, which ultimately returns a list of Transaction instances. Transaction is abstract base class for all possible transaction types. This class does not provide any methods, but is merely hosting (in this scheme) properties which are common for all transactions: transaction ID, transaction type information and transaction PV. All concrete transaction implementations, such as ZeroCouponBond class, will be inherited from this base class. Now, there is a lot more than meets the eye inside Builder namespace and we will definitely get into some specifics later.

Library


This namespace is consisting of class implementations for all possible transaction types. It should be implemented entirely into a new C# console project.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;

namespace Library {

    // abstract base class for all possible transaction types
    // storing only properties common for all transactions
    public abstract class Transaction {

        // no de-serialization for pv attribute
        private double pv;
        public double PV { get { return pv; } set { pv = value; } }

        public string transactionType;
        public string transactionID;

        // default ctor, required for serialization
        public Transaction() {
        }

        // parameter ctor
        public Transaction(string transactionType, string transactionID) {
            this.transactionType = transactionType;
            this.transactionID = transactionID;
        }

    }

    // class for hosting zero-coupon bond term sheet information
    public class ZeroCouponBond : Transaction {

        public double faceAmount;
        public DateTime transactionDate;
        public DateTime maturityDate;
        public string calendar;
        public string daycounter;
        public int settlementDays;

        public ZeroCouponBond()
            : base() {
            // required ctor for serialization
        }

        public ZeroCouponBond(string transactionType, string transactionID,
            double faceAmount, DateTime transactionDate, DateTime maturityDate,
            string calendar, string daycounter, int settlementDays)
            : base(transactionType, transactionID) {

            this.faceAmount = faceAmount;
            this.transactionDate = transactionDate;
            this.maturityDate = maturityDate;
            this.calendar = calendar;
            this.daycounter = daycounter;
            this.settlementDays = settlementDays;
        }

    }

    // class for hosting equity-linked note term sheet information
    public class EquityLinkedNote : Transaction {

        public double notional;
        public double cap;
        public double floor;
        public int settlementDays;
        public bool useAntitheticVariates;
        public int requiredSamples;
        public int maxSamples;
        public int seed;
        public List<DateTime> fixingDates = null;
        public List<DateTime> paymentDates = null;

        public EquityLinkedNote()
            : base() {
            // required ctor for serialization
        }

        public EquityLinkedNote(string transactionType, string transactionID,
            double notional, double cap, double floor, int settlementDays,
            bool useAntitheticVariates, int requiredSamples,
            int maxSamples, int seed, List<DateTime> fixingDates,
            List<DateTime> paymentDates)
            : base(transactionType, transactionID) {

            this.notional = notional;
            this.cap = cap;
            this.floor = floor;
            this.settlementDays = settlementDays;
            this.useAntitheticVariates = useAntitheticVariates;
            this.requiredSamples = requiredSamples;
            this.maxSamples = maxSamples;
            this.seed = seed;
            this.fixingDates = fixingDates;
            this.paymentDates = paymentDates;
        }
    }

}

After a short review, it should be clear that these implementation classes are nothing more, but wrappers for hosting heterogeneous sets of transaction-specific data members.

Builder


TransactionBuilder (plus a couple of other helper classes) is living in Builder namespace. This content should also be implemented into existing C# console project.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;

namespace Builder {

    public static class SerializerFactory {        
        // create generic de-serializer instance from a given transaction type string
        public static dynamic Create(string transactionType) {
            // note : required type string ("Namespace.Classname") is received without namespace string
            Type t = typeof(TransactionSerializer<>).MakeGenericType(Type.GetType(String.Format("Library.{0}", transactionType)));
            return Assembly.GetAssembly(t).CreateInstance(t.FullName);
        }
    }

    // de-serialize given xml file to transaction of type T
    public class TransactionSerializer<T> {
        public T Create(string transactionFilePathName) {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            FileStream stream = File.OpenRead(transactionFilePathName);
            return (T)serializer.Deserialize(stream);
        }
    }

    public static class TransactionsBuilder {

        // return list of transaction instances, de-serialized from xml files 
        public static List<dynamic> Build() {

            // create configurations
            // NOTE : use environmental variable in path construction
            string configurationsFilePathName =
                Path.Combine(Environment.GetEnvironmentVariable("CONFIGURATIONS").ToString(), "configurations.xml");
            XmlDocument configurations = new XmlDocument();
            configurations.Load(configurationsFilePathName);
            string transactionsDirectory =
                configurations.SelectSingleNode("Configurations/TransactionsFilePathName").InnerText.ToString();

            // create transaction file names and empty list for storing transaction instances
            string[] transactionFiles = Directory.GetFiles(transactionsDirectory);
            List<dynamic> transactions = new List<dynamic>();

            // loop through transaction file names
            foreach(string transactionFile in transactionFiles) {

                // create transaction xml file
                XmlDocument transactionXMLDocument = new XmlDocument();
                transactionXMLDocument.Load(transactionFile);

                // investigate transaction type inside file
                string transactionType = (transactionXMLDocument.DocumentElement)["transactionType"].InnerText.ToString();

                // use factory class for creating correct de-serializer
                dynamic factory = SerializerFactory.Create(transactionType);

                // use de-serializer to create transaction instance
                dynamic transaction = factory.Create(transactionFile);
                transactions.Add(transaction);
            }
            return transactions;
        }

    }
}

Let us briefly go through, what is happening here. Ultimately, Build-method of TransactionsBuilder class is returning a list of Transaction instances (as dynamic) to its caller.

In the beginning of this method, all program-specific configurations are read from specific XML file. Based on created configurations, transaction XML files will then be loaded from specific directory, on a sequential manner. For each loaded transaction file, type string will be sniffed from inside file and the correct de-serializer instance (factory) will be created, based on that type string. The entity, which is creating this correct de-serializer instance, is SerializerFactory class. Finally, factory instance is used to de-serialize XML file to correct Transaction instance by using TransactionSerializer<T> class.

Required template parameter T for TransactionSerializer<T> class is constructed directly from a given transaction type string, by using MakeGenericType method. The actual de-serializer instance will be created from a given assembly by using CreateInstance method.

Client


Client namespace content is presented below. Also, this content should be implemented into existing C# console project.

namespace Client {
    using Library;
    using Builder;

    static class Program {
        static void Main(string[] args) {

            try {
                // 1. input
                // use transaction builder class for creating all transaction instances from xml files
                List<dynamic> transactions = TransactionsBuilder.Build();

                // 2. processing
                // process PV for all transactions
                // in real-life scenario, we could create calls in here for some pricing library 
                // and store processed valuation results to transaction PV attribute

                // select all zero-coupon bonds and modify PV attribute
                List<ZeroCouponBond> zeros =
                    transactions.Where(x => x.transactionType == "ZeroCouponBond")
                    .Select(y => (ZeroCouponBond)y).ToList<ZeroCouponBond>();
                zeros.ForEach(it => it.PV = 987654.32);

                // select all equity-linked notes and modify PV attribute
                List<EquityLinkedNote> notes =
                    transactions.Where(x => x.transactionType == "EquityLinkedNote")
                    .Select(y => (EquityLinkedNote)y).ToList<EquityLinkedNote>();
                notes.ForEach(it => it.PV = 32845.93);

                // 3. output
                // finally, print ID, type and PV for all transactions
                transactions.ForEach(it => Console.WriteLine
                    (String.Format("id:{0}, type:{1}, pv:{2}",
                    it.transactionID, it.transactionType, it.PV)));
            } 
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
        }
    }
}

The story in Main goes roughly as follows.
  1. Create all transactions instances from specific directory, by using XML de-serialization. 
  2. As a "service request", use created transaction instances for feeding transaction parameters for corresponding wrapper method (say, ZeroCouponBond instance is used for feeding MJZeroCouponBondWrapper). 
  3. Receive PV from wrapper method and store this result back to transaction PV attribute.
Transaction instances (constructed by TransactionsBuilder) can be investigated in Locals window as presented in the following screenshot.



















Finally, make sure to carefully implement all required configurations, which are listed below.

XML configurations


ZeroCouponBond

<ZeroCouponBond>
  <transactionType>ZeroCouponBond</transactionType>
  <transactionID>HSBC.1028</transactionID>
  <faceAmount>1000000</faceAmount>
  <transactionDate>2018-04-24T00:00:00</transactionDate>
  <maturityDate>2020-04-24T00:00:00</maturityDate>
  <calendar>TARGET</calendar>
  <daycounter>ACT360</daycounter>
  <settlementDays>2</settlementDays>
</ZeroCouponBond>

EquityLinkedNote

<EquityLinkedNote>
  <transactionType>EquityLinkedNote</transactionType>
  <transactionID>NORDEA.3866</transactionID>
  <notional>1000000.0</notional>
  <cap>0.015</cap>
  <floor>0.0</floor>
  <transactionDate>2017-10-30T00:00:00</transactionDate>
  <settlementDays>2</settlementDays>
  <calendar>TARGET</calendar>
  <dayCountConvention>ACT360</dayCountConvention>
  <requiredSamples>1000</requiredSamples>
  <seed>0</seed>
  <fixingDates>
    <dateTime>2017-11-30T00:00:00</dateTime>    <dateTime>2017-12-30T00:00:00</dateTime>
    <dateTime>2018-01-30T00:00:00</dateTime>    <dateTime>2018-02-28T00:00:00</dateTime>
    <dateTime>2018-03-30T00:00:00</dateTime>    <dateTime>2018-04-30T00:00:00</dateTime>
    <dateTime>2018-05-30T00:00:00</dateTime>    <dateTime>2018-06-30T00:00:00</dateTime>
    <dateTime>2018-07-30T00:00:00</dateTime>    <dateTime>2018-08-30T00:00:00</dateTime>
    <dateTime>2018-09-30T00:00:00</dateTime>    <dateTime>2018-10-30T00:00:00</dateTime>
    <dateTime>2018-11-30T00:00:00</dateTime>    <dateTime>2018-12-30T00:00:00</dateTime>
    <dateTime>2019-01-30T00:00:00</dateTime>    <dateTime>2019-02-28T00:00:00</dateTime>
    <dateTime>2019-03-30T00:00:00</dateTime>    <dateTime>2019-04-30T00:00:00</dateTime>
    <dateTime>2019-05-30T00:00:00</dateTime>    <dateTime>2019-06-30T00:00:00</dateTime>
    <dateTime>2019-07-30T00:00:00</dateTime>    <dateTime>2019-08-30T00:00:00</dateTime>
    <dateTime>2019-09-30T00:00:00</dateTime>    <dateTime>2019-10-30T00:00:00</dateTime>
    <dateTime>2019-11-30T00:00:00</dateTime>    <dateTime>2019-12-30T00:00:00</dateTime>
    <dateTime>2020-01-30T00:00:00</dateTime>    <dateTime>2020-02-29T00:00:00</dateTime>
    <dateTime>2020-03-30T00:00:00</dateTime>    <dateTime>2020-04-30T00:00:00</dateTime>
    <dateTime>2020-05-30T00:00:00</dateTime>    <dateTime>2020-06-30T00:00:00</dateTime>
    <dateTime>2020-07-30T00:00:00</dateTime>    <dateTime>2020-08-30T00:00:00</dateTime>
    <dateTime>2020-09-30T00:00:00</dateTime>    <dateTime>2020-10-30T00:00:00</dateTime>
  </fixingDates>
  <paymentDates>
    <dateTime>2018-10-30T00:00:00</dateTime>
    <dateTime>2019-10-30T00:00:00</dateTime>
    <dateTime>2020-10-30T00:00:00</dateTime>
  </paymentDates>
</EquityLinkedNote>

Program configurations

<Configurations>
  <TransactionsFilePathName>C:\temp\transactions</TransactionsFilePathName>
</Configurations>

For setting environmental variables, a great tutorial can be found in here. Finally, configuring a new transaction in this scheme should be relatively easy. First, a new XML file for hosting specific set of transaction-related parameters (plus two parameters common for all transactions: ID and type) should be created. Secondly, a new class implementation for hosting these transaction-related parameters should be implemented into Library namespace. Finally (outside of this assembly), there should be method implementation available in wrapper for this new transaction (for calculating PV for a given set of transaction parameters). Job done.

As always, Thanks for reading this blog. Happy First of May season for everybody.
-Mike

Saturday, October 8, 2016

C# : managing global configurations with XML serializer

Managing configurations within any non-trivial program can easily turn to be a tricky issue. One might have a lot of different types of configuration parameters, which might need to be used as input parameters for several different classes. Moreover, there might be a need for using different set of configurations and one should be able to switch to another set as easily as possible.

This time I wanted to present a scheme, what I have been using for hosting global configuration parameters in some of my applications. Presented scheme solves three following issues :
  1. Configuration set used by program executable can easily be changed to another set
  2. There is no need to touch App.Config file
  3. All configuration properties are global, static and safe (read-only)
First of all, a set of configurations will be processed (read) from XML file using XML serializer. Assume I have following two configuration sets as XML files, one for testing and another for production :



















When running program executable for the both configuration files (path to folder in which the actual configuration XML file exists, will be given as a parameter for executable), we get the following console printouts :










When the program starts, path to configuration folder is captured (command line argument). Calling any class property of static Configurations class will automatically trigger static class constructor. Static class constructor will then use XML serializer (ObjectXMLHandler<T> class) for creating Configuration object instance (nested class inside static Configurations class). Finally, properties of newly created Configuration object will be assigned to properties of static Configurations class.

For testing this scheme, just replicate XML configuration files, create a new console application (GlobalConfigurations) and copyPaste the following code into CS-file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace GlobalConfigurations
{
    public class Program
    {
        public static string configurationFilePathName;
        //
        static void Main(string[] args)
        {
            configurationFilePathName = args[0];
            //
            // print configurations
            ConfigurationTester configurationTester = new ConfigurationTester();
            configurationTester.Print();
        }
    }
    //
    //
    //
    /// <summary>
    /// Class for testing global static read-only configurations 
    /// </summary>
    public class ConfigurationTester
    {
        public void Print()
        {
            // print configurations
            Console.WriteLine("{0}, {1}, {2}, {3}", 
                Configurations.ConfigurationString, 
                Configurations.ConfigurationBoolean, 
                Configurations.ConfigurationLong, 
                Configurations.ConfigurationDouble);
        }
    }
    //
    //
    //
    /// <summary>
    /// Static class for hosting global configurations 
    /// </summary>
    public static class Configurations
    {
        // static read-only properties
        public static readonly string ConfigurationString;
        public static readonly bool ConfigurationBoolean;
        public static readonly long ConfigurationLong;
        public static readonly double ConfigurationDouble;
        //
        /// <summary>
        /// Static constructor will be called immediately 
        /// when static class property will be called. 
        /// </summary>
        static Configurations()
        {
            // create instance of ObjectXMLHandler for Configuration type
            ObjectXMLHandler<Configuration> handler = new ObjectXMLHandler<Configuration>();
            //
            // create Configuration objects from XML files
            string filePathName = Program.configurationFilePathName;
            List<Configuration> configuration = handler.Deserialize(filePathName);
            //
            // assign properties from inner configuration class into static read-only properties
            ConfigurationString = configuration[0].configurationString;
            ConfigurationBoolean = configuration[0].configurationBoolean;
            ConfigurationLong = configuration[0].configurationLong;
            ConfigurationDouble = configuration[0].configurationDouble;
        }
        /// <summary>
        /// Nested class for inner configurations. 
        /// </summary>
        public class Configuration
        {
            public string configurationString;
            public bool configurationBoolean;
            public long configurationLong;
            public double configurationDouble;
            //
            /// <summary>
            /// Default constructor is needed to create configuration parameters 
            /// </summary>
            public Configuration()
            {
                // no implementation
            }
        }
    }
    //
    //
    //
    /// <summary>
    /// Generic template class for handling conversion 
    /// between object and XML presentation.
    /// </summary>
    public class ObjectXMLHandler<T>
    {
        private XmlSerializer serializer = null;
        private Stream stream = null;
        //
        /// <summary>
        /// Parameter constructor for creating an instance. 
        /// </summary>
        public ObjectXMLHandler()
        {
            serializer = new XmlSerializer(typeof(T));
        }
        /// <summary>
        /// Convert a list of objects of type T into XML files. 
        /// </summary>
        public void Serialize(List<T> objects, List<string> fileNames, string folderPathName)
        {
            if (objects.Count != fileNames.Count)
                throw new Exception("objects.Count != fileNames.Count");
            //
            int counter = 0;
            foreach (T t in objects)
            {
                stream = File.Create(Path.Combine(folderPathName, String.Concat(fileNames[counter])));
                serializer.Serialize(stream, t);
                stream.Close();
                counter++;
            }
        }
        /// <summary>
        /// Convert XML files in specific folder into a list of objects of type T.
        /// </summary>
        public List<T> Deserialize(string folderPathName)
        {
            List<T> objects = new List<T>();
            foreach (string t in Directory.GetFiles(folderPathName))
            {
                stream = File.OpenRead(t);
                objects.Add((T)serializer.Deserialize(stream));
                stream.Close();
            }
            return objects;
        }
    }
}

Thanks a lot for using your precious time and reading my blog.
-Mike

Saturday, March 5, 2016

C# : Using XmlSerializer for creating (storing) objects from (to) XML file


This time, I wanted to share a cool mechanism for handling object presentation between object instance and XML file. This mechanism can be found in System.Xml.Serialization namespace. In short, when using XmlSerializer we can create object instance directly from XML file and store object blueprint information to XML file to be used whenever needed.


Real-life design scheme

 

Assume we have some state-of-the-art analytic calculation engine, into which we feed a lot of different transactions and market scenario data in the first place. When the engine is up and running, we can simply give any specific calculation task object to be processed for this engine. One Task object will simply define a specific set of parameters, such as

  • Calculation task name
  • What kind of transactions will be selected?
  • In what kind of market scenario those selected transactions will be valued?
  • What kind of output values will be calculated for each transaction?

Obviously, the beef is really in handling all required configuration parameters for all calculation tasks in an efficient manner. For this purpose, we need to be able to create calculation task instances from some source. Blueprints for all task objects can be stored into XML files, from which the actual objects are going to be created by XmlSerializer to be processed by the engine.


Bridge over troubled water

 

For the purposes mentioned above, I came up with an idea of generic ObjectXMLHandler<T> class for handling Object/XML transformations for any type of object, not only for Task object which has been used in this example. Behind the scenes, this class is nothing more but a wrapper for XmlSerializer, which can create (store) a list of objects from (to) XML files.

For storing object blueprints into XML file (Serialize), the class client will give a list of object instances, a list of file names to be used and a path name for a specific target folder. Below is a screenshot of one Task object blueprint XML file, created by ObjectXMLHandler.








For creating objects from XML file (Deserialize), the class client will only give a path name for a specific target folder, in which all object blueprints are stored in XML files. When calling this method, the class will return a list of object instances (having type of T) for its client. Below is a screenshot of all three Task object instances which have been created from XML files by ObjectXMLHandler.







Personally, I find XmlSerialization class to be extremely useful for the schemes like the one presented in here. It will completely liberate me from writing my own XML handlers for such cases.

A small dark cloud within this overwhelming joy is the fact, that this presented XmlSerializer class can only handle member data which has been defined to be public. For other cases, I would recommend to dig deeper into implementing IXmlSerializable interface, found in the same namespace.

Thanks for reading my blog. I hope you have got some useful ideas for your own programs.


The Program


Create a new project consisting of three CS files (Program, Task, ObjectXMLHandler). CopyPaste the following program into corresponding CS files.

// Program.cs content
using System;
using System.Collections.Generic;

namespace XMLTester
{
    class Program
    {
        private static string FilePathName = @"C:\temp\Tasks\";
        //        
        static void Main(string[] args)
        {
            try
            {
                // create instance of ObjectXMLHandler for Task type
                ObjectXMLHandler<Task> handler = new ObjectXMLHandler<Task>();
                //
                // A. SERIALIZING (object to XML)
                // create a list of required XML file names
                List<string> fileNames = new List<string>() 
                { 
                    "TaskOne.xml", 
                    "TaskTwo.xml", 
                    "TaskThree.xml" 
                };
                // create a list of calculation task configuration objects
                List<Task> tasks = new List<Task>() 
                { 
                    new Task("ALL_SWAPS_BASE", "ALL", "MARKET_BASE", "PV,DELTA,CVA"),
                    new Task("CITIBANK_SWAPS_STRESSED_CDS", "CITIBANK", "MARKET_CDS_STRESS", "PV,DELTA"), 
                    new Task("DEUTSCHE_SWAPS_STRESSED_FX", "DEUTSCHE", "MARKET_FX_STRESS", "PV,DELTA")
                };
                // write task objects to XML files
                handler.Serialize(tasks, fileNames, FilePathName);
                //
                // B. DE-SERIALIZING (XML to object)
                // create task objects from XML files and print task configuration string
                tasks = handler.Deserialize(FilePathName);
                tasks.ForEach(task => Console.WriteLine(task.ToString()));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
//
//
//
// Task.cs content
using System;

namespace XMLTester
{
    /// <summary>
    /// Class for administrating calculation task parameters. 
    /// </summary>
    public class Task
    {
        public string taskName;
        public string tradeSelection;
        public string marketSelection;
        public string calculationOutput;
        //
        /// <summary>
        /// Default constructor is required by XMLSerializer.
        /// </summary>
        public Task()
        {
            //
        }
        /// <summary>
        /// Parameter constructor for creating one calculation task object.
        /// </summary>
        public Task(string taskName, string tradeSelection, 
            string marketSelection, string calculationOutput)
        {
            this.taskName = taskName;
            this.tradeSelection = tradeSelection;
            this.marketSelection = marketSelection;
            this.calculationOutput = calculationOutput;
        }
        /// <summary>
        /// Get configuration string for calculation task.
        /// </summary>
        public override string ToString()
        {
            return String.Format("{0}.{1}.{2}.{3}", 
                taskName, tradeSelection, marketSelection, calculationOutput);
        }
    }
}
//
//
//
// ObjectXMLHandler.cs content
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace XMLTester
{
    /// <summary>
    /// Generic template class for handling conversion 
    /// between object and XML presentation.
    /// </summary>
    public class ObjectXMLHandler<T>
    {
        private XmlSerializer serializer = null;
        private Stream stream = null;
        //
        /// <summary>
        /// Parameter constructor for creating an instance. 
        /// </summary>
        public ObjectXMLHandler()
        {
            serializer = new XmlSerializer(typeof(T));
        }
        /// <summary>
        /// Convert a list of objects of type T into XML files. 
        /// </summary>
        public void Serialize(List<T> objects, List<string> fileNames, string folderPathName)
        {
            if (objects.Count != fileNames.Count) 
                throw new Exception("objects.Count != fileNames.Count");
            //
            int counter = 0;
            foreach (T t in objects)
            {
                stream = File.Create(Path.Combine(folderPathName, String.Concat(fileNames[counter])));
                serializer.Serialize(stream, t);
                stream.Close();
                counter++;
            }
        }
        /// <summary>
        /// Convert XML files in specific folder into a list of objects of type T.
        /// </summary>
        public List<T> Deserialize(string folderPathName)
        {
            List<T> objects = new List<T>();
            foreach (string t in Directory.GetFiles(folderPathName))
            {
                stream = File.OpenRead(t);
                objects.Add((T)serializer.Deserialize(stream));
                stream.Close();
            }
            return objects;
        }
    }
}