Exemplo n.º 1
0
    public override void DoWeights(ConstructGen<double> signalResults_, ConstructGen<double> fullSignalResults_, ConstructGen<double> wts_, List<ProductBase> products_, ConstructGen<double> filters_)
    {
      for (int i = 0; i < products_.Count; ++i)
      {
        double avg = 0;
        for (int j = 0; j < signalResults_.Dates.Count; ++j)
        {
          if(j<WindowLength)
          {
            wts_.SetValue(signalResults_.Dates[j],i,0);
            continue;
          }

          // if the product is not valid on this date then the weight is zero.
          if (double.IsNaN(filters_.GetValue(signalResults_.Dates[j],i)))
          {
            wts_.SetValue(signalResults_.Dates[j], i, 0.0);
          }
          else
          {
            for (int y = 0; y < WindowLength; ++y)
              avg += signalResults_.GetValue(signalResults_.Dates[j - y], i);
            avg /= WindowLength;

            double val = signalResults_.GetValue(signalResults_.Dates[j], i) / avg;

            wts_.MultValue(signalResults_.Dates[j], i, val, false);
          }
        }
      }
    }
Exemplo n.º 2
0
    public override void DoWeights(ConstructGen<double> signalResults_, ConstructGen<double> fullSignalResults_, ConstructGen<double> wts_, List<ProductBase> products_, ConstructGen<double> filters_)
    {
      double posSum;
      double negSum;
      int posCount;
      int negCount;

      foreach (DateTime date in wts_.Dates)
      {
        posSum=0.0;
        negSum=0.0;
        posCount=0;
        negCount=0;

        for (int i = 0; i < wts_.ArrayLength; ++i)
        {
          double val = signalResults_.GetValue(date, i);

          if (val == 0)
            continue;

          if (val > 0)
          {
            posSum+=val;
            ++posCount;
          }
          else
          {
            negSum+=val;
            ++negCount;
          }
        }

        double negAv = negSum / negCount;
        double posAv = posSum / posCount;

        for (int i = 0; i < wts_.ArrayLength; ++i)
        {
          double val = signalResults_.GetValue(date, i);

          if (val == 0)
          {
            wts_.MultValue(date, i, 0.0, false);
          }
          else if (val > 0)
          {
            double mult = val / posAv;
            double wt = 1.0 - (1.0 - (1.0 / mult));
            wts_.MultValue(date, i, wt,false);
          }
          else
          {
            double mult = val / negAv;
            double wt = 1.0 - (1.0 - (1.0 / mult));
            wts_.MultValue(date, i, wt,false);
          }
        }
      }
    }
Exemplo n.º 3
0
    public override void DoWeights(ConstructGen<double> signalResults_, ConstructGen<double> fullSignalResults_, ConstructGen<double> wts_, List<ProductBase> products_, ConstructGen<double> filters_)
    {
      List<SortHelpClass> list = new List<SortHelpClass>();

      foreach (DateTime date in signalResults_.Dates)
      {
        //wts_.MultValue(date, i, val, val < 0);

        list.Clear();

        for (int i = 0; i < signalResults_.ArrayLength; ++i)
        {
          double val = signalResults_.GetValue(date, i);

          if (double.IsNaN(val) == false)
            list.Add(new SortHelpClass(val, i, m_abs,false,false));
        }

        QuickSort.Sort<SortHelpClass>(list);



        for (int i = 0; i < wts_.ArrayLength && i < list.Count; ++i)
        {
          wts_.MultValue(date, list[i].ArrayIndex, list[i].Value, list[i].Value < 0);
        }

      }

    }
    public override void DoWeights(ConstructGen<double> signalResults_, ConstructGen<double> fullSignalResults_, ConstructGen<double> wts_, List<ProductBase> products_, ConstructGen<double> filters_)
    {
      double[] sigToday = new double[products_.Count];

      foreach (DateTime date in signalResults_.Dates)
      {
        double[] filterToday = filters_.GetValues(date);
        int productValidCount = 0;
        double sum = 0;

        for (int i = 0; i < sigToday.Length; ++i)
        {
          sigToday[i] = signalResults_.GetValue(date, i);
          if (double.IsNaN(filterToday[i]) == false && double.IsNaN(sigToday[i]) == false)
          {
            ++productValidCount;
            sum += sigToday[i];
          }
        }

        var avg = sum / Convert.ToDouble(productValidCount);

        for (int i = 0; i < sigToday.Length; ++i)
        {
          if (double.IsNaN(filterToday[i]) == false && double.IsNaN(sigToday[i]) == false)
            wts_.MultValue(date, i, sigToday[i] - avg);
        }
      }
    }
