diff --git a/src/client/spark/Analytics/Core/GeneralVolSurfaceCalculator.cs b/src/client/spark/Analytics/Core/GeneralVolSurfaceCalculator.cs new file mode 100644 index 000000000..3b2c362dd --- /dev/null +++ b/src/client/spark/Analytics/Core/GeneralVolSurfaceCalculator.cs @@ -0,0 +1,179 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Collections.Concurrent; + +using bts; + +namespace mbts.analytics +{ + /// VolModels that can represent their data as GeneralVolSurfaceParameters + /// can be handled in a general way by this surface calculator + public partial class GeneralVolSurfaceCalculator + { + public static VolSurfaceOutput compute(VolSurfaceInput vs_input, + IDictionary> exp_strike_map, + IDictionary aux_data_map) + { + return compute(vs_input, exp_strike_map, aux_data_map, null, null); + } + + /// secs_filter is filter, only those securties + /// will be calculated + public static VolSurfaceOutput compute(VolSurfaceInput vs_input, + IDictionary> exp_strike_map, + IDictionary aux_data_map, + IDictionary action_map, + IDictionary> secs_filter, + bool cascade_up = false, bool cascade_down = false) + { + vs_input = VolSurfaceDataFunctions.sync_volsurface_input_to_settings(vs_input); + ///vs_input, aux_data_map and action_map are all synced exp_strike_map for exps + vs_input = VolSurfaceDataFunctions.sync_input_expirations_to_master_list(vs_input, exp_strike_map.Keys); + vs_input.surface_settings.advanced_settings = vs_input.surface_settings.advanced_settings ?? new VolSurfaceAdvancedSettings() { strike_normalization_axis = VolSurfaceEnums.VolCurveStrikeAxis.RawStrike }; + aux_data_map = VolSurfaceUtilityFunctions.sync_map_exps(exp_strike_map.Keys, aux_data_map, true, vs_exp => VolSurfaceExpirationAuxiliaryData.empty); + action_map = action_map ?? new Dictionary(); + vs_input = _adjust_input_for_slave_actions(vs_input, action_map, aux_data_map); + /// action_map will be made more clear in the future. Right now its enough + /// to assume that it will be the same action across all expirations + action_map.ForEach(kv => Log.assert(kv.Value.action_type == VolCurveAction.ActionType.None || kv.Value.action_type == action_map.ElementAt(0).Value.action_type)); + action_map = VolSurfaceUtilityFunctions.apply_cascade_to_action_map(exp_strike_map.Keys, action_map, cascade_up, cascade_down); + action_map = VolSurfaceUtilityFunctions.sync_map_exps(exp_strike_map.Keys, action_map, true, vs_exp => new VolCurveAction(VolCurveAction.ActionType.None)); + secs_filter = secs_filter == null ? secs_filter : _adjust_filters_for_missing_masters(vs_input, secs_filter); + return _compute_no_interp(vs_input, exp_strike_map, aux_data_map, action_map, secs_filter); + } + + /// If the action is only limited to slaves, its generally changing + /// its input based on the master's. + private static VolSurfaceInput _adjust_input_for_slave_actions(VolSurfaceInput vs_input, + IDictionary action_map, + IDictionary aux_data_map) + { + VolSurfaceInput rv = vs_input; + if (action_map.Count() > 0 && action_map.ElementAt(0).Value.action_type == VolCurveAction.ActionType.SyncSlaveRefFwds) + { + HashSet slave_exps = VolSurfaceUtilityFunctions.get_slave_expirations(vs_input); + VolSurfaceUtilityFunctions.are_hashsets_equal(VolSurfaceUtilityFunctions.get_slave_expirations(vs_input), new HashSet(action_map.Keys)); + rv = VolSurfaceCoreFunctions.sync_slave_ref_fwds_to_masters(vs_input, aux_data_map, action_map.Keys); + } + return rv; + } + + + /// Simpler version of _compute, does not interp unfilled exps + private static VolSurfaceOutput _compute_no_interp(VolSurfaceInput vs_input, + IDictionary> exp_strike_map, + IDictionary aux_data_map, + IDictionary vol_curve_action_map, + IDictionary> secs_filter) + { + Log.assert(VolSurfaceUtilityFunctions.are_hashsets_equal(new HashSet(exp_strike_map.Keys), + new HashSet(vs_input.surface_parameters.curve_parameters_map.Select(t => t.Item1)), + new HashSet(aux_data_map.Keys), + new HashSet(vol_curve_action_map.Keys))); + IDictionary computed_map = new ConcurrentDictionary(); + secs_filter = secs_filter ?? exp_strike_map.ToDictionary(kv => kv.Key, kv => new HashSet()); + //Parallel.ForEach(exp_strike_map.ToList(), kv => + exp_strike_map.ToList().ForEach(kv => + { + VolSurfaceExpiration exp = kv.Key; + IEnumerable strikes = kv.Value; + VolCurveParameters curve_parameters = VolSurfaceDataFunctions.get_curve_parameters(vs_input, exp); + VolSurfaceExpirationAuxiliaryData aux_data = aux_data_map.TryGetValue(exp, out aux_data) ? aux_data : VolSurfaceExpirationAuxiliaryData.empty; + VolCurveAction curve_action = vol_curve_action_map.TryGetValue(exp, out curve_action) ? curve_action : new VolCurveAction(VolCurveAction.ActionType.None); + if (VolSurfaceUtilityFunctions.is_master_expiration(exp, vs_input.surface_settings) || curve_parameters.core_parameters.unhinge_exp_from_master) + { + if (secs_filter.ContainsKey(exp)) + { + MyVolCurveStitcher curve_stitcher = new MyVolCurveStitcher(exp, strikes, vs_input.surface_settings, curve_parameters, aux_data, curve_action); + computed_map.Add(exp, curve_stitcher.get_output()); + } + else + computed_map.Add(exp, VolCurveOutput.get_empty_output(aux_data.fwd, curve_parameters, VolSurfaceEnums.VolSurfaceExpirationCalculationMethod.Master)); + } + }); + IEnumerable>> remaining_exps = exp_strike_map.Where(exp_i => !computed_map.ContainsKey(exp_i.Key)); + remaining_exps.ToList().ForEach(kv => + { + VolSurfaceExpiration slave_exp = kv.Key; + VolCurveParameters slave_curve_parameters = VolSurfaceDataFunctions.get_curve_parameters(vs_input, slave_exp); + VolSurfaceExpirationAuxiliaryData slave_aux_data = aux_data_map.TryGetValue(slave_exp, out slave_aux_data) ? slave_aux_data : VolSurfaceExpirationAuxiliaryData.empty; + if (secs_filter.ContainsKey(slave_exp)) + { + VolSurfaceExpiration master_exp = VolSurfaceUtilityFunctions.find_master_expiration(slave_exp, vs_input.surface_settings, vs_input.surface_parameters.curve_parameters_map.Select(t => t.Item1)); + if (master_exp != null) + { + VolCurveAction master_action = vol_curve_action_map.TryGetValue(master_exp, out master_action) ? master_action : new VolCurveAction(VolCurveAction.ActionType.None); + VolCurveOutput master_output; + VolCurveParameters master_exp_input_params = VolSurfaceDataFunctions.get_curve_parameters(vs_input, master_exp); + if (computed_map.TryGetValue(master_exp, out master_output) && master_exp_input_params != null) + computed_map[slave_exp] = _compute_slave_from_master_input_incremental(vs_input.surface_settings, slave_exp, slave_curve_parameters, kv.Value, slave_aux_data, master_action, master_exp_input_params, master_output); + } + else /// no master + computed_map[slave_exp] = VolCurveOutput.get_empty_output(slave_aux_data.fwd, slave_curve_parameters, VolSurfaceEnums.VolSurfaceExpirationCalculationMethod.UnlinkedSlave); + } + else + computed_map[slave_exp] = VolCurveOutput.get_empty_output(slave_aux_data.fwd, slave_curve_parameters, VolSurfaceEnums.VolSurfaceExpirationCalculationMethod.Slave); + }); + foreach (KeyValuePair kv in computed_map) + VolSurfaceDataFunctions.set_curve_parameters(vs_input, kv.Key, kv.Value.adjusted_curve_parameters); + return new VolSurfaceOutput(vs_input, computed_map, aux_data_map); + } + + /// This is the main function where the slave is computed + private static VolCurveOutput _compute_slave_from_master_input_incremental(VolSurfaceSettings vs_settings, + VolSurfaceExpiration slave_exp, + VolCurveParameters slave_exp_input_params, + IEnumerable slave_exp_strikes, + VolSurfaceExpirationAuxiliaryData slave_exp_aux_data, + VolCurveAction master_exp_action, + VolCurveParameters master_exp_params, + VolCurveOutput master_output) + { + /// TODO : if it cant compute, dont change the input + master_exp_action = master_exp_action ?? new VolCurveAction(VolCurveAction.ActionType.None); + VolCurveOutput rv; + VolCurveParameters slave_inferred_params = VolSurfaceDataFunctions.get_effective_slave_parameters(vs_settings, master_output.adjusted_curve_parameters, slave_exp_input_params); + if (VolSurfaceUtilityFunctions.is_rebuild_action (master_exp_action)) + { + /// this is the only change ever made to the slave parameters + /// by the system automatically + slave_exp_input_params.core_parameters.ref_forward = slave_inferred_params.core_parameters.ref_forward = slave_exp_aux_data.fwd; + MyVolCurveStitcher curve_stitcher = new MyVolCurveStitcher(slave_exp, slave_exp_strikes, vs_settings, slave_inferred_params, slave_exp_aux_data, new VolCurveAction(VolCurveAction.ActionType.None)); + rv = curve_stitcher.get_output(); + } + else + { + MyVolCurveStitcher curve_stitcher = new MyVolCurveStitcher(slave_exp, slave_exp_strikes, vs_settings, slave_inferred_params, slave_exp_aux_data, new VolCurveAction(VolCurveAction.ActionType.None)); + rv = curve_stitcher.get_output(); + } + return VolCurveOutput.replace_curve_inputs(rv, slave_exp_input_params); + } + + /// For slaves with no masters in the filter, + /// it adds the masters for such slaves + private static IDictionary> _adjust_filters_for_missing_masters(VolSurfaceInput vs_input, + IDictionary> secs_filter) + { + if (secs_filter != null) + { + IEnumerable vs_exps = vs_input.surface_parameters.curve_parameters_map.Select(t => t.Item1); + Dictionary> rv = new Dictionary>(secs_filter); + foreach (KeyValuePair> kv in secs_filter) + { + if (VolSurfaceUtilityFunctions.is_slave_expiration(kv.Key, vs_input.surface_settings)) + { + VolSurfaceExpiration master_exp = VolSurfaceUtilityFunctions.find_master_expiration(kv.Key, vs_input.surface_settings, vs_exps); + if (master_exp != null && !secs_filter.ContainsKey(master_exp)) + rv[master_exp] = new HashSet(); + } + } + return rv; + } + else + return null; + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Core/GeneralVolSurfaceCalculatorCurveStitcher.cs b/src/client/spark/Analytics/Core/GeneralVolSurfaceCalculatorCurveStitcher.cs new file mode 100644 index 000000000..074ffa0ab --- /dev/null +++ b/src/client/spark/Analytics/Core/GeneralVolSurfaceCalculatorCurveStitcher.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public partial class GeneralVolSurfaceCalculator + { + private class MyVolCurveStitcher + { + private readonly bool _initialized = false; + private readonly VolCurveOutput _output; + + public MyVolCurveStitcher(VolSurfaceExpiration exp, + IEnumerable tradable_strikes, + VolSurfaceSettings surface_setting, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + VolCurveAction curve_action) + { + VolSurfaceEnums.VolSurfaceExpirationCalculationMethod calc_method = VolSurfaceEnums.VolSurfaceExpirationCalculationMethod.Master; + if (!VolSurfaceUtilityFunctions.is_master_expiration(exp, surface_setting)) + calc_method = curve_parameters.core_parameters.unhinge_exp_from_master ? VolSurfaceEnums.VolSurfaceExpirationCalculationMethod.UnlinkedSlave : VolSurfaceEnums.VolSurfaceExpirationCalculationMethod.Slave; + IVolCurveMainCalculator main_calculator = VolSurfaceCalculatorFactory.get_curve_calculator(surface_setting); + IVolCurveWingCalculator wing_calculator = VolSurfaceCalculatorFactory.get_wing_calculator(surface_setting); + IVolPathCalculator path_calculator = VolSurfaceCalculatorFactory.get_path_calculator(surface_setting); + path_calculator.initialize_for_lifetime(exp, surface_setting, curve_parameters.core_parameters.vol_path_parameters); + double path_induced_atm_vol_move = path_calculator.get_atm_vol_move(curve_parameters.core_parameters.ref_forward, aux_data.fwd); + main_calculator.initialize_for_lifetime(exp, surface_setting, curve_parameters, aux_data, path_induced_atm_vol_move, curve_action); + wing_calculator.initialize_for_lifetime(surface_setting, curve_parameters.core_parameters.put_wing_parameters, curve_parameters.core_parameters.call_wing_parameters, main_calculator.get_output(), curve_action); + if (main_calculator.is_initialized()) + { + _initialized = true; + VolCurveMainOutput main_curve_output = main_calculator.get_output(); + VolCurveWingOutput wing_output = wing_calculator.get_output(); + main_curve_output.adjusted_curve_parameters.core_parameters.put_wing_parameters = wing_output.adjusted_put_wing_parameters; + main_curve_output.adjusted_curve_parameters.core_parameters.call_wing_parameters = wing_output.adjusted_call_wing_parameters; + Func compute_vol = (k, k_axis) => + { + double raw_k = main_curve_output.convert_axis(k_axis, k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + bool is_part_of_main_curve = raw_k >= main_curve_output.put_end_raw_strike && raw_k <= main_curve_output.call_end_raw_strike; + return is_part_of_main_curve ? main_curve_output.get_dvol(raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 0) : wing_output.get_dvol(raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 0); + }; + Func compute_path_vol = fwd => path_calculator.get_atm_vol_move(main_curve_output.adjusted_curve_parameters.core_parameters.ref_forward, fwd) + main_curve_output.input_atm_vol; + _output = new VolCurveOutput(main_curve_output.fwd, main_curve_output.conversion_fwd, main_curve_output.conversion_fwd, main_curve_output.final_atm_vol, main_curve_output.conversion_vol, aux_data, + tradable_strikes, main_curve_output.adjusted_curve_parameters, + main_curve_output.special_call_points.Select(t => Tuple.Create(t, main_curve_output.get_dvol(t, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 0))), + main_curve_output.special_put_points.Select(t => Tuple.Create(t, main_curve_output.get_dvol(t, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 0))), + main_curve_output.call_end_raw_strike, main_curve_output.put_end_raw_strike, compute_vol, main_curve_output.convert_axis, compute_path_vol, calc_method, + VolSurfaceCoreFunctions.compute_diagnostic_data(exp, surface_setting, compute_vol, main_curve_output.convert_axis, aux_data)); + } + else + { + bool is_master = VolSurfaceUtilityFunctions.is_master_expiration(exp, surface_setting); + _output = VolCurveOutput.get_empty_output(aux_data.fwd, curve_parameters, is_master ? VolSurfaceEnums.VolSurfaceExpirationCalculationMethod.Master : VolSurfaceEnums.VolSurfaceExpirationCalculationMethod.Slave); + } + } + + public bool initialized { get { return _initialized; } } + + public VolCurveOutput get_output() { return _output; } + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Core/IVolCurveMainCalculator.cs b/src/client/spark/Analytics/Core/IVolCurveMainCalculator.cs new file mode 100644 index 000000000..132de69ea --- /dev/null +++ b/src/client/spark/Analytics/Core/IVolCurveMainCalculator.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// This is the calculator to compute values for the + /// meat of the curve (vs the IVolCurveWingCalculator + /// which computed values outside the meat) + public interface IVolCurveMainCalculator : IDisposable + { + void initialize_for_lifetime(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action); + bool is_initialized(); + VolCurveParameters fill_missing_inputs(VolCurveParameters main, VolCurveParameters secondary); + VolCurveMainOutput get_output(); + } +} diff --git a/src/client/spark/Analytics/Core/Output/VolCurveMainOutput.cs b/src/client/spark/Analytics/Core/Output/VolCurveMainOutput.cs new file mode 100644 index 000000000..9a7f448a4 --- /dev/null +++ b/src/client/spark/Analytics/Core/Output/VolCurveMainOutput.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class VolCurveMainOutput + { + public readonly double fwd, conversion_fwd; + public readonly double input_atm_vol, final_atm_vol, conversion_vol; + public readonly IEnumerable special_put_points, special_call_points; + public readonly double put_end_raw_strike, call_end_raw_strike; + public readonly VolCurveParameters adjusted_curve_parameters; + public readonly VolSurfaceExpirationAuxiliaryData aux_data; + public readonly Func get_dvol; + public readonly Func convert_axis; + + public VolCurveMainOutput(double this_fwd, + double this_conversion_fwd, + double this_input_atm_vol, + double this_final_atm_vol, + double this_conversion_vol, + IEnumerable this_special_put_points, + IEnumerable this_special_call_points, + double this_put_end_raw_strike, + double this_call_end_raw_strike, + VolCurveParameters this_adjusted_parameters, + VolSurfaceExpirationAuxiliaryData this_aux_data, + Func this_get_dvol, + Func this_convert_axis) + { + fwd = this_fwd; + conversion_fwd = this_conversion_fwd; + input_atm_vol = this_input_atm_vol; + final_atm_vol = this_final_atm_vol; + conversion_vol = this_conversion_vol; + special_put_points = this_special_put_points; + special_call_points = this_special_call_points; + put_end_raw_strike = this_put_end_raw_strike; + call_end_raw_strike = this_call_end_raw_strike; + adjusted_curve_parameters = this_adjusted_parameters; + aux_data = this_aux_data; + get_dvol = this_get_dvol; + convert_axis = this_convert_axis; + } + } +} diff --git a/src/client/spark/Analytics/Core/Output/VolCurveOutput.cs b/src/client/spark/Analytics/Core/Output/VolCurveOutput.cs new file mode 100644 index 000000000..ca27d5151 --- /dev/null +++ b/src/client/spark/Analytics/Core/Output/VolCurveOutput.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// Output for one expiration/curve + public class VolCurveOutput + { + public readonly VolCurveParameters adjusted_curve_parameters; + public readonly double fwd, conversion_fwd, atm_tradable_strike, atm_vol, conversion_vol; + public readonly VolSurfaceExpirationAuxiliaryData aux_data; + public readonly IEnumerable tradeable_strikes; + public readonly IEnumerable> optional_call_control_points, optional_put_control_points; + public readonly double optional_call_wing_start, optional_put_wing_start; + public readonly Func compute_vol; + public readonly Func convert_strike_axis; + public readonly Func compute_path_vol; + public readonly VolSurfaceEnums.VolSurfaceExpirationCalculationMethod calc_method; + public readonly VolCurveOutputDiagnosticData diagnostics_data; + + public VolCurveOutput(double this_fwd, + double this_conversion_fwd, + double this_atm_strike, + double this_atm_vol, + double this_conversion_vol, + VolSurfaceExpirationAuxiliaryData this_aux_data, + IEnumerable this_tradeable_strikes, + VolCurveParameters this_curve_parameters, + IEnumerable> this_optional_call_control_points, + IEnumerable> this_optional_put_control_points, + double this_optional_call_wing_start, + double this_optional_put_wing_start, + Func this_compute_vol, + Func this_convert_strike_axis, + Func this_compute_path_vol, + VolSurfaceEnums.VolSurfaceExpirationCalculationMethod this_calc_method, + VolCurveOutputDiagnosticData diagnostics_data) + { + compute_vol = this_compute_vol; + fwd = this_fwd; + conversion_fwd = this_conversion_fwd; + atm_tradable_strike = this_atm_strike; + atm_vol = this_atm_vol; + conversion_vol = this_conversion_vol; + aux_data = this_aux_data; + tradeable_strikes = this_tradeable_strikes; + adjusted_curve_parameters = this_curve_parameters; + optional_call_control_points = this_optional_call_control_points; + optional_put_control_points = this_optional_put_control_points; + optional_call_wing_start = this_optional_call_wing_start; + optional_put_wing_start = this_optional_put_wing_start; + compute_vol = this_compute_vol; + convert_strike_axis = this_convert_strike_axis; + compute_path_vol = this_compute_path_vol; + calc_method = this_calc_method; + this.diagnostics_data = diagnostics_data ?? VolCurveOutputDiagnosticData.empty; + } + + private IDictionary _strike_vol_map = null; + public IDictionary strike_vol_map + { + get + { + if (_strike_vol_map == null) + { + lock (typeof(VolCurveOutput)) + { + if (_strike_vol_map == null) + { + _strike_vol_map = new Dictionary(); + foreach (double rawk in tradeable_strikes) + _strike_vol_map[rawk] = compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + } + } + } + return _strike_vol_map; + } + } + + public static VolCurveOutput get_empty_output(double this_fwd, VolCurveParameters this_curve_parameters, VolSurfaceEnums.VolSurfaceExpirationCalculationMethod this_calc_method = VolSurfaceEnums.VolSurfaceExpirationCalculationMethod.Master) + { + return new VolCurveOutput(this_fwd, Double.NaN, Double.NaN, Double.NaN, Double.NaN, VolSurfaceExpirationAuxiliaryData.empty, Enumerable.Empty(), this_curve_parameters, null, null, Double.NaN, Double.NaN, + (k, axis) => Double.NaN, (source_axis, k, target_exis) => Double.NaN, f => Double.NaN, this_calc_method, VolCurveOutputDiagnosticData.empty); + } + + public static VolCurveOutput replace_curve_inputs(VolCurveOutput source, VolCurveParameters this_curve_parameters) + { + return new VolCurveOutput(source.fwd, source.conversion_fwd, source.atm_tradable_strike, source.atm_vol, source.conversion_vol, source.aux_data, source.tradeable_strikes, this_curve_parameters, + source.optional_call_control_points, source.optional_put_control_points, source.optional_call_wing_start, source.optional_put_wing_start, + source.compute_vol, source.convert_strike_axis, source.compute_path_vol, source.calc_method, source.diagnostics_data); + } + } +} diff --git a/src/client/spark/Analytics/Core/Output/VolCurveOutputDiagnosticData.cs b/src/client/spark/Analytics/Core/Output/VolCurveOutputDiagnosticData.cs new file mode 100644 index 000000000..d325214d9 --- /dev/null +++ b/src/client/spark/Analytics/Core/Output/VolCurveOutputDiagnosticData.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class VolCurveOutputDiagnosticData + { + public static readonly VolCurveOutputDiagnosticData empty = new VolCurveOutputDiagnosticData(Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, + Double.NaN, Double.NaN, Double.NaN, Double.NaN, double.NaN); + + public readonly double atm_straddle, + risk_reversal, + strangle, + put_butterfly, + call_butterfly, + slope, + curvature, + put_tail, + call_tail, + box; + + public VolCurveOutputDiagnosticData(double atm_straddle, + double risk_reversal, + double strangle, + double put_butterfly, + double call_butterfly, + double slope, + double curvature, + double put_tail, + double call_tail, + double box) + { + this.atm_straddle = atm_straddle; + this.risk_reversal = risk_reversal; + this.strangle = strangle; + this.put_butterfly = put_butterfly; + this.call_butterfly = call_butterfly; + + this.slope = slope; + this.curvature = curvature; + this.put_tail = put_tail; + this.call_tail = call_tail; + this.box = box; + } + } +} diff --git a/src/client/spark/Analytics/Core/Output/VolCurveWingOutput.cs b/src/client/spark/Analytics/Core/Output/VolCurveWingOutput.cs new file mode 100644 index 000000000..56f51d483 --- /dev/null +++ b/src/client/spark/Analytics/Core/Output/VolCurveWingOutput.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class VolCurveWingOutput + { + public readonly VolCurveWingParameters adjusted_put_wing_parameters, adjusted_call_wing_parameters; + public readonly Func get_dvol; + + public VolCurveWingOutput(VolCurveWingParameters this_adjusted_put_wing_parameters, + VolCurveWingParameters this_adjusted_call_wing_parameters, + Func this_get_dvol) + { + adjusted_put_wing_parameters = this_adjusted_put_wing_parameters; + adjusted_call_wing_parameters = this_adjusted_call_wing_parameters; + get_dvol = this_get_dvol; + } + } +} diff --git a/src/client/spark/Analytics/Core/Output/VolSurfaceOutput.cs b/src/client/spark/Analytics/Core/Output/VolSurfaceOutput.cs new file mode 100644 index 000000000..f66fceba7 --- /dev/null +++ b/src/client/spark/Analytics/Core/Output/VolSurfaceOutput.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// Contains the input (and settings) and vol per strike + public class VolSurfaceOutput : ICloneable + { + public readonly VolSurfaceInput volsurface_input; + public readonly IDictionary exp_output_map; + public readonly IDictionary aux_data_map; + + public VolSurfaceOutput(VolSurfaceInput this_volsurface_input, + IDictionary this_exp_output_map, + IDictionary this_aux_data_map) + { + volsurface_input = this_volsurface_input; + exp_output_map = this_exp_output_map; + aux_data_map = this_aux_data_map; + } + + public VolCurveOutput this[VolSurfaceExpiration exp] + { + get + { + VolCurveOutput rv = exp_output_map != null && exp_output_map.TryGetValue(exp, out rv) ? rv : VolCurveOutput.get_empty_output(Double.NaN, null); + return rv; + } + } + + public DateTime get_vol_time() + { + /// TODO : this should be part of the data vs being in each exp + /// (with the baked in assumption that its the same) + return (aux_data_map != null && aux_data_map.Count > 0) ? aux_data_map.ElementAt(0).Value.base_vol_time : DateTime.MinValue; + } + + public object Clone() + { + return null; + // TODO + // return new VolSurfaceOutput(VolSurfaceUtilityFunctions.clone_proto(volsurface_input), + // new Dictionary(exp_output_map), + // new Dictionary(aux_data_map)); + } + + public static VolSurfaceOutput get_empty_output() + { + return new VolSurfaceOutput(new VolSurfaceInput(), + new Dictionary(), + new Dictionary()); + } + } +} diff --git a/src/client/spark/Analytics/Core/Parameters/VolCurveCoreParameters.cs b/src/client/spark/Analytics/Core/Parameters/VolCurveCoreParameters.cs new file mode 100644 index 000000000..17ec3030d --- /dev/null +++ b/src/client/spark/Analytics/Core/Parameters/VolCurveCoreParameters.cs @@ -0,0 +1,112 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// The complete vol specific input (ie not including + /// Time and Fwd's etc) that are needed for + /// computing the vols for a single expiration + /// are here. + [ProtoBuf.ProtoContract(Name = "VolCurveCoreParameters")] + public class VolCurveCoreParameters + { + [ProtoBuf.ProtoMember(10)] + public VolCurveWingParameters call_wing_parameters; + [ProtoBuf.ProtoMember(20)] + public VolCurveWingParameters put_wing_parameters; + [ProtoBuf.ProtoMember(30)] + public double ref_forward = Double.NaN; + [ProtoBuf.ProtoMember(40)] + public double standard_vol = Double.NaN; + [ProtoBuf.ProtoMember(50)] + public VolPathParameters vol_path_parameters; + [ProtoBuf.ProtoMember(60)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double vol_shift = Double.NaN; + [ProtoBuf.ProtoMember(70)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double time_shift = Double.NaN; + [ProtoBuf.ProtoMember(80)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double driver_override = Double.NaN; + [ProtoBuf.ProtoMember(90)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double settlement_price = Double.NaN; + [ProtoBuf.ProtoMember(100)] + [System.ComponentModel.DefaultValue(false)] + public bool unhinge_exp_from_master = false; + [ProtoBuf.ProtoMember(110)] + [System.ComponentModel.DefaultValue(0.0)] + public double conversion_fwd_slider; + [ProtoBuf.ProtoMember(120)] + [System.ComponentModel.DefaultValue(0.0)] + public double conversion_vol_slider; + + // public static explicit operator VolCurveCoreParameters(bts.api.analytics.APIVolCurveCoreParameters other) + // { + // return new VolCurveCoreParameters + // { + // put_wing_parameters = new VolCurveWingParameters + // { + // explicit_slope_wing_parameters = new VolCurveExplicitSlopeWingParameters + // { + // distance = other.left_wing_distance, + // main_curve_decay = other.left_wing_decay, + // slope = other.left_wing_slope + // } + // }, + // call_wing_parameters = new VolCurveWingParameters + // { + // explicit_slope_wing_parameters = new VolCurveExplicitSlopeWingParameters + // { + // distance = other.right_wing_distance, + // main_curve_decay = other.right_wing_decay, + // slope = other.right_wing_slope + // } + // }, + // ref_forward = other.ref_forward, + // standard_vol = other.standard_vol, + // vol_path_parameters = new VolPathParameters + // { + // two_way_slope_vol_path_parameters = new TwoWaySlopeVolPathParameters + // { + // vol_move_for_unit_fwd_down = other.dn_response, + // vol_move_for_unit_fwd_up = other.up_response, + // max_vol_increase = 100.0, + // max_vol_decrease = 100.0, + // } + // }, + // vol_shift = other.vol_shift, + // time_shift = other.time_shift, + // driver_override = other.driver_override, + // }; + // } + + // public static explicit operator bts.api.analytics.APIVolCurveCoreParameters(VolCurveCoreParameters other) + // { + // var put_wing = other.put_wing_parameters.explicit_slope_wing_parameters ?? new VolCurveExplicitSlopeWingParameters(); + // var call_wing = other.call_wing_parameters.explicit_slope_wing_parameters ?? new VolCurveExplicitSlopeWingParameters(); + // var response = other.vol_path_parameters.two_way_slope_vol_path_parameters ?? new TwoWaySlopeVolPathParameters(); + // return new bts.api.analytics.APIVolCurveCoreParameters + // { + // left_wing_slope = put_wing.slope, + // left_wing_distance = put_wing.distance, + // left_wing_decay = put_wing.main_curve_decay, + + // right_wing_slope = call_wing.slope, + // right_wing_distance = call_wing.distance, + // right_wing_decay = call_wing.main_curve_decay, + // ref_forward = other.ref_forward, + // standard_vol = other.standard_vol, + // dn_response = response.vol_move_for_unit_fwd_down, + // up_response = response.vol_move_for_unit_fwd_up, + // vol_shift = other.vol_shift, + // time_shift = other.time_shift, + // driver_override = other.driver_override, + // }; + // } + } +} diff --git a/src/client/spark/Analytics/Core/Parameters/VolCurveNonVolParameters.cs b/src/client/spark/Analytics/Core/Parameters/VolCurveNonVolParameters.cs new file mode 100644 index 000000000..ab272ca42 --- /dev/null +++ b/src/client/spark/Analytics/Core/Parameters/VolCurveNonVolParameters.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolCurveNonVolParameters")] + public class VolCurveNonVolParameters + { + [ProtoBuf.ProtoMember(10)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double riskless_rate; + + [ProtoBuf.ProtoMember(20)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double roll_target; + + [ProtoBuf.ProtoMember(30)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double roll_offset; + } +} diff --git a/src/client/spark/Analytics/Core/Parameters/VolCurveParameters.cs b/src/client/spark/Analytics/Core/Parameters/VolCurveParameters.cs new file mode 100644 index 000000000..6a86632d9 --- /dev/null +++ b/src/client/spark/Analytics/Core/Parameters/VolCurveParameters.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// All models that use GeneralVolSurfaceParameters to represent + /// their parameters, will have an entry here + [ProtoBuf.ProtoContract(Name = "VolCurveParameters")] + public class VolCurveParameters + { + [ProtoBuf.ProtoMember(10)] + public VolCurveCoreParameters core_parameters; + [ProtoBuf.ProtoMember(20)] + public PolynomialModelVolCurveParameters polynomial_model_parameters; + [ProtoBuf.ProtoMember(30)] + public SplineModelVolCurveParameters spline_model_parameters; + [ProtoBuf.ProtoMember(40)] + public DualQuadraticModelVolCurveParameters dualquadratic_model_parameters; + // [ProtoBuf.ProtoMember(1000)] + // public CustomVolModelParameters custom_parameters; + + } +} diff --git a/src/client/spark/Analytics/Core/Parameters/VolSurfaceInput.cs b/src/client/spark/Analytics/Core/Parameters/VolSurfaceInput.cs new file mode 100644 index 000000000..fe1c62ae0 --- /dev/null +++ b/src/client/spark/Analytics/Core/Parameters/VolSurfaceInput.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + // The settings and the surface parameters + // (which comprises of all the inputs by the user) + // are contained here. This is the entire state + // of the vol surface. + [ProtoBuf.ProtoContract(Name = "VolSurfaceInput")] + public class VolSurfaceInput + { + [ProtoBuf.ProtoMember(1)] + public string saver_login; + [ProtoBuf.ProtoMember(10)] + public VolSurfaceSettings surface_settings; + [ProtoBuf.ProtoMember(20)] + public VolSurfaceParameters surface_parameters; + } +} diff --git a/src/client/spark/Analytics/Core/Parameters/VolSurfaceParameters.cs b/src/client/spark/Analytics/Core/Parameters/VolSurfaceParameters.cs new file mode 100644 index 000000000..abd90900e --- /dev/null +++ b/src/client/spark/Analytics/Core/Parameters/VolSurfaceParameters.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// This is anologous to the VolSurfaceSettings, ie + /// all models will have a representation here. + [ProtoBuf.ProtoContract(Name = "VolSurfaceParameters")] + public class VolSurfaceParameters + { + [ProtoBuf.ProtoMember(10)] + public DateTime vol_time; + [ProtoBuf.ProtoMember(20)] + public List> curve_parameters_map; + [ProtoBuf.ProtoMember(30)] + public VolSurfaceTimeParameters time_parameters; + + } +} diff --git a/src/client/spark/Analytics/Core/Parameters/VolSurfaceTimeParameters.cs b/src/client/spark/Analytics/Core/Parameters/VolSurfaceTimeParameters.cs new file mode 100644 index 000000000..67ed22ceb --- /dev/null +++ b/src/client/spark/Analytics/Core/Parameters/VolSurfaceTimeParameters.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolSurfaceTimeParameters")] + public class VolSurfaceTimeParameters + { + [ProtoBuf.ProtoMember(1)] + public DateTime input_time; + [ProtoBuf.ProtoMember(10)] + public List> auto_decay_points; + } +} diff --git a/src/client/spark/Analytics/Core/Settings/SecurityExpiration.cs b/src/client/spark/Analytics/Core/Settings/SecurityExpiration.cs new file mode 100644 index 000000000..b91832027 --- /dev/null +++ b/src/client/spark/Analytics/Core/Settings/SecurityExpiration.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using ProtoBuf; + +using bts.api; +using bts.settings; +using bts.spark; + +using mbts.spark; + +namespace mbts +{ + [ProtoBuf.ProtoContract()] + [Serializable] + public class SecurityExpiration : IEquatable + { + [ProtoBuf.ProtoMember(1)] + private readonly SecurityTuple _sec_tup; + [ProtoBuf.ProtoMember(2)] + public readonly DateTime expiration; + public readonly static SecurityExpiration empty = new SecurityExpiration(SecurityTuple.empty.security_exchange, SecurityTuple.empty.security_type, SecurityTuple.empty.security_name, DateTime.MinValue); + + // for ProtoBuf deserialization + private SecurityExpiration() {} + + public SecurityExpiration(Venue exchange, SecurityType type, string symbol, DateTime exp) + : this(new SecurityTuple(type, symbol, exchange), exp) { } + + public SecurityExpiration(SecurityTuple sec_tup, DateTime exp) { + _sec_tup = sec_tup; + expiration = exp; + } + + public SecurityTuple security_tuple { get { return _sec_tup; } } + + public SecurityType security_type { get { return _sec_tup.security_type; } } + + public string symbol { get { return _sec_tup.security_name; } } + + public Venue exchange { get { return _sec_tup.security_exchange; } } + + public bool is_empty() { return Equals(empty); } + + public SecurityExpiration unset_exchange() + { + return new SecurityExpiration(Venue.Unset, security_type, symbol, expiration); + } + + public bool Equals(SecurityExpiration other) { + if (other != null) + return _sec_tup.Equals(other._sec_tup) && expiration.Equals(other.expiration); + else + return false; + } + + #region Object overrides + + public override int GetHashCode() { return _sec_tup.GetHashCode() ^ expiration.GetHashCode(); } + + public override bool Equals(object obj) + { + return Equals(obj as SecurityExpiration); + } + + public static bool operator ==(SecurityExpiration x, SecurityExpiration y) { + if (Object.ReferenceEquals(x, null)) return Object.ReferenceEquals(y, null); + if (Object.ReferenceEquals(y, null)) return false; + return x.Equals(y); + } + public static bool operator !=(SecurityExpiration x, SecurityExpiration y) { return !(x == y); } + + public override string ToString() + { + return String.Format("{0} {1}", _sec_tup.ToString(), expiration.ToShortDateString()); + } + #endregion + + public static int ExpBasedCompare(SecurityExpiration x, SecurityExpiration y) { + if (y == null) return 1; + if (x == null) return -1; + int rv = x.expiration.CompareTo(y.expiration); + if (rv == 0) + rv = x._sec_tup.CompareTo(y._sec_tup); + return rv; + } + + public static int SecBasedCompare(SecurityExpiration x, SecurityExpiration y) { + if (y == null) return 1; + if (x == null) return -1; + int rv = x._sec_tup.CompareTo(y._sec_tup); + if (rv == 0) + rv = x.expiration.CompareTo(y.expiration); + return rv; + } + } + + [ProtoBuf.ProtoContract] + public class SecurityExpirationProto + { + [ProtoBuf.ProtoMember(1)] + public SecurityTuple security; + + [ProtoBuf.ProtoMember(2)] + public double expiration_oa_date; + } +} diff --git a/src/client/spark/Analytics/Core/Settings/SecurityStrike.cs b/src/client/spark/Analytics/Core/Settings/SecurityStrike.cs new file mode 100644 index 000000000..6cb34aa7a --- /dev/null +++ b/src/client/spark/Analytics/Core/Settings/SecurityStrike.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using ProtoBuf; + +using bts.api; +using bts.settings; +using bts.spark; + +using mbts.spark; + +namespace mbts +{ + public class SecurityStrike : IEquatable + { + public readonly SecurityExpiration expiration; + public readonly double strike; + public SecurityStrike(SecurityExpiration expiration, double strike) + { + this.expiration = expiration; + this.strike = strike; + } + + public SecurityStrike(string symbol, DateTime exp, double strike) + : this(new SecurityExpiration(Venue.Unset, SecurityType.Option, symbol, exp), strike) + { } + + public bool Equals(SecurityStrike other) { + if (other != null) + return expiration.Equals(other.expiration) && strike.Equals(other.strike); + else + return false; + } + + public override int GetHashCode() { return expiration.GetHashCode() ^ strike.GetHashCode(); } + + public override bool Equals(object obj) + { + return Equals(obj as SecurityStrike); + } + + public static bool operator ==(SecurityStrike x, SecurityStrike y) { + if ((object)x == null) return (object)y == null; + return x.Equals(y); + } + + public static bool operator !=(SecurityStrike x, SecurityStrike y) { return !(x == y); } + + public override string ToString() + { + return String.Format("{0} {1}", expiration.ToString(), strike.ToString()); + } + + public SecurityStrike unset_exchange() { return new SecurityStrike(expiration.unset_exchange(), strike); } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Core/Settings/SecurityTuple.cs b/src/client/spark/Analytics/Core/Settings/SecurityTuple.cs new file mode 100644 index 000000000..d5f495adc --- /dev/null +++ b/src/client/spark/Analytics/Core/Settings/SecurityTuple.cs @@ -0,0 +1,85 @@ +// using System; +// using System.Collections.Generic; +// using System.Linq; +// using System.Text; +// using System.Threading.Tasks; +// // using bts.o2.msgs; +// using ProtoBuf; + +// using bts.api; +// using bts.settings; +// using bts.spark; + +// using mbts.persist; +// using mbts.spark; +// using mbts.spark.filters; +// using mbts.ui; +// using mbts.ui.settings; + +// namespace mbts +// { +// // public class SecurityTupleTry { +// // public readonly SecurityType security_type; +// // } +// // Wraps up a security type, security name and exchange +// [ProtoContract] +// [Serializable] +// public class SecurityTuple : IComparable, IEquatable +// { +// [ProtoMember(1)] +// public readonly SecurityType security_type; +// [ProtoMember(2)] +// public readonly string security_name; +// [ProtoMember(3)] +// public readonly Venue security_exchange; +// public readonly static SecurityTuple empty = new SecurityTuple(SecurityType.SECURITYTYPE_UNSET, String.Empty, Venue.VENUE_UNSET); + +// public SecurityTuple() { } +// public SecurityTuple(SecurityType the_security_type, +// string the_security_name, +// Venue the_security_exchange) +// { +// security_type = the_security_type; +// security_name = the_security_name; +// security_exchange = the_security_exchange; +// } + +// public bool is_empty() { return Equals(empty); } + +// public SecurityTuple unset_exchange() { return new SecurityTuple(security_type, security_name, Venue.VENUE_UNSET); } + +// #region Object overrides +// public override int GetHashCode() { return security_type.GetHashCode() ^ security_name.GetHashCode() ^ security_exchange.GetHashCode(); } + +// public override bool Equals(object obj) { return obj != null && obj is SecurityTuple && Equals(obj as SecurityTuple); } + +// public override string ToString() { return String.Format("{0} {1}", security_name, security_type); } +// #endregion + +// #region IComparable Members + +// public int CompareTo(SecurityTuple other) +// { +// if (other == null) +// return 1; +// int rv = security_exchange.CompareTo(other.security_exchange); +// if (rv != 0) +// return rv; +// rv = security_type.CompareTo(other.security_type); +// if (rv != 0) +// return rv; +// return security_name.CompareTo(other.security_name); +// } + +// #endregion + +// #region IEquatable Members +// public bool Equals(SecurityTuple other) { return other != null && CompareTo(other) == 0; } +// #endregion +// } + +// // public interface ISecurityLookup +// // { +// // SecurityTuple get_security(UInt32 security_key); +// // } +// } \ No newline at end of file diff --git a/src/client/spark/Analytics/Core/Settings/VolChangeSafetyCheck.cs b/src/client/spark/Analytics/Core/Settings/VolChangeSafetyCheck.cs new file mode 100644 index 000000000..6ace3b4a1 --- /dev/null +++ b/src/client/spark/Analytics/Core/Settings/VolChangeSafetyCheck.cs @@ -0,0 +1,24 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// Parameterizes the safety by comparing before + /// and after moves in the atm vol and the rest + /// of the curve + [ProtoBuf.ProtoContract(Name = "VolChangeSafetyCheck")] + public class VolChangeSafetyCheck + { + [ProtoBuf.ProtoMember(10)] + public double atm_percentage_change; + [ProtoBuf.ProtoMember(20)] + public double atm_absolute_change; + [ProtoBuf.ProtoMember(30)] + public double general_percentage_change; + [ProtoBuf.ProtoMember(40)] + public double general_absolute_change; + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Core/Settings/VolSurfaceAdvancedSettings.cs b/src/client/spark/Analytics/Core/Settings/VolSurfaceAdvancedSettings.cs new file mode 100644 index 000000000..a74ff0e3f --- /dev/null +++ b/src/client/spark/Analytics/Core/Settings/VolSurfaceAdvancedSettings.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolSurfaceAdvancedSettings")] + public class VolSurfaceAdvancedSettings + { + [ProtoBuf.ProtoMember(1)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double number_of_cashed_saved_days; + + [ProtoBuf.ProtoMember(10)] + public List precomputed_theo_handles; + + [ProtoBuf.ProtoMember(15)] + [System.ComponentModel.DefaultValue(VolSurfaceEnums.GeneralChangeMeasure.Absolute)] + public VolSurfaceEnums.GeneralChangeMeasure theo_handle_measure; + + [ProtoBuf.ProtoMember(20)] + public List precomputed_slide_handles; + + [ProtoBuf.ProtoMember(25)] + [System.ComponentModel.DefaultValue(VolSurfaceEnums.GeneralChangeMeasure.Percentage)] + public VolSurfaceEnums.GeneralChangeMeasure slide_handle_measure; + + [ProtoBuf.ProtoMember(30)] + //[System.ComponentModel.DefaultValue(false)] + public bool publish_from_client; + + [ProtoBuf.ProtoMember(40)] + [System.ComponentModel.DefaultValue("")] + public string publish_from_client_user; + + [ProtoBuf.ProtoMember(50)] + [System.ComponentModel.DefaultValue(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike)] + public VolSurfaceEnums.VolCurveStrikeAxis strike_normalization_axis; + } +} diff --git a/src/client/spark/Analytics/Core/Settings/VolSurfaceCoreSettings.cs b/src/client/spark/Analytics/Core/Settings/VolSurfaceCoreSettings.cs new file mode 100644 index 000000000..fb355c812 --- /dev/null +++ b/src/client/spark/Analytics/Core/Settings/VolSurfaceCoreSettings.cs @@ -0,0 +1,75 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// These are the VolSurface settings that are common + /// to any Vol Model + [ProtoBuf.ProtoContract(Name = "VolSurfaceCoreSettings")] + public class VolSurfaceCoreSettings + { + [ProtoBuf.ProtoMember(1)] + public string vol_surface_name; + [ProtoBuf.ProtoMember(2)] + public int vol_surface_id; + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.VolSurfaceModel vol_surface_model; + [ProtoBuf.ProtoMember(20)] + public List symbols; + [ProtoBuf.ProtoMember(25)] + public List symbol_structure_list; + [ProtoBuf.ProtoMember(30)] + public VolSurfaceWingSettings wing_settings; + [ProtoBuf.ProtoMember(40)] + public VolSurfaceEnums.StandardVolType standard_vol_type; + [ProtoBuf.ProtoMember(50)] + public VolPathSettings volpath_settings; + /// These are the out of box macro operations on the curve + [ProtoBuf.ProtoMember(60)] + public VolCurveMovementOperation call_rotation; + [ProtoBuf.ProtoMember(70)] + public VolCurveMovementOperation put_rotation; + [ProtoBuf.ProtoMember(80)] + public VolCurveMovementOperation full_rotation; + [ProtoBuf.ProtoMember(90)] + public VolCurveMovementOperation strangle; + [ProtoBuf.ProtoMember(100)] + public VolCurveMovementOperation atm_shift; + [ProtoBuf.ProtoMember(110)] + public VolSurfaceEnums.ATMCascading atm_cascading_mode; + [ProtoBuf.ProtoMember(120)] + public VolSurfaceEnums.VolTimePeriod voltime_period; + [ProtoBuf.ProtoMember(130)] + public VolChangeSafetyCheck safety_limits; + [ProtoBuf.ProtoMember(135)] + public VolSurfaceMarketFitSettings market_fit_settings; + [ProtoBuf.ProtoMember(140)] + public VolSurfaceEnums.VolSurfaceUnsetExpirationMatching unset_expiration_matching; + [ProtoBuf.ProtoMember(150)] + public VolSurfaceUnsetExpirationCalculationSettings unset_expiration_calculation_settings; + /// Some symbols could use other symbols's market data ex + /// spx using es's + [ProtoBuf.ProtoMember(160)] + public List symbol_implied_vol_marketdata_source_list; + [ProtoBuf.ProtoMember(170)] + public List> symbol_pricing_model_map; + [ProtoBuf.ProtoMember(180)] + public List implied_vol_marketdata_relationships; + [ProtoBuf.ProtoMember(190)] + public List master_slave_relationships; + /// This tells how the abstract strike axis (moneyness, delta etc) + /// is converted to a real strike. That depends on vol and fwd. + /// This tells what vol and fwd to use for that. + [ProtoBuf.ProtoMember(200)] + public VolSurfaceEnums.StrikeConversionVol strike_conversion_vol; + [ProtoBuf.ProtoMember(210)] + public VolSurfaceEnums.StrikeConversionPrice strike_conversion_price; + [ProtoBuf.ProtoMember(220)] + public VolSurfaceEnums.VolCurveStrikeAxis strike_normalization_axis; + [ProtoBuf.ProtoMember(230)] + public VolSurfaceTimeSettings time_settings; + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Core/Settings/VolSurfaceSettings.cs b/src/client/spark/Analytics/Core/Settings/VolSurfaceSettings.cs new file mode 100644 index 000000000..05c440895 --- /dev/null +++ b/src/client/spark/Analytics/Core/Settings/VolSurfaceSettings.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// All model settings exist here. With the core being there + /// they all in a way "derive" from core + [ProtoBuf.ProtoContract(Name = "VolSurfaceSettings")] + public class VolSurfaceSettings + { + [ProtoBuf.ProtoMember(10)] + public VolSurfaceCoreSettings core_settings; + [ProtoBuf.ProtoMember(15)] + public VolSurfaceAdvancedSettings advanced_settings; + [ProtoBuf.ProtoMember(20)] + public PolynomialModelVolSurfaceSettings polynomial_model_settings; + [ProtoBuf.ProtoMember(30)] + public SplineModelVolSurfaceSettings spline_model_settings; + [ProtoBuf.ProtoMember(40)] + public DualQuadraticModelVolSurfaceSettings dualquadratic_model_settings; + // [ProtoBuf.ProtoMember(50)] + // public CustomModelVolSurfaceSettings custom_model_settings; + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Core/Settings/VolSurfaceTimeMeasure.cs b/src/client/spark/Analytics/Core/Settings/VolSurfaceTimeMeasure.cs new file mode 100644 index 000000000..05d55c321 --- /dev/null +++ b/src/client/spark/Analytics/Core/Settings/VolSurfaceTimeMeasure.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "TimeMeasure")] + public class VolSurfaceTimeMeasure : IEquatable + { + [ProtoBuf.ProtoMember(10)] + public double days_per_year; + [ProtoBuf.ProtoMember(20)] + public bool account_for_holidays_and_weekends; + [ProtoBuf.ProtoMember(30)] + public double constant_offset_days; + [ProtoBuf.ProtoMember(40)] + public VolSurfaceEnums.DayMeasure begin_day_measure; + [ProtoBuf.ProtoMember(50)] + public VolSurfaceEnums.DayMeasure end_day_measure; + + public bool Equals(VolSurfaceTimeMeasure other) { + return other != null + && days_per_year == other.days_per_year + && account_for_holidays_and_weekends == other.account_for_holidays_and_weekends + && constant_offset_days == other.constant_offset_days + && begin_day_measure == other.begin_day_measure + && end_day_measure == other.end_day_measure; + } + public override bool Equals(object obj) { return Equals(obj as VolSurfaceTimeMeasure); } + public override int GetHashCode() { return days_per_year.GetHashCode() ^ account_for_holidays_and_weekends.GetHashCode() ^ constant_offset_days.GetHashCode() ^ begin_day_measure.GetHashCode() ^ end_day_measure.GetHashCode(); } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Core/Settings/VolSurfaceTimeSettings.cs b/src/client/spark/Analytics/Core/Settings/VolSurfaceTimeSettings.cs new file mode 100644 index 000000000..4f4a71d48 --- /dev/null +++ b/src/client/spark/Analytics/Core/Settings/VolSurfaceTimeSettings.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolSurfaceTimeSettings")] + public class VolSurfaceTimeSettings + { + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.VolSurfaceTimeMode time_mode; + [ProtoBuf.ProtoMember(20)] + public VolSurfaceTimeMeasure vol_time_measure; + [ProtoBuf.ProtoMember(30)] + public VolSurfaceTimeMeasure interest_time_measure; + } +} diff --git a/src/client/spark/Analytics/Core/Settings/VolSurfaceUnsetExpirationCalculationSettings.cs b/src/client/spark/Analytics/Core/Settings/VolSurfaceUnsetExpirationCalculationSettings.cs new file mode 100644 index 000000000..e605c9313 --- /dev/null +++ b/src/client/spark/Analytics/Core/Settings/VolSurfaceUnsetExpirationCalculationSettings.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolSurfaceUnsetExpirationCalculationSettings")] + public class VolSurfaceUnsetExpirationCalculationSettings + { + /// if option expiration is within collapsable_days it + /// uses the same x->v as its neighbor + [ProtoBuf.ProtoMember(10)] + public uint vol_collapsable_days = 0; + [ProtoBuf.ProtoMember(20)] + public VolSurfaceEnums.VolSurfaceUnsetExpirationCalculation unset_expiration_calculation; + } +} diff --git a/src/client/spark/Analytics/Core/VolCurveAction.cs b/src/client/spark/Analytics/Core/VolCurveAction.cs new file mode 100644 index 000000000..71fb9e73d --- /dev/null +++ b/src/client/spark/Analytics/Core/VolCurveAction.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class VolCurveAction + { + public enum ActionType + { + None, + Rebuild, + CurveOperation, + FitToMarket, + SyncSlaveRefFwds + } + public readonly ActionType action_type; + /// Will be used when action == CurveOperation + public readonly VolCurveMovementOperation curve_operation; + /// Will be used when action == FitToMarket + public readonly VolCurveMarketFitAction market_fit_action; + + public VolCurveAction(ActionType this_action) { action_type = this_action; } + + public VolCurveAction(VolCurveMovementOperation this_operation) + { + action_type = ActionType.CurveOperation; + curve_operation = this_operation; + } + + public VolCurveAction(VolCurveMarketFitAction this_market_fit_action) + { + action_type = ActionType.FitToMarket; + market_fit_action = this_market_fit_action; + } + } +} diff --git a/src/client/spark/Analytics/Core/VolCurveMovementOperation.cs b/src/client/spark/Analytics/Core/VolCurveMovementOperation.cs new file mode 100644 index 000000000..55b891719 --- /dev/null +++ b/src/client/spark/Analytics/Core/VolCurveMovementOperation.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// This is an abstractionm of an operation + /// on the Vol Curve, which an be expressed + /// in terms of the strike points and how + /// much to move the strike points + /// (and what terms to move it in - vol or price) + [ProtoBuf.ProtoContract(Name = "VolCurveMovementOperation")] + public class VolCurveMovementOperation + { + [ProtoBuf.ProtoMember(10)] + public string operation_name; + [ProtoBuf.ProtoMember(20)] + public VolSurfaceEnums.VolCurveStrikeAxis strike_axis; + [ProtoBuf.ProtoMember(30)] + public VolSurfaceEnums.VolMovementTerms target_terms; + [ProtoBuf.ProtoMember(40)] + public double atm_strike_vol_movement; + [ProtoBuf.ProtoMember(50)] + public List> strike_vol_movement_pairs; + } +} diff --git a/src/client/spark/Analytics/Core/VolSurfaceCalculatorFactory.cs b/src/client/spark/Analytics/Core/VolSurfaceCalculatorFactory.cs new file mode 100644 index 000000000..aafb686cb --- /dev/null +++ b/src/client/spark/Analytics/Core/VolSurfaceCalculatorFactory.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts; + +namespace mbts.analytics +{ + /// Based on the settings, it plucks the correct + /// data/calculator + public class VolSurfaceCalculatorFactory + { + public static IVolCurveMainCalculator get_curve_calculator(VolSurfaceSettings settings) + { + if (settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Polynomial) + return new PolynomialModelVolCurveCalculator(); + else if (settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline) + return new SplineModelVolCurveCalculator(); + else if (settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.DualQuadratic) + return new DualQuadraticModelVolCurveCalculator(); + // else if (settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Custom) + // return new CustomModelVolCurveCalculator(); + return null; + } + + public static IVolCurveWingCalculator get_wing_calculator(VolSurfaceSettings settings) + { + if (settings.core_settings.wing_settings.wing_model == VolSurfaceEnums.VolCurveWingModel.ImplicitSlopeWithHorizontalAsymptotes) + return new VolCurveImplicitSlopeWingCalculator(); + else if (settings.core_settings.wing_settings.wing_model == VolSurfaceEnums.VolCurveWingModel.OnePointSlope) + { + Log.assert(false, String.Format("{0} not supported", settings.core_settings.wing_settings.wing_model)); + return null; + } + else if (settings.core_settings.wing_settings.wing_model == VolSurfaceEnums.VolCurveWingModel.ExplicitSlopeWithHorizontalAsymptotes) + return new VolCurveExplicitSlopeWingCalculator(); + return null; + } + + public static IVolPathCalculator get_path_calculator(VolSurfaceSettings settings) + { + if (settings.core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.TwoWaySlope) + return new TwoWaySlopeVolPathCalculator(); + else if (settings.core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.Parabolic) + return new ParabolicVolPathCalculator(); + // else if (settings.core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.Custom) + // return new CustomModelVolResponseCalculator(); + else + { + Log.assert(false, String.Format("{0} not supported", settings.core_settings.volpath_settings.vol_path_model)); + return null; + } + } + } +} diff --git a/src/client/spark/Analytics/Core/VolSurfaceConstants.cs b/src/client/spark/Analytics/Core/VolSurfaceConstants.cs new file mode 100644 index 000000000..a235914b7 --- /dev/null +++ b/src/client/spark/Analytics/Core/VolSurfaceConstants.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public static class VolSurfaceConstants + { + public static int vol_time_sample_mins = 15; + } +} diff --git a/src/client/spark/Analytics/Core/VolSurfaceEnums.cs b/src/client/spark/Analytics/Core/VolSurfaceEnums.cs new file mode 100644 index 000000000..469d63ec3 --- /dev/null +++ b/src/client/spark/Analytics/Core/VolSurfaceEnums.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class VolSurfaceEnums + { + /// The basic Vol Curve Models (more models like + /// "2 polynomials stiched together" etc will be + /// represented by an enum here) + public enum VolSurfaceModel + { + Polynomial, + CubicSpline, + Custom, + DualQuadratic + } + + /// These are the vol path models, ie they + /// define how the ATM Vol moves as the + /// forward moves + public enum VolSurfaceVolPathModel + { + TwoWaySlope, + Parabolic, + Custom + } + + /// This might be relevant to a "coordinates" based + /// vol models like polynomials and splines, where you + /// need to specify strike points vs other higher level + /// parameters + public enum VolCurveStrikeAxis + { + [System.ComponentModel.DescriptionAttribute("Standardized Moneyness - Log(K/F)/(Vol*sqrt(T))")] + StandardStrike, + [System.ComponentModel.DescriptionAttribute("Flat Vol Delta")] + Delta, + [System.ComponentModel.DescriptionAttribute("Linear Moneyness - K-F")] + StrikeDiffFromATM, + [System.ComponentModel.DescriptionAttribute("Raw Strike")] + RawStrike, + [System.ComponentModel.DescriptionAttribute("Log Simple Moneyness - Log(K/F)")] + LogSimpleMoneyness + } + + /// Similiar to VolCurveStrikeAxis, this might be for "coordinates" + /// based vol models. + public enum VolCurveVolAxis + { + [System.ComponentModel.DescriptionAttribute("Multiplicative Factors of ATM Vol")] + ATMFactor, + [System.ComponentModel.DescriptionAttribute("Additions to ATM Vol")] + ATMAddin, + [System.ComponentModel.DescriptionAttribute("Additions to Previous Vol")] + Incremental + } + + /// This describes what to do with the curve once it + /// enters the wing region (specified elsewhere) + public enum VolCurveWingModel + { + ImplicitSlopeWithHorizontalAsymptotes, + ExplicitSlopeWithHorizontalAsymptotes, + OnePointSlope + } + + /// This is 'sigma' that is used to compute the + /// standard strike. In most places this is set + /// to the ATM Vol + public enum StandardVolType + { + UserConstant, + ATMVol + } + + /// User defined movements in the vol curve + /// can either be in vol terms or price terms + /// (in which case they will have to be translated + /// to vol terms) + public enum VolMovementTerms + { + [System.ComponentModel.DescriptionAttribute("Vol Percent")] + Vol, + Price + } + + /// This is how ATM operations in one expiration are cascaded to + /// other expirations + public enum ATMCascading + { + Constant, + VegaRatio, + StraddleRatio + } + + /// Just a general concept used to mark some change settings + public enum GeneralChangeMeasure + { + [Description ("Difference")] + Absolute, + Percentage, + Ratio + } + + /// For the purpose of vol calculations, the T can + /// be Business or Calendar + public enum VolTimePeriod + { + Business, + [Description("Standard")] + Calendar + } + + /// For unset expirations (with missing inputs) we need to find out the + /// "master" expiration to base the volatility (or input) + /// off from. This tells how to match + public enum VolSurfaceUnsetExpirationMatching + { + SettlementSecurity, + OptionExpiration + } + + /// For unset expiration (with missing inputs), once we have determined + /// the "master" expiration(s), we need a way to use the master's + /// vols to guess this expirations's vols + public enum VolSurfaceUnsetExpirationCalculation + { + SimpleInterpolation + } + + public enum VolCurveFitMarket + { + LiveMid, + Settlement + } + + public enum VolCurveFitRegion + { + ATM, + All + } + + public enum VolSurfaceVisualizationParamater + { + Vol, + //Vega, + //Straddle, + Price + } + + public enum VolSurfacePricingModel + { + [System.ComponentModel.DescriptionAttribute("Black Scholes")] + BlackScholes = 0, + Whaley, + Normal, + EDNormal + } + + public enum VolSurfaceExpirationCalculationMethod + { + Master, + Slave, + UnlinkedSlave, + MasterInterp + /// SlaveInterp + } + + public enum VolSurfaceExpirationCalculationMode + { + Default, + Manual, + Interpolation + } + + /// + /// This is the volatility that is used for conversion + /// of the strike axis (ex if the vol curve is calibrated + /// in delta, then to go from delta to raw strike + /// we need a vol, this tells what vol to use) + /// + public enum StrikeConversionVol + { + [System.ComponentModel.DescriptionAttribute("ATM")] + ATMVol, + [System.ComponentModel.DescriptionAttribute("Path ATM")] + PathATMVol, + [System.ComponentModel.DescriptionAttribute("Standard")] + StandardVol + } + + /// + /// Anologous to StrikeConversionVol, for the fwd + /// + public enum StrikeConversionPrice + { + Live, + Ref + } + + public enum VolSurfaceTimeMode + { + Manual, + [System.ComponentModel.DescriptionAttribute("Auto Decay")] + AutoDecay + } + + public enum DayMeasure + { + Zero, + One, + Fraction + } + + public enum MarketSide + { + Bid, + Ask, + Mid + } + + public enum CalendarMode + { + AM, PM, AM_QUARTERLY_ONE_THIRD_PM_OTHER, AM_ONE_THIRD_SERIAL_PM_OTHER, AM_ONE_THIRD, AM_ONE_QUARTER, + USE_CALENDAR_FOR_BUSINESS + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Core/VolSurfaceExpiration.cs b/src/client/spark/Analytics/Core/VolSurfaceExpiration.cs new file mode 100644 index 000000000..4e129014d --- /dev/null +++ b/src/client/spark/Analytics/Core/VolSurfaceExpiration.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using ProtoBuf; + +using bts.api; +using bts.settings; +using bts.spark; + +using mbts.spark; + +namespace mbts.analytics +{ + /// + /// An expiration in the Vol Surface is expressed + /// with a symbol and an expiration. This is a + /// conveniant way to express unique expirations, + /// but it could very well be a string, that maps + /// to a real expiration. + /// + [ProtoBuf.ProtoContract(Name = "VolSurfaceExpiration")] + public class VolSurfaceExpiration : IEquatable, IComparable + { + public VolSurfaceExpiration() : this(string.Empty, default(DateTime)) { } + + public VolSurfaceExpiration(string symbol, DateTime expiration) { + this.symbol = symbol; + this.expiration = expiration; + } + + [ProtoBuf.ProtoMember(10)] + public string symbol; + [ProtoBuf.ProtoMember(20)] + public DateTime expiration; + + public bool Equals(VolSurfaceExpiration other) { + return other != null && symbol.Equals(other.symbol) && expiration.Equals(other.expiration); + } + + public override int GetHashCode() { return symbol.GetHashCode() ^ expiration.GetHashCode(); } + + public override bool Equals(object obj) { + return Equals(obj as VolSurfaceExpiration); + } + + public int CompareTo(VolSurfaceExpiration other) + { + other = other ?? new VolSurfaceExpiration() { expiration = DateTime.MinValue, symbol = String.Empty }; + int rv = expiration.CompareTo(other.expiration); + return rv != 0 ? rv : symbol.CompareTo(other.symbol); + } + } + + public static class VolSurfaceExpirationExtensions + { + public static SecurityExpiration ToSecurityExp(this VolSurfaceExpiration vs_exp) { + var type = SecurityType.Unset; + if (!string.IsNullOrWhiteSpace(vs_exp.symbol)) { + if (Char.IsLower(vs_exp.symbol.First())) type = SecurityType.Option; + else if (Char.IsUpper(vs_exp.symbol.First())) type =SecurityType.Future; + } + return new SecurityExpiration(Venue.Unset, type, vs_exp.symbol, vs_exp.expiration); + } + } +} diff --git a/src/client/spark/Analytics/Core/VolSurfaceStandardTime.cs b/src/client/spark/Analytics/Core/VolSurfaceStandardTime.cs new file mode 100644 index 000000000..751ea2548 --- /dev/null +++ b/src/client/spark/Analytics/Core/VolSurfaceStandardTime.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class VolSurfaceStandardTime + { + public readonly TimeZoneInfo timezone; + public readonly DateTime server_time, server_time_utc; + + public VolSurfaceStandardTime(TimeZoneInfo timezone, + DateTime server_time, + DateTime server_time_utc) + { + this.timezone = timezone; + this.server_time = server_time; + this.server_time_utc = server_time_utc; + } + + public static VolSurfaceStandardTime get_local_default() + { + DateTime local_rounded = VolSurfaceUtilityFunctions.round_time_mins (DateTime.Now, VolSurfaceConstants.vol_time_sample_mins); + return new VolSurfaceStandardTime (TimeZoneInfo.Local,local_rounded, local_rounded); + } + } +} diff --git a/src/client/spark/Analytics/Core/VolSurfaceSymbolStructure.cs b/src/client/spark/Analytics/Core/VolSurfaceSymbolStructure.cs new file mode 100644 index 000000000..63d71a46f --- /dev/null +++ b/src/client/spark/Analytics/Core/VolSurfaceSymbolStructure.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolSurfaceSymbolStructure")] + public class VolSurfaceSymbolStructure + { + [ProtoBuf.ProtoMember(10)] + public string master_symbol; + [ProtoBuf.ProtoMember(20)] + public List slave_symbol_list; + } + + [ProtoBuf.ProtoContract(Name = "VolSurfaceSymbolRelationship")] + public class VolSurfaceSymbolRelationship + { + [ProtoBuf.ProtoMember(10)] + public string symbol; + [ProtoBuf.ProtoMember(20)] + public List connected_symbols; + } +} diff --git a/src/client/spark/Analytics/DualQuadtric/DualQuadraticCurve.cs b/src/client/spark/Analytics/DualQuadtric/DualQuadraticCurve.cs new file mode 100644 index 000000000..b992dbd42 --- /dev/null +++ b/src/client/spark/Analytics/DualQuadtric/DualQuadraticCurve.cs @@ -0,0 +1,103 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class DualQuadraticCurve + { + private readonly JointQudratic _curve; + + public DualQuadraticCurve(double put_slope, double put_curvature, double put_smoothening_width, + double call_slope, double call_curvature, double call_smoothening_width, + double atm_strike, double atm_vol) + { + _curve = new JointQudratic(put_slope, put_curvature, put_smoothening_width, atm_strike, atm_vol, call_slope, call_curvature, call_smoothening_width); + } + + private DualQuadraticCurve(JointQudratic curve) { _curve = curve; } + + public double compute(double x, uint nth_derv = 0) { return _curve.compute(x, nth_derv); } + + public static DualQuadraticCurve fit_to_market(VolCurveMarketImpliedVolData implied_vol_data, + DualQuadraticModelVolCurveParameters curve_params, + DualQuadraticCurve curr_curve, + DualQuadraticModelVolSurfaceSettings settings, + bool atm_only) + { + double atm_vol = implied_vol_data.atm_vol, + atm_strike = VolSurfaceCoreFunctions.convert_axis(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, implied_vol_data.pricing_model, implied_vol_data.atm_strike, settings.strike_axis, atm_vol, implied_vol_data.aux_data); + JointQudratic curve = curr_curve._curve; + if (atm_only) + { + return new DualQuadraticCurve(curve.left_slope, curve.left_curvature, curve.left_smoothening_width, curve.right_slope, curve.right_curvature, curve.right_smoothening_width, atm_strike, atm_vol); + } + else + { + /// put side + implied_vol_data = VolSurfaceCoreFunctions.filter_for_ends(implied_vol_data, Tuple.Create(settings.curve_endpoint_axis, curve_params.put_end_strike), Tuple.Create(settings.curve_endpoint_axis, curve_params.call_end_strike)); + IDictionary put_points = implied_vol_data.put_rawk_vols.ToDictionary(kv => VolSurfaceCoreFunctions.convert_axis(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, implied_vol_data.pricing_model, kv.Key, settings.strike_axis, atm_vol, implied_vol_data.aux_data), + kv => kv.Value); + put_points[atm_strike] = atm_vol; + put_points = put_points.Where(kv => !Double.IsNaN(kv.Key) && !Double.IsNaN(kv.Value)).ToDictionary(kv => kv.Key, kv => kv.Value); + IEnumerable put_coeffs = VolSurfaceCoreFunctions.get_constrained_least_squares_polynomial(put_points.Select(t => Tuple.Create(t.Key, t.Value, 1.0)), + new Tuple[] { Tuple.Create(atm_strike, atm_vol) }, 2); + /// call side + IDictionary call_points = implied_vol_data.call_rawk_vols.ToDictionary(kv => VolSurfaceCoreFunctions.convert_axis(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, implied_vol_data.pricing_model, kv.Key, settings.strike_axis, atm_vol, implied_vol_data.aux_data), + kv => kv.Value); + call_points[atm_strike] = atm_vol; + call_points = call_points.Where(kv => !Double.IsNaN(kv.Key) && !Double.IsNaN(kv.Value)).ToDictionary(kv => kv.Key, kv => kv.Value); + IEnumerable call_coeffs = VolSurfaceCoreFunctions.get_constrained_least_squares_polynomial(call_points.Select(t => Tuple.Create(t.Key, t.Value, 1.0)), + new Tuple[] { Tuple.Create(atm_strike, atm_vol) }, 2); + return new DualQuadraticCurve(put_coeffs.ElementAt(1), put_coeffs.ElementAt(2), curve.left_smoothening_width, + call_coeffs.ElementAt(1), call_coeffs.ElementAt(2), curve.right_smoothening_width, + atm_strike, atm_vol); + } + } + + public static DualQuadraticCurve shape_action(VolCurveMovementOperation curve_operation, + DualQuadraticCurve curr_curve, + DualQuadraticModelVolSurfaceSettings settings) + { + if (VolSurfaceUtilityFunctions.is_risk_reversal (new VolCurveAction (curve_operation))) + { + JointQudratic rotated_curve = curr_curve._curve.rotate_slope (curve_operation.strike_vol_movement_pairs.ElementAt(0)); + rotated_curve = rotated_curve.rotate_slope (curve_operation.strike_vol_movement_pairs.ElementAt(1)); + return new DualQuadraticCurve (rotated_curve); + } + else if (VolSurfaceUtilityFunctions.is_strangle(new VolCurveAction(curve_operation))) + { + JointQudratic rotated_curve = curr_curve._curve.rotate_slope(curve_operation.strike_vol_movement_pairs.ElementAt(0)); + rotated_curve = rotated_curve.rotate_slope(curve_operation.strike_vol_movement_pairs.ElementAt(1)); + return new DualQuadraticCurve(rotated_curve); + } + else if (VolSurfaceUtilityFunctions.is_put_rotation(new VolCurveAction(curve_operation))) + { + JointQudratic rotated_curve = curr_curve._curve.rotate_slope(curve_operation.strike_vol_movement_pairs.ElementAt(0)); + return new DualQuadraticCurve(rotated_curve); + } + else if (VolSurfaceUtilityFunctions.is_call_rotation(new VolCurveAction(curve_operation))) + { + JointQudratic rotated_curve = curr_curve._curve.rotate_slope(curve_operation.strike_vol_movement_pairs.ElementAt(0)); + return new DualQuadraticCurve(rotated_curve); + } + else + return curr_curve; + } + + public void copy_to_params(ref DualQuadraticModelVolCurveParameters dq_params, bool copy_atm) + { + dq_params.call_curvature = _curve.right_curvature; + dq_params.call_slope = _curve.right_slope; + dq_params.put_curvature = _curve.left_curvature; + dq_params.put_slope = _curve.left_slope; + if (copy_atm) + { + dq_params.atm_vol = _curve.center_y; + dq_params.x0 = _curve.center_x; + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/DualQuadtric/DualQuadraticModelVolCurveCalculator.cs b/src/client/spark/Analytics/DualQuadtric/DualQuadraticModelVolCurveCalculator.cs new file mode 100644 index 000000000..cdd1627b8 --- /dev/null +++ b/src/client/spark/Analytics/DualQuadtric/DualQuadraticModelVolCurveCalculator.cs @@ -0,0 +1,255 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// This implementes the Spline and Polynomial models. The + /// difference is abstracted out in the ControlPointsCurve + public class DualQuadraticModelVolCurveCalculator : IVolCurveMainCalculator + { + /// Copied directly from args + private VolCurveParameters _input_parameters; + private VolSurfaceExpirationAuxiliaryData _aux_data; + private bool _initialized = true; + private double _final_unresponded_atm_vol = Double.NaN, _final_reponded_atm_vol = Double.NaN, + _conversion_vol, _conversion_fwd; + private DualQuadraticCurve _curve; + private DualQuadraticModelVolSurfaceSettings _settings; + private VolSurfaceEnums.VolSurfacePricingModel _pricing_model; /*Needed for axis convertion if delta is one of the axis*/ + + #region IVolCurveMainCalculator + + public void initialize_for_lifetime(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action) + { + _settings = surface_settings.dualquadratic_model_settings; + _input_parameters = curve_parameters; + _aux_data = aux_data; + _pricing_model = VolSurfaceDataFunctions.get_pricing_model(surface_settings, expiration); + path_induced_atm_vol_move = Double.IsNaN(path_induced_atm_vol_move) ? 0.0 : path_induced_atm_vol_move; + _initialized = _can_compute(surface_settings, curve_parameters, _aux_data.fwd, path_induced_atm_vol_move); + if (_initialized) + { + curve_action = CoordinatesBasedModelHelper.clean_action(curve_action); + if (curve_action.action_type == VolCurveAction.ActionType.None) + { + /// this is the only code path that alters that actually plots + /// the curve (ie sets _curve). The rest of the if conditions + /// below are recursive calls that end up here + _final_unresponded_atm_vol = curve_parameters.dualquadratic_model_parameters.atm_vol; + _final_reponded_atm_vol = _final_unresponded_atm_vol + path_induced_atm_vol_move; + _conversion_vol = _get_conversion_vol(surface_settings, curve_parameters, _final_reponded_atm_vol); + _conversion_fwd = _get_conversion_fwd(surface_settings, curve_parameters, aux_data); + DualQuadraticModelVolCurveParameters dq_params = curve_parameters.dualquadratic_model_parameters; + _curve = new DualQuadraticCurve(dq_params.put_slope, dq_params.put_curvature, dq_params.epsilon/2.0, + dq_params.call_slope, dq_params.call_curvature, dq_params.epsilon/2.0, + _convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, _conversion_fwd, _settings.strike_axis), _final_reponded_atm_vol); + } + else if (curve_action.action_type == VolCurveAction.ActionType.CurveOperation) + { + VolCurveMovementOperation movement_action = curve_action.curve_operation; + if (!Double.IsNaN(movement_action.atm_strike_vol_movement) && movement_action.atm_strike_vol_movement != 0) + { + VolCurveParameters new_params = _get_atmvol_move_params(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, curve_action); + initialize_for_lifetime(expiration, surface_settings, new_params, aux_data, path_induced_atm_vol_move, new VolCurveAction(VolCurveAction.ActionType.None)); + } + else + { + VolCurveParameters new_params = _get_shape_move_params(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, curve_action); + initialize_for_lifetime(expiration, surface_settings, new_params, aux_data, path_induced_atm_vol_move, new VolCurveAction(VolCurveAction.ActionType.None)); + } + } + else if (curve_action.action_type == VolCurveAction.ActionType.Rebuild) + { + VolCurveParameters new_params = _get_rebuild_params(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move); + initialize_for_lifetime(expiration, surface_settings, new_params, aux_data, 0.0, new VolCurveAction(VolCurveAction.ActionType.None)); + } + else if (curve_action.action_type == VolCurveAction.ActionType.FitToMarket) + { + VolCurveParameters new_params = _get_marketfit_params(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, curve_action); + initialize_for_lifetime(expiration, surface_settings, new_params, aux_data, 0.0, new VolCurveAction(VolCurveAction.ActionType.None)); + } + } + } + + #region Stateless functions that do input = f(input, action) + /// This is called when action = atm vol move. + /// This essentially does return curve_parameters.atm_vol + move + private static VolCurveParameters _get_atmvol_move_params(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action) + { + var movement_action = VolSurfaceCoreFunctions.normalize_atm_move_action(curve_action.curve_operation, curve_parameters.dualquadratic_model_parameters.atm_vol + path_induced_atm_vol_move, + aux_data, _get_conversion_fwd(surface_settings, curve_parameters, aux_data)); + double atm_vol_action_move = movement_action == null ? 0.0 : VolSurfaceUtilityFunctions.find_atm_vol_move(movement_action); + curve_parameters.dualquadratic_model_parameters.atm_vol = curve_parameters.dualquadratic_model_parameters.atm_vol + atm_vol_action_move; + return curve_parameters; + } + + private static VolCurveParameters _get_shape_move_params(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action) + { + DualQuadraticModelVolCurveCalculator curr_calc = new DualQuadraticModelVolCurveCalculator(); + curr_calc.initialize_for_lifetime(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, new VolCurveAction(VolCurveAction.ActionType.None)); + VolCurveMovementOperation normalized_movement_op = VolSurfaceCoreFunctions.normalize_shape_action(curve_action.curve_operation, aux_data, + (source_axis, source_strike, target_axis) => curr_calc._convert_strike_axis(source_axis, source_strike, target_axis), + (strike, axis) => curr_calc._compute_vol(strike, axis, 0), + surface_settings.dualquadratic_model_settings.strike_axis); + VolCurveParameters rv = VolSurfaceUtilityFunctions.clone_proto(curve_parameters); + DualQuadraticCurve new_curve = DualQuadraticCurve.shape_action(normalized_movement_op, curr_calc._curve, surface_settings.dualquadratic_model_settings); + new_curve.copy_to_params(ref rv.dualquadratic_model_parameters, false); + return rv; + } + + private static VolCurveParameters _get_marketfit_params(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action) + { + VolCurveParameters rv = VolSurfaceUtilityFunctions.clone_proto(curve_parameters); + DualQuadraticModelVolCurveCalculator curr_calc = new DualQuadraticModelVolCurveCalculator(); + curr_calc.initialize_for_lifetime(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, new VolCurveAction(VolCurveAction.ActionType.None)); + DualQuadraticCurve new_curve = DualQuadraticCurve.fit_to_market(curve_action.market_fit_action.implied_vol_data, curve_parameters.dualquadratic_model_parameters, curr_calc._curve, surface_settings.dualquadratic_model_settings, curve_action.market_fit_action.fit_action == VolCurveMarketFitAction.ActionType.FitATM); + new_curve.copy_to_params(ref rv.dualquadratic_model_parameters, true); + rv.core_parameters.ref_forward = aux_data.fwd; + rv.core_parameters.standard_vol = rv.dualquadratic_model_parameters.atm_vol; + return rv; + } + + private static VolCurveParameters _get_rebuild_params(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move) + { + return curve_parameters; + //VolCurveParameters rv = curve_parameters; + //CoordinateModelVolCurveCalculator curr_calc = new CoordinateModelVolCurveCalculator(); + //curr_calc.initialize_for_lifetime(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, new VolCurveAction(VolCurveAction.ActionType.None)); + //double new_atm_vol = curr_calc._compute_vol(aux_data.fwd, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + ///// for each cp, find the K, using new fwd, v atm + //List> new_put_points = new List>(), new_call_points = new List>(); + //bool is_mult = _vol_axis(surface_settings) == VolSurfaceEnums.VolCurveVolAxis.ATMFactor; + //foreach (var put_point in _puts(surface_settings, curve_parameters)) + //{ + // double put_raw_k = VolSurfaceCoreFunctions.convert_axis(_strike_axis(surface_settings), put_point.Item1, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, new_atm_vol, aux_data); + // double curr_vol = curr_calc._compute_vol(put_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + // double abstract_vol = !is_mult ? curr_vol - new_atm_vol : curr_vol / new_atm_vol; + // new_put_points.Add(Tuple.Create(put_point.Item1, abstract_vol)); + //} + //foreach (var call_point in _calls(surface_settings, curve_parameters)) + //{ + // double call_raw_k = VolSurfaceCoreFunctions.convert_axis(_strike_axis(surface_settings), call_point.Item1, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, new_atm_vol, aux_data); + // double curr_vol = curr_calc._compute_vol(call_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + // double abstract_vol = !is_mult ? curr_vol - new_atm_vol : curr_vol / new_atm_vol; + // new_call_points.Add(Tuple.Create(call_point.Item1, abstract_vol)); + //} + + //rv = CoordinatesBasedModelHelper.update_atmvol(surface_settings, curve_parameters, new_atm_vol, false); + //rv = CoordinatesBasedModelHelper.update_controlpoints(surface_settings, rv, new_put_points, new_call_points); + //rv = CoordinatesBasedModelHelper.update_on_rebuild(surface_settings, rv, aux_data); + //return rv; + } + #endregion + + public bool is_initialized() { return _initialized; } + + public VolCurveParameters fill_missing_inputs(VolCurveParameters main_curve_params, VolCurveParameters sec_curve_params) + { + return null; + } + + private static IEnumerable _empty_doubles = Enumerable.Empty(); + public VolCurveMainOutput get_output() + { + if (_initialized) + { + double put_end_raw_strike = _convert_strike_axis(_settings.curve_endpoint_axis, _input_parameters.dualquadratic_model_parameters.put_end_strike, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + call_end_raw_strike = _convert_strike_axis(_settings.curve_endpoint_axis, _input_parameters.dualquadratic_model_parameters.call_end_strike, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + return new VolCurveMainOutput(_aux_data.fwd, + _conversion_fwd, + _final_unresponded_atm_vol, + _final_reponded_atm_vol, + _conversion_vol, + _empty_doubles, + _empty_doubles, + put_end_raw_strike, + call_end_raw_strike, + _input_parameters, + _aux_data, + _compute_vol, + _convert_strike_axis); + } + else + return new VolCurveMainOutput(Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Enumerable.Empty(), Enumerable.Empty(), + Double.NaN, Double.NaN, + _input_parameters, _aux_data, (k, k_axis, nth_derv) => Double.NaN, + (source_axis, k, target_axis) => Double.NaN); + } + + public void Dispose() { } + + #endregion + + private double _compute_vol(double strike, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, uint nth_derv = 0) + { + if (_initialized) + { + double plot_k = _convert_strike_axis(strike_axis, strike, _settings.strike_axis); + return _curve.compute(plot_k, nth_derv); + } + else + return Double.NaN; + } + + private double _convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolCurveStrikeAxis target_axis) + { + return VolSurfaceCoreFunctions.convert_axis(source_axis, source_point, target_axis,_pricing_model, + _conversion_vol, _conversion_fwd, _aux_data.biz_t, _aux_data.cal_t, _aux_data.riskless_rate); + } + + private static double _get_conversion_vol(VolSurfaceSettings vs_settings, VolCurveParameters curve_params, double final_responded_vol) + { + if (vs_settings.core_settings.strike_conversion_vol == VolSurfaceEnums.StrikeConversionVol.StandardVol) return curve_params.core_parameters.standard_vol; + else + { + double conv_vol_slider = curve_params.core_parameters.conversion_vol_slider; + conv_vol_slider = Double.IsNaN(conv_vol_slider) ? 0.0 : VolSurfaceUtilityFunctions.restrict_bw_min_and_max(conv_vol_slider, 0.0, 1.0); + return (conv_vol_slider * final_responded_vol) + ((1 - conv_vol_slider) * curve_params.dualquadratic_model_parameters.atm_vol); + } + } + + private static double _get_conversion_fwd(VolSurfaceSettings vs_settings, VolCurveParameters curve_params, VolSurfaceExpirationAuxiliaryData aux_data) + { + double conv_fwd_slider = curve_params.core_parameters.conversion_fwd_slider; + conv_fwd_slider = Double.IsNaN(conv_fwd_slider) ? 0.0 : VolSurfaceUtilityFunctions.restrict_bw_min_and_max(conv_fwd_slider, 0.0, 1.0); + /// the 1.0 check is just so that users who dont want to deal with ref_fwd's can leave it + /// unattended and we dont run into a NaN situation + return VolSurfaceUtilityFunctions.compare_doubles(conv_fwd_slider, 1.0) ? aux_data.fwd : (conv_fwd_slider * aux_data.fwd) + ((1 - conv_fwd_slider) * curve_params.core_parameters.ref_forward); + } + + private static bool _can_compute(VolSurfaceSettings settings, VolCurveParameters curve_parameters, double current_fwd, double path_induced_atm_vol_move) + { + return !Double.IsNaN(current_fwd) && + !Double.IsNaN(path_induced_atm_vol_move) && + curve_parameters != null && + curve_parameters.dualquadratic_model_parameters != null; + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/DualQuadtric/DualQuadraticModelVolCurveParameters.cs b/src/client/spark/Analytics/DualQuadtric/DualQuadraticModelVolCurveParameters.cs new file mode 100644 index 000000000..470d1aad4 --- /dev/null +++ b/src/client/spark/Analytics/DualQuadtric/DualQuadraticModelVolCurveParameters.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "DualQuadraticModelVolCurveParameters")] + public class DualQuadraticModelVolCurveParameters + { + [ProtoBuf.ProtoMember(20)] + public double put_slope { get; set; } + + [ProtoBuf.ProtoMember(30)] + public double put_curvature { get; set; } + + [ProtoBuf.ProtoMember(40)] + public double atm_vol { get; set; } + + [ProtoBuf.ProtoMember(50)] + public double x0 { get; set; } + + [ProtoBuf.ProtoMember(60)] + public double call_slope { get; set; } + + [ProtoBuf.ProtoMember(70)] + public double call_curvature { get; set; } + + [ProtoBuf.ProtoMember(80)] + public double epsilon { get; set; } + + [ProtoBuf.ProtoMember(90)] + public double put_end_strike { get; set; } + + [ProtoBuf.ProtoMember(100)] + public double call_end_strike { get; set; } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/DualQuadtric/DualQuadraticModelVolSurfaceSettings.cs b/src/client/spark/Analytics/DualQuadtric/DualQuadraticModelVolSurfaceSettings.cs new file mode 100644 index 000000000..e831f6711 --- /dev/null +++ b/src/client/spark/Analytics/DualQuadtric/DualQuadraticModelVolSurfaceSettings.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "DualQuadraticModelVolSurfaceSettings")] + public class DualQuadraticModelVolSurfaceSettings + { + /// Defines the axis the curve is calibrated on + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.VolCurveStrikeAxis strike_axis; + /// Defines the axis of the end of this curve + [ProtoBuf.ProtoMember(20)] + public VolSurfaceEnums.VolCurveStrikeAxis curve_endpoint_axis; + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/DualQuadtric/JointQudratic.cs b/src/client/spark/Analytics/DualQuadtric/JointQudratic.cs new file mode 100644 index 000000000..a6615b536 --- /dev/null +++ b/src/client/spark/Analytics/DualQuadtric/JointQudratic.cs @@ -0,0 +1,87 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// Joins 2 quadratics and smoothens them out in the + /// middle using a clamped cubic spline + public class JointQudratic + { + private readonly SimpleQudratic _left_curve, _right_curve; + private readonly double _left_smooth_x, _right_smooth_x, _center_x, _center_y; + private readonly MathNet.Numerics.Interpolation.CubicSpline _mid_spline; + + public JointQudratic(double left_slope, double left_curvature, double left_smooth_width, + double center_x, double center_y, + double right_slope, double right_curvature, double right_smooth_width) + : this(new SimpleQudratic(left_curvature, left_slope, Tuple.Create(center_x, center_y)), + left_smooth_width, + new SimpleQudratic(right_curvature, right_slope, Tuple.Create(center_x, center_y)), + right_smooth_width, + center_x, + center_y) + { } + + private JointQudratic(SimpleQudratic left_curve, double left_smooth_width, + SimpleQudratic right_curve, double right_smooth_width, + double center_x, double center_y) + { + _left_curve = left_curve; + _right_curve = right_curve; + _center_x = center_x; + _center_y = center_y; + _left_smooth_x = center_x - left_smooth_width; + _right_smooth_x = center_x + right_smooth_width; + _mid_spline = MathNet.Numerics.Interpolation.CubicSpline.InterpolateBoundariesSorted(new double[] { _left_smooth_x, center_x, _right_smooth_x }, + new double[] { _left_curve.compute(_left_smooth_x, 0), center_y, _right_curve.compute(_right_smooth_x, 0) }, + MathNet.Numerics.Interpolation.SplineBoundaryCondition.SecondDerivative, + _left_curve.compute(_left_smooth_x, 2), + MathNet.Numerics.Interpolation.SplineBoundaryCondition.SecondDerivative, + _right_curve.compute(_right_smooth_x, 2)); + } + + public JointQudratic rotate_slope(Tuple move) + { + if (move.Item1 < _center_x) + return new JointQudratic(_left_curve.rotate_slope(move), Math.Abs(_left_smooth_x - _center_x), _right_curve, Math.Abs(_right_smooth_x - _center_x), _center_x, _center_y); + else + return new JointQudratic(_left_curve, Math.Abs(_left_smooth_x - _center_x), _right_curve.rotate_slope(move), Math.Abs(_right_smooth_x - _center_x), _center_x, _center_y); + } + + public double compute(double x, uint nth_derv) + { + if (x <= _left_smooth_x) return _left_curve.compute(x, nth_derv); + if (x >= _right_smooth_x) return _right_curve.compute(x, nth_derv); + else + { + if (nth_derv == 0) + return _mid_spline.Interpolate(x); + else if (nth_derv == 1) + return _mid_spline.Differentiate(x); + else if (nth_derv == 2) + return _mid_spline.Differentiate2(x); + else + return 0.0; + } + } + + public double left_curvature { get { return _left_curve.curvature; } } + + public double left_slope { get { return _left_curve.slope ; } } + + public double right_curvature { get { return _right_curve.curvature; } } + + public double right_slope { get { return _right_curve.slope; } } + + public double center_x { get { return _center_x; } } + + public double center_y { get { return _center_y; } } + + public double left_smoothening_width { get { return Math.Abs(_center_x - _left_smooth_x); } } + + public double right_smoothening_width { get { return Math.Abs(_center_x - _right_smooth_x); } } + } +} diff --git a/src/client/spark/Analytics/DualQuadtric/SimpleQudratic.cs b/src/client/spark/Analytics/DualQuadtric/SimpleQudratic.cs new file mode 100644 index 000000000..35c2abfb1 --- /dev/null +++ b/src/client/spark/Analytics/DualQuadtric/SimpleQudratic.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + //Encapsulates a quadratic curve thats constructed given + //a and b (in ax^2 + bx + c) and a coordinate that lies on it + public class SimpleQudratic + { + private readonly double[] _coeffs; /// ith element has the ith power..c,b,a + private readonly Tuple _fixed_point; + + protected SimpleQudratic(double a, double b, double c, Tuple p) { _coeffs = new double[] { c, b, a }; _fixed_point = p; } + + public SimpleQudratic(double a, double b, Tuple p) + : this(a, b, p.Item2 - ((a * p.Item1 * p.Item1) + (b * p.Item1)) /*y - (ax^2 + bx)*/ , p) + { } + + public double curvature { get { return _coeffs.ElementAt(2); } } + + public double slope { get { return _coeffs.ElementAt(1); } } + + public double compute(double x, uint nth_derv) { return VolSurfaceCoreFunctions.compute_polynomial_df(_coeffs, x, nth_derv); } + + /// Moves the quadratic by changing b (slope), such that + /// move.x is moved by moved.y + public SimpleQudratic rotate_slope(Tuple move) + { + Tuple p1 = _fixed_point, p2 = Tuple.Create(move.Item1, compute(move.Item1, 0) + move.Item2); + IEnumerable coeffs = VolSurfaceCoreFunctions.get_quadratic_with_given_curvature(p1, p2, _coeffs[2]); + return new SimpleQudratic(coeffs.ElementAt(2), coeffs.ElementAt(1), coeffs.ElementAt(0), _fixed_point); + } + } + + public class SimpleQudraticZero + { + static double power_rule(double x, int order, uint nderiv) + { + double value = 0.0; + switch (nderiv) + { + case 0: + value = Math.Pow(x, order); + break; + case 1: + value = order * Math.Pow(x, Math.Max(order - 1, 0)); + break; + case 2: + value = order * (order - 1) * Math.Pow(x, Math.Max(order - 2, 0)); + break; + } + return value; + } + + private readonly double _a, _b; + private readonly Tuple _p0; + + public SimpleQudraticZero(double a, double b, Tuple p0) + { + _a = a; + _b = b; + _p0 = p0; + } + + public double curvature { get { return _a; } } + + public double slope { get { return _b; } } + + public double compute(double x, uint nderiv) + { + x = x - _p0.Item1; + return _p0.Item2 * power_rule(x, 0, nderiv) + _b * power_rule(x, 1, nderiv) + _a * power_rule(x, 2, nderiv); + } + + public SimpleQudraticZero rotate_slope(Tuple location_amount) + { + double new_slope = _b + location_amount.Item2 / location_amount.Item1; + return new SimpleQudraticZero(_a, new_slope, _p0); + } + + public SimpleQudraticZero rotate_curvature(Tuple location_amount) + { + double new_curvature = _a + (location_amount.Item2 / (location_amount.Item1 * location_amount.Item1)); + return new SimpleQudraticZero(new_curvature, _b, _p0); + } + } +} diff --git a/src/client/spark/Analytics/MarketImpliedVol/VolCurveMarketFitAction.cs b/src/client/spark/Analytics/MarketImpliedVol/VolCurveMarketFitAction.cs new file mode 100644 index 000000000..971dcfd49 --- /dev/null +++ b/src/client/spark/Analytics/MarketImpliedVol/VolCurveMarketFitAction.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class VolCurveMarketFitAction + { + public enum ActionType + { + FitATM, + FitWholeCurve + } + public readonly ActionType fit_action; + public readonly VolCurveMarketImpliedVolData implied_vol_data; + public readonly bool use_weighted_regression; + + public VolCurveMarketFitAction(ActionType this_fit_action, VolCurveMarketImpliedVolData this_implied_vol_data, bool this_use_weighted_regression) + { + fit_action = this_fit_action; + implied_vol_data = this_implied_vol_data; + use_weighted_regression = this_use_weighted_regression; + } + } +} diff --git a/src/client/spark/Analytics/MarketImpliedVol/VolCurveMarketImpliedVolData.cs b/src/client/spark/Analytics/MarketImpliedVol/VolCurveMarketImpliedVolData.cs new file mode 100644 index 000000000..ce795585b --- /dev/null +++ b/src/client/spark/Analytics/MarketImpliedVol/VolCurveMarketImpliedVolData.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// Strike by strike market implied vol for + /// one expiration + public class VolCurveMarketImpliedVolData + { + public readonly VolSurfaceExpirationAuxiliaryData aux_data; + public readonly VolSurfaceEnums.VolSurfacePricingModel pricing_model; + public readonly IDictionary put_rawk_vols, call_rawk_vols, stdk_vols = new Dictionary(); + public readonly double atm_strike, atm_vol, conversion_vol; + + public VolCurveMarketImpliedVolData(VolSurfaceExpirationAuxiliaryData this_aux_data, + VolSurfaceEnums.VolSurfacePricingModel pricing_model, + IDictionary this_put_srawk_vols, IDictionary this_call_rawk_vols, + double this_atm_strike, double this_atm_vol, double conversion_vol) + { + aux_data = this_aux_data; + this.pricing_model = pricing_model; + put_rawk_vols = this_put_srawk_vols; + call_rawk_vols = this_call_rawk_vols; + atm_strike = this_atm_strike; + atm_vol = this_atm_vol; + this.conversion_vol = conversion_vol; + foreach (KeyValuePair kv in Enumerable.Concat(put_rawk_vols, call_rawk_vols)) + { + double stdk = VolSurfaceCoreFunctions.convert_axis(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, kv.Key, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, pricing_model, + conversion_vol, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate); + stdk_vols[stdk] = kv.Value; + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/MarketImpliedVol/VolSurfaceBBOUnit.cs b/src/client/spark/Analytics/MarketImpliedVol/VolSurfaceBBOUnit.cs new file mode 100644 index 000000000..0401450a5 --- /dev/null +++ b/src/client/spark/Analytics/MarketImpliedVol/VolSurfaceBBOUnit.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// Just a packaging around BBO + /// (TODO:move it to common edge location and replace + /// blue2's BBOPacket with this) + public class VolSurfaceBBOUnit + { + public readonly double bid_price, ask_price; + public readonly uint bid_size, ask_size; + + public VolSurfaceBBOUnit(double this_bid_price, uint this_bid_size, + double this_ask_price, uint this_ask_size) + { + bid_price = this_bid_price; + bid_size = this_bid_size; + ask_price = this_ask_price; + ask_size = this_ask_size; + } + + public bool is_two_sided () {return bid_size != 0 && ask_size != 0;} + + public double get_mid_price(bool get_one_sided_mid = true) + { + double mid_price = (bid_price + ask_price) / 2.0; + if (Double.IsNaN(mid_price) && get_one_sided_mid) + mid_price = !Double.IsNaN(bid_price) ? bid_price : ask_price; + return mid_price; + } + + public double get_bid_ask_spread() { return ask_price - bid_price; } + } +} diff --git a/src/client/spark/Analytics/MarketImpliedVol/VolSurfaceMarketFitSettings.cs b/src/client/spark/Analytics/MarketImpliedVol/VolSurfaceMarketFitSettings.cs new file mode 100644 index 000000000..a11e518e0 --- /dev/null +++ b/src/client/spark/Analytics/MarketImpliedVol/VolSurfaceMarketFitSettings.cs @@ -0,0 +1,40 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolSurfaceMarketFitSettings")] + public class VolSurfaceMarketFitSettings + { + /// use one sided market or not + [ProtoBuf.ProtoMember(10)] + public bool ignore_one_sided_markets; + /// strikes with either bid size or ask size less than minimum_size are rejected + [ProtoBuf.ProtoMember(20)] + public uint minimum_top_book_size = 1; + /// strikes with bid_aks_spreads (in ticks) >= maximum_bid_ask_spread_ticks, are rejected + [ProtoBuf.ProtoMember(30)] + public uint maximum_bid_ask_spread_ticks = 100; + [ProtoBuf.ProtoMember(40)] + public double graph_update_period_ms = 2500; + /// If this is set to true a regression curve is drawn + /// and the vol model adheres to that + [ProtoBuf.ProtoMember(50)] + public bool use_weighted_regression_fit = false; + [ProtoBuf.ProtoMember(55)] + public uint regression_order = 4; + /// The system auto fits and saves vols if this is + /// set to true + [ProtoBuf.ProtoMember(60)] + public bool enable_auto_fit = false; + /// If enable_auto_fit = true, this governs + /// how often the system auto-fits + [ProtoBuf.ProtoMember(70)] + public double auto_fit_time_ms = 30000; + [ProtoBuf.ProtoMember(80)] + public VolSurfaceEnums.VolCurveFitRegion auto_fit_region = VolSurfaceEnums.VolCurveFitRegion.ATM; + } +} diff --git a/src/client/spark/Analytics/Misc/CubicSpline.cs b/src/client/spark/Analytics/Misc/CubicSpline.cs new file mode 100644 index 000000000..dae628cb0 --- /dev/null +++ b/src/client/spark/Analytics/Misc/CubicSpline.cs @@ -0,0 +1,287 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +using bts; + +namespace mbts.analytics +{ + /// This is implemented based on the wikipedia article: + /// http://en.wikipedia.org/wiki/Spline_interpolation + public class CubicSpline + { + private class MyTriDiagonalMatrix + { + /// A is sub-diagonal (A[0] is never used), + /// B is main diagonal, + /// C is the super-diagonal (C[C.Length-1] is never used) + public double[] A, B, C; + public int N { get { return (A != null ? A.Length : 0); } } + + public MyTriDiagonalMatrix(int n) + { + A = new double[n]; + B = new double[n]; + C = new double[n]; + } + + public double this[int row, int col] + { + get + { + int di = row - col; + if (di == 0) + return B[row]; + else if (di == -1) + { + Log.assert(row < N - 1); + return C[row]; + } + else if (di == 1) + { + Log.assert(row > 0); + return A[row]; + } + else return 0; + } + set + { + int di = row - col; + if (di == 0) + B[row] = value; + else if (di == -1) + { + Log.assert(row < N - 1); + C[row] = value; + } + else if (di == 1) + { + Log.assert(row > 0); + A[row] = value; + } + else + throw new ArgumentException("Only the main, super, and sub diagonals can be set."); + } + } + /// Uses the Thomas algorithm described in the wikipedia article: http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm + /// Not optimized. Not destructive. + /// Right side of the equation. + public double[] Solve(double[] d) + { + int n = this.N; + + if (d.Length != n) + throw new ArgumentException("The input d is not the same size as this matrix."); + + // cPrime + double[] c_prime = new double[n]; + c_prime[0] = C[0] / B[0]; + + for (int i = 1; i < n; i++) + c_prime[i] = C[i] / (B[i] - c_prime[i - 1] * A[i]); + + // dPrime + double[] d_prime = new double[n]; + d_prime[0] = d[0] / B[0]; + for (int i = 1; i < n; i++) + d_prime[i] = (d[i] - d_prime[i - 1] * A[i]) / (B[i] - c_prime[i - 1] * A[i]); + + // Back substitution + double[] x = new double[n]; + x[n - 1] = d_prime[n - 1]; + for (int i = n - 2; i >= 0; i--) + x[i] = d_prime[i] - c_prime[i] * x[i + 1]; + return x; + } + } + + // N-1 spline coefficients for N points + private double[] _a_list, _b_list; + private double[] _x_list, _y_list; + private const double _x_range_error = 1e-06; + /// For a clamped spline specify the end point derivatives + public CubicSpline(IEnumerable> points, double start_slope = double.NaN, double end_slope = double.NaN) + { + _generate_spline(points, start_slope, end_slope); + } + + private void _generate_spline(IEnumerable> points, double start_slope = double.NaN, double end_slope = double.NaN) + { + if (points == null || points.Count() <= 1) + /// I like this better than adding if's. Every follows the same code path + /// and the math takes care of the NaN's to return NaN's + points = new Tuple[] { Tuple.Create(0.0, Double.NaN), Tuple.Create(1.0, Double.NaN) }; + if (double.IsInfinity(start_slope) || double.IsInfinity(end_slope)) + throw new Exception("start_slope and end_slope cannot be infinity."); + points = points.OrderBy(t => t.Item1); + _x_list = points.Select(t => t.Item1).ToArray(); + _y_list = points.Select(t => t.Item2).ToArray(); + + int n = _x_list.Length; + double[] r = new double[n]; // the right hand side numbers: wikipedia page overloads b + + MyTriDiagonalMatrix m = new MyTriDiagonalMatrix(n); + double dx1, dx2, dy1, dy2; + + // First row is different (equation 16 from the article) + if (double.IsNaN(start_slope)) + { + dx1 = _x_list[1] - _x_list[0]; + m.C[0] = 1.0 / dx1; + m.B[0] = 2.0f * m.C[0]; + r[0] = 3 * (_y_list[1] - _y_list[0]) / (dx1 * dx1); + } + else + { + m.B[0] = 1; + r[0] = start_slope; + } + + // Body rows (equation 15 from the article) + for (int i = 1; i < n - 1; i++) + { + dx1 = _x_list[i] - _x_list[i - 1]; + dx2 = _x_list[i + 1] - _x_list[i]; + + m.A[i] = 1.0f / dx1; + m.C[i] = 1.0f / dx2; + m.B[i] = 2.0f * (m.A[i] + m.C[i]); + + dy1 = _y_list[i] - _y_list[i - 1]; + dy2 = _y_list[i + 1] - _y_list[i]; + r[i] = 3 * (dy1 / (dx1 * dx1) + dy2 / (dx2 * dx2)); + } + + // Last row also different (equation 17 from the article) + if (double.IsNaN(end_slope)) + { + dx1 = _x_list[n - 1] - _x_list[n - 2]; + dy1 = _y_list[n - 1] - _y_list[n - 2]; + m.A[n - 1] = 1.0f / dx1; + m.B[n - 1] = 2.0f * m.A[n - 1]; + r[n - 1] = 3 * (dy1 / (dx1 * dx1)); + } + else + { + m.B[n - 1] = 1; + r[n - 1] = end_slope; + } + + // k is the solution to the matrix + double[] k = m.Solve(r); + + // a and b are each spline's coefficients + _a_list = new double[n - 1]; + _b_list = new double[n - 1]; + + for (int i = 1; i < n; i++) + { + dx1 = _x_list[i] - _x_list[i - 1]; + dy1 = _y_list[i] - _y_list[i - 1]; + _a_list[i - 1] = k[i - 1] * dx1 - dy1; // equation 10 from the article + _b_list[i - 1] = -k[i] * dx1 + dy1; // equation 11 from the article + } + } + + public double compute(double x, uint nth_derv = 0) + { + if (nth_derv == 0) + return _compute_f(x); + else if (nth_derv == 1) + return _compute_df(x); + else if (nth_derv == 2) + return _compute_d2f(x); + else if (nth_derv == 3) + return _compute_d3f(x); + else + return 0.0; + } + + /// just linearly extends the spline infinitely. + /// If the arg x happens to be within the spline + /// limits it returns the real value + public double compute_with_infinite_extension(double x) + { + double min_x = _x_list.Min (), max_x = _x_list.Max (); + if (x < min_x) + return VolSurfaceCoreFunctions.get_line_y(Tuple.Create(min_x, compute(min_x)), compute(min_x, 1), x); + else if (x > max_x) + return VolSurfaceCoreFunctions.get_line_y(Tuple.Create(max_x, compute(max_x)), compute(max_x, 1), x); + else + return compute(x, 0); + } + + private double _compute_f(double x) + { + int seg_no = _find_segment(x); + if (seg_no >= 0 && seg_no < _x_list.Count() - 1) + { + double t = (x - _x_list[seg_no]) / (_x_list[seg_no + 1] - _x_list[seg_no]); + double y = (1 - t) * _y_list[seg_no] + t * _y_list[seg_no + 1] + t * (1 - t) * (_a_list[seg_no] * (1 - t) + _b_list[seg_no] * t); // equation 9 + return y; + } + else + return Double.NaN; + } + + private double _compute_df(double x) + { + int seg_no = _find_segment (x); + if (seg_no >= 0 && seg_no < _x_list.Count() - 1) + { + double y1 = _y_list[seg_no], y2 = _y_list[seg_no + 1], + x1 = _x_list[seg_no], x2 = _x_list[seg_no + 1], + a = _a_list[seg_no], b = _b_list[seg_no], + t = (x - x1) / (x2 - x1); + double rv = (y2 - y1) + (1 - 2 * t) * (a * (1 - t) + b * t) + t * (1 - t) * (b - a); + return rv / (x2 - x1); + } + else + return Double.NaN; + } + + private double _compute_d2f(double x) + { + int seg_no = _find_segment(x); + if (seg_no >= 0 && seg_no < _x_list.Count() - 1) + { + double x1 = _x_list[seg_no], x2 = _x_list[seg_no + 1], + t = (x - x1) / (x2 - x1), + a = _a_list[seg_no], + b = _b_list[seg_no]; + return (2 / Math.Pow((x2 - x1), 2.0)) * (b - 2 * a + (a - b) * 3 * t); + } + else + return Double.NaN; + } + + private double _compute_d3f(double x) + { + int seg_no = _find_segment(x); + if (seg_no >= 0 && seg_no < _x_list.Count() - 1) + { + double x1 = _x_list[seg_no], x2 = _x_list[seg_no + 1], + a = _a_list[seg_no], + b = _b_list[seg_no]; + return 6 * (a - b) / Math.Pow(x2 - x1, 3.0); + } + else + return Double.NaN; + } + + /// Finds the segment of the spline where this curve falls. + /// If x is outside the bounds returns -1 + private int _find_segment (double x) + { + int n_points = _x_list.Count(), n_segments = n_points - 1; + if (n_points > 0 && Math.Abs(_x_list.First() - x) < _x_range_error) + return 0; + else if (n_points > 0 && Math.Abs(_x_list.Last() - x) < _x_range_error) + return n_segments - 1; + for (int seg_no = 0; seg_no < n_segments; seg_no++) + if (x >= _x_list[seg_no] && x <= _x_list[seg_no + 1]) + return seg_no; + return -1; + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Misc/ExactFitPolynomial.cs b/src/client/spark/Analytics/Misc/ExactFitPolynomial.cs new file mode 100644 index 000000000..948f2be94 --- /dev/null +++ b/src/client/spark/Analytics/Misc/ExactFitPolynomial.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class ExactFitPolynomial + { + public readonly double[] coeffs; + private readonly double _min_x, _max_x; + public ExactFitPolynomial(IEnumerable> points) + { + if (points == null || points.Count() <= 1) + points = new Tuple[] { Tuple.Create(0.0, Double.NaN), Tuple.Create(1.0, Double.NaN) }; + IEnumerable x_points = points.Select(t => t.Item1); + _min_x = x_points.Min(); _max_x = x_points.Max(); + coeffs = MathNet.Numerics.Fit.Polynomial(points.Select(t => t.Item1).ToArray(), points.Select(t => t.Item2).ToArray(), points.Count() - 1); + } + + public double compute_df(double x, uint nth_derv = 0) { return VolSurfaceCoreFunctions.compute_polynomial_df(coeffs, x, nth_derv); } + + /// just linearly extends the polynomial infinitely. + /// If the arg x happens to be within the range + /// limits it returns the real value + public double compute_with_infinite_extension(double x) + { + if (x < _min_x) + return VolSurfaceCoreFunctions.get_line_y(Tuple.Create(_min_x, compute_df(_min_x)), compute_df(_min_x, 1), x); + else if (x > _max_x) + return VolSurfaceCoreFunctions.get_line_y(Tuple.Create(_max_x, compute_df(_max_x)), compute_df(_max_x, 1), x); + else + return compute_df(x, 0); + } + } +} diff --git a/src/client/spark/Analytics/Misc/MetadataHelper.cs b/src/client/spark/Analytics/Misc/MetadataHelper.cs new file mode 100644 index 000000000..fc490fce9 --- /dev/null +++ b/src/client/spark/Analytics/Misc/MetadataHelper.cs @@ -0,0 +1,59 @@ +//using bts.analytics; +using bts.api; +using bts.config; +// using mbts.collections.extensions; +using mbts.config; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using ProtoBuf; + +namespace mbts.analytics +{ + internal class MetadataHelper + { + static MetadataHelper() { + //conf = mbts.config.Configuration.get(); + //var options = conf.securities.Where(ssmd => ssmd.security_metadata.security.security_type == bts.o2.msgs.SecurityType.type.OPTION); + var options = conf.Securities; + metadata = options.ToDictionary(ssmd => ssmd.SecurityName, ssmd => new SecurityCalendarData(ssmd)); + // historic_metadata = options.ToDictionary(ssmd => ssmd.security_metadata.security.security_name, ssmd => new APISecurityCalendarData(ssmd)); + } + + private readonly static StaticConfiguration conf = new StaticConfiguration(); + private readonly static IDictionary metadata; + //private readonly static IDictionary historic_metadata; + + public static SecurityCalendarData get_calendar_data(string option_name) { return metadata.GetValueOrDefault(option_name); } + //public static APISecurityCalendarData get_historic_metadata(string option_name) { return historic_metadata.GetValueOrDefault(option_name); } + } + + internal class SecurityCalendarData + { + public SecurityCalendarData(StaticSecurityMetaData metadata) { + calendar_mode = VolSurfaceEnums.CalendarMode.PM; + sorted_holidays = metadata.Holidays.StaticHolidayCollection.OrderBy(hd => hd.Date).ToArray(); + } + + // public SecurityCalendarData(bts.analytics.CalendarMode.type calendar_mode, Holiday[] sorted_holidays) { + // this.calendar_mode = calendar_mode; + // this.sorted_holidays = sorted_holidays; + // } + + public readonly VolSurfaceEnums.CalendarMode calendar_mode = VolSurfaceEnums.CalendarMode.PM; + public readonly Holiday[] sorted_holidays; + } + + // internal class APISecurityCalendarData + // { + // public APISecurityCalendarData(StaticSecurityMetaData metadata) { + // SecurityInfo si; + // SecurityAndExpirationInfoModel.create_security_info(metadata.security_metadata, out si); + // security_info = (APISecurityInfo)si; + // sorted_holidays = metadata.holidays.static_holidays.OrderBy(hd => hd.date).Select(hd => (APIDateTime)hd.date).ToArray(); + // } + + // public readonly APISecurityInfo security_info; + // public readonly APIDateTime[] sorted_holidays; + // } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Misc/VolSurfaceCoreFunctions.cs b/src/client/spark/Analytics/Misc/VolSurfaceCoreFunctions.cs new file mode 100644 index 000000000..3ab61bbf6 --- /dev/null +++ b/src/client/spark/Analytics/Misc/VolSurfaceCoreFunctions.cs @@ -0,0 +1,2457 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts.api; +using bts.settings; +using bts.spark; + +using mbts.ui.shell; +using mbts.utils; +using mbts.ui.utility; +using bts; + + +namespace bts.api.analytics.functions +{ + public static class Probability + { + public static double dN(double z) + { + const double INVSQRT2PI=0.39894228040143267793994605993438; + return Math.Exp (-0.5*z*z)*INVSQRT2PI; + } + + public static double normal_pdf(double z) + { + const double MAXSTD=37.61588707; + const double mindN=2.2250738585134157e-308; + if(Math.Abs(z)>MAXSTD) return mindN; + else return dN(z); + } + + public static double inverse_normal(double x,int guess,double zguess) + { + if(x>1.0 || x<0.0) return 0.0; + double z; + const double err_tol=1.0e-15; + if(guess==0) z=(x>0.5)?0.67:-0.67; + else z=zguess; + double Nz=normal_cdf(z); + int counter=0; + for(;Math.Abs(Nz-x)>err_tol && counter<20;counter++){ + double epsilon=z*(x-Nz)/dN(z); + z+=epsilon*(1.0+epsilon*(0.5+epsilon*5.0/16.0))/z; + Nz = normal_cdf(z); + } + if(double.IsNaN(z) && guess!=0) return inverse_normal(x,0,0.0); + else return z; + } + + private readonly static double MAXSTD = 37.5193793471444; + private readonly static double MinNormCDF = 2.2250738585152E-308; + public static double normal_cdf(double x) + { + double XAbs = Math.Abs(x); + double Cumnorm = MinNormCDF; + if(XAbs < MAXSTD) + { + double Exponential = Math.Exp(-0.5 * XAbs * XAbs); + if(XAbs < 7.07106781186547) + { + double build = 3.52624965998911E-02 * XAbs + 0.700383064443688; + build = build * XAbs + 6.37396220353165; + build = build * XAbs + 33.912866078383; + build = build * XAbs + 112.079291497871; + build = build * XAbs + 221.213596169931; + build = build * XAbs + 220.206867912376; + Cumnorm = Exponential * build; + build = 8.83883476483184E-02 * XAbs + 1.75566716318264; + build = build * XAbs + 16.064177579207; + build = build * XAbs + 86.7807322029461; + build = build * XAbs + 296.564248779674; + build = build * XAbs + 637.333633378831; + build = build * XAbs + 793.826512519948; + build = build * XAbs + 440.413735824752; + Cumnorm = Cumnorm / build; + } + else + { + double build = XAbs + 0.65; + build = XAbs + 4.0 / build; + build = XAbs + 3.0 / build; + build = XAbs + 2.0 / build; + build = XAbs + 1.0 / build; + Cumnorm = Exponential / (build * 2.506628274631); + } + } + if(x > 0) Cumnorm = 1.0 - Cumnorm; + return Cumnorm; + } + } + + public static class Normal + { + public static void calls(double fwd, double[] rawk, double riskless, double []vol, double bizt, double calt, + out double[] result) + { + result = new double[rawk.Length]; + double df = Math.Exp(-riskless*calt); + double sqrt_t = Math.Sqrt(bizt); + for(int i = 0; i < result.Length; i++) + { + double vol_root_t = vol[i] * sqrt_t; + double d = (fwd - rawk[i]) / vol_root_t; + double expfactor = vol_root_t * BlackScholes.NormPDF(d); + double call = df * ((fwd - rawk[i]) * BlackScholes.NormCDF(d) + expfactor); + result[i] = call; + } + } + + public static void puts(double fwd, double[] rawk, double riskless, double[] vol, double bizt, double calt, + out double[] result) + { + result = new double[rawk.Length]; + double df = Math.Exp(-riskless * calt); + double sqrt_t = Math.Sqrt(bizt); + for(int i = 0; i < result.Length; i++) + { + double vol_root_t = vol[i] * sqrt_t; + double d = (fwd - rawk[i]) / vol_root_t; + double expfactor = vol_root_t * BlackScholes.NormPDF(d); + double put = df * ((rawk[i] - fwd) * BlackScholes.NormCDF(-d) + expfactor); + result[i] = put; + } + } + + public static void call_deltas(double fwd, double[] rawk, double riskless, double[] vol, double bizt, double calt, + out double[] result) + { + result = new double[rawk.Length]; + double df = Math.Exp(-riskless * calt); + double sqrt_t = Math.Sqrt(bizt); + for (int i = 0; i < result.Length; i++) + { + double vol_root_t = vol[i] * sqrt_t; + double d1 = (fwd - rawk[i]) / vol_root_t; + double cdelta = df * BlackScholes.NormCDF(d1); + result[i] = cdelta; + } + } + + public static void put_deltas(double fwd, double[] rawk, double riskless, double[] vol, double bizt, double calt, + out double[] result) + { + result = new double[rawk.Length]; + double df = Math.Exp(-riskless * calt); + double sqrt_t = Math.Sqrt(bizt); + for (int i = 0; i < result.Length; i++) + { + double vol_root_t = vol[i] * sqrt_t; + double d1 = (fwd - rawk[i]) / vol_root_t; + double pdelta = df * (BlackScholes.NormCDF(d1) - 1.0); + result[i] = pdelta; + } + } + + public static void vega(double fwd, double[] rawk, double riskless, double[] vols, double bizt, double calt, + out double[] vega) + { + vega = new double[rawk.Length]; + double disc = Math.Exp(-riskless * calt); + double sqrt_t = Math.Sqrt(bizt); + for(int i = 0; i < vega.Length; ++i) + { + double vol_root_t = vols[i] * sqrt_t; + double d = (fwd - rawk[i]) / vol_root_t; + double dN = BlackScholes.NormPDF(d); + vega[i] = disc * sqrt_t * dN; + } + } + + public static double normalprice_gen(double fwd,double rawk,double riskfree, double vol, double bizt, double calt, bool is_call) + { + double[] result; + if(is_call) + calls(fwd,new[]{rawk},riskfree,new[]{vol},bizt,calt,out result); + else + puts(fwd,new[]{rawk},riskfree,new[]{vol},bizt,calt,out result); + return result[0]; + } + + public static double normalprice_implied_vol(double fwd, double rawk, double riskless, + double volguess, double bizt, double calt, bool is_call, double price_targ) + { + if(volguess < 0.01 || volguess*volguess>25.0*rawk*fwd) + volguess = 0.05; + double price = normalprice_gen(fwd, rawk, riskless, volguess, bizt, calt, is_call); + const int maxIters=10; + const double errsqLim=1.0e-24; + double err=price_targ-price; + for(int counter=0;err*err>errsqLim && countererrsqLim) + return -1.0; + else + return volguess; + } + } + + public static class BlackScholes + { + static public double NormCDF(double z) + { + //return MathNet.Numerics.Distributions.Normal.CDF(0.0, 1.0, z); + return Probability.normal_cdf(z); + } + static public double NormPDF(double z) + { + //return MathNet.Numerics.Distributions.Normal.PDF(0.0, 1.0, z); + return Probability.normal_pdf(z); + } + + static public void calls(double spot, double[] rawk, double growth, double riskless, + double[] vol, double bizt, double calt, out double[] result) + { + calls(spot * Math.Exp(growth * calt), rawk, riskless, vol, bizt, calt, out result); + } + static public void calls(double fwd, double[] rawk, double riskless, double[] vol, double bizt, double calt, out double[] result) + { + result = new double[rawk.Length]; + double disc = Math.Exp(-riskless * calt); + double sqrt_t = Math.Sqrt(bizt); + for(int i = 0; i < rawk.Length; i++) + { + double vol_root_t = sqrt_t * vol[i]; + double d1 = Math.Log(fwd / rawk[i]) / vol_root_t + 0.5 * vol_root_t; + double d2 = d1 - vol_root_t; + result[i] = disc * (fwd * NormCDF(d1) - rawk[i] * NormCDF(d2)); + } + } + + static public void put(double spot, double[] rawk, double growth, double riskless, + double[] vol, double bizt, double calt, out double[] result) + { + puts(spot * Math.Exp(growth * calt), rawk, riskless, vol, bizt, calt, out result); + } + static public void puts(double fwd, double[] rawk, double riskless, double[] vol, double bizt, double calt, out double[] result) + { + result = new double[rawk.Length]; + double disc = Math.Exp(-riskless * calt); + double sqrt_t = Math.Sqrt(bizt); + for(int i = 0; i < rawk.Length; i++) + { + double vol_root_t = sqrt_t * vol[i]; + double d1 = Math.Log(fwd / rawk[i]) / vol_root_t + 0.5 * vol_root_t; + double d2 = d1 - vol_root_t; + result[i] = disc * (fwd * (NormCDF(d1) - 1.0) + rawk[i] * (1.0 - NormCDF(d2))); + } + } + + static public void vega(double fwd, double[] rawk, double riskless, double[] vol, double bizt, double calt, out double[] result) + { + result = new double[rawk.Length]; + double disc = Math.Exp(-riskless * calt); + double sqrt_t = Math.Sqrt(bizt); + for(int i = 0; i < rawk.Length; ++i) + { + double vol_root_t = sqrt_t * vol[i]; + double d1 = Math.Log(fwd / rawk[i]) / vol_root_t + 0.5 * vol_root_t; + result[i] = disc * fwd * NormPDF(d1) * sqrt_t; + } + } + + static public double atm_straddle(double fwd, double riskless, double vol, double bizt, double calt) + { + return 2.0*Math.Exp((/*growth*/-riskless)*calt)*fwd*(2.0*NormCDF(0.5*vol*Math.Sqrt(bizt))-1.0); + } + + public class PriceDeltaGammaVegaThetaRho + { + public double strike; + public double call, put; + public double cdelta, pdelta; + public double cvega, pvega; + public double cgamma, pgamma; + public double cdiscrho, pdiscrho; + public double cvoltheta, pvoltheta; + } + + static public void analytic_theos(double fwd, double[] rawk, double riskless, double[] vol, + double bizt, double calt, out PriceDeltaGammaVegaThetaRho[] result) + { + result = new PriceDeltaGammaVegaThetaRho[rawk.Length]; + double disc = Math.Exp(-riskless * calt); + double sqrt_t = Math.Sqrt(bizt); + for(int i = 0; i < rawk.Length; ++i) + { + double vol_root_t = sqrt_t * vol[i]; + double d1 = Math.Log(fwd / rawk[i]) / vol_root_t + 0.5 * vol_root_t; + double d2 = d1 - vol_root_t; + double nd1 = NormCDF(d1); + double nd2 = NormCDF(d2); + result[i].strike = rawk[i]; + result[i].call = disc * (fwd * nd1 - rawk[i] * nd2); + result[i].put = disc * (fwd * (nd1 - 1.0) + rawk[i] * (1.0 - nd2)); + result[i].cdelta = disc*nd1; + result[i].pdelta = disc * (nd1 - 1.0); + double dnd1 = NormPDF(d1); + result[i].cgamma = result[i].pgamma = disc * dnd1 / (fwd*vol_root_t); + result[i].cvega = result[i].pvega = disc * dnd1 * fwd * sqrt_t; + result[i].cdiscrho = rawk[i] * calt * disc * nd2; + result[i].pdiscrho = -rawk[i] * calt * disc * (1.0 - nd2); + + double theta_base = -disc * fwd * dnd1 * vol[i] / (2 * sqrt_t); + result[i].cvoltheta = theta_base - riskless * rawk[i] * disc * nd2; + result[i].pvoltheta = theta_base + riskless * rawk[i] * disc * (1.0 - nd2); + } + } + + /// + /// Estimate Vega/Fwd Via 'moneyness' and vol assuming zero interest rate and using t_estimate + /// + /// + /// + static public double moneyness_vega(double x, double sigma, double vol, double t_estimate, double fwd_estimate, double riskless_estimate = 0.0, double calt_estimate = 0.0) + { + double disc = Math.Exp(-riskless_estimate * calt_estimate); + double sqrt_t = Math.Sqrt(t_estimate); + double vol_root_t = sqrt_t * vol; + double ln_k_over_f = x * sigma * sqrt_t; + double d1 = -ln_k_over_f / vol_root_t + 0.5 * vol_root_t; + double vegaish = disc * fwd_estimate * NormPDF(d1) * sqrt_t; + return vegaish / 100.0; + } + + public static double implied_vol(double fwd, double rawk, double riskless, double initVol, double bizt, double calt, + bool is_call, double target_price, int max_iterations = 10) + { + if(max_iterations <= 0) + max_iterations = 10; + const double ImpVolTol = 1.0e-8; + double retinv = Math.Log(fwd / rawk); + double temp_factor = retinv * retinv; + double sqrthalftpi = Math.Sqrt(0.5 * bizt / Math.PI); + double sqrt_t = Math.Sqrt(bizt); + + double disc = Math.Exp(-riskless * calt); + double CurrPrice = 0.0, Vol = initVol; + for(int i = 0; i < max_iterations; i++) + { + double VolRootT = Vol * sqrt_t; + double d1 = retinv / VolRootT + 0.5 * VolRootT; + double d2 = d1 - VolRootT; + if(is_call) + CurrPrice = disc * (fwd * NormCDF(d1) - rawk * NormCDF(d2)); + else + CurrPrice = disc * (fwd * (NormCDF(d1) - 1.0) + rawk * (1.0 - NormCDF(d2))); + if(Math.Abs(CurrPrice - target_price) < ImpVolTol) + break; + else + { + double ratio = temp_factor / (Vol * Vol * Vol * bizt) - 0.25 * Vol * bizt; + double Vega = disc * fwd * sqrthalftpi * Math.Exp(-0.5 * d1 * d1); + if(Vega < 1e-5) + Vega = 1e-5; + double dvol, temp_arg; + if(Math.Abs(ratio) > 0.0001 && (temp_arg = 1.0 + 2.0 * (target_price - CurrPrice) * ratio / Vega) > 0.0001) + dvol = (Math.Sqrt(temp_arg) - 1.0) / ratio; + else + dvol = (target_price - CurrPrice) / Vega; + if(dvol < -0.5 * Vol) + dvol = -0.5 * Vol; + else if(dvol > 0.2) + dvol = 0.2; + Vol += dvol; + } + } + if(Math.Abs(CurrPrice - target_price) < ImpVolTol && Math.Abs(Vol - initVol) > 0.0000001) + return Vol; + else + return -1.0; + } + } + + public static class EurodollarNormal + { + public static void calls(double fwd, double[] rawk, double riskless, double []vol, double bizt, double calt, + out double[] result) + { + fwd = 100.0 - fwd; + rawk = rawk.Select(k => 100.0 - k).ToArray(); + //yes this should really be puts + Normal.puts(fwd, rawk, riskless, vol, bizt, calt, out result); + } + + public static void puts(double fwd, double[] rawk, double riskless, double[] vol, double bizt, double calt, + out double[] result) + { + fwd = 100.0 - fwd; + rawk = rawk.Select(k => 100.0 - k).ToArray(); + //yes this should really be calls + Normal.calls(fwd, rawk, riskless, vol, bizt, calt, out result); + } + + public static void call_deltas(double fwd, double[] rawk, double riskless, double[] vol, double bizt, double calt, + out double[] result) + { + fwd = 100.0 - fwd; + rawk = rawk.Select(k => 100.0 - k).ToArray(); + //yes this should really be puts + Normal.put_deltas(fwd, rawk, riskless, vol, bizt, calt, out result); + result = result.Select(r => -r).ToArray(); + } + + public static void put_deltas(double fwd, double[] rawk, double riskless, double[] vol, double bizt, double calt, + out double[] result) + { + fwd = 100.0 - fwd; + rawk = rawk.Select(k => 100.0 - k).ToArray(); + //yes this should really be calls + Normal.call_deltas(fwd, rawk, riskless, vol, bizt, calt, out result); + result = result.Select(r => -r).ToArray(); + } + + public static void vega(double fwd, double[] rawk, double riskless, double[] vols, double bizt, double calt, + out double[] vega) + { + fwd = 100.0 - fwd; + rawk = rawk.Select(k => 100.0 - k).ToArray(); + Normal.vega(fwd, rawk, riskless, vols, bizt, calt, out vega); + } + + public static double eurodollar_gen(double fwd,double rawk,double riskfree, double vol, double bizt, double calt, bool is_call) + { + double[] result; + if(is_call) + calls(fwd,new[]{rawk},riskfree,new[]{vol},bizt,calt,out result); + else + puts(fwd,new[]{rawk},riskfree,new[]{vol},bizt,calt,out result); + return result[0]; + } + + public static double eurodollar_implied_vol(double fwd, double rawk, double riskless, + double volguess, double bizt, double calt, bool is_call, double price_targ) + { + fwd = 100.0 - fwd; + rawk = 100.0 - rawk; + var v = Normal.normalprice_implied_vol(fwd, rawk, riskless, volguess, bizt, calt, !is_call, price_targ); + return v; + } + } + + public static class Whaley + { + public static void calls(double fwd, double[] rawk, double riskless, double[] vol, + double bizt, double calt, out double[] calls, double sexpower = 0.0) + { + Whaley.calls(fwd, rawk, 0.0, riskless, vol, bizt, calt, out calls, sexpower); + } + public static void calls(double spot, double[] rawk, double growth, double riskless, double[] vol, + double bizt, double calt, out double[] calls, double sexpower = 0.0) + { + int n = rawk.Length; + calls = new double[n]; + double a2 = 0.0, q2 = 0.0; + for(int i = 0; i < n; ++i) + { + double Sex = AmCallSex(rawk[i], growth, riskless, vol[i], bizt, calt, ref a2, ref q2); + Sex *= Math.Pow(spot / Sex, sexpower); + calls[i] = BSGen(spot, rawk[i], growth, riskless, vol[i], bizt, calt, true); + if(spot < Sex) + { + a2 = calca2(Sex, rawk[i], growth, riskless, vol[i], bizt, calt, q2); + double a2_adj = a2 * Math.Pow(spot / Sex, q2); + if(a2_adj > 0.0) calls[i] += a2_adj; + if(calls[i] < (spot - rawk[i])) calls[i] = spot - rawk[i]; + } + else calls[i] = spot - rawk[i]; + if(double.IsNaN(Sex)) + calls[i] = Sex; + } + } + + public static void puts(double fwd, double[] rawk, double riskless, double[] vol, + double bizt, double calt, out double[] calls, double sexpower = 0.0) + { + Whaley.puts(fwd, rawk, 0.0, riskless, vol, bizt, calt, out calls, sexpower); + } + + public static void puts(double spot, double[] rawk, double growth, double riskless, + double[] vol, double bizt, double calt, out double[] puts, double sexpower = 0.0) + { + int n = rawk.Length; + puts = new double[n]; + double a1 = 0.0,q1 = 0.0; + for(int i=0;iSex){ + a1=calca1(Sex,rawk[i],growth,riskless,vol[i],bizt,calt,q1); + double a1_adj = a1*Math.Pow(spot/Sex,q1); + if (a1_adj > 0.0) puts[i]+=a1_adj; + if(puts[i]<(rawk[i]-spot)) puts[i]=rawk[i]-spot; + }else puts[i]=rawk[i]-spot; + if(double.IsNaN(Sex)) + puts[i]=Sex; + } + } + + private static double WhaleyGen(double spot, double rawk, double growth, double riskless, double vol, + double bizt, double calt, bool is_call) + { + double[] temp_temp_price; + if(is_call) + calls(spot, new double[] { rawk }, growth, riskless, new double[] { vol }, bizt, calt, out temp_temp_price); + else + puts(spot, new double[] { rawk }, growth, riskless, new double[] { vol }, bizt, calt, out temp_temp_price); + return temp_temp_price[0]; + } + + public static double american_implied_vol(double fwd, double rawk, double riskless, double initVol, double bizt, double calt, + bool is_call, double target_price, int max_iterations = 20) + { + return american_implied_vol(fwd, rawk, 0.0, riskless, initVol, bizt, calt, is_call, target_price, max_iterations); + } + + private static double american_implied_vol(double spot, double rawk, double growth, double riskless, double initVol, + double bizt, double calt, bool is_call, double target_price, int max_iterations = 20) + { + const double errtol=1.0e-08; + const double ImpVolTol=1.0e-6; + if(max_iterations <= 0) + max_iterations = 20; + + double ImpVol=initVol; + if(initVol<0.0001) ImpVol=0.2; + double dvol=0.01,vol_ub=10.0,vol_lb=0.0; + double[] vol_vec = new double[2 * max_iterations + 1], price_vec = new double[2 * max_iterations + 1]; + double temp_price = WhaleyGen(spot, rawk, growth, riskless, ImpVol, bizt, calt, is_call); + price_vec[0]=temp_price; + vol_vec[0]=ImpVol; + int i; + for(i = 0; i < max_iterations; i++) + { + if(Math.Abs(temp_price - target_price) > ImpVolTol) + { + double last_price=temp_price; + ImpVol+=dvol; + temp_price=WhaleyGen(spot,rawk,growth,riskless,ImpVol,bizt,calt,is_call); + price_vec[i+1]=temp_price; + vol_vec[i+1]=ImpVol; + if(Math.Abs(temp_price-last_price)>errtol){ + if(temp_price > target_price && vol_ub > ImpVol) vol_ub = ImpVol; + if(temp_price < target_price && vol_lb < ImpVol) vol_lb = ImpVol; + dvol = dvol * (target_price - temp_price) / (temp_price - last_price); + if(dvol<(vol_lb-ImpVol)) dvol=0.5*(vol_lb-ImpVol); + else if(dvol>(vol_ub-ImpVol)) dvol=0.5*(vol_ub-ImpVol); + }else break; + } + } + //if(Math.Abs(temp_price - target_price) > 2.0 * ImpVolTol) + //{ + // for (; i<2*max_iterations; i++){ + // //sort_doubles(i+1,price_vec,vol_vec); + // Array.Sort(price_vec, vol_vec); + // ImpVol = Interpolation.interp_linear(target_price, price_vec, vol_vec); + // temp_price=WhaleyGen(spot,rawk,growth,riskless,ImpVol,bizt,calt, is_call); + // price_vec[i+1]=temp_price; + // vol_vec[i+1]=ImpVol; + // if(Math.Abs(temp_price - target_price) < ImpVolTol) break; + // } + // ImpVol = Interpolation.interp_linear(target_price, price_vec, vol_vec); + //} + //if(Math.Abs(temp_price - target_price) > 2.0 * ImpVolTol) + // return -1.0; + //else + // return ImpVol; + + if(Math.Abs(temp_price - target_price) < ImpVolTol && Math.Abs(ImpVol - initVol) > 0.0000001) + return ImpVol; + else + return -1.0; + } + + public static double american_implied_vol_2(double fwd, double rawk, double riskless, double initVol, + double bizt, double calt, bool is_call, double target_price, + int max_iterations = 20) + { + return american_implied_vol_2(fwd, rawk, 0.0, riskless, initVol, bizt, calt, is_call, target_price, max_iterations); + } + private static double american_implied_vol_2(double spot, double rawk, double growth, double riskless, double initVol, + double bizt, double calt, bool is_call, double target_price, + int max_iterations = 20) + { + if(max_iterations <= 0) + max_iterations = 20; + const double ImpVolTol = 1.0e-8; + + double disc = Math.Exp(-riskless * calt); + double fwd = spot*Math.Exp(growth * calt); + double CurrPrice = 0.0, Vol = initVol; + for(int i = 0; i < max_iterations; i++) + { + CurrPrice = WhaleyGen(spot, rawk, growth, riskless, Vol, bizt, calt, is_call); + if(Math.Abs(CurrPrice - target_price) < ImpVolTol) + break; + else + { + double[] vega; + BlackScholes.vega(fwd, new[] { rawk }, riskless, new[] { Vol }, bizt, calt, out vega); + if(vega[0] < 1e-5) + vega[0] = 1e-5; + double dvol = dvol = (target_price - CurrPrice) / vega[0]; + if(dvol < -0.5 * Vol) + dvol = -0.5 * Vol; + else if(dvol > 0.2) + dvol = 0.2; + Vol += dvol; + if(Vol <= 0.0) + Vol = 0.0000001; + } + } + if(Math.Abs(CurrPrice - target_price) < ImpVolTol && Math.Abs(Vol - initVol) > 0.0000001) + return Vol; + else + return -1.0; + } + + #region Call & Put Sex + + private static double calca1(double Sex, double X, double GrowthRate, double RiskFree, double Vol, double bizt, double calt, double q1) + { + double EffDivYld = RiskFree - GrowthRate; + double VolRootT = Vol * Math.Sqrt(bizt); + double div_factor = Math.Exp(-EffDivYld * calt); + double d1ex = (Math.Log(Sex / X) + GrowthRate * calt) / VolRootT + 0.5 * VolRootT; + double Nd1ex = BlackScholes.NormCDF(-d1ex); + return -Sex * (1.0 - div_factor * Nd1ex) / q1; + } + private static double calca2(double Sex, double X, double GrowthRate, double RiskFree, double Vol, double bizt, double calt, double q2) + { + double EffDivYld = RiskFree - GrowthRate; + double VolRootT = Vol * Math.Sqrt(bizt); + double div_factor = Math.Exp(-EffDivYld * calt); + double d1ex = (Math.Log(Sex / X) + GrowthRate * calt) / VolRootT + 0.5 * VolRootT; + double Nd1ex = BlackScholes.NormCDF(d1ex); + return Sex * (1.0 - div_factor * Nd1ex) / q2; + } + private static double BSGen(double Spot, double rawk, double GrowthRate, double RiskFree, double Vol, double bizt, double calt, bool is_call) + { + double[] result = new double[1]; + if(is_call) + BlackScholes.calls(Spot, new double[] { rawk }, RiskFree, new double[] { Vol }, bizt, calt, out result); + else + BlackScholes.puts(Spot, new double[] { rawk }, RiskFree, new double[] { Vol }, bizt, calt, out result); + return result[0]; + } + + //X Here is rawk + const int whaleyIterations = 20; + const double whaleySexError=5.0e-8; + private static double AmCallSex(double X, double GrowthRate, double RiskFree, double Vol, + double bizt, double calt, ref double a2, ref double q2, bool QuadFlag = true) + { + double S_seed = -1.0; + if(Vol < 1.0e-6) return 1.0e-6; + if((RiskFree - GrowthRate) <= 1.0e-6) + {// early ex val>=0 only when riskless>growth + return 1.0e12; + } + double EffDivYld = RiskFree - GrowthRate; + double VolRootT = Vol * Math.Sqrt(bizt); + double Sq2PI_inv = Math.Sqrt(0.5 / Math.PI); + double Sq2PIVRT_inv = Sq2PI_inv / VolRootT; + double vol_sqr = Vol * Vol; + double n = 2.0 * GrowthRate / vol_sqr; + double k; + if(RiskFree > 0.000001) k = 2.0 * RiskFree / (vol_sqr * (1.0 - Math.Exp(-RiskFree * calt))); + else k = 2.0 / (calt * vol_sqr); + q2 = 0.5 * (1.0 - n + Math.Sqrt((n - 1.0) * (n - 1.0) + 4.0 * k)); + + double m = 2.0 * RiskFree / vol_sqr; + double q2temp = 1.0 - n + Math.Sqrt((n - 1.0) * (n - 1.0) + 4.0 * m); + double S_inf = X / (1.0 - 2.0 / q2temp); + double h2 = (GrowthRate * calt + 2.0 * VolRootT) * (1.0 - q2temp / 2.0); + if(S_seed < 0.0) S_seed = X + (S_inf - X) * (1.0 - Math.Exp(h2)); + double Sex = S_seed; + + double div_factor = Math.Exp(-EffDivYld * calt); + double MinError = 1000.0 * X; + double BestSex = Sex; + double d1ex = (Math.Log(Sex / X) + GrowthRate * calt) / VolRootT + 0.5 * VolRootT; + double Nd1ex = BlackScholes.NormCDF(d1ex); + double error = 0.0; + a2 = Sex * (1.0 - div_factor * Nd1ex) / q2; + for(int i = 0; i <= whaleyIterations; i++) + { + error = Sex - X - BSGen(Sex, X, GrowthRate, RiskFree, Vol, bizt, calt, true) - a2; + if(Math.Abs(error) < whaleySexError) + { + MinError = Math.Abs(error); + BestSex = Sex; + break; + } + if(Math.Abs(error) < MinError) + { + BestSex = Sex; + MinError = Math.Abs(error); + } + // da2/dSex=(1.0-div_factor*(Nd1ex+Sex*dNd1exSex))/q2; + double dNd1exSex = Math.Exp(-0.5 * d1ex * d1ex) * Sq2PIVRT_inv;// Sex*dNd1/dSex + double dErrdSex = (1.0 - div_factor * Nd1ex) * (1.0 - 1.0 / q2) + div_factor * dNd1exSex / q2; + double d2ErrdSex = -div_factor * dNd1exSex / Sex * (1.0 - 1.0 / q2 + d1ex / (q2 * VolRootT)); + double dS = 0.0; + if(QuadFlag && error * d2ErrdSex < 0.5 * dErrdSex * dErrdSex && Math.Abs(d2ErrdSex) > 1.0e-4 && Math.Abs(dErrdSex) > 1.0e-4) dS = dErrdSex / d2ErrdSex * (Math.Sqrt(1.0 - 2.0 * error * d2ErrdSex / (dErrdSex * dErrdSex)) - 1.0); + else dS = -error / dErrdSex; + // if(fabs(dErrdSex)<1.0e-6) Sex*=1.5; + if(double.IsNaN(dS)) Sex *= Math.Pow(Sex / X, 0.1);// move it a logarithmic smidge further away from X + else if(dS > 9.0 * Sex) Sex *= 10.0; + else if(dS < -0.9 * Sex) Sex *= 0.1; + else Sex += dS; + d1ex = (Math.Log(Sex / X) + GrowthRate * calt) / VolRootT + 0.5 * VolRootT; + Nd1ex = BlackScholes.NormCDF(d1ex); + a2 = Sex * (1.0 - div_factor * Nd1ex) / q2; + } + if(MinError > 100.0 * whaleySexError) + { + if(QuadFlag) + return AmCallSex(X, GrowthRate, RiskFree, Vol, bizt, calt, ref a2, ref q2, false); + //else sexconv=Failed; + BestSex = Sex = S_seed; + d1ex = (Math.Log(Sex / X) + GrowthRate * calt) / VolRootT + 0.5 * VolRootT; + Nd1ex = BlackScholes.NormCDF(d1ex); + a2 = Sex * (1.0 - div_factor * Nd1ex) / q2; + } + return BestSex; + } + + //X here is rawk + public static double AmPutSex(double X, double GrowthRate, double RiskFree, double Vol, double bizt, double calt, ref double a1, ref double q1, bool QuadFlag = true) + { + double S_seed = -1.0; + if(Vol < 1.0e-6) return 1.0e-6; + double EffDivYld = RiskFree - GrowthRate; + double VolRootT = Vol * Math.Sqrt(bizt); + double vol_sqr = Vol * Vol; + double Sq2PI_inv = Math.Sqrt(0.5 / Math.PI); + double Sq2PIVRT_inv = Sq2PI_inv / VolRootT; + double n = 2.0 * GrowthRate / vol_sqr; + double k; + if(RiskFree > 0.00001) k = 2.0 * RiskFree / (vol_sqr * (1.0 - Math.Exp(-RiskFree * calt))); + else k = 2.0 / (calt * vol_sqr); + q1 = 0.5 * (1.0 - n - Math.Sqrt((n - 1.0) * (n - 1.0) + 4.0 * k)); + double div_factor = Math.Exp(-EffDivYld * calt); + double m = 2.0 * RiskFree / vol_sqr; + double q1temp = 1.0 - n - Math.Sqrt((n - 1.0) * (n - 1.0) + 4.0 * m); + if(q1temp > 2.0001 || q1temp < -0.00001) + { + double S_inf = X / (1.0 - 2.0 / q1temp); + // might need to trap for fabs(RawStrike-Sex) too small to divide by + double h1 = (GrowthRate * calt - 2.0 * VolRootT) * X / (X - S_inf); + if(S_seed < 0.0) S_seed = 0.9 * X; + else S_seed = S_inf + (X - S_inf) * Math.Exp(h1); + } + else if(S_seed <= 0.0) S_seed = 0.9 * X; + double Sex = S_seed; + double BestSex = S_seed; + double MinError = 1000.0 * Sex; + double d1ex = (Math.Log(Sex / X) + GrowthRate * calt) / VolRootT + 0.5 * VolRootT; + double Nd1ex = BlackScholes.NormCDF(-d1ex); + a1 = -Sex * (1.0 - div_factor * Nd1ex) / q1; + for(int i = 0; i <= whaleyIterations; i++) + { + double error = X - Sex - BSGen(Sex, X, GrowthRate, RiskFree, Vol, bizt, calt, false) - a1; + if(Math.Abs(error) < whaleySexError) + { + MinError = Math.Abs(error); + BestSex = Sex; + break; + } + if(Math.Abs(error) < MinError) + { + MinError = Math.Abs(error); + BestSex = Sex; + } + double dNd1exSex = -Math.Exp(-0.5 * d1ex * d1ex) * Sq2PIVRT_inv;// Sex*dNd1/dSex + double dErrdSex = (1.0 - div_factor * Nd1ex) * (1.0 / q1 - 1.0) - div_factor * dNd1exSex / q1; + // double dErrdSex=-1+div_factor*Nd1ex-a1/Sex+div_factor*exp(-0.5*d1ex*d1ex)/(VolRootT*sqrt(2.0*PI))/q1; + double d2ErrdSex = -div_factor * dNd1exSex / Sex * (1.0 / q1 - 1.0 - d1ex / (q1 * VolRootT)); + double dS; + if(QuadFlag && error * d2ErrdSex < 0.5 * dErrdSex * dErrdSex && Math.Abs(d2ErrdSex) > 1.0e-4 && Math.Abs(dErrdSex) > 1.0e-4) dS = dErrdSex / d2ErrdSex * (Math.Sqrt(1.0 - 2.0 * error * d2ErrdSex / (dErrdSex * dErrdSex)) - 1.0); + else dS = -error / dErrdSex; + // if(fabs(dErrdSex)<1.0e-6) Sex*=1.5; + if(double.IsNaN(dS)) Sex *= Math.Pow(Sex / X, 0.1);// move it a logarithmic smidge further away from X + else if(dS > 9.0 * Sex) Sex *= 10.0; + else if(dS < -0.9 * Sex) Sex *= 0.1; + else Sex += dS; + d1ex = (Math.Log(Sex / X) + GrowthRate * calt) / VolRootT + 0.5 * VolRootT; + Nd1ex = BlackScholes.NormCDF(-d1ex); + a1 = -Sex * (1.0 - div_factor * Nd1ex) / q1; + } + if(MinError > 100.0 * whaleySexError) + { + if(QuadFlag) BestSex = AmPutSex(X, GrowthRate, RiskFree, Vol, bizt, calt, ref a1, ref q1, false); + else + { + a1 = -Sex * (1.0 - div_factor * Nd1ex) / q1; + double error = X - Sex - BSGen(Sex, X, GrowthRate, RiskFree, Vol, bizt, calt, false) - a1; + //if(fabs(error)>100.0*whaleySexError){ + // Sex=AmPutSexLastResort(X,GrowthRate,RiskFree,Vol,bizt,calt); + // d1ex=(log(Sex/X)+GrowthRate*calt)/VolRootT+0.5*VolRootT; + // Nd1ex=NormCDF(-d1ex); + // a1=-Sex*(1.0-div_factor*Nd1ex)/q1; + // error=X-Sex-BSGen(Sex,X,GrowthRate,RiskFree,Vol,bizt,calt,Put)-a1; + // if(fabs(error)>100.0*whaleySexError){ + // sexconv=Failed; // send error message to log file reporting failure to converge and listing all argument values + // Sex=S_seed; + // d1ex=(log(Sex/X)+GrowthRate*calt)/VolRootT+0.5*VolRootT; + // Nd1ex=NormCDF(d1ex); + // a1=-Sex*(1.0-div_factor*Nd1ex)/q1; + // } + //} + BestSex = Sex; + } + } + return BestSex; + } + #endregion + } + + public static class VegaFactor + { + public static double interpolate_vol_dates(double target_date, double date1, double date2, double vol1,double vol2) + { + if(date1 == date2 || date1 > target_date) + return vol1; + else if (date2 < target_date) + return vol2; + double a =(date2 - target_date)/(date2 - date1); + double vol = (-vol1 + (vol1 - vol2) * Math.Exp(a) + Math.E * vol2) / (Math.E - 1.0); + return vol; + } + + public static double interpolate_vol(double t1, double vol1, double t2, double vol2, double t) + { + if(t1== t2 || t1 > t) + return vol1; + else if(t2 < t) + return vol2; + double a = t2 / (t2 - t1); + double vol = (-vol1 + (vol1 - vol2) * Math.Exp(a) + Math.E * vol2) / (Math.E - 1.0); + return vol; + } + + static public double vega_factor_shortcut(double normal_bizt, double normal_vol, double current_bizt, double current_vol) + { + normal_bizt = Math.Max(normal_bizt, 0.001); current_bizt = Math.Max(current_bizt, 0.001); + double[] fwd = new double[] { 1.0 }; + double[] normal_vega, current_vega; + BlackScholes.vega(fwd[0], fwd, 0.0, new double[] { normal_vol }, normal_bizt, 0.0, out normal_vega); + BlackScholes.vega(fwd[0], fwd, 0.0, new double[] { current_vol }, current_bizt, 0.0, out current_vega); + const double vega_factor_max = 15.0; + double vf = Math.Min(normal_vega[0] / current_vega[0], vega_factor_max); + return vf; + } + } + +} + +namespace mbts.analytics +{ + public static class TheoHelper + { + static public void set_to_parity(ref mbts.analytics.Theos result, double settle_price) + { + double expiration = result.expiration; + double strike = result.strike; + double call = Math.Max(settle_price - strike, 0.0); + double put = Math.Max(strike - settle_price, 0.0); + double driver = result.driver; + double fwd = result.fwd; + double vol = result.vol; + double move = result.move; + + result = new mbts.analytics.Theos(); //all zeros + result.expiration = expiration; + result.strike = strike; + result.call = call; + result.put = put; + + result.driver = driver; + result.fwd = fwd; + result.vol = vol; + result.move = move; + //See SettledSplineableTheosFunctor.cpp ln 34 + result.cgamma = 0.000001; + result.pgamma = 0.000001; + } + } + + public class VolSurfaceCoreFunctions + { + #region Constants + public static double eps = Math.Pow(0.1, 10); + private static double _h = 0.001; + private static double _sqrt_2pi = _sqrt(2 * Math.PI); + private static double _sqrt_2 = _sqrt(2); + private readonly static int _min_points_for_fit = 5; + #endregion + + #region BSM Pricing + + public static double compute_theo(VolSurfaceEnums.VolSurfacePricingModel pricing_model, double raw_k, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + if (pricing_model == VolSurfaceEnums.VolSurfacePricingModel.BlackScholes) + return compute_bsm_theo(raw_k, is_call, vol, fwd, biz_t, cal_t, riskless_rate); + else if (pricing_model == VolSurfaceEnums.VolSurfacePricingModel.Whaley) + return compute_whaley_theo(raw_k, is_call, vol, fwd, biz_t, cal_t, riskless_rate); + else if(pricing_model == VolSurfaceEnums.VolSurfacePricingModel.Normal) + return compute_normal_theo(raw_k, is_call, vol, fwd, biz_t, cal_t, riskless_rate); + else if(pricing_model == VolSurfaceEnums.VolSurfacePricingModel.EDNormal) + return compute_ednormal_theo(raw_k, is_call, vol, fwd, biz_t, cal_t, riskless_rate); + else + return Double.NaN; + } + + public static double compute_ednormal_theo(double raw_k, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double[] theos; + if(is_call) bts.api.analytics.functions.EurodollarNormal.calls(fwd, new double[] { raw_k }, riskless_rate, new double[] { vol }, biz_t, cal_t, out theos); + else bts.api.analytics.functions.EurodollarNormal.puts(fwd, new double[] { raw_k }, riskless_rate, new double[] { vol }, biz_t, cal_t, out theos); + return theos[0]; + } + + public static double compute_normal_theo(double raw_k, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double[] theos; + if(is_call) bts.api.analytics.functions.Normal.calls(fwd, new double[] { raw_k }, riskless_rate, new double[] { vol }, biz_t, cal_t, out theos); + else bts.api.analytics.functions.Normal.puts(fwd, new double[] { raw_k }, riskless_rate, new double[] { vol }, biz_t, cal_t, out theos); + return theos[0]; + } + + public static double compute_whaley_theo(double raw_k, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double[] theos; + if (is_call) bts.api.analytics.functions.Whaley.calls(fwd, new double[] { raw_k }, riskless_rate, new double[] { vol }, biz_t, cal_t, out theos); + else bts.api.analytics.functions.Whaley.puts(fwd, new double[] { raw_k }, riskless_rate, new double[] { vol }, biz_t, cal_t, out theos); + return theos[0]; + } + + public static double compute_whaley_theo(double spot, double raw_k, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double growth = Math.Log(fwd / spot) / cal_t; + double[] theos; + if(is_call) bts.api.analytics.functions.Whaley.calls(spot, new double[] { raw_k }, growth, riskless_rate, new double[] { vol }, biz_t, cal_t, out theos); + else bts.api.analytics.functions.Whaley.puts(spot, new double[] { raw_k }, growth, riskless_rate, new double[] { vol }, biz_t, cal_t, out theos); + return theos[0]; + } + + public static double compute_bsm_theo(double raw_k, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double disc = Math.Exp(-riskless_rate * cal_t), d1, d2; + compute_bsm_d1_d2(raw_k, vol, fwd, biz_t, out d1, out d2); + return is_call ? disc * (fwd * VolSurfaceCoreFunctions.standard_normal_cdf(d1) - raw_k * VolSurfaceCoreFunctions.standard_normal_cdf(d2)) : + disc * (fwd * (VolSurfaceCoreFunctions.standard_normal_cdf(d1) - 1.0) + raw_k * (1.0 - VolSurfaceCoreFunctions.standard_normal_cdf(d2))); + } + + public static double compute_bsm_delta(double raw_k, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double disc = Math.Exp(-riskless_rate * cal_t), d1, d2; + compute_bsm_d1_d2(raw_k, vol, fwd, biz_t, out d1, out d2); + return is_call ? disc * VolSurfaceCoreFunctions.standard_normal_cdf(d1) : + disc * (VolSurfaceCoreFunctions.standard_normal_cdf(d1) - 1); + } + + public static double compute_bsm_gamma(double raw_k, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double disc = Math.Exp(-riskless_rate * cal_t), d1, d2; + compute_bsm_d1_d2(raw_k, vol, fwd, biz_t, out d1, out d2); + double pdf_d1 = VolSurfaceCoreFunctions.standard_normal_pdf(d1); + return disc * pdf_d1 / (fwd * vol * Math.Sqrt(biz_t)); + } + + public static double compute_bsm_vega(double raw_k, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double disc = Math.Exp(-riskless_rate * cal_t), vol_root_t = Math.Sqrt(biz_t) * vol, d1, d2; + compute_bsm_d1_d2(raw_k, vol, fwd, biz_t, out d1, out d2); + double pdf_d1 = VolSurfaceCoreFunctions.standard_normal_pdf(d1); + return disc * pdf_d1 * fwd * Math.Sqrt(biz_t); + } + + public static double compute_bsm_volga(double raw_k, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + /// this is dVega/dVol, vega = fwd.sqrt(biz_t).e^-rt.pdf(d1) + /// dVega/dVol = fwd.sqrt(biz_t).e^-rt.d/dvol(pdf(d1)) + /// = fwd.sqrt(biz_t).e^-rt.[dpdf(d1)/dd1 . dd1/dvol] chain rule + /// All this ends up being vega * d1 * d2 / vol + double d1, d2; + VolSurfaceCoreFunctions.compute_bsm_d1_d2(raw_k, biz_t, fwd, vol, out d1, out d2); + return compute_bsm_vega(raw_k, vol, fwd, biz_t, cal_t, riskless_rate) * d1 * d2 / vol; + } + + public static void compute_bsm_d1_d2(double raw_k, double vol, double fwd, double biz_t, + out double d1, out double d2) + { + double vol_root_t = _sqrt(biz_t) * vol; + d1 = _ln(fwd / raw_k) / vol_root_t + 0.5 * vol_root_t; + d2 = d1 - vol_root_t; + } + + public static double compute_raw_strike_from_bsm_delta(double delta, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double v_rt_t = _sqrt(biz_t) * vol; + if (is_call) + { + double d1 = standard_normal_cdf_inverse(delta * Math.Exp(riskless_rate * cal_t)); + return fwd * Math.Exp(0.5 * _sqr(v_rt_t) - v_rt_t * d1); + } + else + { + double d1 = standard_normal_cdf_inverse((delta * Math.Exp(riskless_rate * cal_t)) + 1); + return fwd * Math.Exp(0.5 * _sqr(v_rt_t) - v_rt_t * d1); + } + } + + public static double get_rawk_from_standk(double x, double fwd, double sigma, double biz_t) + { + return fwd * Math.Exp(x * sigma * _sqrt(biz_t)); + } + + public static double get_standk_from_rawk(double rawk, double fwd, double sigma_in_fractions, double biz_t) + { + return _ln(rawk / fwd) / (sigma_in_fractions * _sqrt(biz_t)); + } + + public static double compute_ednormal_delta(double raw_k, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double[] deltas; + if (is_call) bts.api.analytics.functions.EurodollarNormal.call_deltas(fwd, new double[] { raw_k }, riskless_rate, new double[] { vol }, biz_t, cal_t, out deltas); + else bts.api.analytics.functions.EurodollarNormal.put_deltas(fwd, new double[] { raw_k }, riskless_rate, new double[] { vol }, biz_t, cal_t, out deltas); + return deltas[0]; + } + + public static double compute_raw_strike_from_ednormal_delta(double delta, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + double v_rt_t = _sqrt(biz_t) * vol; + if (is_call) + { + double d1 = standard_normal_cdf_inverse(delta * Math.Exp(riskless_rate * cal_t)); + return fwd * Math.Exp(0.5 * _sqr(v_rt_t) - v_rt_t * d1); + } + else + { + double d1 = standard_normal_cdf_inverse((delta * Math.Exp(riskless_rate * cal_t)) + 1); + return fwd * Math.Exp(0.5 * _sqr(v_rt_t) - v_rt_t * d1); + } + } + + #endregion + + #region Other Pricing Utilities + + /// Given a price move at a raw strike (and the other inputs + /// needed for pricing), computes the vol move that would + /// result in given price move (everything else being constant) + public static double compute_dvol_from_dprice(double dprice, double raw_k, double biz_t, double cal_t, double riskless_rate, double fwd, double vol) + { + bool use_implied_vol = false; + if (use_implied_vol) + { + bool is_call = raw_k > fwd; + double price_now = compute_bsm_theo(raw_k, is_call, vol, fwd, biz_t, cal_t, riskless_rate), + price_after_move = price_now + dprice, + new_vol = compute_implied_strike_vol(raw_k, is_call, price_after_move, fwd, biz_t, cal_t, riskless_rate, + VolSurfaceCoreFunctions.compute_bsm_theo); + return new_vol - vol; + } + else + { + bool use_volga = false; + double bsm_vega = compute_bsm_vega(raw_k, vol, fwd, biz_t, cal_t, riskless_rate), + first_order_move = dprice / bsm_vega; + if (use_volga) + { + double bsm_volga = compute_bsm_volga(raw_k, vol, fwd, biz_t, cal_t, riskless_rate), dv1, dv2; + VolSurfaceCoreFunctions.solve_quadratic(0.5 * bsm_volga, bsm_vega, -1.0 * dprice, out dv1, out dv2); + double dv1_err = Math.Abs(dv1 - first_order_move), dv2_err = Math.Abs(dv2 - first_order_move); + return dv1_err < dv2_err ? dv1 : dv2; + } + else + { + /// using vega only + /// this will work for small vol moves because + /// dPrice/dVol = vega ~= ChangePrice/ChangeVol + /// and dPrice/dVol ~= ChangePrice/ChangeVol only for small moves + return first_order_move; + } + } + } + + /// Uses taylor series, to compute theo at a nearby driver (to a compute theo driver) + public static double compute_theo_at_nearbydriver(double driver, double theo, double delta, double gamma, double nearby_driver) + { + double driver_diff = nearby_driver - driver; + return theo + (delta * driver_diff) + (0.5 * gamma * driver_diff * driver_diff); + } + + public static void compute_bcg_diagnostic_data(Func compute_vol, VolSurfaceExpirationAuxiliaryData exp_aux_data, + out double slope, out double curvature, out double put_tail, out double call_tail, out double box) + { + const double slope_put = -1.0, slope_call = 1.0; + const double curv_put = -2.0, curv_call = 2.0; + const double tail_put1 = -2.4, tail_put2 = -1.3; + const double tail_call1 = 1.3, tail_call2 = -2.4; + double atm = compute_vol(0.0, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike); + Func slope_function = (xl, xr) => + { + const double slopecoeff = -3.0; + double vl = compute_vol(xl, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike); + double vr = compute_vol(xr, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike); + return slopecoeff*(vl - vr) / atm; + }; + slope = slope_function(slope_put, slope_call); + put_tail = slope_function(tail_put1, tail_put2); + call_tail = slope_function(tail_call1, tail_call2); + double[] curvcoeffs = new double[] {12.0/3.24,12.0,12.0,12.0/3.24}; + double[] strikes = new double[] {curv_put, slope_put, slope_call, curv_call}; + double curv = 0.0, addend = 0.0; + for(int i = 0; i < 4; i++) + { + curv += curvcoeffs[i]*compute_vol(strikes[i], VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike); + addend += curvcoeffs[i]; + } + curvature = curv/atm-addend; + box = 1000.0 * Math.Exp(-1.0 * exp_aux_data.riskless_rate * exp_aux_data.cal_t); + } + + public static double vega_factor(double norm_t, double norm_vol, double t, double vol) + { + return bts.api.analytics.functions.VegaFactor.vega_factor_shortcut(norm_t, norm_vol, t, vol); + } + /// + // public static double beta_adjust_greek (double greek_val, double beta) + // { + // return bts.api.analytics.BetaAdjust.beta_adjust_greek(greek_val, beta); + // } + + // public static IEnumerable beta_adjust_driver(IEnumerable drivers, double center_driver, double beta) + // { + // return bts.api.analytics.BetaAdjust.beta_adjust_driver(drivers, center_driver, beta); + // } + + public static VolCurveOutputDiagnosticData compute_diagnostic_data(VolSurfaceExpiration exp, + VolSurfaceSettings vs_setting, // for pricing model + Func compute_vol, + Func convert_strike_axis, + VolSurfaceExpirationAuxiliaryData aux_data) + { + VolSurfaceEnums.VolSurfacePricingModel pricing_model = VolSurfaceDataFunctions.get_pricing_model(vs_setting, exp); + /// risk reversal + Tuple rr_settings = VolSurfaceDataFunctions.get_risk_reversal_settings(vs_setting); + double /// put side + rr_put_strike = convert_strike_axis(rr_settings.Item1, rr_settings.Item2, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + rr_put_vol = compute_vol(rr_put_strike, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + rr_put_put_theo = compute_theo(pricing_model, rr_put_strike, false, rr_put_vol, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate), + rr_put_call_theo = compute_theo(pricing_model, rr_put_strike, true, rr_put_vol, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate), + /// call side + rr_call_strike = convert_strike_axis(rr_settings.Item1, rr_settings.Item3, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + rr_call_vol = compute_vol(rr_call_strike, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + rr_call_call_theo = compute_theo(pricing_model, rr_call_strike, true, rr_call_vol, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate), + rr_call_put_theo = compute_theo(pricing_model, rr_call_strike, false, rr_call_vol, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate), + /// atm + atm_vol = compute_vol(aux_data.fwd, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + live_atm_call_theo = compute_theo(pricing_model, aux_data.fwd, true, atm_vol, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate), + live_atm_put_theo = compute_theo(pricing_model, aux_data.fwd, false, atm_vol, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate); + double atm_straddle = live_atm_call_theo + live_atm_put_theo, + rr = rr_put_put_theo - rr_call_call_theo, + strangle = rr_call_call_theo + rr_put_put_theo, + call_butterfly = rr_put_call_theo - 2 * live_atm_call_theo + rr_call_call_theo, + put_butterfly = rr_put_put_theo - 2 * live_atm_put_theo + rr_call_put_theo; + double slope, curv, puttail, calltail, box; + compute_bcg_diagnostic_data(compute_vol, aux_data, out slope, out curv, out puttail, out calltail, out box); + return new VolCurveOutputDiagnosticData(atm_straddle, rr, strangle, put_butterfly, call_butterfly, + slope, curv, puttail, calltail, box); + } + + #endregion + + #region Conversion + + public static bool is_call_or_put(double strike_point, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, double fwd) + { + if (strike_axis == VolSurfaceEnums.VolCurveStrikeAxis.RawStrike) + return strike_point > fwd; + else + return strike_point >= 0; + } + + /* + * For all these calculation functions, vol pased to it is NOT in percentage terms + * */ + + public static double convert_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolCurveStrikeAxis target_axis, + double conversion_vol, double conversion_fwd, double biz_t, double cal_t, double riskless_rate) + { + return convert_axis(source_axis, source_point, target_axis, VolSurfaceEnums.VolSurfacePricingModel.BlackScholes, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + } + + public static double convert_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolCurveStrikeAxis target_axis, VolSurfaceEnums.VolSurfacePricingModel pricing_model, + double conversion_vol, double conversion_fwd, double biz_t, double cal_t, double riskless_rate) + /// Unfortunately, the pricing model needs to be passed since + /// delta is one of the axis + { + if (target_axis == source_axis) + return source_point; + else + { + if (target_axis == VolSurfaceEnums.VolCurveStrikeAxis.Delta) + return _to_delta_axis(source_axis, source_point, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + else if (target_axis == VolSurfaceEnums.VolCurveStrikeAxis.RawStrike) + return _to_raw_strike_axis(source_axis, source_point, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + else if (target_axis == VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike) + return _to_standard_strike_axis(source_axis, source_point, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + else if (target_axis == VolSurfaceEnums.VolCurveStrikeAxis.StrikeDiffFromATM) + return _to_strike_diff_axis(source_axis, source_point, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + else if (target_axis == VolSurfaceEnums.VolCurveStrikeAxis.LogSimpleMoneyness) + return _to_simple_log_moneyness(source_axis, source_point, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + return double.NaN; + } + } + + public static double convert_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolCurveStrikeAxis target_axis, + double conversion_vol, VolSurfaceExpirationAuxiliaryData aux_data) + { + return convert_axis(source_axis, VolSurfaceEnums.VolSurfacePricingModel.BlackScholes, source_point, target_axis, conversion_vol, aux_data); + } + + public static double convert_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, VolSurfaceEnums.VolSurfacePricingModel pricing_model, double source_point, VolSurfaceEnums.VolCurveStrikeAxis target_axis, + double conversion_vol, VolSurfaceExpirationAuxiliaryData aux_data) + { + return convert_axis(source_axis, source_point, target_axis, pricing_model, conversion_vol, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate); + } + + private static double _to_raw_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolSurfacePricingModel pricing_model, + double conversion_vol, double conversion_fwd, double biz_t, double cal_t, double riskless_rate) + { + if (source_axis == VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike) + return VolSurfaceCoreFunctions.get_rawk_from_standk(source_point, conversion_fwd, conversion_vol, biz_t); + else if (source_axis == VolSurfaceEnums.VolCurveStrikeAxis.StrikeDiffFromATM) + return conversion_fwd + source_point; + else if (source_axis == VolSurfaceEnums.VolCurveStrikeAxis.Delta) + { + if (pricing_model == VolSurfaceEnums.VolSurfacePricingModel.EDNormal) + return compute_raw_strike_from_ednormal_delta(source_point, source_point > 0, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + else + return compute_raw_strike_from_bsm_delta(source_point, source_point > 0, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + } + else if (source_axis == VolSurfaceEnums.VolCurveStrikeAxis.LogSimpleMoneyness) + return conversion_fwd * Math.Exp(source_point); + return Double.NaN; + } + + private static double _to_delta_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolSurfacePricingModel pricing_model, + double conversion_vol, double conversion_fwd, double biz_t, double cal_t, double riskless_rate) + { + if (source_axis == VolSurfaceEnums.VolCurveStrikeAxis.RawStrike) + { + /// This is the only real conversion code here, the rest of the + /// if's convert the source axis to raw_strike and recursivelly + /// call to this this if + if (pricing_model == VolSurfaceEnums.VolSurfacePricingModel.EDNormal) + return VolSurfaceCoreFunctions.compute_ednormal_delta(source_point, source_point > conversion_fwd, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + else + return VolSurfaceCoreFunctions.compute_bsm_delta(source_point, source_point > conversion_fwd, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + } + else + { + double raw_strike = _to_raw_strike_axis(source_axis, source_point, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + return _to_delta_axis(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, raw_strike, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + } + } + + private static double _to_standard_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolSurfacePricingModel pricing_model, + double conversion_vol, double conversion_fwd, double biz_t, double cal_t, double riskless_rate) + { + if (source_axis == VolSurfaceEnums.VolCurveStrikeAxis.RawStrike) + { + return VolSurfaceCoreFunctions.get_standk_from_rawk(source_point, conversion_fwd, conversion_vol, biz_t); + } + else + { + double raw_strike = _to_raw_strike_axis(source_axis, source_point, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + return _to_standard_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, raw_strike, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + } + } + + private static double _to_strike_diff_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolSurfacePricingModel pricing_model, + double conversion_vol, double conversion_fwd, double biz_t, double cal_t, double riskless_rate) + { + if (source_axis == VolSurfaceEnums.VolCurveStrikeAxis.RawStrike) + { + return source_point - conversion_fwd; + } + else + { + double raw_strike = _to_raw_strike_axis(source_axis, source_point, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + return _to_strike_diff_axis(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, raw_strike, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + } + } + + private static double _to_simple_log_moneyness(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolSurfacePricingModel pricing_model, + double conversion_vol, double conversion_fwd, double biz_t, double cal_t, double riskless_rate) + { + if (source_axis == VolSurfaceEnums.VolCurveStrikeAxis.RawStrike) + { + return _ln(source_point / conversion_fwd); + } + else + { + double raw_strike = _to_raw_strike_axis(source_axis, source_point, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + return _to_simple_log_moneyness(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, raw_strike, pricing_model, conversion_vol, conversion_fwd, biz_t, cal_t, riskless_rate); + } + } + + /// For non ATM actions (call/put tilt, rr and strangle) + /// 1. Converts the strike points to target_axis + /// 2. Converts price moves to vol moves + public static VolCurveMovementOperation normalize_shape_action(VolCurveMovementOperation action, + VolSurfaceExpirationAuxiliaryData aux_data, + Func convert_strike_axis, + Func compute_vol, + VolSurfaceEnums.VolCurveStrikeAxis target_axis = VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike) + { + if (action != null) + { + VolCurveMovementOperation rv = VolSurfaceUtilityFunctions.clone_proto(action); + rv.strike_vol_movement_pairs = new List>(); + if (action.strike_vol_movement_pairs != null) + foreach (Tuple move in action.strike_vol_movement_pairs) + { + double target_strike = convert_strike_axis (rv.strike_axis, move.Item1, target_axis), + vol_move = move.Item2; + if (rv.target_terms == VolSurfaceEnums.VolMovementTerms.Price) + { + double raw_k = convert_strike_axis(target_axis, target_strike, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_at_raw_k = compute_vol(raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + vol_move = compute_dvol_from_dprice(move.Item2, raw_k, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate, aux_data.fwd, vol_at_raw_k); + } + rv.strike_vol_movement_pairs.Add(Tuple.Create(target_strike, vol_move)); + } + return rv; + } + else + return action; + } + + /// Like the above, converts an atm move in price terms to vol terms + public static VolCurveMovementOperation normalize_atm_move_action(VolCurveMovementOperation action, + double atm_vol, + VolSurfaceExpirationAuxiliaryData aux_data, + double conversion_fwd) + { + if (action != null) + { + if (action.target_terms == VolSurfaceEnums.VolMovementTerms.Price) + { + VolCurveMovementOperation rv = VolSurfaceUtilityFunctions.clone_proto(action); + rv.atm_strike_vol_movement = compute_dvol_from_dprice(rv.atm_strike_vol_movement, conversion_fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate, aux_data.fwd, atm_vol); + return rv; + } + } + return action; + } + + public static double convert_vol_to_percentage(double vol) { return vol * 100.0; } + + public static double convert_vol_derv_to_percentage(double derv, uint nth_derv) + { + return derv * pow(0.01, (int)nth_derv); + } + + public static double convert_delta_to_percentage(double delta) { return delta * 100.0; } + + /// Converts control point vols to absolute vols + public static IEnumerable> convert_cpvol_to_absvol(IEnumerable> sorted_controlpoint_list, + double final_atmvol, + VolSurfaceEnums.VolCurveVolAxis vol_axis) + { + if (vol_axis == VolSurfaceEnums.VolCurveVolAxis.Incremental) + { + List> rv = new List>(); + foreach (Tuple t in sorted_controlpoint_list) + rv.Add(Tuple.Create(t.Item1, (rv.Count == 0 ? final_atmvol : rv.Last().Item2) + t.Item2)); + return rv; + } + else + return sorted_controlpoint_list.Select(t => Tuple.Create(t.Item1, vol_axis == VolSurfaceEnums.VolCurveVolAxis.ATMAddin ? t.Item2 + final_atmvol : t.Item2 * final_atmvol)); + } + + public double convert_measure(double val, double change, VolSurfaceEnums.GeneralChangeMeasure measure) + { + if (measure == VolSurfaceEnums.GeneralChangeMeasure.Absolute) + return val + change; + else if (measure == VolSurfaceEnums.GeneralChangeMeasure.Percentage) + return convert_measure (val, val * change / 100.0, VolSurfaceEnums.GeneralChangeMeasure.Absolute); + else if (measure == VolSurfaceEnums.GeneralChangeMeasure.Ratio) + return convert_measure(val, val * change, VolSurfaceEnums.GeneralChangeMeasure.Absolute); + else + { + Log.assert (false, String.Format ("Unidentified measure {0}", measure)); + return Double.NaN; + } + } + + /// For a volsurface output, finds the vol or price + /// (depending on the 4th arg) at the specified + /// control points. Additionally also computes the + /// controlpoint and the data at the ATM + public static void compute_controlpoint_values(VolSurfaceOutput vs_output, + IEnumerable control_points, + VolSurfaceEnums.VolCurveStrikeAxis control_point_axis, + VolSurfaceEnums.VolSurfaceVisualizationParamater data_type, + out IDictionary> controlpoint_data, + out IDictionary> atm_data) + { + controlpoint_data = new Dictionary>(); + atm_data = new Dictionary>(); + + foreach (KeyValuePair kv in vs_output.exp_output_map) + { + VolSurfaceExpiration vs_exp = kv.Key; + VolCurveOutput vc_output = kv.Value; + VolSurfaceEnums.VolSurfacePricingModel pricing_model = VolSurfaceDataFunctions.get_pricing_model (vs_output.volsurface_input.surface_settings, vs_exp); + IDictionary cp_map = new Dictionary(); + controlpoint_data[vs_exp] = cp_map; + foreach (double cp in control_points) + { + double vol = vc_output.compute_vol(cp, control_point_axis), out_val = vol; + if (data_type == VolSurfaceEnums.VolSurfaceVisualizationParamater.Price) + { + double raw_k = vc_output.convert_strike_axis(control_point_axis, cp, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + bool is_call = is_call_or_put(cp, control_point_axis, vc_output.conversion_fwd); + out_val = compute_theo(pricing_model, raw_k, is_call, vol, vc_output.aux_data.fwd, vc_output.aux_data.biz_t, vc_output.aux_data.cal_t, vc_output.aux_data.riskless_rate); + } + cp_map[cp] = out_val; + } + /// atm controlpoint and atm out val + double atm_cp = vc_output.convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, 0, control_point_axis), + atm_out_val = vc_output.atm_vol; + if (data_type == VolSurfaceEnums.VolSurfaceVisualizationParamater.Price) + atm_out_val = compute_theo(pricing_model, vc_output.conversion_fwd, true, vc_output.atm_vol, vc_output.aux_data.fwd, vc_output.aux_data.biz_t, vc_output.aux_data.cal_t, vc_output.aux_data.riskless_rate); + atm_data[vs_exp] = Tuple.Create(atm_cp, atm_out_val); + } + } + + #endregion + + #region Misc Math + + public static void solve_quadratic(double a, double b, double c, out double x1, out double x2) + { + double r = _sqrt(_sqr(b) - (4 * a * c)); + x1 = (-b + r) / (2 * a); + x2 = (-b - r) / (2 * a); + } + + /// Factorial + public static uint fact(uint n) { return n == 0 ? 1 : n * fact(n - 1); } + + /// Returns the result of differentiating ax^n p times, + /// where n and p > 0 + public static double differentiate_axn_ptimes(double a, double x, uint n, uint p) + { + return p > n ? 0.0 : a * (fact(n) / fact(n - p)) * Math.Pow(x, n - p); + } + + /// Returns a line (y=ax+b) that passes through + /// coords and its slope is the 2nd arg + public static void get_line(Tuple coords, double slope, + out double a, out double b) + { + a = slope; + b = coords.Item2 - a * coords.Item1; + } + + /// Returns a line (y=ax+b) that passes through p1 and p2 + public static void get_line(Tuple p1, Tuple p2, + out double a, out double b) + { + get_line(p1, (p2.Item2 - p1.Item2) / (p2.Item1 - p1.Item1), out a, out b); + } + + /// Given a line that passes through p1, with a given slope + /// finds the y at point x + public static double get_line_y(Tuple p1, double slope, double x) + { + double a, b; + get_line(p1, slope, out a, out b); + return a * x + b; + } + + /// Draws a line through x1, y1 and x2, y2 and computes + /// the y for x + public static double lin_interp_exterp(double x1, double y1, double x2, double y2, double x) + { + double a, b; + get_line(Tuple.Create(x1, y1), Tuple.Create(x2, y2), out a, out b); + return a * x + b; + } + + /// Solves Ax=b. Returns false and sets x to Null if + /// the system can not be solved + public static bool solve_axb(double[,] A, double[] b, out double[] x) + { + int A_size = A.GetLength(0); + Log.assert(A.GetLength(0) == A.GetLength(1), "Matrix should be square"); + Log.assert(b.Length == A_size); + double[,] A_aug = new double[A_size, A_size + 1]; + for (int i = 0; i < A_size; i++) + for (int j = 0; j < A_size; j++) + A_aug[i, j] = A[i, j]; + for (int i = 0; i < A_size; i++) + A_aug[i, A_size] = b[i]; + bool rv = solve_axb_augmented(A_aug); + if (rv) + { + x = new double[A_size]; + for (int i = 0; i < A_size; i++) + x[i] = A_aug[i, A_size]; + return true; + } + else + { + x = null; + return false; + } + } + + /// The system of linear equations as an augmented matrix[row, col] where (rows + 1 == cols). + /// It will contain the solution in "row canonical form" if the function returns "true" + public static bool solve_axb_augmented(double[,] M) + { + // input checks + int row_count = M.GetUpperBound(0) + 1; + if (M == null || M.Length != row_count * (row_count + 1)) + throw new ArgumentException("The algorithm must be provided with a (n x n+1) matrix."); + if (row_count < 1) + throw new ArgumentException("The matrix must at least have one row."); + + // pivoting + for (int col = 0; col + 1 < row_count; col++) if (M[col, col] == 0) + // check for zero coefficients + { + // find non-zero coefficient + int swap_row = col + 1; + for (; swap_row < row_count; swap_row++) if (M[swap_row, col] != 0) break; + + if (M[swap_row, col] != 0) // found a non-zero coefficient? + { + // yes, then swap it with the above + double[] tmp = new double[row_count + 1]; + for (int i = 0; i < row_count + 1; i++) + { tmp[i] = M[swap_row, i]; M[swap_row, i] = M[col, i]; M[col, i] = tmp[i]; } + } + else return false; // no, then the matrix has no unique solution + } + + // elimination + for (int source_row = 0; source_row + 1 < row_count; source_row++) + { + for (int destRow = source_row + 1; destRow < row_count; destRow++) + { + double df = M[source_row, source_row]; + double sf = M[destRow, source_row]; + for (int i = 0; i < row_count + 1; i++) + M[destRow, i] = M[destRow, i] * df - M[source_row, i] * sf; + } + } + + // back-insertion + for (int row = row_count - 1; row >= 0; row--) + { + double f = M[row, row]; + if (f == 0) return false; + + for (int i = 0; i < row_count + 1; i++) M[row, i] /= f; + for (int destRow = 0; destRow < row; destRow++) + { M[destRow, row_count] -= M[destRow, row] * M[row, row_count]; M[destRow, row] = 0; } + } + return true; + } + + /// Bends a function from the point x0 such + /// that it asymptotes the line mx+c. + /// The decay dictates how quickly the main function + /// approaches the asymptote. + /// If the slope of f at x0 is close to + /// m, the decay doesnt matter much. It plays more + /// of a role when df(x0) is very different from m. + /// + /// The return function is of the form (g(x))e^-c(x-x0) + mx+c + /// such that it matches f and df at x=x0 and approaches mx + c + /// as x >> x0 + public static Func get_oblique_asymptote_func(double x0, Func get_f, uint order, + double decay, double m, double c) + { + /// hard coded to use 2 orders at the max + double g = get_f(0) - m * x0 - c, + dg = order >= 1 ? get_f(1) + decay * g - m : 0, + d2g = order >= 2 ? get_f(2) + 2 * decay * dg - _sqr(decay) * g : 0.0; + return (x) => + { + double asymp = m * x + c; + return (g + dg * (x - x0) + d2g * _sqr(x - x0) * 0.5) * Math.Exp(-1 * Math.Abs(decay) * Math.Abs(x - x0)) + asymp; + }; + } + + /// Returns the coefficent for a polynomial that EXACTLY + /// fits the argument points + /// - number of coefficent's = number of points + /// - mth member of the returned IEnumerable is the + /// coefficent of the mth degree (x^m) term, + /// so [0] is the constant term, [1] is the + /// x^1 term and so on + public static IEnumerable get_exactfit_polynomial_coeffs(IEnumerable> points) + { + if (points == null || points.Count() == 0) + return Enumerable.Empty(); + else + { + int n_coeffs = points.Count(); + double[,] A = new double[n_coeffs, n_coeffs]; + double[] b = new double[n_coeffs]; + for (int iy = 0; iy < n_coeffs; iy++) + { + double x = points.ElementAt(iy).Item1, y = points.ElementAt(iy).Item2; + b[iy] = y; + for (int ix = 0; ix < n_coeffs; ix++) + { + double elem = Math.Pow(x, n_coeffs - 1 - ix); + A[iy, ix] = elem; + } + } + double[] coeffs; + VolSurfaceCoreFunctions.solve_axb(A, b, out coeffs); + return coeffs == null ? new double[] { } : coeffs.Reverse(); + } + } + + public static double compute_polynomial_df(double[] coefficients, double x, uint nth_derv = 0) + { + double rv = 0; + for (int deg = 0; deg < coefficients.Length; deg++) + rv += VolSurfaceCoreFunctions.differentiate_axn_ptimes(coefficients[deg], x, Convert.ToUInt32(deg), nth_derv); + return rv; + } + + public static IEnumerable get_constrained_least_squares_polynomial(IEnumerable> weighted_points, + IEnumerable> fixed_points, + uint polynomial_order) + { + ///wtdPolyRegtwEqualityConstraints expects the fixed points not be included + ///in the weighted_points + HashSet fixed_x = new HashSet(fixed_points.Select(fp => fp.Item1)); + List> weighted_points_cleaned = new List>(weighted_points); + weighted_points_cleaned.RemoveAll(t => fixed_x.Contains(t.Item1)); + weighted_points.OrderBy(t => t.Item1); + fixed_points.OrderBy(t => t.Item1); + double[] x_points = weighted_points_cleaned.Select(t => t.Item1).ToArray(), + y_points = weighted_points_cleaned.Select(t => t.Item2).ToArray(), + weights = weighted_points_cleaned.Select(t => t.Item3).ToArray(), + x_fixed_points = fixed_points.Select(t => t.Item1).ToArray(), + y_fixed_points = fixed_points.Select(t => t.Item2).ToArray(); + double[] coeffs = Enumerable.Repeat(0d, (int)polynomial_order + 1).ToArray(); + // TODO + // bts_calcsCLR.wtdPolyRegtwEqualityConstraints(weights, x_points, y_points, x_fixed_points, y_fixed_points, coeffs, coeffs.Length, x_points.Length, x_fixed_points.Length); + return coeffs; + } + + /// Given 2 points that the quadratic passes through and the + /// coeff of x^2 (a), returns b and c + public static IEnumerable get_quadratic_with_given_curvature(Tuple p1, Tuple p2, double a) + { + double x0 = p1.Item1, y0 = p1.Item2, + x1 = p2.Item1, y1 = p2.Item2, + a0 = a * x0 * x0, a1 = a * x1 * x1, + b = (y1 + a0 - y0 - a1) / (x1 - x0), + c = y0 - a0 - (b * x0); + return new double[] { c, b, a }; + } + + #endregion + + #region Statistical Functions + + + public static double standard_normal_pdf(double x) { return MathNet.Numerics.Distributions.Normal.PDF(0.0, 1.0, x); } + + public static double standard_normal_cdf(double z) { return standard_normal_cdf_bcg(z); } + + private static double a1 = 0.254829592, + a2 = -0.284496736, + a3 = 1.421413741, + a4 = -1.453152027, + a5 = 1.061405429, + p = 0.3275911; + public static double standard_normal_cdf_abramowitz_stegun(double x) + { + // Save the sign of x + int sign = 1; + if (x < 0) + sign = -1; + x = Math.Abs(x) / _sqrt_2; + + // A&S formula 7.1.26 + double t = 1.0 / (1.0 + p * x); + double y = 1.0 - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * Math.Exp(-x * x); + + return 0.5 * (1.0 + sign * y); + } + + private readonly static double MAXSTD = 37.5193793471444; + private readonly static double MinNormCDF = 2.2250738585152E-308; + public static double standard_normal_cdf_bcg(double x) + { + double XAbs = Math.Abs(x); + double Cumnorm = MinNormCDF; + if (XAbs < MAXSTD) + { + double Exponential = Math.Exp(-0.5 * XAbs * XAbs); + if (XAbs < 7.07106781186547) + { + double build = 3.52624965998911E-02 * XAbs + 0.700383064443688; + build = build * XAbs + 6.37396220353165; + build = build * XAbs + 33.912866078383; + build = build * XAbs + 112.079291497871; + build = build * XAbs + 221.213596169931; + build = build * XAbs + 220.206867912376; + Cumnorm = Exponential * build; + build = 8.83883476483184E-02 * XAbs + 1.75566716318264; + build = build * XAbs + 16.064177579207; + build = build * XAbs + 86.7807322029461; + build = build * XAbs + 296.564248779674; + build = build * XAbs + 637.333633378831; + build = build * XAbs + 793.826512519948; + build = build * XAbs + 440.413735824752; + Cumnorm = Cumnorm / build; + } + else + { + double build = XAbs + 0.65; + build = XAbs + 4.0 / build; + build = XAbs + 3.0 / build; + build = XAbs + 2.0 / build; + build = XAbs + 1.0 / build; + Cumnorm = Exponential / (build * 2.506628274631); + } + } + if (x > 0) Cumnorm = 1.0 - Cumnorm; + return Cumnorm; + } + + + private readonly static double RT2PI = _sqrt(4.0 * Math.Acos(0.0)); + + private readonly static double SPLIT = 7.07106781186547; + + private readonly static double N0 = 220.206867912376; + private readonly static double N1 = 221.213596169931; + private readonly static double N2 = 112.079291497871; + private readonly static double N3 = 33.912866078383; + private readonly static double N4 = 6.37396220353165; + private readonly static double N5 = 0.700383064443688; + private readonly static double N6 = 3.52624965998911e-02; + private readonly static double M0 = 440.413735824752; + private readonly static double M1 = 793.826512519948; + private readonly static double M2 = 637.333633378831; + private readonly static double M3 = 296.564248779674; + private readonly static double M4 = 86.7807322029461; + private readonly static double M5 = 16.064177579207; + private readonly static double M6 = 1.75566716318264; + private readonly static double M7 = 8.83883476483184e-02; + + public static double standard_normal_cdf_re_hart(double x) + { + + double z = Math.Abs(x); + double c = 0.0; + + if (z <= 37.0) + { + double e = Math.Exp(-z * z / 2.0); + if (z < SPLIT) + { + double n = (((((N6 * z + N5) * z + N4) * z + N3) * z + N2) * z + N1) * z + N0; + double d = ((((((M7 * z + M6) * z + M5) * z + M4) * z + M3) * z + M2) * z + M1) * z + M0; + c = e * n / d; + } + else + { + double f = z + 1.0 / (z + 2.0 / (z + 3.0 / (z + 4.0 / (z + 13.0 / 20.0)))); + c = e / (RT2PI * f); + } + } + return x <= 0.0 ? c : 1 - c; + } + + public static double standard_normal_cdf_inverse(double p) { return MathNet.Numerics.Distributions.Normal.InvCDF(0.0, 1.0, p); } + + #endregion + + #region Numerical Differentiation + public enum DerivativeType + { + BackwardDifference = 0, //uses function values for x <= a, where dnf(a) is calculated + CenteredDifference, //uses function values on either side of a, where dnf(a) is calculated + ForwardDifference //uses function values for x >= a, where dnf(a) is calculated + } + + public static double compute_df(Func get_f, double x, DerivativeType derv_type, uint nth_derv, double h = double.NaN) + { + if (nth_derv == 0) + return get_f(x); + else if (nth_derv == 1) + return _compute_df(get_f, x, derv_type, h); + else if (nth_derv == 2) + return _compute_d2f(get_f, x, derv_type, h); + else if (nth_derv == 3) + return _compute_d3f(get_f, x, derv_type, h); + else + { + Log.assert(false, "Derivatives of order higher than 3 not supported"); + return double.NaN; + } + } + + private static double _compute_df(Func f, double x, DerivativeType derv_type, double h = double.NaN) + { + h = Double.IsNaN(h) ? _h : h; + if (derv_type == DerivativeType.BackwardDifference) + return (f(x) - f(x - h)) / h; + else if (derv_type == DerivativeType.CenteredDifference) + return (f(x + h) - f(x - h)) / (2 * h); + else if (derv_type == DerivativeType.ForwardDifference) + return (f(x + h) - f(x)) / h; + else + { + Log.assert(false, String.Format("Incorrect DerivativeType {0}", derv_type.ToString())); + return double.NaN; + } + } + + private static double _compute_d2f(Func f, double x, DerivativeType derv_type, double h = double.NaN) + { + h = Double.IsNaN(h) ? _h : h; + if (derv_type == DerivativeType.BackwardDifference) + return (f(x) - 2 * f(x - h) + f(x - 2 * h)) / _sqr(h); + else if (derv_type == DerivativeType.CenteredDifference) + return (f(x + h) - 2 * f(x) + f(x - h)) / _sqr(h); + else if (derv_type == DerivativeType.ForwardDifference) + return (f(x + 2 * h) - 2 * f(x = h) + f(x)) / _sqr(h); + else + { + Log.assert(false, String.Format("Incorrect DerivativeType {0}", derv_type.ToString())); + return double.NaN; + } + } + + private static double _compute_d3f(Func f, double x, DerivativeType derv_type, double h = double.NaN) + { + h = Double.IsNaN(h) ? _h : h; + if (derv_type == DerivativeType.BackwardDifference) + return (f(x) - 3 * f(x - h) + 3 * f(x - 2 * h) - f(x - 3 * h)) / _cube(h); + else if (derv_type == DerivativeType.CenteredDifference) + return (f(x + 2 * h) - 3 * f(x + h) + 3 * f(x) - f(x - h)) / _cube(h); + else if (derv_type == DerivativeType.ForwardDifference) + return (f(x + 3 * h) - 3 * f(x + 2 * h) + 3 * f(x + h) - f(x)) / _cube(h); + else + { + Log.assert(false, String.Format("Incorrect DerivativeType {0}", derv_type.ToString())); + return double.NaN; + } + } + #endregion + + #region Root Finding + + public static double find_root_bisection(Func f, double x_left, double x_right, uint max_iters, double x_tolerance, double f_0_tolerance, + out uint out_iters, out double out_error) + { + x_tolerance = Math.Abs(x_tolerance); f_0_tolerance = Math.Abs(f_0_tolerance); + out_iters = 0; out_error = double.MaxValue; + double f_left = f(x_left), f_right = f(x_right); + if (Double.IsNaN(f_left) || Double.IsNaN(f_right) || _same_sign(f_left, f_right) || x_left > x_right) + { + //mbts.Logger.log(bts.log.Level.Warn, bts.log.Subsystem.gen, String.Format("Incorrect starting point x1={0} f(x1)={1}; x2={2} f(x2)={3}", x_left, f_left, x_right, f_right)); + return Double.NaN; + } + else if (Math.Abs(f_left) <= f_0_tolerance) + return x_left; + else if (Math.Abs(f_right) <= f_0_tolerance) + return x_right; + while (true) + { + double x_mid = (x_left + x_right) / 2.0, f_mid = f(x_mid); + if (x_right - x_left <= x_tolerance || Math.Abs(f(x_mid)) <= f_0_tolerance || out_iters++ >= max_iters) + { + out_error = x_right - x_left; + return x_mid; + } + x_left = _same_sign(f_left, f_mid) ? x_mid : x_left; + x_right = _same_sign(f_right, f_mid) ? x_mid : x_right; + f_left = f(x_left); f_right = f(x_right); + } + } + + /// This is not tested + public static double find_root_newton(Func f, Func df, double guess, uint max_iters, double max_tolerance, + out int out_iters, out double out_error) + { + Log.assert(false); + max_tolerance = Math.Abs(max_tolerance); + out_iters = 0; out_error = double.MaxValue; + double old_x, new_x = guess; + for (out_iters = 0; out_iters < max_iters && out_error > max_tolerance; out_iters++) + { + old_x = new_x; + double fx = f(old_x), dfx = df(old_x); + double absfprimex = Math.Abs(dfx); + if (absfprimex > 1.0 || Math.Abs(fx) < double.MaxValue * absfprimex) + { + // The division will not overflow + new_x = old_x - fx / dfx; + out_error = Math.Abs(new_x - old_x); + } + else + { + new_x = old_x; + out_error = double.MaxValue; + break; + } + } + return new_x; + } + + /// This is not tested + public static double find_root_brent(Func f, double left_x, double right_x, uint max_iters, double tolerance, + out int out_iters_used, out double out_error) + { + Log.assert(false); + tolerance = Math.Abs(tolerance); + out_error = double.MaxValue; + // Implementation and notation based on Chapter 4 in + // "Algorithms for Minimization without Derivatives" + // by Richard Brent. + + double c, d, e, fa, fb, fc, tol, m, p, q, r, s; + + // set up aliases to match Brent's notation + double a = left_x; double b = right_x; double t = tolerance; + out_iters_used = 0; + + fa = f(a); + fb = f(b); + Log.assert(fa * fb < 0.0, "Initial guess on the left and rigth points should have opposite signs"); + label_int: + c = a; fc = fa; d = e = b - a; + label_ext: + if (Math.Abs(fc) < Math.Abs(fb)) + { + a = b; b = c; c = a; + fa = fb; fb = fc; fc = fa; + } + out_iters_used++; + tol = 2.0 * t * Math.Abs(b) + t; + out_error = m = 0.5 * (c - b); + if (Math.Abs(m) > tol && fb != 0.0) // exact comparison with 0 is OK here + { + // See if bisection is forced + if (Math.Abs(e) < tol || Math.Abs(fa) <= Math.Abs(fb)) + { + d = e = m; + } + else + { + s = fb / fa; + if (a == c) + { + // linear interpolation + p = 2.0 * m * s; q = 1.0 - s; + } + else + { + // Inverse quadratic interpolation + q = fa / fc; r = fb / fc; + p = s * (2.0 * m * q * (q - r) - (b - a) * (r - 1.0)); + q = (q - 1.0) * (r - 1.0) * (s - 1.0); + } + if (p > 0.0) + q = -q; + else + p = -p; + s = e; e = d; + if (2.0 * p < 3.0 * m * q - Math.Abs(tol * q) && p < Math.Abs(0.5 * s * q)) + d = p / q; + else + d = e = m; + } + a = b; fa = fb; + if (Math.Abs(d) > tol) + b += d; + else if (m > 0.0) + b += tol; + else + b -= tol; + if (out_iters_used == max_iters) + return b; + + fb = f(b); + if ((fb > 0.0 && fc > 0.0) || (fb <= 0.0 && fc <= 0.0)) + goto label_int; + else + goto label_ext; + } + else + return b; + } + + #endregion + + #region Vol Interp + /// Interp or exterps vol across time by lin interp/exterping + /// t*vol^2 across t + public static double interp_exterp_vols_across_time(double t1, double vol1, double t2, double vol2, double t) + { + double vol_sqr_t_1 = Math.Pow(vol1, 2.0) * t1, + vol_sqr_t_2 = Math.Pow(vol2, 2.0) * t2; + double vsqr_t = lin_interp_exterp(t1, vol_sqr_t_1, t2, vol_sqr_t_2, t); + return Math.Pow(vsqr_t / t, 0.5); + } + #endregion + + #region Vol Response + + public static double compute_twowayslope_reponse(double current, double reference, double market_down_slope, double market_up_slope, double speed) + { + speed = Double.IsNaN(speed) ? 1.5 : speed; + double dx = (current - reference); + double res = market_up_slope + (market_down_slope - market_up_slope) * (0.5 + Math.Atan(-speed * dx) / Math.PI); + return res * -dx; + } + + #endregion + + #region Implied Vols + /// 1. Filters the market data according to the settings + /// 2. Divides the market data up in puts and calls based on the fwd + public static void get_filtered_bbo_mid(VolSurfaceMarketFitSettings settings, double fwd, + IDictionary> strike_bbo_map, + VolSurfaceEnums.MarketSide market_side, + out IDictionary put_prices, + out IDictionary call_prices) + { + put_prices = new Dictionary(); call_prices = new Dictionary(); + Func extract_bbo = (bbo) => + { + if (market_side == VolSurfaceEnums.MarketSide.Mid) + { + if (settings.ignore_one_sided_markets && !bbo.is_two_sided()) + return Double.NaN; + if ((bbo.bid_size != 0 && bbo.bid_size < settings.minimum_top_book_size) || (bbo.ask_size != 0 && bbo.ask_size < settings.minimum_top_book_size)) + return Double.NaN; + else + return bbo.get_mid_price(); + } + else + return market_side == VolSurfaceEnums.MarketSide.Bid ? bbo.bid_price : bbo.ask_price; + }; + foreach (KeyValuePair> p in strike_bbo_map) + { + double raw_k = p.Key; + if (raw_k < fwd) + { + double put_mid = extract_bbo(p.Value.Item2); + if (!Double.IsNaN(put_mid)) + put_prices.Add(p.Key, put_mid); + } + else + { + double call_mid = extract_bbo(p.Value.Item1); + if (!Double.IsNaN(call_mid)) + call_prices.Add(p.Key, call_mid); + } + } + } + + public static double compute_implied_strike_vol(double raw_k, bool is_call, double price, double fwd, double biz_t, double cal_t, double riskless_rate, + Func pricing_func) + { + double x_tol = 1e-6, f_0_tol = 1e-6, bracket_min = 1e-6, bracket_max = 5.0; + uint iters; double tol; + Func bsm = (vol) => { return pricing_func(raw_k, is_call, vol, fwd, biz_t, cal_t, riskless_rate) - price; }; + double implied_vol = VolSurfaceCoreFunctions.find_root_bisection(bsm, bracket_min, bracket_max, UInt32.MaxValue, x_tol, f_0_tol, out iters, out tol); + return implied_vol; + } + + /// Computes the implied vol for one exp. The whole surface data + /// is passed because of mappings + public static VolCurveMarketImpliedVolData compute_implied_vols(VolSurfaceInput vs_input, VolSurfaceExpiration vs_exp, + IDictionary aux_data_map, + Func>> get_bbo_func, + VolSurfaceEnums.MarketSide market_side, + bool ignore_market_implied_vol_source_settings, + out VolSurfaceExpiration md_exp) + { + md_exp = vs_exp; + if (vs_input != null && aux_data_map != null && vs_exp != null) + { + Func get_std_vol = (p) => p != null && p.core_parameters != null ? p.core_parameters.standard_vol : double.NaN; /// just a wrapper around to get std vol while checking nulls + /// orig + VolSurfaceExpirationAuxiliaryData orig_exp_aux_data = aux_data_map.TryGetValue(vs_exp, out orig_exp_aux_data) ? orig_exp_aux_data : null; + /// md map + md_exp = ignore_market_implied_vol_source_settings ? vs_exp : VolSurfaceUtilityFunctions.find_implied_vol_source_expiration(vs_exp, vs_input); + if (md_exp != null) + { + VolCurveParameters exp_params = VolSurfaceDataFunctions.get_params_resolve_for_master_slave (vs_input, vs_exp), + md_exp_params = VolSurfaceDataFunctions.get_params_resolve_for_master_slave(vs_input, md_exp); + bool use_std_vol = vs_input.surface_settings.core_settings.strike_conversion_vol == VolSurfaceEnums.StrikeConversionVol.StandardVol; + VolSurfaceExpirationAuxiliaryData md_exp_aux_data = aux_data_map.TryGetValue(md_exp, out md_exp_aux_data) ? md_exp_aux_data : null; + IDictionary> md_exp_bbo_map = get_bbo_func(md_exp); + if (md_exp_bbo_map != null && md_exp_aux_data != null && orig_exp_aux_data != null) + { + IDictionary put_prices, call_prices; + VolSurfaceCoreFunctions.get_filtered_bbo_mid(vs_input.surface_settings.core_settings.market_fit_settings, md_exp_aux_data.fwd, md_exp_bbo_map, market_side, + out put_prices, out call_prices); + VolSurfaceEnums.VolSurfacePricingModel source_pricing_model = VolSurfaceDataFunctions.get_pricing_model(vs_input.surface_settings, md_exp); + IDictionary put_vols, call_vols; double implied_atm_vol; + VolSurfaceCoreFunctions.compute_implied_vols(source_pricing_model, md_exp_aux_data, put_prices, call_prices, out put_vols, out call_vols, out implied_atm_vol); + VolCurveMarketImpliedVolData exp_impl_vol_map = new VolCurveMarketImpliedVolData(md_exp_aux_data, source_pricing_model, put_vols, call_vols, md_exp_aux_data.fwd, implied_atm_vol, use_std_vol ? get_std_vol (md_exp_params) : implied_atm_vol); + exp_impl_vol_map = VolSurfaceCoreFunctions.adjust_implied_vols_for_symbols(exp_impl_vol_map, orig_exp_aux_data, use_std_vol ? get_std_vol (exp_params) : implied_atm_vol); + return exp_impl_vol_map; + } + } + } + return null; + } + + /// Given the pricing inputs computes the vol for a series of points + public static void compute_implied_vols(VolSurfaceEnums.VolSurfacePricingModel pricing_model, + VolSurfaceExpirationAuxiliaryData aux_data, + IDictionary put_prices, IDictionary call_prices, + out IDictionary put_vols, out IDictionary call_vols, out double implied_atm_vol) + { + if (pricing_model == VolSurfaceEnums.VolSurfacePricingModel.Whaley) + { + put_vols = put_prices.ToDictionary(kv => kv.Key, kv => compute_implied_strike_vol(kv.Key, false, kv.Value, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate, + VolSurfaceCoreFunctions.compute_whaley_theo)); + call_vols = call_prices.ToDictionary(kv => kv.Key, kv => compute_implied_strike_vol(kv.Key, true, kv.Value, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate, + VolSurfaceCoreFunctions.compute_whaley_theo)); + } + else if(pricing_model == VolSurfaceEnums.VolSurfacePricingModel.Normal) + { + put_vols = put_prices.ToDictionary(kv => kv.Key, kv => compute_implied_strike_vol(kv.Key, false, kv.Value, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate, + VolSurfaceCoreFunctions.compute_normal_theo)); + call_vols = call_prices.ToDictionary(kv => kv.Key, kv => compute_implied_strike_vol(kv.Key, true, kv.Value, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate, + VolSurfaceCoreFunctions.compute_normal_theo)); + } + else if(pricing_model == VolSurfaceEnums.VolSurfacePricingModel.EDNormal) + { + put_vols = put_prices.ToDictionary(kv => kv.Key, kv => compute_implied_strike_vol(kv.Key, false, kv.Value, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate, + VolSurfaceCoreFunctions.compute_ednormal_theo)); + call_vols = call_prices.ToDictionary(kv => kv.Key, kv => compute_implied_strike_vol(kv.Key, true, kv.Value, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate, + VolSurfaceCoreFunctions.compute_ednormal_theo)); + } + else + { + put_vols = put_prices.ToDictionary(kv => kv.Key, kv => compute_implied_strike_vol(kv.Key, false, kv.Value, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate, + VolSurfaceCoreFunctions.compute_bsm_theo)); + call_vols = call_prices.ToDictionary(kv => kv.Key, kv => compute_implied_strike_vol(kv.Key, true, kv.Value, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate, + VolSurfaceCoreFunctions.compute_bsm_theo)); + } + implied_atm_vol = interpolate_implied_atm_vol(put_vols, call_vols, aux_data.fwd, true); + } + + /// Given put and call implied vols for raw_k's, finds the atm vol. + /// Based on the last arg it either lin interps put and call point (nearest to atm) + /// or draws a regression using n put and n call points + public static double interpolate_implied_atm_vol(IDictionary put_vols, IDictionary call_vols, double fwd, bool is_regression) + { + if (is_regression) + { + int n_put_points = 2, n_call_points = 2; + uint order = 2; + if (put_vols.Count > n_put_points && call_vols.Count > n_call_points) + { + IEnumerable> last_put_vols = put_vols.OrderBy(kv => kv.Key).Skip(put_vols.Count - n_put_points).Select(kv => Tuple.Create(kv.Key, kv.Value)), + first_call_vols = call_vols.OrderBy(kv => kv.Key).Take(n_call_points).Select(kv => Tuple.Create(kv.Key, kv.Value)); + IEnumerable> all_weighted_points = Enumerable.Concat(last_put_vols, first_call_vols).Select(i => Tuple.Create(i.Item1, i.Item2, 1.0)); + IEnumerable coeffs = VolSurfaceCoreFunctions.get_constrained_least_squares_polynomial(all_weighted_points, Enumerable.Empty>(), order); + return VolSurfaceCoreFunctions.compute_polynomial_df(coeffs.ToArray(), fwd, 0); + } + else + return Double.NaN; + } + else + { + Tuple last_put_vol = put_vols.OrderBy(kv => kv.Key).Select(kv => Tuple.Create(kv.Key, kv.Value)).Last(), + first_call_vol = call_vols.OrderBy(kv => kv.Key).Select(kv => Tuple.Create(kv.Key, kv.Value)).First(); + return VolSurfaceCoreFunctions.lin_interp_exterp(last_put_vol.Item1, last_put_vol.Item2, first_call_vol.Item1, first_call_vol.Item2, fwd); + } + } + + /// Given implied vols for discrete strikes, interpolates + /// the vol for the arg strike + public static double find_raw_k_vol(VolCurveMarketImpliedVolData implied_vol_data, double raw_k) + { + if (implied_vol_data != null && implied_vol_data.aux_data != null) + { + VolSurfaceExpirationAuxiliaryData aux_data = implied_vol_data.aux_data; + return raw_k == implied_vol_data.atm_strike ? implied_vol_data.atm_vol : _interpolate_strike(raw_k < implied_vol_data.atm_strike ? implied_vol_data.put_rawk_vols : implied_vol_data.call_rawk_vols, raw_k); + } + else + return double.NaN; + } + + /// Just like find_raw_k_vol(above), finds the implied vol for + /// a std k. If its not there, interpolates it + public static double find_std_k_vol(VolCurveMarketImpliedVolData implied_vol_data, double std_k) + { + if (implied_vol_data != null && implied_vol_data.aux_data != null) + return std_k == 0.0 ? implied_vol_data.atm_vol : _interpolate_strike(implied_vol_data.stdk_vols, std_k); + else + return double.NaN; + } + + /// Finds a regression polynomial through the implied vol points, using + /// a weight function to assign weights to strikes. + public static IEnumerable get_implied_vol_regression_curve(VolCurveMarketImpliedVolData implied_vol_data, uint regression_order, + Func weight_func = null) + { + if (weight_func == null) + weight_func = (k) => 1; + List> regression_xy_points = new List>(implied_vol_data.stdk_vols.Select(kv => Tuple.Create(kv.Key, kv.Value, weight_func(kv.Key)))); + regression_xy_points.Add(Tuple.Create(0.0, implied_vol_data.atm_vol, 1.0)); + /// always make it pass through the ATM point + IEnumerable> fixed_points = Enumerable.Range(1, 1).Select(i => Tuple.Create(0.0, implied_vol_data.atm_vol)); + IEnumerable regression_coeffs = VolSurfaceCoreFunctions.get_constrained_least_squares_polynomial(regression_xy_points, fixed_points, regression_order); + return regression_coeffs; + } + + /// When driving off of another symbol's implied vols, this + /// makes adjustments to the implied vol raw strikes for + /// the overridden symbol + public static VolCurveMarketImpliedVolData adjust_implied_vols_for_symbols(VolCurveMarketImpliedVolData mapped_sym_implied_vol_data, VolSurfaceExpirationAuxiliaryData orig_aux_data, double orig_conversion_vol) + { + IDictionary put_rawk_vols = new Dictionary(), + call_rawk_vols = new Dictionary(); + foreach (KeyValuePair kv in mapped_sym_implied_vol_data.stdk_vols.Where(x => x.Key < 0)) + { + double rawk = VolSurfaceCoreFunctions.convert_axis(VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, mapped_sym_implied_vol_data.pricing_model, kv.Key, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, orig_conversion_vol, orig_aux_data); + put_rawk_vols[rawk] = kv.Value; + } + foreach (KeyValuePair kv in mapped_sym_implied_vol_data.stdk_vols.Where(x => x.Key > 0)) + { + double rawk = VolSurfaceCoreFunctions.convert_axis(VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, mapped_sym_implied_vol_data.pricing_model, kv.Key, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, orig_conversion_vol, orig_aux_data); + call_rawk_vols[rawk] = kv.Value; + } + return new VolCurveMarketImpliedVolData(orig_aux_data, mapped_sym_implied_vol_data.pricing_model, put_rawk_vols, call_rawk_vols, orig_aux_data.fwd, mapped_sym_implied_vol_data.atm_vol, orig_conversion_vol); + } + + /// Makes sure the atm vol is not NaN and thhere are more + /// than _min_points_for_fit call and put points + public static bool is_suitable_for_fit(VolCurveMarketImpliedVolData implied_vol_data) + { + return implied_vol_data != null && + !Double.IsNaN(implied_vol_data.atm_vol) && + !Double.IsNaN(implied_vol_data.conversion_vol) && + implied_vol_data.put_rawk_vols != null && implied_vol_data.put_rawk_vols.Count >= _min_points_for_fit && + implied_vol_data.call_rawk_vols != null && implied_vol_data.call_rawk_vols.Count >= _min_points_for_fit; + } + + public static VolCurveMarketImpliedVolData filter_for_ends(VolCurveMarketImpliedVolData implied_vol_data, + Tuple put_end_point, + Tuple call_end_point) + { + double put_end_point_rawk = convert_axis(put_end_point.Item1, implied_vol_data.pricing_model, put_end_point.Item2, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, implied_vol_data.conversion_vol, implied_vol_data.aux_data), + call_end_point_rawk = convert_axis(call_end_point.Item1, implied_vol_data.pricing_model, call_end_point.Item2, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, implied_vol_data.conversion_vol, implied_vol_data.aux_data); + return new VolCurveMarketImpliedVolData(implied_vol_data.aux_data, + implied_vol_data.pricing_model, + implied_vol_data.put_rawk_vols.Where(kv => kv.Key >= put_end_point_rawk).ToDictionary(kv => kv.Key, kv => kv.Value), + implied_vol_data.call_rawk_vols.Where(kv => kv.Key <= call_end_point_rawk).ToDictionary(kv => kv.Key, kv => kv.Value), + implied_vol_data.atm_strike, + implied_vol_data.atm_vol, + implied_vol_data.conversion_vol); + } + + #endregion + + #region Rotation of Points + + /// Rotates the points in point_xs across the pivot point + /// pivot_x, by using the rotation units. See the comments + /// on _linear_rotate_point for the definition of the rotation + public static IDictionary linear_rotate_points(HashSet point_xs, + double pivot_x, + IEnumerable> rotation_units) + { + Dictionary rv = new Dictionary(); + foreach (double x in point_xs) + foreach (Tuple r in rotation_units) + { + double curr = rv.TryGetValue(x, out curr) ? curr : 0.0; + rv[x] = curr + _linear_rotate_point(x, pivot_x, r); + } + return rv; + } + + /// Computes the rotational vertical movement for point_x + /// based around pivot_x based on the rotation_unit (or standard rotation). + /// - the rotation unit defines now much a point at + /// rotation_unit.x moves when rotated around pivot_x + private static double _linear_rotate_point(double point_x, double pivot_x, Tuple rotation_unit) + { + if (rotation_unit == null || rotation_unit.Item1 == pivot_x) + return 0.0; + else + { + if (points_on_same_side_of_pivot(pivot_x, rotation_unit.Item1, point_x)) + { + double move_ratio = rotation_unit.Item2 / (Math.Abs(rotation_unit.Item1 - pivot_x)); + return move_ratio * Math.Abs(point_x - pivot_x); + } + else + return 0.0; + } + } + + /// if x1 and x2 lie on the same side of the anchor + public static bool points_on_same_side_of_pivot(double pivot, double x1, double x2) + { + double dist_x1 = x1 - pivot, dist_x2 = x2 - pivot; + return (dist_x1 <= 0 && dist_x2 <= 0) || (dist_x1 >= 0 && dist_x2 >= 0); + } + + #endregion + + #region Time + + public static DateTime compute_vol_time (VolSurfaceInput vs_input, DateTime system_time) + { + Func to_hours = (dt) => dt.Subtract (dt.Date).TotalHours; + if (vs_input.surface_settings.core_settings.time_settings == null || vs_input.surface_settings.core_settings.time_settings.time_mode == VolSurfaceEnums.VolSurfaceTimeMode.Manual) + return vs_input.surface_parameters.vol_time; + else if (vs_input.surface_settings.core_settings.time_settings.time_mode == VolSurfaceEnums.VolSurfaceTimeMode.AutoDecay) + { + List> auto_decay_points; + if (vs_input.surface_parameters.time_parameters != null && vs_input.surface_parameters.time_parameters.auto_decay_points != null) + auto_decay_points = vs_input.surface_parameters.time_parameters.auto_decay_points.Select(t => Tuple.Create(to_hours(t.Item1), t.Item2)).ToList(); + else + auto_decay_points = new Tuple[] { Tuple.Create(0.0, 0.0), Tuple.Create(24.0, 24.0) }.ToList(); + /// if first and last points are not defined, insert (0, 1) (ie whole day remains at the start), and (24,0) (nothign remains at the end) + if (auto_decay_points.FindIndex(t => t.Item1 == 0) == -1) + auto_decay_points.Add (Tuple.Create(0.0, 0.0)); + if (auto_decay_points.FindIndex(t => t.Item1 == 24.0) == -1) + auto_decay_points.Add(Tuple.Create(24.0, 24.0)); + auto_decay_points = auto_decay_points.OrderBy(t => t.Item1).ToList(); + double today_hours = to_hours(system_time); + Log.assert (today_hours >= 0 && today_hours <= 24); + Tuple low, high; + VolSurfaceUtilityFunctions.find_neighbors(auto_decay_points, today_hours, (t, d) => t.Item1 - d, out low, out high); + double hours_taken_off = 0.0; + if (low == null && high == null) hours_taken_off = Double.NaN; + else if (low == null && high != null) hours_taken_off = high.Item2; + else if (low != null && high == null) hours_taken_off = low.Item2; + else hours_taken_off = lin_interp_exterp(low.Item1, low.Item2, high.Item1, high.Item2, today_hours); + return system_time.Date.Add(TimeSpan.FromHours(hours_taken_off)); + } + else + { + Log.assert(false, String.Format("Unknown time model {0}", vs_input.surface_settings.core_settings.time_settings.time_mode.ToString())); + return DateTime.MinValue; + } + } + + #endregion + + #region Misc + + public static VolSurfaceInput sync_slave_ref_fwds_to_masters(VolSurfaceInput vs_input, + IDictionary aux_data_map, + IEnumerable slave_exp_list) + { + VolSurfaceInput rv = VolSurfaceUtilityFunctions.clone_proto(vs_input); + IEnumerable all_exps = rv.surface_parameters.curve_parameters_map.Select (t => t.Item1); + foreach (VolSurfaceExpiration slave_exp in slave_exp_list) + { + VolSurfaceExpiration master_exp = VolSurfaceUtilityFunctions.find_master_expiration(slave_exp, rv.surface_settings, all_exps); + if (master_exp != null) + { + VolSurfaceExpirationAuxiliaryData master_exp_aux_data, slave_exp_aux_data; + if (aux_data_map.TryGetValue(master_exp, out master_exp_aux_data) && aux_data_map.TryGetValue(slave_exp, out slave_exp_aux_data)) + { + VolCurveParameters master_exp_params = VolSurfaceDataFunctions.get_curve_parameters(rv, master_exp), + slave_exp_params = VolSurfaceDataFunctions.get_curve_parameters(rv, slave_exp); + if (master_exp_params != null && slave_exp_params != null && + !Double.IsNaN(master_exp_aux_data.fwd) && !Double.IsNaN(master_exp_params.core_parameters.ref_forward) && + !Double.IsNaN(slave_exp_aux_data.fwd)) + slave_exp_params.core_parameters.ref_forward = (master_exp_params.core_parameters.ref_forward - master_exp_aux_data.fwd) + slave_exp_aux_data.fwd; + } + } + } + return rv; + } + #endregion + + #region Private Helpers + + private static double _ln(double x) { return Math.Log(x, Math.E); } + + private static double _sqr(double x) { return Math.Pow(x, 2.0); } + + private static double _cube(double x) { return Math.Pow(x, 3.0); } + + private static double _sqrt(double x) { return Math.Pow(x, 0.5); } + + private static bool _same_sign(double a, double b) { return (a > 0 && b > 0) || (a < 0 && b < 0); } + + public static double pow(double x, int p) + { + double rv = 1; + for (int i = 0; i < Math.Abs (p); i++) + rv *= x; + return p >= 0 ? rv : (1 / rv); + } + + /// Linearly interpolates the value of raw_k from neighbors + private static double _interpolate_strike(IDictionary k_value_map, double k) + { + KeyValuePair def_v = default(KeyValuePair); + double rv = Double.NaN; + if (!k_value_map.TryGetValue(k, out rv)) + { + KeyValuePair low, high; + VolSurfaceUtilityFunctions.find_neighbors(k_value_map, k, (kv, v) => v - kv.Key, out low, out high); + if (!low.Equals(def_v) && !high.Equals(def_v)) + rv = lin_interp_exterp(low.Key, low.Value, high.Key, high.Value, k); + else + rv = double.NaN; + } + return rv; + } + + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Misc/VolSurfaceDataFunctions.cs b/src/client/spark/Analytics/Misc/VolSurfaceDataFunctions.cs new file mode 100644 index 000000000..e86bf18c6 --- /dev/null +++ b/src/client/spark/Analytics/Misc/VolSurfaceDataFunctions.cs @@ -0,0 +1,678 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +//using bts.api.analytics; + +namespace mbts.analytics +{ + public class VolSurfaceDataFunctions + { + #region Syncing Data to Settings + + /// The second arg is the complete exp list. This function removes + /// vs_input's extra expirations and adds the missing exps + /// with default inputs + public static VolSurfaceInput sync_input_expirations_to_master_list(VolSurfaceInput vs_input, IEnumerable system_exp_list) + { + HashSet vs_exp_map = new HashSet(vs_input.surface_parameters.curve_parameters_map.Select(t => t.Item1)), + sys_exp_map = new HashSet(system_exp_list); + HashSet deleted_exps, added_exps; + if (VolSurfaceUtilityFunctions.compare_hashsets(sys_exp_map, vs_exp_map, out deleted_exps, out added_exps)) + { + VolSurfaceInput rv = VolSurfaceUtilityFunctions.clone_proto(vs_input); + rv.surface_parameters.curve_parameters_map = rv.surface_parameters.curve_parameters_map ?? new List>(); + rv.surface_parameters.curve_parameters_map.RemoveAll(t => deleted_exps.Contains(t.Item1)); + foreach (VolSurfaceExpiration exp in added_exps) + rv.surface_parameters.curve_parameters_map.Add(Tuple.Create(exp, _sync_curve_parameters_to_settings(null, rv.surface_settings))); + return rv; + } + else + return vs_input; + } + + public static VolSurfaceInput get_default_vs_input(VolSurfaceSettings vs_settings, IEnumerable vs_exp_list) + { + List> exp_params_list = new List>(); + foreach (VolSurfaceExpiration vs_exp in vs_exp_list) + exp_params_list.Add(Tuple.Create(vs_exp, _sync_curve_parameters_to_settings(null, vs_settings))); + return new VolSurfaceInput() + { + surface_settings = vs_settings, + surface_parameters = new VolSurfaceParameters() + { + vol_time = DateTime.Now.Date, + curve_parameters_map = exp_params_list + } + }; + } + + public static VolSurfaceInput get_default_vs_input(VolSurfaceSettings vs_settings, IDictionary> exp_list) + { + List vs_exp_list = new List(); + foreach (KeyValuePair> kv in exp_list) + foreach (DateTime exp in kv.Value) + vs_exp_list.Add(new VolSurfaceExpiration() { symbol = kv.Key, expiration = exp }); + return get_default_vs_input(vs_settings, vs_exp_list); + } + + public static VolCurveParameters get_default_curve_params(VolSurfaceSettings vs_settings) + { + return _sync_curve_parameters_to_settings(null, vs_settings); + } + + /// Syncs inputs to settings + public static VolSurfaceInput sync_volsurface_input_to_settings(VolSurfaceInput vs_input) + { + VolSurfaceInput rv = VolSurfaceUtilityFunctions.clone_proto(vs_input); + /// this is because the above the above translates empty lists to null + rv.surface_parameters.curve_parameters_map = rv.surface_parameters.curve_parameters_map ?? new List>(); + List> curve_parameters_map = new List>(); + foreach (Tuple t in rv.surface_parameters.curve_parameters_map) + curve_parameters_map.Add(Tuple.Create(t.Item1, _sync_curve_parameters_to_settings(t.Item2, vs_input.surface_settings))); + rv.surface_parameters.curve_parameters_map = curve_parameters_map; + return rv; + } + + private static VolCurveParameters _sync_curve_parameters_to_settings(VolCurveParameters exp_params, VolSurfaceSettings vs_settings, bool clone_exp_params = false) + { + VolCurveParameters rv = exp_params != null ? (clone_exp_params ? VolSurfaceUtilityFunctions.clone_proto(exp_params) : exp_params) : new VolCurveParameters(); + rv = _sync_main_model_input_to_settings(rv, vs_settings); + rv = _sync_wing_input_to_settings(rv, vs_settings); + rv = _sync_volpath_input_to_settings(rv, vs_settings); + return rv; + } + + private static VolCurveParameters _sync_main_model_input_to_settings(VolCurveParameters exp_params, VolSurfaceSettings vs_settings) + { + VolCurveParameters rv = exp_params; + if (vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline) + { + rv.polynomial_model_parameters = null; + rv.spline_model_parameters = rv.spline_model_parameters ?? new SplineModelVolCurveParameters() { atm_vol = Double.NaN, put_points = new List>(), call_points = new List>() }; + if (rv.spline_model_parameters.put_points.Count != vs_settings.spline_model_settings.n_put_points) + rv.spline_model_parameters.put_points = _sync_volpoints_to_settings(rv.spline_model_parameters.put_points, false, vs_settings.spline_model_settings.strike_axis, (int)vs_settings.spline_model_settings.n_put_points).ToList(); + if (rv.spline_model_parameters.call_points.Count != vs_settings.spline_model_settings.n_call_points) + rv.spline_model_parameters.call_points = _sync_volpoints_to_settings(rv.spline_model_parameters.call_points, true, vs_settings.spline_model_settings.strike_axis, (int)vs_settings.spline_model_settings.n_call_points).ToList(); + } + else if (vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Polynomial) + { + rv.spline_model_parameters = null; + rv.polynomial_model_parameters = rv.polynomial_model_parameters ?? new PolynomialModelVolCurveParameters() { atm_vol = Double.NaN, put_points = new List>(), call_points = new List>() }; + if (rv.polynomial_model_parameters.put_points.Count != vs_settings.polynomial_model_settings.n_put_points) + rv.polynomial_model_parameters.put_points = _sync_volpoints_to_settings(rv.polynomial_model_parameters.put_points, false, vs_settings.polynomial_model_settings.strike_axis, (int)vs_settings.polynomial_model_settings.n_put_points).ToList(); + if (rv.polynomial_model_parameters.call_points.Count != vs_settings.polynomial_model_settings.n_call_points) + rv.polynomial_model_parameters.call_points = _sync_volpoints_to_settings(rv.polynomial_model_parameters.call_points, true, vs_settings.polynomial_model_settings.strike_axis, (int)vs_settings.polynomial_model_settings.n_call_points).ToList(); + } + else if (vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.DualQuadratic) + { + rv.spline_model_parameters = null; + rv.polynomial_model_parameters = null; + rv.dualquadratic_model_parameters = rv.dualquadratic_model_parameters ?? new DualQuadraticModelVolCurveParameters() { put_slope = Double.NaN, call_slope = Double.NaN, atm_vol = Double.NaN }; + } + // else if(vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Custom) + // { + // rv.spline_model_parameters = null; + // rv.polynomial_model_parameters = null; + // if(rv.custom_parameters == null) + // { + // try + // { + // var model_name = vs_settings.custom_model_settings.vol_model_name; + // var m = CustomModelFactory.create(model_name); + // rv.custom_parameters = new CustomVolModelParameters { model = m }; + // } + // catch { } + // } + // } + return rv; + } + + private static VolCurveParameters _sync_wing_input_to_settings(VolCurveParameters exp_params, VolSurfaceSettings vs_settings) + { + VolCurveParameters rv = exp_params; + VolSurfaceEnums.VolCurveWingModel wing_model = vs_settings.core_settings.wing_settings.wing_model; + rv.core_parameters = rv.core_parameters ?? new VolCurveCoreParameters(); + rv.core_parameters.put_wing_parameters = rv.core_parameters.put_wing_parameters ?? new VolCurveWingParameters(); + rv.core_parameters.call_wing_parameters = rv.core_parameters.call_wing_parameters ?? new VolCurveWingParameters(); + if (wing_model == VolSurfaceEnums.VolCurveWingModel.ImplicitSlopeWithHorizontalAsymptotes) + { + rv.core_parameters.put_wing_parameters.explicit_slope_wing_parameters = rv.core_parameters.call_wing_parameters.explicit_slope_wing_parameters = null; + if (rv.core_parameters.put_wing_parameters.simple_slope_wing_parameters == null) + rv.core_parameters.put_wing_parameters.simple_slope_wing_parameters = new VolCurveSimpleSlopeWingParameters(); + if (rv.core_parameters.call_wing_parameters.simple_slope_wing_parameters == null) + rv.core_parameters.call_wing_parameters.simple_slope_wing_parameters = new VolCurveSimpleSlopeWingParameters(); + } + else if(wing_model == VolSurfaceEnums.VolCurveWingModel.ExplicitSlopeWithHorizontalAsymptotes) + { + rv.core_parameters.put_wing_parameters.simple_slope_wing_parameters = rv.core_parameters.call_wing_parameters.simple_slope_wing_parameters = null; + if (rv.core_parameters.put_wing_parameters.explicit_slope_wing_parameters == null) + rv.core_parameters.put_wing_parameters.explicit_slope_wing_parameters = new VolCurveExplicitSlopeWingParameters(); + if (rv.core_parameters.call_wing_parameters.explicit_slope_wing_parameters == null) + rv.core_parameters.call_wing_parameters.explicit_slope_wing_parameters = new VolCurveExplicitSlopeWingParameters(); + } + return rv; + } + + private static IEnumerable> _sync_volpoints_to_settings(IEnumerable> volpoints, bool is_call, + VolSurfaceEnums.VolCurveStrikeAxis strike_axis, int n_setting_points) + { + List> rv = new List>(volpoints); + rv = VolSurfaceUtilityFunctions.sort_strikes_from_atm(rv, is_call, strike_axis, (t => t.Item1)).ToList(); + if (n_setting_points > rv.Count) + rv.AddRange(Enumerable.Range(1, n_setting_points - rv.Count).Select(i => Tuple.Create(Double.NaN, Double.NaN))); + else if (n_setting_points < rv.Count) + rv = rv.GetRange(0, n_setting_points); + rv = VolSurfaceUtilityFunctions.sort_strikes_from_atm(rv, is_call, strike_axis, (t => t.Item1)).ToList(); + return rv; + } + + private static VolCurveParameters _sync_volpath_input_to_settings(VolCurveParameters exp_params, VolSurfaceSettings vs_settings) + { + VolCurveParameters rv = exp_params; + if(vs_settings.core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.TwoWaySlope) + { + rv.core_parameters = rv.core_parameters ?? new VolCurveCoreParameters(); + rv.core_parameters.vol_path_parameters = rv.core_parameters.vol_path_parameters ?? new VolPathParameters(); + rv.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters = rv.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters ?? new TwoWaySlopeVolPathParameters(); + return rv; + } + else if (vs_settings.core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.Parabolic) + { + rv.core_parameters = rv.core_parameters ?? new VolCurveCoreParameters(); + rv.core_parameters.vol_path_parameters = rv.core_parameters.vol_path_parameters ?? new VolPathParameters(); + rv.core_parameters.vol_path_parameters.parabolic_volpath_parameters = rv.core_parameters.vol_path_parameters.parabolic_volpath_parameters ?? new ParabolicVolPathParameters() { down_move_point = Tuple.Create(Double.NaN, Double.NaN), up_move_point = Tuple.Create(Double.NaN, Double.NaN) }; + return rv; + } + else + { + rv.core_parameters = rv.core_parameters ?? new VolCurveCoreParameters(); + rv.core_parameters.vol_path_parameters = rv.core_parameters.vol_path_parameters ?? new VolPathParameters(); + rv.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters = null; + // if(rv.core_parameters.vol_path_parameters.custom_parameters == null) + // { + // try + // { + // var model_name = vs_settings.custom_model_settings.vol_response_model_name; + // var m = CustomModelFactory.create(model_name); + // rv.core_parameters.vol_path_parameters.custom_parameters = new CustomModelVolResponseParameters { model = m }; + // } + // catch { } + // } + } + return rv; + } + + #endregion + + #region Accessors + + public static VolSurfaceEnums.VolSurfacePricingModel get_pricing_model(VolSurfaceSettings settings, VolSurfaceExpiration exp) + { + if (settings.core_settings.symbol_pricing_model_map != null) + foreach (Tuple t in settings.core_settings.symbol_pricing_model_map) + if (t.Item1 == exp.symbol) + return t.Item2; + return VolSurfaceEnums.VolSurfacePricingModel.BlackScholes; + } + + public static bool is_empty(VolCurveParameters exp_params, VolSurfaceSettings vs_settings) + { + return VolSurfaceUtilityFunctions.are_protos_equal(exp_params, VolSurfaceDataFunctions.get_default_curve_params(vs_settings)); + } + + public static IEnumerable get_symbols(VolSurfaceInput vs_input) + { + return vs_input != null ? get_symbols(vs_input.surface_settings) : new string[] { }; + } + + public static IEnumerable get_symbols(VolSurfaceSettings vs_settings) + { + return vs_settings.core_settings.symbol_pricing_model_map.Select(i => i.Item1); + } + + public static VolCurveParameters get_curve_parameters(VolSurfaceInput vs_input, VolSurfaceExpiration exp) + { + if (vs_input != null && vs_input.surface_parameters != null && vs_input.surface_parameters.curve_parameters_map != null) + { + Tuple t = vs_input.surface_parameters.curve_parameters_map.Find(t_arg => exp.Equals(t_arg.Item1)); + if (t != null) + return t.Item2; + } + return null; + } + + public static VolCurveWingParameters get_wing_parameters(VolSurfaceInput vs_input, VolSurfaceExpiration exp, bool is_call) + { + VolCurveParameters curve_parameters = get_curve_parameters(vs_input, exp); + return curve_parameters != null && curve_parameters.core_parameters != null ? + (is_call ? curve_parameters.core_parameters.call_wing_parameters : curve_parameters.core_parameters.put_wing_parameters) : null; + } + + public static VolPathParameters get_vol_path_parameters(VolSurfaceInput vs_input, VolSurfaceExpiration exp) + { + VolCurveParameters curve_parameters = get_curve_parameters(vs_input, exp); + return curve_parameters != null && curve_parameters.core_parameters != null ? curve_parameters.core_parameters.vol_path_parameters : null; + } + + public static Tuple get_polynomial_coordinates(VolSurfaceInput vs_input, VolSurfaceExpiration vs_exp, bool is_call, uint point_no) + { + VolCurveParameters curve_parameters = get_curve_parameters(vs_input, vs_exp); + if (curve_parameters != null && curve_parameters.polynomial_model_parameters != null) + { + IEnumerable> points = is_call ? curve_parameters.polynomial_model_parameters.call_points : curve_parameters.polynomial_model_parameters.put_points; + //points = points.OrderBy(t => t.Item1); + if (points != null && point_no < points.Count()) + return points.ElementAt((int)point_no); + } + return null; + } + + public static PolynomialModelVolCurveParameters get_polynomial_curve_parameters(VolSurfaceInput vs_input, VolSurfaceExpiration vs_exp) + { + VolCurveParameters curve_parameters = get_curve_parameters(vs_input, vs_exp); + return curve_parameters != null ? curve_parameters.polynomial_model_parameters : null; + } + + public static SplineModelVolCurveParameters get_spline_curve_parameters(VolSurfaceInput vs_input, VolSurfaceExpiration vs_exp) + { + VolCurveParameters curve_parameters = get_curve_parameters(vs_input, vs_exp); + return curve_parameters != null ? curve_parameters.spline_model_parameters : null; + } + + public static Tuple get_spline_coordinates(VolSurfaceInput vs_input, VolSurfaceExpiration vs_exp, bool is_call, uint point_no) + { + VolCurveParameters curve_parameters = get_curve_parameters(vs_input, vs_exp); + if (curve_parameters != null && curve_parameters.spline_model_parameters != null) + { + IEnumerable> points = is_call ? curve_parameters.spline_model_parameters.call_points : curve_parameters.spline_model_parameters.put_points; + if (points != null && point_no < points.Count()) + return points.ElementAt((int)point_no); + } + return null; + } + + public static VolSurfaceMarketFitSettings get_market_fit_settings(VolSurfaceSettings setting) + { + if (setting != null && setting.core_settings != null && setting.core_settings.market_fit_settings != null) + return setting.core_settings.market_fit_settings; + else + return new VolSurfaceMarketFitSettings(); + } + + public static Tuple get_risk_reversal_settings(VolSurfaceSettings settings) + { + if (settings != null && settings.core_settings != null && settings.core_settings.full_rotation != null && settings.core_settings.full_rotation.strike_vol_movement_pairs != null) + if (settings.core_settings.full_rotation.strike_vol_movement_pairs.Count == 2) + return Tuple.Create(settings.core_settings.full_rotation.strike_axis, settings.core_settings.full_rotation.strike_vol_movement_pairs[0].Item1, settings.core_settings.full_rotation.strike_vol_movement_pairs[1].Item1); + return null; + } + + #endregion + + #region Mutators + + public static void set_curve_parameters(VolSurfaceInput vs_input, VolSurfaceExpiration exp, VolCurveParameters curve_parameters) + { + if (vs_input != null) + { + vs_input.surface_parameters = vs_input.surface_parameters ?? new VolSurfaceParameters(); + vs_input.surface_parameters.curve_parameters_map = vs_input.surface_parameters.curve_parameters_map ?? new List>(); + int search_index = vs_input.surface_parameters.curve_parameters_map.FindIndex(t_arg => exp.Equals(t_arg.Item1)); + if (search_index >= 0 && search_index < vs_input.surface_parameters.curve_parameters_map.Count) + vs_input.surface_parameters.curve_parameters_map[search_index] = Tuple.Create(exp, curve_parameters); + else + vs_input.surface_parameters.curve_parameters_map.Add(Tuple.Create(exp, curve_parameters)); + } + } + + public static void set_twowayslope_volpath_parameters(VolSurfaceInput vs_input, VolSurfaceExpiration vs_exp, TwoWaySlopeVolPathParameters exp_volpath_params) + { + VolCurveParameters exp_params = get_curve_parameters(vs_input, vs_exp); + if (exp_params == null) + set_curve_parameters(vs_input, vs_exp, exp_params = new VolCurveParameters()); + exp_params.core_parameters = exp_params.core_parameters ?? new VolCurveCoreParameters(); + exp_params.core_parameters.vol_path_parameters = exp_params.core_parameters.vol_path_parameters ?? new VolPathParameters(); + exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters = exp_volpath_params; + } + + public static void set_parabolic_volpath_parameters(VolSurfaceInput vs_input, VolSurfaceExpiration vs_exp, ParabolicVolPathParameters exp_volpath_params) + { + VolCurveParameters exp_params = get_curve_parameters(vs_input, vs_exp); + if (exp_params == null) + set_curve_parameters(vs_input, vs_exp, exp_params = new VolCurveParameters()); + exp_params.core_parameters = exp_params.core_parameters ?? new VolCurveCoreParameters(); + exp_params.core_parameters.vol_path_parameters = exp_params.core_parameters.vol_path_parameters ?? new VolPathParameters(); + exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters = exp_volpath_params; + } + + /// Based on the vol surface settings, travserses the model + /// and copies the atm vol + public static void set_atm_vol(VolSurfaceSettings vs_settings, VolCurveParameters exp_params, double atm_vol) + { + if(vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Polynomial && (exp_params != null && exp_params.polynomial_model_parameters != null)) + exp_params.polynomial_model_parameters.atm_vol = atm_vol; + else if(vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline && (exp_params != null && exp_params.spline_model_parameters != null)) + exp_params.spline_model_parameters.atm_vol = atm_vol; + // else if(vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Custom && (exp_params != null && exp_params.custom_parameters != null)) + // exp_params.custom_parameters.model.set_atm_vol(atm_vol); + } + + /// Anologous to the above, for getting atm vol + public static double get_atm_vol(VolSurfaceSettings vs_settings, VolCurveParameters exp_params) + { + if(vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Polynomial && (exp_params != null && exp_params.polynomial_model_parameters != null)) + return exp_params.polynomial_model_parameters.atm_vol; + else if(vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline && (exp_params != null && exp_params.spline_model_parameters != null)) + return exp_params.spline_model_parameters.atm_vol; + // else if(vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Custom && (exp_params != null && exp_params.custom_parameters != null)) + // return exp_params.custom_parameters.model.atm_vol(); + else + return Double.NaN; + } + + #endregion + + #region Driver + + public static VolSurfaceInput unset_driver_overrides(VolSurfaceInput vs_input) + { + VolSurfaceInput rv = vs_input; + if (vs_input != null && vs_input.surface_parameters != null && vs_input.surface_parameters.curve_parameters_map != null) + { + rv = VolSurfaceUtilityFunctions.clone_proto(rv); + foreach (var p in rv.surface_parameters.curve_parameters_map) + if (p.Item2.core_parameters != null) + p.Item2.core_parameters.driver_override = Double.NaN; + } + return rv; + } + + public static IDictionary get_driver_map(VolSurfaceInput vs_input, IDictionary driver_price_map) + { + var rv = driver_price_map.ToDictionary (kv => kv.Key, kv => kv.Value); + if (vs_input != null && vs_input.surface_parameters != null && vs_input.surface_parameters.curve_parameters_map != null) + foreach (var t in vs_input.surface_parameters.curve_parameters_map) + if (t.Item2 != null && t.Item2.core_parameters != null && Double.IsNaN(t.Item2.core_parameters.driver_override)) + rv[t.Item1] = t.Item2.core_parameters.driver_override; + return rv; + } + + #endregion + + #region Checking for Data + + public static bool is_empty(VolSurfaceSettings vs_settings, VolCurveParameters exp_params) + { + return true; + } + + /// + /// Checks for obstructing nulls along the path to the VolSurfaceSettings object's nested vol_time_measure field. + /// Returns a default vol time measure object if nulls are found, otherwise returns the object's vol_time_measure. + /// + internal static VolSurfaceTimeMeasure get_vol_time_measure(VolSurfaceSettings settings) { + return settings.core_settings.time_settings != null ? settings.core_settings.time_settings.vol_time_measure ?? VolSurfaceDataFunctions.get_default_vol_time_measure() : VolSurfaceDataFunctions.get_default_vol_time_measure(); + } + + /// + /// Checks for obstructing nulls along the path to the VolSurfaceSettings object's nested interest_time_measure field. + /// Returns a default interest time measure object if nulls are found, otherwise returns the object's interest_time_measure. + /// + internal static VolSurfaceTimeMeasure get_interest_time_measure(VolSurfaceSettings settings) { + return settings.core_settings.time_settings != null ? settings.core_settings.time_settings.interest_time_measure ?? VolSurfaceDataFunctions.get_default_interest_time_measure() : VolSurfaceDataFunctions.get_default_interest_time_measure(); + } + + /// + /// Takes measures to "sanitize" the data. Critical fields/properties are initialized, and VolSurfaceSymbolRelationship objects' connected_symbols are forced to be a [distinct]set. + /// + public static void sanitize(VolSurfaceInput vs_input) { sanitize(vs_input.surface_settings); } + + /// + /// Takes measures to "sanitize" the data. Critical fields/properties are initialized, and VolSurfaceSymbolRelationship objects' connected_symbols are forced to be a [distinct]set. + /// + public static void sanitize(VolSurfaceSettings settings) { + settings.core_settings.time_settings = settings.core_settings.time_settings ?? new VolSurfaceTimeSettings() { time_mode = VolSurfaceEnums.VolSurfaceTimeMode.Manual }; + if (settings.core_settings.time_settings.vol_time_measure == null) { + settings.core_settings.time_settings.vol_time_measure = VolSurfaceDataFunctions.get_default_vol_time_measure(); + settings.core_settings.time_settings.interest_time_measure = VolSurfaceDataFunctions.get_default_interest_time_measure(); + } + if (settings.core_settings.master_slave_relationships != null) + foreach (VolSurfaceSymbolRelationship vssr in settings.core_settings.master_slave_relationships) + _force_distinct_connected_symbols(vssr); + if (settings.core_settings.implied_vol_marketdata_relationships != null) + foreach (VolSurfaceSymbolRelationship vssr in settings.core_settings.implied_vol_marketdata_relationships) + _force_distinct_connected_symbols(vssr); + } + + /// + /// Performs a deep(nested) check of every field and property for nulls, and initializes them. + /// + public static void initialize_everything(VolSurfaceSettings settings) { + if (settings.polynomial_model_settings == null) settings.polynomial_model_settings = new PolynomialModelVolSurfaceSettings(); + if (settings.spline_model_settings == null) settings.spline_model_settings = new SplineModelVolSurfaceSettings(); + if (settings.dualquadratic_model_settings == null) settings.dualquadratic_model_settings = new DualQuadraticModelVolSurfaceSettings(); + //if (settings.custom_model_settings == null) settings.custom_model_settings = new CustomModelVolSurfaceSettings(); + if (settings.core_settings.volpath_settings == null) settings.core_settings.volpath_settings = new VolPathSettings(); + if (settings.core_settings.volpath_settings.two_way_slope_vol_path_settings == null) settings.core_settings.volpath_settings.two_way_slope_vol_path_settings = new TwoWaySlopeVolPathSettings(); + if (settings.core_settings.volpath_settings.parabolic_vol_path_settings == null) settings.core_settings.volpath_settings.parabolic_vol_path_settings = new ParabolicVolPathSettings(); + if (settings.core_settings.wing_settings == null) settings.core_settings.wing_settings = new VolSurfaceWingSettings(); + if (settings.core_settings.wing_settings.implicit_slope_wing_settings == null) settings.core_settings.wing_settings.implicit_slope_wing_settings = new VolSurfaceImplicitSlopeWingSettings(); + if (settings.core_settings.wing_settings.explicit_slope_wing_settings == null) settings.core_settings.wing_settings.explicit_slope_wing_settings = new VolSurfaceExplicitSlopeWingSettings(); + if (settings.core_settings.wing_settings.onepoint_slope_wing_settings == null) settings.core_settings.wing_settings.onepoint_slope_wing_settings = new VolSurfaceOnePointSlopeWingSettings(); + if (settings.core_settings.market_fit_settings == null) settings.core_settings.market_fit_settings = new VolSurfaceMarketFitSettings(); + if (settings.core_settings.time_settings == null) settings.core_settings.time_settings = new VolSurfaceTimeSettings(); + if (settings.core_settings.time_settings.vol_time_measure == null) settings.core_settings.time_settings.vol_time_measure = VolSurfaceDataFunctions.get_default_vol_time_measure(); + if (settings.core_settings.time_settings.interest_time_measure == null) settings.core_settings.time_settings.interest_time_measure = VolSurfaceDataFunctions.get_default_interest_time_measure(); + } + + private static void _force_distinct_connected_symbols(VolSurfaceSymbolRelationship vssr) { + var distinct_syms = vssr.connected_symbols.Distinct().ToList(); + if (distinct_syms.Count != vssr.connected_symbols.Count) + vssr.connected_symbols = distinct_syms; + } + + #endregion + + #region Copying Master Data To Slave + + /// Copies the master exp paramaters to the slave exp parameters. + public static VolCurveParameters get_effective_slave_parameters(VolSurfaceSettings vs_settings, VolCurveParameters master_exp_params, VolCurveParameters slave_exp_params) + { + VolCurveParameters rv = VolSurfaceUtilityFunctions.clone_proto(master_exp_params); + /// vol params are all incrementals, ie main vol curve, wings and volpath + _copy_master_slave_main_model_params(vs_settings, master_exp_params, slave_exp_params, ref rv); + _copy_master_slave_wing_params_params(vs_settings, master_exp_params, slave_exp_params, ref rv); + _copy_master_slave_vol_path_params(vs_settings, master_exp_params, slave_exp_params, ref rv); + _copy_master_slave_strike_conversion_params(vs_settings, master_exp_params, slave_exp_params, ref rv); + rv.core_parameters.standard_vol = _combine(master_exp_params.core_parameters.standard_vol, slave_exp_params.core_parameters.standard_vol); + /// all other parameters are not derived from the master + rv.core_parameters.ref_forward = slave_exp_params.core_parameters.ref_forward; + rv.core_parameters.driver_override = slave_exp_params.core_parameters.driver_override; + rv.core_parameters.time_shift = slave_exp_params.core_parameters.time_shift; + rv.core_parameters.unhinge_exp_from_master = slave_exp_params.core_parameters.unhinge_exp_from_master; + return rv; + } + + /// This function returns the exp params, such that + /// a. if exp is master, returns the masters exp params + /// b. if exp is slave, resolves for master-slave and then returns the params + public static VolCurveParameters get_params_resolve_for_master_slave(VolSurfaceInput vs_input, VolSurfaceExpiration vs_exp) + { + VolCurveParameters exp_params = get_curve_parameters(vs_input, vs_exp); + if (VolSurfaceUtilityFunctions.is_master_expiration(vs_exp, vs_input.surface_settings)) + return exp_params; + else + { + VolSurfaceExpiration master_exp = VolSurfaceUtilityFunctions.find_master_expiration(vs_exp, vs_input.surface_settings, vs_input.surface_parameters.curve_parameters_map.Select(t => t.Item1)); + if (master_exp != null) + { + VolCurveParameters master_exp_params = get_curve_parameters(vs_input, master_exp); + if (master_exp_params != null) + return get_effective_slave_parameters(vs_input.surface_settings, master_exp_params, exp_params); + } + return exp_params; + } + } + + private static void _copy_master_slave_main_model_params(VolSurfaceSettings vs_settings, VolCurveParameters master_exp_params, VolCurveParameters slave_exp_params, ref VolCurveParameters result) + { + if (vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline) + { + result.spline_model_parameters.atm_vol = _combine(master_exp_params.spline_model_parameters.atm_vol, slave_exp_params.spline_model_parameters.atm_vol); + result.spline_model_parameters.put_points = _merge_points(master_exp_params.spline_model_parameters.put_points, slave_exp_params.spline_model_parameters.put_points); + result.spline_model_parameters.call_points = _merge_points(master_exp_params.spline_model_parameters.call_points, slave_exp_params.spline_model_parameters.call_points); + } + else if (vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Polynomial) + { + result.polynomial_model_parameters.atm_vol = _combine(master_exp_params.polynomial_model_parameters.atm_vol, slave_exp_params.polynomial_model_parameters.atm_vol); + result.polynomial_model_parameters.put_points = _merge_points(master_exp_params.polynomial_model_parameters.put_points, slave_exp_params.polynomial_model_parameters.put_points); + result.polynomial_model_parameters.call_points = _merge_points(master_exp_params.polynomial_model_parameters.call_points, slave_exp_params.polynomial_model_parameters.call_points); + } + else if (vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.DualQuadratic) + { + result.dualquadratic_model_parameters.atm_vol = _combine(master_exp_params.dualquadratic_model_parameters.atm_vol, slave_exp_params.dualquadratic_model_parameters.atm_vol); + result.dualquadratic_model_parameters.call_slope = _combine(master_exp_params.dualquadratic_model_parameters.call_slope, slave_exp_params.dualquadratic_model_parameters.call_slope); + result.dualquadratic_model_parameters.call_curvature = _combine(master_exp_params.dualquadratic_model_parameters.call_curvature, slave_exp_params.dualquadratic_model_parameters.call_curvature); + result.dualquadratic_model_parameters.put_slope = _combine(master_exp_params.dualquadratic_model_parameters.put_slope, slave_exp_params.dualquadratic_model_parameters.put_slope); + result.dualquadratic_model_parameters.put_curvature = _combine(master_exp_params.dualquadratic_model_parameters.put_curvature, slave_exp_params.dualquadratic_model_parameters.put_curvature); + result.dualquadratic_model_parameters.put_end_strike = _combine(master_exp_params.dualquadratic_model_parameters.put_end_strike, slave_exp_params.dualquadratic_model_parameters.put_end_strike); + result.dualquadratic_model_parameters.call_end_strike = _combine(master_exp_params.dualquadratic_model_parameters.call_end_strike, slave_exp_params.dualquadratic_model_parameters.call_end_strike); + result.dualquadratic_model_parameters.epsilon = _combine(master_exp_params.dualquadratic_model_parameters.epsilon, slave_exp_params.dualquadratic_model_parameters.epsilon); + } + // else if (vs_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Custom) + // { + // result.custom_parameters.model = master_exp_params.custom_parameters.model.combine(slave_exp_params.custom_parameters.model); + // } + } + + private static List> _merge_points(List> master_points, List> slave_points) + { + List> rv = new List>(); + for (int i = 0; i < master_points.Count; i++) + { + Tuple m = master_points[i], s = slave_points[i]; + rv.Add(Tuple.Create(_combine (m.Item1,s.Item1), _combine (m.Item2, s.Item2))); + } + return rv; + } + + private static void _copy_master_slave_vol_path_params(VolSurfaceSettings vs_settings, VolCurveParameters master_exp_params, VolCurveParameters slave_exp_params, ref VolCurveParameters result) + { + if (vs_settings.core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.TwoWaySlope) + { + result.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.asymptote_speed_for_fwd_down = _combine(master_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.asymptote_speed_for_fwd_down, + slave_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.asymptote_speed_for_fwd_down); + result.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.asymptote_speed_for_fwd_up = _combine(master_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.asymptote_speed_for_fwd_up, + slave_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.asymptote_speed_for_fwd_up); + result.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.max_vol_decrease = _combine(master_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.max_vol_decrease, + slave_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.max_vol_decrease); + result.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.max_vol_increase = _combine(master_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.max_vol_increase, + slave_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.max_vol_increase); + result.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.vol_move_for_unit_fwd_down = _combine(master_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.vol_move_for_unit_fwd_down, + slave_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.vol_move_for_unit_fwd_down); + result.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.vol_move_for_unit_fwd_up = _combine(master_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.vol_move_for_unit_fwd_up, + slave_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.vol_move_for_unit_fwd_up); + result.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.joint_speed = _combine(master_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.joint_speed, + slave_exp_params.core_parameters.vol_path_parameters.two_way_slope_vol_path_parameters.joint_speed); + } + if (vs_settings.core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.Parabolic) + { + result.core_parameters.vol_path_parameters.parabolic_volpath_parameters.down_move_point = Tuple.Create(_combine(master_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.down_move_point.Item1, + slave_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.down_move_point.Item1), + _combine(master_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.down_move_point.Item2, + slave_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.down_move_point.Item2)); + result.core_parameters.vol_path_parameters.parabolic_volpath_parameters.up_move_point = Tuple.Create(_combine(master_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.up_move_point.Item1, + slave_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.up_move_point.Item1), + _combine(master_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.up_move_point.Item2, + slave_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.up_move_point.Item2)); + result.core_parameters.vol_path_parameters.parabolic_volpath_parameters.max_vol_decrease = _combine(master_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.max_vol_decrease, + slave_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.max_vol_decrease); + result.core_parameters.vol_path_parameters.parabolic_volpath_parameters.max_vol_increase = _combine(master_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.max_vol_increase, + slave_exp_params.core_parameters.vol_path_parameters.parabolic_volpath_parameters.max_vol_increase); + } + // else if (vs_settings.core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.Custom) + // { + // result.core_parameters.vol_path_parameters.custom_parameters.model = + // master_exp_params.core_parameters.vol_path_parameters.custom_parameters.model.combine( + // slave_exp_params.core_parameters.vol_path_parameters.custom_parameters.model); + // } + } + + private static void _copy_master_slave_wing_params_params(VolSurfaceSettings vs_settings, VolCurveParameters master_exp_params, VolCurveParameters slave_exp_params, ref VolCurveParameters result) + { + if (vs_settings.core_settings.wing_settings.wing_model == VolSurfaceEnums.VolCurveWingModel.ImplicitSlopeWithHorizontalAsymptotes) + { + result.core_parameters.call_wing_parameters.simple_slope_wing_parameters.max_vol = _combine(master_exp_params.core_parameters.call_wing_parameters.simple_slope_wing_parameters.max_vol, + slave_exp_params.core_parameters.call_wing_parameters.simple_slope_wing_parameters.max_vol); + result.core_parameters.put_wing_parameters.simple_slope_wing_parameters.max_vol = _combine(master_exp_params.core_parameters.put_wing_parameters.simple_slope_wing_parameters.max_vol, + slave_exp_params.core_parameters.put_wing_parameters.simple_slope_wing_parameters.max_vol); + } + else if (vs_settings.core_settings.wing_settings.wing_model == VolSurfaceEnums.VolCurveWingModel.ExplicitSlopeWithHorizontalAsymptotes) + { + result.core_parameters.call_wing_parameters.explicit_slope_wing_parameters.distance = _combine(master_exp_params.core_parameters.call_wing_parameters.explicit_slope_wing_parameters.distance, + slave_exp_params.core_parameters.call_wing_parameters.explicit_slope_wing_parameters.distance); + result.core_parameters.call_wing_parameters.explicit_slope_wing_parameters.main_curve_decay = _combine(master_exp_params.core_parameters.call_wing_parameters.explicit_slope_wing_parameters.main_curve_decay, + slave_exp_params.core_parameters.call_wing_parameters.explicit_slope_wing_parameters.main_curve_decay); + result.core_parameters.call_wing_parameters.explicit_slope_wing_parameters.slope = _combine(master_exp_params.core_parameters.call_wing_parameters.explicit_slope_wing_parameters.slope, + slave_exp_params.core_parameters.call_wing_parameters.explicit_slope_wing_parameters.slope); + result.core_parameters.put_wing_parameters.explicit_slope_wing_parameters.distance = _combine(master_exp_params.core_parameters.put_wing_parameters.explicit_slope_wing_parameters.distance, + slave_exp_params.core_parameters.put_wing_parameters.explicit_slope_wing_parameters.distance); + result.core_parameters.put_wing_parameters.explicit_slope_wing_parameters.main_curve_decay = _combine(master_exp_params.core_parameters.put_wing_parameters.explicit_slope_wing_parameters.main_curve_decay, + slave_exp_params.core_parameters.put_wing_parameters.explicit_slope_wing_parameters.main_curve_decay); + result.core_parameters.put_wing_parameters.explicit_slope_wing_parameters.slope = _combine(master_exp_params.core_parameters.put_wing_parameters.explicit_slope_wing_parameters.slope, + slave_exp_params.core_parameters.put_wing_parameters.explicit_slope_wing_parameters.slope); + } + } + + private static void _copy_master_slave_strike_conversion_params(VolSurfaceSettings vs_settings, VolCurveParameters master_exp_params, VolCurveParameters slave_exp_params, ref VolCurveParameters result) + { + result.core_parameters.conversion_fwd_slider = _combine(master_exp_params.core_parameters.conversion_fwd_slider, slave_exp_params.core_parameters.conversion_fwd_slider); + result.core_parameters.conversion_vol_slider = _combine(master_exp_params.core_parameters.conversion_vol_slider, slave_exp_params.core_parameters.conversion_vol_slider); + } + + private static double _combine(double master, double slave) { return master + _val(slave); } + + private static double _val(double d) { return Double.IsNaN(d) ? 0 : d; } + + #endregion + + #region Time + + public static VolSurfaceEnums.VolSurfaceTimeMode get_time_mode(VolSurfaceInput vs_input) + { + if (vs_input != null && vs_input.surface_settings != null && vs_input.surface_settings.core_settings != null && vs_input.surface_settings.core_settings.time_settings != null) + return vs_input.surface_settings.core_settings.time_settings.time_mode; + else + return VolSurfaceEnums.VolSurfaceTimeMode.Manual; + } + + public static VolSurfaceTimeMeasure get_default_vol_time_measure() + { + return new VolSurfaceTimeMeasure() + { + days_per_year = 252.0, + account_for_holidays_and_weekends = true, + constant_offset_days = 0, + begin_day_measure = VolSurfaceEnums.DayMeasure.Fraction, + end_day_measure = VolSurfaceEnums.DayMeasure.Fraction + }; + } + + public static VolSurfaceTimeMeasure get_default_interest_time_measure() + { + return new VolSurfaceTimeMeasure() + { + days_per_year = 360.0, + account_for_holidays_and_weekends = false, + constant_offset_days = -1.0, + begin_day_measure = VolSurfaceEnums.DayMeasure.One, + end_day_measure = VolSurfaceEnums.DayMeasure.Zero + }; + } + + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Misc/VolSurfaceTimeCalculatorFactory.cs b/src/client/spark/Analytics/Misc/VolSurfaceTimeCalculatorFactory.cs new file mode 100644 index 000000000..d404b76f8 --- /dev/null +++ b/src/client/spark/Analytics/Misc/VolSurfaceTimeCalculatorFactory.cs @@ -0,0 +1,122 @@ +using mbts.config; +using System; +using System.Collections.Generic; +using bts.api; +using ProtoBuf; + +// using APIDateTime = bts.api.analytics.DateTimeType; +// using Calendar = bts.api.analytics.functions.Calendar; + +namespace mbts.analytics +{ + internal interface IVolSurfaceTimeCalculator + { + void compute_vol_time(VolSurfaceInput vs_input, VolSurfaceExpiration exp, DateTime voltime, double days_shift, out double yrs, out double days_per_yr); + void compute_interest_time(VolSurfaceInput vs_input, VolSurfaceExpiration exp, DateTime voltime, double days_shift, out double yrs, out double days_per_yr); + } + + internal static class VolSurfaceTimeCalculatorFactory + { + public static IVolSurfaceTimeCalculator get_calculator() { + return new TimeCalculator(); + // switch (Configuration.get().mode) { + // case bts.config.toggles.VolSurfaceTimeCalcMode.type.DISABLED: return new HistoricTimeCalculator(); + // case bts.config.toggles.VolSurfaceTimeCalcMode.type.ENABLED: return new TimeCalculator(); + // case bts.config.toggles.VolSurfaceTimeCalcMode.type.LOG_DISCREPANCIES: return null; + // default: throw new NotImplementedException(); + // } + } + + // private class HistoricTimeCalculator : IVolSurfaceTimeCalculator + // { + // public void compute_vol_time(VolSurfaceInput vs_input, VolSurfaceExpiration exp, DateTime voltime, double days_shift, out double yrs, out double days_per_yr) { + // VolSurfaceTimeMeasure time_measure = VolSurfaceDataFunctions.get_vol_time_measure(vs_input.surface_settings); + // APISecurityCalendarData cal_data = MetadataHelper.get_historic_metadata(exp.symbol); + // days_per_yr = time_measure.days_per_year; + // if (cal_data != null) { + // double days = Calendar.compute_biz_days(new APIDateTime { oa_date = voltime.ToOADate() }, new APIDateTime { oa_date = exp.expiration.ToOADate() }, cal_data.security_info, cal_data.sorted_holidays, days_shift, time_measure.account_for_holidays_and_weekends); + // yrs = days / days_per_yr; + // } else yrs = double.NaN; + // } + + // public void compute_interest_time(VolSurfaceInput vs_input, VolSurfaceExpiration exp, DateTime voltime, double days_shift, out double yrs, out double days_per_yr) { + // VolSurfaceTimeMeasure time_measure = VolSurfaceDataFunctions.get_interest_time_measure(vs_input.surface_settings); + // double days = bts.api.analytics.functions.Calendar.compute_cal_days(new bts.api.analytics.DateTimeType { oa_date = voltime.ToOADate() }, new bts.api.analytics.DateTimeType { oa_date = exp.expiration.ToOADate() }, days_shift); + // days_per_yr = time_measure.days_per_year; + // yrs = days / days_per_yr; + // } + // } + + private class TimeCalculator : IVolSurfaceTimeCalculator + { + public void compute_vol_time(VolSurfaceInput vs_input, VolSurfaceExpiration exp, DateTime voltime, double days_shift, out double yrs, out double days_per_yr) { + var time_measure = VolSurfaceDataFunctions.get_vol_time_measure(vs_input.surface_settings); + days_per_yr = time_measure.days_per_year; + yrs = VolSurfaceTimeFunctions.get_vol_years_remaining(exp, voltime, time_measure, days_shift); + } + + public void compute_interest_time(VolSurfaceInput vs_input, VolSurfaceExpiration exp, DateTime voltime, double days_shift, out double yrs, out double days_per_yr) { + var time_measure = VolSurfaceDataFunctions.get_interest_time_measure(vs_input.surface_settings); + days_per_yr = time_measure.days_per_year; + yrs = VolSurfaceTimeFunctions.get_interest_years_remaining(exp, voltime, time_measure, days_shift); + } + } + + // private class TimeLoggerCalculator : IVolSurfaceTimeCalculator + // { + // private readonly IVolSurfaceTimeCalculator _historic_calc = new HistoricTimeCalculator(), _calc = new TimeCalculator(); + // private readonly VolSurfaceTimeDiscrepancyLogger _vol_logger = new VolLogger(), _interest_logger = new InterestLogger(); + + // public void compute_vol_time(VolSurfaceInput vs_input, VolSurfaceExpiration exp, DateTime voltime, double days_shift, out double yrs, out double days_per_yr) { + // _historic_calc.compute_vol_time(vs_input, exp, voltime, days_shift, out yrs, out days_per_yr); + // double new_yrs, new_days_per_yr; + // _calc.compute_vol_time(vs_input, exp, voltime, days_shift, out new_yrs, out new_days_per_yr); + // _vol_logger.log(exp, voltime, VolSurfaceDataFunctions.get_vol_time_measure(vs_input.surface_settings), days_shift, yrs, new_yrs); + // } + + // public void compute_interest_time(VolSurfaceInput vs_input, VolSurfaceExpiration exp, DateTime voltime, double days_shift, out double yrs, out double days_per_yr) { + // _historic_calc.compute_interest_time(vs_input, exp, voltime, days_shift, out yrs, out days_per_yr); + // double new_yrs, new_days_per_yr; + // _calc.compute_interest_time(vs_input, exp, voltime, days_shift, out new_yrs, out new_days_per_yr); + // _interest_logger.log(exp, voltime, VolSurfaceDataFunctions.get_interest_time_measure(vs_input.surface_settings), days_shift, yrs, new_yrs); + // } + // } + + // private abstract class VolSurfaceTimeDiscrepancyLogger + // { + // protected VolSurfaceTimeDiscrepancyLogger() { } + + // private readonly Dictionary> _cache = new Dictionary>(); + + // protected abstract double get_test_yrs(VolSurfaceExpiration exp, DateTime vol_time, VolSurfaceTimeMeasure time_measure, double days_shift, SecurityCalendarData calendar_data); + + // public void log(VolSurfaceExpiration exp, DateTime vol_time, VolSurfaceTimeMeasure time_measure, double days_shift, double historic_yrs, double new_yrs) { + // if (Math.Abs(new_yrs - historic_yrs) > ((1 / 60) / 24) / time_measure.days_per_year) { + // // diff > 1 minute + // HashSet set; + // if (!_cache.TryGetValue(exp, out set)) _cache.Add(exp, set = new HashSet()); + // if (set.Add(time_measure)) { + // double test_yrs = get_test_yrs(exp, vol_time, time_measure, days_shift, MetadataHelper.get_calendar_data(exp.symbol)); + // Logger.error(bts.log.Subsystem.ui, "{0} {1} @ {2}: Days/Year = {3}, Account WKHDS = {4}, Historic = {5}, New = {6}, Test = {7}" + // .fmt(exp.symbol, exp.expiration.ToShortDateString(), vol_time, time_measure.days_per_year, time_measure.account_for_holidays_and_weekends, historic_yrs, new_yrs, test_yrs) + // ); + // } + // } + // } + // } + + // private class VolLogger : VolSurfaceTimeDiscrepancyLogger + // { + // protected override double get_test_yrs(VolSurfaceExpiration exp, DateTime vol_time, VolSurfaceTimeMeasure time_measure, double days_shift, SecurityCalendarData calendar_data) { + // return VolSurfaceTimeTests.get_vol_years(exp, vol_time, time_measure, calendar_data.calendar_mode, calendar_data.sorted_holidays, days_shift); + // } + // } + + // private class InterestLogger : VolSurfaceTimeDiscrepancyLogger + // { + // protected override double get_test_yrs(VolSurfaceExpiration exp, DateTime vol_time, VolSurfaceTimeMeasure time_measure, double days_shift, SecurityCalendarData calendar_data) { + // return VolSurfaceTimeTests.get_interest_years(exp, vol_time, time_measure, calendar_data.calendar_mode, calendar_data.sorted_holidays, days_shift); + // } + // } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Misc/VolSurfaceTimeFunctions.cs b/src/client/spark/Analytics/Misc/VolSurfaceTimeFunctions.cs new file mode 100644 index 000000000..44d68cf7d --- /dev/null +++ b/src/client/spark/Analytics/Misc/VolSurfaceTimeFunctions.cs @@ -0,0 +1,128 @@ +using System; +using System.Linq; +using bts.api; +using ProtoBuf; + +namespace mbts.analytics +{ + internal static class VolSurfaceTimeFunctions + { + #region Public Members + + public static DateTime h_date(Holiday h){ + return DateTime.FromOADate(h.Date); + } + public static double get_vol_years_remaining(VolSurfaceExpiration exp, DateTime vol_time, VolSurfaceTimeMeasure time_measure, double time_shift_in_days) { + OptionContract c= new OptionContract(); + if(c.Strike == 0){ + return 0.0; + } + return _get_years_remaining(exp, vol_time, time_measure, time_shift_in_days, 0.005); + } + + public static double get_interest_years_remaining(VolSurfaceExpiration exp, DateTime vol_time, VolSurfaceTimeMeasure time_measure, double time_shift_in_days) { + return _get_years_remaining(exp, vol_time, time_measure, time_shift_in_days, 0.0); + } + + public static double get_exp_date_days(DateTime exp_date, VolSurfaceEnums.CalendarMode mode) { + const double one_third = 1.0 / 3.0, one_quarter = 1.0 / 4.0; + switch (mode) { + case VolSurfaceEnums.CalendarMode.PM: return 1.0; + case VolSurfaceEnums.CalendarMode.AM_QUARTERLY_ONE_THIRD_PM_OTHER: return (exp_date.Month % 3 == 0 && _is_third_friday_or_saturday(exp_date)) ? one_third : 1.0; + case VolSurfaceEnums.CalendarMode.AM_ONE_THIRD_SERIAL_PM_OTHER: return _is_third_friday_or_saturday(exp_date) ? one_third : 1.0; + case VolSurfaceEnums.CalendarMode.AM_ONE_THIRD: return one_third; + case VolSurfaceEnums.CalendarMode.AM_ONE_QUARTER: return one_quarter; + default: return 0; + } + } + + public static DateTime flatten_exp_date(DateTime exp_date, Holiday[] sorted_holidays) { + switch (exp_date.DayOfWeek) { + case DayOfWeek.Saturday: return flatten_exp_date(DateTime.FromOADate(Math.Ceiling(exp_date.ToOADate() - 1.0)), sorted_holidays); + case DayOfWeek.Sunday: return flatten_exp_date(DateTime.FromOADate(Math.Ceiling(exp_date.ToOADate() - 2.0)), sorted_holidays); + default: return sorted_holidays.Any(h => h_date(h) == exp_date) ? flatten_exp_date(DateTime.FromOADate(Math.Ceiling(exp_date.ToOADate() - 1.0)), sorted_holidays) : exp_date; + } + } + + #endregion + + #region Private Members + + private static double _get_years_remaining(VolSurfaceExpiration exp, DateTime vol_time, VolSurfaceTimeMeasure time_measure, double time_shift, double min_days) { + SecurityCalendarData cal_data = MetadataHelper.get_calendar_data(exp.symbol); + double days = _get_days(vol_time, exp.expiration, time_measure.account_for_holidays_and_weekends, time_measure.begin_day_measure, time_measure.end_day_measure, cal_data, min_days); + if (!double.IsNaN(time_shift)) days += time_shift; + if (!double.IsNaN(time_measure.constant_offset_days)) days += time_measure.constant_offset_days; + return days / time_measure.days_per_year; + } + + private static double _get_days(DateTime vol_time, DateTime exp_date, bool account_for_holidays_and_weekends, VolSurfaceEnums.DayMeasure vol_day_measure, VolSurfaceEnums.DayMeasure exp_day_measure, SecurityCalendarData data, double min_days) { + exp_date = flatten_exp_date(exp_date, data.sorted_holidays); + DateTime vol_date = vol_time.Date; + if (vol_date > exp_date) return min_days; + else if (vol_date == exp_date) { + // end_date_measure takes precedence + switch (exp_day_measure) { + case VolSurfaceEnums.DayMeasure.Zero: return Math.Max(0.0, min_days); + case VolSurfaceEnums.DayMeasure.One: return Math.Max(1.0, min_days); + default: + double exp_date_days = get_exp_date_days(exp_date, data.calendar_mode); + switch (vol_day_measure) { + case VolSurfaceEnums.DayMeasure.Zero: return Math.Max(exp_date_days, min_days); + case VolSurfaceEnums.DayMeasure.One: return Math.Max(exp_date_days, min_days); + default: return Math.Max(exp_date_days - vol_time.TimeOfDay.TotalDays, min_days); + } + } + } else { + double days; + DateTime first_full_day; + switch (vol_day_measure) { + case VolSurfaceEnums.DayMeasure.Zero: + first_full_day = vol_date.AddDays(1.0); + days = (exp_date - first_full_day).TotalDays; + break; + case VolSurfaceEnums.DayMeasure.One: + first_full_day = vol_date; + days = (exp_date - first_full_day).TotalDays; + break; + default: + first_full_day = vol_date.AddDays(1.0); + days = (exp_date - first_full_day).TotalDays + _get_remaining_day(vol_time, account_for_holidays_and_weekends, data.sorted_holidays.SkipWhile(h => h_date(h).Date < vol_date).Take(1).FirstOrDefault(h => h_date(h).Date == vol_date)); + break; + } + if (account_for_holidays_and_weekends) { + double full_weeks = Math.Floor(days / 7.0); + double days_remainder = days % 7; + double weekend_days = full_weeks * 2.0; + switch (first_full_day.DayOfWeek) { + case DayOfWeek.Monday: if (days_remainder == 6) weekend_days += 1.0; break; + case DayOfWeek.Tuesday: if (days_remainder > 4) weekend_days += days_remainder > 5 ? 2.0 : 1.0; break; + case DayOfWeek.Wednesday: if (days_remainder > 3) weekend_days += days_remainder > 4 ? 2.0 : 1.0; break; + case DayOfWeek.Thursday: if (days_remainder > 2) weekend_days += days_remainder > 3 ? 2.0 : 1.0; break; + case DayOfWeek.Friday: if (days_remainder > 1) weekend_days += days_remainder > 2 ? 2.0 : 1.0; break; + case DayOfWeek.Saturday: if (days_remainder > 0) weekend_days += days_remainder > 1 ? 2.0 : 1.0; break; + case DayOfWeek.Sunday: if (days_remainder > 0) weekend_days += 1.0; break; + } + days -= (weekend_days + data.sorted_holidays.SkipWhile(h => h_date(h).Date <= vol_date).TakeWhile(h => h_date(h).Date < exp_date).Sum(h => h.PercentDayNotTrading)); + } + switch (exp_day_measure) { + case VolSurfaceEnums.DayMeasure.Zero: return Math.Max(days, min_days); + case VolSurfaceEnums.DayMeasure.One: return Math.Max(days + 1.0, days); + default: return Math.Max(days + get_exp_date_days(exp_date, data.calendar_mode), min_days); + } + } + } + + private static double _get_remaining_day(DateTime vol_time, bool account_for_holidays_and_weekends, Holiday hol) { + double rd = 1.0 - vol_time.TimeOfDay.TotalDays; + if (!account_for_holidays_and_weekends) return rd; + else if (hol != null) return rd * (1.0 - hol.PercentDayNotTrading); + else if (vol_time.DayOfWeek == DayOfWeek.Saturday || vol_time.DayOfWeek == DayOfWeek.Sunday) return 0.0; + else return rd; + } + + private static bool _is_third_friday_or_saturday(DateTime date) { return date.Day > 14 && date.Day < 22 && (date.DayOfWeek == DayOfWeek.Friday || date.DayOfWeek == DayOfWeek.Saturday); } + + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Misc/VolSurfaceTimer.cs b/src/client/spark/Analytics/Misc/VolSurfaceTimer.cs new file mode 100644 index 000000000..b66f0eaa3 --- /dev/null +++ b/src/client/spark/Analytics/Misc/VolSurfaceTimer.cs @@ -0,0 +1,29 @@ +using System; +using System.Runtime.InteropServices; + +namespace mbts.analytics +{ + public class VolSurfaceTimer + { + [DllImport("kernel32.dll")] + public extern static short QueryPerformanceCounter(ref long x); + [DllImport("kernel32.dll")] + public extern static short QueryPerformanceFrequency(ref long x); + + private readonly long _machine_freq = 0; + private long _start_count = 0, _end_count = 0; + + public VolSurfaceTimer() + { + QueryPerformanceFrequency(ref _machine_freq); + if (_machine_freq == 0) throw new ApplicationException("High resolution timers not supported by this machine's hardware"); + } + + public void start() { QueryPerformanceCounter(ref _start_count); } + + public void stop() { QueryPerformanceCounter(ref _end_count); } + + public double last_interval_time_ms { get { return (_end_count - _start_count) * 1000.0 / _machine_freq; } } + + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Misc/VolSurfaceUtilityFunctions.cs b/src/client/spark/Analytics/Misc/VolSurfaceUtilityFunctions.cs new file mode 100644 index 000000000..b5eeef6dd --- /dev/null +++ b/src/client/spark/Analytics/Misc/VolSurfaceUtilityFunctions.cs @@ -0,0 +1,851 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.IO; +using System.IO.Compression; + +using ProtoBuf; + +using bts.api; +using bts.settings; +using bts.spark; + +using mbts.ui.shell; +using mbts.utils; +using mbts.ui.utility; +using bts; + +namespace mbts.analytics +{ + public class VolSurfaceDriverTheo + { + public readonly SecurityExpiration exp, driver_exp; + public readonly double market_price, driver_market_price, + roll, theo, delta, + settlement_price, settlement_theo, settlement_delta; + public static VolSurfaceDriverTheo empty = new VolSurfaceDriverTheo(SecurityExpiration.empty, SecurityExpiration.empty, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN); + public VolSurfaceDriverTheo(SecurityExpiration exp, SecurityExpiration driver_exp, + double market_price, double driver_market_price, + double roll, double theo, double delta, + double settlement_price, double settlement_theo, double settlement_delta) + { + this.exp = exp; + this.driver_exp = driver_exp; + this.market_price = market_price; + this.driver_market_price = driver_market_price; + this.roll = roll; + this.theo = theo; + this.delta = delta; + this.settlement_price = settlement_price; + this.settlement_theo = settlement_theo; + this.settlement_delta = settlement_delta; + } + + public bool has_settlement { get { return !Double.IsNaN(settlement_price); } } + + public double effective_theo { get { return has_settlement ? settlement_price : theo; } } + + public double effective_delta { get { return has_settlement ? 0 : delta; } } + } + + public class VolSurfaceUtilityFunctions + { + #region Serialization + public static T deserialize_proto(byte[] proto_bytes) + { + return ProtoBuf.Serializer.DeserializeWithLengthPrefix(new System.IO.MemoryStream(proto_bytes), ProtoBuf.PrefixStyle.Fixed32); + } + + public static byte[] serialize_proto(T t) + { + System.IO.MemoryStream stream = new System.IO.MemoryStream(); + ProtoBuf.Serializer.SerializeWithLengthPrefix(stream, t, ProtoBuf.PrefixStyle.Fixed32); + stream.Position = 0; + return stream.ToArray(); + } + + public static T clone_proto(T t) + { + System.IO.MemoryStream stream = new System.IO.MemoryStream(); + ProtoBuf.Serializer.SerializeWithLengthPrefix(stream, t, ProtoBuf.PrefixStyle.Fixed32); + stream.Position = 0; + return ProtoBuf.Serializer.DeserializeWithLengthPrefix(stream, ProtoBuf.PrefixStyle.Fixed32); + } + + public static bool are_protos_equal(T t1, T t2) + { + byte[] b1 = serialize_proto(t1), b2 = serialize_proto(t2); + if (b1.Length == b2.Length) + { + for (int i = 0; i < b1.Length; i++) + if (!b1[i].Equals(b2[i])) + return false; + return true; + } + return false; + } + #endregion + + #region Data structures + + /// Sync's exps in data_map to the exps in master_exp_list. + /// For missing exps, uses get_default_func(exp) to get the data. + /// Removes extra exps if the the 4rd arg is set to true + public static IDictionary sync_map_exps(IEnumerable master_exp_list, + IDictionary data_map, + bool remove_extra_exps, + Func get_default_func) + { + HashSet master_exp_map = new HashSet (master_exp_list); + data_map = data_map ?? new Dictionary(); + List> rv = new List> (data_map.ToList()); + rv.AddRange(master_exp_map.Where(e => !data_map.ContainsKey(e)).Select(e => new KeyValuePair(e, get_default_func(e)))); + if (remove_extra_exps) + rv.RemoveAll (kv => !master_exp_map.Contains (kv.Key)); + return rv.ToDictionary(kv => kv.Key, kv => kv.Value); + } + + public static bool compare_hashsets(HashSet new_d, HashSet old_d, + out HashSet deleted_d, out HashSet added_d) + { + added_d = new HashSet(); + deleted_d = new HashSet(); + foreach (T t in new_d) + if (!old_d.Contains(t)) + added_d.Add(t); + foreach (T t in old_d) + if (!new_d.Contains(t)) + deleted_d.Add(t); + return added_d.Count > 0 || deleted_d.Count > 0; + } + + public static bool are_hashsets_equal(params HashSet[] hashsets) + { + if (hashsets.Length > 0) + { + HashSet comp = hashsets[0]; + foreach (HashSet h in hashsets) + { + HashSet del, added; + compare_hashsets(h, comp, out del, out added); + if (del.Count > 0 || added.Count > 0) + return false; + } + } + return true; + } + + public static T find_nearest(IEnumerable list, P nearest_to, Func diff_measure) + { + T rv = default(T); + double min_diff = Double.MaxValue; + foreach (T t in list) + { + double diff = Math.Abs(diff_measure(t, nearest_to)); + if (diff <= min_diff) + { + rv = t; + min_diff = diff; + } + } + return rv; + } + + public static void find_neighbors(IEnumerable list, P nearest_to, Func diff_measure, + out T low_neighbor, out T high_neighbor) + { + low_neighbor = default(T); high_neighbor = default(T); + list = list ?? new List(); + double low_min_diff = double.MaxValue, high_min_diff = double.MaxValue; + foreach (T t in list) + { + double this_diff = diff_measure(t, nearest_to); + if (this_diff <= 0) + { + this_diff = Math.Abs(this_diff); + if (this_diff < low_min_diff) + { + low_min_diff = this_diff; + low_neighbor = t; + } + } + else + { + if (this_diff < high_min_diff) + { + high_min_diff = this_diff; + high_neighbor = t; + } + } + } + } + + public static IDictionary append_dictionaties(IEnumerable> dictionaries) + { + Dictionary rv = new Dictionary(); + foreach (IDictionary d in dictionaries) + foreach (KeyValuePair kv in d) + rv[kv.Key] = kv.Value; + return rv; + } + + /// This sorts strike_points, such that the 0th element is the + /// most distant (to ATM) put point, and the (n-1)st element is + /// the most distant (to ATM) call point (the way its generally displayed) + public static IEnumerable sort_strikes_in_display_order(IEnumerable strike_points, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, Func key_selector) + { + if (strike_axis == VolSurfaceEnums.VolCurveStrikeAxis.RawStrike) + return new List(strike_points.OrderBy(t => key_selector(t))); + else + { + Func is_call = k => k >= 0.0; + IEnumerable call_points = strike_points.Where(t => is_call(key_selector(t))), + put_points = strike_points.Where(t => !is_call(key_selector(t))); + IEnumerable sorted_call_points = sort_strikes_from_atm(call_points, true, strike_axis, key_selector), + sorted_put_points = sort_strikes_from_atm(put_points, false, strike_axis, key_selector); + List rv = new List(sorted_put_points.Reverse()); + rv.AddRange(sorted_call_points); + return rv; + } + } + + /// Sorts strikes such that the 0th element is the nearest + /// to ATM strike + public static IEnumerable sort_strikes_from_atm(IEnumerable strike_points, bool is_call, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, Func key_selector) + { + IEnumerable unset_points = strike_points.Where(t => Double.IsNaN(key_selector(t))); + strike_points = strike_points.Where(t => !Double.IsNaN(key_selector(t))); + List low_to_high = new List(strike_points.OrderBy(t => key_selector(t))), + high_to_low = new List(low_to_high); + high_to_low.Reverse(); + List rv = null; + if (is_call) + { + if (strike_axis == VolSurfaceEnums.VolCurveStrikeAxis.Delta) + rv = high_to_low; + else + rv = low_to_high; + } + else + { + if (strike_axis == VolSurfaceEnums.VolCurveStrikeAxis.Delta) + rv = low_to_high; + else + rv = high_to_low; + } + Log.assert(rv != null, String.Format("Unknown strike axis {0}", strike_axis)); + rv.AddRange(unset_points); + return rv; + } + + public static void get_strike_distribution(IEnumerable strikes, + out double n_strikes, + out double min_strike, + out double max_strike, + out double min_distance, + out double mean_distance) + { + mean_distance = min_strike = max_strike = min_distance = Double.NaN; + List strikes_list = new List(strikes); + strikes_list.Sort(); + n_strikes = strikes_list.Count; + if (strikes_list.Count > 0) + { + min_strike = strikes_list.First(); + max_strike = strikes_list.Last(); + min_distance = Double.MaxValue; + for (int i = 1; i < strikes_list.Count; i++) + { + double diff = strikes_list[i] - strikes_list[i - 1]; + min_distance = min_distance < diff ? min_distance : diff; + } + mean_distance = (max_strike - min_distance) / n_strikes; + } + } + + public static void find_neighboring_exps(VolSurfaceExpiration vs_exp, bool restrict_to_symbol, IEnumerable exps, + out VolSurfaceExpiration low, out VolSurfaceExpiration high) + { + exps = restrict_to_symbol ? exps.Where(exp_i => exp_i.symbol == vs_exp.symbol) : exps; + exps = exps.Where (exp_i => !exp_i.Equals (vs_exp)); + VolSurfaceUtilityFunctions.find_neighbors(exps, vs_exp, (e1, e2) => e1.expiration.Subtract(e2.expiration).TotalHours, out low, out high); + if (low == null || high == null) + { + if (exps.Count() >= 2) + { + exps = exps.OrderBy(exp_i => exp_i.expiration); + if (vs_exp.expiration > exps.Last().expiration) + { + low = exps.ElementAt(exps.Count() - 2); + high = exps.ElementAt(exps.Count() - 1); + } + else if (vs_exp.expiration < exps.First().expiration) + { + low = exps.ElementAt(0); + high = exps.ElementAt(1); + } + } + } + } + + public static IDictionary> split_into_symbols(IDictionary> exp_map) + { + Dictionary> rv = new Dictionary>(); + foreach (KeyValuePair> kv in exp_map) + { + IEnumerable sym_list = null; + if (!rv.TryGetValue(kv.Key.symbol, out sym_list)) + rv[kv.Key.symbol] = sym_list = new List(); + (sym_list as List).AddRange(kv.Value); + } + return rv; + } + + public static IDictionary> get_contracts(VolSurfaceOutput vs_output) + { + IDictionary> rv = new Dictionary>(); + vs_output = vs_output ?? VolSurfaceOutput.get_empty_output(); + foreach (KeyValuePair kvp in vs_output.exp_output_map) + rv.Add(kvp.Key, new HashSet(kvp.Value.tradeable_strikes)); + return rv; + } + + private class DelegateEqualityComparer : IEqualityComparer + { + private Func _comparer_func; + public DelegateEqualityComparer(Func equality_func) { _comparer_func = equality_func; } + + public bool Equals(T x, T y) { return _comparer_func(x, y); } + + public int GetHashCode(T obj) { return obj != null ? obj.GetHashCode() : -1; } + } + + private class DelegateComparer : IComparer + { + private Func _comparer_func; + public DelegateComparer(Func comparer_func) { _comparer_func = comparer_func; } + public int Compare(T x, T y) { return _comparer_func(x, y); } + } + + public static IEqualityComparer get_equality_comparer(Func comparer_func) + { + return new DelegateEqualityComparer(comparer_func); + } + + public static IComparer get_comparer(Func comparer_func) + { + return new DelegateComparer(comparer_func); + } + + /// Converts the vs_exp-> T to exp->sum->T + public static IDictionary> split_into_exp_symbols(IDictionary exp_data) + { + IDictionary> rv = new Dictionary>(); + foreach (KeyValuePair kv in exp_data) + { + VolSurfaceExpiration exp = kv.Key; + IDictionary symbol_map = null; + if (!rv.TryGetValue(exp.expiration, out symbol_map)) + rv[exp.expiration] = symbol_map = new Dictionary(); + symbol_map[exp.symbol] = kv.Value; + } + return rv; + } + + #endregion + + #region Curve Operations + + public static bool is_rebuild_action(VolCurveAction curve_action) + { + return curve_action != null && (curve_action.action_type == VolCurveAction.ActionType.FitToMarket || curve_action.action_type == VolCurveAction.ActionType.Rebuild); + } + + /// If downwards operation then negates the change + public static VolCurveMovementOperation add_side_to_curve_operation(VolCurveMovementOperation curve_action, bool is_up) + { + VolCurveMovementOperation rv = clone_proto(curve_action); + if (!is_up) + { + rv.atm_strike_vol_movement = -1 * curve_action.atm_strike_vol_movement; + rv.strike_vol_movement_pairs = curve_action.strike_vol_movement_pairs == null ? new List>() : curve_action.strike_vol_movement_pairs.Select(i => Tuple.Create(i.Item1, i.Item2 * -1.0)).ToList(); + } + return rv; + } + + public static bool is_atm_move_included(VolCurveMovementOperation curve_action) + { + return curve_action != null && !Double.IsNaN(curve_action.atm_strike_vol_movement) && curve_action.atm_strike_vol_movement != 0.0; + } + + public static bool is_shape_move_included(VolCurveMovementOperation curve_action) + { + return curve_action != null && curve_action.strike_vol_movement_pairs != null && curve_action.strike_vol_movement_pairs.Count > 0; + } + + public static double find_atm_vol_move(VolCurveMovementOperation move_operation) + { + return move_operation != null ? move_operation.atm_strike_vol_movement : 0.0; + } + + public static IEnumerable get_exp_list_from_cascade(IEnumerable all_exps, IEnumerable select_exp, + bool cascade_up, bool cascade_down) + { + List rv = new List(); + HashSet select_exp_map = new HashSet(select_exp == null ? new VolSurfaceExpiration[] { } : select_exp); + if (select_exp_map.Count() > 0) + { + //VolSurfaceExpiration min_exp = select_exp.Min(kv => kv), max_exp = select_exp.Max(kv => kv); + VolSurfaceExpiration min_exp = EnumerableExtensions.Min(select_exp, kv => kv), max_exp = select_exp.Max(kv => kv); + foreach (VolSurfaceExpiration it_exp in all_exps) + { + if (select_exp_map.Contains(it_exp)) + rv.Add(it_exp); + else + { + if (cascade_down && it_exp.CompareTo(max_exp) >= 0) + rv.Add(it_exp); + if (cascade_up && it_exp.CompareTo(min_exp) <= 0) + rv.Add(it_exp); + } + } + } + return rv; + } + + public static IDictionary apply_cascade_to_action_map(IEnumerable all_exps, IDictionary exp_action_map, + bool cascade_up, bool cascade_down) + { + /// this function is very similiar to the above, but yet different enough to not reuse it + exp_action_map = exp_action_map ?? new Dictionary(); + IDictionary rv = new Dictionary(exp_action_map); + if (exp_action_map.Count() > 0) + { + //VolSurfaceExpiration min_exp = exp_action_map.Keys.Min(kv => kv), max_exp = exp_action_map.Keys.Max(kv => kv); + VolSurfaceExpiration min_exp = EnumerableExtensions.Min(exp_action_map.Keys, kv => kv), max_exp = exp_action_map.Keys.Max(kv => kv); + foreach (VolSurfaceExpiration it_exp in all_exps) + { + if (exp_action_map.ContainsKey(it_exp)) + rv[it_exp] = exp_action_map[it_exp]; + else + { + if (cascade_down && it_exp.CompareTo(max_exp) >= 0) + rv[it_exp] = exp_action_map[max_exp]; + if (cascade_up && it_exp.CompareTo(min_exp) <= 0) + rv[it_exp] = exp_action_map[min_exp]; + } + } + } + return rv; + } + + public static IEnumerable> get_vol_path_points(VolCurveOutput vc_out) + { + List> rv = new List>(); + Func compute_path_vol = vc_out.compute_path_vol ?? (k => Double.NaN); + if (vc_out != null) + foreach (double k in vc_out.tradeable_strikes) + rv.Add(Tuple.Create(k, compute_path_vol(k))); + return rv.OrderBy(t => t.Item1); + } + + public static bool is_risk_reversal(VolCurveAction action) + { + if (action != null && action.curve_operation != null && action.action_type == VolCurveAction.ActionType.CurveOperation) + if (!is_atm_move_included(action.curve_operation)) + if (action.curve_operation.strike_vol_movement_pairs != null && action.curve_operation.strike_vol_movement_pairs.Count == 2) + return action.curve_operation.strike_vol_movement_pairs[0].Item2 * action.curve_operation.strike_vol_movement_pairs[1].Item2 < 0; + return false; + } + + public static bool is_strangle(VolCurveAction action) + { + if (action != null && action.curve_operation != null && action.action_type == VolCurveAction.ActionType.CurveOperation) + if (!is_atm_move_included(action.curve_operation)) + if (action.curve_operation.strike_vol_movement_pairs != null && action.curve_operation.strike_vol_movement_pairs.Count == 2) + return action.curve_operation.strike_vol_movement_pairs[0].Item2 * action.curve_operation.strike_vol_movement_pairs[1].Item2 > 0; + return false; + } + + public static bool is_put_rotation(VolCurveAction action) + { + if (action != null && action.curve_operation != null && action.action_type == VolCurveAction.ActionType.CurveOperation) + if (!is_atm_move_included(action.curve_operation)) + if (action.curve_operation.strike_vol_movement_pairs != null && action.curve_operation.strike_vol_movement_pairs.Count == 1) + return !VolSurfaceCoreFunctions.is_call_or_put(action.curve_operation.strike_vol_movement_pairs[0].Item1, action.curve_operation.strike_axis, action.curve_operation.strike_vol_movement_pairs[0].Item1); + return false; + } + + public static bool is_call_rotation(VolCurveAction action) + { + if (action != null && action.curve_operation != null && action.action_type == VolCurveAction.ActionType.CurveOperation) + if (!is_atm_move_included(action.curve_operation)) + if (action.curve_operation.strike_vol_movement_pairs != null && action.curve_operation.strike_vol_movement_pairs.Count == 1) + return VolSurfaceCoreFunctions.is_call_or_put(action.curve_operation.strike_vol_movement_pairs[0].Item1, action.curve_operation.strike_axis, action.curve_operation.strike_vol_movement_pairs[0].Item1); + return false; + } + + #endregion + + #region Master Slave + + /// Puts VolSurfaceSymbolRelationship's into a map of symbol vs its connected symbols + private static IDictionary> _hash_relationship(VolSurfaceSettings vs_settings, IEnumerable rels) + { + IDictionary> rv = rels.ToDictionary(r => r.symbol, r => new HashSet(r.connected_symbols.ToArray())); + foreach (string s in VolSurfaceDataFunctions.get_symbols(vs_settings)) + if (!rv.ContainsKey(s) || rv[s] == null || rv[s].Count == 0) + rv.Add(s, new HashSet(new string[] { s })); + return rv; + } + + private static HashSet _get_slave_symbols(VolSurfaceSettings vs_settings) + { + /// just all - masters + HashSet all_symbols = new HashSet(VolSurfaceDataFunctions.get_symbols(vs_settings)), + master_symbols = get_master_symbols(vs_settings); + HashSet dels, adds; + compare_hashsets(all_symbols, master_symbols, out dels, out adds); + return adds; + } + + private static HashSet _get_masters_for_symbol(VolSurfaceSettings vs_settings, string symbol) + { + IDictionary> rel_map = _hash_relationship(vs_settings, vs_settings.core_settings.master_slave_relationships); + HashSet rv = rel_map.TryGetValue(symbol, out rv) ? rv : null; + return rv ?? new HashSet(); + } + + public static HashSet get_master_symbols(VolSurfaceSettings vs_settings) { + HashSet rv = new HashSet(); + _hash_relationship(vs_settings, vs_settings.core_settings.master_slave_relationships ?? new List()).ToList().ForEach(kv => rv.AddRange(kv.Value.ToArray())); + return rv; + } + + /// Returns a list of master exps, and depending on the last arg, + /// the slaves that are unlinked from the master + public static HashSet get_master_expirations(VolSurfaceInput vs_inp, bool include_unlinked_slaves = true) + { + HashSet master_symbols = get_master_symbols(vs_inp.surface_settings); + return new HashSet(vs_inp.surface_parameters.curve_parameters_map.Where(t => master_symbols.Contains(t.Item1.symbol) || (include_unlinked_slaves && t.Item2.core_parameters.unhinge_exp_from_master)).Select(t => t.Item1)); + } + + public static HashSet get_slave_expirations(VolSurfaceInput vs_inp) + { + if (vs_inp != null && vs_inp.surface_settings != null) + { + HashSet slave_symbols = _get_slave_symbols(vs_inp.surface_settings); + return new HashSet(vs_inp.surface_parameters.curve_parameters_map.Select(t => t.Item1).Where(t => slave_symbols.Contains(t.symbol))); + } + else + return new HashSet(); + } + + public static bool is_slave_expiration(VolSurfaceExpiration vs_exp, VolSurfaceSettings vs_settings) { return _get_slave_symbols(vs_settings).Contains(vs_exp.symbol); } + + public static bool is_master_expiration(VolSurfaceExpiration vs_exp, VolSurfaceSettings vs_settings) { return get_master_symbols(vs_settings).Contains(vs_exp.symbol); } + + public static VolSurfaceExpiration find_master_expiration(VolSurfaceExpiration slave_vs_exp, VolSurfaceSettings vs_settings, IEnumerable vs_exps) + { + IEnumerable master_symbols = _get_masters_for_symbol(vs_settings, slave_vs_exp.symbol); + vs_exps = vs_exps.Where(e => master_symbols.Contains(e.symbol)); + VolSurfaceExpiration rv = VolSurfaceUtilityFunctions.find_nearest(vs_exps, slave_vs_exp, (e1, e2) => Math.Abs(e1.expiration.Subtract(e2.expiration).TotalDays)) ?? new VolSurfaceExpiration() { expiration = DateTime.MinValue }; + /// TODO get this 2 from settings + return Math.Abs (slave_vs_exp.expiration.Subtract(rv.expiration).TotalDays) <= 2 ? rv : null; + } + + public static VolSurfaceExpiration find_implied_vol_source_expiration(VolSurfaceExpiration vs_exp, VolSurfaceInput vs_input) + { + IDictionary> md_rel_map = _hash_relationship(vs_input.surface_settings, vs_input.surface_settings.core_settings.implied_vol_marketdata_relationships); + HashSet source_symbols = (md_rel_map.TryGetValue(vs_exp.symbol, out source_symbols) ? source_symbols : null) ?? new HashSet(); + IEnumerable source_exps = vs_input.surface_parameters.curve_parameters_map.Select(t => t.Item1).Where(e => source_symbols.Contains(e.symbol)); + VolSurfaceExpiration rv = VolSurfaceUtilityFunctions.find_nearest(source_exps, vs_exp, (e1, e2) => Math.Abs(e1.expiration.Subtract(e2.expiration).TotalDays)) ?? new VolSurfaceExpiration() { expiration = DateTime.MinValue }; + /// TODO get this from settings + return Math.Abs (vs_exp.expiration.Subtract(rv.expiration).TotalDays) <= 1 ? rv : null; + } + + #endregion + + #region Misc + + public static DateTime round_time_mins(DateTime dt, int minutes) + { + int rounded_now_mins = Convert.ToInt32(Math.Floor((dt.Minute * 1.0) / minutes) * minutes); + return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, rounded_now_mins, 0); + } + + public static T nan_out_fields(Func create_new) + { + T rv = create_new(); + foreach (System.Reflection.FieldInfo fi in rv.GetType().GetFields()) + { + if (fi.FieldType.Equals(typeof(float))) + fi.SetValue(rv, Single.NaN); + else if (fi.FieldType.Equals (typeof(double))) + fi.SetValue (rv, Double.NaN); + } + return rv; + } + + public static IEnumerable adjust_control_points_signs(IEnumerable cps, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, bool is_call) + { + IEnumerable rv; + if (strike_axis == VolSurfaceEnums.VolCurveStrikeAxis.RawStrike) + rv = cps.Select(k => Math.Abs(k)); + else + { + if (is_call) + rv = cps.Select(k => Math.Abs(k)); + else + rv = cps.Select(k => -1.0 * Math.Abs(k)); + } + return rv; + } + + public static double to_years(TimeSpan ts) { return ts.TotalMinutes / (365 * 24 * 60); } + + public static string log_polynomials(IEnumerable> points, IEnumerable coeffs) + { + string coords_str = "Polynomial coords"; + foreach (Tuple t in points) + coords_str += String.Format(" {0},{1}", t.Item1, t.Item2); + string polynomial_str = String.Empty; + for (int i = 0; i < coeffs.Count(); i++) + polynomial_str += String.Format("{0}{1}x^{2}", String.IsNullOrEmpty(polynomial_str) ? String.Empty : "+", Math.Round(coeffs.ElementAt(i), 6), i); + Log.Gen.info(coords_str); + Log.Gen.info(polynomial_str); + return polynomial_str; + } + + /// Returns the list of symbols vs their md source + public static IDictionary flatten_implied_vol_md_source(IEnumerable implied_vol_md_source) + { + IDictionary rv = new Dictionary(); + foreach (VolSurfaceSymbolStructure s in implied_vol_md_source ?? Enumerable.Empty()) + s.slave_symbol_list.ForEach(i => rv[i] = s.master_symbol); + return rv; + } + + public static double restrict_bw_min_and_max(double v, double min, double max) { return Math.Min(Math.Max(v, min), max); } + + public static bool compare_doubles(double v1, double v2, double eps = 0.0000000001) { return Math.Abs(v1 - v2) <= eps; } + + #endregion + + #region Compression + + public static byte[] compress(byte[] data) + { + byte[] rv; + using (var out_str = new MemoryStream()) + { + using (var compr_str = new GZipStream(out_str, CompressionMode.Compress)) + using (var in_str = new MemoryStream(data)) + in_str.CopyTo(compr_str); + rv = out_str.ToArray(); + } + return rv; + } + + public static byte[] decompress(byte[] compressed_data) + { + byte[] rv; + using (var in_str = new MemoryStream(compressed_data)) + using (var decompr_str = new GZipStream(in_str, CompressionMode.Decompress)) + using (var rv_str = new MemoryStream()) + { + decompr_str.CopyTo(rv_str); + rv = rv_str.ToArray(); + } + return rv; + } + + #endregion + + #region Theos + + private static IDictionary> _greek_getters = new Dictionary>() + { + {VolSurfaceGreeks.AdjustedTheta, (t, cp) => cp ? t.cadjtheta : t.padjtheta}, + {VolSurfaceGreeks.AdjustedVega, (t, cp) => cp ? t.cadjvega : t.padjvega}, + {VolSurfaceGreeks.BSMDelta, (t, cp) => cp ? t.cdeltanovr : t.pdeltanovr}, + {VolSurfaceGreeks.BSMGamma, (t, cp) => cp ? t.gammanovr : t.gammanovr}, + {VolSurfaceGreeks.BSMOEV, (t, cp) => cp ? t.optsnovr : t.optsnovr}, + {VolSurfaceGreeks.BSMVega, (t, cp) => cp ? t.veganovr : t.veganovr}, + {VolSurfaceGreeks.Charm, (t, cp) => cp ? t.cdeltableed : t.pdeltableed}, + {VolSurfaceGreeks.D2VolDUnd2, (t, cp) => cp ? t.d2vol_dund2 : t.d2vol_dund2}, + {VolSurfaceGreeks.Delta, (t, cp) => cp ? t.cdelta : t.pdelta}, + {VolSurfaceGreeks.DiscountRho, (t, cp) => cp ? t.cdiscrho : t.pdiscrho}, + {VolSurfaceGreeks.DPriceDCallTilt, (t, cp) => cp ? t.ccalltailvega : t.pcalltailvega}, + {VolSurfaceGreeks.DPriceDPutTilt, (t, cp) => cp ? t.cputtailvega : t.pputtailvega}, + {VolSurfaceGreeks.DPriceDRiskReversal, (t, cp) => cp ? t.cslopevega : t.pslopevega}, + {VolSurfaceGreeks.DPriceDStrangle, (t, cp) => cp ? t.ccurvvega : t.pcurvvega}, + {VolSurfaceGreeks.DVolDUnd, (t, cp) => cp ? t.dvol_dund : t.dvol_dund}, + {VolSurfaceGreeks.FlatVolDelta, (t, cp) => cp ? t.cflatvoldelta : t.pflatvoldelta}, + {VolSurfaceGreeks.Gamma, (t, cp) => cp ? t.cgamma : t.pgamma}, + {VolSurfaceGreeks.Moneyness, (t, cp) => cp ? t.standard_strike : t.standard_strike}, + {VolSurfaceGreeks.OEV, (t, cp) => cp ? t.copts : t.popts}, + {VolSurfaceGreeks.PNL, (t, cp) => cp ? t.call : t.put}, + {VolSurfaceGreeks.RollRho, (t, cp) => cp ? t.crollrho : t.prollrho}, + {VolSurfaceGreeks.Theo, (t, cp) => cp ? t.call : t.put}, + {VolSurfaceGreeks.Theta, (t, cp) => cp ? t.cvoltheta : t.pvoltheta}, + {VolSurfaceGreeks.TimeValue, (t, cp) => cp ? t.ctimevalue : t.ptimevalue}, + {VolSurfaceGreeks.Vanna, (t, cp) => cp ? t.cvanna : t.pvanna}, + {VolSurfaceGreeks.Vega, (t, cp) => cp ? t.cvega : t.pvega}, + {VolSurfaceGreeks.Vol, (t, cp) => cp ? t.vol : t.vol}, + {VolSurfaceGreeks.Volga, (t, cp) => cp ? t.cvolga : t.pvolga}, + {VolSurfaceGreeks.ExpirationDelta, (t, cp) => cp ? t.cparitydelta : t.pparitydelta}, + }; + + public static double get_greek(VolSurfaceGreeks g, Theos t, bool is_call) + { + return _greek_getters[g](t, is_call); + } + + public static IDictionary> hash_strikes(IEnumerable theos) + { + IDictionary> rv = new Dictionary>(); + foreach (Theos t in theos) + { + IEnumerable k_theos; + if (!rv.TryGetValue(t.strike, out k_theos)) + rv[t.strike] = k_theos = new List(); + (k_theos as List).Add(t); + } + return rv; + } + + #endregion + + #region Calculation outside of this lib + + private static readonly IVolSurfaceTimeCalculator _time_calc = VolSurfaceTimeCalculatorFactory.get_calculator(); + + /// Computes the biz time in years (holidays accounted for) + /// from voltime to the expiration time of an option + /// (Note that the last argument of offset, is in days) + private static void _compute_option_bizt(VolSurfaceInput vs_input, VolSurfaceExpiration exp, DateTime voltime, double offset_in_days, out double biz_yrs, out double biz_days_per_yr) { + _time_calc.compute_vol_time(vs_input, exp, voltime, offset_in_days, out biz_yrs, out biz_days_per_yr); + } + + /// Computes the cal time in years + /// from voltime to the expiration time of an option + /// (Note that the last argument of offset, is in days) + private static void _compute_option_calt(VolSurfaceInput vs_input, VolSurfaceExpiration exp, DateTime voltime, double calday_offset, out double cal_yrs, out double cal_days_per_yr) { + _time_calc.compute_interest_time(vs_input, exp, voltime, calday_offset, out cal_yrs, out cal_days_per_yr); + } + + /// This is for a constant driver to fwd relationship + public static double compute_fwd_with_const_roll(double driver, double roll) { return driver + roll; } + + public static void compute_fwd_with_one_five(double driver, IReadOnlyDictionary rolls, + DateTime one_five_target, double one_five, out Dictionary fwds) + { + double target = 0.5 * (driver - one_five); + fwds = rolls.Select(x => Tuple.Create(x.Key, x.Value + target)).ToDictionary(x=>x.Item1, x=>x.Item2); + if(!fwds.ContainsKey(DateTime.MinValue)) + fwds.Add(DateTime.MinValue, 0.0); + } + + + public static IDictionary compute_aux_data(VolSurfaceInput vs_input, + VolSurfaceNonVolInput vs_nonvol_input, + IDictionary driver_price_map, + VolSurfaceStandardTime vs_standard_time, + bool use_input_driver_overrides = false) + { + IDictionary rv = new Dictionary(); + if (vs_input != null && vs_nonvol_input != null && vs_nonvol_input.exp_input_map != null && driver_price_map != null) + { + DateTime vol_time = VolSurfaceCoreFunctions.compute_vol_time(vs_input, vs_standard_time.server_time); + IDictionary exp_inp_data = vs_nonvol_input.get_option_exp_input(); + foreach (Tuple t in vs_input.surface_parameters.curve_parameters_map) + { + double time_shift = DoubleHelper.CoerceNaN(t.Item2.core_parameters.time_shift); + double biz_yrs, biz_days_per_yr, cal_yrs, cal_days_per_yr; + _compute_option_bizt(vs_input, t.Item1, vol_time, time_shift, out biz_yrs, out biz_days_per_yr); + _compute_option_calt(vs_input, t.Item1, vol_time, time_shift, out cal_yrs, out cal_days_per_yr); + double driver_price = driver_price_map.TryGetValue(t.Item1, out driver_price) ? driver_price : Double.NaN; + if (use_input_driver_overrides && t.Item2.core_parameters != null && !Double.IsNaN(t.Item2.core_parameters.driver_override)) + driver_price = t.Item2.core_parameters.driver_override; + AnalyticsExpirationParameters exp_input = exp_inp_data.TryGetValue(t.Item1, out exp_input) ? exp_input : AnalyticsExpirationParameters.empty; + double fwd = VolSurfaceUtilityFunctions.compute_fwd_with_const_roll(driver_price, DoubleHelper.CoerceNaN(exp_input.roll_target)); + rv[t.Item1] = new VolSurfaceExpirationAuxiliaryData(Double.NaN, fwd, driver_price, 1.0, 1.0, 1.0, vol_time, biz_yrs, cal_yrs, + DoubleHelper.CoerceNaN(exp_input.riskless_rate), exp_input.settlement_price, DoubleHelper.CoerceNaN(exp_input.roll_target), + biz_days_per_yr, cal_days_per_yr); + } + } + return rv; + } + + public static IDictionary compute_future_theos(IEnumerable future_exps, + IDictionary exp_params_map, + IDictionary future_driver_price_map) + { + IDictionary rv = new Dictionary(); + exp_params_map = exp_params_map.ToDictionary (kv => kv.Key.unset_exchange(), kv => kv.Value); + future_driver_price_map = future_driver_price_map.ToDictionary (kv => kv.Key.unset_exchange(), kv => kv.Value); + foreach (SecurityExpiration exp in future_exps) + { + /// This is not the best sln, but the calculations are + /// exchange agnostic, the other data may not be. + /// So this unset's the expirations (this could be + /// problem for multi-listed symbols) + SecurityExpiration exp_no_exch = exp.unset_exchange(); + AnalyticsExpirationParameters exp_param = (exp_params_map.TryGetValue(exp_no_exch, out exp_param) ? exp_param : null) ?? AnalyticsExpirationParameters.empty; + SecurityExpiration driver_exp_no_exch = (exp_param.driver_security ?? SecurityExpiration.empty).unset_exchange(); + double exp_roll = DoubleHelper.CoerceNaN(exp_param.roll_target); + + double driver_exp_market_price = future_driver_price_map.TryGetValue(driver_exp_no_exch, out driver_exp_market_price) ? driver_exp_market_price : Double.NaN, + exp_market_price = future_driver_price_map.TryGetValue(exp_no_exch, out exp_market_price) ? exp_market_price : Double.NaN, + exp_fwd = compute_fwd_with_const_roll(driver_exp_market_price, exp_roll); + rv[exp] = new VolSurfaceDriverTheo(exp, exp_param.driver_security, + exp_market_price, driver_exp_market_price, + exp_roll, exp_fwd, 1.0, /*assumes delta = 1*/ + exp_param.settlement_price, exp_param.settlement_price, 0.0); + } + return rv; + } + + #endregion + + #region Type Conversions + + public static IDictionary> convert_from_strike_map(HashSet strike_map) + { + IDictionary> rv = new Dictionary>(); + foreach (mbts.SecurityStrike k in strike_map) + { + HashSet exp_strike_map; + if (!rv.TryGetValue(k.expiration, out exp_strike_map)) + rv[k.expiration] = exp_strike_map = new HashSet(); + exp_strike_map.Add(k.strike); + } + return rv.ToDictionary(kv => new VolSurfaceExpiration(kv.Key.symbol, kv.Key.expiration), kv => kv.Value); + } + + public static IDictionary> convert_from_strike_map(IDictionary strike_map) + { + IDictionary> rv = new Dictionary>(); + foreach (var kv in strike_map) + { + IDictionary exp_strike_map; + if (!rv.TryGetValue(kv.Key.expiration, out exp_strike_map)) + rv[kv.Key.expiration] = exp_strike_map = new Dictionary(); + exp_strike_map[kv.Key.strike] = kv.Value; + } + return rv.ToDictionary(kv => new VolSurfaceExpiration(kv.Key.symbol, kv.Key.expiration), kv => kv.Value); + } + + public static HashSet convert_to_strike_map(IDictionary> exp_strike_map) + { + HashSet rv = new HashSet(); + foreach (var kv in exp_strike_map.ToDictionary(kv => new SecurityExpiration(Venue.Unset, SecurityType.Option, kv.Key.symbol, kv.Key.expiration), kv => kv.Value)) + rv.AddRange(kv.Value.Select(i => new SecurityStrike(kv.Key, i))); + return rv; + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/PolynomialModel/ControlPointsCurve.cs b/src/client/spark/Analytics/PolynomialModel/ControlPointsCurve.cs new file mode 100644 index 000000000..ccfc3adb0 --- /dev/null +++ b/src/client/spark/Analytics/PolynomialModel/ControlPointsCurve.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts; + +namespace mbts.analytics +{ + public class ControlPointsCurve + { + private readonly ExactFitPolynomial _polynomial = null; + private readonly CubicSpline _spline = null; + + private readonly VolSurfaceEnums.VolCurveStrikeAxis _plot_x_axis; + private readonly CoordinatesBasedModelHelper.ControlPoint.Axis _plot_y_axis; + private readonly double _final_atm_vol; + private readonly bool _directly_plot_vols = false; + + public ControlPointsCurve(VolSurfaceSettings settings, IEnumerable control_points, double final_atm_vol) + { + if (control_points.Count() > 0) + { + _plot_x_axis = settings.advanced_settings.strike_normalization_axis; + _plot_y_axis = control_points.ElementAt(0).y_axis; + _final_atm_vol = final_atm_vol; + /// coordinates are always normalization strike vs factors/adds + IEnumerable> coords = control_points.Select(cp => Tuple.Create(cp.normalization_strike, _directly_plot_vols ? cp.get_absolute_vol (_final_atm_vol) : cp.input_abstract_vol)); + coords = coords.Where(t => !Double.IsNaN(t.Item1) && !Double.IsNaN(t.Item2)); + if (settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline) + _spline = new CubicSpline(coords); + else if (settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Polynomial) + _polynomial = new ExactFitPolynomial(coords); + else + Log.assert(false, "Incorrect Model"); + } + + } + + public double compute(VolSurfaceEnums.VolCurveStrikeAxis strike_axis, double strike, + Func convert_axis, + uint nth_derv = 0) + { + if (nth_derv == 0) + { + double x = convert_axis(strike_axis, strike, _plot_x_axis); + double fn = _spline != null ? _spline.compute_with_infinite_extension(x) : _polynomial.compute_with_infinite_extension(x); + return _directly_plot_vols ? fn : (_plot_y_axis == CoordinatesBasedModelHelper.ControlPoint.Axis.Add ? fn + _final_atm_vol : fn * _final_atm_vol); + } + else + { + bool is_call = convert_axis(strike_axis, strike, VolSurfaceEnums.VolCurveStrikeAxis.LogSimpleMoneyness) >= 0; + return VolSurfaceCoreFunctions.compute_df(strike_arg => compute(strike_axis, strike_arg, convert_axis), strike, + is_call ? VolSurfaceCoreFunctions.DerivativeType.BackwardDifference : VolSurfaceCoreFunctions.DerivativeType.ForwardDifference, nth_derv); + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/PolynomialModel/CoordinateModelVolCurveCalculator.cs b/src/client/spark/Analytics/PolynomialModel/CoordinateModelVolCurveCalculator.cs new file mode 100644 index 000000000..ca210d6a9 --- /dev/null +++ b/src/client/spark/Analytics/PolynomialModel/CoordinateModelVolCurveCalculator.cs @@ -0,0 +1,316 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// This implementes the Spline and Polynomial models. The + /// difference is abstracted out in the ControlPointsCurve + public class CoordinateModelVolCurveCalculator : IVolCurveMainCalculator + { + /// Copied directly from args + private VolCurveParameters _input_parameters; + private VolSurfaceExpirationAuxiliaryData _aux_data; + private bool _initialized = true; + private IEnumerable _control_points; + private ControlPointsCurve _curve; + private double _final_unresponded_atm_vol = Double.NaN, _final_reponded_atm_vol = Double.NaN, + _conversion_vol, _conversion_fwd; + + #region IVolCurveMainCalculator + + public void initialize_for_lifetime(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action) + { + _input_parameters = curve_parameters; + _aux_data = aux_data; + path_induced_atm_vol_move = Double.IsNaN(path_induced_atm_vol_move) ? 0.0 : path_induced_atm_vol_move; + _initialized = _can_compute(surface_settings, curve_parameters, _aux_data.fwd, path_induced_atm_vol_move); + if (_initialized) + { + curve_action = CoordinatesBasedModelHelper.clean_action(curve_action); + if (curve_action.action_type == VolCurveAction.ActionType.None) + { + /// this is the only code path that alters that actually plots + /// the curve (ie sets _curve). The rest of the if conditions + /// below are recursive calls that end up here + _final_unresponded_atm_vol = _atm_vol(surface_settings, curve_parameters); + _final_reponded_atm_vol = _final_unresponded_atm_vol + path_induced_atm_vol_move; + _conversion_vol = _get_conversion_vol(surface_settings, curve_parameters, _final_reponded_atm_vol); + _conversion_fwd = _get_conversion_fwd(surface_settings, curve_parameters, aux_data); + _control_points = CoordinatesBasedModelHelper.convert_to_controlpoints(_vol_axis (surface_settings), + _strike_axis (surface_settings), + surface_settings.advanced_settings.strike_normalization_axis, + _puts (surface_settings, curve_parameters), + _calls(surface_settings, curve_parameters), + _convert_strike_axis); + _curve = new ControlPointsCurve(surface_settings, _control_points, _final_reponded_atm_vol); + } + else if (curve_action.action_type == VolCurveAction.ActionType.CurveOperation) + { + VolCurveMovementOperation movement_action = curve_action.curve_operation; + if (!Double.IsNaN(movement_action.atm_strike_vol_movement) && movement_action.atm_strike_vol_movement != 0) + { + VolCurveParameters new_params = _get_atmvol_move_params(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, curve_action); + initialize_for_lifetime(expiration, surface_settings, new_params, aux_data, path_induced_atm_vol_move, new VolCurveAction(VolCurveAction.ActionType.None)); + } + else + { + VolCurveParameters new_params = _get_shape_move_params(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, curve_action); + initialize_for_lifetime(expiration, surface_settings, new_params, aux_data, path_induced_atm_vol_move, new VolCurveAction(VolCurveAction.ActionType.None)); + } + } + else if (curve_action.action_type == VolCurveAction.ActionType.Rebuild) + { + VolCurveParameters new_params = _get_rebuild_params(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move); + initialize_for_lifetime(expiration, surface_settings, new_params, aux_data, 0.0, new VolCurveAction(VolCurveAction.ActionType.None)); + } + else if (curve_action.action_type == VolCurveAction.ActionType.FitToMarket) + { + VolCurveParameters new_params = _get_marketfit_params(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, curve_action); + initialize_for_lifetime(expiration, surface_settings, new_params, aux_data, 0.0, new VolCurveAction(VolCurveAction.ActionType.None)); + } + } + } + + #region Stateless functions that do input = f(input, action) + /// This is called when action = atm vol move. + /// This essentially does return curve_parameters.atm_vol + move + private static VolCurveParameters _get_atmvol_move_params(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action) + { + var movement_action = VolSurfaceCoreFunctions.normalize_atm_move_action(curve_action.curve_operation, _atm_vol(surface_settings, curve_parameters) + path_induced_atm_vol_move, + aux_data, _get_conversion_fwd(surface_settings, curve_parameters, aux_data)); + double atm_vol_action_move = movement_action == null ? 0.0 : VolSurfaceUtilityFunctions.find_atm_vol_move(movement_action); + return CoordinatesBasedModelHelper.update_atmvol(surface_settings, curve_parameters, atm_vol_action_move); + } + + /// This is called for any of the shape changes + /// (ie risk rev, strangle, put rot, call rot). + /// Since this (and rebuild) need control point details to do + /// the operation, it does the following + /// i. construct CoordinateModelVolCurveCalculator + /// ii. normalize the action parameters to vol vs std k terms (from say price vs delta terms) + /// iii. apply action to get another set of control points + /// iv. copy iii to the input + private static VolCurveParameters _get_shape_move_params(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action) + { + CoordinateModelVolCurveCalculator curr_calc = new CoordinateModelVolCurveCalculator(); + curr_calc.initialize_for_lifetime(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, new VolCurveAction(VolCurveAction.ActionType.None)); + var normalized_movement_action = VolSurfaceCoreFunctions.normalize_shape_action(curve_action.curve_operation, aux_data, + (source_axis, source_strike, target_axis) => curr_calc._convert_strike_axis(source_axis, source_strike, target_axis), + (strike, axis) => curr_calc._compute_vol(strike, axis, 0)); + /// This is getting changed : The right value for the last arg should be atm_vol and not the responded vol. This is + /// so that the base curve is rotated first and then responded + var control_points = CoordinatesBasedModelHelper.apply_action(curr_calc._control_points, normalized_movement_action, _atm_vol(surface_settings, curve_parameters) + path_induced_atm_vol_move); + VolCurveParameters new_params = CoordinatesBasedModelHelper.update_controlpoints(surface_settings, curve_parameters, control_points); + return new_params; + } + + private static VolCurveParameters _get_marketfit_params(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action) + { + VolCurveParameters rv = curve_parameters; + VolCurveMarketFitAction market_fit_action = curve_action.market_fit_action; + if (market_fit_action != null && market_fit_action.implied_vol_data != null) + { + Func convert_axis = (source_axis, source_strike, target_axis) => + { + return VolSurfaceCoreFunctions.convert_axis(source_axis, source_strike, target_axis, market_fit_action.implied_vol_data.atm_vol, aux_data.fwd, aux_data.biz_t, aux_data.cal_t, aux_data.riskless_rate); + }; + IEnumerable control_points = null; + if (market_fit_action.fit_action == VolCurveMarketFitAction.ActionType.FitATM) + control_points = CoordinatesBasedModelHelper.convert_to_controlpoints(_vol_axis(surface_settings), + _strike_axis (surface_settings), + surface_settings.advanced_settings.strike_normalization_axis, + _puts (surface_settings, curve_parameters), + _calls(surface_settings, curve_parameters), + convert_axis); + else if (market_fit_action.fit_action == VolCurveMarketFitAction.ActionType.FitWholeCurve) + control_points = CoordinatesBasedModelHelper.fit_to_market(market_fit_action.implied_vol_data, + aux_data, + surface_settings.core_settings.market_fit_settings, + _vol_axis(surface_settings), + _strike_axis(surface_settings), + surface_settings.advanced_settings.strike_normalization_axis, + convert_axis, + _puts(surface_settings, curve_parameters), + _calls(surface_settings, curve_parameters), + market_fit_action.use_weighted_regression); + rv = CoordinatesBasedModelHelper.update_atmvol(surface_settings, curve_parameters, market_fit_action.implied_vol_data.atm_vol, false); + rv = CoordinatesBasedModelHelper.update_controlpoints(surface_settings, rv, control_points); + rv = CoordinatesBasedModelHelper.update_on_rebuild(surface_settings, rv, aux_data); + } + return rv; + } + + /// The idea is that for each of the raw strike corresponding + /// to the control points and to the live fwd, keep the vols + /// constant + private static VolCurveParameters _get_rebuild_params(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move) + { + VolCurveParameters rv = curve_parameters; + CoordinateModelVolCurveCalculator curr_calc = new CoordinateModelVolCurveCalculator(); + curr_calc.initialize_for_lifetime(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, new VolCurveAction(VolCurveAction.ActionType.None)); + double new_atm_vol = curr_calc._compute_vol(aux_data.fwd, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + /// for each cp, find the K, using new fwd, v atm + List> new_put_points = new List>(), new_call_points = new List>(); + bool is_mult = _vol_axis(surface_settings) == VolSurfaceEnums.VolCurveVolAxis.ATMFactor; + foreach (var put_point in _puts (surface_settings, curve_parameters)) + { + double put_raw_k = VolSurfaceCoreFunctions.convert_axis(_strike_axis(surface_settings), put_point.Item1, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, new_atm_vol, aux_data); + double curr_vol = curr_calc._compute_vol(put_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + double abstract_vol = !is_mult ? curr_vol - new_atm_vol : curr_vol / new_atm_vol; + new_put_points.Add(Tuple.Create(put_point.Item1, abstract_vol)); + } + foreach (var call_point in _calls(surface_settings, curve_parameters)) + { + double call_raw_k = VolSurfaceCoreFunctions.convert_axis(_strike_axis(surface_settings), call_point.Item1, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, new_atm_vol, aux_data); + double curr_vol = curr_calc._compute_vol(call_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + double abstract_vol = !is_mult ? curr_vol - new_atm_vol : curr_vol / new_atm_vol; + new_call_points.Add(Tuple.Create(call_point.Item1, abstract_vol)); + } + + rv = CoordinatesBasedModelHelper.update_atmvol(surface_settings, curve_parameters, new_atm_vol, false); + rv = CoordinatesBasedModelHelper.update_controlpoints(surface_settings, rv, new_put_points, new_call_points); + rv = CoordinatesBasedModelHelper.update_on_rebuild(surface_settings, rv, aux_data); + return rv; + } + #endregion + + public bool is_initialized() { return _initialized; } + + public VolCurveParameters fill_missing_inputs(VolCurveParameters main_curve_params, VolCurveParameters sec_curve_params) + { + return null; + } + + public VolCurveMainOutput get_output() + { + if (_initialized) + { + IEnumerable cp_put_strikes, cp_call_strikes; + CoordinatesBasedModelHelper.get_controlpoint_strikes(_control_points, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, _convert_strike_axis, out cp_put_strikes, out cp_call_strikes); + double put_end_raw_strike, call_end_raw_strike; + CoordinatesBasedModelHelper.get_end_points(_control_points, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, _convert_strike_axis, out put_end_raw_strike, out call_end_raw_strike); + return new VolCurveMainOutput(_aux_data.fwd, + _conversion_fwd, + _final_unresponded_atm_vol, + _final_reponded_atm_vol, + _conversion_vol, + cp_put_strikes, + cp_call_strikes, + put_end_raw_strike, + call_end_raw_strike, + _input_parameters, + _aux_data, + _compute_vol, + _convert_strike_axis); + } + else + return new VolCurveMainOutput(Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Enumerable.Empty(), Enumerable.Empty(), + Double.NaN, Double.NaN, + _input_parameters, _aux_data, (k, k_axis, nth_derv) => Double.NaN, + (source_axis, k, target_axis) => Double.NaN); + } + + public void Dispose() { } + + #endregion + + private double _compute_vol(double strike, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, uint nth_derv = 0) + { + return _initialized ? _curve.compute(strike_axis, strike, _convert_strike_axis, nth_derv) : Double.NaN; + } + + private double _convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolCurveStrikeAxis target_axis) + { + return VolSurfaceCoreFunctions.convert_axis(source_axis, source_point, target_axis, + _conversion_vol, _conversion_fwd, _aux_data.biz_t, _aux_data.cal_t, _aux_data.riskless_rate); + } + + private static double _get_conversion_vol(VolSurfaceSettings vs_settings, VolCurveParameters curve_params, double final_responded_vol) + { + if (vs_settings.core_settings.strike_conversion_vol == VolSurfaceEnums.StrikeConversionVol.StandardVol) return curve_params.core_parameters.standard_vol; + else if (vs_settings.core_settings.strike_conversion_vol == VolSurfaceEnums.StrikeConversionVol.ATMVol) return _atm_vol(vs_settings, curve_params); + else if (vs_settings.core_settings.strike_conversion_vol == VolSurfaceEnums.StrikeConversionVol.PathATMVol) return final_responded_vol; + else return Double.NaN; + } + + private static double _get_conversion_fwd(VolSurfaceSettings vs_settings, VolCurveParameters curve_params, VolSurfaceExpirationAuxiliaryData aux_data) + { + double conv_fwd_slider = curve_params.core_parameters.conversion_fwd_slider; + conv_fwd_slider = Double.IsNaN(conv_fwd_slider) ? 0.0 : VolSurfaceUtilityFunctions.restrict_bw_min_and_max(conv_fwd_slider, 0.0, 1.0); + /// the 1.0 check is just so that users who dont want to deal with ref_fwd's can leave it + /// unattended and we dont run into a NaN situation + return VolSurfaceUtilityFunctions.compare_doubles(conv_fwd_slider, 1.0) ? aux_data.fwd : (conv_fwd_slider * aux_data.fwd) + ((1 - conv_fwd_slider) * curve_params.core_parameters.ref_forward); + } + + #region Spline/Polynomial Demux + /// Checks for fwd, atm vol and calls/puts having 1 non nan value each + private static bool _can_compute(VolSurfaceSettings settings, VolCurveParameters curve_parameters, double current_fwd, double path_induced_atm_vol_move) + { + return !Double.IsNaN(current_fwd) && + !Double.IsNaN(path_induced_atm_vol_move) && + curve_parameters != null && + (_is_spline(settings) ? curve_parameters.spline_model_parameters != null : curve_parameters.polynomial_model_parameters != null) && + !Double.IsNaN(_atm_vol(settings, curve_parameters)) && + _puts(settings, curve_parameters).Where(t => !Double.IsNaN(t.Item1) && !Double.IsNaN(t.Item2)).Count() > 0 && + _calls(settings, curve_parameters).Where(t => !Double.IsNaN(t.Item1) && !Double.IsNaN(t.Item2)).Count() > 0; + } + + private static double _atm_vol(VolSurfaceSettings s, VolCurveParameters c) + { + return _is_spline(s) ? c.spline_model_parameters.atm_vol : c.polynomial_model_parameters.atm_vol; + } + + public static List> _puts(VolSurfaceSettings s, VolCurveParameters c) + { + return _is_spline(s) ? c.spline_model_parameters.put_points : c.polynomial_model_parameters.put_points; + } + + public static List> _calls(VolSurfaceSettings s, VolCurveParameters c) + { + return _is_spline(s) ? c.spline_model_parameters.call_points : c.polynomial_model_parameters.call_points; + } + + private static bool _is_spline(VolSurfaceSettings s) + { + return s.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline; + } + + private static VolSurfaceEnums.VolCurveStrikeAxis _strike_axis (VolSurfaceSettings s) + { + return _is_spline(s) ? s.spline_model_settings.strike_axis : s.polynomial_model_settings.strike_axis; + } + + private static VolSurfaceEnums.VolCurveVolAxis _vol_axis(VolSurfaceSettings s) + { + return _is_spline(s) ? s.spline_model_settings.vol_axis : s.polynomial_model_settings.vol_axis; + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/PolynomialModel/CoordinatesBasedModelHelper.cs b/src/client/spark/Analytics/PolynomialModel/CoordinatesBasedModelHelper.cs new file mode 100644 index 000000000..ba09cdeb0 --- /dev/null +++ b/src/client/spark/Analytics/PolynomialModel/CoordinatesBasedModelHelper.cs @@ -0,0 +1,470 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts; + +namespace mbts.analytics +{ + /// Helper for the polynomial and spline models + public class CoordinatesBasedModelHelper + { + /// Encapsulates a coordinate, this class is independent of + /// the x-axis; the y-axis is stored as either an add or a + /// mult + public class ControlPoint + { + public enum PointType { Put, ATM, Call } + + public enum Axis { Add, Mult } + + public readonly double standard_strike, + input_strike, + normalization_strike, + input_abstract_vol; + public readonly PointType point_type; + public readonly Axis y_axis; + + public ControlPoint(double this_standard_strike, + double this_input_strike, + double this_normlization_strike, + double this_input_abstract_vol, + PointType this_point_type, + Axis this_axis) + { + standard_strike = this_standard_strike; + input_strike = this_input_strike; + normalization_strike = this_normlization_strike; + input_abstract_vol = this_input_abstract_vol; + point_type = this_point_type; + y_axis = this_axis; + } + + public double get_absolute_vol(double atm_vol) + { + return y_axis == Axis.Add ? atm_vol + input_abstract_vol : atm_vol * input_abstract_vol; + } + + /// Moves a point vertically - this could be done as part fo the total + /// curve move (is_full_vertical_move = true) or just a move of this point + public ControlPoint move_vertically(bool is_full_vertical_move, double atm_vol, double move) + { + double new_abstract_vol = Double.NaN; + if (is_full_vertical_move) + { + /// if the whole curve is moved vertically + /// the relative distance bw the cp + /// and atm remain the same + new_abstract_vol = input_abstract_vol; + } + else + { + if (y_axis == Axis.Add) + new_abstract_vol = input_abstract_vol + move; + else + new_abstract_vol = ((input_abstract_vol * atm_vol) + move) / atm_vol; + } + return new ControlPoint(standard_strike, input_strike, normalization_strike, new_abstract_vol, point_type, y_axis); + } + + public static double to_absolute_vol(double atm_vol, double input_abstract_vol, Axis y_axis) + { + return y_axis == Axis.Add ? atm_vol + input_abstract_vol : atm_vol * input_abstract_vol; + } + + public static double from_absolute_vol(double abs_vol, double atm_vol, Axis vol_axis) + { + return vol_axis == Axis.Add ? abs_vol - atm_vol : abs_vol / atm_vol; + } + } + + public class CoordinatesBasedModelInput + { + public double atm_vol; + public IEnumerable> put_points, call_points; + + public CoordinatesBasedModelInput(double this_atm_vol, IEnumerable> this_put_points, IEnumerable> this_call_points) + { + atm_vol = this_atm_vol; + put_points = this_put_points != null ? new List>(this_put_points) : new List>(); + call_points = this_put_points != null ? new List>(this_call_points) : new List>(); + } + } + + #region Translating between add and incremental axis + /// Both the coordinates based models convert the incremental + /// vol axis to simple add-on. These 2 functions help go back + /// and forth between the 2 + public static void convert_vol_axis_from_incremental_to_adds(VolSurfaceEnums.VolCurveStrikeAxis strike_axis, + IEnumerable> incremental_put_points, + IEnumerable> incremental_call_points, + out IEnumerable> add_put_points, + out IEnumerable> add_call_points) + { + incremental_put_points = VolSurfaceUtilityFunctions.sort_strikes_from_atm(incremental_put_points, false, strike_axis, (t => t.Item1)); + incremental_call_points = VolSurfaceUtilityFunctions.sort_strikes_from_atm(incremental_call_points, true, strike_axis, (t => t.Item1)); + List> rv_puts = new List>(), + rv_calls = new List>(); + foreach (Tuple p in incremental_put_points) + rv_puts.Add(Tuple.Create(p.Item1, p.Item2 + (rv_puts.Count == 0 ? 0 : rv_puts[rv_puts.Count - 1].Item2))); + foreach (Tuple c in incremental_call_points) + rv_calls.Add(Tuple.Create(c.Item1, c.Item2 + (rv_calls.Count == 0 ? 0 : rv_calls[rv_calls.Count - 1].Item2))); + add_put_points = rv_puts; add_call_points = rv_calls; + } + + public static void convert_vol_axis_adds_to_increments(VolSurfaceEnums.VolCurveStrikeAxis strike_axis, + IEnumerable> add_put_points, + IEnumerable> add_call_points, + out IEnumerable> incremental_put_points, + out IEnumerable> incremental_call_points) + { + add_put_points = VolSurfaceUtilityFunctions.sort_strikes_from_atm(add_put_points, false, strike_axis, (t => t.Item1)); + add_call_points = VolSurfaceUtilityFunctions.sort_strikes_from_atm(add_call_points, true, strike_axis, (t => t.Item1)); + List> rv_puts = new List>(), + rv_calls = new List>(); + foreach (Tuple p in add_put_points) + rv_puts.Add(Tuple.Create(p.Item1, rv_puts.Count == 0 ? p.Item2 : p.Item2 - add_put_points.ElementAt(rv_puts.Count - 1).Item2)); + foreach (Tuple c in add_call_points) + rv_calls.Add(Tuple.Create(c.Item1, rv_calls.Count == 0 ? c.Item2 : c.Item2 - add_call_points.ElementAt(rv_calls.Count - 1).Item2)); + incremental_put_points = rv_puts; incremental_call_points = rv_calls; + } + + /// Converts the calculated controlpoints into "adjusted" inputs. + /// Adjusted because of + /// a. Operations to the curve need to be reflected back + /// b. Rebuild need to be reflected back to the atm vol + /// c. Since for incremental we work in add-on mode, on the + /// way out values need to be converted back + public static void get_adjusted_parameters(IEnumerable calculated_controlpoints, + VolCurveCoreParameters exp_core_params, + VolSurfaceEnums.VolCurveVolAxis vol_axis, + VolSurfaceEnums.VolCurveStrikeAxis strike_axis, + double input_atm_vol, + double parallel_curve_move, + double volpath_move, + double live_fwd, + bool is_rebuild, + out double adjusted_atm_vol, + out IEnumerable> adjusted_put_points, + out IEnumerable> adjusted_call_points, + out double adjusted_ref_fwd, + out double adjusted_ref_vol) + { + IComparer comp = VolSurfaceUtilityFunctions.get_comparer( + (cp1, cp2) => + { + double d1 = Math.Abs(cp1.standard_strike), d2 = Math.Abs(cp2.standard_strike); + return (Double.IsNaN(d1) ? Double.PositiveInfinity : d1).CompareTo((Double.IsNaN(d2) ? Double.PositiveInfinity : d2)); + }); + adjusted_atm_vol = input_atm_vol + parallel_curve_move + (is_rebuild ? volpath_move : 0.0); + adjusted_put_points = calculated_controlpoints.Where(cp => cp.point_type == CoordinatesBasedModelHelper.ControlPoint.PointType.Put).OrderBy(cp => cp, comp).Select(cp => Tuple.Create(cp.input_strike, cp.input_abstract_vol)); + adjusted_call_points = calculated_controlpoints.Where(cp => cp.point_type == CoordinatesBasedModelHelper.ControlPoint.PointType.Call).OrderBy(cp => cp, comp).Select(cp => Tuple.Create(cp.input_strike, cp.input_abstract_vol)); + if (vol_axis == VolSurfaceEnums.VolCurveVolAxis.Incremental) + CoordinatesBasedModelHelper.convert_vol_axis_adds_to_increments(strike_axis, adjusted_put_points, adjusted_call_points, out adjusted_put_points, out adjusted_call_points); + adjusted_ref_fwd = is_rebuild ? live_fwd : exp_core_params.ref_forward; + adjusted_ref_vol = is_rebuild ? adjusted_atm_vol : exp_core_params.standard_vol; + } + #endregion + + /// Converts atm, call and put inputs to controlpoints + public static IEnumerable convert_to_controlpoints(VolSurfaceEnums.VolCurveVolAxis vol_axis, + VolSurfaceEnums.VolCurveStrikeAxis strike_axis, + VolSurfaceEnums.VolCurveStrikeAxis normalization_strike_axis, + IEnumerable> put_points, + IEnumerable> call_points, + Func convert_strike_axis) + { + if (vol_axis == VolSurfaceEnums.VolCurveVolAxis.Incremental) + { + IEnumerable> out_put_points, out_call_points; + convert_vol_axis_from_incremental_to_adds(strike_axis, put_points, call_points, out out_put_points, out out_call_points); + return convert_to_controlpoints(VolSurfaceEnums.VolCurveVolAxis.ATMAddin, strike_axis, normalization_strike_axis, out_put_points, out_call_points, convert_strike_axis); + } + else + { + List rv = new List(); + ControlPoint.Axis cp_axis = vol_axis == VolSurfaceEnums.VolCurveVolAxis.ATMAddin ? ControlPoint.Axis.Add : ControlPoint.Axis.Mult; + /// ATM + double atm_normalization_k = convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, 0.0, normalization_strike_axis); + rv.Add(new ControlPoint(0.0, Double.NaN, atm_normalization_k, cp_axis == ControlPoint.Axis.Add ? 0.0 : 1.0, ControlPoint.PointType.ATM, cp_axis)); + /// Puts + foreach (Tuple p in VolSurfaceUtilityFunctions.sort_strikes_from_atm(put_points, false, strike_axis, (t => t.Item1))) + { + double stand_k = convert_strike_axis(strike_axis, p.Item1, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike), + normalization_k = convert_strike_axis(strike_axis, p.Item1, normalization_strike_axis); + rv.Add(new ControlPoint(stand_k, p.Item1, normalization_k, p.Item2, ControlPoint.PointType.Put, cp_axis)); + } + /// Calls + foreach (Tuple c in VolSurfaceUtilityFunctions.sort_strikes_from_atm(call_points, true, strike_axis, (t => t.Item1))) + { + double stand_k = convert_strike_axis(strike_axis, c.Item1, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike), + normalization_k = convert_strike_axis(strike_axis, c.Item1, normalization_strike_axis); + rv.Add(new ControlPoint(stand_k, c.Item1, normalization_k, c.Item2, ControlPoint.PointType.Call, cp_axis)); + } + return rv.OrderBy (cp => cp.standard_strike); + } + } + + /// Converts the controlpoints strikes to the target axis + public static void get_controlpoint_strikes(IEnumerable controlpoints, + VolSurfaceEnums.VolCurveStrikeAxis target_axis, + Func convert_strike_axis, + out IEnumerable put_strikes, + out IEnumerable call_strikes) + { + IEnumerable put_controlpoints = controlpoints.Where(t => t.point_type == CoordinatesBasedModelHelper.ControlPoint.PointType.Put), + call_controlpoints = controlpoints.Where(t => t.point_type == CoordinatesBasedModelHelper.ControlPoint.PointType.Call); + put_strikes = put_controlpoints.Select(cp => convert_strike_axis (VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, cp.standard_strike, target_axis)); + call_strikes = call_controlpoints.Select(cp => convert_strike_axis (VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, cp.standard_strike, target_axis)); + put_strikes = VolSurfaceUtilityFunctions.sort_strikes_from_atm(put_strikes, false, target_axis, k => k); + call_strikes = VolSurfaceUtilityFunctions.sort_strikes_from_atm(call_strikes, true, target_axis, k => k); + } + + /// Fills the missing data from secondary to main + public static CoordinatesBasedModelInput fill_missing_input(CoordinatesBasedModelInput main, CoordinatesBasedModelInput secondary) + { + Log.assert(main.put_points.Count() == secondary.put_points.Count()); + Log.assert(main.call_points.Count() == secondary.call_points.Count()); + if (!Double.IsNaN(main.atm_vol) || main.put_points.Where(t => !Double.IsNaN(t.Item1)).Count() > 0 + || main.call_points.Where(t => !Double.IsNaN(t.Item1)).Count() > 0) + return main; + else + return new CoordinatesBasedModelInput(secondary.atm_vol, + _merge_coordinates(main.put_points, secondary.put_points), + _merge_coordinates(main.call_points, secondary.call_points)); + } + + private static IEnumerable> _merge_coordinates (IEnumerable> main_list, IEnumerable> sec_list) + { + Log.assert(main_list.Count() == sec_list.Count()); + List> rv = new List>(); + for (int i = 0; i < sec_list.Count(); i++) + { + Tuple sec_coord = sec_list.ElementAt(i), main_coord = main_list.ElementAt(i); + rv.Add(Tuple.Create(sec_coord.Item1, !Double.IsNaN(main_coord.Item2) ? main_coord.Item2 : sec_coord.Item2)); + } + return rv; + } + + public static void get_end_points(IEnumerable controlpoints, VolSurfaceEnums.VolCurveStrikeAxis axis, + Func convert_strike, + out double put_end_raw_strike, out double call_end_raw_strike) + { + put_end_raw_strike = call_end_raw_strike = Double.NaN; + if (controlpoints != null) + { + controlpoints = controlpoints.Where(i => i.point_type == ControlPoint.PointType.ATM || !Double.IsNaN(i.input_strike)); + controlpoints = controlpoints.OrderBy(i => i.standard_strike); + IEnumerable put_points = controlpoints.Where(cp => cp.point_type == CoordinatesBasedModelHelper.ControlPoint.PointType.Put), + call_points = controlpoints.Where(cp => cp.point_type == CoordinatesBasedModelHelper.ControlPoint.PointType.Call); + if (put_points != null && put_points.Count() > 0) + put_end_raw_strike = convert_strike(VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, put_points.ElementAt(0).standard_strike, axis); + if (call_points != null && call_points.Count() > 0) + call_end_raw_strike = convert_strike(VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, call_points.Last().standard_strike, axis); + } + } + + #region Actions + + public static VolCurveParameters update_atmvol(VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + double val, + bool increment = true) + { + curve_parameters = VolSurfaceUtilityFunctions.clone_proto(curve_parameters); + if (surface_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline) + curve_parameters.spline_model_parameters.atm_vol = increment ? curve_parameters.spline_model_parameters.atm_vol + val : val; + else if (surface_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Polynomial) + curve_parameters.polynomial_model_parameters.atm_vol = increment ? curve_parameters.polynomial_model_parameters.atm_vol + val : val; + return curve_parameters; + } + + + public static VolCurveParameters update_controlpoints(VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + IEnumerable> put_controlpoints, + IEnumerable> call_controlpoints) + { + curve_parameters = VolSurfaceUtilityFunctions.clone_proto(curve_parameters); + if (surface_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline) + { + curve_parameters.spline_model_parameters.put_points = put_controlpoints.ToList(); + curve_parameters.spline_model_parameters.call_points = call_controlpoints.ToList(); + } + else if (surface_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Polynomial) + { + curve_parameters.polynomial_model_parameters.put_points = put_controlpoints.ToList(); + curve_parameters.polynomial_model_parameters.call_points = call_controlpoints.ToList(); + } + return curve_parameters; + } + + public static VolCurveParameters update_controlpoints(VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + IEnumerable calculated_controlpoints) + { + curve_parameters = VolSurfaceUtilityFunctions.clone_proto(curve_parameters); + IComparer comp = VolSurfaceUtilityFunctions.get_comparer( + (cp1, cp2) => + { + double d1 = Math.Abs(cp1.standard_strike), d2 = Math.Abs(cp2.standard_strike); + return (Double.IsNaN(d1) ? Double.PositiveInfinity : d1).CompareTo((Double.IsNaN(d2) ? Double.PositiveInfinity : d2)); + }); + var adjusted_put_points = calculated_controlpoints.Where(cp => cp.point_type == CoordinatesBasedModelHelper.ControlPoint.PointType.Put).OrderBy(cp => cp, comp).Select(cp => Tuple.Create(cp.input_strike, cp.input_abstract_vol)); + var adjusted_call_points = calculated_controlpoints.Where(cp => cp.point_type == CoordinatesBasedModelHelper.ControlPoint.PointType.Call).OrderBy(cp => cp, comp).Select(cp => Tuple.Create(cp.input_strike, cp.input_abstract_vol)); + if (surface_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline) + { + curve_parameters.spline_model_parameters.put_points = adjusted_put_points.ToList(); + curve_parameters.spline_model_parameters.call_points = adjusted_call_points.ToList(); + } + else if (surface_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Polynomial) + { + curve_parameters.polynomial_model_parameters.put_points = adjusted_put_points.ToList(); + curve_parameters.polynomial_model_parameters.call_points = adjusted_call_points.ToList(); + } + return curve_parameters; + } + + public static VolCurveParameters update_on_rebuild(VolSurfaceSettings surface_settings, VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data) + + { + curve_parameters = VolSurfaceUtilityFunctions.clone_proto(curve_parameters); + curve_parameters.core_parameters.ref_forward = aux_data.fwd; + if (surface_settings.core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline) + curve_parameters.core_parameters.standard_vol = curve_parameters.spline_model_parameters.atm_vol; + else + curve_parameters.core_parameters.standard_vol = curve_parameters.polynomial_model_parameters.atm_vol; + return curve_parameters; + } + + public static VolCurveAction clean_action(VolCurveAction curve_action) + { + curve_action = curve_action ?? new VolCurveAction(VolCurveAction.ActionType.None); + if (curve_action.action_type == VolCurveAction.ActionType.FitToMarket) + if (curve_action.market_fit_action == null || !VolSurfaceCoreFunctions.is_suitable_for_fit(curve_action.market_fit_action.implied_vol_data)) + curve_action = new VolCurveAction(VolCurveAction.ActionType.None); + return curve_action; + } + + /// Linearly rotates the control points along the 0 standard strike + /// (Note this is using the standard strike to rotate points) + public static IEnumerable apply_action(IEnumerable control_points, VolCurveMovementOperation curve_action, double atm_vol) + { + if (control_points != null && control_points.Count() > 0 && VolSurfaceUtilityFunctions.is_shape_move_included(curve_action)) + { + double atm_standard_strike = 0.0; + IDictionary move_map = VolSurfaceCoreFunctions.linear_rotate_points(new HashSet(control_points.Select(cp => cp.standard_strike)), + atm_standard_strike, curve_action.strike_vol_movement_pairs); + List rv_control_points = new List(); + foreach (ControlPoint cp in control_points) + { + double move = move_map.TryGetValue(cp.standard_strike, out move) ? move : 0.0; + rv_control_points.Add(cp.move_vertically(false, atm_vol, move)); + } + return rv_control_points; + } + return control_points; + } + + public static IEnumerable fit_to_market(VolCurveMarketImpliedVolData implied_vol_data, + VolSurfaceExpirationAuxiliaryData aux_data, + VolSurfaceMarketFitSettings marketfit_settings, + VolSurfaceEnums.VolCurveVolAxis vol_axis, + VolSurfaceEnums.VolCurveStrikeAxis strike_axis, + VolSurfaceEnums.VolCurveStrikeAxis strike_normalization_axis, + Func convert_strike_axis, + IEnumerable> put_points, IEnumerable> call_points, + bool use_weighted_regression_fit) + { + if (use_weighted_regression_fit) + return _regression_fit_to_market(implied_vol_data, aux_data, marketfit_settings, vol_axis, strike_axis, strike_normalization_axis, convert_strike_axis, put_points, call_points); + else + return _direct_fit_to_market(implied_vol_data, aux_data, marketfit_settings, vol_axis, strike_axis, strike_normalization_axis, convert_strike_axis, put_points, call_points); + } + + + private static IEnumerable _regression_fit_to_market(VolCurveMarketImpliedVolData implied_vol_data, + VolSurfaceExpirationAuxiliaryData aux_data, + VolSurfaceMarketFitSettings marketfit_settings, + VolSurfaceEnums.VolCurveVolAxis vol_axis, + VolSurfaceEnums.VolCurveStrikeAxis strike_axis, + VolSurfaceEnums.VolCurveStrikeAxis strike_normalization_axis, + Func convert_strike_axis, + IEnumerable> put_control_points, IEnumerable> call_control_points) + { + implied_vol_data = _filter_for_wings(implied_vol_data, strike_axis, convert_strike_axis, put_control_points, call_control_points); + ControlPoint.Axis cp_axis = vol_axis == VolSurfaceEnums.VolCurveVolAxis.ATMFactor ? ControlPoint.Axis.Mult : ControlPoint.Axis.Add; + IEnumerable regression_coeffs = VolSurfaceCoreFunctions.get_implied_vol_regression_curve(implied_vol_data, marketfit_settings.regression_order, + x => 1 / Math.Max(Double.Epsilon, Math.Abs(x))); + List rv = new List(); + double atm_std_k = 0, atm_input_k = convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, 0.0, strike_axis), + atm_normalization_k = convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, 0.0, strike_normalization_axis); + rv.Add(new ControlPoint(atm_std_k, atm_input_k, atm_normalization_k, cp_axis == ControlPoint.Axis.Add ? 0.0 : 1.0, ControlPoint.PointType.ATM, cp_axis)); + IEnumerable> all_points = Enumerable.Concat(put_control_points.Select (t => Tuple.Create (ControlPoint.PointType.Put, t.Item1, t.Item2)), + call_control_points.Select (t => Tuple.Create (ControlPoint.PointType.Call, t.Item1, t.Item2))); + foreach (Tuple t in all_points) + { + double std_k = convert_strike_axis(strike_axis, t.Item2, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike); + double normalization_k = convert_strike_axis(strike_axis, t.Item2, strike_normalization_axis); + double vol = VolSurfaceCoreFunctions.compute_polynomial_df(regression_coeffs.ToArray(), std_k); + double y_axis_vol = ControlPoint.from_absolute_vol(vol, implied_vol_data.atm_vol, cp_axis); + rv.Add(new ControlPoint(std_k, t.Item2, normalization_k, y_axis_vol, t.Item1, cp_axis)); + } + return rv; + } + + private static IEnumerable _direct_fit_to_market(VolCurveMarketImpliedVolData implied_vol_data, + VolSurfaceExpirationAuxiliaryData aux_data, + VolSurfaceMarketFitSettings marketfit_settings, + VolSurfaceEnums.VolCurveVolAxis vol_axis, + VolSurfaceEnums.VolCurveStrikeAxis strike_axis, + VolSurfaceEnums.VolCurveStrikeAxis strike_normalization_axis, + Func convert_strike_axis, + IEnumerable> put_control_points, IEnumerable> call_control_points) + { + ControlPoint.Axis cp_axis = vol_axis == VolSurfaceEnums.VolCurveVolAxis.ATMFactor ? ControlPoint.Axis.Mult : ControlPoint.Axis.Add; + double atm_std_k = 0, atm_input_k = convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, 0.0, strike_axis), + atm_normalization_k = convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike, 0.0, strike_normalization_axis); + ControlPoint atm_point = new ControlPoint(atm_std_k, atm_input_k, atm_normalization_k, cp_axis == ControlPoint.Axis.Add ? 0.0 : 1.0, ControlPoint.PointType.ATM, cp_axis); + if (vol_axis == VolSurfaceEnums.VolCurveVolAxis.Incremental) + convert_vol_axis_from_incremental_to_adds(strike_axis, put_control_points, call_control_points, out put_control_points, out call_control_points); + List rv = new List(Enumerable.Range(0, 1).Select(i => atm_point)); + foreach (Tuple p in put_control_points) + { + double std_k = convert_strike_axis(strike_axis, p.Item1, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike), + normalization_k = convert_strike_axis(strike_axis, p.Item1, strike_normalization_axis), + md_implied_vol = VolSurfaceCoreFunctions.find_std_k_vol(implied_vol_data, std_k); + /// if market is absent at this x, we dont try to fit it + md_implied_vol = !Double.IsNaN (md_implied_vol) ? md_implied_vol : ControlPoint.to_absolute_vol(implied_vol_data.atm_vol, p.Item2, cp_axis); + rv.Add(new ControlPoint(std_k, p.Item1, normalization_k, ControlPoint.from_absolute_vol(md_implied_vol, implied_vol_data.atm_vol, cp_axis), ControlPoint.PointType.Put, cp_axis)); + } + foreach (Tuple c in call_control_points) + { + double std_k = convert_strike_axis (strike_axis, c.Item1, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike), + normalization_k = convert_strike_axis(strike_axis, c.Item1, strike_normalization_axis), + md_implied_vol = VolSurfaceCoreFunctions.find_std_k_vol(implied_vol_data, std_k); + md_implied_vol = !Double.IsNaN(md_implied_vol) ? md_implied_vol : ControlPoint.to_absolute_vol(implied_vol_data.atm_vol, c.Item2, cp_axis); + rv.Add(new ControlPoint(std_k, c.Item1, normalization_k, ControlPoint.from_absolute_vol(md_implied_vol, implied_vol_data.atm_vol, cp_axis), ControlPoint.PointType.Call, cp_axis)); + } + return rv; + } + + private static VolCurveMarketImpliedVolData _filter_for_wings(VolCurveMarketImpliedVolData implied_vol_data, + VolSurfaceEnums.VolCurveStrikeAxis strike_axis, + Func convert_strike_axis, + IEnumerable> put_control_points, IEnumerable> call_control_points) + { + var raw_k_puts = put_control_points.Select(t => convert_strike_axis(strike_axis, t.Item1, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike)); + var raw_k_calls = call_control_points.Select(t => convert_strike_axis(strike_axis, t.Item1, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike)); + double put_end_point = raw_k_puts.Where(p => !Double.IsNaN(p)).Min(), call_end_point = raw_k_calls.Where(c => !Double.IsNaN(c)).Max(); + + return VolSurfaceCoreFunctions.filter_for_ends(implied_vol_data, Tuple.Create(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, put_end_point), + Tuple.Create(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, call_end_point)); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/PolynomialModel/PolynomialModelVolCurveCalculator.cs b/src/client/spark/Analytics/PolynomialModel/PolynomialModelVolCurveCalculator.cs new file mode 100644 index 000000000..baeb369da --- /dev/null +++ b/src/client/spark/Analytics/PolynomialModel/PolynomialModelVolCurveCalculator.cs @@ -0,0 +1,245 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class PolynomialModelVolCurveCalculator : IVolCurveMainCalculator + { + private VolSurfaceSettings _vs_settings; + private VolCurveParameters _input_parameters; + private VolCurveAction _action; + private VolSurfaceExpirationAuxiliaryData _aux_data; + private IEnumerable _control_points; + private ExactFitPolynomial _exactfit_polynomial; + /// we dont necessarily have to keep _adjusted_parameters + /// and _curve_output in the state, and compute them + /// when compute_output is called; _adjusted_parameters is + /// not used as in an input to any further + /// calculations + private VolCurveParameters _adjusted_parameters; + private double _final_unresponded_atm_vol = Double.NaN, _final_reponded_atm_vol = Double.NaN; + private CoordinatesBasedModelHelper.ControlPoint.Axis _cp_axis; + + private bool _initialized = true; + + #region IVolCurveMainCalculator + + public void initialize_for_lifetime(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action) + { + _vs_settings = surface_settings; + _input_parameters = curve_parameters; + _action = curve_action; + path_induced_atm_vol_move = Double.IsNaN(path_induced_atm_vol_move) ? 0.0 : path_induced_atm_vol_move; + _aux_data = aux_data; + _initialized = _can_compute(curve_parameters, _aux_data.fwd, path_induced_atm_vol_move); + curve_action = CoordinatesBasedModelHelper.clean_action(curve_action); + if (_initialized) + { + if (curve_action.action_type != VolCurveAction.ActionType.FitToMarket) + { + VolCurveMovementOperation movement_action = curve_action.curve_operation; + movement_action = VolSurfaceCoreFunctions.normalize_atm_move_action(movement_action, curve_parameters.polynomial_model_parameters.atm_vol + path_induced_atm_vol_move, aux_data, _get_conversion_fwd()); + double atm_vol_action_move = movement_action == null ? 0.0 : VolSurfaceUtilityFunctions.find_atm_vol_move(movement_action); + _final_unresponded_atm_vol = curve_parameters.polynomial_model_parameters.atm_vol + atm_vol_action_move; + _final_reponded_atm_vol = _final_unresponded_atm_vol + path_induced_atm_vol_move; + _control_points = CoordinatesBasedModelHelper.convert_to_controlpoints(surface_settings.polynomial_model_settings.vol_axis, + surface_settings.polynomial_model_settings.strike_axis, + surface_settings.advanced_settings.strike_normalization_axis, + curve_parameters.polynomial_model_parameters.put_points, + curve_parameters.polynomial_model_parameters.call_points, + _convert_strike_axis); + _cp_axis = _control_points != null && _control_points.Count() > 0 ? _control_points.ElementAt(0).y_axis : CoordinatesBasedModelHelper.ControlPoint.Axis.Mult; + _exactfit_polynomial = _get_polynomial(_control_points); + movement_action = VolSurfaceCoreFunctions.normalize_shape_action(movement_action, _aux_data, _convert_strike_axis, + (strike, axis) => _compute_vol(strike, axis)); + _control_points = CoordinatesBasedModelHelper.apply_action(_control_points, movement_action, curve_parameters.polynomial_model_parameters.atm_vol + path_induced_atm_vol_move); + _adjusted_parameters = _get_adjusted_parameters(_control_points, surface_settings, curve_parameters, _aux_data, atm_vol_action_move, path_induced_atm_vol_move, curve_action.action_type == VolCurveAction.ActionType.Rebuild); + _exactfit_polynomial = _get_polynomial (_control_points); + } + else + { + VolCurveMarketFitAction market_fit_action = curve_action.market_fit_action; + if (market_fit_action != null && market_fit_action.implied_vol_data != null) + { + /// atm_vol get adjusted to market's atm vol in all market fit scenarios + _final_reponded_atm_vol = _final_unresponded_atm_vol = market_fit_action.implied_vol_data.atm_vol; + if (market_fit_action.fit_action == VolCurveMarketFitAction.ActionType.FitATM) + _control_points = CoordinatesBasedModelHelper.convert_to_controlpoints(surface_settings.polynomial_model_settings.vol_axis, + surface_settings.polynomial_model_settings.strike_axis, + surface_settings.advanced_settings.strike_normalization_axis, + curve_parameters.polynomial_model_parameters.put_points, + curve_parameters.polynomial_model_parameters.call_points, + _convert_strike_axis); + else if (market_fit_action.fit_action == VolCurveMarketFitAction.ActionType.FitWholeCurve) + _control_points = CoordinatesBasedModelHelper.fit_to_market(market_fit_action.implied_vol_data, + _aux_data, + surface_settings.core_settings.market_fit_settings, + surface_settings.polynomial_model_settings.vol_axis, + surface_settings.polynomial_model_settings.strike_axis, + surface_settings.advanced_settings.strike_normalization_axis, + _convert_strike_axis, + curve_parameters.polynomial_model_parameters.put_points, + curve_parameters.polynomial_model_parameters.call_points, + market_fit_action.use_weighted_regression); + _cp_axis = _control_points != null && _control_points.Count() > 0 ? _control_points.ElementAt(0).y_axis : CoordinatesBasedModelHelper.ControlPoint.Axis.Mult; + _adjusted_parameters = _get_adjusted_parameters(_control_points, surface_settings, curve_parameters, _aux_data, _final_reponded_atm_vol - curve_parameters.polynomial_model_parameters.atm_vol, 0, true); + _exactfit_polynomial = _get_polynomial(_control_points); + } + } + } + else + _adjusted_parameters = curve_parameters; + } + + public bool is_initialized() { return _initialized; } + + public VolCurveParameters fill_missing_inputs(VolCurveParameters main_curve_params, VolCurveParameters sec_curve_params) + { + CoordinatesBasedModelHelper.CoordinatesBasedModelInput main_inp = new CoordinatesBasedModelHelper.CoordinatesBasedModelInput(main_curve_params.polynomial_model_parameters.atm_vol, main_curve_params.polynomial_model_parameters.put_points, main_curve_params.polynomial_model_parameters.call_points), + sec_inp = new CoordinatesBasedModelHelper.CoordinatesBasedModelInput(sec_curve_params.polynomial_model_parameters.atm_vol, sec_curve_params.polynomial_model_parameters.put_points, sec_curve_params.polynomial_model_parameters.call_points); + CoordinatesBasedModelHelper.CoordinatesBasedModelInput res_inp = CoordinatesBasedModelHelper.fill_missing_input(main_inp, sec_inp); + VolCurveParameters rv = VolSurfaceUtilityFunctions.clone_proto(main_curve_params); + rv.polynomial_model_parameters = new PolynomialModelVolCurveParameters() { atm_vol = res_inp.atm_vol, put_points = res_inp.put_points.ToList(), call_points = res_inp.call_points.ToList() }; + return rv; + } + + public VolCurveMainOutput get_output() + { + if (_initialized) + { + double input_atm_vol = _final_unresponded_atm_vol, final_atm_vol = _final_reponded_atm_vol; + IEnumerable cp_put_strikes, cp_call_strikes; + CoordinatesBasedModelHelper.get_controlpoint_strikes(_control_points, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, _convert_strike_axis, out cp_put_strikes, out cp_call_strikes); + double put_end_raw_strike, call_end_raw_strike; + CoordinatesBasedModelHelper.get_end_points(_control_points, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, _convert_strike_axis, out put_end_raw_strike, out call_end_raw_strike); + return new VolCurveMainOutput(_aux_data.fwd, + _get_conversion_fwd(), + input_atm_vol, + final_atm_vol, + _get_conversion_vol(), + cp_put_strikes, + cp_call_strikes, + put_end_raw_strike, + call_end_raw_strike, + _adjusted_parameters, + _aux_data, + _compute_vol, + _convert_strike_axis); + } + else + return new VolCurveMainOutput(Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Enumerable.Empty(), Enumerable.Empty(), + Double.NaN, Double.NaN, + _adjusted_parameters, _aux_data, (k, k_axis, nth_derv) => Double.NaN, + (source_axis, k, target_axis) => Double.NaN); + } + + public void Dispose() { } + + #endregion + + private double _compute_vol(double strike, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, uint nth_derv = 0) + { + if (_initialized) + { + if (nth_derv == 0) + { + double x = _convert_strike_axis(strike_axis, strike, _vs_settings.advanced_settings.strike_normalization_axis); + double fn = _exactfit_polynomial.compute_df(x, 0); + return _cp_axis == CoordinatesBasedModelHelper.ControlPoint.Axis.Add ? fn + _final_reponded_atm_vol : fn * _final_reponded_atm_vol; + } + else + return VolSurfaceCoreFunctions.compute_df(strike_arg => _compute_vol(strike_arg, strike_axis), strike, VolSurfaceCoreFunctions.DerivativeType.CenteredDifference, nth_derv); + } + else + return Double.NaN; + } + + private double _convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolCurveStrikeAxis target_axis) + { + return VolSurfaceCoreFunctions.convert_axis(source_axis, source_point, target_axis, + _get_conversion_vol(), _get_conversion_fwd(), _aux_data.biz_t, _aux_data.cal_t, _aux_data.riskless_rate); + } + + private double _get_conversion_vol() + { + if (_vs_settings.core_settings.strike_conversion_vol == VolSurfaceEnums.StrikeConversionVol.StandardVol) return _input_parameters.core_parameters.standard_vol; + else + { + if (VolSurfaceUtilityFunctions.is_rebuild_action(_action)) + return _final_reponded_atm_vol; + else + { + double conv_vol_slider = _input_parameters.core_parameters.conversion_vol_slider; + conv_vol_slider = Double.IsNaN(conv_vol_slider) ? 0.0 : VolSurfaceUtilityFunctions.restrict_bw_min_and_max(conv_vol_slider, 0.0, 1.0); + return (conv_vol_slider * _final_reponded_atm_vol) + ((1 - conv_vol_slider) * _final_unresponded_atm_vol); + } + } + } + + private double _get_conversion_fwd() + { + if (VolSurfaceUtilityFunctions.is_rebuild_action(_action)) + return _aux_data.fwd; + else + { + double conv_fwd_slider = _input_parameters.core_parameters.conversion_fwd_slider; + conv_fwd_slider = Double.IsNaN(conv_fwd_slider) ? 0.0 : VolSurfaceUtilityFunctions.restrict_bw_min_and_max(conv_fwd_slider, 0.0, 1.0); + /// the 1.0 check is just so that users who dont want to deal with ref_fwd's can leave it + /// unattended and we dont run into a NaN situation + return VolSurfaceUtilityFunctions.compare_doubles(conv_fwd_slider, 1.0) ? _aux_data.fwd : (conv_fwd_slider * _aux_data.fwd) + ((1 - conv_fwd_slider) * _input_parameters.core_parameters.ref_forward); + } + } + + private static ExactFitPolynomial _get_polynomial(IEnumerable control_points) + { + IEnumerable> coords = control_points.Select(cp => Tuple.Create(cp.normalization_strike, cp.input_abstract_vol)); + coords = coords.Where(t => !Double.IsNaN(t.Item1) && !Double.IsNaN(t.Item2)); + return new ExactFitPolynomial(coords); + } + + /// Return true is curve_parameters.polynomial_model_parameters + /// has an ATM vol, and atleast one call and put point + private static bool _can_compute(VolCurveParameters curve_parameters, double current_fwd, double path_induced_atm_vol_move) + { + return !Double.IsNaN(current_fwd) && + !Double.IsNaN(path_induced_atm_vol_move) && + curve_parameters != null && + curve_parameters.polynomial_model_parameters != null && + !Double.IsNaN(curve_parameters.polynomial_model_parameters.atm_vol) && + curve_parameters.polynomial_model_parameters.put_points.Where(t => !Double.IsNaN(t.Item1) && !Double.IsNaN(t.Item2)).Count() > 0 && + curve_parameters.polynomial_model_parameters.call_points.Where(t => !Double.IsNaN(t.Item1) && !Double.IsNaN(t.Item2)).Count() > 0; + } + + + private static VolCurveParameters _get_adjusted_parameters(IEnumerable controlpoints, + VolSurfaceSettings settings, + VolCurveParameters input_curve_paramaters, + VolSurfaceExpirationAuxiliaryData aux_data, + double parallel_curve_move, + double volpath_move, + bool is_rebuild) + { + double adjusted_atm_vol; + IEnumerable> adjusted_put_points, adjusted_call_points; + double adjusted_ref_fwd, adjusted_ref_vol; + CoordinatesBasedModelHelper.get_adjusted_parameters(controlpoints, input_curve_paramaters.core_parameters, settings.polynomial_model_settings.vol_axis, settings.polynomial_model_settings.strike_axis, + input_curve_paramaters.polynomial_model_parameters.atm_vol, parallel_curve_move, volpath_move, aux_data.fwd, is_rebuild, + out adjusted_atm_vol, out adjusted_put_points, out adjusted_call_points, out adjusted_ref_fwd, out adjusted_ref_vol); + VolCurveParameters rv = new VolCurveParameters() + { + core_parameters = input_curve_paramaters.core_parameters, + polynomial_model_parameters = new PolynomialModelVolCurveParameters() { atm_vol = adjusted_atm_vol, put_points = adjusted_put_points.ToList(), call_points = adjusted_call_points.ToList() } + }; + rv.core_parameters.ref_forward = adjusted_ref_fwd; + return rv; + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/PolynomialModel/PolynomialModelVolCurveParameters.cs b/src/client/spark/Analytics/PolynomialModel/PolynomialModelVolCurveParameters.cs new file mode 100644 index 000000000..96660c392 --- /dev/null +++ b/src/client/spark/Analytics/PolynomialModel/PolynomialModelVolCurveParameters.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// + /// This defines the meat of the curve (for a single exp), + /// ie the characterstics of the curve defined strictly + /// by the model only (the attempt is to treat the wings, + /// vol path, shifts seperately in a general model + /// independent way). + /// + [ProtoBuf.ProtoContract(Name = "PolynomialModelVolCurveParameters")] + public class PolynomialModelVolCurveParameters + { + [ProtoBuf.ProtoMember(10)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double atm_vol = Double.NaN; + [ProtoBuf.ProtoMember(20)] + public List> put_points; + [ProtoBuf.ProtoMember(30)] + public List> call_points; + + // public static explicit operator PolynomialModelVolCurveParameters(bts.api.analytics.APIPolynomialModelVolCurveParameters other) + // { + // var data = new PolynomialModelVolCurveParameters + // { + // atm_vol = other.atm_vol, + // }; + // data.call_points = other.call_points.Select((x, i) => Tuple.Create(x, other.call_factors[i])).ToList(); + // data.put_points = other.put_points.Select((x, i) => Tuple.Create(x, other.put_factors[i])).ToList(); + // return data; + // } + + // public static explicit operator bts.api.analytics.APIPolynomialModelVolCurveParameters(PolynomialModelVolCurveParameters other) + // { + // var data = new bts.api.analytics.APIPolynomialModelVolCurveParameters + // { + // atm_vol = other.atm_vol, + // put_points = other.put_points.Select(x => x.Item1).ToArray(), + // put_factors = other.put_points.Select(x => x.Item2).ToArray(), + // call_points = other.call_points.Select(x => x.Item1).ToArray(), + // call_factors = other.call_points.Select(x => x.Item2).ToArray(), + // }; + // return data; + // } + } +} diff --git a/src/client/spark/Analytics/PolynomialModel/PolynomialModelVolSurfaceSettings.cs b/src/client/spark/Analytics/PolynomialModel/PolynomialModelVolSurfaceSettings.cs new file mode 100644 index 000000000..47b76d86a --- /dev/null +++ b/src/client/spark/Analytics/PolynomialModel/PolynomialModelVolSurfaceSettings.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract (Name="PolynomialModelVolSurfaceSettings")] + public class PolynomialModelVolSurfaceSettings + { + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.VolCurveStrikeAxis strike_axis; + [ProtoBuf.ProtoMember(20)] + public VolSurfaceEnums.VolCurveVolAxis vol_axis; + /// if (n_call_points + n_put_points > 5), the + /// polynomial will not be an exact fit + [ProtoBuf.ProtoMember(30)] + public uint n_call_points; + [ProtoBuf.ProtoMember(40)] + public uint n_put_points; + [ProtoBuf.ProtoMember(50)] + public List put_points; + [ProtoBuf.ProtoMember(60)] + public List call_points; + [ProtoBuf.ProtoMember(70)] + public bool same_across_all_exps; + } +} diff --git a/src/client/spark/Analytics/Pricing/Theos.cs b/src/client/spark/Analytics/Pricing/Theos.cs new file mode 100644 index 000000000..e37255f9c --- /dev/null +++ b/src/client/spark/Analytics/Pricing/Theos.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [Serializable] + [ProtoBuf.ProtoContract] + // [ProtoBuf.ProtoInclude(1000, typeof(SplineTheos))] + // [ProtoBuf.ProtoInclude(1010, typeof(SlideTheos))] + public class Theos + { + [ProtoBuf.ProtoMember(10)] + public double strike; + [ProtoBuf.ProtoMember(20)] + public double driver; + [ProtoBuf.ProtoMember(30)] + public double move; + [ProtoBuf.ProtoMember(40)] + public double fwd; + [ProtoBuf.ProtoMember(50)] + public double bizt; + + [ProtoBuf.ProtoMember(60)] + public double call; + [ProtoBuf.ProtoMember(70)] + public double put; + [ProtoBuf.ProtoMember(80)] + public double cdelta; + [ProtoBuf.ProtoMember(90)] + public double pdelta; + [ProtoBuf.ProtoMember(100)] + public double cvega; + [ProtoBuf.ProtoMember(110)] + public double pvega; + [ProtoBuf.ProtoMember(120)] + public double cgamma; + [ProtoBuf.ProtoMember(130)] + public double pgamma; + [ProtoBuf.ProtoMember(140)] + public double vol; + + [ProtoBuf.ProtoMember(150)] + public float cadjvega; + [ProtoBuf.ProtoMember(160)] + public float padjvega; + [ProtoBuf.ProtoMember(170)] + public float copts; + [ProtoBuf.ProtoMember(180)] + public float popts; + [ProtoBuf.ProtoMember(190)] + public float cadjtheta; + [ProtoBuf.ProtoMember(200)] + public float padjtheta; + [ProtoBuf.ProtoMember(210)] + public float crollrho; + [ProtoBuf.ProtoMember(220)] + public float prollrho; + [ProtoBuf.ProtoMember(230)] + public float cdiscrho; + [ProtoBuf.ProtoMember(240)] + public float pdiscrho; + [ProtoBuf.ProtoMember(250)] + public float cvoltheta; + [ProtoBuf.ProtoMember(260)] + public float pvoltheta; + [ProtoBuf.ProtoMember(270)] + public float cslopevega; + [ProtoBuf.ProtoMember(280)] + public float pslopevega; + [ProtoBuf.ProtoMember(290)] + public float ccurvvega; + [ProtoBuf.ProtoMember(300)] + public float pcurvvega; + [ProtoBuf.ProtoMember(310)] + public float cputtailvega; + [ProtoBuf.ProtoMember(320)] + public float pputtailvega; + [ProtoBuf.ProtoMember(330)] + public float ccalltailvega; + [ProtoBuf.ProtoMember(340)] + public float pcalltailvega; + [ProtoBuf.ProtoMember(350)] + public float cdeltableed; + [ProtoBuf.ProtoMember(360)] + public float pdeltableed; + [ProtoBuf.ProtoMember(370)] + public float cvanna; + [ProtoBuf.ProtoMember(380)] + public float pvanna; + [ProtoBuf.ProtoMember(390)] + public float cvolga; + [ProtoBuf.ProtoMember(400)] + public float pvolga; + + [ProtoBuf.ProtoMember(410)] + public float cdeltanovr; + [ProtoBuf.ProtoMember(420)] + public float pdeltanovr; + [ProtoBuf.ProtoMember(430)] + public float gammanovr; + [ProtoBuf.ProtoMember(440)] + public float veganovr; + [ProtoBuf.ProtoMember(450)] + public float optsnovr; + + [ProtoBuf.ProtoMember(460)] + public float cparitydelta; + [ProtoBuf.ProtoMember(470)] + public float pparitydelta; + [ProtoBuf.ProtoMember(480)] + public float ctimevalue; + [ProtoBuf.ProtoMember(490)] + public float ptimevalue; + [ProtoBuf.ProtoMember(500)] + public float ceeadj; + [ProtoBuf.ProtoMember(510)] + public float peeadj; + [ProtoBuf.ProtoMember(520)] + public double standard_strike; + [ProtoBuf.ProtoMember(530)] + public float dvol_dund; + [ProtoBuf.ProtoMember(540)] + public float d2vol_dund2; + [ProtoBuf.ProtoMember(550)] + public double expiration; + [ProtoBuf.ProtoMember(560)] + public float source_expiration; + [ProtoBuf.ProtoMember(570)] + public float cflatvoldelta; + [ProtoBuf.ProtoMember(580)] + public float pflatvoldelta; + }; + + + // [Serializable] + // [ProtoBuf.ProtoContract] + // public class SplineTheos : Theos + // { + // } + + // [Serializable] + // [ProtoBuf.ProtoContract] + // public class SlideTheos : Theos + // { + // } +} diff --git a/src/client/spark/Analytics/Pricing/VolMatrix.cs b/src/client/spark/Analytics/Pricing/VolMatrix.cs new file mode 100644 index 000000000..a7aa86d6a --- /dev/null +++ b/src/client/spark/Analytics/Pricing/VolMatrix.cs @@ -0,0 +1,432 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [Serializable] + [ProtoBuf.ProtoContract] + // [ProtoBuf.ProtoInclude(1000, typeof(SplineVolMatrix))] + // [ProtoBuf.ProtoInclude(1010, typeof(SlideVolMatrix))] + public class VolMatrix + { + [ProtoBuf.ProtoMember(10)] + public double strike; + [ProtoBuf.ProtoMember(20)] + public double spot; + [ProtoBuf.ProtoMember(30)] + public double fwd; + [ProtoBuf.ProtoMember(40)] + public double bizt; + [ProtoBuf.ProtoMember(50)] + public double calt; + [ProtoBuf.ProtoMember(60)] + public double growth; + [ProtoBuf.ProtoMember(70)] + public double riskless; + [ProtoBuf.ProtoMember(80)] + public double driver; + [ProtoBuf.ProtoMember(90)] + public double ref_price; + [ProtoBuf.ProtoMember(100)] + public double driver_move; + + [ProtoBuf.ProtoMember(110)] + public double rho_inc; + [ProtoBuf.ProtoMember(120)] + public double delta_inc; + [ProtoBuf.ProtoMember(130)] + public double vega_inc; + [ProtoBuf.ProtoMember(140)] + public double vega_factor; + [ProtoBuf.ProtoMember(150)] + public double typical_vega; + [ProtoBuf.ProtoMember(160)] + public double theta_inc; + [ProtoBuf.ProtoMember(170)] + public double dspot_dund; + [ProtoBuf.ProtoMember(180)] + public double dfwd_dund; + + [ProtoBuf.ProtoMember(190)] + public double vol; /// vol at fwd + [ProtoBuf.ProtoMember(200)] + public double vol_up; /// vol at fwd_up + [ProtoBuf.ProtoMember(210)] + public double vol_dn; /// vol at fwd_down + [ProtoBuf.ProtoMember(220)] + public double vol_t; /// vol tomorrow (ie vol at t_up) + [ProtoBuf.ProtoMember(230)] + public double vol_volup; /// vol at atmvol_up + [ProtoBuf.ProtoMember(240)] + public double vol_voldn; /// vol at atmvol_down + + [ProtoBuf.ProtoMember(250)] + public double vol_slope; + [ProtoBuf.ProtoMember(260)] + public double vol_curv; + [ProtoBuf.ProtoMember(270)] + public double vol_pt; + [ProtoBuf.ProtoMember(280)] + public double vol_ct; + + [ProtoBuf.ProtoMember(290)] + public double ceeadj; + [ProtoBuf.ProtoMember(300)] + public double peeadj; + [ProtoBuf.ProtoMember(310)] + // TODO, looks whats up + //public PricingModel model; + public VolSurfaceEnums.VolSurfacePricingModel model; + [ProtoBuf.ProtoMember(320)] + public double delta_divisor; + [ProtoBuf.ProtoMember(330)] + public double vol_t_up; /// v at t_up, fwd_up + [ProtoBuf.ProtoMember(340)] + public double vol_t_dn; /// v at t_up, fwd_down + [ProtoBuf.ProtoMember(350)] + public double d1; + [ProtoBuf.ProtoMember(360)] + public double d2; + [ProtoBuf.ProtoMember(370)] + public double atmvol; + [ProtoBuf.ProtoMember(380)] + public double standard_strike; + [ProtoBuf.ProtoMember(390)] + public double expiration; + [ProtoBuf.ProtoMember(400)] + public double price_bias; + [ProtoBuf.ProtoMember(410)] + public double conversion_vol; + [ProtoBuf.ProtoMember(420)] + public double conversion_fwd; + [ProtoBuf.ProtoMember(500)] + public bool shape_greeks_in_price_terms; + + + public virtual T clone() where T: VolMatrix + { + return (T)this.MemberwiseClone(); + } + + static public T[] clone_array(T[] from) where T : VolMatrix + { + var vm = new T[from.Length]; + for(int i = 0; i < vm.Length; i++) + vm[i] = from[i].clone(); + return vm; + } + + // public static explicit operator bts.api.analytics.VolMatrix(VolMatrix m) + // { + // return new bts.api.analytics.VolMatrix() + // { + // atmvol = m.atmvol, + // bizt = m.bizt, + // calt = m.calt, + // ceeadj = m.ceeadj, + // d1 = m.d1, + // d2 = m.d2, + // delta_divisor = m.delta_divisor, + // delta_inc = m.delta_inc, + // dfwd_dund = m.dfwd_dund, + // driver = m.driver, + // driver_move = m.driver_move, + // dspot_dund = m.dspot_dund, + // expiration = m.expiration, + // fwd = m.fwd, + // growth = m.growth, + // model = (bts.api.analytics.PricingModel.type) m.model, + // peeadj = m.peeadj, + // price_bias = m.price_bias, + // ref_price = m.ref_price, + // rho_inc = m.rho_inc, + // riskless = m.riskless, + // spot = m.spot, + // standard_strike = m.standard_strike, + // strike = m.strike, + // theta_inc = m.theta_inc, + // typical_vega = m.typical_vega, + // vega_factor = m.vega_factor, + // vega_inc = m.vega_inc, + // vol = m.vol, + // vol_ct = m.vol_ct, + // vol_curv = m.vol_curv, + // vol_dn = m.vol_dn, + // vol_pt = m.vol_pt, + // vol_slope = m.vol_slope, + // vol_t = m.vol_t, + // vol_t_dn = m.vol_t_dn, + // vol_t_up = m.vol_t_up, + // vol_up = m.vol_up, + // vol_voldn = m.vol_voldn, + // vol_volup = m.vol_volup, + // conversion_vol = m.conversion_vol, + // conversion_fwd = m.conversion_fwd, + // shape_greeks_in_price_terms = m.shape_greeks_in_price_terms, + // }; + // } + + // public static explicit operator VolMatrix(bts.api.analytics.VolMatrix m) + // { + // return new VolMatrix() + // { + // atmvol = m.atmvol, + // bizt = m.bizt, + // calt = m.calt, + // ceeadj = m.ceeadj, + // d1 = m.d1, + // d2 = m.d2, + // delta_divisor = m.delta_divisor, + // delta_inc = m.delta_inc, + // dfwd_dund = m.dfwd_dund, + // driver = m.driver, + // driver_move = m.driver_move, + // dspot_dund = m.dspot_dund, + // expiration = m.expiration, + // fwd = m.fwd, + // growth = m.growth, + // model = (PricingModel)m.model, + // peeadj = m.peeadj, + // price_bias = m.price_bias, + // ref_price = m.ref_price, + // rho_inc = m.rho_inc, + // riskless = m.riskless, + // spot = m.spot, + // standard_strike = m.standard_strike, + // strike = m.strike, + // theta_inc = m.theta_inc, + // typical_vega = m.typical_vega, + // vega_factor = m.vega_factor, + // vega_inc = m.vega_inc, + // vol = m.vol, + // vol_ct = m.vol_ct, + // vol_curv = m.vol_curv, + // vol_dn = m.vol_dn, + // vol_pt = m.vol_pt, + // vol_slope = m.vol_slope, + // vol_t = m.vol_t, + // vol_t_dn = m.vol_t_dn, + // vol_t_up = m.vol_t_up, + // vol_up = m.vol_up, + // vol_voldn = m.vol_voldn, + // vol_volup = m.vol_volup, + // conversion_vol = m.conversion_vol, + // conversion_fwd = m.conversion_fwd, + // shape_greeks_in_price_terms = m.shape_greeks_in_price_terms, + // }; + // } + // } + + // [Serializable] + // [ProtoBuf.ProtoContract] + // public class SplineVolMatrix : VolMatrix + // { + // public static explicit operator bts.api.analytics.SplineVolMatrix(SplineVolMatrix m) + // { + // return new bts.api.analytics.SplineVolMatrix() + // { + // atmvol = m.atmvol, + // bizt = m.bizt, + // calt = m.calt, + // ceeadj = m.ceeadj, + // d1 = m.d1, + // d2 = m.d2, + // delta_divisor = m.delta_divisor, + // delta_inc = m.delta_inc, + // dfwd_dund = m.dfwd_dund, + // driver = m.driver, + // driver_move = m.driver_move, + // dspot_dund = m.dspot_dund, + // expiration = m.expiration, + // fwd = m.fwd, + // growth = m.growth, + // model = (bts.api.analytics.PricingModel.type)m.model, + // peeadj = m.peeadj, + // price_bias = m.price_bias, + // ref_price = m.ref_price, + // rho_inc = m.rho_inc, + // riskless = m.riskless, + // spot = m.spot, + // standard_strike = m.standard_strike, + // strike = m.strike, + // theta_inc = m.theta_inc, + // typical_vega = m.typical_vega, + // vega_factor = m.vega_factor, + // vega_inc = m.vega_inc, + // vol = m.vol, + // vol_ct = m.vol_ct, + // vol_curv = m.vol_curv, + // vol_dn = m.vol_dn, + // vol_pt = m.vol_pt, + // vol_slope = m.vol_slope, + // vol_t = m.vol_t, + // vol_t_dn = m.vol_t_dn, + // vol_t_up = m.vol_t_up, + // vol_up = m.vol_up, + // vol_voldn = m.vol_voldn, + // vol_volup = m.vol_volup, + // conversion_vol = m.conversion_vol, + // conversion_fwd = m.conversion_fwd, + // shape_greeks_in_price_terms = m.shape_greeks_in_price_terms, + // }; + // } + + // public static explicit operator SplineVolMatrix(bts.api.analytics.SplineVolMatrix m) + // { + // return new SplineVolMatrix() + // { + // atmvol = m.atmvol, + // bizt = m.bizt, + // calt = m.calt, + // ceeadj = m.ceeadj, + // d1 = m.d1, + // d2 = m.d2, + // delta_divisor = m.delta_divisor, + // delta_inc = m.delta_inc, + // dfwd_dund = m.dfwd_dund, + // driver = m.driver, + // driver_move = m.driver_move, + // dspot_dund = m.dspot_dund, + // expiration = m.expiration, + // fwd = m.fwd, + // growth = m.growth, + // model = (PricingModel)m.model, + // peeadj = m.peeadj, + // price_bias = m.price_bias, + // ref_price = m.ref_price, + // rho_inc = m.rho_inc, + // riskless = m.riskless, + // spot = m.spot, + // standard_strike = m.standard_strike, + // strike = m.strike, + // theta_inc = m.theta_inc, + // typical_vega = m.typical_vega, + // vega_factor = m.vega_factor, + // vega_inc = m.vega_inc, + // vol = m.vol, + // vol_ct = m.vol_ct, + // vol_curv = m.vol_curv, + // vol_dn = m.vol_dn, + // vol_pt = m.vol_pt, + // vol_slope = m.vol_slope, + // vol_t = m.vol_t, + // vol_t_dn = m.vol_t_dn, + // vol_t_up = m.vol_t_up, + // vol_up = m.vol_up, + // vol_voldn = m.vol_voldn, + // vol_volup = m.vol_volup, + // conversion_vol = m.conversion_vol, + // conversion_fwd = m.conversion_fwd, + // shape_greeks_in_price_terms = m.shape_greeks_in_price_terms, + // }; + // } + // } + + // [Serializable] + // [ProtoBuf.ProtoContract] + // public class SlideVolMatrix : VolMatrix + // { + // public static explicit operator bts.api.analytics.SlideVolMatrix(SlideVolMatrix m) + // { + // return new bts.api.analytics.SlideVolMatrix() + // { + // atmvol = m.atmvol, + // bizt = m.bizt, + // calt = m.calt, + // ceeadj = m.ceeadj, + // d1 = m.d1, + // d2 = m.d2, + // delta_divisor = m.delta_divisor, + // delta_inc = m.delta_inc, + // dfwd_dund = m.dfwd_dund, + // driver = m.driver, + // driver_move = m.driver_move, + // dspot_dund = m.dspot_dund, + // expiration = m.expiration, + // fwd = m.fwd, + // growth = m.growth, + // model = (bts.api.analytics.PricingModel.type)m.model, + // peeadj = m.peeadj, + // price_bias = m.price_bias, + // ref_price = m.ref_price, + // rho_inc = m.rho_inc, + // riskless = m.riskless, + // spot = m.spot, + // standard_strike = m.standard_strike, + // strike = m.strike, + // theta_inc = m.theta_inc, + // typical_vega = m.typical_vega, + // vega_factor = m.vega_factor, + // vega_inc = m.vega_inc, + // vol = m.vol, + // vol_ct = m.vol_ct, + // vol_curv = m.vol_curv, + // vol_dn = m.vol_dn, + // vol_pt = m.vol_pt, + // vol_slope = m.vol_slope, + // vol_t = m.vol_t, + // vol_t_dn = m.vol_t_dn, + // vol_t_up = m.vol_t_up, + // vol_up = m.vol_up, + // vol_voldn = m.vol_voldn, + // vol_volup = m.vol_volup, + // conversion_vol = m.conversion_vol, + // conversion_fwd = m.conversion_fwd, + // shape_greeks_in_price_terms = m.shape_greeks_in_price_terms, + // }; + // } + + // public static explicit operator SlideVolMatrix(bts.api.analytics.SlideVolMatrix m) + // { + // return new SlideVolMatrix() + // { + // atmvol = m.atmvol, + // bizt = m.bizt, + // calt = m.calt, + // ceeadj = m.ceeadj, + // d1 = m.d1, + // d2 = m.d2, + // delta_divisor = m.delta_divisor, + // delta_inc = m.delta_inc, + // dfwd_dund = m.dfwd_dund, + // driver = m.driver, + // driver_move = m.driver_move, + // dspot_dund = m.dspot_dund, + // expiration = m.expiration, + // fwd = m.fwd, + // growth = m.growth, + // model = (PricingModel)m.model, + // peeadj = m.peeadj, + // price_bias = m.price_bias, + // ref_price = m.ref_price, + // rho_inc = m.rho_inc, + // riskless = m.riskless, + // spot = m.spot, + // standard_strike = m.standard_strike, + // strike = m.strike, + // theta_inc = m.theta_inc, + // typical_vega = m.typical_vega, + // vega_factor = m.vega_factor, + // vega_inc = m.vega_inc, + // vol = m.vol, + // vol_ct = m.vol_ct, + // vol_curv = m.vol_curv, + // vol_dn = m.vol_dn, + // vol_pt = m.vol_pt, + // vol_slope = m.vol_slope, + // vol_t = m.vol_t, + // vol_t_dn = m.vol_t_dn, + // vol_t_up = m.vol_t_up, + // vol_up = m.vol_up, + // vol_voldn = m.vol_voldn, + // vol_volup = m.vol_volup, + // conversion_vol = m.conversion_vol, + // conversion_fwd = m.conversion_fwd, + // shape_greeks_in_price_terms = m.shape_greeks_in_price_terms, + // }; + // } + } +} diff --git a/src/client/spark/Analytics/Pricing/VolSurfaceGreeks.cs b/src/client/spark/Analytics/Pricing/VolSurfaceGreeks.cs new file mode 100644 index 000000000..82726fac8 --- /dev/null +++ b/src/client/spark/Analytics/Pricing/VolSurfaceGreeks.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Collections.Concurrent; +using System.ComponentModel; + +namespace mbts.analytics +{ + /// move this out later + public enum VolSurfaceGreeks + { + /* *********************Primary Greeks*********************/ + Vol, + Moneyness, + Theo, + Delta, + [Description("BSM Delta")] + BSMDelta, + FlatVolDelta, + Vega, + [Description("BSM Vega")] + BSMVega, + AdjustedVega, /// adjusted_vega = vega * (atm_vega/n_days_atm_vega) + Theta, + AdjustedTheta, /// what is that ? (its in slide) + RollRho, + DiscountRho, + TimeValue, + /* *********************Second Order*********************/ + Gamma, + [Description("BSM Gamma")] + BSMGamma, + OEV, + [Description("BSM OEV")] + BSMOEV, + Vanna, + Volga, + Charm, + [Description("Vol/Und")] + DVolDUnd, + [Description("Vol²/DUnd²")] + D2VolDUnd2, + /* *********************Curve Operations******************/ + [Description("Price/DRR")] + DPriceDRiskReversal, + [Description("Price/Strangle")] + DPriceDStrangle, + [Description("Price/Put Tilt")] + DPriceDPutTilt, + [Description("Price/Call Tilt")] + DPriceDCallTilt, + /* *********************Risk*******************************/ + [Description("PnL")] + PNL, + ExpirationDelta + } + + [ProtoBuf.ProtoContract(Name = "VolSurfaceStrikeTheo")] + public class VolSurfaceStrikeTheo + { + [ProtoBuf.ProtoMember(10)] + public DateTime exp; + [ProtoBuf.ProtoMember(20)] + public double strike; + [ProtoBuf.ProtoMember(30)] + public double driver; + [ProtoBuf.ProtoMember(40)] + public double fwd; + [ProtoBuf.ProtoMember(50)] + public List> call_put_greeks; + } + + [ProtoBuf.ProtoContract(Name = "VolSurfaceSymbolTheos")] + public class VolSurfaceSymbolTheos + { + [ProtoBuf.ProtoMember(10)] + public List all_theos; + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Pricing/VolSurfaceTheoCalculator.cs b/src/client/spark/Analytics/Pricing/VolSurfaceTheoCalculator.cs new file mode 100644 index 000000000..cfe52da09 --- /dev/null +++ b/src/client/spark/Analytics/Pricing/VolSurfaceTheoCalculator.cs @@ -0,0 +1,446 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Collections.Concurrent; + +namespace mbts.analytics +{ + /// Computes greeks from VolMatrix + public class VolSurfaceTheoCalculator + { + #region Individual Greek Functions + private static IDictionary> _func_map = null; + private static void _initialize_func_map() + { + if (_func_map == null) + { + lock (typeof(VolSurfaceTheoCalculator)) + { + if (_func_map == null) + { + _func_map = new Dictionary>() + { + {VolSurfaceGreeks.Vol, (volmat, is_call) => volmat.vol}, + {VolSurfaceGreeks.Moneyness, (volmat, is_call) => volmat.standard_strike}, + {VolSurfaceGreeks.Theo, (volmat, is_call) => compute_theo (volmat, is_call)}, + {VolSurfaceGreeks.Delta, (volmat, is_call) => compute_delta (volmat, is_call)}, + {VolSurfaceGreeks.BSMDelta, (volmat, is_call) => compute_bsm_delta (volmat, is_call)}, + {VolSurfaceGreeks.FlatVolDelta, (volmat, is_call) => compute_flatvol_delta (volmat, is_call)}, + {VolSurfaceGreeks.Vega, (volmat, is_call) => compute_vega (volmat, is_call)}, + {VolSurfaceGreeks.BSMVega, (volmat, is_call) => compute_bsm_vega (volmat)}, + {VolSurfaceGreeks.Theta, (volmat, is_call) => compute_theta (volmat, is_call)}, + {VolSurfaceGreeks.TimeValue, (volmat, is_call) => compute_time_value (volmat, is_call)}, + + {VolSurfaceGreeks.Gamma, (volmat, is_call) => compute_gamma (volmat, is_call)}, + {VolSurfaceGreeks.BSMGamma, (volmat, is_call) => compute_bsm_gamma (volmat)}, + {VolSurfaceGreeks.OEV, (volmat, is_call) => compute_oev (volmat, is_call)}, + {VolSurfaceGreeks.BSMOEV, (volmat, is_call) => compute_bsm_oev (volmat, is_call)}, + {VolSurfaceGreeks.Vanna, (volmat, is_call) => compute_vanna (volmat, is_call)}, + {VolSurfaceGreeks.Volga, (volmat, is_call) => compute_volga (volmat, is_call)}, + {VolSurfaceGreeks.Charm, (volmat, is_call) => compute_charm (volmat, is_call)}, + {VolSurfaceGreeks.DVolDUnd, (volmat, is_call) => compute_dVolDUnd (volmat)}, + {VolSurfaceGreeks.D2VolDUnd2, (volmat, is_call) => compute_d2VolDUnd2 (volmat)}, + + {VolSurfaceGreeks.DPriceDRiskReversal, (volmat, is_call) => compute_dPriceDRiskReversal (volmat, is_call)}, + {VolSurfaceGreeks.DPriceDStrangle, (volmat, is_call) => compute_dPriceDStrangle (volmat, is_call)}, + {VolSurfaceGreeks.DPriceDPutTilt, (volmat, is_call) => compute_dPriceDPutTilt (volmat, is_call)}, + {VolSurfaceGreeks.DPriceDCallTilt, (volmat, is_call) => compute_dPriceDCallTilt (volmat, is_call)}, + + }; + } + } + } + } + + public static double compute_theo(VolMatrix volmat, bool is_call, double? vol_override = null) + { + double vol = vol_override != null && vol_override.HasValue ? vol_override.Value : volmat.vol; + return compute_theo(volmat.strike, is_call, vol, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless); + } + + public static double compute_theo(double strike, bool is_call, double vol, double fwd, double biz_t, double cal_t, double riskless_rate) + { + return VolSurfaceCoreFunctions.compute_bsm_theo(strike, is_call, vol, fwd, biz_t, cal_t, riskless_rate); + } + + public static double compute_bsm_delta(VolMatrix volmat, bool is_call) + { + return VolSurfaceCoreFunctions.compute_bsm_delta(volmat.strike, is_call, volmat.vol, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless); + } + + public static double compute_flatvol_delta(VolMatrix volmat, bool is_call) + { + return VolSurfaceCoreFunctions.compute_bsm_delta(volmat.strike, is_call, volmat.conversion_vol, volmat.conversion_fwd, volmat.bizt, volmat.calt, volmat.riskless); + } + + public static double compute_bsm_gamma(VolMatrix volmat) + { + return VolSurfaceCoreFunctions.compute_bsm_gamma(volmat.strike, volmat.vol, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless); + } + + public static double compute_bsm_vega(VolMatrix volmat) + { + return VolSurfaceCoreFunctions.compute_bsm_vega(volmat.strike, volmat.vol, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless); + } + + public static double compute_delta(VolMatrix volmat, bool is_call) + { + double fwd_h = volmat.delta_inc * volmat.dfwd_dund; + double theo_fwd_up = compute_theo(volmat.strike, is_call, volmat.vol_up, volmat.fwd + fwd_h, volmat.bizt, volmat.calt, volmat.riskless), + theo_fwd_down = compute_theo(volmat.strike, is_call, volmat.vol_dn, volmat.fwd - fwd_h, volmat.bizt, volmat.calt, volmat.riskless); + return (theo_fwd_up - theo_fwd_down) / (2 * volmat.delta_inc); + } + + /// This is the vega when vol is NOT expressed as a + /// percentage. (ex ChangePrice = Vega * ChangeVol, so if + /// vol is in %, vega should be multiplied by 0.01). + public static double compute_vega(VolMatrix volmat, bool is_call) + { + double theo_vol_up = compute_theo(volmat.strike, is_call, volmat.vol_volup, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless), + theo_vol_down = compute_theo(volmat.strike, is_call, volmat.vol_voldn, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless); + return (theo_vol_up - theo_vol_down) / (2 * volmat.vega_inc); + } + + public static double compute_gamma(VolMatrix volmat, bool is_call) + { + double fwd_h = volmat.dfwd_dund * volmat.delta_inc; + double theo_fwd_up = compute_theo(volmat.strike, is_call, volmat.vol_up, volmat.fwd + fwd_h, volmat.bizt, volmat.calt, volmat.riskless), + theo_curr = compute_theo(volmat.strike, is_call, volmat.vol, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless), + theo_fwd_down = compute_theo(volmat.strike, is_call, volmat.vol_dn, volmat.fwd - fwd_h, volmat.bizt, volmat.calt, volmat.riskless); + return (theo_fwd_up - 2 * theo_curr + theo_fwd_down) / Math.Pow(volmat.delta_inc, 2.0); + } + + public static double compute_oev(VolMatrix volmat, bool is_call, double? skew_vega = null) + { + double vega = skew_vega != null && skew_vega.HasValue ? skew_vega.Value : compute_vega(volmat, is_call); + /// TODO, why not use real atm vega instead of BSM + return vega / volmat.typical_vega; + } + + public static double compute_bsm_oev(VolMatrix volmat, bool is_call) + { + return compute_bsm_vega(volmat) / volmat.typical_vega; + } + + public static double compute_theta(VolMatrix volmat, bool is_call) + { + double theo_tomorrow = compute_theo(volmat.strike, is_call, volmat.vol_t, volmat.fwd, + Math.Max(volmat.bizt - volmat.theta_inc, 1e-06), + volmat.calt, + //Math.Max (volmat.calt - volmat.theta_inc, 1e-06), /// TODO why not do this ? + volmat.riskless), + theo_curr = compute_theo(volmat, is_call); + /// no div by theta_inc because by def this is the change per day + return theo_tomorrow - theo_curr; + } + + public static double compute_dPriceDRiskReversal(VolMatrix volmat, bool is_call) + { + return compute_theo(volmat, is_call, volmat.vol_slope) - compute_theo(volmat, is_call); + } + + public static double compute_dPriceDStrangle(VolMatrix volmat, bool is_call) + { + return compute_theo(volmat, is_call, volmat.vol_curv) - compute_theo(volmat, is_call); + } + + public static double compute_dPriceDCallTilt(VolMatrix volmat, bool is_call) + { + return compute_theo(volmat, is_call, volmat.vol_ct) - compute_theo(volmat, is_call); + } + + public static double compute_dPriceDPutTilt(VolMatrix volmat, bool is_call) + { + return compute_theo(volmat, is_call, volmat.vol_pt) - compute_theo(volmat, is_call); + } + + public static double compute_vanna(VolMatrix volmat, bool is_call) + { + /// dvega/dfwd = ddelta/dvol + //double fwd_up = volmat.fwd + volmat.dfwd_dund * volmat.delta_inc, + // fwd_down = volmat.fwd - volmat.dfwd_dund * volmat.delta_inc, + // vol_vol_up_fwd_up = + //double delta_vol_up = (theo_vol_up_fwd_up - theo_vol_up_fwd_down) / (2 * volmat.delta_inc); + //double rv = (delta_vol_up - delta_vol_down) / (2 * volmat.vega_inc); + return double.NaN; + } + + public static double compute_volga(VolMatrix volmat, bool is_call) + { + /// d2price/dvol2 + return (compute_theo(volmat, true, volmat.vol_up) - 2 * compute_theo(volmat, true) + compute_theo(volmat, is_call, volmat.vol_dn)) / Math.Pow(volmat.delta_inc, 2.0); + } + + public static double compute_dVolDUnd(VolMatrix volmat) + { + return (volmat.vol_up - volmat.vol_dn) / (2 * volmat.delta_inc); + } + + public static double compute_d2VolDUnd2(VolMatrix volmat) + { + return (volmat.vol_up - 2 * volmat.vol + volmat.vol_dn) / Math.Pow(volmat.delta_inc, 2.0); + } + + public static double compute_time_value(VolMatrix volmat, bool is_call) + { + double theo = compute_theo(volmat, is_call); + return is_call ? theo - Math.Max(0.0, volmat.fwd - volmat.strike) : theo - Math.Max(0.0, volmat.strike - volmat.fwd); + } + + public static double compute_charm(VolMatrix volmat, bool is_call) + { + /// TODO checks for too close to exp + /// dDelta/dTime = delta tomorrow - delta now + double fwd_inc = volmat.delta_inc * volmat.dfwd_dund, + fwd_up = volmat.fwd + fwd_inc, + fwd_down = volmat.fwd - fwd_inc, + theo_time_up_fwd_up = compute_theo(volmat.strike, is_call, volmat.vol_t_up, fwd_up, volmat.bizt - volmat.theta_inc, volmat.calt /*- volmat.theta_inc*/, volmat.riskless), + theo_time_up_fwd_down = compute_theo(volmat.strike, is_call, volmat.vol_t_dn, fwd_down, volmat.bizt - volmat.theta_inc, volmat.calt /*- volmat.theta_inc*/, volmat.riskless), + delta_now = compute_delta(volmat, is_call), + delta_time_up = (theo_time_up_fwd_up - theo_time_up_fwd_down) / (2 * volmat.delta_inc); + return delta_time_up - delta_now; + } + + public static double get_greek(VolSurfaceStrikeTheo strike_greek, VolSurfaceGreeks greek, bool is_call) + { + Tuple rv = null; + if (strike_greek != null && strike_greek.call_put_greeks != null) + rv = strike_greek.call_put_greeks.Find(i => i.Item1 == greek); + return rv != null ? (is_call ? rv.Item2 : rv.Item3) : Double.NaN; + } + + public static double compute_single_greek(VolMatrix volmat, VolSurfaceGreeks greek, bool is_call) + { + _initialize_func_map(); + Func calc = _func_map.TryGetValue(greek, out calc) ? calc : (a_volmat, a_is_call) => Double.NaN; + return calc(volmat, is_call); + } + + public static VolSurfaceStrikeTheo compute_strike_greeks(VolMatrix volmat, IEnumerable greeks) + { + return new VolSurfaceStrikeTheo() + { + driver = volmat.driver, + exp = DateTime.FromOADate(volmat.expiration), + fwd = volmat.fwd, + strike = volmat.strike, + call_put_greeks = greeks.Select(g => Tuple.Create(g, compute_single_greek(volmat, g, true), compute_single_greek(volmat, g, false))).ToList() + }; + } + + public static IDictionary> compute_greeks(IDictionary> exp_volmats, + IEnumerable greeks) + { + ConcurrentDictionary> exp_theo_map = new ConcurrentDictionary>(); + System.Threading.Tasks.Parallel.ForEach(exp_volmats.ToList(), kv => + { + List exp_theos = new List(); + foreach (VolMatrix volmat in kv.Value) + { + VolSurfaceStrikeTheo k_theo = compute_strike_greeks(volmat, greeks); + exp_theos.Add(k_theo); + } + exp_theo_map[kv.Key] = exp_theos; + }); + return exp_theo_map; + } + #endregion + + const double normalized_vol_caldays = 30.0; + static void compute_normalized_vol_and_time(IDictionary> exp_volmats, + out double norm_vol, out double norm_t) + { + // TODO + // double t = normalized_vol_caldays / bts.api.analytics.functions.Calendar.cal_days_per_year(); + double t = normalized_vol_caldays / 365; + norm_t = t; + norm_vol = double.NaN; + if(exp_volmats == null || exp_volmats.Count == 0) + return; + + var matrices = exp_volmats.Select(x => x.Value.FirstOrDefault() ?? new VolMatrix()).OrderBy(x=>x.calt); + var first = matrices.LastOrDefault(x => x.calt <= t) ?? matrices.First(); + var last = matrices.FirstOrDefault(x => x.calt >= t) ?? matrices.Last(); + norm_vol = bts.api.analytics.functions.VegaFactor.interpolate_vol(first.calt, first.atmvol, last.calt, last.atmvol, t); + } + + public static IDictionary> compute_standard_greeks(VolSurfaceSettings settings, IDictionary> exp_volmats, bool compute_all_greeks) + { + double norm_vol, norm_t; + compute_normalized_vol_and_time(exp_volmats, out norm_vol, out norm_t); + ConcurrentDictionary> exp_theo_map = new ConcurrentDictionary>(); + System.Threading.Tasks.Parallel.ForEach(exp_volmats.ToList(), kv => + { + VolSurfaceEnums.VolSurfacePricingModel pricing_model = VolSurfaceDataFunctions.get_pricing_model(settings, kv.Key); + Func theo_func; + switch(pricing_model) + { + case VolSurfaceEnums.VolSurfacePricingModel.Whaley: + theo_func = VolSurfaceCoreFunctions.compute_whaley_theo; + break; + case VolSurfaceEnums.VolSurfacePricingModel.Normal: + theo_func = VolSurfaceCoreFunctions.compute_normal_theo; + break; + case VolSurfaceEnums.VolSurfacePricingModel.EDNormal: + theo_func = VolSurfaceCoreFunctions.compute_ednormal_theo; + break; + default: + theo_func = VolSurfaceCoreFunctions.compute_bsm_theo; + break; + } + List exp_theos = new List(); + foreach (VolMatrix volmat in kv.Value) + { + Theos k_theo = _compute_greeks(volmat, theo_func, compute_all_greeks, norm_vol, norm_t); + exp_theos.Add(k_theo); + } + exp_theo_map[kv.Key] = exp_theos; + }); + return exp_theo_map; + } + + /// Computes the greeks for the standard set of theos + private static Theos _compute_greeks(VolMatrix volmat, + Func theo_func, + /// TODO, pass in the collection of enums, this arbitrary list is not good + bool compute_all_greeks, double norm_vol, double norm_t) + { + if (volmat.vol == 0) /// overloaded for settlement price + { + Theos rv = new Theos() + { + expiration = volmat.expiration, + strike = volmat.strike, + driver = volmat.driver, + fwd = volmat.fwd, + vol = 0.0, + move = volmat.driver_move + }; + TheoHelper.set_to_parity(ref rv, volmat.fwd); + return rv; + } + else + { + double vega_factor = VolSurfaceCoreFunctions.vega_factor(norm_t, norm_vol, volmat.calt, volmat.atmvol); + double driver_h = volmat.delta_inc, + driver_up = volmat.driver + driver_h, + driver_down = volmat.driver - driver_h, + fwd_h = volmat.dfwd_dund * volmat.delta_inc, + fwd_up = volmat.fwd + fwd_h, + fwd_down = volmat.fwd - fwd_h, + bizt_tomorrow = volmat.bizt - volmat.theta_inc; + double call_theo = theo_func(volmat.strike, true, volmat.vol, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless), + put_theo = theo_func(volmat.strike, false, volmat.vol, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless), + call_fwd_parity = Math.Max(volmat.fwd - volmat.strike, 0.0), + put_fwd_parity = Math.Max(volmat.strike - volmat.fwd, 0.0), + call_theo_driver_up = theo_func(volmat.strike, true, volmat.vol_up, fwd_up, volmat.bizt, volmat.calt, volmat.riskless), + put_theo_driver_up = theo_func(volmat.strike, false, volmat.vol_up, fwd_up, volmat.bizt, volmat.calt, volmat.riskless), + call_theo_driver_down = theo_func(volmat.strike, true, volmat.vol_dn, fwd_down, volmat.bizt, volmat.calt, volmat.riskless), + put_theo_driver_down = theo_func(volmat.strike, false, volmat.vol_dn, fwd_down, volmat.bizt, volmat.calt, volmat.riskless), + call_theo_vol_up = theo_func(volmat.strike, true, volmat.vol_volup, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless), + call_theo_vol_down = theo_func(volmat.strike, true, volmat.vol_voldn, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless), + put_theo_vol_up = theo_func(volmat.strike, false, volmat.vol_volup, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless), + put_theo_vol_down = theo_func(volmat.strike, false, volmat.vol_voldn, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless), + call_theo_tomorrow = bizt_tomorrow <= 0 ? call_fwd_parity : theo_func(volmat.strike, true, volmat.vol_t, volmat.fwd, Math.Max(volmat.bizt - volmat.theta_inc, VolSurfaceExpirationAuxiliaryData.min_biz_t_yrs), volmat.calt, volmat.riskless), + put_theo_tomorrow = bizt_tomorrow <= 0 ? put_fwd_parity : theo_func(volmat.strike, false, volmat.vol_t, volmat.fwd, Math.Max(volmat.bizt - volmat.theta_inc, VolSurfaceExpirationAuxiliaryData.min_biz_t_yrs), volmat.calt, volmat.riskless), + call_theo_risk_reversal = theo_func(volmat.strike, true, volmat.vol_slope, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless), + put_theo_risk_reversal = theo_func(volmat.strike, false, volmat.vol_slope, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless); + + Theos rv = new Theos(); + rv.expiration = volmat.expiration; + rv.strike = volmat.strike; + rv.driver = volmat.driver; + rv.move = volmat.driver_move; + rv.fwd = volmat.fwd; + rv.bizt = volmat.bizt; + rv.call = call_theo; + rv.put = put_theo; + rv.cdelta = (call_theo_driver_up - call_theo_driver_down) / (2 * driver_h); + rv.pdelta = (put_theo_driver_up - put_theo_driver_down) / (2 * driver_h); + rv.cdeltanovr = (float)compute_bsm_delta(volmat, true); + rv.pdeltanovr = (float)compute_bsm_delta (volmat, false); + rv.cflatvoldelta = (float)compute_flatvol_delta(volmat, true); + rv.pflatvoldelta = (float)compute_flatvol_delta(volmat, false); + rv.cvega = (call_theo_vol_up - call_theo_vol_down) / (2 * volmat.vega_inc); + rv.pvega = (put_theo_vol_up - put_theo_vol_down) / (2 * volmat.vega_inc); + rv.cgamma = (call_theo_driver_up - 2 * call_theo + call_theo_driver_down) / Math.Pow(driver_h, 2.0); + rv.pgamma = (put_theo_driver_up - 2 * put_theo + put_theo_driver_down) / Math.Pow(driver_h, 2.0); + rv.vol = volmat.vol; + rv.cadjvega = (float)(vega_factor * rv.cvega); + rv.padjvega = (float)(vega_factor * rv.pvega); + rv.copts = (float)(rv.cvega / volmat.typical_vega); + rv.popts = (float)(rv.pvega / volmat.typical_vega); + rv.cvoltheta = (float)(call_theo_tomorrow - call_theo); + rv.pvoltheta = (float)(put_theo_tomorrow - put_theo); + rv.cslopevega = (float)(call_theo_risk_reversal - call_theo); + rv.pslopevega = (float)(put_theo_risk_reversal - put_theo); + rv.veganovr = (float)compute_bsm_vega(volmat); + rv.standard_strike = volmat.standard_strike; + rv.dvol_dund = (float)((volmat.vol_up - volmat.vol_dn) / (2 * volmat.delta_inc)); + rv.cvolga = (float)((call_theo_vol_up - 2 * call_theo + call_theo_vol_down) / Math.Pow(volmat.vega_inc, 2.0)); + rv.pvolga = (float)((put_theo_vol_up - 2 * put_theo + put_theo_vol_down) / Math.Pow(volmat.vega_inc, 2.0)); + double vol_root_t = volmat.vol * Math.Sqrt(volmat.bizt); + double van_fact = (1.0 - volmat.d1 / vol_root_t) / volmat.fwd; + rv.cvanna = (float)(rv.cvega * van_fact + rv.cvolga * rv.dvol_dund); + rv.pvanna = (float)(rv.pvega * van_fact + rv.pvolga * rv.dvol_dund); + rv.move = volmat.driver_move; + if (compute_all_greeks) + { + double call_theo_tomorrow_driver_up = theo_func(volmat.strike, true, volmat.vol_t_up, fwd_up, Math.Max(bizt_tomorrow, VolSurfaceExpirationAuxiliaryData.min_biz_t_yrs), volmat.calt, volmat.riskless), + call_theo_tomorrow_driver_down = theo_func(volmat.strike, true, volmat.vol_t_dn, fwd_down, Math.Max(bizt_tomorrow, VolSurfaceExpirationAuxiliaryData.min_biz_t_yrs), volmat.calt, volmat.riskless), + put_theo_tomorrow_driver_up = theo_func(volmat.strike, false, volmat.vol_t_up, fwd_up, Math.Max(bizt_tomorrow, VolSurfaceExpirationAuxiliaryData.min_biz_t_yrs), volmat.calt, volmat.riskless), + put_theo_tomorrow_driver_down = theo_func(volmat.strike, false, volmat.vol_t_dn, fwd_down, Math.Max(bizt_tomorrow, VolSurfaceExpirationAuxiliaryData.min_biz_t_yrs), volmat.calt, volmat.riskless), + call_delta_tomorrow = (call_theo_tomorrow_driver_up - call_theo_tomorrow_driver_down) / (2 * volmat.delta_inc), + put_delta_tomorrow = (put_theo_tomorrow_driver_up - put_theo_tomorrow_driver_down) / (2 * volmat.delta_inc); + + rv.cadjtheta = rv.padjtheta = float.NaN; + rv.crollrho = rv.prollrho = rv.cdiscrho = rv.pdiscrho = float.NaN; + rv.ccurvvega = (float)(theo_func(volmat.strike, true, volmat.vol_curv, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless) - call_theo); + rv.pcurvvega = (float)(theo_func(volmat.strike, false, volmat.vol_curv, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless) - put_theo); + rv.cputtailvega = (float)(theo_func(volmat.strike, true, volmat.vol_pt, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless) - call_theo); + rv.pputtailvega = (float)(theo_func(volmat.strike, false, volmat.vol_pt, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless) - put_theo); + rv.ccalltailvega = (float)(theo_func(volmat.strike, true, volmat.vol_ct, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless) - call_theo); + rv.pcalltailvega = (float)(theo_func(volmat.strike, false, volmat.vol_ct, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless) - put_theo); + rv.cdeltableed = (float)(bizt_tomorrow >= 0 ? (call_delta_tomorrow - rv.cdelta) : volmat.strike <= volmat.fwd ? -1.0 * rv.pdelta : -1.0 * rv.cdelta); + rv.pdeltableed = (float)(bizt_tomorrow >= 0 ? (put_delta_tomorrow - rv.pdelta) : volmat.strike <= volmat.fwd ? -1.0 * rv.pdelta : -1.0 * rv.cdelta); + rv.cdeltanovr = (float)VolSurfaceCoreFunctions.compute_bsm_delta(volmat.strike, true, volmat.vol, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless); + rv.pdeltanovr = (float)VolSurfaceCoreFunctions.compute_bsm_delta(volmat.strike, false, volmat.vol, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless); + rv.gammanovr = (float)VolSurfaceCoreFunctions.compute_bsm_gamma(volmat.strike, volmat.vol, volmat.fwd, volmat.bizt, volmat.calt, volmat.riskless); + rv.optsnovr = (float)(rv.veganovr / volmat.typical_vega); + rv.cparitydelta = (float)(volmat.strike <= volmat.fwd ? 1.0 : 0.0); + rv.pparitydelta = (float)(volmat.strike <= volmat.fwd ? 0.0 : -1.0); + rv.ctimevalue = (float)(call_theo - call_fwd_parity); + rv.ptimevalue = (float)(put_theo - put_fwd_parity); + rv.ceeadj = rv.peeadj = float.NaN; + rv.d2vol_dund2 = (float)((volmat.vol_up - 2 * volmat.vol + volmat.vol_dn) / Math.Pow(volmat.delta_inc, 2.0)); + //source_expiration + + //rho below + const double rho_inc = 0.0001; + double driver_growth = Math.Log(volmat.fwd / volmat.driver) / volmat.calt; + double dfwd = 0.0; + if(driver_growth != 0.0) + { + dfwd = Math.Exp((driver_growth + rho_inc) * volmat.calt) * volmat.driver; + dfwd -= volmat.fwd; + } + rv.crollrho = (float)(rv.cdelta * dfwd); + rv.prollrho = (float)(rv.pdelta * dfwd); + //c = exp(-rt)*(fwd*nd1 - k*nd2), exp(-rt) = df + //dc/dr = -t*df*(fwd*nd1 - k*nd2) = -t*c + rv.cdiscrho = (float)(-rv.call * volmat.calt * rho_inc); + rv.pdiscrho = (float)(-rv.put * volmat.calt * rho_inc); + + double calt_tomorrow = Math.Max(volmat.calt - 1.0 / 365.0, 0.0); + double call_theo_tomorrow_calt = calt_tomorrow <= 0 ? call_fwd_parity : theo_func(volmat.strike, true, volmat.vol_t, volmat.fwd, volmat.bizt, calt_tomorrow, volmat.riskless); + double put_theo_tomorrow_calt = calt_tomorrow <= 0 ? put_fwd_parity : theo_func(volmat.strike, false, volmat.vol_t, volmat.fwd, volmat.bizt, calt_tomorrow, volmat.riskless); + rv.cadjtheta = (float)(call_theo_tomorrow_calt - call_theo); + rv.padjtheta = (float)(put_theo_tomorrow_calt - put_theo); + } + return rv; + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Pricing/VolSurfaceVolMatrixCalculator.cs b/src/client/spark/Analytics/Pricing/VolSurfaceVolMatrixCalculator.cs new file mode 100644 index 000000000..4982d9254 --- /dev/null +++ b/src/client/spark/Analytics/Pricing/VolSurfaceVolMatrixCalculator.cs @@ -0,0 +1,230 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Collections.Concurrent; + +using bts; + +namespace mbts.analytics +{ + public class VolSurfaceVolMatrixCalculator + { + private static double _driver_h = 0.1, _time_h = 1.0 / 252, _rho_h = 0.01, _vega_h = 0.002; + private static VolSurfaceOutput _empty_output = VolSurfaceOutput.get_empty_output(); + + private static IDictionary _shift_driver(IDictionary aux_data_map, + IDictionary abs_move_map) + { + return aux_data_map.ToDictionary(kv => kv.Key, kv => kv.Value.shift_driver_time(abs_move_map[kv.Key], 0.0)); + } + + private static IDictionary _shift_driver_time(IDictionary aux_data_map, + double driver_shift, double time_shift) + { + return aux_data_map.ToDictionary(kv => kv.Key, kv => kv.Value.shift_driver_time(driver_shift, time_shift)); + } + + public static IDictionary> generate_volmatrix(VolSurfaceInput vs_input, + IDictionary> exp_strikes_map, + IDictionary aux_data_map, + IEnumerable driver_moves, + bool compute_time_up_driver_move, + bool compute_risk_reversal, + bool compute_risk_strangle, + bool compute_put_tilt, + bool compute_call_tilt, + IDictionary> secs_filter = null) + { + return generate_volmatrix(vs_input, + exp_strikes_map, + aux_data_map, + exp_strikes_map.Keys.ToDictionary(e => e, e => driver_moves), + driver_moves.Count(), + compute_time_up_driver_move, + compute_risk_reversal, + compute_risk_strangle, + compute_put_tilt, + compute_call_tilt, + secs_filter); + } + + /// The last arg is a filter. The reason its passed as a filter + /// vs reducing the exp_strikes_map is because exp_strikes_map + /// is the master secs for everything in this volsurface, and + /// all the other data is synced to it. + /// (Also the possible intra-exp relationships (master-slave, + /// interping etc) makes it more conveniant to provide the whole + /// data set and not compute some secs) + public static IDictionary> generate_volmatrix(VolSurfaceInput vs_input, + IDictionary> exp_strikes_map, + IDictionary aux_data_map, + IDictionary> abs_driver_moves, + int n_moves, + bool compute_time_up_driver_move, + bool compute_risk_reversal, + bool compute_strangle, + bool compute_put_tilt, + bool compute_call_tilt, + IDictionary> secs_filter = null) + { + /// exp_strikes_map is used as the complete list, and other lists's expirations + /// are synced with it + aux_data_map = VolSurfaceUtilityFunctions.sync_map_exps(exp_strikes_map.Keys, aux_data_map, true, exp => VolSurfaceExpirationAuxiliaryData.empty); + abs_driver_moves = VolSurfaceUtilityFunctions.sync_map_exps(exp_strikes_map.Keys, abs_driver_moves, true, exp => Enumerable.Repeat(0, n_moves).Select(i => Double.NaN)); + secs_filter = secs_filter ?? exp_strikes_map.ToDictionary(kv => kv.Key, kv => new HashSet(kv.Value)); + abs_driver_moves.ToList().ForEach(kv => { Log.assert(kv.Value.Count() == n_moves); }); + ConcurrentBag>> move_data_list = new ConcurrentBag>>(); + Parallel.ForEach(Enumerable.Range(0, n_moves), move_index => + { + IDictionary this_move_driver_shift_map = abs_driver_moves.ToDictionary(kv => kv.Key, kv => kv.Value.ElementAt(move_index)); + IDictionary this_move_aux_data_map = _shift_driver(aux_data_map, this_move_driver_shift_map); + IDictionary> this_move_output = _generate_fixed_driver_volmatrix(vs_input, exp_strikes_map, aux_data_map, this_move_aux_data_map, compute_time_up_driver_move, compute_risk_reversal, compute_strangle, compute_put_tilt, compute_call_tilt, secs_filter); + move_data_list.Add(this_move_output); + }); + /// putting together move_data_list into return type + IDictionary> rv = new Dictionary>(); + foreach (IDictionary> m_data in move_data_list) + foreach (KeyValuePair> kv in m_data) + { + IEnumerable exp_list = null; + if (!rv.TryGetValue(kv.Key, out exp_list)) + rv.Add(kv.Key, exp_list = new List()); + (exp_list as List).AddRange(kv.Value); + } + return rv; + } + + + public static IDictionary> _generate_fixed_driver_volmatrix(VolSurfaceInput vs_input, + IDictionary> exp_strikes_map, + IDictionary zero_move_aux_data_map, + IDictionary aux_data_map, + bool compute_time_up_driver_move, + bool compute_risk_reversal, + bool compute_strangle, + bool compute_put_tilt, + bool compute_call_tilt, + IDictionary> secs_filter) + { + IDictionary settle_driver_map = aux_data_map.Where(kv => !Double.IsNaN(kv.Value.settlement_price)).ToDictionary(kv => kv.Key, kv => kv.Value.settlement_price); + + VolSurfaceOutput v_orig = GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, aux_data_map, null, secs_filter), + v_driver_up = GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, _shift_driver_time(aux_data_map, _driver_h, 0.0), null, secs_filter), + v_driver_down = GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, _shift_driver_time(aux_data_map, -1.0 * _driver_h, 0.0), null, secs_filter), + v_t_up = GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, _shift_driver_time(aux_data_map, 0.0, -1.0 * _time_h), null, secs_filter), + /// time up moves + v_t_up_driver_up = compute_time_up_driver_move ? GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, _shift_driver_time(aux_data_map, _driver_h, 1.0 * _time_h), null, secs_filter) : _empty_output, + v_t_up_driver_down = compute_time_up_driver_move ? GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, _shift_driver_time(aux_data_map, -1.0 * _driver_h, -1.0 * _time_h), null, secs_filter) : _empty_output, + /// v_atm up/down + v_atmvol_up = GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, aux_data_map, _copy_action(exp_strikes_map.Keys, new VolCurveMovementOperation() { atm_strike_vol_movement = _vega_h }), secs_filter), + v_atmvol_down = GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, aux_data_map, _copy_action(exp_strikes_map.Keys, new VolCurveMovementOperation() { atm_strike_vol_movement = -1 * _vega_h }), secs_filter), + /// curve shape actions + v_rr = compute_risk_reversal ? GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, aux_data_map, _copy_action(exp_strikes_map.Keys, vs_input.surface_settings.core_settings.full_rotation), secs_filter) : _empty_output, + v_strangle = compute_strangle ? GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, aux_data_map, _copy_action(exp_strikes_map.Keys, vs_input.surface_settings.core_settings.strangle), secs_filter) : _empty_output, + v_puttilt = compute_put_tilt ? GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, aux_data_map, _copy_action(exp_strikes_map.Keys, vs_input.surface_settings.core_settings.put_rotation), secs_filter) : _empty_output, + v_calltilt = compute_call_tilt ? GeneralVolSurfaceCalculator.compute(vs_input, exp_strikes_map, aux_data_map, _copy_action(exp_strikes_map.Keys, vs_input.surface_settings.core_settings.call_rotation), secs_filter) : _empty_output; + /// At this time everything has been calculated (at all the moves) + /// Following is mainly copying the data + IDictionary> rv = new Dictionary>(); + foreach (KeyValuePair> kv in exp_strikes_map) + { + VolSurfaceExpiration exp = kv.Key; + HashSet strike_filter = secs_filter.TryGetValue(exp, out strike_filter) ? strike_filter : null; + if (strike_filter != null) + { + double settlement_price = settle_driver_map.TryGetValue(exp, out settlement_price) ? settlement_price : Double.NaN; + VolSurfaceEnums.VolSurfacePricingModel pricing_model = VolSurfaceDataFunctions.get_pricing_model(vs_input.surface_settings, exp); + // PricingModel old_enum_model = pricing_model == VolSurfaceEnums.VolSurfacePricingModel.Whaley ? PricingModel.WhaleyPower : PricingModel.BlackScholes; + VolSurfaceExpirationAuxiliaryData zero_move_aux_data = zero_move_aux_data_map.TryGetValue(exp, out zero_move_aux_data) ? zero_move_aux_data : VolSurfaceExpirationAuxiliaryData.empty; + List exp_values = new List(); + rv[exp] = exp_values; + VolCurveOutput v_orig_exp = v_orig[exp], + v_driver_up_exp = v_driver_up[exp], + v_driver_down_exp = v_driver_down[exp], + v_t_up_exp = v_t_up[exp], + v_t_up_driver_up_exp = v_t_up_driver_up[exp], + v_t_up_driver_down_exp = v_t_up_driver_down[exp], + v_atmvol_up_exp = v_atmvol_up[exp], + v_atmvol_down_exp = v_atmvol_down[exp], + v_rr_exp = v_rr[exp], + v_strangle_exp = v_strangle[exp], + v_puttilt_exp = v_puttilt[exp], + v_calltilt_exp = v_calltilt[exp]; + double atm_vega = VolSurfaceCoreFunctions.compute_bsm_vega(v_orig_exp.aux_data.fwd, v_orig_exp.atm_vol, v_orig_exp.aux_data.fwd, v_orig_exp.aux_data.biz_t, v_orig_exp.aux_data.cal_t, v_orig_exp.aux_data.riskless_rate); + double sqrt_t = Math.Sqrt(v_orig_exp.aux_data.biz_t); + foreach (double rawk in strike_filter) + { + double vol_rawk = v_orig_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + double vol_root_t = vol_rawk * sqrt_t; + double d1_rawk = (Math.Log(v_orig_exp.aux_data.fwd / rawk, Math.E) / vol_root_t) + (0.5 * vol_root_t); + double d2_rawk = d1_rawk - vol_root_t; + VolMatrix k_vm = new VolMatrix() + { + atmvol = v_orig_exp.atm_vol, + bizt = v_orig_exp.aux_data.biz_t, + calt = v_orig_exp.aux_data.cal_t, + ceeadj = 0.0, + d1 = d1_rawk, + d2 = d2_rawk, + delta_divisor = 1.0, /// TODO + delta_inc = _driver_h, + dfwd_dund = v_orig_exp.aux_data.dfwd_dund, + driver = v_orig_exp.aux_data.driver_price, + driver_move = (v_orig_exp.aux_data.driver_price - zero_move_aux_data.driver_price) / zero_move_aux_data.driver_price, + dspot_dund = v_orig_exp.aux_data.dspot_dund, + expiration = exp.expiration.ToOADate(), + fwd = v_orig_exp.aux_data.fwd, + growth = v_orig_exp.aux_data.growth, + model = pricing_model, + peeadj = 0.0, + price_bias = 0.0, + ref_price = zero_move_aux_data.driver_price, + rho_inc = _rho_h, + riskless = v_orig_exp.aux_data.riskless_rate, + spot = v_orig_exp.aux_data.spot, + standard_strike = v_orig_exp.convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, rawk, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike), + strike = rawk, + theta_inc = _time_h, + typical_vega = atm_vega, + vega_factor = 1.0, /// TODO + vega_inc = _vega_h, + vol = v_orig_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_ct = v_calltilt_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_curv = v_strangle_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_dn = v_driver_down_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_pt = v_puttilt_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_slope = v_rr_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_t = v_t_up_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_t_dn = v_t_up_driver_down_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_t_up = v_t_up_driver_up_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_up = v_driver_up_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_voldn = v_atmvol_down_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + vol_volup = v_atmvol_up_exp.compute_vol(rawk, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + conversion_vol = v_orig_exp.conversion_vol, + conversion_fwd = v_orig_exp.conversion_fwd + }; + exp_values.Add(k_vm); + /// all these calculations chould have been short circuited + /// for the following, but for code simplicity we just set + /// vol to 0 and fwd to settle (and use vol==0 as a marker) + if (!Double.IsNaN(settlement_price)) + { + k_vm.vol = 0; + k_vm.fwd = settlement_price; + } + } + } + } + return rv; + } + + /// Copies movement operation as an action + /// across all exps + private static IDictionary _copy_action(IEnumerable exps, VolCurveMovementOperation movement_op) + { + return exps.ToDictionary(exp => exp, exp => new VolCurveAction(movement_op)); + } + } +} diff --git a/src/client/spark/Analytics/SplineModel/SplineModelVolCurveCalculator.cs b/src/client/spark/Analytics/SplineModel/SplineModelVolCurveCalculator.cs new file mode 100644 index 000000000..30f618822 --- /dev/null +++ b/src/client/spark/Analytics/SplineModel/SplineModelVolCurveCalculator.cs @@ -0,0 +1,306 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class SplineModelVolCurveCalculator : IVolCurveMainCalculator + { + private VolSurfaceSettings _vs_settings; + private VolCurveParameters _input_parameters; + private VolCurveAction _action; + private VolSurfaceExpirationAuxiliaryData _aux_data; + private IEnumerable _control_points; + private CubicSpline _spline; + private VolCurveParameters _adjusted_parameters; + private double _final_unresponded_atm_vol = Double.NaN, _final_reponded_atm_vol = Double.NaN; + private CoordinatesBasedModelHelper.ControlPoint.Axis _cp_axis; + + private bool _initialized = true; + + #region IVolCurveMainCalculator + + public void initialize_for_lifetime(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move, + VolCurveAction curve_action) + { + _vs_settings = surface_settings; + _input_parameters = curve_parameters; + _action = curve_action; + path_induced_atm_vol_move = Double.IsNaN(path_induced_atm_vol_move) ? 0.0 : path_induced_atm_vol_move; + _aux_data = aux_data; + _initialized = _can_compute(curve_parameters, _aux_data.fwd, path_induced_atm_vol_move); + curve_action = CoordinatesBasedModelHelper.clean_action(curve_action); + if (_initialized) + { + if (curve_action.action_type != VolCurveAction.ActionType.FitToMarket) + { + if (curve_action.action_type == VolCurveAction.ActionType.Rebuild) + { + _price_invariant_rebuild(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move); + } + else + { + VolCurveMovementOperation movement_action = curve_action.curve_operation; + movement_action = VolSurfaceCoreFunctions.normalize_atm_move_action(movement_action, curve_parameters.spline_model_parameters.atm_vol + path_induced_atm_vol_move, aux_data, _get_conversion_fwd()); + double atm_vol_action_move = movement_action == null ? 0.0 : VolSurfaceUtilityFunctions.find_atm_vol_move(movement_action); + _final_unresponded_atm_vol = curve_parameters.spline_model_parameters.atm_vol + atm_vol_action_move; + _final_reponded_atm_vol = _final_unresponded_atm_vol + path_induced_atm_vol_move; + _control_points = CoordinatesBasedModelHelper.convert_to_controlpoints(surface_settings.spline_model_settings.vol_axis, + surface_settings.spline_model_settings.strike_axis, + surface_settings.advanced_settings.strike_normalization_axis, + curve_parameters.spline_model_parameters.put_points, + curve_parameters.spline_model_parameters.call_points, + _convert_strike_axis); + _cp_axis = _control_points != null && _control_points.Count() > 0 ? _control_points.ElementAt(0).y_axis : CoordinatesBasedModelHelper.ControlPoint.Axis.Mult; + _spline = _get_spline(_control_points, null); + movement_action = VolSurfaceCoreFunctions.normalize_shape_action(movement_action, _aux_data, _convert_strike_axis, + (strike, axis) => _compute_vol(strike, axis)); + _control_points = CoordinatesBasedModelHelper.apply_action(_control_points, movement_action, curve_parameters.spline_model_parameters.atm_vol + path_induced_atm_vol_move); + _adjusted_parameters = _get_adjusted_parameters(_control_points, surface_settings, curve_parameters, _aux_data, atm_vol_action_move, path_induced_atm_vol_move, curve_action.action_type == VolCurveAction.ActionType.Rebuild); + _spline = _get_spline(_control_points, null); + } + } + else + { + VolCurveMarketFitAction market_fit_action = curve_action.market_fit_action; + if (market_fit_action != null && market_fit_action.implied_vol_data != null) + { + /// atm_vol get adjusted to market's atm vol in all market fit scenarios + _final_reponded_atm_vol = _final_unresponded_atm_vol = market_fit_action.implied_vol_data.atm_vol; + if (market_fit_action.fit_action == VolCurveMarketFitAction.ActionType.FitATM) + _control_points = CoordinatesBasedModelHelper.convert_to_controlpoints(surface_settings.spline_model_settings.vol_axis, + surface_settings.spline_model_settings.strike_axis, + surface_settings.advanced_settings.strike_normalization_axis, + curve_parameters.spline_model_parameters.put_points, + curve_parameters.spline_model_parameters.call_points, + _convert_strike_axis); + else if (market_fit_action.fit_action == VolCurveMarketFitAction.ActionType.FitWholeCurve) + _control_points = CoordinatesBasedModelHelper.fit_to_market(market_fit_action.implied_vol_data, + _aux_data, + surface_settings.core_settings.market_fit_settings, + surface_settings.spline_model_settings.vol_axis, + surface_settings.spline_model_settings.strike_axis, + surface_settings.advanced_settings.strike_normalization_axis, + _convert_strike_axis, + curve_parameters.spline_model_parameters.put_points, + curve_parameters.spline_model_parameters.call_points, + market_fit_action.use_weighted_regression); + _cp_axis = _control_points != null && _control_points.Count() > 0 ? _control_points.ElementAt(0).y_axis : CoordinatesBasedModelHelper.ControlPoint.Axis.Mult; + _adjusted_parameters = _get_adjusted_parameters(_control_points, surface_settings, curve_parameters, _aux_data, _final_reponded_atm_vol - curve_parameters.spline_model_parameters.atm_vol, 0, true); + _spline = _get_spline(_control_points, null); + } + } + } + else + _adjusted_parameters = curve_parameters; + } + + /// The main idea is to minimize for shape changes in raw strike space. This is achieved + /// by keeping the change to vols at the raw strikes corresponding to the control points to 0. + private void _price_invariant_rebuild(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolCurveParameters curve_parameters, + VolSurfaceExpirationAuxiliaryData aux_data, + double path_induced_atm_vol_move) + { + SplineModelVolCurveCalculator curr_calc = new SplineModelVolCurveCalculator(); + curr_calc.initialize_for_lifetime(expiration, surface_settings, curve_parameters, aux_data, path_induced_atm_vol_move, new VolCurveAction(VolCurveAction.ActionType.None)); + double new_atm_vol = curr_calc._compute_vol(aux_data.fwd, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike), + conversion_vol = curr_calc._get_conversion_vol(); + List> new_put_points = new List>(), new_call_points = new List>(); + foreach (var put_point in curve_parameters.spline_model_parameters.put_points) + { + /// This is the new raw_k's where the control points will now fall (with the new fwd and new convesion_vol (if not std vol)). + /// We find the curr vol for that raw_k and assign that at the vol for the points. That way the raw strike points at + /// the control points will have the same abs vol + double new_cp_put_raw_k = VolSurfaceCoreFunctions.convert_axis(surface_settings.spline_model_settings.strike_axis, put_point.Item1, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, conversion_vol, aux_data); + double curr_vol = curr_calc._compute_vol_with_infinite_extension(new_cp_put_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + double new_abstract_vol = curr_calc._cp_axis == CoordinatesBasedModelHelper.ControlPoint.Axis.Add ? curr_vol - new_atm_vol : curr_vol / new_atm_vol; + new_put_points.Add(Tuple.Create(put_point.Item1, new_abstract_vol)); + } + foreach (var call_point in curve_parameters.spline_model_parameters.call_points) + { + double new_cp_call_raw_k = VolSurfaceCoreFunctions.convert_axis(surface_settings.spline_model_settings.strike_axis, call_point.Item1, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, conversion_vol, aux_data); + double curr_vol = curr_calc._compute_vol_with_infinite_extension(new_cp_call_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + double abstract_vol = curr_calc._cp_axis == CoordinatesBasedModelHelper.ControlPoint.Axis.Add ? curr_vol - new_atm_vol : curr_vol / new_atm_vol; + new_call_points.Add(Tuple.Create(call_point.Item1, abstract_vol)); + } + SplineModelVolCurveParameters new_spline_params = new SplineModelVolCurveParameters() + { + atm_vol = new_atm_vol, + put_points = new List>(new_put_points), + call_points = new List>(new_call_points) + }; + VolCurveCoreParameters new_core_params = VolSurfaceUtilityFunctions.clone_proto(curve_parameters.core_parameters); + new_core_params.ref_forward = aux_data.fwd; + VolCurveParameters new_curve_params = new VolCurveParameters() + { + core_parameters = new_core_params, + spline_model_parameters = new_spline_params + }; + initialize_for_lifetime(expiration, surface_settings, new_curve_params, aux_data, 0.0, new VolCurveAction(VolCurveAction.ActionType.None)); + } + + public bool is_initialized() { return _initialized; } + + public VolCurveParameters fill_missing_inputs(VolCurveParameters main_curve_params, VolCurveParameters sec_curve_params) + { + CoordinatesBasedModelHelper.CoordinatesBasedModelInput main_inp = new CoordinatesBasedModelHelper.CoordinatesBasedModelInput(main_curve_params.spline_model_parameters.atm_vol, main_curve_params.spline_model_parameters.put_points, main_curve_params.spline_model_parameters.call_points), + sec_inp = new CoordinatesBasedModelHelper.CoordinatesBasedModelInput(sec_curve_params.spline_model_parameters.atm_vol, sec_curve_params.spline_model_parameters.put_points, sec_curve_params.spline_model_parameters.call_points); + CoordinatesBasedModelHelper.CoordinatesBasedModelInput res_inp = CoordinatesBasedModelHelper.fill_missing_input(main_inp, sec_inp); + VolCurveParameters rv = VolSurfaceUtilityFunctions.clone_proto(main_curve_params); + rv.spline_model_parameters = new SplineModelVolCurveParameters() { atm_vol = res_inp.atm_vol, put_points = res_inp.put_points.ToList(), call_points = res_inp.call_points.ToList() }; + return rv; + } + + public VolCurveMainOutput get_output() + { + if (_initialized) + { + double input_atm_vol = _final_unresponded_atm_vol, final_atm_vol = _final_reponded_atm_vol; + IEnumerable cp_put_strikes, cp_call_strikes; + CoordinatesBasedModelHelper.get_controlpoint_strikes(_control_points, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, _convert_strike_axis, out cp_put_strikes, out cp_call_strikes); + double put_end_raw_strike, call_end_raw_strike; + CoordinatesBasedModelHelper.get_end_points(_control_points, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, _convert_strike_axis, out put_end_raw_strike, out call_end_raw_strike); + return new VolCurveMainOutput(_aux_data.fwd, + _get_conversion_fwd (), + input_atm_vol, + final_atm_vol, + _get_conversion_vol(), + cp_put_strikes, + cp_call_strikes, + put_end_raw_strike, + call_end_raw_strike, + _adjusted_parameters, + _aux_data, + _compute_vol, + _convert_strike_axis); + } + else + return new VolCurveMainOutput(Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Enumerable.Empty(), Enumerable.Empty(), + Double.NaN, Double.NaN, + _adjusted_parameters, _aux_data, (k, k_axis, nth_derv) => Double.NaN, + (source_axis, k, target_axis) => Double.NaN); + } + + public void Dispose() { } + + #endregion + + private double _compute_vol(double strike, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, uint nth_derv = 0) + { + if (_initialized) + { + if (nth_derv == 0) + { + double x = _convert_strike_axis(strike_axis, strike, _vs_settings.advanced_settings.strike_normalization_axis); + double fn = _spline.compute(x, nth_derv); + return _cp_axis == CoordinatesBasedModelHelper.ControlPoint.Axis.Add ? fn + _final_reponded_atm_vol : fn * _final_reponded_atm_vol; + } + else + { + double x = _convert_strike_axis(strike_axis, strike, VolSurfaceEnums.VolCurveStrikeAxis.StandardStrike); + return VolSurfaceCoreFunctions.compute_df(strike_arg => _compute_vol(strike_arg, strike_axis), strike, + x >= 0 ? VolSurfaceCoreFunctions.DerivativeType.BackwardDifference : VolSurfaceCoreFunctions.DerivativeType.ForwardDifference, nth_derv); + } + } + else + return Double.NaN; + } + + private double _compute_vol_with_infinite_extension(double strike, VolSurfaceEnums.VolCurveStrikeAxis strike_axis) + { + if (_initialized) + { + double x = _convert_strike_axis(strike_axis, strike, _vs_settings.advanced_settings.strike_normalization_axis); + double fn = _spline.compute_with_infinite_extension(x); + return _cp_axis == CoordinatesBasedModelHelper.ControlPoint.Axis.Add ? fn + _final_reponded_atm_vol : fn * _final_reponded_atm_vol; + } + else + return Double.NaN; + } + + private double _convert_strike_axis(VolSurfaceEnums.VolCurveStrikeAxis source_axis, double source_point, VolSurfaceEnums.VolCurveStrikeAxis target_axis) + { + return VolSurfaceCoreFunctions.convert_axis(source_axis, source_point, target_axis, + _get_conversion_vol(), _get_conversion_fwd(), _aux_data.biz_t, _aux_data.cal_t, _aux_data.riskless_rate); + } + + private double _get_conversion_vol() + { + if (_vs_settings.core_settings.strike_conversion_vol == VolSurfaceEnums.StrikeConversionVol.StandardVol) return _input_parameters.core_parameters.standard_vol; + else + { + if (VolSurfaceUtilityFunctions.is_rebuild_action(_action)) + return _final_reponded_atm_vol; + else + { + double conv_vol_slider = _input_parameters.core_parameters.conversion_vol_slider; + conv_vol_slider = Double.IsNaN(conv_vol_slider) ? 0.0 : VolSurfaceUtilityFunctions.restrict_bw_min_and_max(conv_vol_slider, 0.0, 1.0); + return (conv_vol_slider * _final_reponded_atm_vol) + ((1 - conv_vol_slider) * _final_unresponded_atm_vol); + } + } + } + + private double _get_conversion_fwd() + { + if (VolSurfaceUtilityFunctions.is_rebuild_action(_action)) + return _aux_data.fwd; + else + { + double conv_fwd_slider = _input_parameters.core_parameters.conversion_fwd_slider; + conv_fwd_slider = Double.IsNaN(conv_fwd_slider) ? 0.0 : VolSurfaceUtilityFunctions.restrict_bw_min_and_max(conv_fwd_slider, 0.0, 1.0); + /// the 1.0 check is just so that users who dont want to deal with ref_fwd's can leave it + /// unattended and we dont run into a NaN situation + return VolSurfaceUtilityFunctions.compare_doubles(conv_fwd_slider, 1.0) ? _aux_data.fwd : (conv_fwd_slider * _aux_data.fwd) + ((1 - conv_fwd_slider) * _input_parameters.core_parameters.ref_forward); + } + } + + private static CubicSpline _get_spline(IEnumerable control_points, VolCurveWingParameters wing_parameters) + { + IEnumerable> coords = control_points.Select(cp => Tuple.Create(cp.normalization_strike, cp.input_abstract_vol)); + coords = coords.Where(t => !Double.IsNaN(t.Item1) && !Double.IsNaN(t.Item2)); + return new CubicSpline(coords); + } + + private static bool _can_compute(VolCurveParameters curve_parameters, double current_fwd, double path_induced_atm_vol_move) + { + return !Double.IsNaN(current_fwd) && + !Double.IsNaN(path_induced_atm_vol_move) && + curve_parameters != null && + curve_parameters.spline_model_parameters != null && + !Double.IsNaN(curve_parameters.spline_model_parameters.atm_vol) && + curve_parameters.spline_model_parameters.put_points.Where(t => !Double.IsNaN(t.Item1) && !Double.IsNaN(t.Item2)).Count() > 0 && + curve_parameters.spline_model_parameters.call_points.Where(t => !Double.IsNaN(t.Item1) && !Double.IsNaN(t.Item2)).Count() > 0; + } + + private static VolCurveParameters _get_adjusted_parameters(IEnumerable controlpoints, + VolSurfaceSettings settings, + VolCurveParameters input_curve_paramaters, + VolSurfaceExpirationAuxiliaryData aux_data, + double parallel_curve_move, + double volpath_move, + bool is_rebuild) + { + double adjusted_atm_vol; + IEnumerable> adjusted_put_points, adjusted_call_points; + double adjusted_ref_fwd, adjusted_ref_vol; + CoordinatesBasedModelHelper.get_adjusted_parameters(controlpoints, input_curve_paramaters.core_parameters, settings.spline_model_settings.vol_axis, settings.spline_model_settings.strike_axis, + input_curve_paramaters.spline_model_parameters.atm_vol, parallel_curve_move, volpath_move, aux_data.fwd, is_rebuild, + out adjusted_atm_vol, out adjusted_put_points, out adjusted_call_points, out adjusted_ref_fwd, out adjusted_ref_vol); + VolCurveParameters rv = new VolCurveParameters() + { + core_parameters = input_curve_paramaters.core_parameters, + spline_model_parameters = new SplineModelVolCurveParameters() { atm_vol = adjusted_atm_vol, put_points = adjusted_put_points.ToList(), call_points = adjusted_call_points.ToList() } + }; + rv.core_parameters.ref_forward = adjusted_ref_fwd; + return rv; + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/SplineModel/SplineModelVolCurveParameters.cs b/src/client/spark/Analytics/SplineModel/SplineModelVolCurveParameters.cs new file mode 100644 index 000000000..e40d9ab1b --- /dev/null +++ b/src/client/spark/Analytics/SplineModel/SplineModelVolCurveParameters.cs @@ -0,0 +1,45 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// Same as the Polynomial counterpart + [ProtoBuf.ProtoContract(Name = "SplineModelVolCurveParameters")] + public class SplineModelVolCurveParameters + { + [ProtoBuf.ProtoMember(10)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double atm_vol = Double.NaN; + [ProtoBuf.ProtoMember(20)] + public List> put_points; + [ProtoBuf.ProtoMember(30)] + public List> call_points; + + // public static explicit operator SplineModelVolCurveParameters(bts.api.analytics.APISplineModelVolCurveParameters other) + // { + // var data = new SplineModelVolCurveParameters + // { + // atm_vol = other.atm_vol, + // }; + // data.call_points = other.call_points.Select((x, i) => Tuple.Create(x, other.call_factors[i])).ToList(); + // data.put_points = other.put_points.Select((x, i) => Tuple.Create(x, other.put_factors[i])).ToList(); + // return data; + // } + + // public static explicit operator bts.api.analytics.APISplineModelVolCurveParameters(SplineModelVolCurveParameters other) + // { + // var data = new bts.api.analytics.APISplineModelVolCurveParameters + // { + // atm_vol = other.atm_vol, + // put_points = other.put_points.Select(x => x.Item1).ToArray(), + // put_factors = other.put_points.Select(x => x.Item2).ToArray(), + // call_points = other.call_points.Select(x => x.Item1).ToArray(), + // call_factors = other.call_points.Select(x => x.Item2).ToArray(), + // }; + // return data; + // } + } +} diff --git a/src/client/spark/Analytics/SplineModel/SplineModelVolSurfaceSettings.cs b/src/client/spark/Analytics/SplineModel/SplineModelVolSurfaceSettings.cs new file mode 100644 index 000000000..a37f48f0d --- /dev/null +++ b/src/client/spark/Analytics/SplineModel/SplineModelVolSurfaceSettings.cs @@ -0,0 +1,27 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "SplineModelVolSurfaceSettings")] + public class SplineModelVolSurfaceSettings + { + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.VolCurveStrikeAxis strike_axis; + [ProtoBuf.ProtoMember(20)] + public VolSurfaceEnums.VolCurveVolAxis vol_axis; + [ProtoBuf.ProtoMember(30)] + public uint n_call_points; + [ProtoBuf.ProtoMember(40)] + public uint n_put_points; + [ProtoBuf.ProtoMember(50)] + public List put_points; + [ProtoBuf.ProtoMember(60)] + public List call_points; + [ProtoBuf.ProtoMember(70)] + public bool same_across_all_exps; + } +} diff --git a/src/client/spark/Analytics/SupportingData/AnalyticsExpirationParameters.cs b/src/client/spark/Analytics/SupportingData/AnalyticsExpirationParameters.cs new file mode 100644 index 000000000..e9639413f --- /dev/null +++ b/src/client/spark/Analytics/SupportingData/AnalyticsExpirationParameters.cs @@ -0,0 +1,62 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [Serializable] + public class AnalyticsExpirationParameters : IEquatable + { + public readonly SecurityExpiration security, + driver_security, + deliverable_security, + roll_schedule_expiration; + public readonly double roll_target, riskless_rate, settlement_price; + public readonly double driver_addend, driver_factor, driver_translation_target, delta_beta, vega_beta; + + public static AnalyticsExpirationParameters empty = new AnalyticsExpirationParameters(SecurityExpiration.empty, SecurityExpiration.empty, SecurityExpiration.empty, SecurityExpiration.empty, + Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN); + + public AnalyticsExpirationParameters(SecurityExpiration this_security, SecurityExpiration this_driver_security, SecurityExpiration this_deliverable_security, SecurityExpiration this_roll_schedule_expiration, + double this_roll_target, double this_riskless_rate, double this_settlement_price, double this_delta_beta, double this_vega_beta) + { + security = this_security; + driver_security = this_driver_security; + deliverable_security = this_deliverable_security; + roll_schedule_expiration = this_roll_schedule_expiration; + roll_target = this_roll_target; + riskless_rate = this_riskless_rate; + settlement_price = this_settlement_price; + delta_beta = this_delta_beta; + vega_beta = this_vega_beta; + + } + + public bool Equals(AnalyticsExpirationParameters other) + { + return other != null && + security.Equals(other.security) && + _null_equal(driver_security, other.driver_security) && + _null_equal(deliverable_security, other.deliverable_security) && + _null_equal(roll_schedule_expiration, other.roll_schedule_expiration) && + roll_target.Equals(other.roll_target) && + riskless_rate.Equals(other.riskless_rate) && + settlement_price.Equals(other.settlement_price) && + delta_beta.Equals(other.delta_beta) && + vega_beta.Equals(other.vega_beta); + } + + public override bool Equals(object obj) { return Equals(obj as AnalyticsExpirationParameters); } + + public override int GetHashCode() { return security.GetHashCode(); } + + private static bool _null_equal(SecurityExpiration a, SecurityExpiration b) + { + a = a == null ? null : (a.is_empty() ? null : a); + b = b == null ? null : (b.is_empty() ? null : b); + return (a == null && b == null) || (a != null && b != null && a.Equals(b)); + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/SupportingData/VolSurfaceExpirationAuxiliaryData.cs b/src/client/spark/Analytics/SupportingData/VolSurfaceExpirationAuxiliaryData.cs new file mode 100644 index 000000000..264239a03 --- /dev/null +++ b/src/client/spark/Analytics/SupportingData/VolSurfaceExpirationAuxiliaryData.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// This might need better organization, but this + /// is all the data that is needed for an expiration + /// wrt vol calculations (dividend schedule is ignored + /// for now). + public class VolSurfaceExpirationAuxiliaryData + { + public const double min_biz_t_yrs = 0.05 / 252; + public readonly double spot = Double.NaN; + public readonly double fwd = Double.NaN; + public readonly double driver_price = Double.NaN; + public readonly double growth = Double.NaN; + public readonly double dfwd_dund = Double.NaN; + public readonly double dspot_dund = Double.NaN; + public readonly DateTime base_vol_time = DateTime.MinValue; + public readonly double biz_t = Double.NaN; /// in years + public readonly double cal_t = Double.NaN; /// in years + public readonly double riskless_rate = Double.NaN; + public readonly double settlement_price = Double.NaN; + public readonly double roll = Double.NaN; + public readonly double bizdays_per_yr = Double.NaN; + public readonly double caldays_per_yr = Double.NaN; + + public static readonly VolSurfaceExpirationAuxiliaryData empty = new VolSurfaceExpirationAuxiliaryData(); + + private VolSurfaceExpirationAuxiliaryData() { } + + public VolSurfaceExpirationAuxiliaryData(double this_spot, + double this_fwd, + double this_driver_price, + double this_growth, + double this_dfwd_dund, + double this_dspot_dund, + DateTime this_base_vol_time, + double this_biz_t, + double this_cal_t, + double this_riskless_rate, + double this_settlement_price, + double this_roll, + double this_bizdays_per_yr, + double this_caldays_per_yr) + { + spot = this_spot; + fwd = this_fwd; + driver_price = this_driver_price; + growth = this_growth; + dfwd_dund = this_dfwd_dund; + dspot_dund = this_dspot_dund; + base_vol_time = this_base_vol_time; + biz_t = this_biz_t; + cal_t = this_cal_t; + riskless_rate = this_riskless_rate; + settlement_price = this_settlement_price; + roll = this_roll; + bizdays_per_yr = this_bizdays_per_yr; + caldays_per_yr = this_caldays_per_yr; + } + + public double biz_days { get { return biz_t * bizdays_per_yr; } } + + public double cal_days { get { return cal_t * caldays_per_yr; } } + + /// The shifts are numerical additions. So for time, it simply + /// subtracts time_shift from biz_t. So if you want to move the + /// the-date up (or "take time off"), pass a -ve time_shift + public VolSurfaceExpirationAuxiliaryData shift_driver_time(double driver_shift, double time_shift) + { + double new_driver = driver_price + driver_shift; + double new_spot = spot + (driver_shift * dspot_dund); + double new_fwd = fwd + (dfwd_dund * driver_shift); + double new_biz_t = Math.Max(biz_t + time_shift, min_biz_t_yrs); + double new_cal_t = cal_t;// +time_shift; + return new VolSurfaceExpirationAuxiliaryData(new_spot, new_fwd, new_driver, growth, dfwd_dund, dspot_dund, base_vol_time, new_biz_t, new_cal_t, riskless_rate, settlement_price, roll, bizdays_per_yr, caldays_per_yr); + } + } +} diff --git a/src/client/spark/Analytics/SupportingData/VolSurfaceExpirationTimeData.cs b/src/client/spark/Analytics/SupportingData/VolSurfaceExpirationTimeData.cs new file mode 100644 index 000000000..0a33c81a8 --- /dev/null +++ b/src/client/spark/Analytics/SupportingData/VolSurfaceExpirationTimeData.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// + /// We can come up with T (either for vol or pricing) by knowing + /// 1. The class below + /// 2. The time set by the user + /// 3. Whether to use cal or biz days (setting) + /// + public class VolSurfaceExpirationTimeData + { + /// The time when the option actually expires + public readonly DateTime expiration_datetime; + /// The time of the day when trading starts and stops + public readonly DateTime regular_start_time, regular_stop_time; + public IEnumerable weekends; + /// For days that where trading hours diverge from the regular + /// trading hours (above). The 2nd and 3rd arguments are the + /// start, stop time respectively. Start=stop for complete holidays + public readonly IEnumerable> non_full_trading_days; + + public VolSurfaceExpirationTimeData(DateTime this_expiration_datetime, + DateTime this_regular_start_time, DateTime this_regular_stop_time, + IEnumerable this_weekends, + IEnumerable> this_non_full_trading_days) + { + expiration_datetime = this_expiration_datetime; + regular_start_time = this_regular_start_time; + regular_stop_time = this_regular_stop_time; + weekends = this_weekends; + non_full_trading_days = this_non_full_trading_days; + } + + public static TimeSpan get_timeperiod(DateTime start, VolSurfaceExpirationTimeData exp_data, double additional_hours) + { + TimeSpan rv = TimeSpan.Zero; + HashSet weekend_map = new HashSet(exp_data.weekends); + IDictionary> non_full_map = new Dictionary>(); + foreach (Tuple t in exp_data.non_full_trading_days) + non_full_map[t.Item1.Date] = t; + if (start > exp_data.expiration_datetime) + return TimeSpan.Zero; + else + { + DateTime d = start.Date; + while (d <= exp_data.expiration_datetime) + { + if (d.Date == exp_data.expiration_datetime.Date) + rv = rv.Add(_get_time_diff(exp_data.regular_start_time, exp_data.expiration_datetime)); + else + { + if (!weekend_map.Contains(d.DayOfWeek)) + { + Tuple non_full = null; + if (non_full_map.TryGetValue(d, out non_full)) + rv = rv.Add(_get_time_diff(non_full.Item3, non_full.Item2)); + else + rv = rv.Add(_get_time_diff(exp_data.regular_start_time, exp_data.regular_stop_time)); + } + } + d = d.AddDays(1.0); + } + rv = rv.Add(TimeSpan.FromHours(additional_hours)); + } + return rv; + } + + private static TimeSpan _get_time_diff(DateTime start_time, DateTime stop_time) + { + TimeSpan tod_1 = start_time.TimeOfDay, tod_2 = stop_time.TimeOfDay; + return tod_2 > tod_1 ? tod_2 - tod_1 : TimeSpan.Zero; + } + } +} diff --git a/src/client/spark/Analytics/SupportingData/VolSurfaceNonVolData.cs b/src/client/spark/Analytics/SupportingData/VolSurfaceNonVolData.cs new file mode 100644 index 000000000..b028969e7 --- /dev/null +++ b/src/client/spark/Analytics/SupportingData/VolSurfaceNonVolData.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using ProtoBuf; + +using bts.api; +using bts.settings; +using bts.spark; + +using mbts.spark; +using mbts; + +namespace mbts.analytics +{ + /// Just a conveniant packaging of data for a single + /// Vol surface. The input is for all symbols across + /// the system + public class VolSurfaceNonVolData + { + public readonly VolSurfaceNonVolInput input; + public readonly IDictionary driver_price_map; + public readonly IDictionary> contracts; + public readonly HashSet strike_map; + + public VolSurfaceNonVolData(VolSurfaceNonVolInput input, + IDictionary driver_price_map, + IDictionary> contracts) + { + this.input = input; + this.driver_price_map = driver_price_map; + this.contracts = contracts; + //TODO + //strike_map = VolSurfaceUtilityFunctions.convert_to_strike_map(contracts); + } + + public IEnumerable> get_cpp_list() + { + return input.get_cpp_list(); + } + + public IDictionary get_cpp_map() + { + return input.get_cpp_list().ToDictionary(i => new mbts.SecurityTuple(i.Item1, i.Item2, Venue.Unset), i => i.Item3); + } + + private static mbts.SecurityExpiration _unset = mbts.SecurityExpiration.empty; + public HashSet get_associated_non_options() + { + HashSet rv = new HashSet(); + foreach (VolSurfaceExpiration exp in contracts.Keys) + { + AnalyticsExpirationParameters exp_params = input.find_exp_parameter(SecurityType.Option, exp.symbol, exp.expiration); + if (exp_params != null) + { + if (exp_params.driver_security != null && !exp_params.driver_security.Equals(_unset)) + rv.Add(exp_params.driver_security.unset_exchange()); + if (exp_params.deliverable_security != null && !exp_params.deliverable_security.Equals(_unset)) + rv.Add(exp_params.deliverable_security.unset_exchange()); + } + } + return rv; + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/SupportingData/VolSurfaceNonVolInput.cs b/src/client/spark/Analytics/SupportingData/VolSurfaceNonVolInput.cs new file mode 100644 index 000000000..beddc586d --- /dev/null +++ b/src/client/spark/Analytics/SupportingData/VolSurfaceNonVolInput.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using ProtoBuf; + +using bts.api; +using bts.settings; +using bts.spark; + +using mbts.spark; + +namespace mbts.analytics +{ + /// This is the input data (other than vol) that + /// is used for vol/price calculations. It is not + /// vol surface specific, but spans across all the + /// entire symbols in the system. It consists of + /// 1. Symbol based data + /// - cpp + /// - expiration time + /// - holiday schedule + /// 2. Expiration based data + /// - driver + /// - deliverable + /// - roll + /// - settlement price (if applicable) + /// - interest rate + public class VolSurfaceNonVolInput + { + //public readonly bts.config.StaticConfiguration sym_input; + public readonly IDictionary exp_input_map; + + public VolSurfaceNonVolInput(/*bts.config.StaticConfiguration this_sym_input,*/ + IDictionary this_exp_input_map) + { + //sym_input = this_sym_input; + exp_input_map = this_exp_input_map; + } + + public IDictionary get_option_exp_input() + { + var list = exp_input_map.Where(kv => kv.Key.security_type == SecurityType.Option); + return list.ToDictionary(kv => new VolSurfaceExpiration() { symbol = kv.Key.symbol, expiration = kv.Key.expiration }, kv => kv.Value); + } + + public AnalyticsExpirationParameters find_exp_parameter(SecurityExpiration exp) + { + AnalyticsExpirationParameters rv = null; + return exp_input_map.TryGetValue(exp, out rv) ? rv : null; + } + + /// This ignores the exchange in the comparison and returns + /// the first match. This will be a problem for multi-listed + /// symbols + public AnalyticsExpirationParameters find_exp_parameter(SecurityType sec_type, string symbol, DateTime exp) + { + /// TODO:incons + foreach (KeyValuePair kv in exp_input_map) + if (kv.Key.security_type == sec_type && kv.Key.symbol == symbol && kv.Key.expiration == exp) + return kv.Value; + return null; + } + + public IEnumerable> get_cpp_list() + { + return null; + // return sym_input.securities.Select(s => Tuple.Create(s.security_metadata.security.security_type, s.security_metadata.security.security_name, s.security_metadata.cash_per_point)); + } + + public IDictionary get_cpp_map() + { + // TODO + //return get_cpp_list().ToDictionaryDupes(t => new mbts.SecurityTuple(t.Item1, t.Item2, Exchange.type.UNSET), t => t.Item3); + return get_cpp_list().ToDictionary(t => new mbts.SecurityTuple(t.Item1, t.Item2, Venue.Unset), t => t.Item3); + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/VolPath/IVolPathCalculator.cs b/src/client/spark/Analytics/VolPath/IVolPathCalculator.cs new file mode 100644 index 000000000..3b9c02b96 --- /dev/null +++ b/src/client/spark/Analytics/VolPath/IVolPathCalculator.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// This interface wraps up the idea of the ATM Vol move, + /// given the new price and the ref price, it comes + /// up with the new atm vol + public interface IVolPathCalculator + { + void initialize_for_lifetime(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolPathParameters volpath_parameters); + VolPathParameters fill_missing_inputs(VolPathParameters main, VolPathParameters secondary); + double get_atm_vol_move(double ref_price, double new_price); + } +} diff --git a/src/client/spark/Analytics/VolPath/Parabolic/ParabolicVolPathCalculator.cs b/src/client/spark/Analytics/VolPath/Parabolic/ParabolicVolPathCalculator.cs new file mode 100644 index 000000000..4d785784c --- /dev/null +++ b/src/client/spark/Analytics/VolPath/Parabolic/ParabolicVolPathCalculator.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts; + +namespace mbts.analytics +{ + public class ParabolicVolPathCalculator : IVolPathCalculator + { + private ParabolicVolPathParameters _params; + private double[] _coeffs; + private ParabolicVolPathSettings _settings; + public void initialize_for_lifetime(VolSurfaceExpiration expiration, VolSurfaceSettings surface_settings, VolPathParameters volpath_parameters) + { + _params = volpath_parameters.parabolic_volpath_parameters; + _settings = surface_settings.core_settings.volpath_settings.parabolic_vol_path_settings; + ParabolicVolPathParameters parab_params = (volpath_parameters != null && volpath_parameters.parabolic_volpath_parameters != null) ? volpath_parameters.parabolic_volpath_parameters : null; + _coeffs = VolSurfaceCoreFunctions.get_exactfit_polynomial_coeffs(new Tuple[] { + Tuple.Create (-1.0 * Math.Abs (parab_params.down_move_point.Item1), parab_params.down_move_point.Item2), + Tuple.Create (0.0, 0.0), + Tuple.Create (Math.Abs (parab_params.up_move_point.Item1), parab_params.up_move_point.Item2) + }).ToArray(); + } + + public VolPathParameters fill_missing_inputs(VolPathParameters main, VolPathParameters secondary) + { + Log.assert(false); + return null; + } + + public double get_atm_vol_move(double ref_price, double new_price) + { + double x_move = new_price - ref_price; + if (_settings.price_change_measure == VolSurfaceEnums.GeneralChangeMeasure.Percentage) x_move = 100.0 * x_move / ref_price; + else if (_settings.price_change_measure == VolSurfaceEnums.GeneralChangeMeasure.Ratio) x_move = x_move / ref_price; + double rv = VolSurfaceCoreFunctions.compute_polynomial_df(_coeffs, x_move); + return rv > 0 ? Math.Min(rv, _max_abs_vol_increase) : rv = -1.0 * Math.Min(Math.Abs(rv), _max_abs_vol_decrease); + } + + private double _max_abs_vol_increase { get { return (Double.IsNaN(_params.max_vol_increase) || _params.max_vol_increase == 0) ? Double.MaxValue : Math.Abs(_params.max_vol_increase); } } + + private double _max_abs_vol_decrease { get { return (Double.IsNaN(_params.max_vol_decrease) || _params.max_vol_decrease == 0) ? Double.MaxValue : Math.Abs(_params.max_vol_decrease); } } + + } +} diff --git a/src/client/spark/Analytics/VolPath/Parabolic/ParabolicVolPathParameters.cs b/src/client/spark/Analytics/VolPath/Parabolic/ParabolicVolPathParameters.cs new file mode 100644 index 000000000..eba23b0cf --- /dev/null +++ b/src/client/spark/Analytics/VolPath/Parabolic/ParabolicVolPathParameters.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "ParabolicVolPathParameters")] + public class ParabolicVolPathParameters + { + [ProtoBuf.ProtoMember(10)] + public Tuple down_move_point; + [ProtoBuf.ProtoMember(20)] + public Tuple up_move_point; + [ProtoBuf.ProtoMember(30)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double max_vol_increase; + [ProtoBuf.ProtoMember(40)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double max_vol_decrease; + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/VolPath/Parabolic/ParabolicVolPathSettings.cs b/src/client/spark/Analytics/VolPath/Parabolic/ParabolicVolPathSettings.cs new file mode 100644 index 000000000..743a2f417 --- /dev/null +++ b/src/client/spark/Analytics/VolPath/Parabolic/ParabolicVolPathSettings.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "ParabolicVolPathSettings")] + public class ParabolicVolPathSettings + { + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.GeneralChangeMeasure price_change_measure; + [ProtoBuf.ProtoMember(20)] + public VolSurfaceEnums.GeneralChangeMeasure vol_change_measure; + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/VolPath/SimpleTwoPointVolPathParameters.cs b/src/client/spark/Analytics/VolPath/SimpleTwoPointVolPathParameters.cs new file mode 100644 index 000000000..d972ca25e --- /dev/null +++ b/src/client/spark/Analytics/VolPath/SimpleTwoPointVolPathParameters.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// + /// This is the simplest parametrization of a VolPath, + /// with a down point (ie when market moves down) and + /// an up path. The is wrt to the ref being the mid, + /// and movements are incremental to the Vol @ Ref + /// + [ProtoBuf.ProtoContract(Name = "SimpleTwoPointVolPathParameters")] + public class SimpleTwoPointVolPathParameters + { + [ProtoBuf.ProtoMember(10)] + public Tuple down_move_point; + [ProtoBuf.ProtoMember(20)] + public Tuple up_move_point; + } +} diff --git a/src/client/spark/Analytics/VolPath/TwoWaySlopeVolPathCalculator.cs b/src/client/spark/Analytics/VolPath/TwoWaySlopeVolPathCalculator.cs new file mode 100644 index 000000000..51d88c6d1 --- /dev/null +++ b/src/client/spark/Analytics/VolPath/TwoWaySlopeVolPathCalculator.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class TwoWaySlopeVolPathCalculator : IVolPathCalculator + { + private double _fwd_down_vol_slope, _fwd_up_vol_slope, + _max_vol_increase, _max_vol_decrease, + _joint_speed; + public void initialize_for_lifetime(VolSurfaceExpiration expiration, + VolSurfaceSettings surface_settings, + VolPathParameters volpath_parameters) + { + /// TODO, get % vs abs from settings + _fwd_down_vol_slope = 0.0; _fwd_up_vol_slope = 0.0; + if (volpath_parameters.two_way_slope_vol_path_parameters != null) + { + _fwd_down_vol_slope = volpath_parameters.two_way_slope_vol_path_parameters.vol_move_for_unit_fwd_down; + _fwd_up_vol_slope = volpath_parameters.two_way_slope_vol_path_parameters.vol_move_for_unit_fwd_up; + _max_vol_increase = Math.Abs(volpath_parameters.two_way_slope_vol_path_parameters.max_vol_increase); + _max_vol_decrease = Math.Abs(volpath_parameters.two_way_slope_vol_path_parameters.max_vol_decrease); + _joint_speed = volpath_parameters.two_way_slope_vol_path_parameters.joint_speed; + } + } + + public VolPathParameters fill_missing_inputs(VolPathParameters main, VolPathParameters secondary) + { + TwoWaySlopeVolPathParameters main_model_inp = main != null && main.two_way_slope_vol_path_parameters != null ? main.two_way_slope_vol_path_parameters : _new(), + sec_model_inp = secondary != null && secondary.two_way_slope_vol_path_parameters != null ? secondary.two_way_slope_vol_path_parameters : _new(); + return new VolPathParameters() + { + two_way_slope_vol_path_parameters = new TwoWaySlopeVolPathParameters() + { + vol_move_for_unit_fwd_down = _non_nan(main_model_inp.vol_move_for_unit_fwd_down, sec_model_inp.vol_move_for_unit_fwd_down), + vol_move_for_unit_fwd_up = _non_nan(main_model_inp.vol_move_for_unit_fwd_up, sec_model_inp.vol_move_for_unit_fwd_up), + max_vol_decrease = _non_nan(main_model_inp.max_vol_decrease, sec_model_inp.max_vol_decrease), + max_vol_increase = _non_nan(main_model_inp.max_vol_increase, sec_model_inp.max_vol_increase), + asymptote_speed_for_fwd_down = _non_nan(main_model_inp.asymptote_speed_for_fwd_down, sec_model_inp.asymptote_speed_for_fwd_down), + asymptote_speed_for_fwd_up = _non_nan(main_model_inp.asymptote_speed_for_fwd_up, sec_model_inp.asymptote_speed_for_fwd_up), + joint_speed = _non_nan (main_model_inp.joint_speed, sec_model_inp.joint_speed) + } + }; + } + + public double get_atm_vol_move(double ref_price, double new_price) + { + double rv = VolSurfaceCoreFunctions.compute_twowayslope_reponse(new_price, ref_price, _fwd_down_vol_slope, -1.0 * _fwd_up_vol_slope, _joint_speed); + if (rv > 0 && !Double.IsNaN(_max_vol_increase)) + rv = Math.Min(rv, _max_vol_increase); + if (rv < 0 && !Double.IsNaN(_max_vol_decrease)) + rv = -1.0 * Math.Min(Math.Abs(rv), _max_vol_decrease); + return rv; + } + + #region Stateless Helpers + private static double _non_nan(double main, double sec) { return !double.IsNaN(main) ? main : sec; } + + private static TwoWaySlopeVolPathParameters _new() + { + return new TwoWaySlopeVolPathParameters() + { + vol_move_for_unit_fwd_up = double.NaN, + vol_move_for_unit_fwd_down = double.NaN, + max_vol_increase = double.NaN, + max_vol_decrease = double.NaN, + asymptote_speed_for_fwd_up = double.NaN, + asymptote_speed_for_fwd_down = double.NaN, + joint_speed = double.NaN + }; + } + #endregion + } +} diff --git a/src/client/spark/Analytics/VolPath/TwoWaySlopeVolPathParameters.cs b/src/client/spark/Analytics/VolPath/TwoWaySlopeVolPathParameters.cs new file mode 100644 index 000000000..d1c9354da --- /dev/null +++ b/src/client/spark/Analytics/VolPath/TwoWaySlopeVolPathParameters.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "TwoWaySlopeVolPathParameters")] + public class TwoWaySlopeVolPathParameters + { + /// This is the vol move (from input atm vol) per 1 $ move in the fwd. + /// Sings matter : the sign of the vol change should +ve for vol going up + [ProtoBuf.ProtoMember(10)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double vol_move_for_unit_fwd_up = double.NaN; + /// Same as above for donward move + [ProtoBuf.ProtoMember(20)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double vol_move_for_unit_fwd_down = double.NaN; + /// This is the max vol move (from input atm vol) on the upwards move in the fwd + [ProtoBuf.ProtoMember(30)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double max_vol_increase = double.NaN; + /// Same as above for donward move + [ProtoBuf.ProtoMember(40)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double max_vol_decrease = double.NaN; + /// This is the rate at which the path approaches the asymptote on downwards move + [ProtoBuf.ProtoMember(50)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double asymptote_speed_for_fwd_down = double.NaN; + /// Same as above for donward move + [ProtoBuf.ProtoMember(60)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double asymptote_speed_for_fwd_up = double.NaN; + [ProtoBuf.ProtoMember(70)] + [System.ComponentModel.DefaultValue(1.5)] + public double joint_speed = double.NaN; + } +} diff --git a/src/client/spark/Analytics/VolPath/TwoWaySlopeVolPathSettings.cs b/src/client/spark/Analytics/VolPath/TwoWaySlopeVolPathSettings.cs new file mode 100644 index 000000000..fe6ae90dd --- /dev/null +++ b/src/client/spark/Analytics/VolPath/TwoWaySlopeVolPathSettings.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "TwoWaySlopeVolPathSettings")] + public class TwoWaySlopeVolPathSettings + { + /// The fwd change can be represented in absolute $ move or % from ref fwd + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.GeneralChangeMeasure fwd_change_measure; + /// Vol path induced change can be expressed in vol points move or % from atm input vol + [ProtoBuf.ProtoMember(20)] + public VolSurfaceEnums.GeneralChangeMeasure vol_change_measure; + } +} diff --git a/src/client/spark/Analytics/VolPath/VolPathParameters.cs b/src/client/spark/Analytics/VolPath/VolPathParameters.cs new file mode 100644 index 000000000..27b188081 --- /dev/null +++ b/src/client/spark/Analytics/VolPath/VolPathParameters.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// Union of of vol paths + [ProtoBuf.ProtoContract(Name = "VolPathParameters")] + public class VolPathParameters + { + [ProtoBuf.ProtoMember(10)] + public SimpleTwoPointVolPathParameters simple_two_point_volpath_parameters; + [ProtoBuf.ProtoMember(20)] + public TwoWaySlopeVolPathParameters two_way_slope_vol_path_parameters; + [ProtoBuf.ProtoMember(30)] + public ParabolicVolPathParameters parabolic_volpath_parameters; + // [ProtoBuf.ProtoMember(1000)] + // public CustomModelVolResponseParameters custom_parameters; + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/VolPath/VolPathSettings.cs b/src/client/spark/Analytics/VolPath/VolPathSettings.cs new file mode 100644 index 000000000..938250818 --- /dev/null +++ b/src/client/spark/Analytics/VolPath/VolPathSettings.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolPathSettings")] + public class VolPathSettings + { + [ProtoBuf.ProtoMember(1)] + public VolSurfaceEnums.VolSurfaceVolPathModel vol_path_model; + [ProtoBuf.ProtoMember(50)] + public TwoWaySlopeVolPathSettings two_way_slope_vol_path_settings; + [ProtoBuf.ProtoMember(60)] + public ParabolicVolPathSettings parabolic_vol_path_settings; + } +} diff --git a/src/client/spark/Analytics/Wings/ExplicitSlope/VolCurveExplicitSlopeWingCalculator.cs b/src/client/spark/Analytics/Wings/ExplicitSlope/VolCurveExplicitSlopeWingCalculator.cs new file mode 100644 index 000000000..bc15ffed8 --- /dev/null +++ b/src/client/spark/Analytics/Wings/ExplicitSlope/VolCurveExplicitSlopeWingCalculator.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + public class VolCurveExplicitSlopeWingCalculator : IVolCurveWingCalculator + { + private double _put_start_raw_k, _call_start_raw_k; + private Func _put_wing_f, _call_wing_f; + private const uint _approx_order = 1; + private VolCurveWingParameters _put_wing_parameters, _call_wing_parameters; + private VolCurveMainOutput _main_curve_output; + private readonly bool _fit_wings_to_market = false; + + #region IVolCurveWingCalculator + public void initialize_for_lifetime(VolSurfaceSettings surface_settings, + VolCurveWingParameters put_wing_parameters, + VolCurveWingParameters call_wing_parameters, + VolCurveMainOutput main_curve_output, + VolCurveAction curve_action) + { + _put_wing_parameters = VolSurfaceUtilityFunctions.clone_proto(put_wing_parameters); + _call_wing_parameters = VolSurfaceUtilityFunctions.clone_proto(call_wing_parameters); + _main_curve_output = main_curve_output; + _put_start_raw_k = main_curve_output.put_end_raw_strike; + _call_start_raw_k = main_curve_output.call_end_raw_strike; + double put_start_vol = main_curve_output.get_dvol(_put_start_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 0), + call_start_vol = main_curve_output.get_dvol(_call_start_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 0); + + if (_fit_wings_to_market && curve_action != null && curve_action.action_type == VolCurveAction.ActionType.FitToMarket && + curve_action.market_fit_action != null && curve_action.market_fit_action.fit_action == VolCurveMarketFitAction.ActionType.FitWholeCurve && + VolSurfaceCoreFunctions.is_suitable_for_fit (curve_action.market_fit_action.implied_vol_data)) + { + /// fitting the wings to implied vols + double put_start_dvol = main_curve_output.get_dvol(_put_start_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 1), + call_start_dvol = main_curve_output.get_dvol(_call_start_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 1); + IEnumerable> p_points = _add_weights(curve_action.market_fit_action.implied_vol_data.put_rawk_vols.Where(kv => kv.Key < _put_start_raw_k), false), + c_points = _add_weights(curve_action.market_fit_action.implied_vol_data.call_rawk_vols.Where(kv => kv.Key > _call_start_raw_k), true); + /// puts + IEnumerable put_reg_line = VolSurfaceCoreFunctions.get_constrained_least_squares_polynomial(p_points, new Tuple[] { Tuple.Create(_put_start_raw_k, put_start_vol) }, 1); + if (put_reg_line != null && put_reg_line.Count() == 2) + _put_wing_parameters.explicit_slope_wing_parameters.slope = put_reg_line.ElementAt(1); + /// calls + IEnumerable call_reg_line = VolSurfaceCoreFunctions.get_constrained_least_squares_polynomial(c_points, new Tuple[] { Tuple.Create(_call_start_raw_k, call_start_vol) }, 1); + if (call_reg_line != null && call_reg_line.Count() == 2) + _call_wing_parameters.explicit_slope_wing_parameters.slope = call_reg_line.ElementAt(1); + } + VolCurveExplicitSlopeWingParameters put_params = _put_wing_parameters.explicit_slope_wing_parameters, + call_params = _call_wing_parameters.explicit_slope_wing_parameters; + _put_wing_f = VolSurfaceCoreFunctions.get_oblique_asymptote_func(_put_start_raw_k, nth_derv => main_curve_output.get_dvol(_put_start_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, nth_derv), _approx_order, + put_params.main_curve_decay, put_params.slope, put_start_vol - put_params.slope * _put_start_raw_k); + _call_wing_f = VolSurfaceCoreFunctions.get_oblique_asymptote_func(_call_start_raw_k, nth_derv => main_curve_output.get_dvol(_call_start_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, nth_derv), _approx_order, + call_params.main_curve_decay, call_params.slope, call_start_vol - call_params.slope * _call_start_raw_k); + } + + private static IEnumerable> _add_weights(IEnumerable> vol_points, bool is_call) + { + vol_points = vol_points.OrderBy(i => i.Key); + vol_points = is_call ? vol_points : vol_points.Reverse(); + List> rv = new List>(); + for (int i = 0; i < vol_points.Count(); i++) + { + KeyValuePair k_vol = vol_points.ElementAt(i); + rv.Add(Tuple.Create(k_vol.Key, k_vol.Value, 10.0 * (vol_points.Count() - i))); + } + return rv; + } + + public VolCurveWingOutput get_output() { return new VolCurveWingOutput(_put_wing_parameters, _call_wing_parameters, _compute_vol); } + #endregion + + private double _compute_vol(double strike, VolSurfaceEnums.VolCurveStrikeAxis axis, uint nth_derv = 0) + { + strike = _convert_to_raw_strike(strike, axis); + if (strike >= _call_start_raw_k) + return _call_wing_f(strike); + else if (strike <= _put_start_raw_k) + return _put_wing_f(strike); + else + return double.NaN; + } + + private double _convert_to_raw_strike(double strike, VolSurfaceEnums.VolCurveStrikeAxis x_axis) + { + return _main_curve_output.convert_axis(x_axis, strike, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + } + + #region Stateless Helpers + private static double _non_nan(double main, double sec) { return !double.IsNaN(main) ? main : sec; } + + private static VolCurveExplicitSlopeWingParameters _new() + { + return new VolCurveExplicitSlopeWingParameters() + { + distance = double.NaN, + main_curve_decay = double.NaN, + slope = double.NaN + }; + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Wings/ExplicitSlope/VolCurveExplicitSlopeWingParameters.cs b/src/client/spark/Analytics/Wings/ExplicitSlope/VolCurveExplicitSlopeWingParameters.cs new file mode 100644 index 000000000..e6ae0f493 --- /dev/null +++ b/src/client/spark/Analytics/Wings/ExplicitSlope/VolCurveExplicitSlopeWingParameters.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolCurveExplicitSlopeWingParameters")] + public class VolCurveExplicitSlopeWingParameters + { + [ProtoBuf.ProtoMember(10)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double slope = Double.NaN; + [ProtoBuf.ProtoMember(20)] + public double distance = Double.NaN; + [ProtoBuf.ProtoMember(30)] + [System.ComponentModel.DefaultValue (Double.NaN)] + public double main_curve_decay = Double.NaN; + } +} diff --git a/src/client/spark/Analytics/Wings/ExplicitSlope/VolSurfaceExplicitSlopeWingSettings.cs b/src/client/spark/Analytics/Wings/ExplicitSlope/VolSurfaceExplicitSlopeWingSettings.cs new file mode 100644 index 000000000..5fed4a4a9 --- /dev/null +++ b/src/client/spark/Analytics/Wings/ExplicitSlope/VolSurfaceExplicitSlopeWingSettings.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolSurfaceExplicitSlopeWingSettings")] + public class VolSurfaceExplicitSlopeWingSettings + { + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.VolCurveStrikeAxis wing_start_strike_axis; + } +} diff --git a/src/client/spark/Analytics/Wings/IVolCurveWingCalculator.cs b/src/client/spark/Analytics/Wings/IVolCurveWingCalculator.cs new file mode 100644 index 000000000..b0231edb0 --- /dev/null +++ b/src/client/spark/Analytics/Wings/IVolCurveWingCalculator.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// Computes the vols (and its derivatives wrt the x-axis) + /// in the wing region of a vol curve at a given x-axis + /// strike point (which can be any strike respresentation, + /// raw, moneyness/standard strike etc) + public interface IVolCurveWingCalculator + { + void initialize_for_lifetime(VolSurfaceSettings surface_settings, + VolCurveWingParameters put_wing_parameters, + VolCurveWingParameters call_wing_parameters, + VolCurveMainOutput main_curve_output, + VolCurveAction curve_action); + VolCurveWingOutput get_output(); + } +} diff --git a/src/client/spark/Analytics/Wings/ImplicitSlope/VolCurveImplicitSlopeWingCalculator.cs b/src/client/spark/Analytics/Wings/ImplicitSlope/VolCurveImplicitSlopeWingCalculator.cs new file mode 100644 index 000000000..27458ceec --- /dev/null +++ b/src/client/spark/Analytics/Wings/ImplicitSlope/VolCurveImplicitSlopeWingCalculator.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// Extends the curve beyond the meat, with straight lines + /// having the same slope as the meat at the end points wrt + /// raw stikes + public class VolCurveImplicitSlopeWingCalculator : IVolCurveWingCalculator + { + private VolCurveWingParameters _put_wing_parameters, _call_wing_parameters; + private VolCurveMainOutput _main_curve_output; + private Tuple _put_start, _call_start; + private Tuple _put_rawk_line, _call_rawk_line; + private double _put_max_vol, _call_max_vol; + + #region IVolCurveWingCalculator + public void initialize_for_lifetime(VolSurfaceSettings surface_settings, + VolCurveWingParameters put_wing_parameters, + VolCurveWingParameters call_wing_parameters, + VolCurveMainOutput main_curve_output, + VolCurveAction curve_action) + { + /// this wing calc does not change the input parameters + _put_wing_parameters = put_wing_parameters; + _call_wing_parameters = call_wing_parameters; + _main_curve_output = main_curve_output; + _put_max_vol = put_wing_parameters.simple_slope_wing_parameters.max_vol; + _call_max_vol = call_wing_parameters.simple_slope_wing_parameters.max_vol; + double put_start_raw_k = main_curve_output.put_end_raw_strike, + call_start_raw_k = main_curve_output.call_end_raw_strike, + put_start_y = main_curve_output.get_dvol(put_start_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 0), + call_start_y = main_curve_output.get_dvol(call_start_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 0), + put_start_dy = main_curve_output.get_dvol(put_start_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 1), + call_start_dy = main_curve_output.get_dvol(call_start_raw_k, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike, 1); + _put_start = Tuple.Create(put_start_raw_k, put_start_y); + _call_start = Tuple.Create(call_start_raw_k, call_start_y); + double a, b; + VolSurfaceCoreFunctions.get_line(_put_start, put_start_dy, out a, out b); + _put_rawk_line = Tuple.Create(a, b); + VolSurfaceCoreFunctions.get_line(_call_start, call_start_dy, out a, out b); + _call_rawk_line = Tuple.Create(a, b); + } + + public VolCurveWingOutput get_output() { return new VolCurveWingOutput(_put_wing_parameters, _call_wing_parameters, _compute_vol); } + #endregion + + private static double _non_nan(double main, double sec) { return !double.IsNaN(main) ? main : sec; } + + private double _compute_vol(double strike, VolSurfaceEnums.VolCurveStrikeAxis axis, uint nth_derv = 0) + { + strike = _convert_to_raw_strike(strike, axis); + if (strike < _put_start.Item1) + { + /// put wing + double rv = _put_rawk_line.Item1 * strike + _put_rawk_line.Item2; + rv = Math.Max(0.0, Math.Min(rv, _put_max_vol)); + return rv; + } + else if (strike > _call_start.Item1) + { + /// call wing + double rv = _call_rawk_line.Item1 * strike + _call_rawk_line.Item2; + rv = Math.Max(0.0, Math.Min(rv, _call_max_vol)); + return rv; + } + else + { + return Double.NaN; + } + } + + private double _convert_to_raw_strike(double strike, VolSurfaceEnums.VolCurveStrikeAxis x_axis) + { + return _main_curve_output.convert_axis(x_axis, strike, VolSurfaceEnums.VolCurveStrikeAxis.RawStrike); + } + } +} \ No newline at end of file diff --git a/src/client/spark/Analytics/Wings/ImplicitSlope/VolCurveSimpleSlopeWingParameters.cs b/src/client/spark/Analytics/Wings/ImplicitSlope/VolCurveSimpleSlopeWingParameters.cs new file mode 100644 index 000000000..78c973602 --- /dev/null +++ b/src/client/spark/Analytics/Wings/ImplicitSlope/VolCurveSimpleSlopeWingParameters.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// This wing starts with the slope at the + /// wing_start_strike and asymptotically + /// approaches the max_vol. + [ProtoBuf.ProtoContract(Name = "VolCurveSimpleSlopeWingParameters")] + public class VolCurveSimpleSlopeWingParameters + { + [ProtoBuf.ProtoMember(10)] + [System.ComponentModel.DefaultValue(Double.NaN)] + public double max_vol = double.NaN; + } +} diff --git a/src/client/spark/Analytics/Wings/ImplicitSlope/VolSurfaceImplicitSlopeWingSettings.cs b/src/client/spark/Analytics/Wings/ImplicitSlope/VolSurfaceImplicitSlopeWingSettings.cs new file mode 100644 index 000000000..0c52c294f --- /dev/null +++ b/src/client/spark/Analytics/Wings/ImplicitSlope/VolSurfaceImplicitSlopeWingSettings.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolSurfaceSimpleSlopeWingSettings")] + public class VolSurfaceImplicitSlopeWingSettings + { + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.VolCurveStrikeAxis wing_start_strike_axis; + } +} diff --git a/src/client/spark/Analytics/Wings/OnePointSlope/VolCurveOnePointSlopeWingParameters.cs b/src/client/spark/Analytics/Wings/OnePointSlope/VolCurveOnePointSlopeWingParameters.cs new file mode 100644 index 000000000..1c9158dc8 --- /dev/null +++ b/src/client/spark/Analytics/Wings/OnePointSlope/VolCurveOnePointSlopeWingParameters.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolCurveOnePointSlopeWingParameters")] + public class VolCurveOnePointSlopeWingParameters + { + [ProtoBuf.ProtoMember(10)] + public Tuple slope_point; + } +} diff --git a/src/client/spark/Analytics/Wings/OnePointSlope/VolSurfaceOnePointSlopeWingSettings.cs b/src/client/spark/Analytics/Wings/OnePointSlope/VolSurfaceOnePointSlopeWingSettings.cs new file mode 100644 index 000000000..ce67a1077 --- /dev/null +++ b/src/client/spark/Analytics/Wings/OnePointSlope/VolSurfaceOnePointSlopeWingSettings.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolSurfaceOnePointSlopeWingSettings")] + public class VolSurfaceOnePointSlopeWingSettings + { + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.VolCurveStrikeAxis wing_start_strike_axis; + [ProtoBuf.ProtoMember(20)] + public VolSurfaceEnums.VolCurveStrikeAxis wing_slope_point_strike_axis; + [ProtoBuf.ProtoMember(30)] + public bool rotate_with_main_curve = true; + } +} diff --git a/src/client/spark/Analytics/Wings/VolCurveWingParameters.cs b/src/client/spark/Analytics/Wings/VolCurveWingParameters.cs new file mode 100644 index 000000000..fd742ceb4 --- /dev/null +++ b/src/client/spark/Analytics/Wings/VolCurveWingParameters.cs @@ -0,0 +1,25 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// "Union" class that will hold all wing parameters. + [ProtoBuf.ProtoContract(Name = "VolCurveWingParameters")] + public class VolCurveWingParameters + { + /// Every wing model has to have the notion of where + /// the wings start (This can be pushed to the curve + /// parameters too, so that the curve controls it) + [ProtoBuf.ProtoMember(10)] + public double wing_start_strike = double.NaN; + [ProtoBuf.ProtoMember(20)] + public VolCurveSimpleSlopeWingParameters simple_slope_wing_parameters; /// TODO, rename + [ProtoBuf.ProtoMember(30)] + public VolCurveOnePointSlopeWingParameters onepoint_slope_wing_parameters; + [ProtoBuf.ProtoMember(40)] + public VolCurveExplicitSlopeWingParameters explicit_slope_wing_parameters; + } +} diff --git a/src/client/spark/Analytics/Wings/VolSurfaceWingSettings.cs b/src/client/spark/Analytics/Wings/VolSurfaceWingSettings.cs new file mode 100644 index 000000000..60c525734 --- /dev/null +++ b/src/client/spark/Analytics/Wings/VolSurfaceWingSettings.cs @@ -0,0 +1,21 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + [ProtoBuf.ProtoContract(Name = "VolSurfaceWingSettings")] + public class VolSurfaceWingSettings + { + [ProtoBuf.ProtoMember(10)] + public VolSurfaceEnums.VolCurveWingModel wing_model = VolSurfaceEnums.VolCurveWingModel.ImplicitSlopeWithHorizontalAsymptotes; + [ProtoBuf.ProtoMember(30)] + public VolSurfaceImplicitSlopeWingSettings implicit_slope_wing_settings; + [ProtoBuf.ProtoMember(40)] + public VolSurfaceExplicitSlopeWingSettings explicit_slope_wing_settings; + [ProtoBuf.ProtoMember(50)] + public VolSurfaceOnePointSlopeWingSettings onepoint_slope_wing_settings; + } +} diff --git a/src/client/spark/Spark.csproj b/src/client/spark/Spark.csproj index 06ef8c592..4f8304966 100644 --- a/src/client/spark/Spark.csproj +++ b/src/client/spark/Spark.csproj @@ -26,6 +26,7 @@ 1.0.0 + diff --git a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs index a009ff234..cdf1b9dc8 100644 --- a/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs +++ b/src/client/spark_core/Collections/Extensions/EnumerableExtensions.cs @@ -751,5 +751,15 @@ namespace System.Collections.Generic { public void RemoveAt(int index) => _list.RemoveAt(index); IEnumerator IEnumerable.GetEnumerator() => _list.GetEnumerator(); } + + public static void AddRange(this ISet set, IEnumerable items) { + foreach (T t in items) + set.Add(t); + //items.ForEach(i => set.Add(i)); + } + public static void AddRange(this ISet set, params T[] items) { + foreach (T t in items) + set.Add(t); + } } } diff --git a/src/lib/domain_model/Security.proto b/src/lib/domain_model/Security.proto index 7b8939baa..3e5d329a1 100644 --- a/src/lib/domain_model/Security.proto +++ b/src/lib/domain_model/Security.proto @@ -197,3 +197,34 @@ message Product { bts.api.SecurityType type = 2; string symbol = 3; } + +// abomination of the only data AW2 didnt take over + +message DateTimeType +{ + double oa_date = 10; +} + +message Holiday +{ + double date = 10; + double percent_day_not_trading = 20; +} + +message StaticHolidays +{ + string key = 10; + repeated Holiday static_holiday_collection = 20; +} + +message StaticSecurityMetaData +{ + string key = 5; + string security_name = 10; + StaticHolidays holidays = 20; +} + +message StaticConfiguration +{ + repeated StaticSecurityMetaData securities = 10; +}