private void CreateDeployment(Collar collar, ArgosPlatform platform, DateTime startDateTime)
        {
            DateTime?endDateTime = null;

            if (platform.ArgosDeployments.Count > 0 || collar.ArgosDeployments.Count > 0)
            {
                if (!FixOtherDeployments(collar, platform, startDateTime, ref endDateTime))
                {
                    return;
                }
            }
            var deploy = new ArgosDeployment
            {
                ArgosPlatform = platform,
                Collar        = collar,
                StartDate     = startDateTime,
                EndDate       = endDateTime
            };

            Database.ArgosDeployments.InsertOnSubmit(deploy);
            //Creating a deployment is optional, so we submit now, so a failure will not stop other transactions.
            if (!SubmitChanges())
            {
                Database.ArgosDeployments.DeleteOnSubmit(deploy);
            }
        }
示例#2
0
 private static bool CanDeleteCollar(Collar collar)
 {
     return(!collar.CollarDeployments.Any() &&
            !collar.CollarFixes.Any() &&
            !collar.CollarParameters.Any(p => p.CollarFiles.Any()) &&
            !collar.ArgosDeployments.Any());
 }
        private void CreateParameter(Collar collar, CollarParameterFile file, DateTime startDateTime)
        {
            DateTime?endDateTime = null;

            if (collar.CollarParameters.Count > 0)
            {
                if (!FixOtherParameters(collar, file, startDateTime, ref endDateTime))
                {
                    return;
                }
            }
            var param = new CollarParameter
            {
                Collar = collar,
                CollarParameterFile = file,
                StartDate           = startDateTime,
                EndDate             = endDateTime
            };

            Database.CollarParameters.InsertOnSubmit(param);
            //Creating a parameter is optional, so we submit now, so a failure will not stop other transactions.
            if (!SubmitChanges())
            {
                Database.CollarParameters.DeleteOnSubmit(param);
            }
        }
示例#4
0
 public Dog(string name, int age, double length)
 {
     this.name = "Axl";
     this.age = 3;
     this.length = 0.5;
     this.collar = new Collar();
 }
示例#5
0
            public CapFloor makeCapFloor(CapFloorType type, List <CashFlow> leg, double capStrike,
                                         double floorStrike, double vol)
            {
                CapFloor result = null;

                switch (type)
                {
                case CapFloorType.Cap:
                    result = new Cap(leg, new InitializedList <double>(1, capStrike));
                    break;

                case CapFloorType.Floor:
                    result = new Floor(leg, new InitializedList <double>(1, floorStrike));
                    break;

                case CapFloorType.Collar:
                    result = new Collar(leg, new InitializedList <double>(1, capStrike),
                                        new InitializedList <double>(1, floorStrike));
                    break;

                default:
                    Utils.QL_FAIL("unknown cap/floor type");
                    break;
                }
                result.setPricingEngine(makeEngine(vol));
                return(result);
            }
示例#6
0
        private void AddArgosDeployment(string argosId, Collar collar, DateTime start)
        {
            var platform = Database.ArgosPlatforms.FirstOrDefault(a => a.PlatformId == argosId);

            if (platform == null)
            {
                return;
            }
            DateTime?endDate = null;

            if (platform.ArgosDeployments.Count > 0 || collar.ArgosDeployments.Count > 0)
            {
                if (!FixOtherArgosDeployments(collar, platform, start, ref endDate))
                {
                    return;
                }
            }
            var deploy = new ArgosDeployment
            {
                ArgosPlatform = platform,
                Collar        = collar,
                StartDate     = start,
                EndDate       = endDate
            };

            Database.ArgosDeployments.InsertOnSubmit(deploy);
            if (SubmitChanges())
            {
                TpfDataChanged();
            }
        }