Exemplo n.º 5
0
    public override void DoWeights(ConstructGen<double> signalResults_, ConstructGen<double> fullSignalResults_, ConstructGen<double> wts_, List<ProductBase> products_, ConstructGen<double> filters_)
    {
      double[] sigToday = new double[products_.Count];
      double sum;

      foreach (DateTime date in signalResults_.Dates)
      {
        double[] filterToday = filters_.GetValues(date);
        sum = 0;

        for (int i = 0; i < sigToday.Length; ++i)
          if(double.IsNaN(filterToday[i])==false)
            sum += signalResults_.GetValue(date, i);

        for (int i = 0; i < sigToday.Length; ++i)
          if(double.IsNaN(filterToday[i])==false)
            wts_.MultValue(date, i, signalResults_.GetValue(date, i) / sum, false);
      }

    }
Exemplo n.º 6
0
    public override void DoWeights(ConstructGen<double> signalResults_, ConstructGen<double> fullSignalResults_, ConstructGen<double> wts_, List<ProductBase> products_, ConstructGen<double> filters_)
    {
      // go through each rebal date
      foreach (DateTime date in wts_.Dates)
      {
        for (int i = 0; i < wts_.ArrayLength; ++i)
        {
          if (products_[i].IsValid(date))
          {
            wts_.MultValue(date, i, signalResults_.GetValue(date, i) / Math.Pow(products_[i].GetVol(date, m_volType, m_windowLength), m_power), false);
          }
        }
      }

    }
Exemplo n.º 7
0
    public override void DoWeights(ConstructGen<double> signalResults_, ConstructGen<double> fullSignalResults_, ConstructGen<double> wts_, List<ProductBase> products_, ConstructGen<double> filters_)
    {
      foreach (DateTime date in signalResults_.Dates)
      {
        for (int i = 0; i < signalResults_.ArrayLength; ++i)
        {
          double val = signalResults_.GetValue(date, i);

          if (val < 0 && GoShort == false)
            wts_.SetValue(date, i, 0.0);
          else if (val > 0 && GoLong == false)
            wts_.SetValue(date, i, 0.0);
          else
            wts_.MultValue(date, i, val, false);
        }
      }
    }
Exemplo n.º 8
0
        public static ConstructGen<double> getOHLCSeriesFromBbg(DateTime firstDate_, string ticker_, bool insertNan_ = true)
        {
            var ret = new ConstructGen<double>(new string[] { "PX_OPEN", "PX_HIGH", "PX_LOW", "PX_CLOSE_1D" });
            DateTime[] bbgDates = null;
            for (int i = 0; i < ret.ColumnHeadings.Length; ++i)
            {
                DateTime start;
                if (i == 3)
                    start = firstDate_.AddDays(1);
                else
                    start = firstDate_;

                var b = BbgTalk.HistoryRequester.GetHistory(start, ticker_, ret.ColumnHeadings[i], false);

                if (b == null || b.Length == 0)
                {
                    throw new Exception(string.Format("No data retrieved for given ticker '{0}'", ticker_.ToUpper()));
                }
                else
                    b = HelperMethods.ensureAllWeekdays(b, insertNan_);

                if (i == 3)
                {
                    var closeData = bbgDates.Length > b.Dates.Length ? b.Data : b.Data.Skip(1).ToArray();
                    ret.SetColumnValues(i, bbgDates.SkipLast().ToArray(), closeData);
                }
                else
                {
                    ret.SetColumnValues(i, b.Dates, b.Data);
                    bbgDates = b.Dates;
                }
            }
            
            foreach (var d in ret.Dates.OrderByDescending(d => d))
            {
                if (ret.GetValue(d, 3) == 0)
                {
                    ret.RemoveValues(d);
                }
                else break;                
            }

            return ret;
        }
Exemplo n.º 9
0
    public FXCarry_5_20()
    {
      m_dailyCarry = Singleton<FXCarry>.Instance.GetData(
        startDate_: DataConstants.DATA_START,
        endDate_: DateTime.Today,
        forceRefresh_:true);

      StartDate = MyCalendar.NextDayOfWeek(m_dailyCarry.Dates.First().AddDays(30d), DayOfWeek.Tuesday);

      EER = (ccy_, date_) =>
      {
        int endIndex = m_dailyCarry.Dates.Contains(date_)
          ? m_dailyCarry.Dates.IndexOf(date_) - 1
          : m_dailyCarry.Dates.Count - 1;

        var carryLength = ccy_.IsGroup(FXGroup.NDF) ? 20 : 5;

        double sum = 0d;
        for (int i = 0; i < carryLength; ++i)
          sum += m_dailyCarry.GetValue(m_dailyCarry.Dates[endIndex - i], ccy_.ArrayIndex);

        var result = sum/Convert.ToDouble(carryLength);

        return result;
      };

      USDMin = -0.00001;
      USDMax = 0.00001;

      USDMin = USDMax = 0d;

      TargetVol = 0.06;

      LowerLimit = (ccy_, date_) => !ccy_.IsGroup(FXGroup.G10)
        ? -TargetVol*10d
        : -TargetVol*25d;

      UpperLimit = (ccy_, date_) => !ccy_.IsGroup(FXGroup.G10)
        ? TargetVol*10d
        : TargetVol*25d;
    }
