This commit is contained in:
2024-02-23 06:53:16 -05:00
commit dbdccce727
1094 changed files with 57645 additions and 0 deletions

View File

@@ -0,0 +1,161 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using MarketData.Utils;
using MarketData.Numerical;
namespace MarketData.MarketDataModel
{
public class BollingerBandElementsByDate : Dictionary<DateTime, BollingerBandElement>
{
public BollingerBandElementsByDate()
{
}
}
public class BollingerBands : BollingerBandElements
{
public BollingerBands()
{
}
public BollingerBands(List<BollingerBandElement> bollingerBandElements)
{
foreach(BollingerBandElement bollingerBandElement in bollingerBandElements)Add(bollingerBandElement);
}
public static String GetHeader(int movingAverageDays)
{
StringBuilder sb = new StringBuilder();
sb.Append("Date,Symbol,Open,High,Low,Close,Volume,SMA(").Append(movingAverageDays).Append("),StDev(").Append(movingAverageDays).Append("),K,L,K-1,L+1");
return sb.ToString();
}
public BollingerBandElementsByDate GetBollingerBandElementsByDate()
{
BollingerBandElementsByDate bollingerBandElementsByDate = new BollingerBandElementsByDate();
for (int index = 0; index < Count; index++)
{
BollingerBandElement bollingerBandElement = this[index];
if (!bollingerBandElementsByDate.ContainsKey(bollingerBandElement.Date)) bollingerBandElementsByDate.Add(bollingerBandElement.Date, bollingerBandElement);
}
return bollingerBandElementsByDate;
}
}
public class BollingerBandElements : List<BollingerBandElement>
{
public BollingerBandElements()
{
}
public BollingerBandElements(List<BollingerBandElement> bollingerBandElements)
{
foreach(BollingerBandElement bollingerBandElement in bollingerBandElements)Add(bollingerBandElement);
}
public LeastSquaresResult LeastSquaresFitClose()
{
double[] closingPrices=(from BollingerBandElement bollingerBandElement in this select bollingerBandElement.Close).ToList().ToArray();
LeastSquaresResult leastSquaresResult=Numerics.LeastSquares(closingPrices);
return leastSquaresResult;
}
}
public class BollingerBandElement
{
private DateTime date;
private String symbol;
private double open;
private double high;
private double low;
private double close;
private long volume;
private double smaN;
private double stdevN;
private double k;
private double l;
private double kl1;
private double lp1;
public BollingerBandElement()
{
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
public String Symbol
{
get { return symbol; }
set { symbol = value; }
}
public double Open
{
get { return open; }
set { open = value; }
}
public double High
{
get { return high; }
set { high = value; }
}
public double Low
{
get { return low; }
set { low = value; }
}
public double Close
{
get { return close; }
set { close = value; }
}
public double SMAN
{
get { return smaN; }
set { smaN = value; }
}
public double StDevN
{
get { return stdevN; }
set { stdevN = value; }
}
public long Volume
{
get { return volume; }
set { volume = value; }
}
public double K
{
get { return k; }
set { k = value; }
}
public double L
{
get { return l; }
set { l = value; }
}
public double KL1
{
get { return kl1; }
set { kl1 = value; }
}
public double LP1
{
get { return lp1; }
set { lp1 = value; }
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(Date)).Append(",");
sb.Append(Symbol).Append(",");
sb.Append(Open).Append(",");
sb.Append(High).Append(",");
sb.Append(Low).Append(",");
sb.Append(Close).Append(",");
sb.Append(Volume).Append(",");
sb.Append(SMAN).Append(",");
sb.Append(StDevN).Append(",");
sb.Append(K).Append(",");
sb.Append(L).Append(",");
sb.Append(KL1).Append(",");
sb.Append(LP1);
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MarketData.MarketDataModel
{
public class Constants
{
public const String CONST_ALL ="{All}";
public const String CONST_DASHES = "---";
public const String NA = "N.A.";
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MarketData.MarketDataModel
{
public class GainLossSummaryItemCollection : List<GainLossSummaryItem>
{
public GainLossSummaryItemCollection()
{
}
public GainLossSummaryItemCollection(List<GainLossSummaryItem> gainLossSummaryItemCollection)
{
foreach(GainLossSummaryItem gainLossSummaryItem in gainLossSummaryItemCollection)Add(gainLossSummaryItem);
}
public GainLossSummaryItemCollection SortByChange()
{
GainLossSummaryItemCollection gainLossSummaryCollection=new GainLossSummaryItemCollection((from GainLossSummaryItem gainLossSummaryItem in this orderby gainLossSummaryItem.Date descending,gainLossSummaryItem.Change descending, gainLossSummaryItem.Symbol descending select gainLossSummaryItem).ToList());
return gainLossSummaryCollection;
}
}
public class GainLossSummaryItem
{
public GainLossSummaryItem()
{
}
public DateTime Date{get;set;}
public String Symbol{get;set;}
public String CompanyName{get;set;}
public double CurrentGainLoss{get;set;}
public double PreviousGainLoss{get;set;}
public double Change{get;set;}
public double ChangePercent{get;set;}
public bool HasStopLimit{get;set;}
}
}

View File

@@ -0,0 +1,35 @@
using System;
namespace MarketData.MarketDataModel.GainLoss
{
public class DMAValue
{
private DateTime date;
private double value;
private double maValue;
public DMAValue()
{
}
public DMAValue(DateTime date, double value)
{
this.date = date;
this.value = value;
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
public double Value
{
get { return value; }
set { this.value = value; }
}
public double MAValue
{
get { return maValue; }
set { this.maValue = value; }
}
}
}

View File

@@ -0,0 +1,21 @@
using System.Collections.Generic;
namespace MarketData.MarketDataModel.GainLoss
{
public class DMAValues : List<DMAValue>
{
public DMAValues()
{
}
public float[] GetValues(int startIndex, int count)
{
if (startIndex + count > Count) return null;
float[] valuesArray = new float[count];
for (int index = startIndex, arrayIndex = 0; index < startIndex + count; index++, arrayIndex++)
{
valuesArray[arrayIndex] = (float)this[index].Value;
}
return valuesArray;
}
}
}

View File

@@ -0,0 +1,19 @@
using System;
namespace MarketData.MarketDataModel.GainLoss
{
// **************************************************************************************************************************************************************
// *********************************************** G A I N / L O S S C O M P O U N D M O D E L ****************************************
// **************************************************************************************************************************************************************
// This GainLossModel will be used to model the GainLossView in terms of surfacing the Active Gain/Loss, Active Exposure, Active Gain/Loss%, Total Gain/Loss, Total Gain/Loss % data
public class GainLossCompoundModel
{
public DateTime Date{get;set;}
public double ActiveExposure{get;set;}
public double ActiveGainLoss{get;set;}
public double ActiveGainLossPercent{get;set;}
public double TotalGainLoss{get;set;}
public double TotalGainLossPercent{get;set;}
public double TotalDividendsPaid{get;set;}
}
}

View File

@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
namespace MarketData.MarketDataModel.GainLoss
{
// The GainLossCompoundModelCollection contains both the active gain loss and the total gain loss time series data
public class GainLossCompoundModelCollection : List<GainLossCompoundModel>
{
public GainLossCompoundModelCollection()
{
}
public GainLossCompoundModelCollection(List<GainLossCompoundModel> items)
{
foreach(GainLossCompoundModel item in items)Add(item);
}
public GainLossCompoundModelCollection(GainLossCollection activeGainLossCollection,TotalGainLossCollection totalGainLossCollection)
{
if(null==activeGainLossCollection||null==totalGainLossCollection)return;
Dictionary<DateTime,GainLossItem> activeGainLossCollectionByDate=new Dictionary<DateTime,GainLossItem>();
Dictionary<DateTime,TotalGainLossItem> totalGainLossCollectionByDate=new Dictionary<DateTime,TotalGainLossItem>();
foreach(GainLossItem gainLossItem in activeGainLossCollection)if(!activeGainLossCollectionByDate.ContainsKey(gainLossItem.Date))activeGainLossCollectionByDate.Add(gainLossItem.Date,gainLossItem);
foreach(TotalGainLossItem gainLossItem in totalGainLossCollection)if(!totalGainLossCollectionByDate.ContainsKey(gainLossItem.Date))totalGainLossCollectionByDate.Add(gainLossItem.Date,gainLossItem);
List<DateTime> dates=new List<DateTime>(activeGainLossCollectionByDate.Keys);
dates.Sort();
foreach(DateTime date in dates)
{
GainLossItem activeGainLossItem=activeGainLossCollectionByDate[date];
if(!totalGainLossCollectionByDate.ContainsKey(date))continue;
TotalGainLossItem totalGainLossItem=totalGainLossCollectionByDate[date];
GainLossCompoundModel gainLossModel=new GainLossCompoundModel();
gainLossModel.Date=activeGainLossItem.Date;
gainLossModel.ActiveExposure=activeGainLossItem.Exposure;
gainLossModel.ActiveGainLoss=activeGainLossItem.GainLoss;
gainLossModel.ActiveGainLossPercent=activeGainLossItem.GainLossPercent;
gainLossModel.TotalGainLoss=totalGainLossItem.TotalGainLoss;
gainLossModel.TotalGainLossPercent=totalGainLossItem.TotalGainLossPercent;
gainLossModel.TotalDividendsPaid=totalGainLossItem.TotalDividendsPaid;
Add(gainLossModel);
}
}
public DMAValues DMAValuesActiveGainLoss
{
get
{
DMAValues dmaValues = new DMAValues();
foreach (GainLossCompoundModel gainLoss in this)
{
dmaValues.Add(new DMAValue(gainLoss.Date,gainLoss.ActiveGainLoss));
}
return dmaValues;
}
}
public DMAValues DMAValuesTotalGainLoss
{
get
{
DMAValues dmaValues = new DMAValues();
foreach (GainLossCompoundModel gainLoss in this)
{
dmaValues.Add(new DMAValue(gainLoss.Date,gainLoss.TotalGainLoss));
}
return dmaValues;
}
}
public DMAValues DMAValuesActiveGainLossPercent
{
get
{
DMAValues dmaValues = new DMAValues();
foreach (GainLossCompoundModel gainLoss in this)
{
dmaValues.Add(new DMAValue(gainLoss.Date,gainLoss.ActiveGainLossPercent));
}
return dmaValues;
}
}
public DMAValues DMAValuesTotalGainLossPercent
{
get
{
DMAValues dmaValues = new DMAValues();
foreach (GainLossCompoundModel gainLoss in this)
{
dmaValues.Add(new DMAValue(gainLoss.Date,gainLoss.TotalGainLossPercent));
}
return dmaValues;
}
}
}
}

View File

@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using MarketData.Utils;
namespace MarketData.MarketDataModel.GainLoss
{
// *********************************************************************************************************************************************************************
// ************************************************************************ G A I N L O S S **************************************************************************
// *********************************************************************************************************************************************************************
// This gain loss provides a picture of the Active Gain/Loss. The gain loss on open positions
public class GainLossItem : IComparable
{
private DateTime date;
private double gainLoss;
private double gainLossPercent;
private double exposure;
private double dividends;
private bool valueIsPercent;
public GainLossItem()
{
}
public GainLossItem(DateTime date, double gainLoss,double exposure,bool valueIsPercent)
{
this.date = date;
this.gainLoss = gainLoss;
this.exposure = exposure;
this.valueIsPercent = valueIsPercent;
}
public GainLossItem(DateTime date, double gainLoss,double gainLossPercent,double exposure,bool valueIsPercent)
{
this.date = date;
this.gainLoss = gainLoss;
this.gainLossPercent=gainLossPercent;
this.exposure = exposure;
this.valueIsPercent = valueIsPercent;
}
public GainLossItem(DateTime date, double gainLoss,double gainLossPercent,double exposure,double dividends,bool valueIsPercent)
{
this.date = date;
this.gainLoss = gainLoss;
this.gainLossPercent=gainLossPercent;
this.exposure = exposure;
this.dividends=dividends;
this.valueIsPercent = valueIsPercent;
}
public DateTime Date
{
get { return date; }
}
public double Exposure
{
get
{
return exposure;
}
}
public double GainLoss
{
get { return gainLoss; }
}
public double Dividends
{
get{return dividends;}
}
public double GainLossPercent
{
get { return gainLossPercent; }
}
public bool ValueIsPercent
{
get
{
return valueIsPercent;
}
set
{
valueIsPercent = value;
}
}
public String FormattedGainLoss
{
get
{
if (valueIsPercent) return Utility.FormatNumber(gainLoss);
return Utility.FormatCurrency(gainLoss);
}
}
public int CompareTo(Object obj)
{
if (!obj.GetType().IsInstanceOfType(this)) throw new Exception("Expected GainLoss");
GainLossItem that = (GainLossItem)obj;
return date.CompareTo(that.Date);
}
}
public class GainLossCollection : List<GainLossItem>
{
public GainLossCollection(ICollection<GainLossItem> gainLoss)
: base(gainLoss)
{
}
public DMAValues DMAValues
{
get
{
DMAValues dmaValues = new DMAValues();
foreach (GainLossItem gainLoss in this)
{
dmaValues.Add(new DMAValue(gainLoss.Date,gainLoss.GainLoss));
}
return dmaValues;
}
}
}
}

View File

@@ -0,0 +1,16 @@
using System.Collections.Generic;
namespace MarketData.MarketDataModel.GainLoss
{
// ****************************************************************************************************************************************************
// ********************************************************************** T O T A L G A I N L O S S *************************************************
// ****************************************************************************************************************************************************
// This Gain/Loss provides a picture of the total Gain/Loss. This is Gain/Loss generated by all trades
public class TotalGainLossCollection : List<TotalGainLossItem>
{
public TotalGainLossCollection(ICollection<TotalGainLossItem> gainLoss)
: base(gainLoss)
{
}
}
}

View File

@@ -0,0 +1,49 @@
using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.IO;
//using MarketData.Utils;
//using System.Collections.ObjectModel;
//using MarketData.Generator.GainLoss;
//using MarketData.DataAccess;
namespace MarketData.MarketDataModel.GainLoss
{
// ****************************************************************************************************************************************************
// ********************************************************************** T O T A L G A I N L O S S *************************************************
// ****************************************************************************************************************************************************
// This Gain/Loss provides a picture of the total Gain/Loss. This is Gain/Loss generated by all trades
public class TotalGainLossItem : IComparable
{
public TotalGainLossItem(DateTime date,double totalGainLoss,double totalGainLossPercent,double totalExposure,double totalMarketValue)
{
Date=date;
TotalGainLoss=totalGainLoss;
TotalExposure=totalExposure;
TotalMarketValue=totalMarketValue;
TotalGainLossPercent=totalGainLossPercent;
}
public TotalGainLossItem(DateTime date,double totalGainLoss,double totalGainLossPercent,double totalExposure,double totalMarketValue,double totalDividendsPaid)
{
Date=date;
TotalGainLoss=totalGainLoss;
TotalExposure=totalExposure;
TotalMarketValue=totalMarketValue;
TotalGainLossPercent=totalGainLossPercent;
TotalDividendsPaid=totalDividendsPaid;
}
public DateTime Date{get;private set;}
public double TotalGainLoss{get;private set;}
public double TotalGainLossPercent{get;private set;}
public double TotalExposure{get;private set;}
public double TotalMarketValue{get;private set;}
public double TotalDividendsPaid{get;private set;}
public int CompareTo(Object obj)
{
if (!obj.GetType().IsInstanceOfType(this)) throw new Exception("Expected GainLoss");
TotalGainLossItem that = (TotalGainLossItem)obj;
return Date.CompareTo(that.Date);
}
}
}

View File

@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MarketData.MarketDataModel
{
public class Headlines : List<Headline>
{
}
public class Headline
{
public Headline()
{
}
public Headline(Headline headline)
{
Date=headline.Date;
Symbol=headline.Symbol;
CompanyName=headline.CompanyName;
Entry=headline.Entry;
Modified=headline.Modified;
Source=headline.Source;
}
public Headline(String symbol,DateTime date,String entry)
{
Symbol=symbol;
Date=date;
Entry=entry;
Modified=DateTime.Now;
}
public DateTime Date{get;set;}
public String Symbol{get;set;}
public String CompanyName{get;set;}
public String Entry{get;set;}
public DateTime Modified{get;set;}
public String Source{get;set;}
}
}

View File

@@ -0,0 +1,51 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using MarketData.Generator;
namespace MarketData.MarketDataModel
{
// These are models that were designed to be consumed by the mobile platform
public class PortfolioTradesWithParityPrice
{
public PortfolioTradesWithParityPrice(PortfolioTrades portfolioTrades, Price parityPrice)
{
Trades = portfolioTrades;
ParityPrice = parityPrice;
}
public Price ParityPrice { get; set; }
public PortfolioTrades Trades { get; set; }
}
// ************************************************************************************
public class GainLossSummaryItemDetail: GainLossSummaryItem
{
public GainLossSummaryItemDetail()
{
}
public GainLossSummaryItemDetail(GainLossSummaryItem gainLossSummaryItem)
{
this.Date=gainLossSummaryItem.Date;
this.Symbol=gainLossSummaryItem.Symbol;
this.CompanyName=gainLossSummaryItem.CompanyName;
this.CurrentGainLoss=gainLossSummaryItem.CurrentGainLoss;
this.PreviousGainLoss=gainLossSummaryItem.PreviousGainLoss;
this.Change=gainLossSummaryItem.Change;
this.ChangePercent=gainLossSummaryItem.ChangePercent;
this.HasStopLimit = gainLossSummaryItem.HasStopLimit;
}
public int Lots{get;set;}
public double Shares{get;set;}
public double Exposure{get;set;}
public double DividendYield{get;set;} // decimal
public double AnnualDividend{get;set;} // amount
public ParityElement ParityElement{get;set;}
public String ParityElementDescription{get{return null==ParityElement?"":ParityElement.ToString();}}
public double AllTimeGainLossPercent{get;set;}
public double PercentDistanceFromAllTimeGainLossPercent{get;set;}
public Price LatestPrice{get;set;}
public double PriceChange{get;set;}
public bool HasStopLimit{get;set;}
}
}

View File

@@ -0,0 +1,96 @@
using System;
using System.Text;
using MarketData.Utils;
using MarketData.MarketDataModel;
namespace MarketData.MarketDataModel
{
public class ModelTrade
{
public enum TradeType { Buy, Sell };
private DateTime tradeDate;
private String symbol;
private int shares;
private double price;
private TradeType tradeType;
private int daysHeld;
private double gainLoss;
private double exposure;
private double returnOnPosition;
private String comment;
public ModelTrade()
{
}
public String Symbol
{
get { return symbol; }
set { symbol = value; }
}
public DateTime TradeDate
{
get { return tradeDate; }
set { tradeDate = value; }
}
public int Shares
{
get { return shares; }
set { shares = value; }
}
public double Price
{
get { return price; }
set { price = value; }
}
public int DaysHeld
{
get { return daysHeld; }
set { daysHeld = value; }
}
public double GainLoss
{
get { return gainLoss; }
set { gainLoss = value; }
}
public double Return
{
get { return returnOnPosition; }
set { returnOnPosition = value; }
}
public double Exposure
{
get { return exposure; }
set { exposure = value; }
}
public String Comment
{
get { return comment; }
set { comment = value; }
}
public ModelTrade.TradeType Type
{
get { return tradeType; }
set { tradeType = value; }
}
public static String Header
{
get
{
return "Date,Buy/Sell,Symbol,Shares,Price,Gain/Loss,Days Held,Comment";
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(TradeDate)).Append(",");
sb.Append(tradeType.Equals(ModelTrade.TradeType.Sell) ? "Sell" : "Buy").Append(",");
sb.Append(Symbol).Append(",");
sb.Append(Shares).Append(",");
sb.Append("\"" + String.Format("{0:C}", price) + "\"").Append(",");
sb.Append("\"" + String.Format("{0:C}", gainLoss) + "\"").Append(",");
sb.Append(daysHeld).Append(",");
sb.Append("\"").Append(null!=comment?comment:"").Append("\"");
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MarketData.Utils;
namespace MarketData.MarketDataModel
{
public class ParityElement
{
public String Symbol { get; set; }
public DateTime PricingDate { get; set; }
public double ParityOffsetPrice { get; set; }
public double ParityOffsetPercent { get; set; } // This is not a percent it needs to be multiplied by 100 to be a percentage
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("Even @").Append(Utility.FormatCurrency(ParityOffsetPrice)).Append(" (").Append(ParityOffsetPercent > 0 ? "+" : "").Append(Utility.FormatPercent(ParityOffsetPercent)).Append(")");
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
//using MarketData.DataAccess;
namespace MarketData.MarketDataModel
{
public class Portfolio
{
private List<ModelTrade> trades = new List<ModelTrade>();
private bool openPosition = false;
private double availableCash;
private double initialCash;
public Portfolio(double initialCash)
{
this.initialCash = this.availableCash = initialCash;
}
public List<ModelTrade> Trades
{
get { return trades; }
set { trades = value; }
}
public double AvailableCash
{
get { return availableCash; }
set { availableCash = value; }
}
public double GetPortfolioReturn(Price priceOpenPosition)
{
return (GetPortfolioValue(priceOpenPosition)-initialCash)/initialCash;
}
// pass in latest price so we can price any open position
public double GetPortfolioValue(Price priceOpenPosition)
{
double cashValue = AvailableCash;
if (0 != trades.Count)
{
ModelTrade lastTrade = trades[trades.Count - 1];
if (lastTrade.Type.Equals(ModelTrade.TradeType.Buy)) cashValue += (lastTrade.Shares * priceOpenPosition.Close);
}
return cashValue;
}
public void Add(ModelTrade trade)
{
trades.Add(trade);
}
public ModelTrade GetLastTrade()
{
return trades[trades.Count - 1];
}
public bool HasOpenPosition
{
get { return openPosition; }
set { openPosition = value; }
}
public int GetTradeCount()
{
return trades.Count;
}
public double GetAverageGainLoss()
{
double totalGainLoss = 0;
for (int index = 0; index < trades.Count; index++)
{
totalGainLoss += trades[index].GainLoss;
}
return totalGainLoss / trades.Count;
}
public int GetAverageHoldingDays()
{
int totalHoldingDays = 0;
int numberOfSellTrades = 0;
for (int index = 0; index < trades.Count; index++)
{
ModelTrade trade = trades[index];
if (trade.Type == ModelTrade.TradeType.Sell)
{
totalHoldingDays += trades[index].DaysHeld;
numberOfSellTrades++;
}
}
return (numberOfSellTrades>0?totalHoldingDays / numberOfSellTrades:0);
}
public int GetMinHoldingDays()
{
int minHoldingDays = Int16.MaxValue;
for (int index = 0; index < trades.Count; index++)
{
ModelTrade trade = trades[index];
int holdingDays = trade.DaysHeld;
if (trade.Type == ModelTrade.TradeType.Sell && holdingDays < minHoldingDays) minHoldingDays = holdingDays;
}
return minHoldingDays;
}
public int GetMaxHoldingDays()
{
int maxHoldingDays =0;
for (int index = 0; index < trades.Count; index++)
{
ModelTrade trade = trades[index];
int holdingDays = trade.DaysHeld;
if (trade.Type==ModelTrade.TradeType.Sell && holdingDays > maxHoldingDays) maxHoldingDays = holdingDays;
}
return maxHoldingDays;
}
}
}

View File

@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MarketData.Utils;
namespace MarketData.MarketDataModel
{
public class PortfolioTrade
{
private int tradeId=-1;
private String symbol;
private DateTime tradeDate;
private double shares;
private double price;
private double commission;
private String buySell;
private String account;
private String status;
private double sellPrice=double.NaN;
private DateTime sellDate=Utility.Epoch;
public int TradeId
{
get {return tradeId ;}
set { tradeId = value; ;}
}
public String Symbol
{
get { return symbol; }
set { symbol = value; }
}
public DateTime TradeDate
{
get { return tradeDate; }
set { tradeDate = value; }
}
public double Shares
{
get { return shares; }
set { shares = value; }
}
public double Exposure()
{
return Price*Shares;
}
public String BuySell
{
get { return buySell; }
set { buySell = value; }
}
public String Status
{
get { return status; }
set { status = value; }
}
public bool IsOpen
{
get { return status.ToUpper().Equals("OPEN"); }
}
public bool IsClosed
{
get { return !IsOpen; }
}
public String Account
{
get { return account; }
set{account=value;}
}
public DateTime SellDate
{
get { return sellDate; }
set { sellDate = value; }
}
public double SellPrice
{
get { return sellPrice;}
set { sellPrice = value;}
}
public double Price
{
get { return price; }
set { price = value; }
}
public double Commission
{
get { return commission; }
set { commission = value; }
}
}
}

View File

@@ -0,0 +1,179 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MarketData.Utils;
namespace MarketData.MarketDataModel
{
public class Position
{
public String Symbol { get; set; }
public double Shares{get;set;}
public double Exposure { get; set; }
public double MarketValue { get; set; }
}
public class PortfolioTrades : List<PortfolioTrade>
{
public PortfolioTrades()
{
}
public PortfolioTrades(List<PortfolioTrade> trades)
{
if(null==trades)return;
for (int index = 0; index < trades.Count; index++) Add(trades[index]);
}
public List<String> Symbols
{
get
{
Dictionary<String, String> uniqueSymbols = new Dictionary<String, String>();
List<String> symbols = new List<String>();
foreach (PortfolioTrade portfolioTrade in this)
{
if (!uniqueSymbols.ContainsKey(portfolioTrade.Symbol)) uniqueSymbols.Add(portfolioTrade.Symbol, portfolioTrade.Symbol);
}
symbols = new List<String>(uniqueSymbols.Values);
symbols.Sort();
return symbols;
}
}
public List<Position> GetPositions(DateTime asOf)
{
List<Position> positions = new List<Position>();
List<String> symbols = Symbols;
foreach (String symbol in symbols) positions.Add(GetPosition(symbol, asOf));
return positions;
}
public Position GetPosition(String symbol,DateTime asof)
{
List<PortfolioTrade> portfolioTrades = new List<PortfolioTrade>();
for (int index = 0; index < Count; index++)
{
PortfolioTrade portfolioTrade = this[index];
if (!portfolioTrade.Symbol.Equals(symbol)) continue;
if (portfolioTrade.IsOpen && portfolioTrade.TradeDate<=asof) { portfolioTrades.Add(portfolioTrade); continue; }
if (portfolioTrade.IsClosed && portfolioTrade.SellDate > asof) { portfolioTrades.Add(portfolioTrade); continue; }
}
if (0 == portfolioTrades.Count) return null;
Position position = new Position();
position.Symbol = symbol;
position.Shares = portfolioTrades.Sum(x => x.Shares);
position.Exposure = portfolioTrades.Sum(x=>x.Shares*x.Price);
return position;
}
public double Exposure(){return this.Sum(x=>x.Exposure());}
public List<String> Accounts
{
get
{
Dictionary<String, String> uniqueAccounts = new Dictionary<String, String>();
List<String> accounts = new List<String>();
foreach (PortfolioTrade portfolioTrade in this)
{
if (!uniqueAccounts.ContainsKey(portfolioTrade.Account)) uniqueAccounts.Add(portfolioTrade.Account, portfolioTrade.Account);
}
accounts = new List<String>(uniqueAccounts.Values);
accounts.Sort();
return accounts;
}
}
public DateTime GetMinTradeDate()
{
DateTime minDate = Utility.Epoch;
minDate = (from portfolioTrade in this select portfolioTrade.TradeDate).Min();
return minDate;
}
public DateTime GetMinTradeDate(String symbol)
{
DateTime minDate=Utility.Epoch;
symbol=symbol.ToUpper();
minDate = (from portfolioTrade in this where portfolioTrade.Symbol.Equals(symbol) select portfolioTrade.TradeDate).Min();
return minDate;
}
// We just want the trades (open or closed) on or before the specified date. This will be used to run a cumulative gain/loss and return
public PortfolioTrades GetTradesOnOrBefore(DateTime date)
{
PortfolioTrades tradesOnOrBefore = new PortfolioTrades();
foreach (PortfolioTrade portfolioTrade in this)
{
if (date >= portfolioTrade.TradeDate) tradesOnOrBefore.Add(portfolioTrade);
}
return tradesOnOrBefore;
}
// This will remove trades that are status='CLOSED' and SELL_DATE=closingDate
// The user of this fucntion would be making the inference that a trade that closed on closingDate should not be seen as part of the holdings.
// For example. The assumption would be that trades that closed on closingDate would not be a part of the portfolio on closingDate
public PortfolioTrades RemoveClosedTradesWhereClosedOn(DateTime closingDate)
{
PortfolioTrades portfolioTrades;
List<PortfolioTrade> removeTrades = (from PortfolioTrade portfolioTrade in this where portfolioTrade.Status.Equals("CLOSED") && portfolioTrade.SellDate.Date.Equals(closingDate.Date) select portfolioTrade).ToList();
if (null != removeTrades && 0 != removeTrades.Count) portfolioTrades = new PortfolioTrades(this.Except(removeTrades).ToList());
else portfolioTrades = this;
return portfolioTrades;
}
public PortfolioTrades GetOpenTradesOn(DateTime date)
{
PortfolioTrades openTrades = new PortfolioTrades();
foreach (PortfolioTrade portfolioTrade in this)
{
if (Utility.Epoch.Equals(portfolioTrade.SellDate)) // No sell date so trade is open
{
if (date >= portfolioTrade.TradeDate) openTrades.Add(portfolioTrade);
}
else // sell date is not epoch so see if date is in between tradedate and selldate
{
if (date >= portfolioTrade.TradeDate && date < portfolioTrade.SellDate) openTrades.Add(portfolioTrade); // assume that if the sell date is equal to date then the position is closed
}
}
return openTrades;
}
public bool HasOpenPositions(String symbol)
{
int openTrades=(from PortfolioTrade portfolioTrade in this where portfolioTrade.Symbol.Equals(symbol) && portfolioTrade.IsOpen select portfolioTrade).Count();
return openTrades>0?true:false;
}
public bool HasOpenPositionsOn(String symbol,DateTime dateTime)
{
PortfolioTrades portfolioTrades=GetOpenTradesOn(dateTime);
int numTrades=(from PortfolioTrade portfolioTrade in portfolioTrades where portfolioTrade.Symbol.Equals(symbol) select portfolioTrade).Count();
return numTrades>0?true:false;
}
// This method relies on the fact that BreakoutTrades method in PortfolioDA.GetTradesSymbol() creates pairs of BUY and SELL legs with paired legs sharing the same TradeId.
// The open trades will show up with count==1 when we group them by TradeId
public PortfolioTrades GetOpenTrades()
{
if(0==Count)return new PortfolioTrades();
PortfolioTrades openTrades=new PortfolioTrades((from PortfolioTrade trade in this select trade).GroupBy(x=>x.TradeId).Where(grouping=>grouping.Count()==1).Select(grouping=>grouping.FirstOrDefault()).ToList());
return openTrades;
}
public PortfolioTrades FilterAccount(String account)
{
PortfolioTrades portfolioTrades = new PortfolioTrades();
foreach (PortfolioTrade portfolioTrade in this)
{
if (portfolioTrade.Account.Equals(account)) portfolioTrades.Add(portfolioTrade);
}
return portfolioTrades;
}
public PortfolioTrades FilterAccount(List<String> accounts)
{
PortfolioTrades portfolioTrades = new PortfolioTrades();
foreach (PortfolioTrade portfolioTrade in this)
{
if(accounts.Any(x=>x.Equals(portfolioTrade.Account)))portfolioTrades.Add(portfolioTrade);
}
return portfolioTrades;
}
public PortfolioTrades FilterSymbol(String symbol)
{
PortfolioTrades portfolioTrades = new PortfolioTrades();
foreach (PortfolioTrade portfolioTrade in this)
{
if (portfolioTrade.Symbol.Equals(symbol)) portfolioTrades.Add(portfolioTrade);
}
return portfolioTrades;
}
}
}

View File

@@ -0,0 +1,23 @@
using System;
namespace MarketData.MarketDataModel
{
public class PositionWithDescription : MarketDataModel.Position
{
public PositionWithDescription()
{
}
public PositionWithDescription(MarketDataModel.Position position, String companyName, String description)
{
if (null == position || null == description) return;
this.Symbol = position.Symbol;
this.Shares = position.Shares;
this.MarketValue = position.MarketValue;
this.Exposure = position.Exposure;
this.Description = description;
this.CompanyName = companyName;
}
public String Description { get; set; }
public String CompanyName { get; set; }
}
}

View File

@@ -0,0 +1,19 @@
using System;
using System.Collections.Generic;
namespace MarketData.MarketDataModel
{
public class PremarketElement
{
public String Market { get; set; }
public double ChangePercent { get; set; }
public double ChangeValue { get; set; }
public DateTime Timestamp { get; set; }
}
public class PremarketElements:List<PremarketElement>
{
public PremarketElements()
{
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
namespace MarketData.MarketDataModel
{
public class PriceIndex
{
public String Code{get;set;}
public String Name{get;set;}
public double Value{get;set;}
public DateTime AsOf{get;set;}
public String Source{get;set;}
}
public class PriceIndices : List<PriceIndex>
{
public PriceIndices()
{
}
public PriceIndices(List<PriceIndex> priceIndices)
{
foreach(PriceIndex priceIndex in priceIndices)
{
Add(priceIndex);
}
}
}
}

View File

@@ -0,0 +1,448 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using MarketData.Utils;
using MarketData.Numerical;
//using MarketData.DataAccess;
namespace MarketData.MarketDataModel
{
public class PricesByDate : Dictionary<DateTime, Price>
{
private DateTime maxDate=Utility.Epoch;
private DateTime minDate=Utility.Epoch;
public PricesByDate()
{
}
public new void Add(DateTime key,Price price)
{
base.Add(key,price);
if(key>maxDate)maxDate=key;
else if(Utility.IsEpoch(minDate))minDate=key;
else if(key<minDate)minDate=key;
}
public DateTime MaxDate
{
get{return maxDate;}
}
public DateTime MinDate
{
get{return minDate;}
}
}
public class PriceComparerDesc : IComparer<Price>
{
public int Compare(Price p1, Price p2)
{
if (p1.Date < p2.Date) return -1;
else if (p1.Date > p2.Date) return 1;
return 0;
}
}
// Throughout the application it is assumed that these collections, when populated, be be in descending date order.
public class Prices : List<Price>
{
public Prices()
{
}
public Prices(Price[] prices)
{
foreach (Price price in prices) Add(price);
}
public Prices(List<Price> prices)
{
foreach(Price price in prices)Add(price);
}
public Prices(String strCSV,String symbol)
{
String[] csvLines = strCSV.Split('\n');
Clear();
for (int index = 1; index < csvLines.Length; index++)
{
if (csvLines[index].Length < 1) continue;
String[] lineItems = csvLines[index].Split(',');
Price price = new Price();
String[] dateParts = lineItems[0].Split('-');
try { price.Date = new DateTime(int.Parse(dateParts[0]), int.Parse(dateParts[1]), int.Parse(dateParts[2])); }
catch (Exception /*exception*/)
{
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("'{0}' does not contain a date", lineItems[0]));
continue;
}
price.Symbol = symbol;
price.Open = Double.Parse(lineItems[1]);
price.High = Double.Parse(lineItems[2]);
price.Low = Double.Parse(lineItems[3]);
price.Close = Double.Parse(lineItems[4]);
price.Volume = Int64.Parse(lineItems[5]);
if(lineItems.Length>6)price.AdjClose=Double.Parse(lineItems[6]);
Add(price);
}
}
// This Beta differs wildly with Yahoo Finance. Yahoo finance uses 36 buckets of monthly returns which was simulated when building this Investopedia-based routine.
// I have yet to discover the cause of the difference but I leave this routine in place as a matter of further study and to make comparisons.
// I tested the bucket methodology against just using a stream of returns and they produce the same result so this routine simply uses a stream of returns.
// At any rate, the beta produced by this method does not match to Yahoo finance.
//public double Beta(Prices bmkPrices)
//{
// double beta=double.NaN;
// if(Count!=bmkPrices.Count)return beta;
// float[] cumReturnsPricesArray=GetReturns();
// float[] cumReturnsPricesBenchmark=bmkPrices.GetReturns();
// beta=Numerics.Beta(ref cumReturnsPricesArray,ref cumReturnsPricesBenchmark);
// return beta*10;
//}
// Assumes that the prices are stored lowest date first
public double MaxDrawdown()
{
return Numerics.MaxDrawdown(GetPrices());
}
public double MaxUpside()
{
return Numerics.MaxUpside(GetPrices());
}
public PricesByDate GetPricesByDate()
{
PricesByDate pricesByDate = new PricesByDate();
for (int index = 0; index < Count; index++) pricesByDate.Add(this[index].Date, this[index]);
return pricesByDate;
}
public Prices Top(int count)
{
Prices prices = new Prices();
for (int index = 0; index < count && index<Count; index++)
{
prices.Add(this[index]);
}
return prices;
}
public Prices Bottom(int count)
{
Prices prices = new Prices();
for (int index = Count-1; index>=0 && prices.Count<count; index--)
{
prices.Add(this[index]);
}
return prices;
}
public double Volatility()
{
float[] pricesAr = GetPrices();
return Numerics.StdDev(ref pricesAr);
}
public double Min()
{
float[] pricesAr = GetPrices();
return Numerics.Min(ref pricesAr);
}
public double MinLow()
{
float[] pricesAr = GetPricesLow();
return Numerics.Min(ref pricesAr);
}
public double Max()
{
float[] pricesAr = GetPrices();
return Numerics.Max(ref pricesAr);
}
public double Mean()
{
float[] pricesAr = GetPrices();
return Numerics.Mean(ref pricesAr);
}
public double[] GetLeastSquaresFit()
{
double[] pricesArray = new double[Count];
for (int index = 0; index < Count; index++)
{
pricesArray[index] = (float)this[index].Close;
}
LeastSquaresResult leastSquaresResult=Numerics.LeastSquares(pricesArray);
return leastSquaresResult.LeastSquares;
}
public double[] GetVolume()
{
double[] volumeArray = new double[Count];
for (int index = 0; index < Count; index++)
{
volumeArray[index] = (double)this[index].Volume;
}
return volumeArray;
}
public float[] GetPrices()
{
float[] pricesArray = new float[Count];
for (int index = 0; index < Count; index++)
{
pricesArray[index] = (float)this[index].Close;
}
return pricesArray;
}
public float[] GetPricesLow()
{
float[] pricesArray = new float[Count];
for (int index = 0; index < Count; index++)
{
pricesArray[index] = (float)this[index].Low;
}
return pricesArray;
}
public float[] GetPricesHigh()
{
float[] pricesArray = new float[Count];
for (int index = 0; index < Count; index++)
{
pricesArray[index] = (float)this[index].High;
}
return pricesArray;
}
public float[] GetPrices(int startIndex, int count)
{
if (startIndex + count > Count) return null;
float[] pricesArray=new float[count];
for (int index = startIndex,arrayIndex=0; index < startIndex + count; index++,arrayIndex++)
{
pricesArray[arrayIndex] = (float)this[index].Close;
}
return pricesArray;
}
public float[] GetPricesHigh(int startIndex, int count)
{
if (startIndex + count > Count) return null;
float[] pricesArray = new float[count];
for (int index = startIndex, arrayIndex = 0; index < startIndex + count; index++, arrayIndex++)
{
pricesArray[arrayIndex] = (float)this[index].High;
}
return pricesArray;
}
public float[] GetPricesLow(int startIndex, int count)
{
if (startIndex + count > Count) return null;
float[] pricesArray = new float[count];
for (int index = startIndex, arrayIndex = 0; index < startIndex + count; index++, arrayIndex++)
{
pricesArray[arrayIndex] = (float)this[index].Low;
}
return pricesArray;
}
public float[] GetReturns()
{
if(Count==0||1==Count)return null;
float[] returns = new float[Count - 1];
for (int index = 0; index < Count - 1; index++)
{
Price currentPrice = this[index];
Price prevPrice = this[index + 1];
if (0.00 == prevPrice.Close) returns[index] = 0.00F;
else returns[index] = (float)((currentPrice.Close - prevPrice.Close) / Math.Abs(prevPrice.Close));
}
return returns;
}
public double GetReturn1D()
{
if(Count<2)return double.NaN;
Prices pricesForReturn1D=new Prices(this.Take(2).ToList());
return pricesForReturn1D.GetCumulativeReturn();
}
public float[] GetReturns(int dayCount)
{
if(Count-dayCount<=0)return new float[0];
float[] returns = new float[Count - dayCount];
for (int index = 0; index < Count - dayCount; index++)
{
Price currentPrice = this[index];
Price prevPrice = this[index + dayCount];
if (0.00 == prevPrice.Close) returns[index] = 0.00F;
else returns[index] = (float)((currentPrice.Close - prevPrice.Close) / Math.Abs(prevPrice.Close));
}
return returns;
}
public double GetCumulativeReturn()
{
float[] returns=GetReturns();
if(null==returns)return double.NaN;
double itemReturn=0.00;
for(int index=0;index<returns.Length;index++)itemReturn+=(double)returns[index];
return itemReturn;
}
public double GetCumulativeReturn(int dayCount)
{
float[] returns=GetReturns(dayCount);
double itemReturn=0.00;
for(int index=0;index<returns.Length;index++)itemReturn+=(double)returns[index];
return itemReturn;
}
public double[] GetReturnsAsDoubleArray()
{
double[] returns = new double[Count - 1];
for (int index = 0; index < Count - 1; index++)
{
Price currentPrice = this[index];
Price prevPrice = this[index + 1];
if (0.00 == prevPrice.Close) returns[index] = 0.00;
else returns[index] = (double)((currentPrice.Close - prevPrice.Close) / Math.Abs(prevPrice.Close));
}
return returns;
}
public double[] GetReturnsAsDoubleArray(int dayCount)
{
if (0 == Count) return null;
double[] returns = new double[Count - dayCount];
for (int index = 0; index < Count - dayCount; index++)
{
Price currentPrice = this[index];
Price prevPrice = this[index + dayCount];
if (0.00 == prevPrice.Close) returns[index] = 0.00F;
else returns[index] = ((currentPrice.Close - prevPrice.Close) / Math.Abs(prevPrice.Close));
}
return returns;
}
// *********************************
//public static Prices GetMonthlyPrices(String symbol, DateTime asof, int months = 36)
//{
// DateGenerator dateGenerator = new DateGenerator();
// Prices prices = new Prices();
// DateTime startDate = dateGenerator.GetCurrMonthStart(asof);
// DateTime minPricingDate = PricingDA.GetEarliestDate(symbol);
// Dictionary<DateTime, Price> symbolPricesByDate = new Dictionary<DateTime, Price>();
// List<DateTime> historicalDates = new List<DateTime>();
// while (historicalDates.Count < (months + 1))
// {
// historicalDates.Add(startDate);
// startDate = dateGenerator.GetPrevMonthStart(startDate);
// }
// DateTime requestStartDate = dateGenerator.DaysAddActual(asof, 5); // advance 5 days to provide an error margin for holidays
// Prices symbolPrices = PricingDA.GetPrices(symbol, requestStartDate, historicalDates[historicalDates.Count - 1]);
// foreach (Price price in symbolPrices) symbolPricesByDate.Add(price.Date, price);
// startDate = dateGenerator.GetCurrMonthStart(asof);
// while (prices.Count < (months + 1))
// {
// Price price = GetPrice(symbol, startDate, symbolPricesByDate);
// if (null == price) return null;
// prices.Add(price);
// startDate = dateGenerator.GetPrevMonthStart(startDate);
// if (startDate < minPricingDate) break;
// }
// return prices;
//}
private static Price GetPrice(String symbol,DateTime requestedDate, Dictionary<DateTime, Price> symbolPricesByDate)
{
int maxAdvanceDays = 5;
Price symbolPrice = null;
for (int advanceDays = 0; advanceDays < maxAdvanceDays; advanceDays++)
{
if (!symbolPricesByDate.ContainsKey(requestedDate)) { requestedDate = requestedDate.AddDays(1); continue; }
symbolPrice = symbolPricesByDate[requestedDate];
}
return symbolPrice;
}
// **********************************
}
public class Price
{
private String symbol;
private DateTime date;
private double open;
private double high;
private double low;
private double close;
private long volume;
private double adjClose;
public Price()
{
}
public Price Clone()
{
Price clonePrice=new Price();
clonePrice.Symbol=Symbol;
clonePrice.Date=Date;
clonePrice.Open=Open;
clonePrice.High=High;
clonePrice.Low=Low;
clonePrice.Close=Close;
clonePrice.Volume=Volume;
clonePrice.AdjClose=AdjClose;
return clonePrice;
}
public String Symbol
{
get { return symbol; }
set { symbol = value; }
}
public DateTime Date
{
get { return date; }
set { date = value; }
}
public double Open
{
get { return open; }
set { open = value; }
}
public double High
{
get { return high; }
set { high = value; }
}
public double Low
{
get { return low; }
set { low = value; }
}
public double Close
{
get { return close; }
set { close = value; }
}
public long Volume
{
get { return volume; }
set { volume = value; }
}
public double AdjClose
{
get { return adjClose; }
set { adjClose = value; }
}
public bool IsValid
{
get
{
if(null==symbol)return false;
if(Utility.IsEpoch(date))return false;
if(double.IsNaN(open))return false;
if(double.IsNaN(high))return false;
if(double.IsNaN(low))return false;
if(double.IsNaN(close))return false;
if(double.IsNaN(adjClose))return false;
return true;
}
}
public static String Header
{
get { return "Date,Symbol,Open,High,Low,Close,Volume,Adj Close"; } // ,M12,M26,MACD,Signal,Histogram
}
public override String ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(symbol).Append(",");
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(Date)).Append(",");
sb.Append(String.Format("{0:0.00}", Open)).Append(",");
sb.Append(String.Format("{0:0.00}", High)).Append(",");
sb.Append(String.Format("{0:0.00}", Low)).Append(",");
sb.Append(String.Format("{0:0.00}", Close)).Append(",");
sb.Append(Volume).Append(",");
sb.Append(String.Format("{0:0.00}", AdjClose));
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
namespace MarketData.MarketDataModel
{
public class StopLimit
{
public String Symbol{get;set;}
public double StopPrice{get;set;}
public double Shares{get;set;}
public String StopType{get;set;}
public int Active{get;set;}
}
}

View File

@@ -0,0 +1,144 @@
using System;
using System.Linq;
using System.Collections.Generic;
using MarketData.Numerical;
namespace MarketData.MarketDataModel
{
public class TimeSeriesCollection : List<TimeSeriesElement>
{
public TimeSeriesCollection()
{
}
public TimeSeriesCollection(List<TimeSeriesElement> elements)
{
if (null == elements) return;
foreach (TimeSeriesElement element in elements) Add(element);
}
// Returns the intersection of both sets on the common dates
public static AlignDatesResult AlignDates(TimeSeriesCollection tsA,TimeSeriesCollection tsB)
{
List<DateTime> tsADates=(from ts in tsA select ts.AsOf).ToList();
List<DateTime> tsBDates=(from ts in tsB select ts.AsOf).ToList();
List<DateTime> tsIntersect=tsADates.Intersect(tsBDates).Distinct().ToList();
tsA=new TimeSeriesCollection((from ts in tsA where tsIntersect.Any(x=>x.Equals(ts.AsOf)) select ts).ToList());
tsB=new TimeSeriesCollection((from ts in tsB where tsIntersect.Any(x=>x.Equals(ts.AsOf)) select ts).ToList());
return new AlignDatesResult(tsA,tsB);
}
public float[] ToFloat()
{
float[] values = new float[Count];
for (int index = 0; index < Count; index++) values[index] = (float)this[index].Value;
return values;
}
public bool ContainsNegativeValues()
{
int count= (from TimeSeriesElement element in this where element.Value < 0 select element).Count();
return count > 0 ? true : false;
}
public TimeSeriesCollection RemoveNegativeValues()
{
return new TimeSeriesCollection((from TimeSeriesElement element in this where element.Value >= 0 select element).ToList());
}
// Removes the outliers from the collection. If the resulting collection contains zero elements then returns the original collection.
//public TimeSeriesCollection RemoveOutliers(int standardDeviations=4)
//{
// double[] values = (from TimeSeriesElement element in this select element.Value).ToArray();
// double valuesStd=Numerics.Volatility(ref values)*standardDeviations;
// TimeSeriesCollection timeSeriesCollection=new TimeSeriesCollection((from TimeSeriesElement element in this where element.Value <=valuesStd select element).ToList());
// if(0==timeSeriesCollection.Count)return this;
// else return timeSeriesCollection;
//}
}
public class TimeSeriesElement
{
public enum ElementType { INVALID, OTHER,BVPS, EPS, OperatingCashflow,FreeCashflow,Revenue,QuarterlyRevenue,Inventory,QuarterlyInventory,ROIC,OperatingIncome,WorkingCapital,ROA,NetIncomeAvailableToCommonShareholders,TaxRate,InterestExpense,COGS};
private String symbol;
private DateTime asof;
private ElementType elementType;
private double value;
private String otherType;
public TimeSeriesElement()
{
}
public String Symbol
{
get { return symbol; }
set { symbol = value; }
}
public DateTime AsOf
{
get { return asof; }
set { asof = value; }
}
public double Value
{
get { return value; }
set { this.value = value; }
}
public String OtherType
{
get{return otherType;}
set{otherType=value;}
}
public TimeSeriesElement.ElementType Type
{
get { return elementType; }
set { elementType = value; }
}
public static String StringForType(TimeSeriesElement.ElementType type)
{
switch (type)
{
case ElementType.INVALID :
return "???";
case ElementType.BVPS:
return "bvps";
case ElementType.EPS:
return "eps";
case ElementType.OperatingCashflow :
return "operating_cashflow";
case ElementType.FreeCashflow:
return "free_cashflow";
case ElementType.Revenue:
return "revenue";
case ElementType.QuarterlyRevenue:
return "quarterly_revenue";
case ElementType.OperatingIncome:
return "operating_income";
case ElementType.ROIC:
return "roic";
case ElementType.WorkingCapital:
return "working_capital";
case ElementType.ROA:
return "roa";
case ElementType.TaxRate :
return "tax_rate";
case ElementType.InterestExpense:
return "interest_expense";
case ElementType.NetIncomeAvailableToCommonShareholders:
return "net_income_available_to_common_shareholders";
case ElementType.COGS:
return "cogs";
default:
return "???";
}
}
}
public class AlignDatesResult
{
public AlignDatesResult()
{
}
public AlignDatesResult(TimeSeriesCollection collectionA,TimeSeriesCollection collectionB)
{
CollectionA=collectionA;
CollectionB=collectionB;
}
public TimeSeriesCollection CollectionA{get;set;}
public TimeSeriesCollection CollectionB{get;set;}
}
}