From 41a072d4d260176a24934e95877aeaad8a017a46 Mon Sep 17 00:00:00 2001 From: Taha Afzal Date: Wed, 16 Feb 2022 23:32:21 -0500 Subject: [PATCH] Started importing Risk --- .../Risk/Bus/GeneralReportConfiguration.cs | 34 + .../spark/Risk/Slide/ReportParameters.cs | 242 +++++++ .../spark/Risk/Slide/SlideContractUnit.cs | 86 +++ src/client/spark/Risk/Slide/SlideFullData.cs | 138 ++++ src/client/spark/Risk/Slide/SlideGreekUnit.cs | 79 +++ .../spark/Risk/Slide/SlideModelUIOverrides.cs | 42 ++ src/client/spark/Risk/TimeFilter.cs | 35 + src/client/spark/Risk/TradeLogRow.cs | 42 ++ .../spark/Risk/VolSurfaceRiskCalculator.cs | 624 ++++++++++++++++++ .../spark_core/utils/CollectionHelper.cs | 24 +- 10 files changed, 1338 insertions(+), 8 deletions(-) create mode 100644 src/client/spark/Risk/Bus/GeneralReportConfiguration.cs create mode 100644 src/client/spark/Risk/Slide/ReportParameters.cs create mode 100644 src/client/spark/Risk/Slide/SlideContractUnit.cs create mode 100644 src/client/spark/Risk/Slide/SlideFullData.cs create mode 100644 src/client/spark/Risk/Slide/SlideGreekUnit.cs create mode 100644 src/client/spark/Risk/Slide/SlideModelUIOverrides.cs create mode 100644 src/client/spark/Risk/TimeFilter.cs create mode 100644 src/client/spark/Risk/TradeLogRow.cs create mode 100644 src/client/spark/Risk/VolSurfaceRiskCalculator.cs diff --git a/src/client/spark/Risk/Bus/GeneralReportConfiguration.cs b/src/client/spark/Risk/Bus/GeneralReportConfiguration.cs new file mode 100644 index 000000000..30b5c1ddb --- /dev/null +++ b/src/client/spark/Risk/Bus/GeneralReportConfiguration.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace BCG +{ + [Serializable] + public class GeneralReportConfiguration + { + public string report_family; + public string report_name; + public string report_query; + public bool is_live; + + public GeneralReportConfiguration() { } + + public GeneralReportConfiguration(string the_report_family, + string the_report_name, + string the_report_query, + bool the_is_alive) + { + report_family = the_report_family; + report_name = the_report_name; + report_query = the_report_query; + is_live = the_is_alive; + } + + public static bool is_valid(GeneralReportConfiguration conf) + { + return conf != null && !String.IsNullOrEmpty(conf.report_family) && !String.IsNullOrEmpty(conf.report_name) && !String.IsNullOrEmpty(conf.report_query); + } + } +} diff --git a/src/client/spark/Risk/Slide/ReportParameters.cs b/src/client/spark/Risk/Slide/ReportParameters.cs new file mode 100644 index 000000000..2cf3a3fa7 --- /dev/null +++ b/src/client/spark/Risk/Slide/ReportParameters.cs @@ -0,0 +1,242 @@ +using mbts; +using mbts.analytics; +using mbts.user; + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; + +namespace BCG { + public interface IVolSurfaceBroker { + int get_new_volsurface_id(); + void save_volsurface(int volsurface_id, string volsurface_name, byte[] data, string save_marker = null); + void delete_volsurface(int volsurface_id); + /// Cleans up all the vol surfaces, leeping the + /// last active_list_size around + void clean_up(int active_list_size); + } + + public interface IReportBroker { + void save_report(ReportParameters report_params); + void delete_report(ReportType type, string name); + } + + public enum ReportType { Slide = 0, Combo = 1, PnL } + public enum StrikeGrouping { RawStrike = 0, Delta = 1, StandardStrike = 2 } + + [Serializable] + public class ReportParameters : IEquatable, ICloneable { + public enum ReportCalculationMode { + [Description("User Prompted")] + UserPrompted, + [Description("Position/Theo Change")] + PositionOrTheoChange + } + + public static ReportParameters get_slide_parameters( + string name, + string internal_account, + string risk_terms_name, + SecurityType risk_terms_type, + string option_equivalence_name, + SecurityTuple[] securities, + IEnumerable ordered_greeks, + int volsurface_id, + IEnumerable handles, + bool slide_handles_in_percentage, + ReportCalculationMode calculation_mode) { + return new ReportParameters(ReportType.Slide, name, internal_account, risk_terms_name, risk_terms_type, option_equivalence_name, ordered_greeks, volsurface_id, securities, handles, slide_handles_in_percentage, calculation_mode); + } + + public static ReportParameters get_combo_parameters( + string name, + string internal_account, + string risk_terms_name, + SecurityType risk_terms_type) { + return new ReportParameters(ReportType.Combo, name, internal_account, risk_terms_name, risk_terms_type); + } + + public static ReportParameters get_pnl_parameters( + string name, + string internal_account, + string risk_terms_name, + SecurityType risk_terms_type, + string option_equivalence_name, + IEnumerable ordered_greeks, + int volsurface_id) { + return new ReportParameters(ReportType.PnL, name, internal_account, risk_terms_name, risk_terms_type, option_equivalence_name, ordered_greeks, volsurface_id); + } + + public ReportParameters(ReportType type, string name) { + id = -1; + volsurface_id = -1; + this.type = type; + this.name = name; + handles = type == ReportType.Slide ? new double[] { -25.0, -10.0, -5.0, -2.5, -1, 0.0, 1, 2.5, 5.0, 10.0, 25.0 } : new double[0]; + slide_handles_in_percentage = true; + this.calculation_mode = ReportCalculationMode.UserPrompted; + if (type == ReportType.Slide) + ordered_greeks = new VolSurfaceGreeks[] { + VolSurfaceGreeks.Delta, + VolSurfaceGreeks.Gamma, + VolSurfaceGreeks.Vega, + VolSurfaceGreeks.Theta, + VolSurfaceGreeks.OEV, + VolSurfaceGreeks.DPriceDRiskReversal + }; + else if (type == ReportType.PnL) { + ordered_greeks = new VolSurfaceGreeks[] { + VolSurfaceGreeks.PNL, + VolSurfaceGreeks.Theo, + VolSurfaceGreeks.Delta, + VolSurfaceGreeks.Gamma, + VolSurfaceGreeks.Theta, + VolSurfaceGreeks.OEV, + VolSurfaceGreeks.DPriceDRiskReversal + }; + } else ordered_greeks = new VolSurfaceGreeks[0]; + } + + private ReportParameters( + ReportType type, + string name, + string internal_account, + string risk_terms_name, + SecurityType risk_terms_type, + string option_equivalence_name = null, + IEnumerable ordered_greeks = null, + int volsurface_id = -1, + SecurityTuple[] securities = null, + IEnumerable handles = null, + bool slide_handles_in_percentage = false, + ReportCalculationMode calculation_mode = ReportCalculationMode.UserPrompted) { + + id = -1; + this.type = type; + this.name = name; + this.internal_account = internal_account; + this.risk_terms_name = risk_terms_name; + this.risk_terms_type = risk_terms_type; + this.option_equivalence_name = option_equivalence_name; + this.securities = securities; + if (ordered_greeks != null) this.ordered_greeks = ordered_greeks.ToArray(); + if (handles != null) this.handles = handles.ToArray(); + this.slide_handles_in_percentage = slide_handles_in_percentage; + this.calculation_mode = calculation_mode; + this.volsurface_id = volsurface_id; + } + + private ReportParameters(ReportParameters from) { + id = from.id; + volsurface_id = from.volsurface_id; + type = from.type; + name = from.name; + internal_account = from.internal_account; + risk_terms_name = from.risk_terms_name; + risk_terms_type = from.risk_terms_type; + option_equivalence_name = from.option_equivalence_name; + securities = from.securities; + handles = from.handles; + slide_handles_in_percentage = from.slide_handles_in_percentage; + calculation_mode = from.calculation_mode; + strike_grouping = from.strike_grouping; + strike_buckets = from.strike_buckets; + ordered_greeks = from.ordered_greeks; + } + + public readonly int id, volsurface_id; + public readonly ReportType type; + public readonly string name, internal_account, risk_terms_name, option_equivalence_name; + public readonly SecurityType risk_terms_type; + public readonly SecurityTuple[] securities; + public readonly double[] handles, strike_buckets; + public readonly StrikeGrouping strike_grouping; + public readonly mbts.analytics.VolSurfaceGreeks[] ordered_greeks; + public readonly bool slide_handles_in_percentage; + public ReportCalculationMode calculation_mode; + + private static double[] _get_doubles(string doubles_str) { + var doubles = new List(); + if (!string.IsNullOrWhiteSpace(doubles_str)) { + foreach (var ds in doubles_str.Split(' ')) { + double d; + if (Double.TryParse(ds, out d)) + doubles.Add(d); + } + } + return doubles.ToArray(); + } + + private static mbts.analytics.VolSurfaceGreeks[] _get_greeks(string greeks_str) { + var greeks = new List(); + if (!string.IsNullOrWhiteSpace(greeks_str)) { + foreach (var gs in greeks_str.Split(' ')) { + mbts.analytics.VolSurfaceGreeks g; + if (Enum.TryParse(gs, out g)) + greeks.Add(g); + } + } + return greeks.ToArray(); + } + + // private static SecurityTuple[] _get_securities(string symbols_str) { + // using (var ch = new UserConfigHelper()) { + // var known_secs = ch.get_all_sectups(); + // var options = known_secs.Where(s => s.security_type == SecurityType.type.OPTION).ToArray(); + // var futures = known_secs.Where(s => s.security_type == SecurityType.type.FUTURE).ToArray(); + // return symbols_str.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(str => { + // string[] parts = str.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries); + // switch (parts.Length) { + // case 1: { + // string sym = parts[0]; + // var o = options.FirstOrDefault(s => s.security_name == sym); + // if (o != null) return o; + // var f = futures.FirstOrDefault(s => s.security_name == sym); + // if (f != null) return f; + // sym = sym.ToLower(); + // return options.FirstOrDefault(s => s.security_name.ToLower() == sym) ?? futures.FirstOrDefault(s => s.security_name.ToLower() == sym) ?? SecurityTuple.empty; + // } + // case 2: { + // SecurityType.type sec_type; + // if (Enum.TryParse(parts[0], true, out sec_type)) { + // string sym = parts[1].ToLower(); + // switch (sec_type) { + // case SecurityType.type.OPTION: return options.FirstOrDefault(s => s.security_name.ToLower() == sym) ?? SecurityTuple.empty; + // case SecurityType.type.FUTURE: return futures.FirstOrDefault(s => s.security_name.ToLower() == sym) ?? SecurityTuple.empty; + // } + // } + // break; + // } + // } + // return SecurityTuple.empty; + // }).Where(s => !s.is_empty()).ToArray(); + // } + // } + + public bool Equals(ReportParameters other) { return other != null && id == other.id; } + + public bool has_identical_values(ReportParameters other) { + return other != null && + other.internal_account == internal_account && + other.risk_terms_name == risk_terms_name && + other.risk_terms_type == risk_terms_type && + other.option_equivalence_name == option_equivalence_name && + _arrays_are_equal(securities, other.securities) && + _arrays_are_equal(handles, other.handles) && + other.slide_handles_in_percentage == slide_handles_in_percentage && + other.calculation_mode == calculation_mode && + _arrays_are_equal(strike_buckets, other.strike_buckets) && + _arrays_are_equal(ordered_greeks, other.ordered_greeks) && + other.strike_grouping == strike_grouping && + other.volsurface_id == volsurface_id; + } + + private static bool _arrays_are_equal(T[] a, T[] b) { return (a == null && b == null) || (a != null && b != null && a.SequenceEqual(b)); } + + public object Clone() { return new ReportParameters(this); } + } +} \ No newline at end of file diff --git a/src/client/spark/Risk/Slide/SlideContractUnit.cs b/src/client/spark/Risk/Slide/SlideContractUnit.cs new file mode 100644 index 000000000..8e7594347 --- /dev/null +++ b/src/client/spark/Risk/Slide/SlideContractUnit.cs @@ -0,0 +1,86 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.analytics +{ + /// This is a wrapper around SlideGreekUnit at various + /// handles. So this is the complete slide data for + /// a security (expiration or strike or sum) + /// h1 h2 h3 h4 + /// ------------------- + /// g1 g1 g1 g1 + /// g2 g2 g2 g2 + /// g3 g3 g3 g3 + /// g4 g4 g4 g4 + + public class SlideContractUnit + { + public readonly SlideGreekUnit[] handle_units; + + public SlideContractUnit(IEnumerable handle_units) { this.handle_units = handle_units.ToArray(); } + + public SlideContractUnit(int n_greeks, IEnumerable handle_prices) + { + SlideGreekUnit u = new SlideGreekUnit(0.0, new double[n_greeks]); + handle_units = handle_prices.Select(h => new SlideGreekUnit(h, new double[n_greeks])).ToArray(); + } + + public SlideContractUnit(int n_greeks, IEnumerable handle_theos) + { + SlideGreekUnit u = new SlideGreekUnit(0.0, new double[n_greeks]); + handle_units = handle_theos.Select(t => new SlideGreekUnit(t.driver, new double[n_greeks])).ToArray(); + } + + public SlideGreekUnit get_greeks_at_handle(int handle_no) + { + bts.Log.assert(handle_no >= 0 && handle_no < handle_units.Length); + return handle_units[handle_no]; + } + + public void update_pnl(int zero_handle_index, int pnl_index) + { + if (zero_handle_index >= 0 && zero_handle_index < handle_units.Length && pnl_index != -1) + { + double center_theo = handle_units[zero_handle_index].position_greeks[pnl_index]; + foreach (SlideGreekUnit u in handle_units) + u.set_value(pnl_index, u.position_greeks[pnl_index] - center_theo); + } + } + + public static SlideContractUnit operator +(SlideContractUnit d1, IEnumerable d2_list) + { + List handle_sums = new List(); + for (int handle_no = 0; handle_no < d1.handle_units.Length; handle_no++) + { + SlideGreekUnit greeks_at_handle_no = d1.get_greeks_at_handle(handle_no); + IEnumerable all_greeks_at_handle_no = d2_list.Select(d2 => d2.get_greeks_at_handle(handle_no)); + SlideGreekUnit sum_for_greeks_at_handle_no = greeks_at_handle_no + all_greeks_at_handle_no; + handle_sums.Add(sum_for_greeks_at_handle_no); + } + return new SlideContractUnit(handle_sums); + } + + public static SlideContractUnit sum(IEnumerable list) + { + if (list.Count() == 0) + return new SlideContractUnit(new SlideGreekUnit[] { }); + else if (list.Count() == 1) + return list.ElementAt(0); + else + return list.ElementAt(0) + list.ToList().GetRange(1, list.Count() - 1); + } + + public SlideContractUnit normalize_greeks(IEnumerable ordered_greeks, double cpp, double delta_terms_cpp, double oev_terms_cpp) + { + return new SlideContractUnit(handle_units.Select(u => u.normalize_greeks(ordered_greeks, cpp, delta_terms_cpp, oev_terms_cpp))); + } + + public void set_value(int handle_index, int greek_index, double val) + { + handle_units[handle_index].set_value(greek_index, val); + } + } +} diff --git a/src/client/spark/Risk/Slide/SlideFullData.cs b/src/client/spark/Risk/Slide/SlideFullData.cs new file mode 100644 index 000000000..e630db093 --- /dev/null +++ b/src/client/spark/Risk/Slide/SlideFullData.cs @@ -0,0 +1,138 @@ +// using bts.o2.msgs; +// using mbts; +// using System; +// using System.Collections.Generic; +// using System.Linq; +// using mbts.analytics; + +// namespace BCG +// { +// class SlideGreekUnitKey : IEquatable +// { +// public enum GroupType { SumAll, SumPostWeekly, SumPostMonthly, SumPostQuarterly, Exp, SymExp } + +// public static SlideGreekUnitKey get_sum_all_key() { return new SlideGreekUnitKey(GroupType.SumAll, "All"); } + +// public static SlideGreekUnitKey get_sum_post_weekly_key() { return new SlideGreekUnitKey(GroupType.SumPostWeekly, "Post Weekly"); } + +// public static SlideGreekUnitKey get_sum_post_monthly_key() { return new SlideGreekUnitKey(GroupType.SumPostMonthly, "Post Monthly"); } + +// public static SlideGreekUnitKey get_sum_post_quarterly_key() { return new SlideGreekUnitKey(GroupType.SumPostQuarterly, "Post Quarterly"); } + +// public static SlideGreekUnitKey get_exp_date_key(DateTime exp_date) { return new SlideGreekUnitKey(exp_date); } + +// public static SlideGreekUnitKey get_symbol_exp_date_key(DateTime exp_date, string symbol) { return new SlideGreekUnitKey(exp_date, symbol); } + +// private SlideGreekUnitKey(GroupType type, string name) +// { +// _unique_name = display_name = name; +// this.type = type; +// } + +// private SlideGreekUnitKey(DateTime exp_date) +// { +// _exp = exp_date; +// _unique_name = exp_date.ToShortDateString(); +// display_name = ContractUtilities.get_expiration_text_no_symbol(exp_date); +// type = GroupType.Exp; +// } + +// private SlideGreekUnitKey(DateTime exp_date, string symbol) +// { +// _exp = exp_date; +// _symbol = symbol; +// display_name = symbol; +// _unique_name = "{0}:{1}".fmt(exp_date.ToShortDateString(), symbol); +// type = GroupType.SymExp; +// } + +// private readonly DateTime _exp; +// private readonly string _symbol; +// private readonly string _unique_name; +// public readonly string display_name; +// public readonly GroupType type; + +// public bool Equals(SlideGreekUnitKey other) { return other != null && other._unique_name == _unique_name; } + +// public override bool Equals(object obj) { return Equals(obj as SlideGreekUnitKey); } + +// public override int GetHashCode() { return _unique_name.GetHashCode(); } + +// public static int comp(SlideGreekUnitKey k1, SlideGreekUnitKey k2) +// { +// int rv = 0; +// if (k1.type == GroupType.SumAll) +// rv = -1; +// else if (k1.type == GroupType.Exp) +// { +// if (k2.type == GroupType.SumAll) +// rv = 1; +// else +// { +// int exp_comp = k1._exp.CompareTo(k2._exp); +// rv = exp_comp != 0 ? exp_comp : (k2.type == GroupType.SymExp ? -1 : exp_comp); +// } +// } +// else if (k1.type == GroupType.SymExp) +// { +// if (k2.type == GroupType.SumAll) +// rv = 1; +// else +// { +// int exp_comp = k1._exp.CompareTo(k2._exp); +// rv = exp_comp != 0 ? exp_comp : (k2.type == GroupType.Exp ? 1 : k1._symbol.CompareTo (k2._symbol)); +// } +// } +// return rv; +// } +// } + +// class SlideFullData +// { +// public static SlideFullData empty(string report_name = "") +// { +// return new SlideFullData(new ReportParameters(ReportType.Slide, report_name), +// Enumerable.Empty(), +// new Dictionary>(), +// null, +// Enumerable.Empty(), +// DateTime.MinValue, +// null); +// } + +// public readonly ReportParameters report_parameters; +// public readonly IEnumerable ordered_headers; +// public readonly mbts.TradeLogRow last_trade; +// public readonly DateTime last_volsave_time; +// public readonly IEnumerable all_expirations; +// public readonly SlideModelUIOverrides ui_override; +// public readonly IDictionary> _map; + +// public SlideFullData(ReportParameters report_parameters, +// IEnumerable this_ordered_headers, +// IDictionary> map, +// mbts.TradeLogRow this_last_trade, +// IEnumerable all_expirations, +// DateTime this_last_volsave_time, +// SlideModelUIOverrides ui_override) +// { +// this.report_parameters = report_parameters; +// ordered_headers = this_ordered_headers; +// _map = map; +// last_trade = this_last_trade; +// this.all_expirations = all_expirations; +// last_volsave_time = this_last_volsave_time; +// this.ui_override = ui_override; +// } + +// public SlideGreekUnit get_data(SlideGreekUnitKey header, double slide_handle) +// { +// IDictionary row = null; +// SlideGreekUnit rv = null; +// if (_map.TryGetValue(header, out row)) +// if (row.TryGetValue(slide_handle, out rv) && rv != null) +// return rv; +// return new SlideGreekUnit(Double.NaN, Enumerable.Repeat(Double.NaN, report_parameters.ordered_greeks.Length).ToList()); +// } +// } +// } \ No newline at end of file diff --git a/src/client/spark/Risk/Slide/SlideGreekUnit.cs b/src/client/spark/Risk/Slide/SlideGreekUnit.cs new file mode 100644 index 000000000..785eca9ee --- /dev/null +++ b/src/client/spark/Risk/Slide/SlideGreekUnit.cs @@ -0,0 +1,79 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + + +namespace mbts.analytics { + /// This encapsulates a get of slide greeks computed at + /// a certain driver handle + /// h1 + /// -- + /// g1 + /// g2 + /// g3 + /// g4 + public class SlideGreekUnit { + public readonly double driver_price; + public readonly double[] position_greeks; + + public SlideGreekUnit(double driver_price, IEnumerable position_greeks) { + this.driver_price = driver_price; + this.position_greeks = position_greeks.ToArray(); + } + + public SlideGreekUnit(double driver_price, double[] position_greeks) { + this.driver_price = driver_price; + this.position_greeks = position_greeks; + } + + public static SlideGreekUnit operator +(SlideGreekUnit u1, SlideGreekUnit u2) { + SlideGreekUnit rv; + if (u1 != null && u2 != null && + u1.position_greeks != null && u2.position_greeks != null && + u1.position_greeks.Length == u2.position_greeks.Length) { + List rv_greeks = new List(); + for (int i = 0; i < u1.position_greeks.Length; i++) + rv_greeks.Add(u1.position_greeks[i] + u2.position_greeks[i]); + rv = new SlideGreekUnit(u1.driver_price, rv_greeks); + } else + rv = u1 != null ? u1 : u2; + return rv; + } + + public static SlideGreekUnit operator +(SlideGreekUnit u1, IEnumerable u2_list) { + double[] res_array = u1.position_greeks.ToArray(); + foreach (SlideGreekUnit u2 in u2_list) + VolSurfaceRiskCalculator._add_arrays(res_array, u2.position_greeks, ref res_array); + return new SlideGreekUnit(u1.driver_price, res_array); + } + + public SlideGreekUnit change_greek(int index, double new_value) { + double[] rv = position_greeks.ToArray(); + rv[index] = new_value; + return new SlideGreekUnit(driver_price, rv); + } + + public SlideGreekUnit normalize_greeks(IEnumerable ordered_greeks, double cpp, double delta_terms_cpp, double oev_terms_cpp) { + List rv = new List(); + bts.Log.assert(position_greeks.Length == ordered_greeks.Count()); + for (int i = 0; i < ordered_greeks.Count(); i++) { + VolSurfaceGreeks g = ordered_greeks.ElementAt(i); + double g_val = cpp * position_greeks.ElementAt(i); + if (VolSurfaceRiskCalculator.is_delta_greek(g) || VolSurfaceRiskCalculator.is_gamma_greek(g)) + g_val /= delta_terms_cpp; + else if (VolSurfaceRiskCalculator.is_oev_col(g)) + g_val /= oev_terms_cpp; + rv.Add(g_val); + } + return new SlideGreekUnit(driver_price, rv); + } + + public static SlideGreekUnit get_empty(double driver, int n_handles) { + return new SlideGreekUnit(driver, Enumerable.Repeat(Double.NaN, n_handles)); + } + + public void set_value(int index, double value) { position_greeks[index] = value; } + } +} \ No newline at end of file diff --git a/src/client/spark/Risk/Slide/SlideModelUIOverrides.cs b/src/client/spark/Risk/Slide/SlideModelUIOverrides.cs new file mode 100644 index 000000000..f0a6ab26f --- /dev/null +++ b/src/client/spark/Risk/Slide/SlideModelUIOverrides.cs @@ -0,0 +1,42 @@ +using mbts.ui; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace BCG +{ + public class SlideModelUIOverrides + { + public readonly HashSet excluded_expirations; + public readonly bool use_candidate_values; + public readonly TimeFilter time_filter; + public readonly double vol_move; + public readonly double time_move; + + public SlideModelUIOverrides(IEnumerable excluded_expirations, + bool operate_on_candidate_values, + TimeFilter time_filter, + double time_move, + double vol_move) + { + this.excluded_expirations = new HashSet(excluded_expirations); + this.use_candidate_values = operate_on_candidate_values; + this.time_filter = time_filter; + this.vol_move = vol_move; + this.time_move = time_move; + } + + public bool is_positition_overridden + { + get { return excluded_expirations.Count > 0 || time_filter.filter_mode != TimeFilter.Mode.Off; } + } + + public bool is_value_overridden + { + get { return use_candidate_values; } + } + + } +} diff --git a/src/client/spark/Risk/TimeFilter.cs b/src/client/spark/Risk/TimeFilter.cs new file mode 100644 index 000000000..1ded5881c --- /dev/null +++ b/src/client/spark/Risk/TimeFilter.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace mbts.ui +{ + public class TimeFilter : IEquatable + { + public enum Mode { Before, After, Off } + + public TimeFilter(Mode filter_mode, DateTime date_time) { + this.filter_mode = filter_mode; + this.date_time = date_time; + } + + public static TimeFilter get_default() { return new TimeFilter(Mode.Off, default(DateTime)); } + + public readonly Mode filter_mode; + public readonly DateTime date_time; + + public bool Equals(TimeFilter other) { + return other != null && other.filter_mode == filter_mode && other.date_time == date_time; + } + + public override bool Equals(object obj) { + return Equals(obj as TimeFilter); + } + + public override int GetHashCode() { + return date_time.GetHashCode(); + } + } +} diff --git a/src/client/spark/Risk/TradeLogRow.cs b/src/client/spark/Risk/TradeLogRow.cs new file mode 100644 index 000000000..276699314 --- /dev/null +++ b/src/client/spark/Risk/TradeLogRow.cs @@ -0,0 +1,42 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using bts.api; + + +namespace mbts { + public abstract class TradeLogRow { + public abstract int trade_id { get; } + + public abstract SecurityType security_type { get; } + + public abstract string symbol { get; } + + public abstract DateTime expiration { get; } + + public abstract double strike { get; } + + public abstract SecurityExpiration security_expiration { get; } + + public abstract SecurityStrike security_strike { get; } + + public abstract PutOrCall call_put { get; } + + public abstract int size { get; } + + public abstract double price { get; } + + public abstract double theo { get; } + + public abstract string account { get; } + + public abstract bool is_day_trade { get; } + + public abstract DateTime time_entered { get; } + + public abstract string trader { get; } + } +} \ No newline at end of file diff --git a/src/client/spark/Risk/VolSurfaceRiskCalculator.cs b/src/client/spark/Risk/VolSurfaceRiskCalculator.cs new file mode 100644 index 000000000..3d737f00a --- /dev/null +++ b/src/client/spark/Risk/VolSurfaceRiskCalculator.cs @@ -0,0 +1,624 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; +using bts.utils; + +namespace mbts.analytics +{ + public class ComboStrikeData + { + public static readonly ComboStrikeData Empty = new ComboStrikeData(double.NaN, double.NaN, double.NaN, double.NaN); + + public ComboStrikeData(double call_pos, double put_pos, double call_raw_pos, double put_raw_pos) + { + this.call_pos = call_pos; + this.put_pos = put_pos; + this.call_raw_pos = call_raw_pos; + this.put_raw_pos = put_raw_pos; + } + + public double call_pos { get; private set; } + public double put_pos { get; private set; } + public double net_pos { get { return put_pos + call_pos; } } + + public double call_raw_pos { get; private set; } + public double put_raw_pos { get; private set; } + public double net_raw_pos { get { return call_raw_pos + put_raw_pos; } } + } + + public class ComboFutureData + { + public static readonly ComboFutureData Empty = new ComboFutureData(double.NaN, double.NaN); + + public ComboFutureData(double pos, double raw_pos) + { + this.pos = pos; + this.raw_pos = raw_pos; + } + public double pos { get; private set; } + public double raw_pos { get; private set; } + } + + public class VolSurfaceRiskCalculator + { + #region Position/Theo Calculation + + public static void compute_position(IEnumerable rows, + out TradeLogRow latest_trade, + out IDictionary> option_pos_map, + out IDictionary future_pos_map) + { + IDictionary option_pos_map_aux = new Dictionary(); + future_pos_map = new Dictionary (); + latest_trade = null; + foreach (var r in rows) + { + latest_trade = latest_trade == null || r.time_entered > latest_trade.time_entered ? r : latest_trade; + if (r.security_type == SecurityType.Option) + { + double[] k_pos = null; + if (!option_pos_map_aux.TryGetValue(r.security_strike, out k_pos)) + option_pos_map_aux[r.security_strike] = k_pos = new double[] { 0.0, 0.0 }; + if (r.call_put == PutOrCall.Call) k_pos[0] = k_pos[0] + r.size; + else if (r.call_put == PutOrCall.Put) k_pos[1] = k_pos[1] + r.size; + } + else if (r.security_type == SecurityType.Future) + { + double exp_pos = future_pos_map.TryGetValue(r.security_expiration, out exp_pos) ? exp_pos : 0; + exp_pos += r.size; + future_pos_map[r.security_expiration] = exp_pos; + } + } + option_pos_map = option_pos_map_aux.ToDictionary(kv => kv.Key, kv => Tuple.Create(kv.Value[0], kv.Value[1])); + } + + public static void compute_position(IEnumerable rows, + out TradeLogRow latest_trade, + out IDictionary>> option_pos_map, + out IDictionary future_pos_map) + { + IDictionary> option_pos_map_aux = new Dictionary>(); + IDictionary future_pos_map_aux = new Dictionary(); + latest_trade = null; + foreach (var r in rows) + { + latest_trade = latest_trade == null || r.time_entered > latest_trade.time_entered ? r : latest_trade; + if (r.security_type == SecurityType.Option) + { + IDictionary exp_pos_map = null; + if (!option_pos_map_aux.TryGetValue(r.security_expiration, out exp_pos_map)) + option_pos_map_aux[r.security_expiration] = exp_pos_map = new Dictionary(); + double[] k_pos = null; + if (!exp_pos_map.TryGetValue(r.strike, out k_pos)) + exp_pos_map[r.strike] = k_pos = new double[] { 0.0, 0.0 }; + if (r.call_put == PutOrCall.Call) k_pos[0] = k_pos[0] + r.size; + else if (r.call_put == PutOrCall.Put) k_pos[1] = k_pos[1] + r.size; + } + else if (r.security_type == SecurityType.Future) + { + double exp_pos = future_pos_map_aux.TryGetValue(r.security_expiration, out exp_pos) ? exp_pos : 0; + exp_pos += r.size; + future_pos_map_aux[r.security_expiration] = exp_pos; + } + } + option_pos_map = option_pos_map_aux.ToDictionary(kv => new VolSurfaceExpiration(kv.Key.symbol, kv.Key.expiration), kv => kv.Value.ToDictionaryDupes(i => i.Key, i => Tuple.Create(i.Value[0], i.Value[1]))); + future_pos_map = future_pos_map_aux.ToDictionary(kv => new VolSurfaceExpiration(kv.Key.symbol, kv.Key.expiration), kv => kv.Value); + } + + public static IDictionary>> convert_option_pos (IDictionary> k_pos_map) + { + Dictionary>> rv = new Dictionary>>(); + foreach (var kv in k_pos_map) + { + mbts.SecurityExpiration exp = kv.Key.expiration; + IDictionary> exp_map = null; + if (!rv.TryGetValue(exp, out exp_map)) + rv[exp] = exp_map = new Dictionary>(); + exp_map[kv.Key.strike] = kv.Value; + } + return rv; + } + + public static IDictionary> get_option_slide_theos(VolSurfaceInput vs_input, + IDictionary aux_data_map, + IDictionary> vs_exp_strike_map, + IDictionary> pos_exp_strike_map, + IEnumerable perc_moves) + { + VolSurfaceTimer timer = new VolSurfaceTimer(); + vs_input = VolSurfaceDataFunctions.sync_input_expirations_to_master_list(vs_input, vs_exp_strike_map.Keys); + aux_data_map = VolSurfaceUtilityFunctions.sync_map_exps(vs_exp_strike_map.Keys, aux_data_map, true, vs_exp => VolSurfaceExpirationAuxiliaryData.empty); + IDictionary> abs_moves = aux_data_map.ToDictionary(kv => kv.Key, kv => perc_moves.Select(m => kv.Value.driver_price * (0.01 * m)).ToArray() as IEnumerable); + timer.start(); IDictionary> exp_vm_map = VolSurfaceVolMatrixCalculator.generate_volmatrix(vs_input, vs_exp_strike_map, aux_data_map, abs_moves, perc_moves.Count(), true, true, true, true, true, pos_exp_strike_map); timer.stop(); + bts.Log.Gen.info(String.Format("VolSurfaceSlideTheosProducer.get_option_slide_theos volmat time {0}", timer.last_interval_time_ms)); + timer.start(); IDictionary> exp_theo_map = VolSurfaceTheoCalculator.compute_standard_greeks(vs_input.surface_settings, exp_vm_map, true); timer.stop(); + bts.Log.Gen.info(String.Format("VolSurfaceSlideTheosProducer.get_option_slide_theos theo time {0}", timer.last_interval_time_ms)); + return exp_theo_map; + } + + #endregion + + #region Combo + + public static void compute_combo(IEnumerable trade_rows, + IDictionary cpp_map, + SecurityTuple interms_cpp_sec, + out TradeLogRow latest_trade, + out IDictionary> option_data, + out IDictionary> future_data) + { + IDictionary>> option_pos_map; + IDictionary future_pos_map; + compute_position(trade_rows, out latest_trade, out option_pos_map, out future_pos_map); + double interms_cpp = cpp_map.TryGetValue(interms_cpp_sec, out interms_cpp) ? interms_cpp : Double.NaN; + option_data = new Dictionary>(); + future_data = new Dictionary>(); + + foreach (var exp_kv in option_pos_map) + { + double cpp = cpp_map.TryGetValue(new SecurityTuple(SecurityType.Option, exp_kv.Key.symbol, Venue.Unset), out cpp) ? cpp : Double.NaN; + option_data[exp_kv.Key] = exp_kv.Value.ToDictionary(kv => kv.Key, kv => new ComboStrikeData(kv.Value.Item1 * cpp / interms_cpp, kv.Value.Item2 * cpp / interms_cpp, kv.Value.Item1, kv.Value.Item2)); + } + + future_data = future_pos_map.ToDictionaryDupes(kv => kv.Key, + kv => + { + double cpp = cpp_map.TryGetValue(new SecurityTuple (SecurityType.Future, kv.Key.symbol, Venue.Unset), out cpp) ? cpp : Double.NaN; + return Tuple.Create(kv.Value * cpp / interms_cpp, kv.Value); + }); + } + + #endregion + + #region General Risk Aggregation + internal static readonly Theos nan_option_theos = VolSurfaceUtilityFunctions.nan_out_fields(() => new Theos()); + internal static readonly VolSurfaceDriverTheo nan_future_theos = new VolSurfaceDriverTheo(SecurityExpiration.empty, SecurityExpiration.empty, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN, Double.NaN); + + internal static HashSet delta_greeks = new HashSet(new VolSurfaceGreeks[] {VolSurfaceGreeks.Delta, VolSurfaceGreeks.BSMDelta, VolSurfaceGreeks.FlatVolDelta, VolSurfaceGreeks.ExpirationDelta, + VolSurfaceGreeks.Charm, VolSurfaceGreeks.Vanna}), + gamma_greeks = new HashSet(new VolSurfaceGreeks[] { VolSurfaceGreeks.Gamma, VolSurfaceGreeks.BSMGamma }), + option_equivalence_cols = new HashSet(new VolSurfaceGreeks[] { VolSurfaceGreeks.OEV, VolSurfaceGreeks.BSMOEV }); + + public static bool is_delta_greek(VolSurfaceGreeks g) { return delta_greeks.Contains(g); } + + public static bool is_gamma_greek(VolSurfaceGreeks g) { return gamma_greeks.Contains(g); } + + public static bool is_oev_col(VolSurfaceGreeks g) { return option_equivalence_cols.Contains(g); } + + /// Multiplies by cpp, and converts delta and gamma terms from + /// dollars to in_terms_symbol contracts + public static IEnumerable normalize_greeks(IEnumerable ordered_greeks, Func get_greek, double position, + double cpp, double delta_interms_cpp, double option_equivalence_symbol_cpp) + { + List rv = new List (); + foreach (VolSurfaceGreeks g in ordered_greeks) + { + double pos_greek_value = get_greek(g) * cpp * position; + if (delta_greeks.Contains(g) || gamma_greeks.Contains(g)) + pos_greek_value /= delta_interms_cpp; + else if (option_equivalence_cols.Contains(g)) + pos_greek_value /= option_equivalence_symbol_cpp; + rv.Add(pos_greek_value); + } + return rv; + } + + /// Multiplies by cpp, and converts delta and gamma terms from + /// dollars to in_terms_symbol contracts + public static SlideGreekUnit normalize_greeks(IEnumerable ordered_greeks, double cpp, double delta_interms_cpp, double option_equivalence_symbol_cpp, SlideGreekUnit s) + { + bts.Log.assert(s.position_greeks.Count() == ordered_greeks.Count()); + double[] rv_pos_greeks = new double[ordered_greeks.Count()]; + int i = 0; + foreach (VolSurfaceGreeks g in ordered_greeks) + { + rv_pos_greeks[i] = s.position_greeks.ElementAt(i) * cpp; + if (delta_greeks.Contains(g) || gamma_greeks.Contains(g)) + rv_pos_greeks[i] = rv_pos_greeks[i] / delta_interms_cpp; + else if (option_equivalence_cols.Contains(g)) + rv_pos_greeks[i] = rv_pos_greeks[i] / option_equivalence_symbol_cpp; + i++; + } + return new SlideGreekUnit(s.driver_price, rv_pos_greeks); + } + + public static void change_vol_dervs_to_percentages(ref IDictionary> theos) + { + foreach (var kv in theos) + foreach (Theos t in kv.Value) + _change_vol_dervs_to_percentages(t); + } + + public static void change_vol_dervs_to_percentages(ref IDictionary theos) + { + foreach (Theos t in theos.Values) + _change_vol_dervs_to_percentages(t); + } + + private static void _change_vol_dervs_to_percentages(Theos t) + { + t.cvega = VolSurfaceCoreFunctions.convert_vol_derv_to_percentage(t.cvega, 1); + t.pvega = VolSurfaceCoreFunctions.convert_vol_derv_to_percentage(t.pvega, 1); + t.veganovr = (float)VolSurfaceCoreFunctions.convert_vol_derv_to_percentage(t.veganovr, 1); + t.cvanna = (float)VolSurfaceCoreFunctions.convert_vol_derv_to_percentage(t.cvanna, 1); + t.pvanna = (float)VolSurfaceCoreFunctions.convert_vol_derv_to_percentage(t.pvanna, 1); + t.cvolga = (float)VolSurfaceCoreFunctions.convert_vol_derv_to_percentage(t.cvolga, 2); + t.pvolga = (float)VolSurfaceCoreFunctions.convert_vol_derv_to_percentage(t.pvolga, 2); + } + #endregion + + #region Slide + + public static IDictionary> compute_option_slide(IEnumerable ordered_greeks, + IEnumerable perc_move_handles, + mbts.SecurityTuple delta_terms_symbol, + string oev_terms_option_symbol, + IDictionary>> pos_map, + IDictionary> theo_map, + IDictionary cpp_map) + { + bts.Log.assert(mbts.analytics.VolSurfaceUtilityFunctions.are_hashsets_equal(new HashSet(pos_map.Keys), new HashSet(theo_map.Keys))); + IDictionary> rv = new Dictionary>(); + foreach (KeyValuePair>> kv in pos_map) + { + IEnumerable exp_theos = theo_map.TryGetValue(kv.Key, out exp_theos) ? exp_theos : null; + double cpp = cpp_map.TryGetValue(new SecurityTuple(SecurityType.Option, kv.Key.symbol, Venue.Unset), out cpp) ? cpp : Double.NaN, + delta_terms_sym_cpp = cpp_map.TryGetValue(delta_terms_symbol, out delta_terms_sym_cpp) ? delta_terms_sym_cpp : Double.NaN, + oev_terms_sym_cpp = cpp_map.TryGetValue(new SecurityTuple(SecurityType.Option, oev_terms_option_symbol, Venue.Unset), out oev_terms_sym_cpp) ? oev_terms_sym_cpp : Double.NaN; + rv[kv.Key] = _compute_single_exp_option_slide(ordered_greeks, perc_move_handles, kv.Value, VolSurfaceUtilityFunctions.hash_strikes(exp_theos), cpp, delta_terms_sym_cpp, oev_terms_sym_cpp); + } + return rv; + } + + /// For one exp + private static IEnumerable _compute_single_exp_option_slide(IEnumerable ordered_greeks, + IEnumerable handles, + IDictionary> pos_map, + IDictionary> theo_map, + double sym_cpp, double delta_terms_sym_cpp, double oev_terms_sym_cpp) + { + foreach (double k in pos_map.Keys) bts.Log.assert(theo_map.ContainsKey(k)); ///asserting on presense of all pos strikes in theos + IDictionary> strike_pos_greek_map = new Dictionary>(); + foreach (KeyValuePair> kv in pos_map) + { + IEnumerable strike_theos = theo_map[kv.Key]; + bts.Log.assert(strike_theos.Count() == handles.Count()); + IEnumerable strike_pos_greek = _compute_single_strike_option_slide(ordered_greeks, strike_theos, kv.Value.Item1, kv.Value.Item2); + strike_pos_greek_map.Add(kv.Key, strike_pos_greek); + } + IEnumerable exp_sum = sum_across_slide_handles(handles.Count(), strike_pos_greek_map); + exp_sum = exp_sum.Select(s => normalize_greeks(ordered_greeks, sym_cpp, delta_terms_sym_cpp, oev_terms_sym_cpp, s)); /// $ terms and converts the delta/gamma to in terms symbol + exp_sum = compute_slide_pnl(ordered_greeks, handles, exp_sum); /// Till now we have theos in the pnl, this subtracts the handle theos form the 0 theos + return exp_sum; + } + + /// strike theos is theos for one strike multiple handles + private static IEnumerable _compute_single_strike_option_slide(IEnumerable ordered_greeks, IEnumerable strike_theos, double call_pos, double put_pos) + { + strike_theos = strike_theos.OrderBy(t => t.driver); + List rv = new List(); + foreach (Theos handle_theo in strike_theos) + rv.Add(_multiply_pos(ordered_greeks, handle_theo, call_pos, put_pos)); + return rv; + } + + /// For all the greeks, it multiplies those greeks by the + /// call_pos and put_pos (This is where the order of the greeks + /// in the SlideGreekUnit is matched to ordered_greek_list) + private static SlideGreekUnit _multiply_pos(IEnumerable ordered_greeks, Theos theos, double call_pos, double put_pos) + { + double[] rv = new double[ordered_greeks.Count()]; + int i = 0; + foreach (VolSurfaceGreeks g in ordered_greeks) + rv[i++] = VolSurfaceUtilityFunctions.get_greek(g, theos, true) * call_pos + VolSurfaceUtilityFunctions.get_greek(g, theos, false) * put_pos; + return new SlideGreekUnit(theos.driver, rv); + } + + /// Sums up the respective handles across keys + /// (think about this as a square with T across + /// y, and handles across x) + /// NOTE: the returned enumerable will always have an element count equal to n_handnles, although elements may be null + public static IEnumerable sum_across_slide_handles(int n_handles, IDictionary> t_vs_handles) + { + foreach (IEnumerable handles in t_vs_handles.Values) bts.Log.assert(handles.Count() == n_handles); + List rv = Enumerable.Repeat(null, n_handles).ToList(); + for (int x = 0; x < n_handles; x++) + foreach (IEnumerable y in t_vs_handles.Values) + rv[x] = rv[x] + y.ElementAt(x); + return rv; + } + + /// Converts list of SlideGreekUnit to map of % handle vs SlideGreekUnit + public static IDictionary convert_handle_list_to_handle_map(IEnumerable handles, IEnumerable sorted_handles) + { + bts.Log.assert(handles.Count() == sorted_handles.Count()); + IDictionary rv = new Dictionary(); + for (int i = 0; i < handles.Count(); i++) + rv[handles.ElementAt(i)] = sorted_handles.ElementAt(i); + return rv; + } + + /// For a set of handles, computes the pnl for each handle. + /// PNL = theo - zero_theo + public static IEnumerable compute_slide_pnl(IEnumerable ordered_greeks, IEnumerable ordered_handles, IEnumerable handle_greeks) + { + bts.Log.assert(handle_greeks.Count() == ordered_handles.Count()); + int zero_move_index = Array.FindIndex(ordered_handles.ToArray(), d => d == 0), + pnl_index = Array.FindIndex(ordered_greeks.ToArray(), g => g == VolSurfaceGreeks.PNL); + if (pnl_index >= 0 && zero_move_index >= 0) + { + List rv = new List(); + double zero_move_theo = handle_greeks.ElementAt(zero_move_index).position_greeks.ElementAt(pnl_index); + foreach (SlideGreekUnit u in handle_greeks) + { + double calc_pnl = u.position_greeks.ElementAt(pnl_index) - zero_move_theo; + rv.Add(u.change_greek(pnl_index, calc_pnl)); + } + return rv; + } + else + return handle_greeks; + } + + public static IDictionary> compute_future_slide(IEnumerable ordered_greeks, + IEnumerable handles, + mbts.SecurityTuple delta_terms_symbol, + IDictionary fut_pos_map, + IDictionary fut_theo_map, + IDictionary cpp_map) + { + IDictionary> rv = new Dictionary>(); + foreach (string future_symbol in new HashSet(fut_pos_map.Keys.Select(e => e.symbol))) + { + double cpp = cpp_map.TryGetValue(new mbts.SecurityTuple(SecurityType.Future, future_symbol, Venue.Unset), out cpp) ? cpp : Double.NaN, + delta_terms_symbol_cpp = cpp_map.TryGetValue(delta_terms_symbol, out delta_terms_symbol_cpp) ? delta_terms_symbol_cpp : Double.NaN; + IDictionary> sym_rv = _compute_single_symbol_future_slide(ordered_greeks, handles, future_symbol, fut_theo_map, fut_pos_map, cpp, delta_terms_symbol_cpp); + sym_rv.ToList().ForEach(kv => rv.Add(kv)); + } + //rv = rv.ToDictionary(kv => new VolSurfaceExpiration() + //{ + // symbol = kv.Key.symbol, + // expiration = mbts.ui.utility.ExpirationFormatter.convert_real_to_mapped(SecurityType.type.FUTURE, kv.Key.symbol, kv.Key.expiration) + //}, + //kv => kv.Value); + return rv; + } + + /// Computed the exp -> handles for one symbol + private static IDictionary> _compute_single_symbol_future_slide(IEnumerable ordered_greeks, + IEnumerable handles, + string fut_sym, + IDictionary fut_theo_map, + IDictionary future_pos_map, + double sym_cpp, double interms_sym_cpp) + { + IDictionary> rv = new Dictionary>(); + foreach (KeyValuePair kv in future_pos_map.Where(kv => kv.Key.symbol == fut_sym)) + { + VolSurfaceDriverTheo theo_tup = fut_theo_map.TryGetValue(kv.Key, out theo_tup) ? theo_tup : null; + IEnumerable exp_pos_greeks = _compute_single_exp_future_slide(ordered_greeks, handles, + theo_tup != null ? theo_tup.effective_theo : Double.NaN, + theo_tup != null ? theo_tup.effective_delta : Double.NaN, + theo_tup != null ? theo_tup.roll : Double.NaN, + kv.Value); + exp_pos_greeks = exp_pos_greeks.Select(s => VolSurfaceRiskCalculator.normalize_greeks(ordered_greeks, sym_cpp, interms_sym_cpp, 1.0, s)); + exp_pos_greeks = VolSurfaceRiskCalculator.compute_slide_pnl(ordered_greeks, handles, exp_pos_greeks); + rv[kv.Key] = exp_pos_greeks; + } + return rv; + } + + /// Computes the handles for one exp + private static IEnumerable _compute_single_exp_future_slide(IEnumerable ordered_greeks, IEnumerable handles, + double theo, double delta, double roll, double pos) + { + IEnumerable> handle_theos = _compute_future_slide_theos(handles, theo, delta, roll); + int pnl_index = Array.FindIndex(ordered_greeks.ToArray(), g => g == VolSurfaceGreeks.PNL), + delta_index = Array.FindIndex(ordered_greeks.ToArray(), g => g == VolSurfaceGreeks.Delta), + bsm_delta_index = Array.FindIndex(ordered_greeks.ToArray(), g => g == VolSurfaceGreeks.BSMDelta), + exp_delta_index = Array.FindIndex(ordered_greeks.ToArray(), g => g == VolSurfaceGreeks.ExpirationDelta), + flat_vol_delta_index = Array.FindIndex(ordered_greeks.ToArray(), g => g == VolSurfaceGreeks.FlatVolDelta); + List rv_handle_pos_greeks = new List(); + foreach (Tuple t in handle_theos) + { + double[] position_greeks = Enumerable.Repeat(0.0, ordered_greeks.Count()).ToArray(); + if (pnl_index >= 0) + position_greeks[pnl_index] = t.Item1 * pos; + if (delta_index >= 0) + position_greeks[delta_index] = t.Item2 * pos; + if (bsm_delta_index >= 0) + position_greeks[bsm_delta_index] = t.Item2 * pos; + if (flat_vol_delta_index >= 0) + position_greeks[flat_vol_delta_index] = t.Item2 * pos; + if (exp_delta_index >= 0) + position_greeks[exp_delta_index] = t.Item2 * pos; + rv_handle_pos_greeks.Add(new SlideGreekUnit(t.Item3, position_greeks)); + } + return rv_handle_pos_greeks; + } + + /// Returns an IEnum of theo, delta, driver for each handle + internal static IEnumerable> _compute_future_slide_theos(IEnumerable handles, double theo, double delta, double roll) + { + return handles.Select(h => + { + h = h / 100.0; + double handle_theo = h * (theo - roll) * delta + theo; + return Tuple.Create(handle_theo, delta, theo + (h * theo)); + }); + } + + #endregion + + #region Slide Simplification + + public static void compute_future_slide(IEnumerable ordered_greeks, + IEnumerable perc_handles, + mbts.SecurityTuple delta_terms_symbol, + IDictionary pos_map, + IDictionary theo_map, + IDictionary cpp_map, + out IDictionary slide_expiration_map) + { + slide_expiration_map = new Dictionary(); + int n_greeks = ordered_greeks.Count(), + zero_handle_index = perc_handles.find_first_index(0.0), + pnl_index = ordered_greeks.find_first_index(VolSurfaceGreeks.PNL); + double delta_terms_cpp = cpp_map.TryGetValue (delta_terms_symbol, out delta_terms_cpp) ? delta_terms_cpp : Double.NaN; + foreach (var kv_exp in pos_map) + { + VolSurfaceExpiration exp = kv_exp.Key; + double exp_pos = kv_exp.Value; + VolSurfaceDriverTheo exp_theo = theo_map.TryGetValue(exp, out exp_theo) ? exp_theo : VolSurfaceDriverTheo.empty; + double cpp = cpp_map.TryGetValue(new SecurityTuple(SecurityType.Future, exp.symbol, Venue.Unset), out cpp) ? cpp : Double.NaN; + IEnumerable> exp_handle_theos = _compute_future_slide_theos(perc_handles, exp_theo.theo, exp_theo.delta, exp_theo.roll); + SlideContractUnit exp_val = new SlideContractUnit(n_greeks, exp_handle_theos.Select(t => t.Item3)); + slide_expiration_map.Add(VolSurfaceRiskCalculator._to_sec_exp(exp, false), exp_val); + int handle_index = 0; + foreach (var t in exp_handle_theos) + { + double handle_theo = t.Item1, handle_driver = t.Item3; + int greek_index = 0; + foreach (VolSurfaceGreeks g in ordered_greeks) + { + double pos_greek_val = 0.0; + if (g == VolSurfaceGreeks.PNL) + pos_greek_val = handle_theo * exp_pos * cpp; + else if (g == VolSurfaceGreeks.Delta || g == VolSurfaceGreeks.BSMDelta || g == VolSurfaceGreeks.FlatVolDelta || g == VolSurfaceGreeks.ExpirationDelta) + pos_greek_val = exp_theo.delta * exp_pos * cpp / delta_terms_cpp; + exp_val.set_value(handle_index, greek_index, pos_greek_val); + greek_index++; + } + handle_index++; + } + exp_val.update_pnl(zero_handle_index, pnl_index); + } + } + + public static void compute_option_slide(IEnumerable ordered_greeks, + IEnumerable perc_handles, + mbts.SecurityTuple delta_terms_symbol, + string oev_terms_option_symbol, + IDictionary>> pos_map, + IDictionary> theo_map, + IDictionary cpp_map, + out IDictionary slide_strike_map, + out IDictionary slide_expiration_map) + { + slide_strike_map = new Dictionary(); + double delta_terms_cpp = cpp_map.TryGetValue (delta_terms_symbol, out delta_terms_cpp) ? delta_terms_cpp : Double.NaN, + oev_terms_cpp = cpp_map.TryGetValue(new SecurityTuple(SecurityType.Option, oev_terms_option_symbol,Venue.Unset), out oev_terms_cpp) ? oev_terms_cpp : Double.NaN; + int n_greeks = ordered_greeks.Count(), + zero_handle_index = perc_handles.find_first_index(0.0), + pnl_index = ordered_greeks.find_first_index(VolSurfaceGreeks.PNL); + IDictionary> exp_k_theo_map = VolSurfaceRiskCalculator._convert_exp_theos_to_strike_theos(theo_map); + /* expiration */ + foreach (var kv_exp in pos_map) + { + SecurityExpiration exp = _to_sec_exp(kv_exp.Key, true); + IDictionary> exp_pos_map = kv_exp.Value; + double cpp = cpp_map.TryGetValue(new SecurityTuple(SecurityType.Option, exp.symbol, Venue.Unset), out cpp) ? cpp : Double.NaN; + /* strike */ + foreach (var kv_k in exp_pos_map) + { + SecurityStrike k = new SecurityStrike(exp, kv_k.Key); + Tuple k_pos = kv_k.Value; + List k_ordered_theos = exp_k_theo_map[k]; + SlideContractUnit k_val = new SlideContractUnit(n_greeks, k_ordered_theos); + slide_strike_map[k] = k_val; + int handle_index = 0; + /* handle */ + foreach (Theos t in k_ordered_theos) + { + int greek_index = 0; + /* greeks */ + foreach (VolSurfaceGreeks g in ordered_greeks) + { + double mult = cpp / ((VolSurfaceRiskCalculator.is_delta_greek(g) || VolSurfaceRiskCalculator.is_gamma_greek(g)) ? delta_terms_cpp : (VolSurfaceRiskCalculator.is_oev_col(g) ? oev_terms_cpp : 1.0)); + double val = mult * (k_pos.Item1 * VolSurfaceUtilityFunctions.get_greek(g, t, true) + k_pos.Item2 * VolSurfaceUtilityFunctions.get_greek(g, t, false)); + k_val.set_value(handle_index, greek_index, val); + greek_index++; + } + handle_index++; + } + k_val.update_pnl(zero_handle_index, pnl_index); + } + } + IDictionary> exp_rv = new Dictionary>(); + foreach (var kv in slide_strike_map) + { + List exp_list; + if (!exp_rv.TryGetValue(kv.Key.expiration, out exp_list)) + exp_rv[kv.Key.expiration] = exp_list = new List(); + exp_list.Add(kv.Value); + } + slide_expiration_map = exp_rv.ToDictionary(kv => kv.Key, kv => SlideContractUnit.sum(kv.Value)); + } + + #endregion + + #region Conversions + + internal static VolSurfaceExpiration _to_vs_exp(SecurityExpiration exp) { return new VolSurfaceExpiration(exp.symbol, exp.expiration); } + + internal static mbts.SecurityExpiration _to_sec_exp(VolSurfaceExpiration exp, bool is_option) + { + return new SecurityExpiration(Venue.Unset, is_option ? SecurityType.Option : SecurityType.Future, exp.symbol, exp.expiration); + } + + internal static IDictionary _to_strike_map(IDictionary> exp_map) + { + IDictionary rv = new Dictionary(); + foreach (var kv_exp in exp_map) + foreach (var kv_strike in kv_exp.Value) + rv[new SecurityStrike (kv_exp.Key, kv_strike.Key)] = kv_strike.Value; + return rv; + } + + internal static IDictionary> _from_strike_map(IDictionary k_map) + { + IDictionary> rv = new Dictionary>(); + foreach (var kv in k_map) + { + IDictionary exp_map = null; + if (!rv.TryGetValue(kv.Key.expiration, out exp_map)) + rv[kv.Key.expiration] = exp_map = new Dictionary(); + exp_map[kv.Key.strike] = kv.Value; + } + return rv; + } + + internal static IDictionary> _convert_exp_theos_to_strike_theos(IDictionary> exp_theo_map) + { + Dictionary> rv = new Dictionary>(); + foreach (var kv in exp_theo_map) + foreach (Theos t in kv.Value) + { + SecurityStrike k = new SecurityStrike(kv.Key.symbol, kv.Key.expiration, t.strike); + List k_theos = null; + if (!rv.TryGetValue(k, out k_theos)) + rv[k] = k_theos = new List(); + k_theos.Add(t); + } + return rv.ToDictionary(kv => kv.Key, kv => kv.Value.OrderBy(t => t.driver).ToList()); + } + + #endregion + + #region Misc + + internal static void _add_arrays(double[] a1, double[] a2, ref double[] res) + { + res = res ?? Enumerable.Repeat(0.0, a1.Length).ToArray(); + bts.Log.assert(a1.Length == a2.Length); + bts.Log.assert(a1.Length == res.Length); + for (int i = 0; i < a1.Length; i++) + res[i] = a1[i] + a2[i]; + } + + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark_core/utils/CollectionHelper.cs b/src/client/spark_core/utils/CollectionHelper.cs index 94c9cf9ac..8a1d2691e 100644 --- a/src/client/spark_core/utils/CollectionHelper.cs +++ b/src/client/spark_core/utils/CollectionHelper.cs @@ -439,8 +439,7 @@ namespace bts.utils { } public static void compare_hashsets(HashSet new_d, HashSet old_d, - out HashSet deleted_d, out HashSet added_d) - { + out HashSet deleted_d, out HashSet added_d) { added_d = new HashSet(); deleted_d = new HashSet(); foreach (T t in new_d) @@ -451,16 +450,14 @@ namespace bts.utils { deleted_d.Add(t); } - public static IEnumerable append_arrays(params IEnumerable[] ienum_list) - { + public static IEnumerable append_arrays(params IEnumerable[] ienum_list) { List rv = new List(); foreach (IEnumerable ienum in ienum_list) rv.AddRange(ienum); return rv; } - public static bool hashset_equals(HashSet new_d, HashSet old_d) - { + public static bool hashset_equals(HashSet new_d, HashSet old_d) { HashSet deleted_d, added_d; compare_hashsets(new_d, old_d, out deleted_d, out added_d); return deleted_d.Count == 0 && added_d.Count == 0; @@ -471,12 +468,23 @@ namespace bts.utils { public static IDictionary ToDictionaryDupes(this IEnumerable items, Func key_selector, Func value_selector) { IDictionary rv = new Dictionary(); //(items ?? new List()).ForEach(t => rv[key_selector(t)] = value_selector(t)); - if (items != null){ - foreach (var t in items){ + if (items != null) { + foreach (var t in items) { rv[key_selector(t)] = value_selector(t); } } return rv; } + + public static int find_first_index(this IEnumerable list, T elem_to_find, Func equals = null) { + if (equals == null) equals = (t1, t2) => t1.Equals(t2); + int rv = 0; + foreach (T t in list) { + if (elem_to_find.Equals(t)) + return rv; + rv++; + } + return -1; + } } }