Exemplo n.º 10
0
    public override void DoWeights(ConstructGen<double> signalResults_, ConstructGen<double> fullSignalResults_, ConstructGen<double> wts_, List<ProductBase> products_, ConstructGen<double> filters_)
    {
      foreach (DateTime date in signalResults_.Dates)
        for (int i = 0; i < products_.Count; ++i)
        {
          double v = signalResults_.GetValue(date, i);

          v = (v == 0) ? 0.0 : (v < 0) ? -1.0 : 1.0;
          v = (m_reverse) ? -v : v;

          if (m_scaleSignDifferently && v != 0)
          {
            v = (v < 0) ? (v * m_negScale) : (v * m_posScale);

            wts_.MultValue(date, i, v, v < 0);
          }
          else
          {
            wts_.SetValue(date, i, v);
            //wts_.SetToSign(date, i, v);
          }
        }
    }
Exemplo n.º 11
0
    public void Create(ConstructGen<double> candleData_, int openIndex_ = 0, int highIndex_ = 1, int lowIndex_ = 2, int closeIndex_ = 3)
    {
      var dt = new DataTable();
      dt.Rows.Clear();
      dt.Columns.Clear();

      dt.Columns.Add("Label", typeof(string));
      dt.Columns.Add("Date", typeof(DateTime));
      dt.Columns.Add("Open", typeof(double));
      dt.Columns.Add("High", typeof(double));
      dt.Columns.Add("Low", typeof(double));
      dt.Columns.Add("Close", typeof(double));
      dt.Columns.Add("Volume", typeof (double));

      CandleSeries cs = (CandleSeries)ultraChart1.CompositeChart.Series[0];

      var setupStarts = DeMarkAnalysis.GetSetups(candleData_);

      for(int i=0;i<candleData_.Dates.Count;++i)
      {
        var date = candleData_.Dates[i];
        var arr = candleData_.GetValues(date);
        dt.LoadDataRow(new object[]
        {
          ((dt.Rows.Count+1) % 10).ToString(),
          date,
          arr[openIndex_],
          arr[highIndex_],
          arr[lowIndex_],
          arr[closeIndex_],
          0d
        }, true);

        // any mark for this date?
        var mark = setupStarts.FirstOrDefault(x => x.Date == date);

        if (mark != null)
        {
          switch (mark.EventType)
          {
            case DeMarkEventType.BuySetupStart:
            {
              var annotation = createAnnotation("BuySetup", i + 0.5d, candleData_.GetValue(date, lowIndex_) - 1,
                Color.Green);
              ultraChart1.Annotations.Add(annotation);
            }
              break;
            case DeMarkEventType.SellSetupStart:
            {
              var annotatio = createAnnotation("SellSetup", i + 0.5d, candleData_.GetValue(date, highIndex_) + 1,
                Color.Red);
              ultraChart1.Annotations.Add(annotatio);
            }
              break;
          }
        }
      }

      cs.Data.LabelColumn = "Label";
      cs.Data.LowColumn = "Low";
      cs.Data.HighColumn = "High";
      cs.Data.OpenColumn = "Open";
      cs.Data.CloseColumn = "Close";
      cs.Data.DateColumn = "Date";
      cs.Data.VolumeColumn = "Volume";
      cs.Data.DataSource = dt;

      ultraChart1.InvalidateLayers();

      //EstablishDefaultTooltip((hash) =>
      //{
      //  return null;
      //});
    }
