Adding VoLSurface calulation code
This commit is contained in:
1 parent
c0e75c2de2
commit
31bb4c418e
94 files changed
+11101
No files matched your search
@@ -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<VolSurfaceExpiration, IEnumerable<double>> exp_strike_map,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> 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<VolSurfaceExpiration, IEnumerable<double>> exp_strike_map,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map,
|
||||
IDictionary<VolSurfaceExpiration, VolCurveAction> action_map,
|
||||
IDictionary<VolSurfaceExpiration, HashSet<double>> 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<VolSurfaceExpiration, VolCurveAction>();
|
||||
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<VolSurfaceExpiration, VolCurveAction> action_map,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map)
|
||||
{
|
||||
VolSurfaceInput rv = vs_input;
|
||||
if (action_map.Count() > 0 && action_map.ElementAt(0).Value.action_type == VolCurveAction.ActionType.SyncSlaveRefFwds)
|
||||
{
|
||||
HashSet<VolSurfaceExpiration> slave_exps = VolSurfaceUtilityFunctions.get_slave_expirations(vs_input);
|
||||
VolSurfaceUtilityFunctions.are_hashsets_equal(VolSurfaceUtilityFunctions.get_slave_expirations(vs_input), new HashSet<VolSurfaceExpiration>(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<VolSurfaceExpiration, IEnumerable<double>> exp_strike_map,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map,
|
||||
IDictionary<VolSurfaceExpiration, VolCurveAction> vol_curve_action_map,
|
||||
IDictionary<VolSurfaceExpiration, HashSet<double>> secs_filter)
|
||||
{
|
||||
Log.assert(VolSurfaceUtilityFunctions.are_hashsets_equal(new HashSet<VolSurfaceExpiration>(exp_strike_map.Keys),
|
||||
new HashSet<VolSurfaceExpiration>(vs_input.surface_parameters.curve_parameters_map.Select(t => t.Item1)),
|
||||
new HashSet<VolSurfaceExpiration>(aux_data_map.Keys),
|
||||
new HashSet<VolSurfaceExpiration>(vol_curve_action_map.Keys)));
|
||||
IDictionary<VolSurfaceExpiration, VolCurveOutput> computed_map = new ConcurrentDictionary<VolSurfaceExpiration, VolCurveOutput>();
|
||||
secs_filter = secs_filter ?? exp_strike_map.ToDictionary(kv => kv.Key, kv => new HashSet<double>());
|
||||
//Parallel.ForEach(exp_strike_map.ToList(), kv =>
|
||||
exp_strike_map.ToList().ForEach(kv =>
|
||||
{
|
||||
VolSurfaceExpiration exp = kv.Key;
|
||||
IEnumerable<double> 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<KeyValuePair<VolSurfaceExpiration, IEnumerable<double>>> 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<VolSurfaceExpiration, VolCurveOutput> 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<double> 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<VolSurfaceExpiration, HashSet<double>> _adjust_filters_for_missing_masters(VolSurfaceInput vs_input,
|
||||
IDictionary<VolSurfaceExpiration, HashSet<double>> secs_filter)
|
||||
{
|
||||
if (secs_filter != null)
|
||||
{
|
||||
IEnumerable<VolSurfaceExpiration> vs_exps = vs_input.surface_parameters.curve_parameters_map.Select(t => t.Item1);
|
||||
Dictionary<VolSurfaceExpiration, HashSet<double>> rv = new Dictionary<VolSurfaceExpiration, HashSet<double>>(secs_filter);
|
||||
foreach (KeyValuePair<VolSurfaceExpiration, HashSet<double>> 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<double>();
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
else
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<double> 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<double, VolSurfaceEnums.VolCurveStrikeAxis, double> 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<double, double> 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; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<double> 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<double, VolSurfaceEnums.VolCurveStrikeAxis, uint, double> get_dvol;
|
||||
public readonly Func<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> 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<double> this_special_put_points,
|
||||
IEnumerable<double> 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<double, VolSurfaceEnums.VolCurveStrikeAxis, uint, double> this_get_dvol,
|
||||
Func<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<double> tradeable_strikes;
|
||||
public readonly IEnumerable<Tuple<double, double>> optional_call_control_points, optional_put_control_points;
|
||||
public readonly double optional_call_wing_start, optional_put_wing_start;
|
||||
public readonly Func<double, VolSurfaceEnums.VolCurveStrikeAxis, double> compute_vol;
|
||||
public readonly Func<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> convert_strike_axis;
|
||||
public readonly Func<double, double> 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<double> this_tradeable_strikes,
|
||||
VolCurveParameters this_curve_parameters,
|
||||
IEnumerable<Tuple<double, double>> this_optional_call_control_points,
|
||||
IEnumerable<Tuple<double, double>> this_optional_put_control_points,
|
||||
double this_optional_call_wing_start,
|
||||
double this_optional_put_wing_start,
|
||||
Func<double, VolSurfaceEnums.VolCurveStrikeAxis, double> this_compute_vol,
|
||||
Func<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> this_convert_strike_axis,
|
||||
Func<double, double> 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<double, double> _strike_vol_map = null;
|
||||
public IDictionary<double, double> strike_vol_map
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_strike_vol_map == null)
|
||||
{
|
||||
lock (typeof(VolCurveOutput))
|
||||
{
|
||||
if (_strike_vol_map == null)
|
||||
{
|
||||
_strike_vol_map = new Dictionary<double, double>();
|
||||
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<double>(), 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<double, VolSurfaceEnums.VolCurveStrikeAxis, uint, double> get_dvol;
|
||||
|
||||
public VolCurveWingOutput(VolCurveWingParameters this_adjusted_put_wing_parameters,
|
||||
VolCurveWingParameters this_adjusted_call_wing_parameters,
|
||||
Func<double, VolSurfaceEnums.VolCurveStrikeAxis, uint, double> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<VolSurfaceExpiration, VolCurveOutput> exp_output_map;
|
||||
public readonly IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map;
|
||||
|
||||
public VolSurfaceOutput(VolSurfaceInput this_volsurface_input,
|
||||
IDictionary<VolSurfaceExpiration, VolCurveOutput> this_exp_output_map,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> 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<VolSurfaceExpiration, VolCurveOutput>(exp_output_map),
|
||||
// new Dictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData>(aux_data_map));
|
||||
}
|
||||
|
||||
public static VolSurfaceOutput get_empty_output()
|
||||
{
|
||||
return new VolSurfaceOutput(new VolSurfaceInput(),
|
||||
new Dictionary<VolSurfaceExpiration, VolCurveOutput>(),
|
||||
new Dictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData>());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
// };
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<Tuple<VolSurfaceExpiration, VolCurveParameters>> curve_parameters_map;
|
||||
[ProtoBuf.ProtoMember(30)]
|
||||
public VolSurfaceTimeParameters time_parameters;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<Tuple<DateTime, double>> auto_decay_points;
|
||||
}
|
||||
}
|
||||
@@ -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<SecurityExpiration>
|
||||
{
|
||||
[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;
|
||||
}
|
||||
}
|
||||
@@ -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<SecurityStrike>
|
||||
{
|
||||
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); }
|
||||
}
|
||||
}
|
||||
@@ -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<SecurityTuple>, IEquatable<SecurityTuple>
|
||||
// {
|
||||
// [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<SecurityTuple> 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<SecurityTuple> Members
|
||||
// public bool Equals(SecurityTuple other) { return other != null && CompareTo(other) == 0; }
|
||||
// #endregion
|
||||
// }
|
||||
|
||||
// // public interface ISecurityLookup
|
||||
// // {
|
||||
// // SecurityTuple get_security(UInt32 security_key);
|
||||
// // }
|
||||
// }
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<double> precomputed_theo_handles;
|
||||
|
||||
[ProtoBuf.ProtoMember(15)]
|
||||
[System.ComponentModel.DefaultValue(VolSurfaceEnums.GeneralChangeMeasure.Absolute)]
|
||||
public VolSurfaceEnums.GeneralChangeMeasure theo_handle_measure;
|
||||
|
||||
[ProtoBuf.ProtoMember(20)]
|
||||
public List<double> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<string> symbols;
|
||||
[ProtoBuf.ProtoMember(25)]
|
||||
public List<VolSurfaceSymbolStructure> 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<VolSurfaceSymbolStructure> symbol_implied_vol_marketdata_source_list;
|
||||
[ProtoBuf.ProtoMember(170)]
|
||||
public List<Tuple<string, VolSurfaceEnums.VolSurfacePricingModel>> symbol_pricing_model_map;
|
||||
[ProtoBuf.ProtoMember(180)]
|
||||
public List<VolSurfaceSymbolRelationship> implied_vol_marketdata_relationships;
|
||||
[ProtoBuf.ProtoMember(190)]
|
||||
public List<VolSurfaceSymbolRelationship> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace mbts.analytics
|
||||
{
|
||||
[ProtoBuf.ProtoContract(Name = "TimeMeasure")]
|
||||
public class VolSurfaceTimeMeasure : IEquatable<VolSurfaceTimeMeasure>
|
||||
{
|
||||
[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(); }
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+19
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Tuple<double, double>> strike_vol_movement_pairs;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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)
|
||||
/// </summary>
|
||||
public enum StrikeConversionVol
|
||||
{
|
||||
[System.ComponentModel.DescriptionAttribute("ATM")]
|
||||
ATMVol,
|
||||
[System.ComponentModel.DescriptionAttribute("Path ATM")]
|
||||
PathATMVol,
|
||||
[System.ComponentModel.DescriptionAttribute("Standard")]
|
||||
StandardVol
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Anologous to StrikeConversionVol, for the fwd
|
||||
/// </summary>
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[ProtoBuf.ProtoContract(Name = "VolSurfaceExpiration")]
|
||||
public class VolSurfaceExpiration : IEquatable<VolSurfaceExpiration>, IComparable<VolSurfaceExpiration>
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string> slave_symbol_list;
|
||||
}
|
||||
|
||||
[ProtoBuf.ProtoContract(Name = "VolSurfaceSymbolRelationship")]
|
||||
public class VolSurfaceSymbolRelationship
|
||||
{
|
||||
[ProtoBuf.ProtoMember(10)]
|
||||
public string symbol;
|
||||
[ProtoBuf.ProtoMember(20)]
|
||||
public List<string> connected_symbols;
|
||||
}
|
||||
}
|
||||
@@ -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<double, double> 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<double> put_coeffs = VolSurfaceCoreFunctions.get_constrained_least_squares_polynomial(put_points.Select(t => Tuple.Create(t.Key, t.Value, 1.0)),
|
||||
new Tuple<double, double>[] { Tuple.Create(atm_strike, atm_vol) }, 2);
|
||||
/// call side
|
||||
IDictionary<double, double> 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<double> call_coeffs = VolSurfaceCoreFunctions.get_constrained_least_squares_polynomial(call_points.Select(t => Tuple.Create(t.Key, t.Value, 1.0)),
|
||||
new Tuple<double, double>[] { 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Tuple<double, double>> new_put_points = new List<Tuple<double, double>>(), new_call_points = new List<Tuple<double, double>>();
|
||||
//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<double> _empty_doubles = Enumerable.Empty<double>();
|
||||
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<double>(), Enumerable.Empty<double>(),
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<double, double> 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); } }
|
||||
}
|
||||
}
|
||||
@@ -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<double, double> _fixed_point;
|
||||
|
||||
protected SimpleQudratic(double a, double b, double c, Tuple<double, double> p) { _coeffs = new double[] { c, b, a }; _fixed_point = p; }
|
||||
|
||||
public SimpleQudratic(double a, double b, Tuple<double, double> 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<double, double> move)
|
||||
{
|
||||
Tuple<double, double> p1 = _fixed_point, p2 = Tuple.Create(move.Item1, compute(move.Item1, 0) + move.Item2);
|
||||
IEnumerable<double> 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<double, double> _p0;
|
||||
|
||||
public SimpleQudraticZero(double a, double b, Tuple<double, double> 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<double, double> location_amount)
|
||||
{
|
||||
double new_slope = _b + location_amount.Item2 / location_amount.Item1;
|
||||
return new SimpleQudraticZero(_a, new_slope, _p0);
|
||||
}
|
||||
|
||||
public SimpleQudraticZero rotate_curvature(Tuple<double, double> location_amount)
|
||||
{
|
||||
double new_curvature = _a + (location_amount.Item2 / (location_amount.Item1 * location_amount.Item1));
|
||||
return new SimpleQudraticZero(new_curvature, _b, _p0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<double, double> put_rawk_vols, call_rawk_vols, stdk_vols = new Dictionary<double, double>();
|
||||
public readonly double atm_strike, atm_vol, conversion_vol;
|
||||
|
||||
public VolCurveMarketImpliedVolData(VolSurfaceExpirationAuxiliaryData this_aux_data,
|
||||
VolSurfaceEnums.VolSurfacePricingModel pricing_model,
|
||||
IDictionary<double, double> this_put_srawk_vols, IDictionary<double, double> 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<double, double> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
/// <param name="d">Right side of the equation.</param>
|
||||
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<Tuple<double, double>> points, double start_slope = double.NaN, double end_slope = double.NaN)
|
||||
{
|
||||
_generate_spline(points, start_slope, end_slope);
|
||||
}
|
||||
|
||||
private void _generate_spline(IEnumerable<Tuple<double, double>> 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<double, double>[] { 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Tuple<double, double>> points)
|
||||
{
|
||||
if (points == null || points.Count() <= 1)
|
||||
points = new Tuple<double, double>[] { Tuple.Create(0.0, Double.NaN), Tuple.Create(1.0, Double.NaN) };
|
||||
IEnumerable<double> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<StaticConfiguration>();
|
||||
//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<string, SecurityCalendarData> metadata;
|
||||
//private readonly static IDictionary<string, APISecurityCalendarData> 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;
|
||||
// }
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<VolSurfaceExpiration> system_exp_list)
|
||||
{
|
||||
HashSet<VolSurfaceExpiration> vs_exp_map = new HashSet<VolSurfaceExpiration>(vs_input.surface_parameters.curve_parameters_map.Select(t => t.Item1)),
|
||||
sys_exp_map = new HashSet<VolSurfaceExpiration>(system_exp_list);
|
||||
HashSet<VolSurfaceExpiration> 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<Tuple<VolSurfaceExpiration, VolCurveParameters>>();
|
||||
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<VolSurfaceExpiration> vs_exp_list)
|
||||
{
|
||||
List<Tuple<VolSurfaceExpiration, VolCurveParameters>> exp_params_list = new List<Tuple<VolSurfaceExpiration, VolCurveParameters>>();
|
||||
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<string, IEnumerable<DateTime>> exp_list)
|
||||
{
|
||||
List<VolSurfaceExpiration> vs_exp_list = new List<VolSurfaceExpiration>();
|
||||
foreach (KeyValuePair<string, IEnumerable<DateTime>> 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<Tuple<VolSurfaceExpiration, VolCurveParameters>>();
|
||||
List<Tuple<VolSurfaceExpiration, VolCurveParameters>> curve_parameters_map = new List<Tuple<VolSurfaceExpiration, VolCurveParameters>>();
|
||||
foreach (Tuple<VolSurfaceExpiration, VolCurveParameters> 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<Tuple<double, double>>(), call_points = new List<Tuple<double, double>>() };
|
||||
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<Tuple<double, double>>(), call_points = new List<Tuple<double, double>>() };
|
||||
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<ICustomVolModel>.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<Tuple<double, double>> _sync_volpoints_to_settings(IEnumerable<Tuple<double, double>> volpoints, bool is_call,
|
||||
VolSurfaceEnums.VolCurveStrikeAxis strike_axis, int n_setting_points)
|
||||
{
|
||||
List<Tuple<double, double>> rv = new List<Tuple<double, double>>(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<ICustomVolResponseModel>.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<string, VolSurfaceEnums.VolSurfacePricingModel> 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<string> get_symbols(VolSurfaceInput vs_input)
|
||||
{
|
||||
return vs_input != null ? get_symbols(vs_input.surface_settings) : new string[] { };
|
||||
}
|
||||
|
||||
public static IEnumerable<string> 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<VolSurfaceExpiration, VolCurveParameters> 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<double, double> 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<Tuple<double, double>> 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<double, double> 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<Tuple<double, double>> 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<VolSurfaceEnums.VolCurveStrikeAxis, double, double> 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<Tuple<VolSurfaceExpiration, VolCurveParameters>>();
|
||||
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<VolSurfaceExpiration, double> get_driver_map(VolSurfaceInput vs_input, IDictionary<VolSurfaceExpiration, double> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <para>Checks for obstructing nulls along the path to the VolSurfaceSettings object's nested vol_time_measure field.</para>
|
||||
/// <para>Returns a default vol time measure object if nulls are found, otherwise returns the object's vol_time_measure.</para>
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <para>Checks for obstructing nulls along the path to the VolSurfaceSettings object's nested interest_time_measure field.</para>
|
||||
/// <para>Returns a default interest time measure object if nulls are found, otherwise returns the object's interest_time_measure.</para>
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes measures to "sanitize" the data. Critical fields/properties are initialized, and VolSurfaceSymbolRelationship objects' connected_symbols are forced to be a [distinct]set.
|
||||
/// </summary>
|
||||
public static void sanitize(VolSurfaceInput vs_input) { sanitize(vs_input.surface_settings); }
|
||||
|
||||
/// <summary>
|
||||
/// Takes measures to "sanitize" the data. Critical fields/properties are initialized, and VolSurfaceSymbolRelationship objects' connected_symbols are forced to be a [distinct]set.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Performs a deep(nested) check of every field and property for nulls, and initializes them.
|
||||
/// </summary>
|
||||
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<Tuple<double, double>> _merge_points(List<Tuple<double, double>> master_points, List<Tuple<double, double>> slave_points)
|
||||
{
|
||||
List<Tuple<double, double>> rv = new List<Tuple<double, double>>();
|
||||
for (int i = 0; i < master_points.Count; i++)
|
||||
{
|
||||
Tuple<double, double> 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
|
||||
}
|
||||
}
|
||||
@@ -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<bts.config.toggles.VolSurfaceTimeCalcMode>().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<VolSurfaceExpiration, HashSet<VolSurfaceTimeMeasure>> _cache = new Dictionary<VolSurfaceExpiration, HashSet<VolSurfaceTimeMeasure>>();
|
||||
|
||||
// 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<VolSurfaceTimeMeasure> set;
|
||||
// if (!_cache.TryGetValue(exp, out set)) _cache.Add(exp, set = new HashSet<VolSurfaceTimeMeasure>());
|
||||
// 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);
|
||||
// }
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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; } }
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<T>(byte[] proto_bytes)
|
||||
{
|
||||
return ProtoBuf.Serializer.DeserializeWithLengthPrefix<T>(new System.IO.MemoryStream(proto_bytes), ProtoBuf.PrefixStyle.Fixed32);
|
||||
}
|
||||
|
||||
public static byte[] serialize_proto<T>(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 t)
|
||||
{
|
||||
System.IO.MemoryStream stream = new System.IO.MemoryStream();
|
||||
ProtoBuf.Serializer.SerializeWithLengthPrefix(stream, t, ProtoBuf.PrefixStyle.Fixed32);
|
||||
stream.Position = 0;
|
||||
return ProtoBuf.Serializer.DeserializeWithLengthPrefix<T>(stream, ProtoBuf.PrefixStyle.Fixed32);
|
||||
}
|
||||
|
||||
public static bool are_protos_equal<T>(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<VolSurfaceExpiration, T> sync_map_exps<T>(IEnumerable<VolSurfaceExpiration> master_exp_list,
|
||||
IDictionary<VolSurfaceExpiration, T> data_map,
|
||||
bool remove_extra_exps,
|
||||
Func<VolSurfaceExpiration, T> get_default_func)
|
||||
{
|
||||
HashSet<VolSurfaceExpiration> master_exp_map = new HashSet<VolSurfaceExpiration> (master_exp_list);
|
||||
data_map = data_map ?? new Dictionary<VolSurfaceExpiration, T>();
|
||||
List<KeyValuePair<VolSurfaceExpiration, T>> rv = new List<KeyValuePair<VolSurfaceExpiration,T>> (data_map.ToList());
|
||||
rv.AddRange(master_exp_map.Where(e => !data_map.ContainsKey(e)).Select(e => new KeyValuePair<VolSurfaceExpiration, T>(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<T>(HashSet<T> new_d, HashSet<T> old_d,
|
||||
out HashSet<T> deleted_d, out HashSet<T> added_d)
|
||||
{
|
||||
added_d = new HashSet<T>();
|
||||
deleted_d = new HashSet<T>();
|
||||
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<T>(params HashSet<T>[] hashsets)
|
||||
{
|
||||
if (hashsets.Length > 0)
|
||||
{
|
||||
HashSet<T> comp = hashsets[0];
|
||||
foreach (HashSet<T> h in hashsets)
|
||||
{
|
||||
HashSet<T> 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<T, P>(IEnumerable<T> list, P nearest_to, Func<T, P, double> 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<T, P>(IEnumerable<T> list, P nearest_to, Func<T, P, double> diff_measure,
|
||||
out T low_neighbor, out T high_neighbor)
|
||||
{
|
||||
low_neighbor = default(T); high_neighbor = default(T);
|
||||
list = list ?? new List<T>();
|
||||
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<K, V> append_dictionaties<K, V>(IEnumerable<IDictionary<K, V>> dictionaries)
|
||||
{
|
||||
Dictionary<K, V> rv = new Dictionary<K, V>();
|
||||
foreach (IDictionary<K, V> d in dictionaries)
|
||||
foreach (KeyValuePair<K, V> 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<T> sort_strikes_in_display_order<T>(IEnumerable<T> strike_points, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, Func<T, double> key_selector)
|
||||
{
|
||||
if (strike_axis == VolSurfaceEnums.VolCurveStrikeAxis.RawStrike)
|
||||
return new List<T>(strike_points.OrderBy(t => key_selector(t)));
|
||||
else
|
||||
{
|
||||
Func<double, bool> is_call = k => k >= 0.0;
|
||||
IEnumerable<T> call_points = strike_points.Where(t => is_call(key_selector(t))),
|
||||
put_points = strike_points.Where(t => !is_call(key_selector(t)));
|
||||
IEnumerable<T> 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<T> rv = new List<T>(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<T> sort_strikes_from_atm<T>(IEnumerable<T> strike_points, bool is_call, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, Func<T, double> key_selector)
|
||||
{
|
||||
IEnumerable<T> unset_points = strike_points.Where(t => Double.IsNaN(key_selector(t)));
|
||||
strike_points = strike_points.Where(t => !Double.IsNaN(key_selector(t)));
|
||||
List<T> low_to_high = new List<T>(strike_points.OrderBy(t => key_selector(t))),
|
||||
high_to_low = new List<T>(low_to_high);
|
||||
high_to_low.Reverse();
|
||||
List<T> 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<double> 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<double> strikes_list = new List<double>(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<VolSurfaceExpiration> 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<string, IEnumerable<T>> split_into_symbols<T>(IDictionary<VolSurfaceExpiration, IEnumerable<T>> exp_map)
|
||||
{
|
||||
Dictionary<string, IEnumerable<T>> rv = new Dictionary<string, IEnumerable<T>>();
|
||||
foreach (KeyValuePair<VolSurfaceExpiration, IEnumerable<T>> kv in exp_map)
|
||||
{
|
||||
IEnumerable<T> sym_list = null;
|
||||
if (!rv.TryGetValue(kv.Key.symbol, out sym_list))
|
||||
rv[kv.Key.symbol] = sym_list = new List<T>();
|
||||
(sym_list as List<T>).AddRange(kv.Value);
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static IDictionary<VolSurfaceExpiration, HashSet<double>> get_contracts(VolSurfaceOutput vs_output)
|
||||
{
|
||||
IDictionary<VolSurfaceExpiration, HashSet<double>> rv = new Dictionary<VolSurfaceExpiration, HashSet<double>>();
|
||||
vs_output = vs_output ?? VolSurfaceOutput.get_empty_output();
|
||||
foreach (KeyValuePair<VolSurfaceExpiration, VolCurveOutput> kvp in vs_output.exp_output_map)
|
||||
rv.Add(kvp.Key, new HashSet<double>(kvp.Value.tradeable_strikes));
|
||||
return rv;
|
||||
}
|
||||
|
||||
private class DelegateEqualityComparer<T> : IEqualityComparer<T>
|
||||
{
|
||||
private Func<T, T, bool> _comparer_func;
|
||||
public DelegateEqualityComparer(Func<T, T, bool> 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<T> : IComparer<T>
|
||||
{
|
||||
private Func<T, T, int> _comparer_func;
|
||||
public DelegateComparer(Func<T, T, int> comparer_func) { _comparer_func = comparer_func; }
|
||||
public int Compare(T x, T y) { return _comparer_func(x, y); }
|
||||
}
|
||||
|
||||
public static IEqualityComparer<T> get_equality_comparer<T>(Func<T, T, bool> comparer_func)
|
||||
{
|
||||
return new DelegateEqualityComparer<T>(comparer_func);
|
||||
}
|
||||
|
||||
public static IComparer<T> get_comparer<T>(Func<T, T, int> comparer_func)
|
||||
{
|
||||
return new DelegateComparer<T>(comparer_func);
|
||||
}
|
||||
|
||||
/// Converts the vs_exp-> T to exp->sum->T
|
||||
public static IDictionary<DateTime, IDictionary<string, T>> split_into_exp_symbols<T>(IDictionary<VolSurfaceExpiration, T> exp_data)
|
||||
{
|
||||
IDictionary<DateTime, IDictionary<string, T>> rv = new Dictionary<DateTime, IDictionary<string, T>>();
|
||||
foreach (KeyValuePair<VolSurfaceExpiration, T> kv in exp_data)
|
||||
{
|
||||
VolSurfaceExpiration exp = kv.Key;
|
||||
IDictionary<string, T> symbol_map = null;
|
||||
if (!rv.TryGetValue(exp.expiration, out symbol_map))
|
||||
rv[exp.expiration] = symbol_map = new Dictionary<string, T>();
|
||||
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<Tuple<double, double>>() : 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<VolSurfaceExpiration> get_exp_list_from_cascade(IEnumerable<VolSurfaceExpiration> all_exps, IEnumerable<VolSurfaceExpiration> select_exp,
|
||||
bool cascade_up, bool cascade_down)
|
||||
{
|
||||
List<VolSurfaceExpiration> rv = new List<VolSurfaceExpiration>();
|
||||
HashSet<VolSurfaceExpiration> select_exp_map = new HashSet<VolSurfaceExpiration>(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<VolSurfaceExpiration, VolCurveAction> apply_cascade_to_action_map(IEnumerable<VolSurfaceExpiration> all_exps, IDictionary<VolSurfaceExpiration, VolCurveAction> 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<VolSurfaceExpiration, VolCurveAction>();
|
||||
IDictionary<VolSurfaceExpiration, VolCurveAction> rv = new Dictionary<VolSurfaceExpiration, VolCurveAction>(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<Tuple<double, double>> get_vol_path_points(VolCurveOutput vc_out)
|
||||
{
|
||||
List<Tuple<double, double>> rv = new List<Tuple<double, double>>();
|
||||
Func<double, double> 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<string, HashSet<string>> _hash_relationship(VolSurfaceSettings vs_settings, IEnumerable<VolSurfaceSymbolRelationship> rels)
|
||||
{
|
||||
IDictionary<string, HashSet<string>> rv = rels.ToDictionary(r => r.symbol, r => new HashSet<string>(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<string>(new string[] { s }));
|
||||
return rv;
|
||||
}
|
||||
|
||||
private static HashSet<string> _get_slave_symbols(VolSurfaceSettings vs_settings)
|
||||
{
|
||||
/// just all - masters
|
||||
HashSet<string> all_symbols = new HashSet<string>(VolSurfaceDataFunctions.get_symbols(vs_settings)),
|
||||
master_symbols = get_master_symbols(vs_settings);
|
||||
HashSet<string> dels, adds;
|
||||
compare_hashsets(all_symbols, master_symbols, out dels, out adds);
|
||||
return adds;
|
||||
}
|
||||
|
||||
private static HashSet<string> _get_masters_for_symbol(VolSurfaceSettings vs_settings, string symbol)
|
||||
{
|
||||
IDictionary<string, HashSet<string>> rel_map = _hash_relationship(vs_settings, vs_settings.core_settings.master_slave_relationships);
|
||||
HashSet<string> rv = rel_map.TryGetValue(symbol, out rv) ? rv : null;
|
||||
return rv ?? new HashSet<string>();
|
||||
}
|
||||
|
||||
public static HashSet<string> get_master_symbols(VolSurfaceSettings vs_settings) {
|
||||
HashSet<string> rv = new HashSet<string>();
|
||||
_hash_relationship(vs_settings, vs_settings.core_settings.master_slave_relationships ?? new List<VolSurfaceSymbolRelationship>()).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<VolSurfaceExpiration> get_master_expirations(VolSurfaceInput vs_inp, bool include_unlinked_slaves = true)
|
||||
{
|
||||
HashSet<string> master_symbols = get_master_symbols(vs_inp.surface_settings);
|
||||
return new HashSet<VolSurfaceExpiration>(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<VolSurfaceExpiration> get_slave_expirations(VolSurfaceInput vs_inp)
|
||||
{
|
||||
if (vs_inp != null && vs_inp.surface_settings != null)
|
||||
{
|
||||
HashSet<string> slave_symbols = _get_slave_symbols(vs_inp.surface_settings);
|
||||
return new HashSet<VolSurfaceExpiration>(vs_inp.surface_parameters.curve_parameters_map.Select(t => t.Item1).Where(t => slave_symbols.Contains(t.symbol)));
|
||||
}
|
||||
else
|
||||
return new HashSet<VolSurfaceExpiration>();
|
||||
}
|
||||
|
||||
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<VolSurfaceExpiration> vs_exps)
|
||||
{
|
||||
IEnumerable<string> 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<string, HashSet<string>> md_rel_map = _hash_relationship(vs_input.surface_settings, vs_input.surface_settings.core_settings.implied_vol_marketdata_relationships);
|
||||
HashSet<string> source_symbols = (md_rel_map.TryGetValue(vs_exp.symbol, out source_symbols) ? source_symbols : null) ?? new HashSet<string>();
|
||||
IEnumerable<VolSurfaceExpiration> 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<T>(Func<T> 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<double> adjust_control_points_signs(IEnumerable<double> cps, VolSurfaceEnums.VolCurveStrikeAxis strike_axis, bool is_call)
|
||||
{
|
||||
IEnumerable<double> 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<Tuple<double, double>> points, IEnumerable<double> coeffs)
|
||||
{
|
||||
string coords_str = "Polynomial coords";
|
||||
foreach (Tuple<double, double> 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<string, string> flatten_implied_vol_md_source(IEnumerable<VolSurfaceSymbolStructure> implied_vol_md_source)
|
||||
{
|
||||
IDictionary<string, string> rv = new Dictionary<string, string>();
|
||||
foreach (VolSurfaceSymbolStructure s in implied_vol_md_source ?? Enumerable.Empty<VolSurfaceSymbolStructure>())
|
||||
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<VolSurfaceGreeks, Func<Theos, bool, double>> _greek_getters = new Dictionary<VolSurfaceGreeks, Func<Theos, bool, double>>()
|
||||
{
|
||||
{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<double, IEnumerable<Theos>> hash_strikes(IEnumerable<Theos> theos)
|
||||
{
|
||||
IDictionary<double, IEnumerable<Theos>> rv = new Dictionary<double, IEnumerable<Theos>>();
|
||||
foreach (Theos t in theos)
|
||||
{
|
||||
IEnumerable<Theos> k_theos;
|
||||
if (!rv.TryGetValue(t.strike, out k_theos))
|
||||
rv[t.strike] = k_theos = new List<Theos>();
|
||||
(k_theos as List<Theos>).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<DateTime,double> rolls,
|
||||
DateTime one_five_target, double one_five, out Dictionary<DateTime,double> 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<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> compute_aux_data(VolSurfaceInput vs_input,
|
||||
VolSurfaceNonVolInput vs_nonvol_input,
|
||||
IDictionary<VolSurfaceExpiration, double> driver_price_map,
|
||||
VolSurfaceStandardTime vs_standard_time,
|
||||
bool use_input_driver_overrides = false)
|
||||
{
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> rv = new Dictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData>();
|
||||
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<VolSurfaceExpiration, AnalyticsExpirationParameters> exp_inp_data = vs_nonvol_input.get_option_exp_input();
|
||||
foreach (Tuple<VolSurfaceExpiration, VolCurveParameters> 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<SecurityExpiration, VolSurfaceDriverTheo> compute_future_theos(IEnumerable<SecurityExpiration> future_exps,
|
||||
IDictionary<SecurityExpiration, AnalyticsExpirationParameters> exp_params_map,
|
||||
IDictionary<SecurityExpiration, double> future_driver_price_map)
|
||||
{
|
||||
IDictionary<SecurityExpiration, VolSurfaceDriverTheo> rv = new Dictionary<SecurityExpiration, VolSurfaceDriverTheo>();
|
||||
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<VolSurfaceExpiration, HashSet<double>> convert_from_strike_map(HashSet<mbts.SecurityStrike> strike_map)
|
||||
{
|
||||
IDictionary<mbts.SecurityExpiration, HashSet<double>> rv = new Dictionary<mbts.SecurityExpiration, HashSet<double>>();
|
||||
foreach (mbts.SecurityStrike k in strike_map)
|
||||
{
|
||||
HashSet<double> exp_strike_map;
|
||||
if (!rv.TryGetValue(k.expiration, out exp_strike_map))
|
||||
rv[k.expiration] = exp_strike_map = new HashSet<double>();
|
||||
exp_strike_map.Add(k.strike);
|
||||
}
|
||||
return rv.ToDictionary(kv => new VolSurfaceExpiration(kv.Key.symbol, kv.Key.expiration), kv => kv.Value);
|
||||
}
|
||||
|
||||
public static IDictionary<VolSurfaceExpiration, IDictionary<double, T>> convert_from_strike_map<T>(IDictionary<mbts.SecurityStrike, T> strike_map)
|
||||
{
|
||||
IDictionary<mbts.SecurityExpiration, IDictionary<double, T>> rv = new Dictionary<mbts.SecurityExpiration, IDictionary<double, T>>();
|
||||
foreach (var kv in strike_map)
|
||||
{
|
||||
IDictionary<double, T> exp_strike_map;
|
||||
if (!rv.TryGetValue(kv.Key.expiration, out exp_strike_map))
|
||||
rv[kv.Key.expiration] = exp_strike_map = new Dictionary<double, T>();
|
||||
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<SecurityStrike> convert_to_strike_map(IDictionary<VolSurfaceExpiration, IEnumerable<double>> exp_strike_map)
|
||||
{
|
||||
HashSet<SecurityStrike> rv = new HashSet<SecurityStrike>();
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<CoordinatesBasedModelHelper.ControlPoint> 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<Tuple<double, double>> 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<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<CoordinatesBasedModelHelper.ControlPoint> _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<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> 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<CoordinatesBasedModelHelper.ControlPoint> 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<Tuple<double, double>> new_put_points = new List<Tuple<double, double>>(), new_call_points = new List<Tuple<double, double>>();
|
||||
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<double> 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<double>(), Enumerable.Empty<double>(),
|
||||
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<Tuple<double, double>> _puts(VolSurfaceSettings s, VolCurveParameters c)
|
||||
{
|
||||
return _is_spline(s) ? c.spline_model_parameters.put_points : c.polynomial_model_parameters.put_points;
|
||||
}
|
||||
|
||||
public static List<Tuple<double, double>> _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
|
||||
}
|
||||
}
|
||||
@@ -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<Tuple<double, double>> put_points, call_points;
|
||||
|
||||
public CoordinatesBasedModelInput(double this_atm_vol, IEnumerable<Tuple<double, double>> this_put_points, IEnumerable<Tuple<double, double>> this_call_points)
|
||||
{
|
||||
atm_vol = this_atm_vol;
|
||||
put_points = this_put_points != null ? new List<Tuple<double, double>>(this_put_points) : new List<Tuple<double, double>>();
|
||||
call_points = this_put_points != null ? new List<Tuple<double, double>>(this_call_points) : new List<Tuple<double, double>>();
|
||||
}
|
||||
}
|
||||
|
||||
#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<Tuple<double, double>> incremental_put_points,
|
||||
IEnumerable<Tuple<double, double>> incremental_call_points,
|
||||
out IEnumerable<Tuple<double, double>> add_put_points,
|
||||
out IEnumerable<Tuple<double, double>> 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<Tuple<double, double>> rv_puts = new List<Tuple<double, double>>(),
|
||||
rv_calls = new List<Tuple<double, double>>();
|
||||
foreach (Tuple<double, double> 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<double, double> 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<Tuple<double, double>> add_put_points,
|
||||
IEnumerable<Tuple<double, double>> add_call_points,
|
||||
out IEnumerable<Tuple<double, double>> incremental_put_points,
|
||||
out IEnumerable<Tuple<double, double>> 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<Tuple<double, double>> rv_puts = new List<Tuple<double, double>>(),
|
||||
rv_calls = new List<Tuple<double, double>>();
|
||||
foreach (Tuple<double, double> 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<double, double> 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<CoordinatesBasedModelHelper.ControlPoint> 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<Tuple<double, double>> adjusted_put_points,
|
||||
out IEnumerable<Tuple<double, double>> adjusted_call_points,
|
||||
out double adjusted_ref_fwd,
|
||||
out double adjusted_ref_vol)
|
||||
{
|
||||
IComparer<ControlPoint> comp = VolSurfaceUtilityFunctions.get_comparer<ControlPoint>(
|
||||
(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<ControlPoint> convert_to_controlpoints(VolSurfaceEnums.VolCurveVolAxis vol_axis,
|
||||
VolSurfaceEnums.VolCurveStrikeAxis strike_axis,
|
||||
VolSurfaceEnums.VolCurveStrikeAxis normalization_strike_axis,
|
||||
IEnumerable<Tuple<double, double>> put_points,
|
||||
IEnumerable<Tuple<double, double>> call_points,
|
||||
Func<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> convert_strike_axis)
|
||||
{
|
||||
if (vol_axis == VolSurfaceEnums.VolCurveVolAxis.Incremental)
|
||||
{
|
||||
IEnumerable<Tuple<double, double>> 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<ControlPoint> rv = new List<ControlPoint>();
|
||||
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<double, double> 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<double, double> 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<CoordinatesBasedModelHelper.ControlPoint> controlpoints,
|
||||
VolSurfaceEnums.VolCurveStrikeAxis target_axis,
|
||||
Func<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> convert_strike_axis,
|
||||
out IEnumerable<double> put_strikes,
|
||||
out IEnumerable<double> call_strikes)
|
||||
{
|
||||
IEnumerable<CoordinatesBasedModelHelper.ControlPoint> 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<Tuple<double, double>> _merge_coordinates (IEnumerable<Tuple<double, double>> main_list, IEnumerable<Tuple<double, double>> sec_list)
|
||||
{
|
||||
Log.assert(main_list.Count() == sec_list.Count());
|
||||
List<Tuple<double, double>> rv = new List<Tuple<double, double>>();
|
||||
for (int i = 0; i < sec_list.Count(); i++)
|
||||
{
|
||||
Tuple<double, double> 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<ControlPoint> controlpoints, VolSurfaceEnums.VolCurveStrikeAxis axis,
|
||||
Func<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> 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<CoordinatesBasedModelHelper.ControlPoint> 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<Tuple<double, double>> put_controlpoints,
|
||||
IEnumerable<Tuple<double, double>> 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<ControlPoint> calculated_controlpoints)
|
||||
{
|
||||
curve_parameters = VolSurfaceUtilityFunctions.clone_proto(curve_parameters);
|
||||
IComparer<ControlPoint> comp = VolSurfaceUtilityFunctions.get_comparer<ControlPoint>(
|
||||
(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<ControlPoint> apply_action(IEnumerable<ControlPoint> 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<double, double> move_map = VolSurfaceCoreFunctions.linear_rotate_points(new HashSet<double>(control_points.Select(cp => cp.standard_strike)),
|
||||
atm_standard_strike, curve_action.strike_vol_movement_pairs);
|
||||
List<ControlPoint> rv_control_points = new List<ControlPoint>();
|
||||
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<ControlPoint> 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<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> convert_strike_axis,
|
||||
IEnumerable<Tuple<double, double>> put_points, IEnumerable<Tuple<double, double>> 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<ControlPoint> _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<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> convert_strike_axis,
|
||||
IEnumerable<Tuple<double, double>> put_control_points, IEnumerable<Tuple<double, double>> 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<double> 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<ControlPoint> rv = new List<ControlPoint>();
|
||||
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<Tuple<ControlPoint.PointType, double, double>> 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<ControlPoint.PointType, double, double> 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<ControlPoint> _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<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> convert_strike_axis,
|
||||
IEnumerable<Tuple<double, double>> put_control_points, IEnumerable<Tuple<double, double>> 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<ControlPoint> rv = new List<ControlPoint>(Enumerable.Range(0, 1).Select(i => atm_point));
|
||||
foreach (Tuple<double, double> 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<double, double> 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<VolSurfaceEnums.VolCurveStrikeAxis, double, VolSurfaceEnums.VolCurveStrikeAxis, double> convert_strike_axis,
|
||||
IEnumerable<Tuple<double, double>> put_control_points, IEnumerable<Tuple<double, double>> 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
|
||||
}
|
||||
}
|
||||
@@ -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<CoordinatesBasedModelHelper.ControlPoint> _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<double> 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<double>(), Enumerable.Empty<double>(),
|
||||
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<CoordinatesBasedModelHelper.ControlPoint> control_points)
|
||||
{
|
||||
IEnumerable<Tuple<double, double>> 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<CoordinatesBasedModelHelper.ControlPoint> 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<Tuple<double, double>> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace mbts.analytics
|
||||
{
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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<Tuple<double, double>> put_points;
|
||||
[ProtoBuf.ProtoMember(30)]
|
||||
public List<Tuple<double, double>> 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;
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -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<double> put_points;
|
||||
[ProtoBuf.ProtoMember(60)]
|
||||
public List<double> call_points;
|
||||
[ProtoBuf.ProtoMember(70)]
|
||||
public bool same_across_all_exps;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
// {
|
||||
// }
|
||||
}
|
||||
@@ -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<T>() where T: VolMatrix
|
||||
{
|
||||
return (T)this.MemberwiseClone();
|
||||
}
|
||||
|
||||
static public T[] clone_array<T>(T[] from) where T : VolMatrix
|
||||
{
|
||||
var vm = new T[from.Length];
|
||||
for(int i = 0; i < vm.Length; i++)
|
||||
vm[i] = from[i].clone<T>();
|
||||
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,
|
||||
// };
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -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<Tuple<VolSurfaceGreeks, double, double>> call_put_greeks;
|
||||
}
|
||||
|
||||
[ProtoBuf.ProtoContract(Name = "VolSurfaceSymbolTheos")]
|
||||
public class VolSurfaceSymbolTheos
|
||||
{
|
||||
[ProtoBuf.ProtoMember(10)]
|
||||
public List<VolSurfaceStrikeTheo> all_theos;
|
||||
}
|
||||
}
|
||||
@@ -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<VolSurfaceGreeks, Func<VolMatrix, bool, double>> _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, Func<VolMatrix, bool, double>>()
|
||||
{
|
||||
{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<VolSurfaceGreeks, double, double> 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<VolMatrix, bool, double> 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<VolSurfaceGreeks> 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<VolSurfaceExpiration, IEnumerable<VolSurfaceStrikeTheo>> compute_greeks(IDictionary<VolSurfaceExpiration, IEnumerable<VolMatrix>> exp_volmats,
|
||||
IEnumerable<VolSurfaceGreeks> greeks)
|
||||
{
|
||||
ConcurrentDictionary<VolSurfaceExpiration, IEnumerable<VolSurfaceStrikeTheo>> exp_theo_map = new ConcurrentDictionary<VolSurfaceExpiration, IEnumerable<VolSurfaceStrikeTheo>>();
|
||||
System.Threading.Tasks.Parallel.ForEach(exp_volmats.ToList(), kv =>
|
||||
{
|
||||
List<VolSurfaceStrikeTheo> exp_theos = new List<VolSurfaceStrikeTheo>();
|
||||
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<VolSurfaceExpiration, IEnumerable<VolMatrix>> 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<VolSurfaceExpiration, IEnumerable<Theos>> compute_standard_greeks(VolSurfaceSettings settings, IDictionary<VolSurfaceExpiration, IEnumerable<VolMatrix>> 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<VolSurfaceExpiration, IEnumerable<Theos>> exp_theo_map = new ConcurrentDictionary<VolSurfaceExpiration, IEnumerable<Theos>>();
|
||||
System.Threading.Tasks.Parallel.ForEach(exp_volmats.ToList(), kv =>
|
||||
{
|
||||
VolSurfaceEnums.VolSurfacePricingModel pricing_model = VolSurfaceDataFunctions.get_pricing_model(settings, kv.Key);
|
||||
Func<double, bool, double, double, double, double, double, double> 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<Theos> exp_theos = new List<Theos>();
|
||||
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<double, bool, double, double, double, double, double, double> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> _shift_driver(IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map,
|
||||
IDictionary<VolSurfaceExpiration, double> 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<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> _shift_driver_time(IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> 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<VolSurfaceExpiration, IEnumerable<VolMatrix>> generate_volmatrix(VolSurfaceInput vs_input,
|
||||
IDictionary<VolSurfaceExpiration, IEnumerable<double>> exp_strikes_map,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map,
|
||||
IEnumerable<double> 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<VolSurfaceExpiration, HashSet<double>> 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<VolSurfaceExpiration, IEnumerable<VolMatrix>> generate_volmatrix(VolSurfaceInput vs_input,
|
||||
IDictionary<VolSurfaceExpiration, IEnumerable<double>> exp_strikes_map,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map,
|
||||
IDictionary<VolSurfaceExpiration, IEnumerable<double>> 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<VolSurfaceExpiration, HashSet<double>> 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<double>(kv.Value));
|
||||
abs_driver_moves.ToList().ForEach(kv => { Log.assert(kv.Value.Count() == n_moves); });
|
||||
ConcurrentBag<IDictionary<VolSurfaceExpiration, List<VolMatrix>>> move_data_list = new ConcurrentBag<IDictionary<VolSurfaceExpiration, List<VolMatrix>>>();
|
||||
Parallel.ForEach(Enumerable.Range(0, n_moves), move_index =>
|
||||
{
|
||||
IDictionary<VolSurfaceExpiration, double> this_move_driver_shift_map = abs_driver_moves.ToDictionary(kv => kv.Key, kv => kv.Value.ElementAt(move_index));
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> this_move_aux_data_map = _shift_driver(aux_data_map, this_move_driver_shift_map);
|
||||
IDictionary<VolSurfaceExpiration, List<VolMatrix>> 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<VolSurfaceExpiration, IEnumerable<VolMatrix>> rv = new Dictionary<VolSurfaceExpiration, IEnumerable<VolMatrix>>();
|
||||
foreach (IDictionary<VolSurfaceExpiration, List<VolMatrix>> m_data in move_data_list)
|
||||
foreach (KeyValuePair<VolSurfaceExpiration, List<VolMatrix>> kv in m_data)
|
||||
{
|
||||
IEnumerable<VolMatrix> exp_list = null;
|
||||
if (!rv.TryGetValue(kv.Key, out exp_list))
|
||||
rv.Add(kv.Key, exp_list = new List<VolMatrix>());
|
||||
(exp_list as List<VolMatrix>).AddRange(kv.Value);
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
|
||||
public static IDictionary<VolSurfaceExpiration, List<VolMatrix>> _generate_fixed_driver_volmatrix(VolSurfaceInput vs_input,
|
||||
IDictionary<VolSurfaceExpiration, IEnumerable<double>> exp_strikes_map,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> zero_move_aux_data_map,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> 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<VolSurfaceExpiration, HashSet<double>> secs_filter)
|
||||
{
|
||||
IDictionary<VolSurfaceExpiration, double> 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<VolSurfaceExpiration, List<VolMatrix>> rv = new Dictionary<VolSurfaceExpiration, List<VolMatrix>>();
|
||||
foreach (KeyValuePair<VolSurfaceExpiration, IEnumerable<double>> kv in exp_strikes_map)
|
||||
{
|
||||
VolSurfaceExpiration exp = kv.Key;
|
||||
HashSet<double> 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<VolMatrix> exp_values = new List<VolMatrix>();
|
||||
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<VolSurfaceExpiration, VolCurveAction> _copy_action(IEnumerable<VolSurfaceExpiration> exps, VolCurveMovementOperation movement_op)
|
||||
{
|
||||
return exps.ToDictionary(exp => exp, exp => new VolCurveAction(movement_op));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<CoordinatesBasedModelHelper.ControlPoint> _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<Tuple<double, double>> new_put_points = new List<Tuple<double, double>>(), new_call_points = new List<Tuple<double, double>>();
|
||||
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<Tuple<double, double>>(new_put_points),
|
||||
call_points = new List<Tuple<double, double>>(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<double> 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<double>(), Enumerable.Empty<double>(),
|
||||
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<CoordinatesBasedModelHelper.ControlPoint> control_points, VolCurveWingParameters wing_parameters)
|
||||
{
|
||||
IEnumerable<Tuple<double, double>> 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<CoordinatesBasedModelHelper.ControlPoint> 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<Tuple<double, double>> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Tuple<double, double>> put_points;
|
||||
[ProtoBuf.ProtoMember(30)]
|
||||
public List<Tuple<double, double>> 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;
|
||||
// }
|
||||
}
|
||||
}
|
||||
@@ -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<double> put_points;
|
||||
[ProtoBuf.ProtoMember(60)]
|
||||
public List<double> call_points;
|
||||
[ProtoBuf.ProtoMember(70)]
|
||||
public bool same_across_all_exps;
|
||||
}
|
||||
}
|
||||
@@ -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<AnalyticsExpirationParameters>
|
||||
{
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace mbts.analytics
|
||||
{
|
||||
/// <summary>
|
||||
/// 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)
|
||||
/// </summary>
|
||||
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<DayOfWeek> 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<Tuple<DateTime, DateTime, DateTime>> non_full_trading_days;
|
||||
|
||||
public VolSurfaceExpirationTimeData(DateTime this_expiration_datetime,
|
||||
DateTime this_regular_start_time, DateTime this_regular_stop_time,
|
||||
IEnumerable<DayOfWeek> this_weekends,
|
||||
IEnumerable<Tuple<DateTime, DateTime, DateTime>> 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<DayOfWeek> weekend_map = new HashSet<DayOfWeek>(exp_data.weekends);
|
||||
IDictionary<DateTime, Tuple<DateTime, DateTime, DateTime>> non_full_map = new Dictionary<DateTime, Tuple<DateTime, DateTime, DateTime>>();
|
||||
foreach (Tuple<DateTime, DateTime, DateTime> 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<DateTime, DateTime, DateTime> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<VolSurfaceExpiration, double> driver_price_map;
|
||||
public readonly IDictionary<VolSurfaceExpiration, IEnumerable<double>> contracts;
|
||||
public readonly HashSet<SecurityStrike> strike_map;
|
||||
|
||||
public VolSurfaceNonVolData(VolSurfaceNonVolInput input,
|
||||
IDictionary<VolSurfaceExpiration, double> driver_price_map,
|
||||
IDictionary<VolSurfaceExpiration, IEnumerable<double>> 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<Tuple<SecurityType, string, double>> get_cpp_list()
|
||||
{
|
||||
return input.get_cpp_list();
|
||||
}
|
||||
|
||||
public IDictionary<mbts.SecurityTuple, double> 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<mbts.SecurityExpiration> get_associated_non_options()
|
||||
{
|
||||
HashSet<mbts.SecurityExpiration> rv = new HashSet<SecurityExpiration>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<SecurityExpiration, AnalyticsExpirationParameters> exp_input_map;
|
||||
|
||||
public VolSurfaceNonVolInput(/*bts.config.StaticConfiguration this_sym_input,*/
|
||||
IDictionary<SecurityExpiration, AnalyticsExpirationParameters> this_exp_input_map)
|
||||
{
|
||||
//sym_input = this_sym_input;
|
||||
exp_input_map = this_exp_input_map;
|
||||
}
|
||||
|
||||
public IDictionary<VolSurfaceExpiration, AnalyticsExpirationParameters> 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<SecurityExpiration, AnalyticsExpirationParameters> 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<Tuple<SecurityType, string, double>> 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<mbts.SecurityTuple, double> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<double, double>[] {
|
||||
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); } }
|
||||
|
||||
}
|
||||
}
|
||||
@@ -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<double, double> down_move_point;
|
||||
[ProtoBuf.ProtoMember(20)]
|
||||
public Tuple<double, double> 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace mbts.analytics
|
||||
{
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// </summary>
|
||||
[ProtoBuf.ProtoContract(Name = "SimpleTwoPointVolPathParameters")]
|
||||
public class SimpleTwoPointVolPathParameters
|
||||
{
|
||||
[ProtoBuf.ProtoMember(10)]
|
||||
public Tuple<double, double> down_move_point;
|
||||
[ProtoBuf.ProtoMember(20)]
|
||||
public Tuple<double, double> up_move_point;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
+105
@@ -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<double, double> _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<Tuple<double, double, double>> 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<double> put_reg_line = VolSurfaceCoreFunctions.get_constrained_least_squares_polynomial(p_points, new Tuple<double, double>[] { 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<double> call_reg_line = VolSurfaceCoreFunctions.get_constrained_least_squares_polynomial(c_points, new Tuple<double, double>[] { 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<Tuple<double, double, double>> _add_weights(IEnumerable<KeyValuePair<double, double>> vol_points, bool is_call)
|
||||
{
|
||||
vol_points = vol_points.OrderBy(i => i.Key);
|
||||
vol_points = is_call ? vol_points : vol_points.Reverse();
|
||||
List<Tuple<double, double, double>> rv = new List<Tuple<double, double, double>>();
|
||||
for (int i = 0; i < vol_points.Count(); i++)
|
||||
{
|
||||
KeyValuePair<double, double> 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
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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<double, double> _put_start, _call_start;
|
||||
private Tuple<double, double> _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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<double, double> slope_point;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@
|
||||
<Version Condition="'$(version)'=='..'">1.0.0</Version>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MathNet.Numerics" Version="4.15.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="5.0.2" />
|
||||
<PackageReference Include="System.Composition" Version="5.0.1" />
|
||||
<PackageReference Include="System.Composition.AttributedModel" Version="5.0.1" />
|
||||
|
||||
@@ -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<T>(this ISet<T> set, IEnumerable<T> items) {
|
||||
foreach (T t in items)
|
||||
set.Add(t);
|
||||
//items.ForEach(i => set.Add(i));
|
||||
}
|
||||
public static void AddRange<T>(this ISet<T> set, params T[] items) {
|
||||
foreach (T t in items)
|
||||
set.Add(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user