示例#7
0
 public Shirt(Collar collarType, bool cufflink, string color, string name, string producer, string material, double price) :
     base(name, producer, material, price)
 {
     CollarType = collarType;
     Cufflink   = cufflink;
     Color      = color;
 }
        private bool FixOtherDeployments(Collar collar, ArgosPlatform platform, DateTime start, ref DateTime?endDate)
        {
            //I'm willing to move a existing null end dates (there can only be one for the platform and one for the collar) back to my start date.
            //Any existing non-null enddate must have been explicitly set by the user, so they should be dealt with explicitly
            //If this situation exists, and I correct it, I am guaranteed to be fine (the new one will exist in the space created)
            var deployment1 =
                collar.ArgosDeployments.SingleOrDefault(d =>
                                                        d.ArgosPlatform != platform &&
                                                        d.StartDate < start && d.EndDate == null);
            var deployment2 =
                platform.ArgosDeployments.SingleOrDefault(d =>
                                                          d.Collar != collar &&
                                                          d.StartDate < start && d.EndDate == null);

            if (deployment1 != null)
            {
                deployment1.EndDate = start;
            }
            if (deployment2 != null)
            {
                deployment2.EndDate = start;
            }
            if (deployment1 != null || deployment2 != null)
            {
                if (!SubmitChanges())
                {
                    return(false);
                }
            }

            //If my enddate is null, I should set my end to the earliest start time of the others that are larger than my start but smaller than my end (infinity, so all).
            //I don't try to fix a non-null end date, because that was explicitly set by the user, and be should explicitly changed.
            if (endDate == null)
            {
                endDate =
                    Database.ArgosDeployments.Where(d =>
                                                    ((d.Collar == collar && d.ArgosPlatform != platform) ||
                                                     (d.Collar != collar && d.ArgosPlatform == platform)) &&
                                                    start < d.StartDate)
                    .Select(d => d.StartDate).Min();         //If min gets an empty enumerable, it will return null, which in this case is no change.
            }
            //Since my startdate is non-null, there is no situation where I would need to change an existing null start date.

            //now check if the new deployment is in conflict with any existing deployments
            DateTime?end         = endDate;
            var      competition = Database.ArgosDeployments.Where(d => (d.Collar == collar && d.ArgosPlatform != platform) ||
                                                                   (d.Collar != collar && d.ArgosPlatform == platform)).ToList();
            bool conflict = competition.Any(d => DatesOverlap(d.StartDate, d.EndDate, start, end));

            if (conflict)
            {
                MessageBox.Show(
                    "The other deployment(s) for this collar or platform will require manual adjustment before this platform can be used on this collar",
                    "Oh No!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            return(true);
        }
 internal CollarDetailsForm(Collar collar)
 {
     InitializeComponent();
     RestoreWindow();
     Collar      = collar;
     CurrentUser = Environment.UserDomainName + @"\" + Environment.UserName;
     LoadDataContext();
     SetUpHeader();
 }
示例#10
0
 public AddArgosDeploymentForm(Collar collar = null, ArgosPlatform platform = null)
 {
     InitializeComponent();
     Collar      = collar;
     Platform    = platform;
     CurrentUser = Environment.UserDomainName + @"\" + Environment.UserName;
     LoadDataContext();
     SetUpControls();  //Called before events are triggered
 }
示例#11
0
 public AddCollarParametersForm(Collar collar = null, CollarParameterFile file = null)
 {
     InitializeComponent();
     Collar      = collar;
     File        = file;
     CurrentUser = Environment.UserDomainName + @"\" + Environment.UserName;
     LoadDataContext();
     LoadDefaultFormContents();  //Called before events are triggered
 }
 public AddCollarDeploymentForm(Collar collar = null, Animal animal = null)
 {
     InitializeComponent();
     Collar      = collar;
     Animal      = animal;
     CurrentUser = Environment.UserDomainName + @"\" + Environment.UserName;
     LoadDataContext();
     LoadDefaultFormContents();
 }
示例#13
0
        private bool CanEditCollar(Collar collar)
        {
            if (collar == null)
            {
                return(Database.ProjectInvestigators.Any(
                           pi =>
                           pi.Login == CurrentUser || pi.ProjectInvestigatorAssistants.Any(a => a.Assistant == CurrentUser)));
            }
            var functions = new AnimalMovementFunctions();

            return(functions.IsInvestigatorEditor(collar.Manager, CurrentUser) ?? false);
        }
示例#14
0
        public void testConsistency()
        {
            CommonVars vars = new CommonVars();

            int[]    lengths     = { 1, 2, 3, 5, 7, 10, 15, 20 };
            double[] cap_rates   = { 0.03, 0.04, 0.05, 0.06, 0.07 };
            double[] floor_rates = { 0.03, 0.04, 0.05, 0.06, 0.07 };
            double[] vols        = { 0.01, 0.05, 0.10, 0.15, 0.20 };

            Date startDate = vars.termStructure.link.referenceDate();

            for (int i = 0; i < lengths.Length; i++)
            {
                for (int j = 0; j < cap_rates.Length; j++)
                {
                    for (int k = 0; k < floor_rates.Length; k++)
                    {
                        for (int l = 0; l < vols.Length; l++)
                        {
                            List <CashFlow> leg = vars.makeLeg(startDate, lengths[i]);
                            Instrument      cap = vars.makeCapFloor(CapFloorType.Cap, leg,
                                                                    cap_rates[j], vols[l]);
                            Instrument floor = vars.makeCapFloor(CapFloorType.Floor, leg,
                                                                 floor_rates[k], vols[l]);
                            Collar collar = new Collar(leg, new InitializedList <double>(1, cap_rates[j]),
                                                       new InitializedList <double>(1, floor_rates[k]));
                            collar.setPricingEngine(vars.makeEngine(vols[l]));

                            if (Math.Abs((cap.NPV() - floor.NPV()) - collar.NPV()) > 1e-10)
                            {
                                QAssert.Fail(
                                    "inconsistency between cap, floor and collar:\n"
                                    + "    length:       " + lengths[i] + " years\n"
                                    + "    volatility:   " + vols[l] + "\n"
                                    + "    cap value:    " + cap.NPV()
                                    + " at strike: " + cap_rates[j] + "\n"
                                    + "    floor value:  " + floor.NPV()
                                    + " at strike: " + floor_rates[k] + "\n"
                                    + "    collar value: " + collar.NPV());
                            }
                        }
                    }
                }
            }
        }
示例#15
0
        private string BuildCollarText(Collar collar)
        {
            string name    = collar.ToString();
            var    animals = from deployment in Database.CollarDeployments
                             where deployment.Collar == collar && deployment.RetrievalDate == null
                             select deployment.Animal;
            var animal = animals.FirstOrDefault();

            if (animal != null)
            {
                name += " on " + animal;
            }
            if (collar.DisposalDate != null)
            {
                name = String.Format("{0} (disp:{1:M/d/yy})", name, collar.DisposalDate.Value.ToLocalTime());
            }
            return(name);
        }
示例#16
0
        private void ArgosAdded(string argosId, Collar collar, DateTime start)
        {
            var platform = Database.ArgosPlatforms.FirstOrDefault(a => a.PlatformId == argosId);

            if (platform == null)
            {
                return;
            }
            var deploy = new ArgosDeployment
            {
                ArgosPlatform = platform,
                Collar        = collar,
                StartDate     = start
            };

            Database.ArgosDeployments.InsertOnSubmit(deploy);
            if (SubmitChanges())
            {
                TpfDataChanged();
            }
        }
        private bool FixOtherParameters(Collar collar, CollarParameterFile file, DateTime start, ref DateTime?end)
        {
            //I'm willing to move a existing null end date (there can only be one) back to my start date.
            //Any existing non-null enddate must have been explicitly set by the user, so they should be dealt with explicitly
            //If this situation exists, and I correct it, I am guaranteed to be fine (the new one will exist in the space created), so I can exit
            var parameter = collar.CollarParameters.SingleOrDefault(p => p.CollarParameterFile != file && p.StartDate < start && p.EndDate == null);

            if (parameter != null)
            {
                parameter.EndDate = start;
                if (!SubmitChanges())
                {
                    return(false);
                }
            }

            //If my enddate is null (when fixing existng, or adding new), I should set my end to the earliest start time of the others that are larger than my start but smaller than my end (infinity, so all).
            //This could only happen on a fix if there was an existing integrity violation.
            //I don't try to fix a non-null end date, because that was explicitly set by the user, and should explicitly changed.
            if (end == null)
            {
                end = collar.CollarParameters.Where(p => p.CollarParameterFile != file && start < p.StartDate)
                      .Select(p => p.StartDate).Min();       //If there is no min gets an empty enumerable, it will return null, which in this case is no change.
            }
            //There is no situation where I would need to change an existing null start date.

            //now check if the new parameter is in conflict with any existing parameters
            DateTime?endDate     = end;
            var      competition = collar.CollarParameters.Where(p => p.CollarParameterFile != file).ToList();
            bool     conflict    = competition.Any(p => DatesOverlap(p.StartDate, p.EndDate, start, endDate));

            if (conflict)
            {
                MessageBox.Show(
                    "The other parameter assignment(s) for this collar will require manual adjustment before this file can be used on this collar",
                    "Oh No!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            return(true);
        }
示例#18
0
        private Collar[] GetCollars()
        {
            var collarIds = TpfDataGridView.Rows.Cast <DataGridViewRow>().Select(r => (string)r.Cells[1].Value).ToArray();

            if (IgnoreSuffixCheckBox.Checked)
            {
                collarIds = collarIds.Select(c => c.Length > 6 ? c.Substring(0, 6) : c).ToArray();
            }

            var unsortedCollars =
                Database.Collars.Where(
                    c =>
                    c.CollarManufacturer == "Telonics" && collarIds.Contains(c.CollarId)).ToList();

            var sortedCollars = new Collar[TpfDataGridView.Rows.Count];

            for (int i = 0; i < TpfDataGridView.Rows.Count; i++)
            {
                sortedCollars[i] = unsortedCollars.SingleOrDefault(c => c.CollarId == collarIds[i]);
            }
            return(sortedCollars);
        }
示例#19
0
        private void CreateButton_Click(object sender, EventArgs e)
        {
            var    mfgr     = (LookupCollarManufacturer)ManufacturerComboBox.SelectedItem;
            string collarId = CollarIdTextBox.Text.NullifyIfEmpty();

            if (Database.Collars.Any(c => c.LookupCollarManufacturer == mfgr && c.CollarId == collarId))
            {
                MessageBox.Show("The collar Id is not unique.  Try again", "Database Error", MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                CollarIdTextBox.Focus();
                CreateButton.Enabled = false;
                return;
            }
            var collar = new Collar
            {
                CollarId                 = CollarIdTextBox.Text.NullifyIfEmpty(),
                Frequency                = FrequencyTextBox.Text.DoubleOrNull(),
                HasGps                   = HasGpsCheckBox.Checked,
                DisposalDate             = DisposalDateTimePicker.Checked ? DisposalDateTimePicker.Value : (DateTime?)null,
                LookupCollarManufacturer = (LookupCollarManufacturer)ManufacturerComboBox.SelectedItem,
                LookupCollarModel        = (LookupCollarModel)ModelComboBox.SelectedItem,
                Notes = NotesTextBox.Text.NullifyIfEmpty(),
                Owner = OwnerTextBox.Text.NullifyIfEmpty(),
                ProjectInvestigator = (ProjectInvestigator)ManagerComboBox.SelectedItem,
                SerialNumber        = SerialNumberTextBox.Text.NullifyIfEmpty(),
            };

            Database.Collars.InsertOnSubmit(collar);
            if (!SubmitChanges())
            {
                CollarIdTextBox.Focus();
                CreateButton.Enabled = false;
                return;
            }
            OnDatabaseChanged();
            Close();
        }
示例#20
0
 private static bool FrequencyMismatch(Collar collar, double frequency)
 {
     return(collar.Frequency != frequency);
 }
示例#21
0
        public void testDecomposition()
        {
            // Testing collared coupon against its decomposition

            CommonVars vars = new CommonVars();

            double         tolerance = 1e-12;
            double         npvVanilla, npvCappedLeg, npvFlooredLeg, npvCollaredLeg, npvCap, npvFloor, npvCollar;
            double         error;
            double         floorstrike = 0.05;
            double         capstrike   = 0.10;
            List <double?> caps        = new InitializedList <double?>(vars.length, capstrike);
            List <double?> caps0       = new List <double?>();
            List <double?> floors      = new InitializedList <double?>(vars.length, floorstrike);
            List <double?> floors0     = new List <double?>();
            double         gearing_p   = 0.5;
            double         spread_p    = 0.002;
            double         gearing_n   = -1.5;
            double         spread_n    = 0.12;
            // fixed leg with zero rate
            List <CashFlow> fixedLeg = vars.makeFixedLeg(vars.startDate, vars.length);
            // floating leg with gearing=1 and spread=0
            List <CashFlow> floatLeg = vars.makeFloatingLeg(vars.startDate, vars.length);
            // floating leg with positive gearing (gearing_p) and spread<>0
            List <CashFlow> floatLeg_p = vars.makeFloatingLeg(vars.startDate, vars.length, gearing_p, spread_p);
            // floating leg with negative gearing (gearing_n) and spread<>0
            List <CashFlow> floatLeg_n = vars.makeFloatingLeg(vars.startDate, vars.length, gearing_n, spread_n);
            // Swap with null fixed leg and floating leg with gearing=1 and spread=0
            Swap vanillaLeg = new Swap(fixedLeg, floatLeg);
            // Swap with null fixed leg and floating leg with positive gearing and spread<>0
            Swap vanillaLeg_p = new Swap(fixedLeg, floatLeg_p);
            // Swap with null fixed leg and floating leg with negative gearing and spread<>0
            Swap vanillaLeg_n = new Swap(fixedLeg, floatLeg_n);

            IPricingEngine engine = new DiscountingSwapEngine(vars.termStructure);

            vanillaLeg.setPricingEngine(engine);
            vanillaLeg_p.setPricingEngine(engine);
            vanillaLeg_n.setPricingEngine(engine);

            /* CAPPED coupon - Decomposition of payoff
             * Payoff = Nom * Min(rate,strike) * accrualperiod =
             *       = Nom * [rate + Min(0,strike-rate)] * accrualperiod =
             *       = Nom * rate * accrualperiod - Nom * Max(rate-strike,0) * accrualperiod =
             *       = VanillaFloatingLeg - Call
             */

            // Case gearing = 1 and spread = 0
            List <CashFlow> cappedLeg = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors0, vars.volatility);
            Swap            capLeg    = new Swap(fixedLeg, cappedLeg);

            capLeg.setPricingEngine(engine);
            Cap cap = new Cap(floatLeg, new InitializedList <double>(1, capstrike));

            cap.setPricingEngine(vars.makeEngine(vars.volatility));
            npvVanilla   = vanillaLeg.NPV();
            npvCappedLeg = capLeg.NPV();
            npvCap       = cap.NPV();
            error        = Math.Abs(npvCappedLeg - (npvVanilla - npvCap));
            if (error > tolerance)
            {
                QAssert.Fail("\nCapped Leg: gearing=1, spread=0%, strike=" + capstrike * 100 +
                             "%\n" +
                             "  Capped Floating Leg NPV: " + npvCappedLeg + "\n" +
                             "  Floating Leg NPV - Cap NPV: " + (npvVanilla - npvCap) + "\n" +
                             "  Diff: " + error);
            }

            /* gearing = 1 and spread = 0
             * FLOORED coupon - Decomposition of payoff
             * Payoff = Nom * Max(rate,strike) * accrualperiod =
             *       = Nom * [rate + Max(0,strike-rate)] * accrualperiod =
             *       = Nom * rate * accrualperiod + Nom * Max(strike-rate,0) * accrualperiod =
             *       = VanillaFloatingLeg + Put
             */

            List <CashFlow> flooredLeg = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps0, floors, vars.volatility);
            Swap            floorLeg   = new Swap(fixedLeg, flooredLeg);

            floorLeg.setPricingEngine(engine);
            Floor floor = new Floor(floatLeg, new InitializedList <double>(1, floorstrike));

            floor.setPricingEngine(vars.makeEngine(vars.volatility));
            npvFlooredLeg = floorLeg.NPV();
            npvFloor      = floor.NPV();
            error         = Math.Abs(npvFlooredLeg - (npvVanilla + npvFloor));
            if (error > tolerance)
            {
                QAssert.Fail("Floored Leg: gearing=1, spread=0%, strike=" + floorstrike * 100 +
                             "%\n" +
                             "  Floored Floating Leg NPV: " + npvFlooredLeg + "\n" +
                             "  Floating Leg NPV + Floor NPV: " + (npvVanilla + npvFloor) + "\n" +
                             "  Diff: " + error);
            }

            /* gearing = 1 and spread = 0
             * COLLARED coupon - Decomposition of payoff
             * Payoff = Nom * Min(strikem,Max(rate,strikeM)) * accrualperiod =
             *       = VanillaFloatingLeg - Collar
             */

            List <CashFlow> collaredLeg = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors, vars.volatility);
            Swap            collarLeg   = new Swap(fixedLeg, collaredLeg);

            collarLeg.setPricingEngine(engine);
            Collar collar = new Collar(floatLeg, new InitializedList <double>(1, capstrike),
                                       new InitializedList <double>(1, floorstrike));

            collar.setPricingEngine(vars.makeEngine(vars.volatility));
            npvCollaredLeg = collarLeg.NPV();
            npvCollar      = collar.NPV();
            error          = Math.Abs(npvCollaredLeg - (npvVanilla - npvCollar));
            if (error > tolerance)
            {
                QAssert.Fail("\nCollared Leg: gearing=1, spread=0%, strike=" +
                             floorstrike * 100 + "% and " + capstrike * 100 + "%\n" +
                             "  Collared Floating Leg NPV: " + npvCollaredLeg + "\n" +
                             "  Floating Leg NPV - Collar NPV: " + (npvVanilla - npvCollar) + "\n" +
                             "  Diff: " + error);
            }

            /* gearing = a and spread = b
             * CAPPED coupon - Decomposition of payoff
             * Payoff
             * = Nom * Min(a*rate+b,strike) * accrualperiod =
             * = Nom * [a*rate+b + Min(0,strike-a*rate-b)] * accrualperiod =
             * = Nom * a*rate+b * accrualperiod + Nom * Min(strike-b-a*rate,0) * accrualperiod
             * --> If a>0 (assuming positive effective strike):
             *    Payoff = VanillaFloatingLeg - Call(a*rate+b,strike)
             * --> If a<0 (assuming positive effective strike):
             *    Payoff = VanillaFloatingLeg + Nom * Min(strike-b+|a|*rate+,0) * accrualperiod =
             *          = VanillaFloatingLeg + Put(|a|*rate+b,strike)
             */

            // Positive gearing
            List <CashFlow> cappedLeg_p = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors0,
                                                                 vars.volatility, gearing_p, spread_p);
            Swap capLeg_p = new Swap(fixedLeg, cappedLeg_p);

            capLeg_p.setPricingEngine(engine);
            Cap cap_p = new Cap(floatLeg_p, new InitializedList <double>(1, capstrike));

            cap_p.setPricingEngine(vars.makeEngine(vars.volatility));
            npvVanilla   = vanillaLeg_p.NPV();
            npvCappedLeg = capLeg_p.NPV();
            npvCap       = cap_p.NPV();
            error        = Math.Abs(npvCappedLeg - (npvVanilla - npvCap));
            if (error > tolerance)
            {
                QAssert.Fail("\nCapped Leg: gearing=" + gearing_p + ", " +
                             "spread= " + spread_p * 100 +
                             "%, strike=" + capstrike * 100 + "%, " +
                             "effective strike= " + (capstrike - spread_p) / gearing_p * 100 +
                             "%\n" +
                             "  Capped Floating Leg NPV: " + npvCappedLeg + "\n" +
                             "  Vanilla Leg NPV: " + npvVanilla + "\n" +
                             "  Cap NPV: " + npvCap + "\n" +
                             "  Floating Leg NPV - Cap NPV: " + (npvVanilla - npvCap) + "\n" +
                             "  Diff: " + error);
            }

            // Negative gearing
            List <CashFlow> cappedLeg_n = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors0,
                                                                 vars.volatility, gearing_n, spread_n);
            Swap capLeg_n = new Swap(fixedLeg, cappedLeg_n);

            capLeg_n.setPricingEngine(engine);
            Floor floor_n = new Floor(floatLeg, new InitializedList <double>(1, (capstrike - spread_n) / gearing_n));

            floor_n.setPricingEngine(vars.makeEngine(vars.volatility));
            npvVanilla   = vanillaLeg_n.NPV();
            npvCappedLeg = capLeg_n.NPV();
            npvFloor     = floor_n.NPV();
            error        = Math.Abs(npvCappedLeg - (npvVanilla + gearing_n * npvFloor));
            if (error > tolerance)
            {
                QAssert.Fail("\nCapped Leg: gearing=" + gearing_n + ", " +
                             "spread= " + spread_n * 100 +
                             "%, strike=" + capstrike * 100 + "%, " +
                             "effective strike= " + (capstrike - spread_n) / gearing_n * 100 +
                             "%\n" +
                             "  Capped Floating Leg NPV: " + npvCappedLeg + "\n" +
                             "  npv Vanilla: " + npvVanilla + "\n" +
                             "  npvFloor: " + npvFloor + "\n" +
                             "  Floating Leg NPV - Cap NPV: " + (npvVanilla + gearing_n * npvFloor) + "\n" +
                             "  Diff: " + error);
            }

            /* gearing = a and spread = b
             * FLOORED coupon - Decomposition of payoff
             * Payoff
             * = Nom * Max(a*rate+b,strike) * accrualperiod =
             * = Nom * [a*rate+b + Max(0,strike-a*rate-b)] * accrualperiod =
             * = Nom * a*rate+b * accrualperiod + Nom * Max(strike-b-a*rate,0) * accrualperiod
             * --> If a>0 (assuming positive effective strike):
             *    Payoff = VanillaFloatingLeg + Put(a*rate+b,strike)
             * --> If a<0 (assuming positive effective strike):
             *    Payoff = VanillaFloatingLeg + Nom * Max(strike-b+|a|*rate+,0) * accrualperiod =
             *          = VanillaFloatingLeg - Call(|a|*rate+b,strike)
             */

            // Positive gearing
            List <CashFlow> flooredLeg_p1 = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps0, floors,
                                                                   vars.volatility, gearing_p, spread_p);
            Swap floorLeg_p1 = new Swap(fixedLeg, flooredLeg_p1);

            floorLeg_p1.setPricingEngine(engine);
            Floor floor_p1 = new Floor(floatLeg_p, new InitializedList <double>(1, floorstrike));

            floor_p1.setPricingEngine(vars.makeEngine(vars.volatility));
            npvVanilla    = vanillaLeg_p.NPV();
            npvFlooredLeg = floorLeg_p1.NPV();
            npvFloor      = floor_p1.NPV();
            error         = Math.Abs(npvFlooredLeg - (npvVanilla + npvFloor));
            if (error > tolerance)
            {
                QAssert.Fail("\nFloored Leg: gearing=" + gearing_p + ", "
                             + "spread= " + spread_p * 100 + "%, strike=" + floorstrike * 100 + "%, "
                             + "effective strike= " + (floorstrike - spread_p) / gearing_p * 100
                             + "%\n" +
                             "  Floored Floating Leg NPV: " + npvFlooredLeg
                             + "\n" +
                             "  Floating Leg NPV + Floor NPV: " + (npvVanilla + npvFloor)
                             + "\n" +
                             "  Diff: " + error);
            }
            // Negative gearing
            List <CashFlow> flooredLeg_n = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps0, floors,
                                                                  vars.volatility, gearing_n, spread_n);
            Swap floorLeg_n = new Swap(fixedLeg, flooredLeg_n);

            floorLeg_n.setPricingEngine(engine);
            Cap cap_n = new Cap(floatLeg, new InitializedList <double>(1, (floorstrike - spread_n) / gearing_n));

            cap_n.setPricingEngine(vars.makeEngine(vars.volatility));
            npvVanilla    = vanillaLeg_n.NPV();
            npvFlooredLeg = floorLeg_n.NPV();
            npvCap        = cap_n.NPV();
            error         = Math.Abs(npvFlooredLeg - (npvVanilla - gearing_n * npvCap));
            if (error > tolerance)
            {
                QAssert.Fail("\nCapped Leg: gearing=" + gearing_n + ", " +
                             "spread= " + spread_n * 100 +
                             "%, strike=" + floorstrike * 100 + "%, " +
                             "effective strike= " + (floorstrike - spread_n) / gearing_n * 100 +
                             "%\n" +
                             "  Capped Floating Leg NPV: " + npvFlooredLeg + "\n" +
                             "  Floating Leg NPV - Cap NPV: " + (npvVanilla - gearing_n * npvCap) + "\n" +
                             "  Diff: " + error);
            }

            /* gearing = a and spread = b
             * COLLARED coupon - Decomposition of payoff
             * Payoff = Nom * Min(caprate,Max(a*rate+b,floorrate)) * accrualperiod
             * --> If a>0 (assuming positive effective strike):
             *    Payoff = VanillaFloatingLeg - Collar(a*rate+b, floorrate, caprate)
             * --> If a<0 (assuming positive effective strike):
             *    Payoff = VanillaFloatingLeg + Collar(|a|*rate+b, caprate, floorrate)
             */
            // Positive gearing
            List <CashFlow> collaredLeg_p = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors,
                                                                   vars.volatility, gearing_p, spread_p);
            Swap collarLeg_p1 = new Swap(fixedLeg, collaredLeg_p);

            collarLeg_p1.setPricingEngine(engine);
            Collar collar_p = new Collar(floatLeg_p, new InitializedList <double>(1, capstrike),
                                         new InitializedList <double>(1, floorstrike));

            collar_p.setPricingEngine(vars.makeEngine(vars.volatility));
            npvVanilla     = vanillaLeg_p.NPV();
            npvCollaredLeg = collarLeg_p1.NPV();
            npvCollar      = collar_p.NPV();
            error          = Math.Abs(npvCollaredLeg - (npvVanilla - npvCollar));
            if (error > tolerance)
            {
                QAssert.Fail("\nCollared Leg: gearing=" + gearing_p + ", "
                             + "spread= " + spread_p * 100 + "%, strike="
                             + floorstrike * 100 + "% and " + capstrike * 100
                             + "%, "
                             + "effective strike=" + (floorstrike - spread_p) / gearing_p * 100
                             + "% and " + (capstrike - spread_p) / gearing_p * 100
                             + "%\n" +
                             "  Collared Floating Leg NPV: " + npvCollaredLeg
                             + "\n" +
                             "  Floating Leg NPV - Collar NPV: " + (npvVanilla - npvCollar)
                             + "\n" +
                             "  Diff: " + error);
            }
            // Negative gearing
            List <CashFlow> collaredLeg_n = vars.makeCapFlooredLeg(vars.startDate, vars.length, caps, floors,
                                                                   vars.volatility, gearing_n, spread_n);
            Swap collarLeg_n1 = new Swap(fixedLeg, collaredLeg_n);

            collarLeg_n1.setPricingEngine(engine);
            Collar collar_n = new Collar(floatLeg, new InitializedList <double>(1, (floorstrike - spread_n) / gearing_n),
                                         new InitializedList <double>(1, (capstrike - spread_n) / gearing_n));

            collar_n.setPricingEngine(vars.makeEngine(vars.volatility));
            npvVanilla     = vanillaLeg_n.NPV();
            npvCollaredLeg = collarLeg_n1.NPV();
            npvCollar      = collar_n.NPV();
            error          = Math.Abs(npvCollaredLeg - (npvVanilla - gearing_n * npvCollar));
            if (error > tolerance)
            {
                QAssert.Fail("\nCollared Leg: gearing=" + gearing_n + ", "
                             + "spread= " + spread_n * 100 + "%, strike="
                             + floorstrike * 100 + "% and " + capstrike * 100
                             + "%, "
                             + "effective strike=" + (floorstrike - spread_n) / gearing_n * 100
                             + "% and " + (capstrike - spread_n) / gearing_n * 100
                             + "%\n" +
                             "  Collared Floating Leg NPV: " + npvCollaredLeg
                             + "\n" +
                             "  Floating Leg NPV - Collar NPV: " + (npvVanilla - gearing_n * npvCollar)
                             + "\n" +
                             "  Diff: " + error);
            }
        }