Exemplo n.º 12
0
    public static void Go()
    {
      // var is like 'dim'

      // make an array of size 10 - each initalized to the default double value i.e. 0d

      var arr = new double[10];

      // I could 'initialise' the values of this array in one call:

      arr = new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

      // an expanding construct is a list

      // make a list that I can only put doubles into

      var list = new List<double>();
      list.Add(1);
      list.Add(2);
      list.Add(3);

      // this is exactly the same as using an intializer:

      list = new List<double> {1, 2, 3};

      // I can use in built stuff to convert this to an array really easily

      double[] arr2 = list.ToArray();

      // dictionaries are lookups or hashmaps with types

      var birthdays = new Dictionary<string, DateTime>();
      birthdays.Add("Ben", new DateTime(1979, 12, 11));
      //or
      birthdays["Jess"] = new DateTime(1985, 1, 19);

      // note, the first method (.Add) will throw an exception if the item already exists, the second method will just overwrite

      // might be better to:
      if (birthdays.ContainsKey("Ben"))
        birthdays.Add("Ben", new DateTime(1979, 12, 11));

      // as we're dealing with time series a lot, I have created some classes that make it easier to work with dates and associated values

      // first of these is DatedDataCollection<T> where T is normally 'double'.

      // these are created with an array of Dates, and an array of 'Ts', which obviously must be of the same length, as the values correspond


      // NOTE: creating array on 1st, 3rd, 5th

      var dtsArray = new DateTime[] {new DateTime(2001, 1, 1), new DateTime(2001, 1, 3), new DateTime(2001, 1, 5)};
      var valuesArray = new double[] {1.21, 1.45, 1.65};

      var ddc = new DatedDataCollectionGen<double>(dtsArray, valuesArray);

      // obviously you wouldn't put normally create ddc like this - it normally gets populated from calls the the database or bbg initially, but we'll 
      // look at that later

      var date4th = new DateTime(2001, 1, 4);

      var value = ddc.ValueOnExactDate(date4th);  // this will fail as I'm insisting on the date being exact and there's nothing for 4th

      var value2 = ddc.ValueOnDate(date4th); // this will give me a value equal to that on the 3rd, since that is value for max date that is before 4th

      var value3 = ddc.ValueOnExactDate_Zero(date4th); // this won't fail but will pass back zero if there isn't an exact date

      // I've extended the classes to make it really easy to plot and see stuff

      ddc.DisplayColumnChart("Values in column chart");
      ddc.DisplayInGrid("values in grid");
      ddc.DisplayLineChart("Line chart");

      // this might be a bit of a leap, but I could very quickly extract EUR values from bloomberg in the following way, and display in a graph

      BbgTalk.HistoryRequester.GetHistory(new DateTime(2001, 1, 1),"EUR Curncy","PX_CLOSE",true)
        .DisplayLineChart("EUR from bbg from 2001");

      // what's this done?

      // BbgTalk.HistoryRequest knows how to connect to bloomberg and pulls out the series as a DatedDataCollection (so long as you're logged into bloomberg)

      DatedDataCollectionGen<double> euroSeries = BbgTalk.HistoryRequester.GetHistory(new DateTime(2001, 1, 1),
        "EUR Curncy", "PX_CLOSE", true);

      // then we displayed in a line chart:

      euroSeries.DisplayLineChart("EUR");

      // what else could we do with this euro series?

      // convert to returns:
      var euroReturns = euroSeries.ToReturns();
      var cumulative = euroReturns.ToCumulative();

      var stdFromMean = euroSeries.ToStdevFromMean(meanWindowLength_: 21, sdWindowLength_: 126);

      // I've also done a load of stuff to transform this series, take a look at HelperMethods.
      
      // often, we don't deal with individual price series, though we need inline data

      // for this I have made something called ConstructGen<T>, where again, T is normally a double

      var firstConstruct = new ConstructGen<double>(9);

      // this has made a construct that is set up to store dated values for 9 different variables

      // it's good to set the columnHeadings on the construct so you know what they refer to

      var headings = new string[] {"AUD", "CAD", "CHF", "EUR", "GBP", "JPY", "NOK", "NZD", "SEK"};
      firstConstruct.ColumnHeadings = headings;

      // (I'll show you how to do this more easily in a bit...

      // let's look at what we can do with construct and how we use it

      DateTime conDate = new DateTime(2014, 1, 1);

      firstConstruct.SetValue(conDate, 0, 100.2);

      // this has set the value for the first column (AUD) on the given Date

      // we get it out by:

      var v1 = firstConstruct.GetValue(conDate, 0);

      // set the second value:

      firstConstruct.SetValue(conDate, 1, 45.6);

      // this has set the value for the given date for 'CAD'

      // we could set all values at once using SetValues rather than SetValue

      firstConstruct.SetValues(conDate, new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9});

      // and we could get them out using:

      double[] allValuesOnDate = firstConstruct.GetValues(conDate);

      // there are lots of methods on Construct<T> to make our life easier when dealing with data

      // we can fill it up randomly using the SetValues, and then just call SortKeys() to ensure teh dates are in order

      firstConstruct.SortKeys();

      // this means that we will be iterate over the dates in order when we go through it

      // e.g.

      foreach (DateTime date in firstConstruct.Dates)
      {
        var datesVAlues = firstConstruct.GetValues(date);

        // here we could process them...
      }

      // there are methods on ConstructGen<T> to make it easy to see what's in it.  e.g.

      firstConstruct.DisplayInGrid("Grid of construct values");
      firstConstruct.DisplayInDataCollectionDisplay("Display each column as a line in a chart");

      // there is also a useful method to get the column of values as a DatedDataCollection<T>

      DatedDataCollectionGen<double> firstColumn = firstConstruct.GetColumnValuesAsDDC(0);

      // this is an expensive operation FYI, so you wouldn't use this iterating over the dates within the ConstructGen<T> , but it is useful

      
      // ok, now, as we have a set universe of ccys, in the way I extract data from the database (prices / weights / carry / etc) I tend to pull
      // out in a standard way, making a ConstructGen<double> with a column for every currency in the universe

      // so, for example, if I wanted the spots from the database from 2013 onwards, I would call this

      SI.Data.FXSpots spotsProvider = new FXSpots();

      ConstructGen<double> spots = spotsProvider.GetData(new DateTime(2013, 1, 1), DateTime.Today);

      // this returns me a ConstructGen<double> with 27 columns, with each row being a date 

      // I can then use the spots values as I wish

      // similarly

      SI.Data.FXForwards1Wk fwdProvider = new FXForwards1Wk();

      ConstructGen<double> fwds = fwdProvider.GetData(new DateTime(2013, 1, 1), DateTime.Today);

      // within these classes, the data is cached, so that I don't call the database again if I don't need to

      // so if I call for the second time:

      var spots2 = spotsProvider.GetData(new DateTime(2013, 1, 1), DateTime.Today);

      // ... this won't have hit the database again, but will get from the cached data

      // but you'll notice that i have to have a reference to spotsProvider to benefit from the cached data.
      // if I was to make the same request from another point in my code, I would have to create a new FXSpots() instance and then call the method on it to get the data

      // it can be useful in this instance to make use of what's known as the 'Singleton' pattern.
      // This basically provides a means of referring to the same instance every time, in this case so that we make use of cached data

      // I have a Singleton<T> wrapper that wraps up a single instance of T so that I know I'm calling methods on the same instance every time

      // so I would usually get spots from the database wrapping FXSpots in this.  like:

      spots = Singleton<FXSpots>.Instance.GetData(new DateTime(2013, 1, 1), DateTime.Today);

      // now I could call the method on Singleton<FXSpots>.Instance from anywhere in my code and I would benefit from the caching

      // I do tend to use most of the classes that retrive from the database Within SI.Data wrapped in a Singleton

      // another example is the class that pulls information about signals

      var signals = Singleton<Signals>.Instance;

      // this is just a list of SI.Data.Signal classes

      

    }
