本文整理汇总了C#中ConstructGen.SetValues方法的典型用法代码示例。如果您正苦于以下问题:C# ConstructGen.SetValues方法的具体用法?C# ConstructGen.SetValues怎么用?C# ConstructGen.SetValues使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ConstructGen
的用法示例。
在下文中一共展示了ConstructGen.SetValues方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Refresh
public void Refresh()
{
// going to get historical values from our database
ConstructGen<double> hist = new ConstructGen<double>(m_tickers.Count<string>());
for (int i = 0; i < m_tickers.Length; ++i)
{
var histvalues = BbgTalk.HistoryRequester.GetHistory(SI.Data.DataConstants.DATA_START, m_tickers[i],
"PX_LAST", false, null);
//histvalues = histvalues.unwind_1d();
hist.SetColumnValues(i, histvalues);
}
hist.SortKeys();
// initialise 'today's' values to previous day
hist.SetValues(DateTime.Today, (double[])hist.GetValues(hist.LastDate).Clone());
double[] avgs = new double[m_windowLength];
// initialise the avgs array NOTE: today's value is in item with index 0
for (int i = 0; i < m_windowLength; ++i)
avgs[i] = hist.GetValues(hist.Dates[hist.Dates.Count - 1 - i]).Average();
m_avgs = avgs;
m_liveValues = hist.GetValues(DateTime.Today);
}
示例2: DoScaleWeights
public static ConstructGen<double> DoScaleWeights(ConstructGen<double> wts_, TraderArgs args_, Func<DateTime,double> getVolTargetForDate_)
{
if (wts_.ColumnHeadings == null)
wts_.ColumnHeadings = args_.Products.Select(x => x.Name).ToArray();
var logReturns = args_.AllProductPrices(fillInGapsWithPrevious_: true).ToLogReturns(
args_.Products.Select(x => x.Convention).ToArray());
var scaledWts = new ConstructGen<double>(wts_.ColumnHeadings);
foreach (var date in wts_.Dates)
{
var wtArr = wts_.GetValues(date);
for (int i = 0; i < wtArr.Length; ++i)
if (double.IsInfinity(wtArr[i]))
wtArr[i] = 0d;
int indexOfDate = logReturns.FindIndexOfEffectiveDateOnDate(date);
indexOfDate = (indexOfDate < 252) ? 252 : indexOfDate - 1; // note offset
var subValues = logReturns.GetSubValues(logReturns.Dates[indexOfDate - 251], logReturns.Dates[indexOfDate]);
var covArr = SI.Data.FXHistCovar.MatCovar(subValues.ToArray());
var cov = new CovarianceItem(covArr);
scaledWts.SetValues(date, cov.ScaleSeries(wtArr, getVolTargetForDate_(date)));
}
return scaledWts;
}
示例3: getData
protected override ConstructGen<double> getData(DateTime startDate_, DateTime endDate_, bool forceRefresh_)
{
var con = new ConstructGen<double>(Singleton<FXIDs>.Instance.ColumnHeadings);
var spots = Singleton<FXSpots>.Instance.GetData(startDate_, endDate_, forceRefresh_);
var fwds = Singleton<FXForwards1Wk>.Instance.GetData(startDate_, endDate_, forceRefresh_);
var conventions = Singleton<FXIDs>.Instance.ConventionsDs;
var divisor = 5d;
foreach (var date in spots.Dates)
{
var spotsD = spots.GetValues(date);
var fwdsD = fwds.GetValues(date);
var cryD = new double[fwdsD.Length];
for (int i = 0; i < cryD.Length; ++i)
if (spotsD[i] != 0d && fwdsD[i] != 0d)
{
cryD[i] = (Math.Pow(spotsD[i] / fwdsD[i], conventions[i]) - 1d) * (252d/divisor);
}
con.SetValues(date, cryD);
}
return con;
}
示例4: extractDataFromDataset
private ConstructGen<double> extractDataFromDataset(DataSet ds_)
{
ConstructGen<double> con = new ConstructGen<double>(1);
foreach (DataRow row in ds_.Tables[0].Rows)
{
var r = extractPrice(row);
con.SetValues(r.Item1, new double[] { r.Item2 }, ConstructGenGen<DateTime, double>.KeyOptionsWhenAdding.AddEveryTime);
}
return con;
}
示例5: DoIt_DailyWeights
public static ReturnsFromWeightsResult DoIt_DailyWeights(ConstructGen<double> dailyWts_, DateTime? maxPnlDate_=null)
{
var wts = (ConstructGen<double>)dailyWts_.Clone();
var indexPrices = Singleton<ComIndexPrices>.Instance.GetData(DataConstants.DATA_START, DateTime.Today, false);
var indexReturns = indexPrices.ToReturns().GetSubValues(dailyWts_.Dates.First(),DateTime.Today);
var coms = Singleton<ComIDs>.Instance.ToArray();
var spotPnl = new ConstructGen<double>(wts.ColumnHeadings) {Name = wts.Name};
var dollImpWts = new ConstructGen<double>(wts.ColumnHeadings);
double[] currentWts = Utils.GetArrayOfValue(0d, wts.ArrayLength);
for (int i = 0; i < indexReturns.Dates.Count; ++i)
{
var date = indexReturns.Dates[i];
if (maxPnlDate_.HasValue && date > maxPnlDate_.Value)
break;
var todayIndexReturns = indexReturns.GetValues(date);
var todayStratReturns=new double[wts.ArrayLength];
for (int j = 0; j < todayStratReturns.Length; ++j)
{
// set today's strat returns
todayStratReturns[j] = currentWts[j]*todayIndexReturns[j];
// dollar impact weights
currentWts[j] *= (1d + todayStratReturns[j]);
}
spotPnl.SetValues(date, todayStratReturns);
// if the weights have change at the end of today, update currentWts so they affect tomorrows pnl
if (wts.Dates.Contains(indexReturns.Dates[i]))
currentWts = wts.GetValues(indexReturns.Dates[i]);
dollImpWts.SetValues(date, (double[]) currentWts.Clone());
}
return new ReturnsFromWeightsResult(dailyWts_.Name)
{
SpotPnl = spotPnl,
OriginalWts = dailyWts_,
DailyDollarImpactedWeights = dollImpWts,
SpotsUsed = indexPrices.GetSubValues(dailyWts_.Dates.First(),DateTime.Today)
};
}
示例6: Run
public override System.Collections.Generic.KeyValuePair<ConstructGen<double>, ReturnsEval.DataSeriesEvaluator> Run()
{
var dates = SI.Research.Backtest.Trader.GenerateRebalDates(Backtest.RebalFreq.Monthly,
MyCalendar.NextWeekDay(new System.DateTime(2006, 3, 1)));
var wts = new ConstructGen<double>(Singleton<ComIDs>.Instance.ColumnHeadings);
Func<ComID, bool> smallerPositionFunc =
(x) => x.Name.Equals("Lead") || x.Sector.Equals("Meats") || x.Sector.Equals("Softs");
var volTarget = 0.06d;
var limit = 0.3d;
var expReturns = ExtensionMethods.CreateArrayRep<double>(0.1d, wts.ArrayLength);
var lowerLimit = Singleton<ComIDs>.Instance.Select(x => smallerPositionFunc(x) ? -limit / 2d : -limit).ToArray();
var upperLimit = Singleton<ComIDs>.Instance.Select(x => smallerPositionFunc(x) ? limit / 2d : limit).ToArray();
var tcosts = ExtensionMethods.CreateArrayRep<double>(0d, wts.ArrayLength);
var oldwts = ExtensionMethods.CreateArrayRep(0d, wts.ArrayLength);
using (var opt = new SI.Research.ExcelOpt.ExcelOptimizer())
{
foreach (var date in dates)
{
var cov = Singleton<ComCovarianceSource>.Instance.GetCovarianceForDateElesePrevious(date, 30);
var result =
opt.DoIt(
numCcys_: expReturns.Length,
targetVol_: volTarget,
covariance_: cov.Data,
eer_: expReturns,
tcosts_: tcosts,
oldwts_: oldwts,
mins_: lowerLimit,
maxs_: upperLimit,
usdMin_: -100d,
usdMax_: 100d,
optHorizon_: "2W",
currentDate_: date);
if (result != null && result.Wts != null)
wts.SetValues(date, result.Wts);
}
}
var eval = BacktestHelper.DoCommodsPnl(wts,"Scratchpad");
return new System.Collections.Generic.KeyValuePair<ConstructGen<double>, ReturnsEval.DataSeriesEvaluator>(wts,
eval);
}
示例7: WtsSeriesAnalyzer
public WtsSeriesAnalyzer(string name_, ConstructGen<double> wts_, ConstructGen<double> dailyReturns_, GetCov covDelegate_, bool addFXGroups_=true)
{
m_wts = wts_;
m_perf = dailyReturns_;
m_covDelegate=covDelegate_;
Name=name_;
m_c2v = new ConstructGen<double>(wts_.ArrayLength);
m_c2v.ColumnHeadings = wts_.ColumnHeadings;
foreach (DateTime date in wts_.Dates)
{
double[] dayWts = wts_.GetValues(date);
if (Statistics.SumAbs(dayWts) == 0d || covDelegate_==null)
m_c2v.SetValues(date, new double[m_c2v.ArrayLength]);
else
m_c2v.SetValues(date, covDelegate_(date).GetContToVar(wts_.GetValues(date), false));
}
m_anal = new WtsAnalyzer(Name);
if(addFXGroups_) m_anal.AddFXGroups();
analyzePersistence();
EvaluateAll();
}
示例8: lblScore_Click
private void lblScore_Click(object sender, EventArgs e)
{
var we = SI.Research.FXStrat.BacktestHelper.getWE(Research.FXStrat.Strat.RVOL).Key;
var lastWeights = we.GetValues(we.LastDate);
var mult = Singleton<SI.Research.LiveIndicators.BreakoutStrategy.ParameterSets>.Instance.AvgAllocation;
var newWeights = lastWeights.MultiplyBy(mult*6d/1.215914d);
var sig = Singleton<SI.Data.Signals>.Instance.First(x => x.Name.StartsWith("Break"));
var con = new ConstructGen<double>(we.ColumnHeadings);
con.SetValues(DateTime.Today, newWeights);
sig.SaveWeightsToDB(wts_: con, obliterateCurrent_: false, overwrite_: true);
}
示例9: GetData
public static ConstructGen<double> GetData()
{
const string pathToConstruct = @"E:\CSI\EquityData.con";
if (File.Exists(pathToConstruct))
return Singleton<DiscCache>.Instance.ReadFromGivenFilePath<ConstructGen<double>>(pathToConstruct,true);
const string pathToCSV = @"E:\CSI\EquityData.csv";
var ret = new ConstructGen<double>(new string[] {"Open", "High", "Low", "Close"});
foreach (var v in CsvFile.Read<RowItem>(pathToCSV))
{
ret.SetValues(v.Date, new double[] {v.Open, v.High, v.Low, v.Close});
}
Singleton<DiscCache>.Instance.WriteToGivenFilePath(pathToConstruct, ret);
return ret;
}
示例10: GetBackTestWeights
//.........这里部分代码省略.........
var corrRanks =
Singleton<CovarianceSource>.Instance.GetCovarianceForDateElesePrevious(date, 5)
.GetIndividualAverageCorrelations()
.ToRanks(ascending_: true);
for (int i = 0; i < eerPos.Length; ++i)
{
var rank = corrRanks[i];
eerNeg[i] = (rank <= rankThreshold) ? 0.1 : -0.1;
eerPos[i] = (rank <= rankThreshold) ? -0.1 : 0.1;
}
}
break;
case ExpectedReturnType.EqualExceptLowestCorrel_pct10:
{
var pctThreshold = 0.1d;
var indivAvgCorrelations = Singleton<CovarianceSource>.Instance.GetCovarianceForDateElesePrevious(date, 5)
.GetIndividualAverageCorrelations();
double min = indivAvgCorrelations.Min();
double max = indivAvgCorrelations.Max();
double threshold = min + ((max - min)*pctThreshold);
for (int i = 0; i < eerPos.Length; ++i)
{
eerNeg[i] = (indivAvgCorrelations[i] <= threshold) ? 0.1 : -0.1;
eerPos[i] = (indivAvgCorrelations[i] <= threshold) ? -0.1 : 0.1;
}
}
break;
}
if (optArgs_.OptType == OptimationType.Excel)
{
var result = Singleton<ExcelOptimizer>.Instance.DoIt(
numCcys, targetVol, simCov.Data, doNeg ? eerNeg : eerPos, tcosts, prevWts, mins, maxs, usdMin, usdMax, optHorizon,
date);
//if (result.OptimizationResult != Optimizer.CarryOptResult.OptResult.OK_SolutionFoundAllConstraintsSatisfied)
// System.Diagnostics.Debugger.Break();
double[] dateWts = result.Wts;
if (result.Wts.SumAbs() == 0d)
System.Diagnostics.Debugger.Break();
// cross-sectional demean?
if (optArgs_.CSDemean)
{
double sum = 0d;
double count = 0d;
for (int i = 0; i < dateWts.Length; ++i)
if (dateWts[i] != 0d)
{
sum += dateWts[i];
count += 1d;
}
double avg = sum/count;
for (int i = 0; i < dateWts.Length; ++i)
if (dateWts[i] != 0d)
dateWts[i] -= avg;
dateWts = scaleCov.ScaleSeries(dateWts, CovarianceItem.VolFromVaR(0.02));
}
wts.SetValues(date, dateWts);
}
else if (optArgs_.OptType == OptimationType.SolverFoundation)
{
var model = new RvolSolveModel(
simCov,
Singleton<FXIDs>.Instance.Select(
(x, i) => new CurrencyLine(x, doNeg ? eerNeg[i] : eerPos[i], mins[i], maxs[i])).ToArray(),
targetVol)
{
SumOfWeightsMin=0d,
SumOfWeightsMax=0d
};
new RvolSolver().Solve(model);
wts.SetValues(date, model.CurrencyLines.Select(x => x.Weight).ToArray());
}
}
if(optArgs_.OptType==OptimationType.Excel)
Singleton<ExcelOptimizer>.Instance.Dispose();
return new RVOlOptResult()
{
TArgs = args,
Weights = wts,
TriggerDates = triggerDates
};
//return new KeyValuePair<TraderArgs, Construct>(args, wts);
}
示例11: TransformToCompoChartDataAndShift
public static Tuple<ConstructGen<double>, int, DateTime> TransformToCompoChartDataAndShift(DataAroundEvent[] data_, int numberAroundEvents_, DataAroundEventField field_)
{
ConstructGen<double> ret = new ConstructGen<double>(numberAroundEvents_ + 1);
ret.ColumnHeadings = new string[ret.ArrayLength];
//ret.ColumnHeadings[0] = DateTime.Today.ToString("dd-MMM-yyyy");
for (int i = 0; i <= numberAroundEvents_; ++i)
{
ret.ColumnHeadings[i] = i.ToString();
}
var headings = new List<string>(ret.ColumnHeadings);
int dayShift=0;
DateTime closestEvent=DateTime.MinValue;
if (data_ != null)
{
var eventdates = data_.Select(d => d.EventDate).ToArray();
// first find out any events falls within next 15 days
var maxAllowEventDate = DateTime.Today.AddDays(numberAroundEvents_);
var includeEvents = eventdates
.Where(newEvent => newEvent >= DateTime.Today && newEvent <= maxAllowEventDate);
if (includeEvents.Any())
{
closestEvent = includeEvents.OrderBy(e => e).First();
dayShift = (int)(closestEvent -DateTime.Today).TotalDays;
int firstDataIndex = numberAroundEvents_ - dayShift;
foreach (var eve in data_.OrderBy(x => x.EventDate))
{
// initialise to NaN
ret.SetValues(eve.EventDate, Utils.GetArrayOfValue<double>(double.NaN, ret.ArrayLength));
var subData = eve[field_];
if (subData != null)
for (int i = 0; i <= numberAroundEvents_; i++)
{
if (firstDataIndex + i > subData.Data.Length -1) continue;
if (subData.Data[firstDataIndex+i] == null) continue;
ret.SetValue(eve.EventDate, i, subData.Data[firstDataIndex+i].Value);
}
}
}
}
return new Tuple<ConstructGen<double>, int, DateTime>(ret, dayShift, closestEvent);
}
示例12: TransformToCon
public static ConstructGen<double> TransformToCon(DataAroundEvent[] data_, int numberAroundEvents_, DataAroundEventField field_)
{
ConstructGen<double> ret = new ConstructGen<double>((numberAroundEvents_ * 2) + 1);
ret.ColumnHeadings = new string[ret.ArrayLength];
ret.ColumnHeadings[numberAroundEvents_] = "0";
for (int i = 1; i <= numberAroundEvents_; ++i)
{
ret.ColumnHeadings[numberAroundEvents_ - i] = (-i).ToString();
ret.ColumnHeadings[numberAroundEvents_ + i] = i.ToString();
}
var headings = new List<string>(ret.ColumnHeadings);
if(data_!=null)
foreach (var eve in data_.OrderBy(x => x.EventDate))
{
// initialise to NaN
ret.SetValues(eve.EventDate, Utils.GetArrayOfValue<double>(double.NaN, ret.ArrayLength));
var subData = eve[field_];
if(subData!=null)
foreach (var point in subData.Data)
{
if (point == null) continue;
var index = headings.IndexOf((point.Index - data_.First().Offset).ToString());
ret.SetValue(eve.EventDate, index, point.Value);
}
}
return ret;
}
示例13: Create
public void Create(ConstructGen<double> wts_, FXGroup[] groups_)
{
ConstructGen<double> groupConv = new ConstructGen<double>(groups_.Length);
groupConv.ColumnHeadings = groups_.Select(x => x.ToString()).ToArray();
Currency[] ccys = wts_.ColumnHeadings.Select(x => Singleton<FXIDs>.Instance[x]).ToArray();
List<int[]> indicies =new List<int[]>();
foreach(FXGroup group in groups_)
{
List<int> groupIndicies=new List<int>();
for(int i=0;i<ccys.Length;++i)
if(ccys[i].IsGroup(group))
groupIndicies.Add(i);
indicies.Add(groupIndicies.ToArray());
}
foreach (DateTime date in wts_.Dates)
{
double[] dateWeights = wts_.GetValues(date);
double[] buckets = new double[groups_.Length];
for(int g=0;g<groups_.Length;++g)
foreach (int index in indicies[g])
buckets[g] += dateWeights[index];
groupConv.SetValues(date, buckets);
}
DataTable dt1 = groupConv.ToDataTable(groupConv.ColumnHeadings, "Date", "dd-MMM-yyyy");
Chart.ChartType = Infragistics.UltraChart.Shared.Styles.ChartType.Composite;
ChartArea area = new ChartArea();
Chart.CompositeChart.ChartAreas.Add(area);
AxisItem axisY = new AxisItem();
axisY.Extent = 50;
axisY.DataType = AxisDataType.Numeric;
axisY.OrientationType = AxisNumber.Y_Axis;
axisY.LineColor = Color.Blue;
axisY.Labels.Visible = true;
area.Axes.Add(axisY);
AxisItem axisX = new AxisItem();
axisX.DataType = AxisDataType.String;
axisX.Extent = 80;
axisX.SetLabelAxisType = Infragistics.UltraChart.Core.Layers.SetLabelAxisType.GroupBySeries;
axisX.OrientationType = AxisNumber.X_Axis;
axisX.LineColor = Color.Blue;
axisX.Labels.Orientation = TextOrientation.VerticalLeftFacing;
axisX.Labels.SeriesLabels.Orientation = TextOrientation.VerticalLeftFacing;
area.Axes.Add(axisX);
AxisItem axisX2 = new AxisItem();
axisX2.DataType = AxisDataType.String;
axisX2.Extent = 80;
axisX2.OrientationType = AxisNumber.X_Axis;
axisX2.LineColor = Color.Blue;
axisX2.Labels.Orientation = TextOrientation.VerticalLeftFacing;
axisX2.Labels.SeriesLabels.Orientation = TextOrientation.VerticalLeftFacing;
axisX2.SetLabelAxisType = SetLabelAxisType.ContinuousData;
area.Axes.Add(axisX2);
ChartLayerAppearance myColumnLayer = new ChartLayerAppearance();
myColumnLayer.ChartType = ChartType.StackColumnChart;
myColumnLayer.ChartArea = area;
foreach (FXGroup group in groups_)
{
NumericSeries series1 = new NumericSeries();
series1.Key = group.ToString();
series1.DataBind(dt1, group.ToString(), "Date");
series1.PEs.Add(new PaintElement(ColorAttribute.GetAttribute(group).Color));
myColumnLayer.Series.Add(series1);
Chart.CompositeChart.Series.Add(series1);
}
DataTable dt2 = wts_.SumRows().ToDataTable(format_:"dd-MMM-yyyy");
ChartLayerAppearance myColumnLayer2 = new ChartLayerAppearance();
myColumnLayer2.ChartType = ChartType.LineChart;
myColumnLayer2.ChartArea = area;
NumericSeries seriesA = new NumericSeries();
seriesA.Key = "Sum of Wts";
seriesA.DataBind(dt2, "Value", "Date");
seriesA.PEs.Add(new PaintElement(Color.Orange));
myColumnLayer2.Series.Add(seriesA);
Chart.CompositeChart.Series.Add(seriesA);
LineChartAppearance la = new LineChartAppearance();
la.Thickness = 4;
myColumnLayer2.ChartTypeAppearance = la;
myColumnLayer.AxisX = axisX;
myColumnLayer.AxisY = axisY;
//.........这里部分代码省略.........
示例14: WhatIfTradingRestrictions
public ConstructGen<double> WhatIfTradingRestrictions(WtRestriction[] wtsFlowMaxs_)
{
System.Diagnostics.Debug.Assert(wtsFlowMaxs_.Length == SourceWts.ArrayLength, "Need wtsFlowMaxs_ length to match the ArrayLength of the weights in question, else don't know how to restrict the flow");
ConstructGen<double> ret = new ConstructGen<double>(SourceWts.ArrayLength);
ret.ColumnHeadings = SourceWts.ColumnHeadings;
ConstructGen<double> workingSourceWts = (ConstructGen<double>)SourceWts.Clone();
DateTime currentDate = workingSourceWts.Dates[0];
double[] priorWeights = ExtensionMethods.CreateArrayRep<double>(0d, ret.ArrayLength);
while (currentDate <= DateTime.Today)
{
// do we have new target weights for today?
if (workingSourceWts.Dates.Contains(currentDate) == false)
{
currentDate = MyCalendar.NextWeekDay(currentDate);
continue;
}
double[] targetWeights = workingSourceWts.GetValues(currentDate);
// check the movement on all weights to ensure that they're within tolerance
bool needToTradeResidualTomorrow = false;
double[] newWeights = new double[ret.ArrayLength];
for (int i = 0; i < targetWeights.Length; ++i)
{
double targetWeight = targetWeights[i];
double allowedTargetWeight = wtsFlowMaxs_[i].GetNewWeight(oldWeight_: priorWeights[i], targetWeight_: targetWeights[i]);
if (allowedTargetWeight != targetWeights[i])
if (!(wtsFlowMaxs_[i].MaxSize != null && wtsFlowMaxs_[i].MaxSize == Math.Abs(allowedTargetWeight)))
needToTradeResidualTomorrow = true;
newWeights[i] = allowedTargetWeight;
}
ret.SetValues(currentDate, newWeights);
priorWeights = newWeights;
// if we haven't successed to reach the target weights then we need to try and get there tomorrow...
if (needToTradeResidualTomorrow)
{
workingSourceWts.SetValues(MyCalendar.NextWeekDay(currentDate), targetWeights);
}
currentDate = MyCalendar.NextWeekDay(currentDate);
}
return ret;
}
示例15: AllConstantMaturityPrices
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;
}