示例#22
0
文件: Collar.cs 项目: minikie/test
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Collar obj) {
   return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
 }
示例#23
0
 private bool FileNotOnCollar(Collar collar)
 {
     //true if this file is not assigned to this collar
     return(collar.CollarParameters.All(p => p.CollarParameterFile != File));
 }
示例#24
0
        static void Main(string[] args)
        {
            const double tolerance = 10.0;
            //load the strike
            var st = new Strike(OptionType.Call, 100.0);

            var tr = new TransactionDetail("BHP");

            tr.SetStrike(st);
            tr.CurrentSpot = 100.0;
            tr.PayStyle    = PayStyleType.European;
            tr.TradeDate   = DateTime.Parse("25-Mar-2008");
            tr.ExpiryDate  = tr.TradeDate.AddDays(107);


            //set the curvature
            var wc = new[] { new WingCurvature() };

            wc[0].EtoDate = DateTime.Parse("25-Mar-2008");;
            wc[0][WingCurvature.WingCurvatureProperty.CallCurvature]        = -1.1478;
            wc[0][WingCurvature.WingCurvatureProperty.CurrentVolatility]    = 0.2417;
            wc[0][WingCurvature.WingCurvatureProperty.DownCutOff]           = -.2871;
            wc[0][WingCurvature.WingCurvatureProperty.DownSmoothingRange]   = 0.5;
            wc[0][WingCurvature.WingCurvatureProperty.PutCurvature]         = 0.2283;
            wc[0][WingCurvature.WingCurvatureProperty.ReferenceForward]     = 100.0;
            wc[0][WingCurvature.WingCurvatureProperty.SkewSwimmingnessRate] = 100.0;
            wc[0][WingCurvature.WingCurvatureProperty.SlopeChangeRate]      = 0.0;
            wc[0][WingCurvature.WingCurvatureProperty.SlopeReference]       = -0.1234;
            wc[0][WingCurvature.WingCurvatureProperty.UpCutOff]             = 0.1327;
            wc[0][WingCurvature.WingCurvatureProperty.UpSmoothingRange]     = 0.50;
            wc[0][WingCurvature.WingCurvatureProperty.VolChangeRate]        = 0.0;


            DateTime d1   = DateTime.Parse("25-Sep-2008");
            var      div1 = new Dividend(d1, d1.AddDays(10), 1.0, "AUD");

            d1 = DateTime.Parse("26-Oct-2009");
            var div2  = new Dividend(d1, d1.AddDays(10), 1.0, "AUD");
            var dList = new DividendList {
                div1, div2
            };

            var ist = new Stock("BHP", "BHP", dList, wc)
            {
                Transaction = tr
            };

            //set up the zerocurve

            var tDates = new List <DateTime>();
            var tRates = new List <double>();

            tDates.Add(DateTime.Parse("25-Jun-2008"));
            tDates.Add(DateTime.Parse("25-Sep-2008"));

            tRates.Add(0.05);
            tRates.Add(0.05);

            var zc = new ZeroAUDCurve(DateTime.Parse("25-Mar-2008"), tDates, tRates);


            //test the price
            var col = new Collar();


            //test the pricer
            double price = col.FindPrice(ist, zc);

            //test collar
            var st2 = new Strike(OptionType.Call, 102.0);

            ist.Transaction.SetStrike(st2);
            price = col.FindZeroCostPutStrike(ist, zc);


            var st3 = new Strike(OptionType.Put, 98.0);

            ist.Transaction.SetStrike(st3);
            price = col.FindZeroCostCallStrike(ist, zc);


            //Test against an ETO in Orc;

            //load the strike
            var testSt1 = new Strike(OptionType.Put, 3900.00);

            var tr2 = new TransactionDetail("BHP");

            tr2.SetStrike(testSt1);
            tr2.CurrentSpot = 3900.00;
            tr2.PayStyle    = PayStyleType.American;
            tr2.TradeDate   = DateTime.Parse("25-Mar-2008");
            tr2.ExpiryDate  = DateTime.Parse("26-Mar-2009");


            //set the curvature
            var wc2 = new[] { new WingCurvature() };

            wc2[0].EtoDate = DateTime.Parse("25-Mar-2008");
            wc2[0][WingCurvature.WingCurvatureProperty.CallCurvature]        = 0.0;
            wc2[0][WingCurvature.WingCurvatureProperty.CurrentVolatility]    = 0.7056;
            wc2[0][WingCurvature.WingCurvatureProperty.DownCutOff]           = -0.1438;
            wc2[0][WingCurvature.WingCurvatureProperty.DownSmoothingRange]   = 0.0;
            wc2[0][WingCurvature.WingCurvatureProperty.PutCurvature]         = 16.5346;
            wc2[0][WingCurvature.WingCurvatureProperty.ReferenceForward]     = 3440.27;
            wc2[0][WingCurvature.WingCurvatureProperty.SkewSwimmingnessRate] = 92.11;
            wc2[0][WingCurvature.WingCurvatureProperty.SlopeChangeRate]      = 0.0;
            wc2[0][WingCurvature.WingCurvatureProperty.SlopeReference]       = 4.0573;
            wc2[0][WingCurvature.WingCurvatureProperty.UpCutOff]             = 0.0001;
            wc2[0][WingCurvature.WingCurvatureProperty.UpSmoothingRange]     = 82.6825;
            wc2[0][WingCurvature.WingCurvatureProperty.VolChangeRate]        = 0.0;


            DateTime date      = DateTime.Parse("01-Sep-2008");
            var      dividend1 = new Dividend(date, DateTime.Parse("25-Sep-2008"), 34.5, "AUD");

            date = DateTime.Parse("23-Feb-2009");
            var dividend2 = new Dividend(date, DateTime.Parse("17-Mar-2009"), 36.5, "AUD");
            var dList2    = new DividendList {
                dividend1, dividend2
            };

            var ist2 = new Stock("BHP", "BHP", dList2, wc2)
            {
                Transaction = tr2
            };

            //set up the zerocurve

            var tDates2 = new List <DateTime>();
            var tRates2 = new List <double>();

            tDates2.Add(DateTime.Parse("26-Mar-2008"));
            tDates2.Add(DateTime.Parse("26-Apr-2008"));
            tDates2.Add(DateTime.Parse("27-May-2008"));
            tDates2.Add(DateTime.Parse("25-Jun-2008"));
            tDates2.Add(DateTime.Parse("05-Jul-2008"));
            tDates2.Add(DateTime.Parse("04-Oct-2008"));
            tDates2.Add(DateTime.Parse("03-Jan-2009"));
            tDates2.Add(DateTime.Parse("04-Apr-2009"));

            tRates2.Add(0.068646);
            tRates2.Add(0.070701);
            tRates2.Add(0.072238);
            tRates2.Add(0.073009);
            tRates2.Add(0.073086);
            tRates2.Add(0.073792);
            tRates2.Add(0.074177);
            tRates2.Add(0.074375);


            var zc2 = new ZeroAUDCurve(DateTime.Parse("25-Mar-2008"), tDates2, tRates2);

            //test the price
            var col2 = new Collar();

            //test the pricer - put
            double testPrice = col2.FindPrice(ist2, zc2);

            //test the pricer - call
            var _testSt1 = new Strike(OptionType.Call, 5379.10);

            tr2.SetStrike(_testSt1);
            double _testPrice = col2.FindPrice(ist2, zc2);

            //test collar
            var testSt2 = new Strike(OptionType.Call, 5379.10);

            ist2.Transaction.SetStrike(testSt2);
            price = col2.FindZeroCostPutStrike(ist2, zc2);

            var testSt3 = new Strike(OptionType.Put, 3900.00);

            ist2.Transaction.SetStrike(testSt3);
            price = col2.FindZeroCostCallStrike(ist2, zc2);

            //Specify downside strike of 3900:
            // Orc put price @ 3900 744.11
            // Orc call price @ 5379.10 748.30
        }