Exemplo n.º 13
0
    private ConstructGen<double>[] getWeights(TraderArgs args_, List<DateTime> rebalDates_, ConstructGen<double> filter_)
    {
      if (m_resultsWts.Count == 0)
        return null;

      ConstructGen<double>[] allWts = new ConstructGen<double>[args_.WtIndicators.Count];

      // go through all wtIndicators - will normally only be one
      for (int i = 0; i < args_.WtIndicators.Count; ++i)
      {
        ConstructGen<double> all_c,rebal_c;

        int length = args_.Products.Count;

        all_c = new ConstructGen<double>(length);
        rebal_c = new ConstructGen<double>(length);

        for (int j = 0; j < args_.Products.Count; ++j)
        {
          // extract the signal series for this wtIndicator and product
          DatedDataCollectionGen<double> dataForProductAndIndicator = m_resultsWts[args_.Products[j]][i];

          // put the data in the contruct that represents the signal at every point
          for (int y = 0; y < dataForProductAndIndicator.Length; ++y)
            all_c.SetValue(
              dataForProductAndIndicator.Dates[y],
              j,
              dataForProductAndIndicator.Data[y]);

          // put the data in the construct that represents the signal just on rebal days
          // NOTE: is offset by 1 day so not in sample
          foreach (DateTime d in rebalDates_)
          {
            //if (d == new DateTime(2010, 3, 19))
            //  System.Diagnostics.Debugger.Break();
            if (args_.Products[j].IsValid(d))
              rebal_c.SetValue(d, j, dataForProductAndIndicator.ValueOnDate(d, args_.DayOffset));
          }
        }

        // c is now a representation of the signal for all products on all days

        // do we want the product of the weights to determine which products can have positions on different days?
        if (args_.UseWeightsForFilter)
        {
          foreach (DateTime d in rebalDates_)
          {
            for (int ii = 0; ii < rebal_c.ArrayLength; ++ii)
              if (double.IsNaN(rebal_c.GetValue(d, ii)))
                filter_.SetValue(d, ii, double.NaN);
          }
        }

        // multiply it by the filter to get rid of non-eligible days

        rebal_c = multiply(rebal_c, filter_,false);

        //ConstructDisplay.Show(rebal_c, args_.Products.ToArray(), "raw signal * filter");

        // now need to scale the weights based on the weighting scheme supplied on the signal indicator 

        // create a construct which will be the multiple

        foreach (SI.Research.Backtest.Builder.Model.WtScheme transform in args_.WtIndicators[i].TransformList)
        {
          ConstructGen<double> wts = new ConstructGen<double>(length);
          wts.InitialiseToValue(rebalDates_,1d);

          transform.DoWeights(rebal_c, all_c, wts, args_.Products,filter_);

          wts = multiply(wts, filter_, true);

          rebal_c = wts;

          //ConstructDisplay.Show(rebal_c, args_.Products.ToArray(), "weights");
        }

        //ConstructDisplay.Show(rebal_c, new object[] { "wts" }, "transformed weights");

        allWts[i] = rebal_c;
      }

      return allWts;
    }
Exemplo n.º 14
0
    private ConstructGen<double> agreeSign(ConstructGen<double> a_, ConstructGen<double> b_)
    {
      ConstructGen<double> ret = new ConstructGen<double>(a_.ArrayLength);

      foreach (DateTime d in a_.Dates)
      {
        for (int i = 0; i < ret.ArrayLength; ++i)
        {
          double valA = a_.GetValue(d, i);
          double valB = b_.GetValue(d, i);

          if (double.IsNaN(valA)
            || double.IsNaN(valB)
            || ((valA > 0) && (valB < 0))
            || ((valA < 0) && (valB > 0))
            || ((valA==0) && (valB !=0))
            || ((valB==0) && (valA!=0)))
          {
            ret.SetValue(d, i, 0.0);
          }
          else
          {
            ret.SetValue(d, i, valA + valB);
          }
        }
      }
      return ret;
    }
    public ConstructGen<double> AllConstantMaturityPrices()
    {
      if (m_allFuturePrices != null)
        return m_allFuturePrices;

      // get the quarterlyin contracts
      var allIMMs = Underlying.IMM_Contracts();

      // build up the list of prices for all contracts

      ConstructGen<double> subCon;
      {
        var con = new ConstructGen<double>(allIMMs.Select(x => x.SymmetryCode).ToArray());
        {
          for (int i = 0; i < con.ArrayLength; ++i)
            con.SetColumnValues(i, allIMMs[i].GetPrices(marketSnapCode_:MarketSnapCode,quoteSource_:QuoteSourceCode,priceType_:1));

          con.SortKeys();
        }

        var dates = SI.Strategy.RatesSpreads.DateHelper.GetBusinessDates(CurveNames.USD3M);

        subCon = new ConstructGen<double>(con.ColumnHeadings);

        foreach (var date in dates)
          if (con.Dates.Contains(date))
            subCon.SetValues(date, con.GetValues(date));
      }

      // create the construct that will hode the constant maturity prices
      // is NumContracts+1 as first column will be interest rate fixing

      m_allFuturePrices =
        new ConstructGen<double>(
          ExtensionMethods.CreateArrayRep(Underlying.FutureStart, NumContracts+1)
            .Select((x, i) => string.Format("{0}cm{1}", x.ToUpper(), i))
            .ToArray());

      foreach (var date in subCon.Dates)
      {
        // set the fixing
        m_allFuturePrices.SetValue(date, 0, Underlying.FixingInstrmnet.GetPrices().ValueOnDate(date)*100d);

        for (int pointIndex = 0; pointIndex < NumContracts; ++pointIndex)
        {
          var daysForward = Convert.ToDouble(pointIndex + 1)*DaysSpan;
          var forwardDate = date.AddDays(daysForward);

          int beforeIndex=-1, afterIndex=-1;
          for (int i = 0; i < allIMMs.Count-1; ++i)
          {
            if(allIMMs[i].Maturity.Value==forwardDate)
            {
              beforeIndex = i;
              afterIndex = i;
              break;
            }
            else if (allIMMs[i].Maturity.Value < forwardDate && allIMMs[i+1].Maturity.Value > forwardDate)
            {
              beforeIndex = i;
              afterIndex = i + 1;
            }
          }

          // were the indexes of the contract that straddle the forward date found?
          if (beforeIndex >= 0)
          {
            if (beforeIndex == afterIndex)
            {
              m_allFuturePrices.SetValue(date, pointIndex+1, 100d-subCon.GetValue(date, beforeIndex));
            }
            else
            {
              var beforeValue = subCon.GetValue(date, beforeIndex);
              var afterValue = subCon.GetValue(date, afterIndex);

              if (beforeValue == 0d || afterValue == 0d)
                continue;

              var width = allIMMs[afterIndex].Maturity.Value - allIMMs[beforeIndex].Maturity.Value;

              var w1 = forwardDate - allIMMs[beforeIndex].Maturity.Value;

              var propAfter = w1.TotalDays/width.TotalDays;

              var interpValue = (afterValue*propAfter) + (beforeValue*(1d - propAfter));

              m_allFuturePrices.SetValue(date, pointIndex+1, 100d-interpValue);
            }
          }
        }
      }

      return m_allFuturePrices;
    }