示例#25
0
        public void testConsistency()
        {
            CommonVars vars = new CommonVars();

            int[] lengths = { 1, 2, 3, 5, 7, 10, 15, 20 };
            double[] cap_rates = { 0.03, 0.04, 0.05, 0.06, 0.07 };
            double[] floor_rates = { 0.03, 0.04, 0.05, 0.06, 0.07 };
            double[] vols = { 0.01, 0.05, 0.10, 0.15, 0.20 };

            Date startDate = vars.termStructure.link.referenceDate();

            for (int i = 0; i < lengths.Length; i++) {
                for (int j = 0; j < cap_rates.Length; j++) {
                    for (int k = 0; k < floor_rates.Length; k++) {
                        for (int l = 0; l < vols.Length; l++) {

                            List<CashFlow> leg = vars.makeLeg(startDate, lengths[i]);
                            Instrument cap = vars.makeCapFloor(CapFloorType.Cap, leg,
                                                  cap_rates[j], vols[l]);
                            Instrument floor = vars.makeCapFloor(CapFloorType.Floor, leg,
                                                  floor_rates[k], vols[l]);
                            Collar collar = new Collar(leg, new InitializedList<double>(1, cap_rates[j]),
                                          new InitializedList<double>(1, floor_rates[k]));
                            collar.setPricingEngine(vars.makeEngine(vols[l]));

                            if (Math.Abs((cap.NPV() - floor.NPV()) - collar.NPV()) > 1e-10) {
                                Assert.Fail(
                                  "inconsistency between cap, floor and collar:\n"
                                  + "    length:       " + lengths[i] + " years\n"
                                  + "    volatility:   " + vols[l] + "\n"
                                  + "    cap value:    " + cap.NPV()
                                  + " at strike: " + cap_rates[j] + "\n"
                                  + "    floor value:  " + floor.NPV()
                                  + " at strike: " + floor_rates[k] + "\n"
                                  + "    collar value: " + collar.NPV());
                            }
                        }
                    }
                }
            }
        }