Exemplo n.º 16
0
    public override void DoWeights(ConstructGen<double> signalResults_, ConstructGen<double> fullSignalResults_, ConstructGen<double> wts_, List<ProductBase> products_, ConstructGen<double> filters_)
    {
      List<SortHelpClass> list = new List<SortHelpClass>();

      // go through each rebal date
      foreach (DateTime date in wts_.Dates)
      {
        list.Clear();

        // pull out values and put into the list to sort
        for (int i = 0; i < wts_.ArrayLength; ++i)
        {
          double val = signalResults_.GetValue(date, i);
          double filt = filters_.GetValue(date, i);

          // has been filtered out already?  (indicated by NaN)
          if (double.IsNaN(filt) == false)
          {
            // filter out certain values?
            if (m_filterOutValues && (val >= m_lowerFilterOut && val <= m_higherFilterOut))
              continue;

            list.Add(new SortHelpClass(val, i, m_abs, m_smallestTopWeight,ReverseNegativeOrder));
          }
        }

        // sort the list
        QuickSort.Sort<SortHelpClass>(list);

        // initialise the values to zero
        wts_.InitialiseToValue(date, 0.0);

        // determine how many to select (can't selected more than number in list)
        int topCount = (m_topCount > list.Count) ? list.Count : m_topCount;
        int bottomCount = (m_bottomCount > list.Count) ? list.Count : m_bottomCount;

        if (topCount == 0) topCount = Convert.ToInt32(TopPercentage * Convert.ToDouble(list.Count));
        if (bottomCount == 0) bottomCount = Convert.ToInt32(BottomPercentage * Convert.ToDouble(list.Count));

        // ensure that, if doing top and bottom, there isn't overlap over the list
        if (m_doTop && m_doBottom && (topCount + bottomCount) > list.Count)
        {
          if (PickInLineWithSign)
          {
            int posCount = 0;
            int negCount = 0;
            foreach (SortHelpClass shc in list)
            {
              if (shc.Value > 0)
                ++posCount;
              else
                ++negCount;
            }
            topCount = posCount;
            bottomCount = negCount;
          }
          else
          {
            if (list.Count % 2 == 0)
              topCount = bottomCount = (list.Count / 2);
            else
              topCount = bottomCount = ((list.Count - 1) / 2);
          }
        }

        if (m_doTop)
        {
          for (int i = 0; i < topCount; ++i)
          {
            wts_.SetValue(date, list[i].ArrayIndex, getWeight(list[i].Value, i + 1, topCount, true));
          }
        }

        if (m_doBottom)
        {
          for (int i = 0; i < bottomCount; ++i)
          {
            int index = list.Count - 1 - i;

            wts_.SetValue(date, list[index].ArrayIndex, getWeight(list[index].Value, i + 1, bottomCount, false));
          }
        }

      }
    }
Exemplo n.º 17
0
 private static void AppendData(ConstructGen<string> ticker, StringBuilder sb, DateTime d, ConstructGen<double> spreads)
 {
     for (int i = 0; i < ticker.ColumnHeadings.Count(); i++)
     {
         sb.Append(ticker.GetValue(d, i));
         sb.Append(",");
         sb.Append(spreads.GetValue(d, i));
         sb.Append(",");
     }
 }