示例#26
0
        // This is a template for client side usage
        private static void LoadAndProcessFilePath(string filePath, Project project, ProjectInvestigator owner, Collar collar,
                                                   char status, bool allowDups)
        {
            var fileLoader = new FileLoader(filePath)
            {
                Project         = project,
                Owner           = owner,
                Collar          = collar,
                Status          = status,
                AllowDuplicates = allowDups
            };
            var file = fileLoader.Load();

            if (file.LookupCollarFileFormat.ArgosData == 'Y' || file.Format == 'H')
            {
                FileProcessor.ProcessFile(file);
            }
        }
示例#27
0
 private static bool MissingArgosDeployment(Collar collar, string argosId)
 {
     return(collar.ArgosDeployments.All(a => a.PlatformId != argosId));
 }
示例#28
0
 private bool ParameterExistsWithDate(Collar collar, DateTime paramaterStart)
 {
     //possible, though not probable, or even logical, for collar to have more than one parameter set (different date ranges) with File
     //If any of the parameters match, assume we are goodone of them matches
     return(collar.CollarParameters.Any(p => p.CollarParameterFile == File && p.StartDate == paramaterStart));
 }
示例#29
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Collar obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
示例#30
0
        /// <summary>
        /// Attempts to load the file (or all the files in a folder) into the database
        /// </summary>
        /// <param name="path">A complete file or folder path to data that will be loaded</param>
        /// <param name="handler">Delegate to handle exceptions on each file, so that processing can continue.
        /// If the handler is null, processing will stop on first exception.
        /// The handler can throw it's own exception to halt further processing</param>
        /// <param name="project">Associate the new file with this Project (optional)</param>
        /// <param name="manager">Associate the new file with this Project Investigator (optional)</param>
        /// <param name="collar">This file contains data for this collar.  Not required for files with Argos data, or
        /// if the collar can be determined from the file contents</param>
        /// <param name="status">The new file should be (A)ctive (generate fixes, default) or (I)nactive (no fixes)</param>
        /// <param name="allowDups">File will not be rejected if the contents match an existing file</param>
        /// <remarks>Only one of project and manager can be non-null.</remarks>
        public static void LoadPath(string path, Action <Exception, string, Project, ProjectInvestigator> handler = null,
                                    Project project = null, ProjectInvestigator manager = null, Collar collar = null,
                                    char status     = 'A', bool allowDups = false)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path", "A path must be provided");
            }
            if (project != null && manager != null)
            {
                throw new InvalidOperationException(
                          String.Format("Project: {0} and Manager: {1} cannot both be non-null.", project.ProjectId,
                                        manager.Login));
            }

            if (File.Exists(path))
            {
                try
                {
                    LoadAndProcessFilePath(path, project, manager, collar, status, allowDups);
                }
                catch (Exception ex)
                {
                    if (handler == null)
                    {
                        throw;
                    }
                    handler(ex, path, project, manager);
                }
            }
            else
            {
                if (Directory.Exists(path))
                {
                    foreach (var file in Directory.EnumerateFiles(path))
                    {
                        try
                        {
                            LoadAndProcessFilePath(file, project, manager, collar, status, allowDups);
                        }
                        catch (Exception ex)
                        {
                            if (handler == null)
                            {
                                throw;
                            }
                            handler(ex, file, project, manager);
                        }
                    }
                }
                else
                {
                    throw new InvalidOperationException(path + " is not a folder or file");
                }
            }
        }