Exemplo n.º 18
0
    private SortedDictionary<DateTime, double[]> getCumulativePnls()
    {
      int[] selIndexes = getSelectedIndixes();

      ConstructGen<double> cum = new ConstructGen<double>(selIndexes.Length);

      DateTime prevDate = DateTime.MinValue;

      DateTime startDate = m_comp.GetDate(m_focus);
      int startI = m_comp.PnlConstruct.Dates.IndexOf(startDate);

      int endI = m_comp.PnlConstruct.Dates.IndexOf(m_comp.AsOfDate);

      for (int i = startI; i <= endI; ++i)
      {
        DateTime date = m_comp.PnlConstruct.Dates[i];

        for (int j = 0; j < selIndexes.Length; ++j)
        {
          if (i == startI)
          {
            cum.SetValue(date, j, m_comp.PnlConstruct.GetValue(date, selIndexes[j]));
          }
          else
          {
            cum.SetValue(date, j, m_comp.PnlConstruct.GetValue(date, selIndexes[j]) + cum.GetValue(prevDate, j));
          }
        }

        prevDate = date;
      }

      return new SortedDictionary<DateTime, double[]>(cum.GetInnerData());
    }
Exemplo n.º 19
0
    internal static void SaveWeightsFX(TraderArgs args_, ConstructGen<double> wts_, string stratName_)
    {
      foreach (DateTime date in wts_.Dates)
      {
        Dictionary<Data.Currency, double> wtsToday = new Dictionary<Data.Currency, double>();

        for (int i = 0; i < args_.Products.Count; ++i)
        {
          Data.Currency ccy = ((ProductFX)args_.Products[i]).CoreProduct;

          wtsToday.Add(ccy, wts_.GetValue(date, i));
        }
        //FXPositionSaver.SavePortfolio(stratName_, date, args_.ScaleToThisVol, wtsToday);

      }
    }
Exemplo n.º 20
0
    private void backFill(ConstructGen<double> data_, DayField valueField_, DayField volumeField_)
    {
      if (data_ == null || data_.Dates==null || data_.Dates.Count==0)
      {
        Logger.Error(
          string.Format("Today's backfill data was empty.  Unable to set intraday backfil data for {0} or {1}",
            valueField_, volumeField_), typeof (LiveDayComparison));
        return;
      }

      foreach (var key in data_.Keys)
      {
        var relativeKey = new RelativeDate(m_currentRoll.Dates, key);

        m_data.EnsureKey(relativeKey);

        var line = m_data.GetValue(relativeKey, currentIndex);

        if(line==null)
        {
          line = new Line();
          m_data.SetValue(relativeKey, (int)RollGeneration.Current, line);
        }

        line.SetValue(valueField_, data_.GetValue(key, (int)BarDataField.Close));
        line.SetValue(volumeField_, data_.GetValue(key, (int) BarDataField.Volume));
        line.CalcSeriesValue(m_currentRoll.DefaultTail);
      }
    }
Exemplo n.º 21
0
    private void backFill(ConstructGen<double> data_, DayField valueField_, DayField volumeField_)
    {
      if (data_ == null || data_.Dates == null || data_.Dates.Count == 0)
      {
        Logger.Error(
          string.Format("Today's backfill data was empty.  Unable to set intraday backfill data for {0} or {1}",
            valueField_, volumeField_), typeof(Day));
        return;
      }

      foreach (var key in data_.Keys)
      {
        var relativeKey = new RelativeDate(IndexedDates, key.ToTZfromGMT(DispTimeZone),DispTimeZone);

        if (relativeKey.Index == RelativeDate.INVALID_INDEX) 
          continue;

        m_data.EnsureKey(relativeKey);

        var line = m_data.GetValue(relativeKey, 0);

        if (line == null)
        {
          line = new Line {GMTDateTime = key.ToString(Line.MongoDateFormat)};
          m_data.SetValue(relativeKey, 0, line);
        }

        line.SetValue(valueField_, data_.GetValue(key, (int)BarDataField.Close));
        line.SetValue(volumeField_, data_.GetValue(key, (int)BarDataField.Volume));
        line.CalcSeriesValue(DefaultTail);
      }
    }
Exemplo n.º 22
0
    private ConstructGen<double> multiply(ConstructGen<double> a_, ConstructGen<double> b_, bool convertNAN_)
    {
      ConstructGen<double> ret = new ConstructGen<double>(a_.ArrayLength);

      foreach (DateTime d in a_.Dates)
      {
        for (int i = 0; i < ret.ArrayLength; ++i)
        {
          double val = a_.GetValue(d, i) * b_.GetValue(d, i);

          if (double.IsNaN(val) && convertNAN_)
            val = 0.0;

          ret.SetValue(d, i, val);
        }
      }

      return ret;
    }