Initial Commit
This commit is contained in:
76
MarketData/MarketDataLib/MarketDataModel/AnalystPriceTarget.cs
Executable file
76
MarketData/MarketDataLib/MarketDataModel/AnalystPriceTarget.cs
Executable file
@@ -0,0 +1,76 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class AnalystPriceTarget
|
||||
{
|
||||
private DateTime date;
|
||||
private String symbol;
|
||||
private double meanTargetPrice;
|
||||
private double medianTargetPrice;
|
||||
private double highTargetPrice;
|
||||
private double lowTargetPrice;
|
||||
|
||||
public AnalystPriceTarget()
|
||||
{
|
||||
}
|
||||
public DateTime Date
|
||||
{
|
||||
get { return date; }
|
||||
set { date = value; }
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public double MeanTargetPrice
|
||||
{
|
||||
get { return meanTargetPrice; }
|
||||
set { meanTargetPrice = value; }
|
||||
}
|
||||
public double MedianTargetPrice
|
||||
{
|
||||
get { return medianTargetPrice; }
|
||||
set { medianTargetPrice = value; }
|
||||
}
|
||||
public double HighTargetPrice
|
||||
{
|
||||
get { return highTargetPrice; }
|
||||
set { highTargetPrice = value; }
|
||||
}
|
||||
public double LowTargetPrice
|
||||
{
|
||||
get { return lowTargetPrice; }
|
||||
set { lowTargetPrice = value; }
|
||||
}
|
||||
public static String Header
|
||||
{
|
||||
get
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("Date").Append(",");
|
||||
sb.Append("Symbol").Append(",");
|
||||
sb.Append("MeanTargetPrice").Append(",");
|
||||
sb.Append("MedianTargetPrice").Append(",");
|
||||
sb.Append("HighTargetPrice").Append(",");
|
||||
sb.Append("LowTargetPrice");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(Symbol).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(Date)).Append(",");
|
||||
sb.Append(symbol).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", MeanTargetPrice)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", MedianTargetPrice)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", HighTargetPrice)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", LowTargetPrice));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
108
MarketData/MarketDataLib/MarketDataModel/AnalystRatings.cs
Executable file
108
MarketData/MarketDataLib/MarketDataModel/AnalystRatings.cs
Executable file
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class AnalystRatings : List<AnalystRating>
|
||||
{
|
||||
public AnalystRatings()
|
||||
{
|
||||
}
|
||||
public AnalystRatings(List<AnalystRating> analystRatings)
|
||||
{
|
||||
foreach(AnalystRating analystRating in analystRatings)Add(analystRating);
|
||||
}
|
||||
public List<String> Symbols
|
||||
{
|
||||
get { return (from analystRating in this select analystRating.Symbol).ToList(); }
|
||||
}
|
||||
public void Remove(List<String> symbols)
|
||||
{
|
||||
for (int index = 0; index < symbols.Count; index++)
|
||||
{
|
||||
this.RemoveAll(x => x.Symbol.Equals(symbols[index]));
|
||||
}
|
||||
}
|
||||
public void CalculateUpdatePercentiles()
|
||||
{
|
||||
double totalCount=1;
|
||||
double upgradeCount=0;
|
||||
for(int index=this.Count-1;index>=0;index--,totalCount++)
|
||||
{
|
||||
AnalystRating analystRating=this[index];
|
||||
if(analystRating.Type.Equals("Upgrades")&&!analystRating.RatingsChange.Contains("Sell"))upgradeCount++;
|
||||
analystRating.UpgradePercentile=(upgradeCount/totalCount)*100.00;
|
||||
}
|
||||
}
|
||||
}
|
||||
public class AnalystRating
|
||||
{
|
||||
private DateTime date;
|
||||
private String symbol;
|
||||
private String brokerageFirm;
|
||||
private String type;
|
||||
private String ratingsChange;
|
||||
private double priceTarget;
|
||||
private String companyName;
|
||||
private double upgradePercentile;
|
||||
|
||||
public AnalystRating()
|
||||
{
|
||||
}
|
||||
public DateTime Date
|
||||
{
|
||||
get { return date; }
|
||||
set { date = value; }
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value.Trim(); }
|
||||
}
|
||||
public String CompanyName
|
||||
{
|
||||
get { return companyName; }
|
||||
set { companyName = value; }
|
||||
}
|
||||
public String BrokerageFirm
|
||||
{
|
||||
get { return brokerageFirm; }
|
||||
set { brokerageFirm=value; }
|
||||
}
|
||||
public String Type
|
||||
{
|
||||
get { return type; }
|
||||
set { type = value; }
|
||||
}
|
||||
public String RatingsChange
|
||||
{
|
||||
get { return ratingsChange; }
|
||||
set { ratingsChange = value; }
|
||||
}
|
||||
public double PriceTarget
|
||||
{
|
||||
get { return priceTarget; }
|
||||
set { priceTarget = value; }
|
||||
}
|
||||
public double UpgradePercentile
|
||||
{
|
||||
get{return upgradePercentile;}
|
||||
set{upgradePercentile=value;}
|
||||
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(Symbol).Append(",");
|
||||
sb.Append(CompanyName).Append(",");
|
||||
sb.Append(BrokerageFirm).Append(",");
|
||||
sb.Append(Type).Append(",");
|
||||
sb.Append(RatingsChange).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(PriceTarget));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
209
MarketData/MarketDataLib/MarketDataModel/BalanceSheet.cs
Executable file
209
MarketData/MarketDataLib/MarketDataModel/BalanceSheet.cs
Executable file
@@ -0,0 +1,209 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class BalanceSheet
|
||||
{
|
||||
public enum PeriodType { Annual = 0, Quarterly = 1 }
|
||||
private String symbol;
|
||||
private DateTime asof;
|
||||
private double longTermDebt;
|
||||
private double otherLiabilities;
|
||||
private double deferredLongTermLiabilities;
|
||||
private double minorityInterest;
|
||||
private double negativeGoodwill;
|
||||
private double goodwill;
|
||||
private double totalStockHolderEquity;
|
||||
private double inventory;
|
||||
private double propertyPlantAndEquipment;
|
||||
private double intangibleAssets;
|
||||
private double accumulatedAmortization;
|
||||
private double totalAssets;
|
||||
private double totalCurrentAssets;
|
||||
private double totalLiabilities;
|
||||
private double totalCurrentLiabilities;
|
||||
private double cashAndCashEquivalents;
|
||||
private PeriodType period;
|
||||
private DateTime modified;
|
||||
|
||||
public BalanceSheet()
|
||||
{
|
||||
}
|
||||
// It is appropriate to use the AsOf date in the comparison of the financial statements because the AsOf date is the statement date.
|
||||
public void MergeFrom(BalanceSheet previousBalanceSheet)
|
||||
{
|
||||
if(null==previousBalanceSheet)return;
|
||||
if(!Symbol.Equals(previousBalanceSheet.Symbol))return;
|
||||
if(!AsOf.Date.Equals(previousBalanceSheet.AsOf.Date))return;
|
||||
if(!Period.Equals(previousBalanceSheet.Period))return;
|
||||
if(Utility.IsZeroOrNaN(LongTermDebt))LongTermDebt=previousBalanceSheet.LongTermDebt;
|
||||
if(Utility.IsZeroOrNaN(OtherLiabilities))OtherLiabilities=previousBalanceSheet.OtherLiabilities;
|
||||
if(Utility.IsZeroOrNaN(DeferredLongTermLiabilities))DeferredLongTermLiabilities=previousBalanceSheet.DeferredLongTermLiabilities;
|
||||
if(Utility.IsZeroOrNaN(MinorityInterest))MinorityInterest=previousBalanceSheet.MinorityInterest;
|
||||
if(Utility.IsZeroOrNaN(NegativeGoodwill))NegativeGoodwill=previousBalanceSheet.NegativeGoodwill;
|
||||
if(Utility.IsZeroOrNaN(Goodwill))Goodwill=previousBalanceSheet.Goodwill;
|
||||
if(Utility.IsZeroOrNaN(TotalStockHolderEquity))TotalStockHolderEquity=previousBalanceSheet.TotalStockHolderEquity;
|
||||
if(Utility.IsZeroOrNaN(Inventory))Inventory=previousBalanceSheet.Inventory;
|
||||
if(Utility.IsZeroOrNaN(PropertyPlantAndEquipment))PropertyPlantAndEquipment=previousBalanceSheet.PropertyPlantAndEquipment;
|
||||
if(Utility.IsZeroOrNaN(IntangibleAssets))IntangibleAssets=previousBalanceSheet.IntangibleAssets;
|
||||
if(Utility.IsZeroOrNaN(AccumulatedAmortization))AccumulatedAmortization=previousBalanceSheet.AccumulatedAmortization;
|
||||
if(Utility.IsZeroOrNaN(TotalAssets))TotalAssets=previousBalanceSheet.TotalAssets;
|
||||
if(Utility.IsZeroOrNaN(TotalCurrentAssets))TotalCurrentAssets=previousBalanceSheet.TotalCurrentAssets;
|
||||
if(Utility.IsZeroOrNaN(TotalLiabilities))TotalLiabilities=previousBalanceSheet.TotalLiabilities;
|
||||
if(Utility.IsZeroOrNaN(TotalCurrentLiabilities))TotalCurrentLiabilities=previousBalanceSheet.TotalCurrentLiabilities;
|
||||
if(Utility.IsZeroOrNaN(CashAndCashEquivalents))CashAndCashEquivalents=previousBalanceSheet.CashAndCashEquivalents;
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public DateTime AsOf
|
||||
{
|
||||
get { return asof; }
|
||||
set { asof = value; }
|
||||
}
|
||||
public double CashAndCashEquivalents
|
||||
{
|
||||
get { return cashAndCashEquivalents; }
|
||||
set { cashAndCashEquivalents = value; }
|
||||
}
|
||||
public double LongTermDebt
|
||||
{
|
||||
get { return longTermDebt; }
|
||||
set { longTermDebt = value; }
|
||||
}
|
||||
public double OtherLiabilities
|
||||
{
|
||||
get { return otherLiabilities; }
|
||||
set { otherLiabilities = value; }
|
||||
}
|
||||
public double DeferredLongTermLiabilities
|
||||
{
|
||||
get { return deferredLongTermLiabilities; }
|
||||
set { deferredLongTermLiabilities = value; }
|
||||
}
|
||||
public double MinorityInterest
|
||||
{
|
||||
get { return minorityInterest; }
|
||||
set { minorityInterest = value; }
|
||||
}
|
||||
public double Goodwill
|
||||
{
|
||||
get { return goodwill; }
|
||||
set { goodwill = value; }
|
||||
}
|
||||
public double NegativeGoodwill
|
||||
{
|
||||
get { return negativeGoodwill; }
|
||||
set { negativeGoodwill = value; }
|
||||
}
|
||||
public double TotalStockHolderEquity
|
||||
{
|
||||
get { return totalStockHolderEquity; }
|
||||
set { totalStockHolderEquity=value; }
|
||||
}
|
||||
public PeriodType Period
|
||||
{
|
||||
get { return period; }
|
||||
set { period = value; }
|
||||
}
|
||||
public double Inventory
|
||||
{
|
||||
get { return inventory; }
|
||||
set { inventory = value; }
|
||||
}
|
||||
public double PropertyPlantAndEquipment
|
||||
{
|
||||
get { return propertyPlantAndEquipment; }
|
||||
set { propertyPlantAndEquipment = value; }
|
||||
}
|
||||
public double IntangibleAssets
|
||||
{
|
||||
get { return intangibleAssets; }
|
||||
set { intangibleAssets = value; }
|
||||
}
|
||||
public double AccumulatedAmortization
|
||||
{
|
||||
get { return accumulatedAmortization; }
|
||||
set { accumulatedAmortization=value; }
|
||||
}
|
||||
public String PeriodAsString
|
||||
{
|
||||
get { return PeriodType.Quarterly.Equals(period) ? "Quarterly" : "Annual"; }
|
||||
}
|
||||
public double TotalAssets
|
||||
{
|
||||
get{return totalAssets;}
|
||||
set{totalAssets=value;}
|
||||
}
|
||||
public double TotalCurrentAssets
|
||||
{
|
||||
get{return totalCurrentAssets;}
|
||||
set{totalCurrentAssets=value;}
|
||||
}
|
||||
public double TotalLiabilities
|
||||
{
|
||||
get{return totalLiabilities;}
|
||||
set{totalLiabilities=value;}
|
||||
}
|
||||
public double TotalCurrentLiabilities
|
||||
{
|
||||
get{return totalCurrentLiabilities;}
|
||||
set{totalCurrentLiabilities=value;}
|
||||
}
|
||||
public double NetCurrentAssetValue
|
||||
{
|
||||
get{return TotalCurrentAssets-TotalLiabilities;}
|
||||
}
|
||||
public double NetFixedAssets
|
||||
{
|
||||
get
|
||||
{
|
||||
if(double.IsNaN(TotalAssets)||double.IsNaN(TotalCurrentAssets)||double.IsNaN(Goodwill))return double.NaN;
|
||||
return TotalAssets-TotalCurrentAssets-Goodwill;
|
||||
}
|
||||
}
|
||||
public DateTime Modified
|
||||
{
|
||||
get { return modified; }
|
||||
set { modified = value; }
|
||||
}
|
||||
|
||||
public static String Heading
|
||||
{
|
||||
get
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("Symbol,AsOf,LongTermDebt,OtherLiabilities,DeferredLongTermLiabilities,MinorityInterest,NegativeGoodwill,TotalStockHolderEquity,Inventory,PP&E,IntangibleAssets,AccumulatedAmortization,Period,TotalAssets,TotalCurrentAssets,TotalLiabilities,TotalCurrentLiabilities,CashAndCashEquivalents,NetCurrentAssetValue");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(symbol).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(asof)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", LongTermDebt)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", OtherLiabilities)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", DeferredLongTermLiabilities)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", MinorityInterest)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", NegativeGoodwill)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", TotalStockHolderEquity)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", Inventory)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", PropertyPlantAndEquipment)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", IntangibleAssets)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", AccumulatedAmortization)).Append(",");
|
||||
sb.Append(PeriodAsString).Append(",");
|
||||
sb.Append(String.Format("{0:C}", TotalAssets)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", TotalCurrentAssets)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", TotalLiabilities)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", TotalCurrentLiabilities)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", CashAndCashEquivalents)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", NetCurrentAssetValue));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
88
MarketData/MarketDataLib/MarketDataModel/BetaModel.cs
Executable file
88
MarketData/MarketDataLib/MarketDataModel/BetaModel.cs
Executable file
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using MarketData.Utils;
|
||||
using System.Collections.Generic;
|
||||
using MarketData.ValueAtRisk;
|
||||
using MarketData.Numerical;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class PortfolioHoldingsWithBeta : List<PortfolioHoldingWithBeta>
|
||||
{
|
||||
private PortfolioHoldingsWithBeta()
|
||||
{
|
||||
}
|
||||
// Copy Constructor
|
||||
public PortfolioHoldingsWithBeta(List<PortfolioHoldingWithBeta> portfolioHoldingsWithBeta)
|
||||
{
|
||||
PortfolioBeta = 0.00;
|
||||
if (null == portfolioHoldingsWithBeta) return;
|
||||
foreach (PortfolioHoldingWithBeta portfolioHoldingWithBeta in portfolioHoldingsWithBeta) Add(portfolioHoldingWithBeta);
|
||||
foreach (PortfolioHoldingWithBeta portfolioHoldingWithBeta in this) PortfolioBeta += portfolioHoldingWithBeta.WeightedBeta;
|
||||
}
|
||||
public PortfolioHoldingsWithBeta(PortfolioHoldings portfolioHoldings,DateTime analysisDate)
|
||||
{
|
||||
PortfolioBeta = 0.00;
|
||||
if (null == portfolioHoldings) return;
|
||||
foreach (PortfolioHolding portfolioHolding in portfolioHoldings) Add(new PortfolioHoldingWithBeta(portfolioHolding, analysisDate));
|
||||
foreach (PortfolioHoldingWithBeta portfolioHoldingWithBeta in this) PortfolioBeta += portfolioHoldingWithBeta.WeightedBeta;
|
||||
foreach (PortfolioHoldingWithBeta portfolioHoldingWithBeta in this) portfolioHoldingWithBeta.BetaContribution = portfolioHoldingWithBeta.WeightedBeta / PortfolioBeta;
|
||||
}
|
||||
public PortfolioHoldingsWithBeta(PortfolioTrades portfolioTrades, DateTime analysisDate)
|
||||
{
|
||||
PortfolioBeta = 0.00;
|
||||
double totalExposure = 0.00;
|
||||
if (null == portfolioTrades) return;
|
||||
List<MarketDataModel.Position> positions = portfolioTrades.GetPositions(analysisDate);
|
||||
foreach (MarketDataModel.Position position in positions) Add(new PortfolioHoldingWithBeta(position, analysisDate));
|
||||
foreach (PortfolioHoldingWithBeta portfolioHoldingWithBeta in this) totalExposure += portfolioHoldingWithBeta.Exposure;
|
||||
foreach (PortfolioHoldingWithBeta portfolioHoldingWithBeta in this)
|
||||
{
|
||||
portfolioHoldingWithBeta.WeightExp = portfolioHoldingWithBeta.Exposure / totalExposure;
|
||||
portfolioHoldingWithBeta.WeightedBeta = portfolioHoldingWithBeta.WeightExp * portfolioHoldingWithBeta.Beta;
|
||||
}
|
||||
foreach (PortfolioHoldingWithBeta portfolioHoldingWithBeta in this) PortfolioBeta += portfolioHoldingWithBeta.WeightedBeta;
|
||||
foreach (PortfolioHoldingWithBeta portfolioHoldingWithBeta in this) portfolioHoldingWithBeta.BetaContribution = portfolioHoldingWithBeta.WeightedBeta / PortfolioBeta;
|
||||
}
|
||||
public double PortfolioBeta { get; private set; }
|
||||
public double Exposure
|
||||
{
|
||||
get
|
||||
{
|
||||
return (from PortfolioHoldingWithBeta portfolioHoldingWithBeta in this select portfolioHoldingWithBeta.Exposure).Sum();
|
||||
}
|
||||
}
|
||||
}
|
||||
public class PortfolioHoldingWithBeta
|
||||
{
|
||||
private PortfolioHoldingWithBeta()
|
||||
{
|
||||
}
|
||||
// Assumes that the portfolioTrade is an open trade
|
||||
// public PortfolioHoldingWithBeta(MarketDataModel.Position position, DateTime? analysisDate = null)
|
||||
public PortfolioHoldingWithBeta(MarketDataModel.Position position, DateTime analysisDate)
|
||||
{
|
||||
Symbol = position.Symbol;
|
||||
Exposure = position.Exposure;
|
||||
//if (null == analysisDate) analysisDate = DateTime.Now;
|
||||
Beta = BetaGenerator.Beta(position.Symbol, analysisDate);
|
||||
}
|
||||
// public PortfolioHoldingWithBeta(PortfolioHolding portfolioHolding, DateTime? analysisDate = null)
|
||||
public PortfolioHoldingWithBeta(PortfolioHolding portfolioHolding, DateTime analysisDate)
|
||||
{
|
||||
//if (null == analysisDate) analysisDate = DateTime.Now;
|
||||
Symbol = portfolioHolding.Symbol;
|
||||
Exposure = portfolioHolding.Exposure;
|
||||
WeightExp = portfolioHolding.WeightExp;
|
||||
Beta = BetaGenerator.Beta(portfolioHolding.Symbol, analysisDate);
|
||||
WeightedBeta = portfolioHolding.WeightExp * Beta;
|
||||
}
|
||||
public String Symbol { get; set; }
|
||||
public double Exposure { get; set; }
|
||||
public double Beta { get; private set; }
|
||||
public double WeightExp { get; set; }
|
||||
public double WeightedBeta { get; set; }
|
||||
public double BetaContribution { get; set; }
|
||||
}
|
||||
}
|
||||
162
MarketData/MarketDataLib/MarketDataModel/BollingerBand.cs
Executable file
162
MarketData/MarketDataLib/MarketDataModel/BollingerBand.cs
Executable file
@@ -0,0 +1,162 @@
|
||||
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=20)
|
||||
{
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
23
MarketData/MarketDataLib/MarketDataModel/CashTransactions.cs
Executable file
23
MarketData/MarketDataLib/MarketDataModel/CashTransactions.cs
Executable file
@@ -0,0 +1,23 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class CashTransactions : List<CashTransaction>
|
||||
{
|
||||
}
|
||||
public class CashTransaction
|
||||
{
|
||||
public CashTransaction()
|
||||
{
|
||||
}
|
||||
public String Account { get; set; }
|
||||
public DateTime TransactionDate { get; set; }
|
||||
public String Description { get; set; }
|
||||
public double Credit { get; set; }
|
||||
public double Debit { get; set; }
|
||||
public double Balance { get; set; }
|
||||
}
|
||||
}
|
||||
160
MarketData/MarketDataLib/MarketDataModel/CashflowStatement.cs
Executable file
160
MarketData/MarketDataLib/MarketDataModel/CashflowStatement.cs
Executable file
@@ -0,0 +1,160 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
|
||||
public class CashflowStatement
|
||||
{
|
||||
public enum PeriodType { Annual=0,Quarterly=1}
|
||||
private String symbol;
|
||||
private DateTime asof;
|
||||
private double depreciationAndAmortization;
|
||||
private double deferredIncomeTaxes;
|
||||
private double stockBasedCompensation;
|
||||
private double accountsReceivable;
|
||||
private double inventory;
|
||||
private double accountsPayable;
|
||||
private double accruedLiabilities;
|
||||
private double operatingCashflow;
|
||||
private double freeCashflow;
|
||||
private PeriodType period;
|
||||
private DateTime modified;
|
||||
|
||||
public CashflowStatement()
|
||||
{
|
||||
}
|
||||
// It is appropriate to use the AsOf date in the comparison of the financial statements because the AsOf date is the statement date.
|
||||
public void MergeFrom(CashflowStatement previousCashflowStatement)
|
||||
{
|
||||
if(null==previousCashflowStatement)return;
|
||||
if(!symbol.Equals(previousCashflowStatement.Symbol))return;
|
||||
if(!AsOf.Date.Equals(previousCashflowStatement.AsOf.Date))return;
|
||||
if(!Period.Equals(previousCashflowStatement.Period))return;
|
||||
if(Utility.IsZeroOrNaN(DepreciationAndAmortization))DepreciationAndAmortization=previousCashflowStatement.DepreciationAndAmortization;
|
||||
if(Utility.IsZeroOrNaN(DeferredIncomeTaxes))DeferredIncomeTaxes=previousCashflowStatement.DeferredIncomeTaxes;
|
||||
if(Utility.IsZeroOrNaN(StockBasedCompensation))StockBasedCompensation=previousCashflowStatement.StockBasedCompensation;
|
||||
if(Utility.IsZeroOrNaN(AccountsReceivable))AccountsReceivable=previousCashflowStatement.AccountsReceivable;
|
||||
if(Utility.IsZeroOrNaN(Inventory))Inventory=previousCashflowStatement.Inventory;
|
||||
if(Utility.IsZeroOrNaN(AccountsPayable))AccountsPayable=previousCashflowStatement.AccountsPayable;
|
||||
if(Utility.IsZeroOrNaN(AccruedLiabilities))AccruedLiabilities=previousCashflowStatement.AccruedLiabilities;
|
||||
if(Utility.IsZeroOrNaN(OperatingCashflow))OperatingCashflow=previousCashflowStatement.OperatingCashflow;
|
||||
if(Utility.IsZeroOrNaN(FreeCashflow))FreeCashflow=previousCashflowStatement.FreeCashflow;
|
||||
}
|
||||
|
||||
public bool IsValid()
|
||||
{
|
||||
if(String.IsNullOrEmpty(symbol))return false;
|
||||
if(AsOf.Date.Equals(Utility.Epoch))return false;
|
||||
if(Utility.IsZeroOrNaN(DepreciationAndAmortization)&&
|
||||
Utility.IsZeroOrNaN(DeferredIncomeTaxes)&&
|
||||
Utility.IsZeroOrNaN(StockBasedCompensation)&&
|
||||
Utility.IsZeroOrNaN(AccountsReceivable)&&
|
||||
Utility.IsZeroOrNaN(Inventory)&&
|
||||
Utility.IsZeroOrNaN(AccountsPayable)&&
|
||||
Utility.IsZeroOrNaN(AccruedLiabilities)&&
|
||||
Utility.IsZeroOrNaN(OperatingCashflow)&&
|
||||
Utility.IsZeroOrNaN(FreeCashflow)
|
||||
)return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public DateTime AsOf
|
||||
{
|
||||
get { return asof; }
|
||||
set { asof = value; }
|
||||
}
|
||||
public double DepreciationAndAmortization
|
||||
{
|
||||
get{return depreciationAndAmortization;}
|
||||
set{depreciationAndAmortization=value;}
|
||||
}
|
||||
public double DeferredIncomeTaxes
|
||||
{
|
||||
get{return deferredIncomeTaxes;}
|
||||
set{deferredIncomeTaxes=value;}
|
||||
}
|
||||
public double StockBasedCompensation
|
||||
{
|
||||
get{return stockBasedCompensation;}
|
||||
set{stockBasedCompensation=value;}
|
||||
}
|
||||
public double AccountsReceivable
|
||||
{
|
||||
get{return accountsReceivable;}
|
||||
set{accountsReceivable=value;}
|
||||
}
|
||||
public double Inventory
|
||||
{
|
||||
get{return inventory;}
|
||||
set{inventory=value;}
|
||||
}
|
||||
public double AccountsPayable
|
||||
{
|
||||
get{return accountsPayable;}
|
||||
set{accountsPayable=value;}
|
||||
}
|
||||
public double AccruedLiabilities
|
||||
{
|
||||
get{return accruedLiabilities;}
|
||||
set{accruedLiabilities=value;}
|
||||
}
|
||||
public double OperatingCashflow
|
||||
{
|
||||
get{return operatingCashflow;}
|
||||
set{operatingCashflow=value;}
|
||||
}
|
||||
public double FreeCashflow
|
||||
{
|
||||
get{return freeCashflow;}
|
||||
set{freeCashflow=value;}
|
||||
}
|
||||
public PeriodType Period
|
||||
{
|
||||
get { return period; }
|
||||
set { period = value; }
|
||||
}
|
||||
public String PeriodAsString
|
||||
{
|
||||
get { return PeriodType.Quarterly.Equals(period) ? "Quarterly" : "Annual"; }
|
||||
}
|
||||
public DateTime Modified
|
||||
{
|
||||
get { return modified; }
|
||||
set { modified = value; }
|
||||
}
|
||||
public static String Heading
|
||||
{
|
||||
get
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("Symbol,AsOf,DepreciationAndAmortization,DeferredIncomeTaxes,StockBasedCompensation,AccountsReceivable,Inventory,AccountsPayable,AccruedLiabilities,OperatingCashflow,FreeCashflow,Period");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(symbol).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(asof)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", DepreciationAndAmortization))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", DeferredIncomeTaxes))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", StockBasedCompensation))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", AccountsReceivable))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", Inventory))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", AccountsPayable))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", AccruedLiabilities))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", OperatingCashflow))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", FreeCashflow))).Append(",");
|
||||
sb.Append(PeriodAsString);
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
19
MarketData/MarketDataLib/MarketDataModel/Cashflows.cs
Executable file
19
MarketData/MarketDataLib/MarketDataModel/Cashflows.cs
Executable file
@@ -0,0 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class Cashflows : List<CashflowElement>
|
||||
{
|
||||
}
|
||||
public class CashflowElement
|
||||
{
|
||||
public CashflowElement(DateTime asof, double cashflow)
|
||||
{
|
||||
AsOf = asof;
|
||||
Cashflow = cashflow;
|
||||
}
|
||||
public DateTime AsOf { get; set; }
|
||||
public double Cashflow { get; set; }
|
||||
}
|
||||
}
|
||||
95
MarketData/MarketDataLib/MarketDataModel/CompanyProfile.cs
Executable file
95
MarketData/MarketDataLib/MarketDataModel/CompanyProfile.cs
Executable file
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class CompanyProfiles : List<CompanyProfile>
|
||||
{
|
||||
public CompanyProfiles()
|
||||
{
|
||||
}
|
||||
}
|
||||
public class CompanyProfile
|
||||
{
|
||||
public enum EnumPricingSource{YAHOO,BIGCHARTS,UNKNOWN};
|
||||
public static String PRICING_SOURCE_YAHOO="YAHOO";
|
||||
public static String PRICING_SOURCE_BIGCHARTS="BIGCHARTS";
|
||||
private String symbol;
|
||||
private String industry;
|
||||
private String sector;
|
||||
private String securityType;
|
||||
private String companyName;
|
||||
private String description;
|
||||
private String pricingSource;
|
||||
private bool canRollPrevious;
|
||||
private bool freezePricing;
|
||||
|
||||
public CompanyProfile()
|
||||
{
|
||||
}
|
||||
public String Industry
|
||||
{
|
||||
get { return industry; }
|
||||
set { industry = value; }
|
||||
}
|
||||
public String Sector
|
||||
{
|
||||
get { return sector; }
|
||||
set { sector = value; }
|
||||
}
|
||||
public String SecurityType
|
||||
{
|
||||
get { return securityType;; }
|
||||
set { securityType = value; }
|
||||
}
|
||||
public bool IsEquity
|
||||
{
|
||||
get
|
||||
{
|
||||
return null!=SecurityType && SecurityType.Equals("EQUITY");
|
||||
}
|
||||
}
|
||||
public String CompanyName
|
||||
{
|
||||
get{return companyName;}
|
||||
set{companyName=value;}
|
||||
}
|
||||
public String Description
|
||||
{
|
||||
get{return description;}
|
||||
set{description=value;}
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public String PricingSource
|
||||
{
|
||||
set{pricingSource=value;}
|
||||
}
|
||||
public bool CanRollPrevious
|
||||
{
|
||||
get{return canRollPrevious;}
|
||||
set{canRollPrevious=value;}
|
||||
}
|
||||
public bool FreezePricing
|
||||
{
|
||||
get{return freezePricing;}
|
||||
set{freezePricing=value;}
|
||||
}
|
||||
|
||||
public EnumPricingSource PricingSourceEnum
|
||||
{
|
||||
get
|
||||
{
|
||||
if(null==pricingSource)return EnumPricingSource.UNKNOWN;
|
||||
else if(pricingSource.Equals(PRICING_SOURCE_YAHOO))return EnumPricingSource.YAHOO;
|
||||
else if(pricingSource.Equals(PRICING_SOURCE_BIGCHARTS))return EnumPricingSource.BIGCHARTS;
|
||||
return EnumPricingSource.UNKNOWN;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
17
MarketData/MarketDataLib/MarketDataModel/Constants.cs
Executable file
17
MarketData/MarketDataLib/MarketDataModel/Constants.cs
Executable file
@@ -0,0 +1,17 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class Constants
|
||||
{
|
||||
public static readonly String CONST_ALL ="{All}";
|
||||
public static readonly String CONST_DASHES = "---";
|
||||
public static readonly String CONST_QUESTION = "???";
|
||||
public static readonly String NA = "N.A.";
|
||||
public static readonly DateTime MIN_PRICING_DATE=DateTime.Parse("01-01-2009");
|
||||
}
|
||||
}
|
||||
27
MarketData/MarketDataLib/MarketDataModel/CurrencyConversionElement.cs
Executable file
27
MarketData/MarketDataLib/MarketDataModel/CurrencyConversionElement.cs
Executable file
@@ -0,0 +1,27 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class CurrencyConversionCollection : List<CurrencyConversionElement>
|
||||
{
|
||||
public CurrencyConversionCollection()
|
||||
{
|
||||
}
|
||||
public CurrencyConversionCollection(List<CurrencyConversionElement> currencyConversionCollection)
|
||||
{
|
||||
foreach(CurrencyConversionElement currencyConversionElement in currencyConversionCollection)Add(currencyConversionElement);
|
||||
}
|
||||
}
|
||||
public class CurrencyConversionElement
|
||||
{
|
||||
public String SourceCurrency{get;set;}
|
||||
public DateTime AsOf{get;set;}
|
||||
public String DestinationCurrency{get;set;}
|
||||
public String DestinationCurrencyName{get;set;}
|
||||
public double UnitsPerSource{get;set;}
|
||||
public double SourcePerUnit{get;set;}
|
||||
}}
|
||||
317
MarketData/MarketDataLib/MarketDataModel/DCFValuation.cs
Executable file
317
MarketData/MarketDataLib/MarketDataModel/DCFValuation.cs
Executable file
@@ -0,0 +1,317 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class Enhancements
|
||||
{
|
||||
public bool DebtLoad { get; set; }
|
||||
public double ROIC { get; set; }
|
||||
public double ROICGrowth { get; set; }
|
||||
public double EPSGrowth { get; set; }
|
||||
public double RevenueGrowth { get; set; }
|
||||
public double BVPS { get; set; }
|
||||
public double PBVPS { get; set; }
|
||||
public double EPS { get; set; }
|
||||
public double PE { get; set; }
|
||||
public double PEG { get; set; }
|
||||
public double MOS { get; set; }
|
||||
public double MOS80 { get; set; }
|
||||
public double IntrinsicValue { get; set; } // Benjamin Graham original intrinsic value
|
||||
public double IntrinsicValueRevised { get; set; } // Benjamin Graham revised instrinsic value (uses the yield on 20 year corporate bonds
|
||||
public double RGVIntrinsic { get; set; }
|
||||
public double RGVIntrinsicRevised { get; set; }
|
||||
public Enhancements()
|
||||
{
|
||||
DebtLoad = false;
|
||||
ROIC = double.NaN;
|
||||
ROICGrowth = double.NaN;
|
||||
EPSGrowth = double.NaN;
|
||||
RevenueGrowth = double.NaN;
|
||||
BVPS = double.NaN;
|
||||
PBVPS = double.NaN;
|
||||
EPS = double.NaN;
|
||||
PE = double.NaN;
|
||||
PEG = double.NaN;
|
||||
MOS = double.NaN;
|
||||
MOS80 = double.NaN;
|
||||
IntrinsicValue = double.NaN;
|
||||
RGVIntrinsic = double.NaN;
|
||||
IntrinsicValueRevised = double.NaN;
|
||||
RGVIntrinsicRevised = double.NaN;
|
||||
}
|
||||
}
|
||||
public class DCFValuation
|
||||
{
|
||||
public const double MARKET_RETURN=.11;
|
||||
private String symbol;
|
||||
private double wacc=double.NaN;
|
||||
private double costOfEquity=double.NaN;
|
||||
private double costOfDebt=double.NaN;
|
||||
private double marketValueOfEquity=double.NaN;
|
||||
private double marketValueOfDebt = double.NaN;
|
||||
private double totalCapitalInvested = double.NaN;
|
||||
private double corporateTaxRate = double.NaN;
|
||||
private double beta = double.NaN;
|
||||
private double riskFreeRate = double.NaN;
|
||||
private double interestExpense = double.NaN;
|
||||
private double interestRate = double.NaN;
|
||||
private double totalDebt = double.NaN;
|
||||
private double outstandingShares = double.NaN;
|
||||
private double freeCashflowGrowth = double.NaN;
|
||||
private double presentValue = double.NaN;
|
||||
private double stockPriceValuation = double.NaN;
|
||||
private double marketReturn=MARKET_RETURN;
|
||||
private Price currentPrice;
|
||||
private Cashflows cashflows = new Cashflows();
|
||||
private ReturnItems returnItems = new ReturnItems();
|
||||
private Enhancements enhancements = new Enhancements();
|
||||
private String message;
|
||||
private bool useMarketReturn = false;
|
||||
public bool success = false;
|
||||
|
||||
public bool UseMarketReturn
|
||||
{
|
||||
get { return useMarketReturn; }
|
||||
set { useMarketReturn = value; if (useMarketReturn)marketReturn = 0.00; else marketReturn = MARKET_RETURN; }
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public Price CurrentPrice
|
||||
{
|
||||
get { return currentPrice; }
|
||||
set { currentPrice = value; }
|
||||
}
|
||||
public double WACC
|
||||
{
|
||||
get { return wacc; }
|
||||
set { wacc = value; }
|
||||
}
|
||||
public double CostOfEquity
|
||||
{
|
||||
get { return costOfEquity; }
|
||||
set { costOfEquity = value; }
|
||||
}
|
||||
public double CostOfDebt
|
||||
{
|
||||
get { return costOfDebt; }
|
||||
set { costOfDebt = value; }
|
||||
}
|
||||
public double MarketValueOfEquity
|
||||
{
|
||||
get { return marketValueOfEquity; }
|
||||
set { marketValueOfEquity = value; }
|
||||
}
|
||||
public double MarketValueOfDebt
|
||||
{
|
||||
get { return marketValueOfDebt; }
|
||||
set { marketValueOfDebt = value; }
|
||||
}
|
||||
public double TotalCapitalInvested
|
||||
{
|
||||
get { return totalCapitalInvested; }
|
||||
set { totalCapitalInvested = value; }
|
||||
}
|
||||
public double CorporateTaxRate
|
||||
{
|
||||
get { return corporateTaxRate; }
|
||||
set { corporateTaxRate = value; }
|
||||
}
|
||||
public double Beta
|
||||
{
|
||||
get { return beta; }
|
||||
set { beta = value; }
|
||||
}
|
||||
public double RiskFreeRate
|
||||
{
|
||||
get { return riskFreeRate; }
|
||||
set { riskFreeRate = value; }
|
||||
}
|
||||
public double InterestExpense
|
||||
{
|
||||
get { return interestExpense; }
|
||||
set { interestExpense = value; }
|
||||
}
|
||||
public double InterestRate
|
||||
{
|
||||
get { return interestRate; }
|
||||
set { interestRate = value; }
|
||||
}
|
||||
public double TotalDebt
|
||||
{
|
||||
get { return totalDebt; }
|
||||
set { totalDebt = value; }
|
||||
}
|
||||
public double FreeCashflowGrowth
|
||||
{
|
||||
get { return freeCashflowGrowth; }
|
||||
set { freeCashflowGrowth = value; }
|
||||
}
|
||||
public double OutstandingShares
|
||||
{
|
||||
get { return outstandingShares; }
|
||||
set { outstandingShares = value; }
|
||||
}
|
||||
public ReturnItems ReturnItems
|
||||
{
|
||||
get { return returnItems; }
|
||||
}
|
||||
public Cashflows Cashflows
|
||||
{
|
||||
get { return cashflows; }
|
||||
}
|
||||
public double StockPriceValuation
|
||||
{
|
||||
get { return stockPriceValuation; }
|
||||
set { stockPriceValuation = value; }
|
||||
}
|
||||
public double PresentValue
|
||||
{
|
||||
get { return presentValue; }
|
||||
set { presentValue = value; }
|
||||
}
|
||||
public double MarketReturn
|
||||
{
|
||||
get { return marketReturn; }
|
||||
set { marketReturn = value; }
|
||||
}
|
||||
public String Message
|
||||
{
|
||||
get { return message; }
|
||||
set { message = value; }
|
||||
}
|
||||
public bool Success
|
||||
{
|
||||
get { return success; }
|
||||
set { success = value; }
|
||||
}
|
||||
public Enhancements Enhancements
|
||||
{
|
||||
get { return enhancements; }
|
||||
set { enhancements = value; }
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(Symbol).Append(",");
|
||||
sb.Append(Success).Append(",");
|
||||
if (!Success)
|
||||
{
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
|
||||
sb.Append(Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append(WACC).Append(",");
|
||||
sb.Append(MarketReturn).Append(",");
|
||||
sb.Append(CostOfEquity).Append(",");
|
||||
sb.Append(CostOfDebt).Append(",");
|
||||
sb.Append(MarketValueOfEquity).Append(",");
|
||||
sb.Append(MarketValueOfDebt).Append(",");
|
||||
sb.Append(TotalCapitalInvested).Append(",");
|
||||
sb.Append(CorporateTaxRate).Append(",");
|
||||
sb.Append(Beta).Append(",");
|
||||
sb.Append(RiskFreeRate).Append(",");
|
||||
sb.Append(InterestExpense).Append(",");
|
||||
sb.Append(InterestRate).Append(",");
|
||||
sb.Append(TotalDebt).Append(",");
|
||||
sb.Append(OutstandingShares).Append(",");
|
||||
sb.Append(FreeCashflowGrowth).Append(",");
|
||||
sb.Append(PresentValue).Append(",");
|
||||
sb.Append(StockPriceValuation).Append(",");
|
||||
if (null == currentPrice)
|
||||
{
|
||||
sb.Append(",");
|
||||
sb.Append(",");
|
||||
}
|
||||
else
|
||||
{
|
||||
sb.Append(CurrentPrice.Close).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(CurrentPrice.Date)).Append(",");
|
||||
}
|
||||
|
||||
sb.Append(Enhancements.DebtLoad?"PASS":"FAIL").Append(",");
|
||||
sb.Append(Enhancements.ROIC).Append(",");
|
||||
sb.Append(Enhancements.ROICGrowth).Append(",");
|
||||
sb.Append(Enhancements.EPSGrowth).Append(",");
|
||||
sb.Append(Enhancements.RevenueGrowth).Append(",");
|
||||
sb.Append(Enhancements.BVPS).Append(",");
|
||||
sb.Append(Enhancements.PBVPS).Append(",");
|
||||
sb.Append(Enhancements.EPS).Append(",");
|
||||
sb.Append(Enhancements.PEG).Append(",");
|
||||
sb.Append(Enhancements.MOS).Append(",");
|
||||
sb.Append(Enhancements.MOS80).Append(",");
|
||||
sb.Append(Enhancements.IntrinsicValue).Append(",");
|
||||
sb.Append(Enhancements.IntrinsicValueRevised).Append(",");
|
||||
sb.Append(Enhancements.RGVIntrinsic).Append(",");
|
||||
sb.Append(Enhancements.RGVIntrinsicRevised).Append(",");
|
||||
|
||||
sb.Append(Message);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
public static String Header
|
||||
{
|
||||
get
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("SYMBOL,STATUS,WACC,MARKET_RETURN,COST_OF_EQUITY,COST_OF_DEBT,MARKET_VALUE_OF_EQUITY,MARKET_VALUE_OF_DEBT,TOTAL_CAPITAL_INVESTED,CORPORATE_TAX_RATE,BETA,RISK_FREE_RATE,INTEREST_EXPENSE,INTEREST_RATE,TOTAL_DEBT,OUTSTANDING_SHARES,FREE_CASHFLOW_GROWTH,PRESENT_VALUE,STOCK_PRICE_VALUATION,CURRENT_STOCK_PRICE,PRICING_DATE,");
|
||||
sb.Append("DEBT_LOAD,");
|
||||
sb.Append("ROIC_GROWTH,");
|
||||
sb.Append("EPS_GROWTH,");
|
||||
sb.Append("REVENUE_GROWTH,");
|
||||
sb.Append("BVPS,");
|
||||
sb.Append("PBVPS,");
|
||||
sb.Append("EPS,");
|
||||
sb.Append("PEG,");
|
||||
sb.Append("MOS,");
|
||||
sb.Append("MOS80,");
|
||||
sb.Append("INTRINSIC_VALUE,");
|
||||
sb.Append("INSTRINSIC_VALUE_REVISED,");
|
||||
sb.Append("RGV_INSTRINSIC_VALUE,");
|
||||
sb.Append("RGV_INSTRINSIC_VALUE_REVISED,");
|
||||
sb.Append("MESSAGE");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
42
MarketData/MarketDataLib/MarketDataModel/DMADeviation.cs
Executable file
42
MarketData/MarketDataLib/MarketDataModel/DMADeviation.cs
Executable file
@@ -0,0 +1,42 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class DMADeviations : List<DMADeviation>
|
||||
{
|
||||
public DMADeviations()
|
||||
{
|
||||
}
|
||||
}
|
||||
public class DMADeviation
|
||||
{
|
||||
private String symbol;
|
||||
private DateTime date;
|
||||
private double stdevPrice;
|
||||
private double currentPrice;
|
||||
public DMADeviation()
|
||||
{
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public DateTime Date
|
||||
{
|
||||
get { return date; }
|
||||
set { date = value; }
|
||||
}
|
||||
public double StDevPrice
|
||||
{
|
||||
get { return stdevPrice; }
|
||||
set { stdevPrice = value; }
|
||||
}
|
||||
public double CurrentPrice
|
||||
{
|
||||
get { return currentPrice; }
|
||||
set { currentPrice = value; }
|
||||
}
|
||||
}
|
||||
}
|
||||
150
MarketData/MarketDataLib/MarketDataModel/DMAPrice.cs
Executable file
150
MarketData/MarketDataLib/MarketDataModel/DMAPrice.cs
Executable file
@@ -0,0 +1,150 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class DMAPricesByDate : Dictionary<DateTime, DMAPrice>
|
||||
{
|
||||
public DMAPricesByDate()
|
||||
{
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
public class DMAPrices : List<DMAPrice>
|
||||
{
|
||||
public DMAPrices()
|
||||
{
|
||||
}
|
||||
public DMAPrices(List<DMAPrice> dmaPrices)
|
||||
{
|
||||
foreach(DMAPrice dmaPrice in dmaPrices)Add(dmaPrice);
|
||||
}
|
||||
public DMAPrices Top(int count)
|
||||
{
|
||||
DMAPrices dmaPrices=new DMAPrices();
|
||||
for(int index=0;index<count&&index<Count;index++)
|
||||
{
|
||||
dmaPrices.Add(this[index]);
|
||||
}
|
||||
return dmaPrices;
|
||||
}
|
||||
public DMAPricesByDate GetDMAPricesByDate()
|
||||
{
|
||||
DMAPricesByDate dmaPricesByDate = new DMAPricesByDate();
|
||||
for (int index = 0; index < Count; index++)
|
||||
{
|
||||
DMAPrice dmaPrice = this[index];
|
||||
if (!dmaPricesByDate.ContainsKey(dmaPrice.Date))dmaPricesByDate.Add(dmaPrice.Date,dmaPrice);
|
||||
}
|
||||
return dmaPricesByDate;
|
||||
}
|
||||
public double[] GetAverages()
|
||||
{
|
||||
if(0==Count)return null;
|
||||
double[] averages=new double[Count];
|
||||
for(int index=0;index<Count;index++)averages[index]=this[index].AVGPrice;
|
||||
return averages;
|
||||
}
|
||||
// new 10/27/2018
|
||||
public float[] GetReturns()
|
||||
{
|
||||
if(Count==0||1==Count)return null;
|
||||
float[] returns = new float[Count - 1];
|
||||
for (int index = 0; index < Count - 1; index++)
|
||||
{
|
||||
double currentPrice = this[index].AVGPrice;
|
||||
double prevPrice = this[index + 1].AVGPrice;
|
||||
if (0.00 == prevPrice) returns[index] = 0.00F;
|
||||
else returns[index] = (float)((currentPrice - prevPrice) / Math.Abs(prevPrice));
|
||||
}
|
||||
return returns;
|
||||
}
|
||||
}
|
||||
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; }
|
||||
}
|
||||
}
|
||||
public class DMAPrice
|
||||
{
|
||||
private String symbol;
|
||||
private DateTime date;
|
||||
private double avgPrice;
|
||||
private double minPrice;
|
||||
private double maxPrice;
|
||||
private double currentPrice;
|
||||
public DMAPrice()
|
||||
{
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public DateTime Date
|
||||
{
|
||||
get { return date; }
|
||||
set { date = value; }
|
||||
}
|
||||
public double AVGPrice
|
||||
{
|
||||
get { return avgPrice; }
|
||||
set { avgPrice = value; }
|
||||
}
|
||||
public double MinPrice
|
||||
{
|
||||
get { return minPrice; }
|
||||
set { minPrice = value; }
|
||||
}
|
||||
public double MaxPrice
|
||||
{
|
||||
get { return maxPrice; }
|
||||
set { maxPrice = value; }
|
||||
}
|
||||
public double CurrentPrice
|
||||
{
|
||||
get { return currentPrice; }
|
||||
set { currentPrice = value; }
|
||||
}
|
||||
}
|
||||
}
|
||||
122
MarketData/MarketDataLib/MarketDataModel/Decay.cs
Executable file
122
MarketData/MarketDataLib/MarketDataModel/Decay.cs
Executable file
@@ -0,0 +1,122 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
|
||||
// Filename: Decay.cs
|
||||
// Author:Sean Kessler
|
||||
// Date:06/2003
|
||||
// 11/2003 modified as Per W. Stanzl to alleviate problem with potential loss of precision
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
/// <summary>Decay - decay utility class</summary>
|
||||
public class Decay
|
||||
{
|
||||
private int days;
|
||||
private int applyDays;
|
||||
private float[] decays;
|
||||
private float seed;
|
||||
private const float SEED=.0116F;
|
||||
|
||||
public Decay(int days, float factor, int applyDays)
|
||||
{
|
||||
CreateDecay(factor, days, applyDays);
|
||||
}
|
||||
public Decay(int days,float factor)
|
||||
{
|
||||
CreateDecay(factor,days, days);
|
||||
}
|
||||
public Decay(int days)
|
||||
{
|
||||
CreateDecay(SEED,days, days);
|
||||
}
|
||||
public float this[int day]
|
||||
{
|
||||
get{return decays[day];}
|
||||
set{decays[day]=value;}
|
||||
}
|
||||
public int Count
|
||||
{
|
||||
get{return decays.Length;}
|
||||
}
|
||||
public void Reverse()
|
||||
{
|
||||
float[] inverted=new float[this.decays.Length];
|
||||
for(int index=0;index<this.decays.Length;index++)
|
||||
{
|
||||
inverted[index]=this.decays[this.decays.Length-index-1];
|
||||
}
|
||||
decays=inverted;
|
||||
}
|
||||
public double[] ToDoubleReverse()
|
||||
{
|
||||
double[] decays=new double[this.decays.Length];
|
||||
for(int index=0;index<this.decays.Length;index++)
|
||||
decays[index]=this.decays[this.decays.Length-index-1];
|
||||
return decays;
|
||||
}
|
||||
public void CreateDecay(int days)
|
||||
{
|
||||
CreateDecay(seed,days);
|
||||
}
|
||||
public void CreateDecay(float seed,int days)
|
||||
{
|
||||
CreateDecay(seed, days, applyDays);
|
||||
}
|
||||
public void CreateDecay(float seed,int days, int applyDays)
|
||||
{
|
||||
this.seed=seed;
|
||||
this.days=days;
|
||||
this.applyDays=applyDays;
|
||||
decays=new float[days];
|
||||
|
||||
if (days > 0)
|
||||
{
|
||||
decays[0] = 1F;
|
||||
if (applyDays > 0) decays[0] -= seed;
|
||||
|
||||
for(int index=1;index<days;index++)
|
||||
{
|
||||
if (index < applyDays)
|
||||
decays[index]=(1.00F-seed)*decays[index-1];
|
||||
else
|
||||
decays[index] = decays[index-1];
|
||||
}
|
||||
}
|
||||
PostProcess();
|
||||
}
|
||||
public virtual void PostProcess()
|
||||
{
|
||||
return;
|
||||
}
|
||||
public float Seed
|
||||
{
|
||||
get{return seed;}
|
||||
}
|
||||
public int Days
|
||||
{
|
||||
get
|
||||
{
|
||||
return days;
|
||||
}
|
||||
}
|
||||
public int ApplyDays
|
||||
{
|
||||
get
|
||||
{
|
||||
return applyDays;
|
||||
}
|
||||
}
|
||||
public new string ToString()
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
int length=Count;
|
||||
char[] crlf={'\r','\n'};
|
||||
|
||||
for(int day=0;day<length;day++)
|
||||
{
|
||||
sb.Append(this[day].ToString()).Append(crlf);
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
93
MarketData/MarketDataLib/MarketDataModel/DividendHistory.cs
Executable file
93
MarketData/MarketDataLib/MarketDataModel/DividendHistory.cs
Executable file
@@ -0,0 +1,93 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class DivExDateItem
|
||||
{
|
||||
public DivExDateItem()
|
||||
{
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
public DateTime DivExDate
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
public class DividendHistory : List<DividendHistoryItem>
|
||||
{
|
||||
public DividendHistory()
|
||||
{
|
||||
}
|
||||
public DividendHistory(List<DividendHistoryItem> items)
|
||||
{
|
||||
foreach(DividendHistoryItem item in items)Add(item);
|
||||
}
|
||||
public bool HasConsecutivePayments(int requiredConsecutiveMonths)
|
||||
{
|
||||
if(0==Count||Count<requiredConsecutiveMonths+1)return false;
|
||||
DateGenerator dateGenerator=new DateGenerator();
|
||||
DateTime initialDate=this[0].DivExDate;
|
||||
for(int index=1;index<requiredConsecutiveMonths+1;index++)
|
||||
{
|
||||
initialDate-=new TimeSpan(DateTime.DaysInMonth(initialDate.Year,initialDate.Month),0,0,0);
|
||||
if(!initialDate.Month.Equals(this[index].DivExDate.Month))return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public class DividendHistoryItem
|
||||
{
|
||||
public DividendHistoryItem()
|
||||
{
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
public String DividendType
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
public double? CashAmount
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
public DateTime? DeclarationDate
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
public DateTime? RecordDate
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
public DateTime? PaymentDate
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
public DateTime DivExDate
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
public DateTime Modified
|
||||
{
|
||||
get;
|
||||
set;
|
||||
}
|
||||
}
|
||||
}
|
||||
37
MarketData/MarketDataLib/MarketDataModel/DividendLoad.cs
Executable file
37
MarketData/MarketDataLib/MarketDataModel/DividendLoad.cs
Executable file
@@ -0,0 +1,37 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using MarketData.Utils;
|
||||
using MarketData.Numerical;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class DividendLoadCollection : List<DividendLoadElement>
|
||||
{
|
||||
public DividendLoadCollection()
|
||||
{
|
||||
}
|
||||
public DividendLoadCollection(List<DividendLoadElement> elements)
|
||||
{
|
||||
foreach(DividendLoadElement dividendLoadElement in elements)Add(dividendLoadElement);
|
||||
}
|
||||
//public DividendLoadCollection RemoveOutliers(int standardDeviations=4)
|
||||
//{
|
||||
// double[] values = (from DividendLoadElement element in this select element.DividendLoadPcnt).ToArray();
|
||||
// double valuesStd=Numerics.Volatility(ref values)*standardDeviations;
|
||||
// DividendLoadCollection dividendLoadCollection=new DividendLoadCollection((from DividendLoadElement element in this where element.DividendLoadPcnt <=valuesStd select element).ToList());
|
||||
// if(0==dividendLoadCollection.Count)return this;
|
||||
// else return dividendLoadCollection;
|
||||
//}
|
||||
}
|
||||
public class DividendLoadElement
|
||||
{
|
||||
public String Symbol{get;set;}
|
||||
public int Year{get;set;}
|
||||
public double EPS{get;set;}
|
||||
public double CashAmount{get;set;}
|
||||
public int Payments{get;set;}
|
||||
public double DividendLoadPcnt{get;set;}
|
||||
}
|
||||
}
|
||||
45
MarketData/MarketDataLib/MarketDataModel/DividendPayment.cs
Executable file
45
MarketData/MarketDataLib/MarketDataModel/DividendPayment.cs
Executable file
@@ -0,0 +1,45 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class DividendPayments : List<DividendPayment>
|
||||
{
|
||||
public DividendPayments()
|
||||
{
|
||||
}
|
||||
public DividendPayments(List<DividendPayment> dividendPayments)
|
||||
{
|
||||
foreach(DividendPayment dividendPayment in dividendPayments)Add(dividendPayment);
|
||||
}
|
||||
public double GetDividendPaymentsToDate(DateTime date)
|
||||
{
|
||||
return (from DividendPayment dividendPayment in this where dividendPayment.PaymentDate<=date select dividendPayment.Amount).Sum();
|
||||
}
|
||||
public DividendPayments FilterAccounts(String filterAccounts)
|
||||
{
|
||||
if(null==filterAccounts)return this;
|
||||
List<String> accountsToInclude=Utility.ToList(filterAccounts);
|
||||
DividendPayments dividendPayments=new DividendPayments((from DividendPayment dividendPayment in this where accountsToInclude.Any(x=>x.Equals(dividendPayment.Account)) select dividendPayment).ToList());
|
||||
return dividendPayments;
|
||||
}
|
||||
public DividendPayments FilterSymbols(String filterSymbols)
|
||||
{
|
||||
if(null==filterSymbols) return this;
|
||||
List<String> symbolsToInclude=Utility.ToList(filterSymbols);
|
||||
DividendPayments dividendPayments=new DividendPayments((from DividendPayment dividendPayment in this where symbolsToInclude.Any(x => x.Equals(dividendPayment.Symbol)) select dividendPayment).ToList());
|
||||
return dividendPayments;
|
||||
}
|
||||
}
|
||||
public class DividendPayment
|
||||
{
|
||||
public String Account{get;set;}
|
||||
public String Symbol{get;set;}
|
||||
public DateTime PaymentDate{get;set;}
|
||||
public double Amount{get;set;}
|
||||
}
|
||||
}
|
||||
64
MarketData/MarketDataLib/MarketDataModel/ETFHoldings.cs
Executable file
64
MarketData/MarketDataLib/MarketDataModel/ETFHoldings.cs
Executable file
@@ -0,0 +1,64 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class ETFHoldings : List<ETFHolding>
|
||||
{
|
||||
public List<String> GetETFSymbols()
|
||||
{
|
||||
Dictionary<String, String> distinctETFSymbols = new Dictionary<String, String>();
|
||||
for (int index = 0; index < Count; index++)
|
||||
{
|
||||
ETFHolding etfHolding = this[index];
|
||||
if (!distinctETFSymbols.ContainsKey(etfHolding.ETFSymbol)) distinctETFSymbols.Add(etfHolding.ETFSymbol, etfHolding.ETFSymbol);
|
||||
}
|
||||
return new List<String>(distinctETFSymbols.Values);
|
||||
}
|
||||
}
|
||||
public class ETFHolding
|
||||
{
|
||||
private String etfSymbol;
|
||||
private String holdingSymbol;
|
||||
private String holdingSymbolShareClass;
|
||||
private String holdingCompanyName;
|
||||
private double percentOfAssets;
|
||||
private DateTime modified;
|
||||
|
||||
public ETFHolding()
|
||||
{
|
||||
}
|
||||
public String ETFSymbol
|
||||
{
|
||||
get { return etfSymbol; }
|
||||
set { etfSymbol = value; }
|
||||
}
|
||||
public String HoldingSymbol
|
||||
{
|
||||
get { return holdingSymbol; }
|
||||
set { holdingSymbol = value; }
|
||||
}
|
||||
public String HoldingSymbolShareClass
|
||||
{
|
||||
get { return holdingSymbolShareClass; }
|
||||
set { holdingSymbolShareClass = value; }
|
||||
}
|
||||
public String HoldingCompanyName
|
||||
{
|
||||
get { return holdingCompanyName; }
|
||||
set { holdingCompanyName = value; }
|
||||
}
|
||||
public double PercentOfAssets
|
||||
{
|
||||
get { return percentOfAssets; }
|
||||
set { percentOfAssets = value; }
|
||||
}
|
||||
public DateTime Modified
|
||||
{
|
||||
get { return modified; }
|
||||
set { modified = value; }
|
||||
}
|
||||
}
|
||||
}
|
||||
33
MarketData/MarketDataLib/MarketDataModel/EarningsAnnouncement.cs
Executable file
33
MarketData/MarketDataLib/MarketDataModel/EarningsAnnouncement.cs
Executable file
@@ -0,0 +1,33 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class EarningsAnnouncements : List<EarningsAnnouncement>
|
||||
{
|
||||
public EarningsAnnouncements()
|
||||
{
|
||||
}
|
||||
public EarningsAnnouncements(List<EarningsAnnouncement> earningsAnnouncements)
|
||||
{
|
||||
foreach(EarningsAnnouncement earningsAnnouncement in earningsAnnouncements)Add(earningsAnnouncement);
|
||||
}
|
||||
}
|
||||
public class EarningsAnnouncement
|
||||
{
|
||||
public EarningsAnnouncement()
|
||||
{
|
||||
}
|
||||
public String Symbol{get;set;}
|
||||
public DateTime Date{get;set;}
|
||||
public DateTime PeriodEnding{get;set;}
|
||||
public double Estimate{get;set;}
|
||||
public double Reported{get;set;}
|
||||
public double Surprise{get;set;}
|
||||
public double SurprisePct{get;set;}
|
||||
public String Time{get;set;}
|
||||
}
|
||||
}
|
||||
51
MarketData/MarketDataLib/MarketDataModel/EarningsAnnouncementModel.cs
Executable file
51
MarketData/MarketDataLib/MarketDataModel/EarningsAnnouncementModel.cs
Executable file
@@ -0,0 +1,51 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using MarketData.MarketDataModel;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class EarningsAnnouncementModel : IComparable
|
||||
{
|
||||
public EarningsAnnouncementModel()
|
||||
{
|
||||
}
|
||||
public EarningsAnnouncementModel(String symbol,DateTime nextEarningsDate)
|
||||
{
|
||||
Symbol = symbol;
|
||||
NextEarningsDate = nextEarningsDate;
|
||||
}
|
||||
public int CompareTo(object other)
|
||||
{
|
||||
if (other.GetType() != typeof(EarningsAnnouncementModel)) throw new Exception("Expected typeof " + this.GetType().Name);
|
||||
EarningsAnnouncementModel otherModel = (EarningsAnnouncementModel)other;
|
||||
return NextEarningsDate.CompareTo(otherModel.NextEarningsDate);
|
||||
}
|
||||
public String Symbol { get; set; }
|
||||
public String CompanyName { get; set; }
|
||||
public DateTime NextEarningsDate { get; set; }
|
||||
public int DaysFromToday { get; set; }
|
||||
public double LastPrice { get; set; }
|
||||
public double Upside { get; set; }
|
||||
public double Downside { get; set; }
|
||||
public double UpsidePcnt { get; set; }
|
||||
public double DownsidePcnt { get; set; }
|
||||
public DateTime PricingDate { get; set; }
|
||||
public double PE { get; set; }
|
||||
public double PEG { get; set; }
|
||||
public double AnticipatedEarningsGrowth { get; set; }
|
||||
public String AnticipatedEarningsGrowthStr
|
||||
{
|
||||
get
|
||||
{
|
||||
if (double.IsInfinity(AnticipatedEarningsGrowth) || double.NaN.Equals(AnticipatedEarningsGrowth)) return Constants.CONST_DASHES;;
|
||||
return Utility.FormatPercent(AnticipatedEarningsGrowth);
|
||||
}
|
||||
}
|
||||
public String PEGValuation { get; set; }
|
||||
public DateTime FundamentalDate { get; set; } // fundamental date
|
||||
public DateTime PriceTargetDate{get;set;}
|
||||
}
|
||||
}
|
||||
156
MarketData/MarketDataLib/MarketDataModel/EconomicIndicators.cs
Executable file
156
MarketData/MarketDataLib/MarketDataModel/EconomicIndicators.cs
Executable file
@@ -0,0 +1,156 @@
|
||||
using System.Data;
|
||||
using MarketData.CSVHelper;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class EconomicIndicators : List<EconomicIndicator>
|
||||
{
|
||||
public EconomicIndicators()
|
||||
{
|
||||
}
|
||||
public List<Int32> GetYears()
|
||||
{
|
||||
if(0==Count)return null;
|
||||
List<Int32> years=(from EconomicIndicator economicIndicator in this select economicIndicator.Year).Distinct().ToList();
|
||||
years.Sort();
|
||||
return years;
|
||||
}
|
||||
public Dictionary<String,EconomicIndicators> GetDictionary()
|
||||
{
|
||||
Dictionary<String,EconomicIndicators> dictionary=new Dictionary<String,EconomicIndicators>();
|
||||
if(0==Count)return null;
|
||||
for(int index=0;index<Count;index++)
|
||||
{
|
||||
EconomicIndicator economicIndicator=this[index];
|
||||
if(!dictionary.ContainsKey(economicIndicator.CountryCode))
|
||||
{
|
||||
List<EconomicIndicator> list=new List<EconomicIndicator>();
|
||||
dictionary.Add(economicIndicator.CountryCode,new EconomicIndicators());
|
||||
}
|
||||
EconomicIndicators economicIndicators=dictionary[economicIndicator.CountryCode];
|
||||
economicIndicators.Add(economicIndicator);
|
||||
}
|
||||
List<String> keys=new List<String>(dictionary.Keys);
|
||||
foreach(String key in keys)
|
||||
{
|
||||
dictionary[key].Sort(new EconomicIndicatorByYear());
|
||||
}
|
||||
return dictionary;
|
||||
}
|
||||
public static EconomicIndicators FromZipFile(String strPathZipFile,String strPathExtractFolder,bool debug=false)
|
||||
{
|
||||
try
|
||||
{
|
||||
if(Directory.Exists(strPathExtractFolder))
|
||||
{
|
||||
try{Directory.Delete(strPathExtractFolder,true);}
|
||||
catch(Exception exception){MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Unable to delete folder {0}, exception was {1}",strPathExtractFolder,exception.ToString()));}
|
||||
}
|
||||
Directory.CreateDirectory(strPathExtractFolder);
|
||||
List<String> extractFiles=ExtractFileHelper.ExtractToFolder(strPathZipFile,strPathExtractFolder);
|
||||
if(null==extractFiles||0==extractFiles.Count)
|
||||
{
|
||||
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Could not locate data in zip file {0}",strPathZipFile));
|
||||
return null;
|
||||
}
|
||||
String strPathExtractFile=(from String strPathExtractFileName in extractFiles where !strPathExtractFileName.Contains("Metadata") select strPathExtractFileName).FirstOrDefault();
|
||||
if(null==strPathExtractFile)
|
||||
{
|
||||
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Could not locate data in zip file {0}",strPathZipFile));
|
||||
return null;
|
||||
}
|
||||
CSVFileExt2 csvFile=new CSVFileExt2();
|
||||
int dataRow=csvFile.FindLineWith(strPathExtractFile,"Country Name");
|
||||
if(-1==dataRow)
|
||||
{
|
||||
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Could not locate start of data in zip file {0}",strPathZipFile));
|
||||
return null;
|
||||
}
|
||||
csvFile.LoadCSVFile(strPathExtractFile,dataRow);
|
||||
if(0==csvFile.RowCount)
|
||||
{
|
||||
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Could not locate data in zip file {0}",strPathZipFile));
|
||||
return null;
|
||||
}
|
||||
if(!debug)
|
||||
{
|
||||
try{File.Delete(strPathZipFile);}
|
||||
catch(Exception exception)
|
||||
{
|
||||
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Could not remove zip file {0}, exception was {1}",strPathZipFile,exception.ToString()));
|
||||
}
|
||||
}
|
||||
try{Directory.Delete(strPathExtractFolder,true);}
|
||||
catch(Exception exception)
|
||||
{
|
||||
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Error removing folder {0}, exception was {1}",strPathExtractFolder,exception.ToString()));
|
||||
}
|
||||
return EconomicIndicators.FromDataTable(csvFile.ToDataTable());
|
||||
}
|
||||
catch(Exception exception)
|
||||
{
|
||||
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Error extracting economic indicators from zip file {0}, error was {1}",strPathZipFile,exception.ToString()));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
public static EconomicIndicators FromDataTable(DataTable dataTable)
|
||||
{
|
||||
String strValue=null;
|
||||
String strYear=null;
|
||||
try
|
||||
{
|
||||
EconomicIndicators economicIndicators=new EconomicIndicators();
|
||||
DataColumnCollection columns=dataTable.Columns;
|
||||
DataRowCollection rows=dataTable.Rows;
|
||||
|
||||
for(int rowIndex=0;rowIndex<rows.Count;rowIndex++)
|
||||
{
|
||||
DataRow dataRow=rows[rowIndex];
|
||||
String countryName=dataRow[0].ToString();
|
||||
String countryCode=dataRow[1].ToString();
|
||||
String indicatorName=dataRow[2].ToString();
|
||||
String indicatorCode=dataRow[3].ToString();
|
||||
for(int columnIndex=4;columnIndex<columns.Count;columnIndex++)
|
||||
{
|
||||
EconomicIndicator economicIndicator=new EconomicIndicator();
|
||||
economicIndicator.CountryName=countryName;
|
||||
economicIndicator.CountryCode=countryCode;
|
||||
economicIndicator.IndicatorName=indicatorName;
|
||||
economicIndicator.IndicatorCode=indicatorCode;
|
||||
economicIndicator.Source="World Bank";
|
||||
strYear=columns[columnIndex].ToString();
|
||||
if("".Equals(strYear)||strYear.StartsWith("Column"))continue;
|
||||
economicIndicator.Year=int.Parse(strYear);
|
||||
strValue=dataRow[columnIndex].ToString();
|
||||
if("".Equals(strValue))continue;
|
||||
economicIndicator.IndicatorValue=Double.Parse(strValue);
|
||||
economicIndicators.Add(economicIndicator);
|
||||
}
|
||||
}
|
||||
return economicIndicators;
|
||||
}
|
||||
catch(Exception exception)
|
||||
{
|
||||
MDTrace.WriteLine(LogLevel.DEBUG,exception.ToString());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
public class EconomicIndicatorByYear : IComparer<EconomicIndicator>
|
||||
{
|
||||
public int Compare(EconomicIndicator p1,EconomicIndicator p2)
|
||||
{
|
||||
return p1.Year.CompareTo(p2.Year);
|
||||
}
|
||||
}
|
||||
public class EconomicIndicator
|
||||
{
|
||||
public String Source{get;set;}
|
||||
public String CountryName{get;set;}
|
||||
public String CountryCode{get;set;}
|
||||
public String IndicatorName{get;set;}
|
||||
public String IndicatorCode{get;set;}
|
||||
public double IndicatorValue{get;set;}
|
||||
public int Year{get;set;}
|
||||
}
|
||||
}
|
||||
35
MarketData/MarketDataLib/MarketDataModel/ExponentialDecay.cs
Executable file
35
MarketData/MarketDataLib/MarketDataModel/ExponentialDecay.cs
Executable file
@@ -0,0 +1,35 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using MarketData.Numerical;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class ExponentialDecay
|
||||
{
|
||||
private double[] decays=null;
|
||||
public ExponentialDecay()
|
||||
{
|
||||
}
|
||||
public double this[int sample]
|
||||
{
|
||||
get{return decays[sample];}
|
||||
}
|
||||
public void Prime(float[] samples,double deviations=2.00)
|
||||
{
|
||||
double[]factors=new double[samples.Length];
|
||||
decays=new double[samples.Length];
|
||||
double stddev=Numerics.StdDev(ref samples);
|
||||
for(int index=0,ordinal=samples.Length;index<samples.Length;index++,ordinal--)
|
||||
{
|
||||
factors[index]=(ordinal*ordinal)+(deviations*stddev);
|
||||
}
|
||||
double min=factors.Max();
|
||||
double max=factors.Min();
|
||||
for(int index=0;index<samples.Length;index++)
|
||||
{
|
||||
decays[index]=factors[index]*(100.00/(max-min))/100.00;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
113
MarketData/MarketDataLib/MarketDataModel/FeedStatistics.cs
Executable file
113
MarketData/MarketDataLib/MarketDataModel/FeedStatistics.cs
Executable file
@@ -0,0 +1,113 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class FeedStatistics : List<FeedStatistic>
|
||||
{
|
||||
public FeedStatistics()
|
||||
{
|
||||
}
|
||||
public FeedStatistics(List<FeedStatistic> feedStatistics)
|
||||
{
|
||||
foreach (FeedStatistic feedStatistic in feedStatistics) Add(feedStatistic);
|
||||
}
|
||||
}
|
||||
public class FeedStatistic
|
||||
{
|
||||
public enum FeedStatisticType
|
||||
{
|
||||
ZACKS_RANK, VALUATIONS, YIELD_CURVE, SPLITS, SECURITY_MASTER, SEC_FILINGS, PRICES, OPTIONS, INSIDER_TRANSACTIONS, FUNDAMENTALS, INCOME_STATEMENT, CASHFLOW_STATEMENT,
|
||||
BALANCE_SHEET, HISTORICAL, HEADLINES, ETF_HOLDINGS, ECONOMIC_INDICATORS, EARNINGS_ANNOUNCEMENTS, DIVIDEND_HISTORY, CURRENCY_CONVERSION, ANALYST_RATINGS, ANALYST_PRICE_TARGET,
|
||||
INVALID
|
||||
};
|
||||
public FeedStatistic()
|
||||
{
|
||||
}
|
||||
public String Feed { get; set; }
|
||||
public int Records { get; set; }
|
||||
public DateTime Date { get; set; }
|
||||
|
||||
public static List<String> GetFeedStatisticTypes()
|
||||
{
|
||||
List<String> types = new List<String>();
|
||||
types.Add("Zacks Rank");
|
||||
types.Add("Valuations");
|
||||
types.Add("Yield Curve");
|
||||
types.Add("Splits");
|
||||
types.Add("Security Master");
|
||||
types.Add("SEC Filings");
|
||||
types.Add("Prices");
|
||||
types.Add("Options");
|
||||
types.Add("Insider Transactions");
|
||||
types.Add("Fundamentals");
|
||||
types.Add("Income Statement");
|
||||
types.Add("Cashflow Statement");
|
||||
types.Add("Balance Sheet");
|
||||
types.Add("Historical");
|
||||
types.Add("Headlines");
|
||||
types.Add("ETF Holdings");
|
||||
types.Add("Economic Indicators");
|
||||
types.Add("Earnings Announcements");
|
||||
types.Add("Dividend History");
|
||||
types.Add("Currency Conversion");
|
||||
types.Add("Analyst Ratings");
|
||||
types.Add("Analyst Price Target");
|
||||
return types;
|
||||
}
|
||||
public static String TypeToString(FeedStatisticType feedStatisticType)
|
||||
{
|
||||
if (feedStatisticType.Equals(FeedStatisticType.ZACKS_RANK)) return "Zacks Rank";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.VALUATIONS)) return "Valuations";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.YIELD_CURVE)) return "Yield Curve";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.SPLITS)) return "Splits";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.SECURITY_MASTER)) return "Security Master";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.SEC_FILINGS)) return "SEC Filings";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.PRICES)) return "Prices";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.OPTIONS)) return "Options";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.INSIDER_TRANSACTIONS)) return "Insider Transactions";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.FUNDAMENTALS)) return "Fundamentals";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.INCOME_STATEMENT)) return "Income Statement";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.CASHFLOW_STATEMENT)) return "Cashflow Statement";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.BALANCE_SHEET)) return "Balance Sheet";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.HISTORICAL)) return "Historical";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.HEADLINES)) return "Headlines";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.ETF_HOLDINGS)) return "ETF Holdings";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.ECONOMIC_INDICATORS)) return "Economic Indicators";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.EARNINGS_ANNOUNCEMENTS)) return "Earnings Announcements";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.DIVIDEND_HISTORY)) return "Dividend History";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.CURRENCY_CONVERSION)) return "Currency Conversion";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.ANALYST_RATINGS)) return "Analyst Ratings";
|
||||
if (feedStatisticType.Equals(FeedStatisticType.ANALYST_PRICE_TARGET)) return "Analyst Price Target";
|
||||
return "Invalid";
|
||||
}
|
||||
public static FeedStatisticType FromString(String strFeedStatisticType)
|
||||
{
|
||||
if (strFeedStatisticType.Equals("Zacks Rank")) return FeedStatisticType.ZACKS_RANK;
|
||||
if (strFeedStatisticType.Equals("Valuations")) return FeedStatisticType.VALUATIONS;
|
||||
if (strFeedStatisticType.Equals("Yield Curve")) return FeedStatisticType.YIELD_CURVE;
|
||||
if (strFeedStatisticType.Equals("Splits")) return FeedStatisticType.SPLITS;
|
||||
if (strFeedStatisticType.Equals("Security Master")) return FeedStatisticType.SECURITY_MASTER;
|
||||
if (strFeedStatisticType.Equals("SEC Filings")) return FeedStatisticType.SEC_FILINGS;
|
||||
if (strFeedStatisticType.Equals("Prices")) return FeedStatisticType.PRICES;
|
||||
if (strFeedStatisticType.Equals("Options")) return FeedStatisticType.OPTIONS;
|
||||
if (strFeedStatisticType.Equals("Insider Transactions")) return FeedStatisticType.INSIDER_TRANSACTIONS;
|
||||
if (strFeedStatisticType.Equals("Fundamentals")) return FeedStatisticType.FUNDAMENTALS;
|
||||
if (strFeedStatisticType.Equals("Income Statement")) return FeedStatisticType.INCOME_STATEMENT;
|
||||
if (strFeedStatisticType.Equals("Cashflow Statement")) return FeedStatisticType.CASHFLOW_STATEMENT;
|
||||
if (strFeedStatisticType.Equals("Balance Sheet")) return FeedStatisticType.BALANCE_SHEET;
|
||||
if (strFeedStatisticType.Equals("Historical")) return FeedStatisticType.HISTORICAL;
|
||||
if (strFeedStatisticType.Equals("Headlines")) return FeedStatisticType.HEADLINES;
|
||||
if (strFeedStatisticType.Equals("ETF Holdings")) return FeedStatisticType.ETF_HOLDINGS;
|
||||
if (strFeedStatisticType.Equals("Economic Indicators")) return FeedStatisticType.ECONOMIC_INDICATORS;
|
||||
if (strFeedStatisticType.Equals("Earnings Announcements")) return FeedStatisticType.EARNINGS_ANNOUNCEMENTS;
|
||||
if (strFeedStatisticType.Equals("Dividend History")) return FeedStatisticType.DIVIDEND_HISTORY;
|
||||
if (strFeedStatisticType.Equals("Currency Conversion")) return FeedStatisticType.CURRENCY_CONVERSION;
|
||||
if (strFeedStatisticType.Equals("Analyst Ratings")) return FeedStatisticType.ANALYST_RATINGS;
|
||||
if (strFeedStatisticType.Equals("Analyst Price Target")) return FeedStatisticType.ANALYST_PRICE_TARGET;
|
||||
return FeedStatisticType.INVALID;
|
||||
}
|
||||
}
|
||||
}
|
||||
398
MarketData/MarketDataLib/MarketDataModel/Fundamentals.cs
Executable file
398
MarketData/MarketDataLib/MarketDataModel/Fundamentals.cs
Executable file
@@ -0,0 +1,398 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class Fundamentals : List<Fundamental>
|
||||
{
|
||||
public Fundamentals()
|
||||
{
|
||||
}
|
||||
}
|
||||
public class Fundamental
|
||||
{
|
||||
private String symbol;
|
||||
private DateTime asOf;
|
||||
private DateTime nextEarningsDate;
|
||||
private double beta;
|
||||
private double low52;
|
||||
private double high52;
|
||||
private Int64 volume;
|
||||
private double marketCap;
|
||||
private double pe;
|
||||
private double eps;
|
||||
private double peg;
|
||||
private double returnOnAssets;
|
||||
private double returnOnEquity;
|
||||
private double totalCash;
|
||||
private double totalDebt;
|
||||
private double sharesOutstanding;
|
||||
private double revenue;
|
||||
private double revenuePerShare;
|
||||
private double qtrlyRevenueGrowth;
|
||||
private double grossProfit;
|
||||
private double ebitda;
|
||||
private double netIncomeAvailableToCommon;
|
||||
private double bookValuePerShare;
|
||||
private double operatingCashflow;
|
||||
private double leveragedFreeCashflow;
|
||||
private double equity;
|
||||
private double trailingPE;
|
||||
private double enterpriseValue;
|
||||
private double ebit;
|
||||
private double debtToEquity;
|
||||
private String source;
|
||||
|
||||
public Fundamental()
|
||||
{
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public DateTime AsOf
|
||||
{
|
||||
get { return asOf; }
|
||||
set { asOf = value; }
|
||||
}
|
||||
public String Source
|
||||
{
|
||||
get { return source; }
|
||||
set { source = value; }
|
||||
}
|
||||
public DateTime NextEarningsDate
|
||||
{
|
||||
get { return nextEarningsDate; }
|
||||
set { nextEarningsDate = value; }
|
||||
}
|
||||
public double Beta
|
||||
{
|
||||
get { return beta; }
|
||||
set { beta = value; }
|
||||
}
|
||||
public double Low52
|
||||
{
|
||||
get { return low52; }
|
||||
set { low52 = value; }
|
||||
}
|
||||
public double High52
|
||||
{
|
||||
get { return high52; }
|
||||
set { high52 = value; }
|
||||
}
|
||||
public Int64 Volume
|
||||
{
|
||||
get { return volume; }
|
||||
set { volume = value; }
|
||||
}
|
||||
public double MarketCap
|
||||
{
|
||||
get { return marketCap; }
|
||||
set { marketCap = value; }
|
||||
}
|
||||
public double PE
|
||||
{
|
||||
get { return pe; }
|
||||
set { pe = value; }
|
||||
}
|
||||
public double EPS
|
||||
{
|
||||
get { return eps; }
|
||||
set { eps = value; }
|
||||
}
|
||||
public double PEG
|
||||
{
|
||||
get { return peg; }
|
||||
set { peg = value; }
|
||||
}
|
||||
public double ReturnOnAssets
|
||||
{
|
||||
get { return returnOnAssets; }
|
||||
set { returnOnAssets = value; }
|
||||
}
|
||||
public double ReturnOnEquity
|
||||
{
|
||||
get { return returnOnEquity; }
|
||||
set { returnOnEquity = value; }
|
||||
}
|
||||
public double TotalCash
|
||||
{
|
||||
get { return totalCash; }
|
||||
set { totalCash = value; }
|
||||
}
|
||||
public double TotalDebt
|
||||
{
|
||||
get { return totalDebt; }
|
||||
set { totalDebt = value; }
|
||||
}
|
||||
public double SharesOutstanding
|
||||
{
|
||||
get { return sharesOutstanding; }
|
||||
set { sharesOutstanding = value; }
|
||||
}
|
||||
public double Revenue
|
||||
{
|
||||
get { return revenue; }
|
||||
set { revenue = value; }
|
||||
}
|
||||
public double RevenuePerShare
|
||||
{
|
||||
get { return revenuePerShare; }
|
||||
set { revenuePerShare = value; }
|
||||
}
|
||||
public double QtrlyRevenueGrowth
|
||||
{
|
||||
get { return qtrlyRevenueGrowth; }
|
||||
set { qtrlyRevenueGrowth = value; }
|
||||
}
|
||||
public double GrossProfit
|
||||
{
|
||||
get { return grossProfit; }
|
||||
set { grossProfit=value; }
|
||||
}
|
||||
public double EBITDA
|
||||
{
|
||||
get { return ebitda; }
|
||||
set { ebitda = value; }
|
||||
}
|
||||
public double EBIT
|
||||
{
|
||||
get{return ebit;}
|
||||
set{ebit=value;}
|
||||
}
|
||||
public double EnterpriseValue
|
||||
{
|
||||
get{return enterpriseValue;}
|
||||
set{enterpriseValue=value;}
|
||||
}
|
||||
public double NetIncomeAvailableToCommon
|
||||
{
|
||||
get { return netIncomeAvailableToCommon; }
|
||||
set { netIncomeAvailableToCommon = value; }
|
||||
}
|
||||
public double BookValuePerShare
|
||||
{
|
||||
get { return bookValuePerShare; }
|
||||
set { bookValuePerShare = value; }
|
||||
}
|
||||
public double OperatingCashflow
|
||||
{
|
||||
get {return operatingCashflow; }
|
||||
set { operatingCashflow = value; }
|
||||
}
|
||||
public double LeveragedFreeCashflow
|
||||
{
|
||||
get { return leveragedFreeCashflow; }
|
||||
set { leveragedFreeCashflow = value; }
|
||||
}
|
||||
public double Equity // on the fly as record is pulled from database
|
||||
{
|
||||
get { return equity; }
|
||||
set { equity = value; }
|
||||
}
|
||||
public double TrailingPE
|
||||
{
|
||||
get { return trailingPE; }
|
||||
set { trailingPE = value; }
|
||||
}
|
||||
public double DebtToEquity
|
||||
{
|
||||
get{return debtToEquity;}
|
||||
set{debtToEquity=value;}
|
||||
}
|
||||
// If columns are added to this object must ensure that the columns are also added to the MergeFrom, IsZero, and GetLoad() methods so that the consistency checks can still function properly
|
||||
// Do not include a comparison of the AsOf date. The prior fundamental will always have an AsOf date that precedes the one that we fetch.
|
||||
// In contrast, the AsOf date in the financial statements is the statement date and we use the AsOf date as a comparison there.
|
||||
// The idea here is to ensure that we do not lose any fidelity of the fundamental data if elements are missing in the current fetch but were present in a previous fetch.
|
||||
public void MergeFrom(Fundamental previousFundamental)
|
||||
{
|
||||
if(null==previousFundamental)return;
|
||||
if(!Symbol.Equals(previousFundamental.Symbol))return;
|
||||
if(Utility.IsEpoch(NextEarningsDate))NextEarningsDate=previousFundamental.NextEarningsDate;
|
||||
if(Utility.IsZeroOrNaN(Beta))Beta=previousFundamental.Beta;
|
||||
if(Utility.IsZeroOrNaN(Low52))Low52=previousFundamental.Low52;
|
||||
if(Utility.IsZeroOrNaN(High52))High52=previousFundamental.High52;
|
||||
if(Int64.MinValue.Equals(Volume)||Int64.MaxValue.Equals(Volume))Volume=previousFundamental.Volume;
|
||||
if(Utility.IsZeroOrNaN(MarketCap))MarketCap=previousFundamental.MarketCap;
|
||||
if(Utility.IsZeroOrNaN(PE))PE=previousFundamental.PE;
|
||||
if(Utility.IsZeroOrNaN(EPS))EPS=previousFundamental.EPS;
|
||||
if(Utility.IsZeroOrNaN(PEG))PEG=previousFundamental.PEG;
|
||||
if(Utility.IsZeroOrNaN(ReturnOnAssets))ReturnOnAssets=previousFundamental.ReturnOnAssets;
|
||||
if(Utility.IsZeroOrNaN(ReturnOnEquity))ReturnOnEquity=previousFundamental.ReturnOnEquity;
|
||||
if(Utility.IsZeroOrNaN(TotalCash))TotalCash=previousFundamental.TotalCash;
|
||||
if(Utility.IsZeroOrNaN(TotalDebt))TotalDebt=previousFundamental.TotalDebt;
|
||||
if(Utility.IsZeroOrNaN(SharesOutstanding))SharesOutstanding=previousFundamental.SharesOutstanding;
|
||||
if(Utility.IsZeroOrNaN(Revenue))Revenue=previousFundamental.Revenue;
|
||||
if(Utility.IsZeroOrNaN(RevenuePerShare))RevenuePerShare=previousFundamental.RevenuePerShare;
|
||||
if(Utility.IsZeroOrNaN(QtrlyRevenueGrowth))QtrlyRevenueGrowth=previousFundamental.QtrlyRevenueGrowth;
|
||||
if(Utility.IsZeroOrNaN(GrossProfit))GrossProfit=previousFundamental.GrossProfit;
|
||||
if(Utility.IsZeroOrNaN(EBITDA))EBITDA=previousFundamental.EBITDA;
|
||||
if(Utility.IsZeroOrNaN(EBIT))EBIT=previousFundamental.EBIT;
|
||||
if(Utility.IsZeroOrNaN(EnterpriseValue))EnterpriseValue=previousFundamental.EnterpriseValue;
|
||||
if(Utility.IsZeroOrNaN(NetIncomeAvailableToCommon))NetIncomeAvailableToCommon=previousFundamental.NetIncomeAvailableToCommon;
|
||||
if(Utility.IsZeroOrNaN(BookValuePerShare))BookValuePerShare=previousFundamental.BookValuePerShare;
|
||||
if(Utility.IsZeroOrNaN(OperatingCashflow))OperatingCashflow=previousFundamental.OperatingCashflow;
|
||||
if(Utility.IsZeroOrNaN(LeveragedFreeCashflow))LeveragedFreeCashflow=previousFundamental.LeveragedFreeCashflow;
|
||||
if(Utility.IsZeroOrNaN(Equity))Equity=previousFundamental.Equity;
|
||||
if(Utility.IsZeroOrNaN(TrailingPE))TrailingPE=previousFundamental.TrailingPE;
|
||||
if(Utility.IsZeroOrNaN(DebtToEquity))DebtToEquity=previousFundamental.DebtToEquity;
|
||||
}
|
||||
public bool IsZero()
|
||||
{
|
||||
double missingItemCount=0.00;
|
||||
double totalItems=29.00;
|
||||
double percentMissing=0.00;
|
||||
if(Utility.IsZeroOrNaN(Beta))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(Low52))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(High52))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN((double)Volume))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(MarketCap))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(PE))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(EPS))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(PEG))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(ReturnOnAssets))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(ReturnOnEquity))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(TotalCash))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(TotalDebt))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(SharesOutstanding))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(Revenue))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(SharesOutstanding))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(Revenue))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(RevenuePerShare))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(QtrlyRevenueGrowth))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(GrossProfit))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(EBITDA))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(NetIncomeAvailableToCommon))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(BookValuePerShare))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(OperatingCashflow))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(LeveragedFreeCashflow))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(Equity))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(TrailingPE))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(EnterpriseValue))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(EBIT))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(DebtToEquity))missingItemCount++;
|
||||
percentMissing=(missingItemCount/totalItems)*100.00;
|
||||
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Fundamental load for {0} is {1}%",symbol,100.00-percentMissing));
|
||||
if(percentMissing>85.00)return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public double GetLoad()
|
||||
{
|
||||
double missingItemCount=0.00;
|
||||
double totalItems=29.00;
|
||||
double percentMissing=0.00;
|
||||
if(Utility.IsZeroOrNaN(Beta))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(Low52))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(High52))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN((double)Volume))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(MarketCap))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(PE))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(EPS))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(PEG))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(ReturnOnAssets))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(ReturnOnEquity))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(TotalCash))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(TotalDebt))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(SharesOutstanding))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(Revenue))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(SharesOutstanding))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(Revenue))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(RevenuePerShare))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(QtrlyRevenueGrowth))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(GrossProfit))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(EBITDA))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(NetIncomeAvailableToCommon))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(BookValuePerShare))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(OperatingCashflow))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(LeveragedFreeCashflow))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(Equity))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(TrailingPE))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(EnterpriseValue))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(EBIT))missingItemCount++;
|
||||
if(Utility.IsZeroOrNaN(DebtToEquity))missingItemCount++;
|
||||
percentMissing=(missingItemCount/totalItems)*100.00;
|
||||
return 100.00-percentMissing;
|
||||
}
|
||||
|
||||
public static String Header
|
||||
{
|
||||
get
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.Append("Symbol").Append(",");
|
||||
sb.Append("AsOf").Append(",");
|
||||
sb.Append("Source,");
|
||||
sb.Append("NextEarningsDate").Append(",");
|
||||
sb.Append("Beta").Append(",");
|
||||
sb.Append("Low52").Append(",");
|
||||
sb.Append("High52").Append(",");
|
||||
sb.Append("Volume").Append(",");
|
||||
sb.Append("MarketCap").Append(",");
|
||||
sb.Append("PE").Append(",");
|
||||
sb.Append("EPS").Append(",");
|
||||
sb.Append("PEG").Append(",");
|
||||
sb.Append("Return On Assets").Append(",");
|
||||
sb.Append("Return On Equity").Append(",");
|
||||
sb.Append("Total Cash").Append(",");
|
||||
sb.Append("Total Debt").Append(",");
|
||||
sb.Append("Shares Outstanding").Append(",");
|
||||
sb.Append("Revenue").Append(",");
|
||||
sb.Append("RevenuePerShare").Append(",");
|
||||
sb.Append("QtrlyRevenueGrowth").Append(",");
|
||||
sb.Append("GrossProfit").Append(",");
|
||||
sb.Append("EBITDA").Append(",");
|
||||
sb.Append("NetIncomeAvailableToCommon").Append(",");
|
||||
sb.Append("BookValuePerShare").Append(",");
|
||||
sb.Append("OperatingCashflow").Append(",");
|
||||
sb.Append("LeveragedFreeCashflow").Append(",");
|
||||
sb.Append("Equity").Append(",");
|
||||
sb.Append("Trailing PE,");
|
||||
sb.Append("EBIT,");
|
||||
sb.Append("EnterpriseValue,");
|
||||
sb.Append("DebtToEquity");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(Symbol).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(AsOf)).Append(",");
|
||||
sb.Append(null == Source ? "" : Source).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(NextEarningsDate)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}",Beta )).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}",Low52)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}",High52)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", Volume)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", MarketCap)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", PE)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", EPS)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", PEG)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", ReturnOnAssets)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", ReturnOnEquity)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", TotalCash)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", TotalDebt)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", SharesOutstanding)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", Revenue)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", RevenuePerShare)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", QtrlyRevenueGrowth)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", GrossProfit)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", EBITDA)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", NetIncomeAvailableToCommon)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", BookValuePerShare)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", OperatingCashflow)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", LeveragedFreeCashflow)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", Equity)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", TrailingPE)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", EBIT)).Append(",");
|
||||
sb.Append(String.Format("{0}", EnterpriseValue)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00}", DebtToEquity));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
27
MarketData/MarketDataLib/MarketDataModel/GainLoss/GainLossCompoundModel.cs
Executable file
27
MarketData/MarketDataLib/MarketDataModel/GainLoss/GainLossCompoundModel.cs
Executable file
@@ -0,0 +1,27 @@
|
||||
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
|
||||
{
|
||||
// **************************************************************************************************************************************************************
|
||||
// *********************************************** 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;}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
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
|
||||
{
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
142
MarketData/MarketDataLib/MarketDataModel/GainLoss/GainLossItem.cs
Executable file
142
MarketData/MarketDataLib/MarketDataModel/GainLoss/GainLossItem.cs
Executable file
@@ -0,0 +1,142 @@
|
||||
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
|
||||
{
|
||||
// *********************************************************************************************************************************************************************
|
||||
// ************************************************************************ 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;
|
||||
}
|
||||
}
|
||||
public void WriteToDisk(String strPathFileName)
|
||||
{
|
||||
FileStream outStream=new FileStream(strPathFileName,FileMode.Create);
|
||||
StreamWriter streamWriter=new StreamWriter(outStream);
|
||||
streamWriter.WriteLine("Date,GainLoss,GainLossPercent,Exposure,Dividends,ValueIsPercent");
|
||||
foreach(GainLossItem item in this)
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.Append(item.Date.ToShortDateString()).Append(",");
|
||||
sb.Append(item.GainLoss).Append(",");
|
||||
sb.Append(item.GainLossPercent).Append(",");
|
||||
sb.Append(item.Exposure).Append(",");
|
||||
sb.Append(item.Dividends).Append(",");
|
||||
sb.Append(item.ValueIsPercent);
|
||||
streamWriter.WriteLine(sb.ToString());
|
||||
}
|
||||
streamWriter.Flush();
|
||||
streamWriter.Close();
|
||||
streamWriter.Dispose();
|
||||
outStream.Close();
|
||||
outStream.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
27
MarketData/MarketDataLib/MarketDataModel/GainLoss/GainLossSummaryItem.cs
Executable file
27
MarketData/MarketDataLib/MarketDataModel/GainLoss/GainLossSummaryItem.cs
Executable file
@@ -0,0 +1,27 @@
|
||||
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
|
||||
{
|
||||
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;}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
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;
|
||||
|
||||
// The summary item collection is the data behind the views right-hand grid. This view shows the gain/loss for the date that is selected in the compound model
|
||||
|
||||
namespace MarketData.MarketDataModel.GainLoss
|
||||
{
|
||||
public class GainLossSummaryItemCollection:List<GainLossSummaryItem>
|
||||
{
|
||||
public GainLossSummaryItemCollection()
|
||||
{
|
||||
}
|
||||
public GainLossSummaryItemCollection(PortfolioTrades portfolioTrades,ITotalGainLossGenerator gainLossGenerator,IActiveGainLossGenerator activeGainLossGenerator,DateTime? maxDateRef=null)
|
||||
{
|
||||
List<String> symbols=portfolioTrades.Symbols;
|
||||
|
||||
if(null==gainLossGenerator || null==activeGainLossGenerator)return;
|
||||
|
||||
foreach(String symbol in symbols)
|
||||
{
|
||||
PortfolioTrades portfolioTradesSymbol=portfolioTrades.FilterSymbol(symbol);
|
||||
GainLossCollection gainLossCollection=activeGainLossGenerator.GenerateGainLoss(portfolioTradesSymbol,maxDateRef);
|
||||
|
||||
TotalGainLossCollection totalGainLossCollection=gainLossGenerator.GenerateTotalGainLoss(portfolioTradesSymbol,maxDateRef);
|
||||
GainLossCompoundModelCollection gainLossCompoundModelCollection=new GainLossCompoundModelCollection(gainLossCollection,totalGainLossCollection);
|
||||
|
||||
if(1>gainLossCompoundModelCollection.Count) continue;
|
||||
GainLossSummaryItem gainLossSummaryItem=new GainLossSummaryItem();
|
||||
gainLossSummaryItem.Date=gainLossCompoundModelCollection[gainLossCompoundModelCollection.Count-1].Date;
|
||||
gainLossSummaryItem.Symbol=symbol;
|
||||
gainLossSummaryItem.CompanyName=PricingDA.GetNameForSymbol(symbol);
|
||||
gainLossSummaryItem.CurrentGainLoss=gainLossCompoundModelCollection[gainLossCompoundModelCollection.Count-1].ActiveGainLoss;
|
||||
double previousGainLoss=1==gainLossCompoundModelCollection.Count?0.00:gainLossCompoundModelCollection[gainLossCompoundModelCollection.Count-2].ActiveGainLoss;
|
||||
gainLossSummaryItem.PreviousGainLoss=previousGainLoss;
|
||||
gainLossSummaryItem.Change=gainLossSummaryItem.CurrentGainLoss-gainLossSummaryItem.PreviousGainLoss;
|
||||
if(1==gainLossCollection.Count) gainLossSummaryItem.ChangePercent=0.00;
|
||||
else
|
||||
{
|
||||
double currentMarketValue=gainLossCollection[gainLossCollection.Count-1].Exposure+gainLossCollection[gainLossCollection.Count-1].GainLoss;
|
||||
double previousMarketValue=gainLossCollection[gainLossCollection.Count-2].Exposure+gainLossCollection[gainLossCollection.Count-2].GainLoss;
|
||||
if(0.00==previousMarketValue) gainLossSummaryItem.ChangePercent=0.00;
|
||||
else gainLossSummaryItem.ChangePercent=((currentMarketValue-previousMarketValue)/previousMarketValue)*100;
|
||||
if(gainLossSummaryItem.CurrentGainLoss<0&&gainLossSummaryItem.PreviousGainLoss<0)
|
||||
{ // if current gainloss is negative and previous gainloss is negative then show change percent as a further dip into negative (i.e.) make sure sign is negative
|
||||
if(Math.Abs(gainLossSummaryItem.CurrentGainLoss)>Math.Abs(gainLossSummaryItem.PreviousGainLoss)) gainLossSummaryItem.ChangePercent=Math.Abs(gainLossSummaryItem.ChangePercent)*-1.00;
|
||||
}
|
||||
else if(gainLossSummaryItem.CurrentGainLoss<0&&gainLossSummaryItem.PreviousGainLoss>0)
|
||||
{
|
||||
gainLossSummaryItem.ChangePercent=Math.Abs(gainLossSummaryItem.ChangePercent)*-1.00;
|
||||
}
|
||||
else if(gainLossSummaryItem.CurrentGainLoss>0&&gainLossSummaryItem.PreviousGainLoss>0)
|
||||
{
|
||||
if(gainLossSummaryItem.CurrentGainLoss<gainLossSummaryItem.PreviousGainLoss) gainLossSummaryItem.ChangePercent=Math.Abs(gainLossSummaryItem.ChangePercent)*-1.00;
|
||||
}
|
||||
}
|
||||
// here we need to check maxDateRef for null and then call appropriate HasOpenPositions() / HasOpenPositionsOn(date) method
|
||||
if(null!=maxDateRef)
|
||||
{
|
||||
if(!portfolioTrades.HasOpenPositionsOn(symbol,maxDateRef.Value)) continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(!portfolioTrades.HasOpenPositions(symbol)) continue;
|
||||
}
|
||||
gainLossSummaryItem.HasStopLimit=PortfolioDA.HasStopLimit(symbol);
|
||||
Add(gainLossSummaryItem);
|
||||
}
|
||||
GainLossSummaryItemCollection gainLossSummaryCollection=new GainLossSummaryItemCollection((from GainLossSummaryItem gainLossSummaryItem in this orderby gainLossSummaryItem.Date descending,gainLossSummaryItem.Change descending,gainLossSummaryItem.Symbol descending select gainLossSummaryItem).ToList());
|
||||
Clear();
|
||||
AddRange(gainLossSummaryCollection);
|
||||
}
|
||||
public GainLossSummaryItemCollection(PortfolioTrades portfolioTrades,DateTime? maxDateRef=null)
|
||||
{
|
||||
List<String> symbols=portfolioTrades.Symbols;
|
||||
foreach(String symbol in symbols)
|
||||
{
|
||||
PortfolioTrades portfolioTradesSymbol=portfolioTrades.FilterSymbol(symbol);
|
||||
ITotalGainLossGenerator gainLossGenerator=new GainLossGenerator();
|
||||
IActiveGainLossGenerator activeGainLossGenerator=new ActiveGainLossGenerator();
|
||||
GainLossCollection gainLossCollection=activeGainLossGenerator.GenerateGainLoss(portfolioTradesSymbol,maxDateRef);
|
||||
TotalGainLossCollection totalGainLossCollection=gainLossGenerator.GenerateTotalGainLoss(portfolioTradesSymbol,maxDateRef);
|
||||
GainLossCompoundModelCollection gainLossCompoundModelCollection=new GainLossCompoundModelCollection(gainLossCollection,totalGainLossCollection);
|
||||
if(1>gainLossCompoundModelCollection.Count) continue;
|
||||
GainLossSummaryItem gainLossSummaryItem=new GainLossSummaryItem();
|
||||
gainLossSummaryItem.Date=gainLossCompoundModelCollection[gainLossCompoundModelCollection.Count-1].Date;
|
||||
gainLossSummaryItem.Symbol=symbol;
|
||||
gainLossSummaryItem.CompanyName=PricingDA.GetNameForSymbol(symbol);
|
||||
gainLossSummaryItem.CurrentGainLoss=gainLossCompoundModelCollection[gainLossCompoundModelCollection.Count-1].ActiveGainLoss;
|
||||
double previousGainLoss=1==gainLossCompoundModelCollection.Count?0.00:gainLossCompoundModelCollection[gainLossCompoundModelCollection.Count-2].ActiveGainLoss;
|
||||
gainLossSummaryItem.PreviousGainLoss=previousGainLoss;
|
||||
gainLossSummaryItem.Change=gainLossSummaryItem.CurrentGainLoss-gainLossSummaryItem.PreviousGainLoss;
|
||||
if(1==gainLossCollection.Count) gainLossSummaryItem.ChangePercent=0.00;
|
||||
else
|
||||
{
|
||||
double currentMarketValue=gainLossCollection[gainLossCollection.Count-1].Exposure+gainLossCollection[gainLossCollection.Count-1].GainLoss;
|
||||
double previousMarketValue=gainLossCollection[gainLossCollection.Count-2].Exposure+gainLossCollection[gainLossCollection.Count-2].GainLoss;
|
||||
if(0.00==previousMarketValue) gainLossSummaryItem.ChangePercent=0.00;
|
||||
else gainLossSummaryItem.ChangePercent=((currentMarketValue-previousMarketValue)/previousMarketValue)*100;
|
||||
if(gainLossSummaryItem.CurrentGainLoss<0&&gainLossSummaryItem.PreviousGainLoss<0)
|
||||
{ // if current gainloss is negative and previous gainloss is negative then show change percent as a further dip into negative (i.e.) make sure sign is negative
|
||||
if(Math.Abs(gainLossSummaryItem.CurrentGainLoss)>Math.Abs(gainLossSummaryItem.PreviousGainLoss)) gainLossSummaryItem.ChangePercent=Math.Abs(gainLossSummaryItem.ChangePercent)*-1.00;
|
||||
}
|
||||
else if(gainLossSummaryItem.CurrentGainLoss<0&&gainLossSummaryItem.PreviousGainLoss>0)
|
||||
{
|
||||
gainLossSummaryItem.ChangePercent=Math.Abs(gainLossSummaryItem.ChangePercent)*-1.00;
|
||||
}
|
||||
else if(gainLossSummaryItem.CurrentGainLoss>0&&gainLossSummaryItem.PreviousGainLoss>0)
|
||||
{
|
||||
if(gainLossSummaryItem.CurrentGainLoss<gainLossSummaryItem.PreviousGainLoss) gainLossSummaryItem.ChangePercent=Math.Abs(gainLossSummaryItem.ChangePercent)*-1.00;
|
||||
}
|
||||
}
|
||||
// here we need to check maxDateRef for null and then call appropriate HasOpenPositions() / HasOpenPositionsOn(date) method
|
||||
if(null!=maxDateRef)
|
||||
{
|
||||
if(!portfolioTrades.HasOpenPositionsOn(symbol,maxDateRef.Value)) continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
if(!portfolioTrades.HasOpenPositions(symbol)) continue;
|
||||
}
|
||||
gainLossSummaryItem.HasStopLimit=PortfolioDA.HasStopLimit(symbol);
|
||||
Add(gainLossSummaryItem);
|
||||
}
|
||||
GainLossSummaryItemCollection gainLossSummaryCollection=new GainLossSummaryItemCollection((from GainLossSummaryItem gainLossSummaryItem in this orderby gainLossSummaryItem.Date descending,gainLossSummaryItem.Change descending,gainLossSummaryItem.Symbol descending select gainLossSummaryItem).ToList());
|
||||
Clear();
|
||||
AddRange(gainLossSummaryCollection);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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
|
||||
{
|
||||
public class SortGainLossCompoundModelYearDescendingOrder : IComparer<GainLossCompoundModel>
|
||||
{
|
||||
int IComparer<GainLossCompoundModel>.Compare(GainLossCompoundModel gainLossA, GainLossCompoundModel gainLossB)
|
||||
{
|
||||
if (gainLossA.Date < gainLossB.Date) return 1;
|
||||
if (gainLossA.Date > gainLossB.Date) return -1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
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
|
||||
{
|
||||
public class SortTotalGainLossYearDescendingOrder:IComparer<TotalGainLossItem>
|
||||
{
|
||||
int IComparer<TotalGainLossItem>.Compare(TotalGainLossItem gainLossA,TotalGainLossItem gainLossB)
|
||||
{
|
||||
if(gainLossA.Date<gainLossB.Date) return 1;
|
||||
if(gainLossA.Date>gainLossB.Date) return -1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
23
MarketData/MarketDataLib/MarketDataModel/GainLoss/SortYearDescendingOrder.cs
Executable file
23
MarketData/MarketDataLib/MarketDataModel/GainLoss/SortYearDescendingOrder.cs
Executable file
@@ -0,0 +1,23 @@
|
||||
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
|
||||
{
|
||||
public class SortYearDescendingOrder:IComparer<GainLossItem>
|
||||
{
|
||||
int IComparer<GainLossItem>.Compare(GainLossItem gainLossA,GainLossItem gainLossB)
|
||||
{
|
||||
if(gainLossA.Date<gainLossB.Date) return 1;
|
||||
if(gainLossA.Date>gainLossB.Date) return -1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
24
MarketData/MarketDataLib/MarketDataModel/GainLoss/TotalGainLossCollection.cs
Executable file
24
MarketData/MarketDataLib/MarketDataModel/GainLoss/TotalGainLossCollection.cs
Executable file
@@ -0,0 +1,24 @@
|
||||
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 TotalGainLossCollection : List<TotalGainLossItem>
|
||||
{
|
||||
public TotalGainLossCollection(ICollection<TotalGainLossItem> gainLoss)
|
||||
: base(gainLoss)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
52
MarketData/MarketDataLib/MarketDataModel/GainLoss/TotalGainLossItem.cs
Executable file
52
MarketData/MarketDataLib/MarketDataModel/GainLoss/TotalGainLossItem.cs
Executable file
@@ -0,0 +1,52 @@
|
||||
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()
|
||||
//{
|
||||
//}
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
60
MarketData/MarketDataLib/MarketDataModel/Headlines.cs
Executable file
60
MarketData/MarketDataLib/MarketDataModel/Headlines.cs
Executable file
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class HeadlinesEqualityComparer : IEqualityComparer<Headline>
|
||||
{
|
||||
public bool Equals(Headline x,Headline y)
|
||||
{
|
||||
if(null==x || null ==y || null==x.Entry || null==y.Entry)return false;
|
||||
if(x.Date.Equals(y.Date) && x.Entry.Equals(y.Entry))return false;
|
||||
return true;
|
||||
}
|
||||
public int GetHashCode(Headline headline)
|
||||
{
|
||||
return (headline.Date.ToShortDateString()+headline.Entry).GetHashCode();
|
||||
}
|
||||
}
|
||||
public class Headlines : List<Headline>
|
||||
{
|
||||
public Headlines()
|
||||
{
|
||||
}
|
||||
public Headlines(List<Headline> headlines)
|
||||
{
|
||||
foreach(Headline headline in headlines)Add(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;}
|
||||
}
|
||||
}
|
||||
165
MarketData/MarketDataLib/MarketDataModel/IncomeStatement.cs
Executable file
165
MarketData/MarketDataLib/MarketDataModel/IncomeStatement.cs
Executable file
@@ -0,0 +1,165 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class IncomeStatement
|
||||
{
|
||||
public enum PeriodType { Annual=0,Quarterly=1}
|
||||
private String symbol;
|
||||
private DateTime asof;
|
||||
private double totalRevenue=double.NaN;
|
||||
private double costOfRevenue=double.NaN;
|
||||
private double incomeTaxExpense=double.NaN;
|
||||
private double grossProfit = double.NaN;
|
||||
private double netIncome = double.NaN;
|
||||
private double sga = double.NaN;
|
||||
private double netIncomeApplicableToCommonShares = double.NaN;
|
||||
private double ebit = double.NaN;
|
||||
private double operatingExpenses = double.NaN;
|
||||
private double researchAndDevelopment = double.NaN;
|
||||
private double interestExpense = double.NaN;
|
||||
private PeriodType period;
|
||||
private DateTime modified;
|
||||
|
||||
public IncomeStatement()
|
||||
{
|
||||
}
|
||||
// It is appropriate to use the AsOf date in the comparison of the financial statements because the AsOf date is the statement date.
|
||||
public void MergeFrom(IncomeStatement previousIncomeStatement)
|
||||
{
|
||||
if(null==previousIncomeStatement)return;
|
||||
if(!Symbol.Equals(previousIncomeStatement.Symbol))return;
|
||||
if(!AsOf.Date.Equals(previousIncomeStatement.AsOf.Date))return;
|
||||
if(!Period.Equals(previousIncomeStatement.Period))return;
|
||||
if(Utility.IsZeroOrNaN(TotalRevenue))TotalRevenue=previousIncomeStatement.TotalRevenue;
|
||||
if(Utility.IsZeroOrNaN(CostOfRevenue))CostOfRevenue=previousIncomeStatement.CostOfRevenue;
|
||||
if(Utility.IsZeroOrNaN(IncomeTaxExpense))IncomeTaxExpense=previousIncomeStatement.IncomeTaxExpense;
|
||||
if(Utility.IsZeroOrNaN(GrossProfit))GrossProfit=previousIncomeStatement.GrossProfit;
|
||||
if(Utility.IsZeroOrNaN(NetIncome))NetIncome=previousIncomeStatement.NetIncome;
|
||||
if(Utility.IsZeroOrNaN(SGA))SGA=previousIncomeStatement.SGA;
|
||||
if(Utility.IsZeroOrNaN(NetIncomeApplicableToCommonShares))NetIncomeApplicableToCommonShares=previousIncomeStatement.NetIncomeApplicableToCommonShares;
|
||||
if(Utility.IsZeroOrNaN(EBIT))EBIT=previousIncomeStatement.EBIT;
|
||||
if(Utility.IsZeroOrNaN(OperatingExpenses))OperatingExpenses=previousIncomeStatement.OperatingExpenses;
|
||||
if(Utility.IsZeroOrNaN(ResearchAndDevelopment))ResearchAndDevelopment=previousIncomeStatement.ResearchAndDevelopment;
|
||||
if(Utility.IsZeroOrNaN(InterestExpense))InterestExpense=previousIncomeStatement.InterestExpense;
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public DateTime AsOf
|
||||
{
|
||||
get { return asof; }
|
||||
set { asof = value; }
|
||||
}
|
||||
public double TotalRevenue
|
||||
{
|
||||
get { return totalRevenue; }
|
||||
set { totalRevenue = value; }
|
||||
}
|
||||
public double CostOfRevenue
|
||||
{
|
||||
get { return costOfRevenue; }
|
||||
set { costOfRevenue = value; }
|
||||
}
|
||||
public double GrossProfit
|
||||
{
|
||||
get { return grossProfit; }
|
||||
set { grossProfit = value; }
|
||||
}
|
||||
public double NetIncome
|
||||
{
|
||||
get { return netIncome; }
|
||||
set { netIncome = value; }
|
||||
}
|
||||
// this number is expressed as a percentage so multiply result by 100 to get the percent.
|
||||
// this number tells you how much of every sales dollar you get to use in the business.
|
||||
public double GrossMargin
|
||||
{
|
||||
get
|
||||
{
|
||||
if (double.IsNaN(GrossProfit) || double.IsNaN(TotalRevenue)) return double.NaN;
|
||||
return (GrossProfit / TotalRevenue);
|
||||
}
|
||||
}
|
||||
public double IncomeTaxExpense
|
||||
{
|
||||
get { return incomeTaxExpense; }
|
||||
set { incomeTaxExpense = value; }
|
||||
}
|
||||
public double SGA
|
||||
{
|
||||
get { return sga; }
|
||||
set { sga = value; }
|
||||
}
|
||||
public double NetIncomeApplicableToCommonShares
|
||||
{
|
||||
get { return netIncomeApplicableToCommonShares; }
|
||||
set { netIncomeApplicableToCommonShares = value; }
|
||||
}
|
||||
public double EBIT
|
||||
{
|
||||
get { return ebit; }
|
||||
set { ebit = value; }
|
||||
}
|
||||
public double OperatingExpenses
|
||||
{
|
||||
get { return operatingExpenses; }
|
||||
set { operatingExpenses = value; }
|
||||
}
|
||||
public double ResearchAndDevelopment
|
||||
{
|
||||
get { return researchAndDevelopment; }
|
||||
set { researchAndDevelopment = value; }
|
||||
}
|
||||
public double InterestExpense
|
||||
{
|
||||
get { return interestExpense; }
|
||||
set { interestExpense = value; }
|
||||
}
|
||||
public PeriodType Period
|
||||
{
|
||||
get { return period; }
|
||||
set { period = value; }
|
||||
}
|
||||
public String PeriodAsString
|
||||
{
|
||||
get { return PeriodType.Quarterly.Equals(period) ? "Quarterly" : "Annual"; }
|
||||
}
|
||||
public DateTime Modified
|
||||
{
|
||||
get { return modified; }
|
||||
set { modified = value; }
|
||||
}
|
||||
public static String Heading
|
||||
{
|
||||
get
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("Symbol,AsOf,TotalRevenue,CostOfRevenue,IncomeTaxExpense,GrossProfit,NetIncome,SG&A,NetIncomeApplicableToCommonShares,EBIT,Period");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(symbol).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(asof)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", totalRevenue)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", costOfRevenue)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", incomeTaxExpense)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", grossProfit)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", netIncome)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", sga)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", netIncomeApplicableToCommonShares)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", ebit)).Append(",");
|
||||
sb.Append(String.Format("{0:C}", interestExpense)).Append(",");
|
||||
sb.Append(PeriodAsString);
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
80
MarketData/MarketDataLib/MarketDataModel/InsiderTransaction.cs
Executable file
80
MarketData/MarketDataLib/MarketDataModel/InsiderTransaction.cs
Executable file
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
using MarketData.Utils;
|
||||
using MarketData.Numerical;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class InsiderTransactionSummaries : List<InsiderTransactionSummary>
|
||||
{
|
||||
public InsiderTransactionSummaries(List<InsiderTransactionSummary> insiderTransactionSummaries)
|
||||
{
|
||||
foreach(InsiderTransactionSummary insiderTransactionSummary in insiderTransactionSummaries)Add(insiderTransactionSummary);
|
||||
}
|
||||
public InsiderTransactionSummaries()
|
||||
{
|
||||
}
|
||||
}
|
||||
public class InsiderTransactionSummary : IComparable, IBinValueExtractor
|
||||
{
|
||||
public String Symbol{get;set;}
|
||||
public DateTime TransactionDate{get;set;}
|
||||
public double NumberOfSharesAcquiredDisposed{get;set;}
|
||||
public double BinValue()
|
||||
{
|
||||
return NumberOfSharesAcquiredDisposed;
|
||||
}
|
||||
public int CompareTo(Object item)
|
||||
{
|
||||
InsiderTransactionSummary other=(InsiderTransactionSummary)item;
|
||||
return NumberOfSharesAcquiredDisposed.CompareTo(other.NumberOfSharesAcquiredDisposed);
|
||||
}
|
||||
}
|
||||
public class InsiderTransactions : List<InsiderTransaction>
|
||||
{
|
||||
}
|
||||
public class InsiderTransaction
|
||||
{
|
||||
public String Symbol { get; set; }
|
||||
public DateTime FilingDate { get; set; }
|
||||
public DateTime TransactionDate { get; set; }
|
||||
public String InsiderName { get; set; }
|
||||
public String OwnershipType { get; set; }
|
||||
public String Securities { get; set; }
|
||||
public String NatureOfTransaction { get; set; }
|
||||
public double NumberOrValueAcquiredDisposed { get; set; }
|
||||
public double Price { get; set; }
|
||||
public String Form { get; set; }
|
||||
public String SECAccessionNumber { get; set; }
|
||||
public String FormRowNumber { get; set; }
|
||||
public DateTime Modified { get;set; }
|
||||
public static String Header
|
||||
{
|
||||
get
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.Append("Symbol,FilingDSate,TransactionDate,InsiderName,OwnershipType,Securities,NatureOfTransaction,NumberOrValueAcquiredDisposed,Price,Form,SECAccessionNumber,FormRowNumber,Modified");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.Append(Utility.AddQuotes(Symbol)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(FilingDate.ToShortDateString())).Append(",");
|
||||
sb.Append(Utility.AddQuotes(TransactionDate.ToShortDateString())).Append(",");
|
||||
sb.Append(Utility.AddQuotes(InsiderName)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(OwnershipType)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Securities)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(NatureOfTransaction)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatNumber(NumberOrValueAcquiredDisposed,2,true))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatNumber(Price,2,true))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Form)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(SECAccessionNumber)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(FormRowNumber)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Modified.ToShortDateString()));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
22
MarketData/MarketDataLib/MarketDataModel/KeyValue.cs
Executable file
22
MarketData/MarketDataLib/MarketDataModel/KeyValue.cs
Executable file
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class KeyValue
|
||||
{
|
||||
public KeyValue()
|
||||
{
|
||||
}
|
||||
public KeyValue(String key,String value)
|
||||
{
|
||||
Key=key;
|
||||
Value=value;
|
||||
}
|
||||
public String Key{get;set;}
|
||||
public String Value{get;set;}
|
||||
}
|
||||
}
|
||||
60
MarketData/MarketDataLib/MarketDataModel/Lexical.cs
Executable file
60
MarketData/MarketDataLib/MarketDataModel/Lexical.cs
Executable file
@@ -0,0 +1,60 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class LexicalDictionary : Dictionary<String,LexicalElement>
|
||||
{
|
||||
public LexicalDictionary()
|
||||
{
|
||||
}
|
||||
public LexicalCollection ToList()
|
||||
{
|
||||
List<LexicalElement> lexicalElements=new List<LexicalElement>(this.Values);
|
||||
return new LexicalCollection(lexicalElements);
|
||||
}
|
||||
}
|
||||
public class LexicalElement
|
||||
{
|
||||
public const String POSITIVE_SENTIMENT="Positive";
|
||||
public const String NEGATIVE_SENTIMENT="Negative";
|
||||
public const String NEUTRAL_SENTIMENT="Neutral";
|
||||
public const String VERB="verb";
|
||||
public const String ADJECTIVE="adjective";
|
||||
public const String ADVERB="adverb";
|
||||
public const String NOUN="noun";
|
||||
public const String CONJUNCTION="conjunction";
|
||||
|
||||
public LexicalElement()
|
||||
{
|
||||
}
|
||||
public LexicalElement(String word,String sentiment)
|
||||
{
|
||||
Word=word;
|
||||
Sentiment=sentiment;
|
||||
}
|
||||
public String Word{get;set;}
|
||||
public String PartOfSpeech{get;set;}
|
||||
public String Sentiment{get;set;}
|
||||
}
|
||||
public class LexicalCollection : List<LexicalElement>
|
||||
{
|
||||
public LexicalCollection()
|
||||
{
|
||||
}
|
||||
public LexicalCollection(List<LexicalElement> lexicalCollection)
|
||||
{
|
||||
foreach(LexicalElement lexicalElement in lexicalCollection)Add(lexicalElement);
|
||||
}
|
||||
public LexicalDictionary ToDictionary(String sentiment)
|
||||
{
|
||||
LexicalDictionary lexicalCollectionDictionary=new LexicalDictionary();
|
||||
List<LexicalElement> lexicalCollection=(from LexicalElement lexicalElement in this where lexicalElement.Sentiment.Equals(sentiment) select lexicalElement).ToList();
|
||||
foreach(LexicalElement lexicalElement in lexicalCollection)lexicalCollectionDictionary.Add(lexicalElement.Word,lexicalElement);
|
||||
return lexicalCollectionDictionary;
|
||||
}
|
||||
}
|
||||
}
|
||||
193
MarketData/MarketDataLib/MarketDataModel/MACD.cs
Executable file
193
MarketData/MarketDataLib/MarketDataModel/MACD.cs
Executable file
@@ -0,0 +1,193 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class MACDFastSlowSignalsComparerDesc : IComparer<MACDFastSlowSignal>
|
||||
{
|
||||
public int Compare(MACDFastSlowSignal macd1, MACDFastSlowSignal macd2)
|
||||
{
|
||||
if (macd1.Date < macd2.Date) return -1;
|
||||
else if (macd1.Date > macd2.Date) return 1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
public class MACDFastSlowSignalsComparerAsc : IComparer<MACDFastSlowSignal>
|
||||
{
|
||||
public int Compare(MACDFastSlowSignal macd1, MACDFastSlowSignal macd2)
|
||||
{
|
||||
if (macd1.Date > macd2.Date) return -1;
|
||||
else if (macd1.Date < macd2.Date) return 1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
public class MACDFastSlowSignals : List<MACDFastSlowSignal>
|
||||
{
|
||||
private String symbol;
|
||||
private DateTime fromDate;
|
||||
private DateTime thruDate;
|
||||
private DateTime date;
|
||||
public MACDFastSlowSignals()
|
||||
{
|
||||
}
|
||||
public MACDFastSlowSignals(ICollection<MACDFastSlowSignal> collection)
|
||||
{
|
||||
IEnumerator<MACDFastSlowSignal> enumerator=collection.GetEnumerator();
|
||||
while (enumerator.MoveNext()) Add(enumerator.Current);
|
||||
}
|
||||
public Signals FastCondensedSignals{get;set;}
|
||||
public Signals SlowCondensedSignals{get;set;}
|
||||
public double MinFastMACD
|
||||
{
|
||||
get{return (from MACDFastSlowSignal signal in this select signal.MACDFast).Min()-.25;}
|
||||
}
|
||||
public double MinSlowMACD
|
||||
{
|
||||
get{return (from MACDFastSlowSignal signal in this select signal.MACDSlow).Min()-.25;}
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public DateTime Date
|
||||
{
|
||||
get { return date; }
|
||||
set { date = value; }
|
||||
}
|
||||
public DateTime FromDate
|
||||
{
|
||||
get { return fromDate; }
|
||||
set { fromDate = value; }
|
||||
}
|
||||
public DateTime ThruDate
|
||||
{
|
||||
get { return thruDate; }
|
||||
set { thruDate = value; }
|
||||
}
|
||||
}
|
||||
public class MACDFastSlowSignal
|
||||
{
|
||||
private DateTime date;
|
||||
private double signalFast;
|
||||
private double macdFast;
|
||||
private double signalSlow;
|
||||
private double macdSlow;
|
||||
|
||||
public MACDFastSlowSignal()
|
||||
{
|
||||
}
|
||||
public DateTime Date
|
||||
{
|
||||
get { return date; }
|
||||
set { date = value; }
|
||||
}
|
||||
public double SignalFast
|
||||
{
|
||||
get { return signalFast; }
|
||||
set { signalFast = value; }
|
||||
}
|
||||
public double MACDFast
|
||||
{
|
||||
get { return macdFast; }
|
||||
set { macdFast = value; }
|
||||
}
|
||||
public double SignalSlow
|
||||
{
|
||||
get { return signalSlow; }
|
||||
set { signalSlow = value; }
|
||||
}
|
||||
public double MACDSlow
|
||||
{
|
||||
get { return macdSlow; }
|
||||
set { macdSlow = value; }
|
||||
}
|
||||
}
|
||||
public class MACDSignals : List<MACDSignal>
|
||||
{
|
||||
public MACDSignals()
|
||||
{
|
||||
}
|
||||
public float[] GetMACD(int startIndex, int count)
|
||||
{
|
||||
if (startIndex + count > Count) return null;
|
||||
float[] macdArray = new float[count];
|
||||
for (int index = startIndex, arrayIndex = 0; index < startIndex + count; index++, arrayIndex++)
|
||||
{
|
||||
macdArray[arrayIndex] = (float)this[index].MACD;
|
||||
}
|
||||
return macdArray;
|
||||
}
|
||||
}
|
||||
public class MACDSignal
|
||||
{
|
||||
private String symbol;
|
||||
private DateTime date;
|
||||
private double fast; // fast 12
|
||||
private double slow; // slow 26
|
||||
private double signal; // signal 9
|
||||
private double macd;
|
||||
private double histogram;
|
||||
|
||||
public MACDSignal()
|
||||
{
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get {return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public DateTime Date
|
||||
{
|
||||
get { return date; }
|
||||
set { date = value; }
|
||||
}
|
||||
public double Fast
|
||||
{
|
||||
get { return fast; }
|
||||
set { fast = value; }
|
||||
}
|
||||
public double Slow
|
||||
{
|
||||
get { return slow; }
|
||||
set { slow = value; }
|
||||
}
|
||||
public double Signal
|
||||
{
|
||||
get { return signal; }
|
||||
set { signal = value; }
|
||||
}
|
||||
public double MACD
|
||||
{
|
||||
get { return macd; }
|
||||
set { macd = value; }
|
||||
}
|
||||
public double Histogram
|
||||
{
|
||||
get { return histogram; }
|
||||
set { histogram = value; }
|
||||
}
|
||||
public static String Header
|
||||
{
|
||||
get
|
||||
{
|
||||
return "Symbol,Date,Fast,Slow,Signal,MACD,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.00000}",Fast)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00000}",Slow)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00000}",Signal)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00000}",MACD)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00000}",Histogram));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
61
MarketData/MarketDataLib/MarketDataModel/MACDSetup.cs
Executable file
61
MarketData/MarketDataLib/MarketDataModel/MACDSetup.cs
Executable file
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
// MACD(12,26,9) is common
|
||||
// MACD(12,25,9) is another
|
||||
// MACD(5,35,5) is another alternative
|
||||
// MACD(8,17,9) is faster, more sensitive
|
||||
public class MACDSetup
|
||||
{
|
||||
public int fast;
|
||||
public int slow;
|
||||
public int signal;
|
||||
|
||||
public MACDSetup(String macdSetup) // (12,26,9) , MACD(8,17,9) macd(12,26,9)
|
||||
{
|
||||
macdSetup = macdSetup.ToUpper();
|
||||
macdSetup = macdSetup.Replace("MACD", "");
|
||||
macdSetup = macdSetup.Replace("(", "");
|
||||
macdSetup = macdSetup.Replace(")", "");
|
||||
String[] macd = macdSetup.Split(',');
|
||||
fast = int.Parse(macd[0]);
|
||||
Slow = int.Parse(macd[1]);
|
||||
signal = int.Parse(macd[2]);
|
||||
}
|
||||
public MACDSetup()
|
||||
{
|
||||
fast = 12;
|
||||
slow = 26;
|
||||
signal = 9;
|
||||
}
|
||||
public MACDSetup(int fast, int slow, int signal)
|
||||
{
|
||||
this.fast = fast;
|
||||
this.slow = slow;
|
||||
this.signal = signal;
|
||||
}
|
||||
public int Fast
|
||||
{
|
||||
get { return fast; }
|
||||
set { fast = value; }
|
||||
}
|
||||
public int Slow
|
||||
{
|
||||
get { return slow; }
|
||||
set { slow = value; }
|
||||
}
|
||||
public int Signal
|
||||
{
|
||||
get { return signal; }
|
||||
set { signal = value; }
|
||||
}
|
||||
public override string ToString()
|
||||
{
|
||||
return "MACD(" + fast + "," + slow + "," + signal + ")";
|
||||
}
|
||||
}
|
||||
}
|
||||
50
MarketData/MarketDataLib/MarketDataModel/MobileDataModels.cs
Executable file
50
MarketData/MarketDataLib/MarketDataModel/MobileDataModels.cs
Executable file
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MarketData.Generator;
|
||||
using MarketData.MarketDataModel.GainLoss;
|
||||
|
||||
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 double AllTimeGainLossPercent{get;set;}
|
||||
public double PercentDistanceFromAllTimeGainLossPercent{get;set;}
|
||||
public Price LatestPrice{get;set;}
|
||||
public double PriceChange{get;set;}
|
||||
}
|
||||
}
|
||||
83
MarketData/MarketDataLib/MarketDataModel/ModelPerformance.cs
Executable file
83
MarketData/MarketDataLib/MarketDataModel/ModelPerformance.cs
Executable file
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class ModelPerformanceSeries : List<ModelPerformanceItem>
|
||||
{
|
||||
public ModelPerformanceSeries()
|
||||
{
|
||||
}
|
||||
public ModelPerformanceSeries(List<ModelPerformanceItem> modelPerformanceItemList)
|
||||
{
|
||||
foreach(ModelPerformanceItem modelPerformanceItem in modelPerformanceItemList) Add(modelPerformanceItem);
|
||||
}
|
||||
public void CalculatePerformance()
|
||||
{
|
||||
for(int index=0;index<this.Count;index++)
|
||||
{
|
||||
ModelPerformanceItem currentModelPerformanceItem=this[index];
|
||||
ModelPerformanceItem prevModelPerformanceItem=0==index?null:this[index-1];
|
||||
if(null==prevModelPerformanceItem)
|
||||
{
|
||||
currentModelPerformanceItem.CumulativeGainLoss=currentModelPerformanceItem.GainLossDOD;
|
||||
if(0==currentModelPerformanceItem.Exposure)currentModelPerformanceItem.R=0;
|
||||
else currentModelPerformanceItem.R=(currentModelPerformanceItem.MarketValue-currentModelPerformanceItem.Exposure)/currentModelPerformanceItem.Exposure;
|
||||
currentModelPerformanceItem.OnePlusR=1.00+currentModelPerformanceItem.R;
|
||||
currentModelPerformanceItem.CumProd=currentModelPerformanceItem.OnePlusR;
|
||||
currentModelPerformanceItem.CumProdMinusOne=currentModelPerformanceItem.CumProd-1.00;
|
||||
}
|
||||
else
|
||||
{
|
||||
currentModelPerformanceItem.CumulativeGainLoss=currentModelPerformanceItem.GainLossDOD+prevModelPerformanceItem.CumulativeGainLoss;
|
||||
if(0==currentModelPerformanceItem.Exposure)currentModelPerformanceItem.R=0;
|
||||
else currentModelPerformanceItem.R=prevModelPerformanceItem.Exposure.Equals(currentModelPerformanceItem.Exposure)?(currentModelPerformanceItem.MarketValue-prevModelPerformanceItem.MarketValue)/prevModelPerformanceItem.MarketValue:0;
|
||||
currentModelPerformanceItem.OnePlusR=1.00+currentModelPerformanceItem.R;
|
||||
currentModelPerformanceItem.CumProd=currentModelPerformanceItem.OnePlusR*prevModelPerformanceItem.CumProd;
|
||||
currentModelPerformanceItem.CumProdMinusOne=currentModelPerformanceItem.CumProd-1.00;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
public class ModelPerformanceItem
|
||||
{
|
||||
public DateTime Date { get; set; }
|
||||
public double Exposure { get; set; } // This is the exposure on a given day.
|
||||
public double MarketValue { get; set; } // This is the MarketValue on a given day
|
||||
public double GainLossDOD { get; set; } // This is the gain loss change from day to day
|
||||
public double GainLoss { get; set; } // This is the gain loss on the given day
|
||||
public double CumulativeGainLoss{get;set;} // This is the cumulative gain loss. The last item in the series contains the cumulative amount gained or lost.
|
||||
public double R{get;set;} // This is the period Return. (MV[n]-MV[n-1])/MV[n-1]
|
||||
public double OnePlusR{get;set;} // (R+1)
|
||||
public double CumProd{get;set;} // (R+1)*(R+1).....
|
||||
public double CumProdMinusOne{get;set;} // subtract 1 from CumProd to get a decimal return. Each item in the series represents a cumulative return for that date. The final element contains the cumulative return for the entire series
|
||||
public bool ClosedPositions{get;set;} // inidcates if any positions closed on this date
|
||||
public ModelPerformanceItem()
|
||||
{
|
||||
}
|
||||
public static String Header()
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.Append("Date,Exposure,MarketValue,GainLossDOD,GainLoss,CumulativeGainLoss,R,OnePlusR,CumProd,CumProdMinusOne,ClosedPositions");
|
||||
return sb.ToString();
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.Append(Utility.AddQuotes(Utility.DateTimeToStringMMSDDSYYYY(Date))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(Exposure))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(MarketValue))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(GainLossDOD))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(GainLoss))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(CumulativeGainLoss))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatPercent(R,2))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatNumber(OnePlusR,2))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatNumber(CumProd,2))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatPercent(CumProdMinusOne,3))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(ClosedPositions.ToString()));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
95
MarketData/MarketDataLib/MarketDataModel/ModelTrade.cs
Executable file
95
MarketData/MarketDataLib/MarketDataModel/ModelTrade.cs
Executable file
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
98
MarketData/MarketDataLib/MarketDataModel/MovingAverage.cs
Executable file
98
MarketData/MarketDataLib/MarketDataModel/MovingAverage.cs
Executable file
@@ -0,0 +1,98 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class MovingAverages : List<MovingAverageElement>
|
||||
{
|
||||
private DateTime fromDate;
|
||||
private DateTime thruDate;
|
||||
|
||||
public MovingAverages()
|
||||
{
|
||||
}
|
||||
public MovingAverages(List<MovingAverageElement> list)
|
||||
{
|
||||
foreach(MovingAverageElement element in list)Add(element);
|
||||
}
|
||||
public DateTime FromDate
|
||||
{
|
||||
get { return fromDate; }
|
||||
set { fromDate = value; }
|
||||
}
|
||||
public DateTime ThruDate
|
||||
{
|
||||
get { return thruDate; }
|
||||
set { thruDate = value; }
|
||||
}
|
||||
}
|
||||
public class MovingAverageElement
|
||||
{
|
||||
private String symbol;
|
||||
private DateTime date;
|
||||
private double close;
|
||||
private double high;
|
||||
private double low;
|
||||
private double ma200;
|
||||
private double ma100;
|
||||
private double ma55;
|
||||
private double ma21;
|
||||
private double ma5;
|
||||
|
||||
public MovingAverageElement()
|
||||
{
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public DateTime Date
|
||||
{
|
||||
get { return date; }
|
||||
set { date = value; }
|
||||
}
|
||||
public double Close
|
||||
{
|
||||
get { return close; }
|
||||
set { close = value; }
|
||||
}
|
||||
public double High
|
||||
{
|
||||
get { return high; }
|
||||
set { high = value; }
|
||||
}
|
||||
public double Low
|
||||
{
|
||||
get { return low; }
|
||||
set { low = value; }
|
||||
}
|
||||
public double MA200
|
||||
{
|
||||
get{return ma200;}
|
||||
set{ma200=value;}
|
||||
}
|
||||
public double MA100
|
||||
{
|
||||
get { return ma100; }
|
||||
set { ma100 = value; }
|
||||
}
|
||||
public double MA55
|
||||
{
|
||||
get { return ma55; }
|
||||
set { ma55 = value; }
|
||||
}
|
||||
public double MA21
|
||||
{
|
||||
get { return ma21; }
|
||||
set { ma21 = value; }
|
||||
}
|
||||
public double MA5
|
||||
{
|
||||
get { return ma5; }
|
||||
set { ma5 = value; }
|
||||
}
|
||||
}
|
||||
}
|
||||
40
MarketData/MarketDataLib/MarketDataModel/MovingDeviation.cs
Executable file
40
MarketData/MarketDataLib/MarketDataModel/MovingDeviation.cs
Executable file
@@ -0,0 +1,40 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using MarketData.Numerical;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class MovingDeviation
|
||||
{
|
||||
private MovingDeviation()
|
||||
{
|
||||
}
|
||||
public static DMADeviations GenerateMovingDeviation(Prices prices, int dayCount)
|
||||
{
|
||||
try
|
||||
{
|
||||
DMADeviations dmaDeviations = new DMADeviations();
|
||||
|
||||
for (int index = 0; index < prices.Count; index++)
|
||||
{
|
||||
Price price = prices[index];
|
||||
DMADeviation dmaDeviation = new DMADeviation();
|
||||
dmaDeviation.Symbol = price.Symbol;
|
||||
dmaDeviation.Date = price.Date;
|
||||
float[] pricesArray = prices.GetPrices(index, dayCount);
|
||||
dmaDeviation.StDevPrice = Numerics.Volatility(ref pricesArray);
|
||||
if (double.IsNaN(dmaDeviation.StDevPrice)) continue;
|
||||
dmaDeviation.CurrentPrice = price.Close;
|
||||
dmaDeviations.Add(dmaDeviation);
|
||||
}
|
||||
return dmaDeviations;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MDTrace.WriteLine(LogLevel.DEBUG,exception);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
335
MarketData/MarketDataLib/MarketDataModel/OptionsModel.cs
Executable file
335
MarketData/MarketDataLib/MarketDataModel/OptionsModel.cs
Executable file
@@ -0,0 +1,335 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class EquityPriceShocks : List<EquityPriceShock>
|
||||
{
|
||||
public static EquityPriceShocks CreateEquityPriceShocks(Price latestPrice, OptionsParams optionsParams)
|
||||
{
|
||||
EquityPriceShocks equityPriceShocks = new EquityPriceShocks();
|
||||
int[] shocks = { 50, 25, 15, 10, 0, -5, -10, -15, -25, -50 };
|
||||
for (int index = 0; index < shocks.Length; index++)
|
||||
{
|
||||
EquityPriceShock equityPriceShock = new EquityPriceShock();
|
||||
equityPriceShock.Rank = shocks[index];
|
||||
if (equityPriceShock.Rank > 0) equityPriceShock.PriceShock = "+" + Utility.FormatNumber(equityPriceShock.Rank, 0, false).ToString() + "%";
|
||||
else if (equityPriceShock.Rank < 0) equityPriceShock.PriceShock = Utility.FormatNumber(equityPriceShock.Rank, 0, false) + "%";
|
||||
else equityPriceShock.PriceShock = "+-" + Utility.FormatNumber(equityPriceShock.Rank, 0, false) + "%";
|
||||
equityPriceShock.Premium = optionsParams.Premium;
|
||||
equityPriceShock.Rank /= 100.00;
|
||||
equityPriceShock.MarketPrice = latestPrice.Close + (latestPrice.Close * equityPriceShock.Rank);
|
||||
equityPriceShock.StrikePrice = optionsParams.Strike;
|
||||
|
||||
// We expect the option to be excercises because the strike price is more favorable than market price
|
||||
// price our gain loss as if we had purchased at prevailing market price and then sold at the strike price
|
||||
if (optionsParams.Strike < equityPriceShock.MarketPrice)
|
||||
{
|
||||
equityPriceShock.PositionGL = (equityPriceShock.StrikePrice * optionsParams.Shares) - (latestPrice.Close * optionsParams.Shares);
|
||||
equityPriceShock.TransactionGL = equityPriceShock.Premium + equityPriceShock.PositionGL;
|
||||
equityPriceShock.ExpectedOutcome = "Option will be assigned.";
|
||||
}
|
||||
else
|
||||
// We expect the option to go un-excercised because the stock can be purchased in the open market more cheaply than at our strike price
|
||||
// price our gain/loss as if we had purchased at prevailing market prie and then sold at the shock price
|
||||
{
|
||||
equityPriceShock.PositionGL = (equityPriceShock.MarketPrice * optionsParams.Shares) - (latestPrice.Close * optionsParams.Shares);
|
||||
equityPriceShock.TransactionGL = equityPriceShock.Premium + equityPriceShock.PositionGL;
|
||||
equityPriceShock.ExpectedOutcome = "Option will not be assigned.";
|
||||
}
|
||||
equityPriceShocks.Add(equityPriceShock);
|
||||
}
|
||||
return equityPriceShocks;
|
||||
}
|
||||
}
|
||||
public class EquityPriceShock
|
||||
{
|
||||
public String PriceShock { get; set; }
|
||||
public double Rank { get; set; }
|
||||
public double MarketPrice { get; set; }
|
||||
public double StrikePrice { get; set; }
|
||||
public double Premium { get; set; }
|
||||
public double PositionGL { get; set; }
|
||||
public double TransactionGL { get; set; }
|
||||
public String ExpectedOutcome { get; set; }
|
||||
}
|
||||
[Serializable]
|
||||
public class OptionsParams
|
||||
{
|
||||
private int contracts;
|
||||
private double shares;
|
||||
public static int CONTRACT_SIZE = 100;
|
||||
public String Symbol { get; set; }
|
||||
public String CompanyName { get; set; }
|
||||
public double Cashdown { get; set; }
|
||||
public DateTime ExpirationDate { get; set; }
|
||||
public double Bid { get; set; }
|
||||
public double Strike { get; set; }
|
||||
public double OpenInterest { get; set; }
|
||||
public double Volume { get; set; }
|
||||
public double Shares
|
||||
{
|
||||
get
|
||||
{
|
||||
return shares;
|
||||
}
|
||||
}
|
||||
public int Contracts
|
||||
{
|
||||
get
|
||||
{
|
||||
return contracts;
|
||||
}
|
||||
set
|
||||
{
|
||||
contracts = value;
|
||||
shares = contracts * 100.00;
|
||||
}
|
||||
}
|
||||
public double MarketPrice { get; set; }
|
||||
public double Premium { get; set; }
|
||||
public double Volatility { get; set; }
|
||||
public int VolatilityDays { get; set; }
|
||||
public static String Header
|
||||
{
|
||||
get
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("Symbol").Append(",");
|
||||
sb.Append("CompanyName").Append(",");
|
||||
sb.Append("Cashdown").Append(",");
|
||||
sb.Append("ExpirationDate").Append(",");
|
||||
sb.Append("Bid").Append(",");
|
||||
sb.Append("Strike").Append(",");
|
||||
sb.Append("OpenInterest").Append(",");
|
||||
sb.Append("Shares").Append(",");
|
||||
sb.Append("Contracts").Append(",");
|
||||
sb.Append("MarketPrice").Append(",");
|
||||
sb.Append("Premium").Append(",");
|
||||
sb.Append("Volatility").Append(",");
|
||||
sb.Append("VolatilityDays");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("\"").Append(Symbol).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(CompanyName).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.FormatCurrency(Cashdown)).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.DateTimeToStringMMHDDHYYYY(ExpirationDate)).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.FormatCurrency(Bid)).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.FormatCurrency(Strike)).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.FormatNumber(OpenInterest,0,true)).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.FormatNumber(Shares)).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.FormatNumber(Contracts,0,true)).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.FormatCurrency(MarketPrice)).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.FormatCurrency(Premium)).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.FormatCurrency(Volatility)).Append("\"").Append(",");
|
||||
sb.Append("\"").Append(Utility.FormatNumber(VolatilityDays,0,false)).Append("\"");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
public class MoneyType
|
||||
{
|
||||
public enum MoneyTypeEnum { AtTheMoney, InTheMoney, OutOfTheMoney, Unset };
|
||||
public MoneyTypeEnum moneyType = MoneyTypeEnum.Unset;
|
||||
public MoneyType()
|
||||
{
|
||||
moneyType = MoneyTypeEnum.Unset;
|
||||
}
|
||||
public MoneyType(double currentPrice, double strikePrice)
|
||||
{
|
||||
SetMoney(currentPrice, strikePrice);
|
||||
}
|
||||
public MoneyType.MoneyTypeEnum Money
|
||||
{
|
||||
get { return moneyType; }
|
||||
set { moneyType = value; }
|
||||
}
|
||||
public void SetMoney(double currentPrice, double strikePrice)
|
||||
{
|
||||
double upperPrice = strikePrice + .15;
|
||||
double lowerPrice = strikePrice - .15;
|
||||
if (currentPrice <= upperPrice && currentPrice >= lowerPrice)
|
||||
{
|
||||
Money = MoneyTypeEnum.AtTheMoney;
|
||||
}
|
||||
else if (strikePrice < currentPrice) Money = MoneyTypeEnum.InTheMoney;
|
||||
else Money = MoneyTypeEnum.OutOfTheMoney;
|
||||
}
|
||||
public override string ToString()
|
||||
{
|
||||
switch (Money)
|
||||
{
|
||||
case MoneyTypeEnum.AtTheMoney:
|
||||
return "At The Money";
|
||||
case MoneyTypeEnum.InTheMoney:
|
||||
return "In The Money";
|
||||
case MoneyTypeEnum.OutOfTheMoney:
|
||||
return "Out Of The Money";
|
||||
default:
|
||||
return "Unset";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// *******************************************************************************************************************************************************************
|
||||
// ************************************************************** P U T C A L L R A T I O C A L C U L A T O R ***********************************************
|
||||
// *******************************************************************************************************************************************************************
|
||||
public class PutCallRatioHelper
|
||||
{
|
||||
protected class StrikeExpiryKey
|
||||
{
|
||||
public StrikeExpiryKey(double strike,DateTime expiration)
|
||||
{
|
||||
Expiration=expiration;
|
||||
Strike=strike;
|
||||
}
|
||||
public DateTime Expiration{get;set;}
|
||||
public double Strike{get;set;}
|
||||
public override int GetHashCode()
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.Append(Expiration.ToShortDateString()).Append(Utility.FormatCurrency(Strike));
|
||||
return sb.ToString().GetHashCode();
|
||||
}
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
return Equals(obj as StrikeExpiryKey);
|
||||
}
|
||||
public bool Equals(StrikeExpiryKey obj)
|
||||
{
|
||||
return obj.ToString().Equals(ToString());
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.Append(Expiration.ToShortDateString()).Append(Utility.FormatCurrency(Strike));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
private PutCallRatioHelper()
|
||||
{
|
||||
}
|
||||
public static void CalculatePutCallRatios(Options options)
|
||||
{
|
||||
Dictionary<StrikeExpiryKey,Option> putOptions=new Dictionary<StrikeExpiryKey,Option>();
|
||||
Dictionary<StrikeExpiryKey,Option> callOptions=new Dictionary<StrikeExpiryKey,Option>();
|
||||
foreach(Option option in options)
|
||||
{
|
||||
StrikeExpiryKey strikeExpiryKey=new StrikeExpiryKey(option.Strike,option.Expiration);
|
||||
if(option.Type.Equals(OptionTypeEnum.CallOption)&&!callOptions.ContainsKey(strikeExpiryKey))callOptions.Add(strikeExpiryKey,option);
|
||||
else if(!putOptions.ContainsKey(strikeExpiryKey))putOptions.Add(strikeExpiryKey,option);
|
||||
}
|
||||
foreach(Option option in options)
|
||||
{
|
||||
if(option.Volume==0)
|
||||
{
|
||||
option.PutCallRatio=double.NaN;
|
||||
option.CallPutRatio=double.NaN;
|
||||
continue;
|
||||
}
|
||||
StrikeExpiryKey strikeExpiryKey=new StrikeExpiryKey(option.Strike,option.Expiration);
|
||||
if(option.Type.Equals(OptionTypeEnum.PutOption)) // put options
|
||||
{
|
||||
Option callOption=null;
|
||||
option.CallPutRatio=double.NaN;
|
||||
if(!callOptions.ContainsKey(strikeExpiryKey))
|
||||
{
|
||||
option.PutCallRatio=double.NaN;
|
||||
continue;
|
||||
}
|
||||
callOption=callOptions[strikeExpiryKey];
|
||||
if(0==callOption.Volume)
|
||||
{
|
||||
option.PutCallRatio=double.NaN;
|
||||
continue;
|
||||
}
|
||||
option.PutCallRatio=(double)option.Volume/(double)callOption.Volume;
|
||||
}
|
||||
else // call options
|
||||
{
|
||||
Option putOption=null;
|
||||
option.PutCallRatio=double.NaN;
|
||||
if(!putOptions.ContainsKey(strikeExpiryKey))
|
||||
{
|
||||
option.CallPutRatio=double.NaN;
|
||||
continue;
|
||||
}
|
||||
putOption=putOptions[strikeExpiryKey];
|
||||
if(0==putOption.Volume)
|
||||
{
|
||||
option.CallPutRatio=double.NaN;
|
||||
continue;
|
||||
}
|
||||
option.CallPutRatio=(double)option.Volume/(double)putOption.Volume;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// *******************************************************************************************************************************************************************
|
||||
|
||||
public enum OptionTypeEnum { CallOption, PutOption };
|
||||
public class Options : List<Option>
|
||||
{
|
||||
public Options()
|
||||
{
|
||||
}
|
||||
public Options(List<Option> options)
|
||||
{
|
||||
foreach(Option option in options)Add(option);
|
||||
}
|
||||
}
|
||||
[Serializable]
|
||||
public class Option
|
||||
{
|
||||
private MoneyType moneyType = new MoneyType();
|
||||
public DateTime Expiration { get; set; }
|
||||
public String Symbol { get; set; }
|
||||
public OptionTypeEnum Type { get; set; }
|
||||
public double Strike { get; set; }
|
||||
public double PutCallRatio{get;set;}
|
||||
public double CallPutRatio{get;set;}
|
||||
public Double Ratio
|
||||
{
|
||||
get
|
||||
{
|
||||
if(Type.Equals(OptionTypeEnum.CallOption))return CallPutRatio;
|
||||
return PutCallRatio;
|
||||
}
|
||||
}
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return (Symbol+Expiration.ToShortDateString()+Utility.FormatNumber(Strike,2)+(int)Type).GetHashCode();
|
||||
}
|
||||
public double Last { get; set; }
|
||||
public double Change { get; set; }
|
||||
public double Bid { get; set; }
|
||||
public double Ask { get; set; }
|
||||
public long Volume { get; set; }
|
||||
public double OpenInterest { get; set; }
|
||||
public double OptionValue { get; set; }
|
||||
public DateTime Modified { get; set; }
|
||||
public MoneyType MoneyType
|
||||
{
|
||||
get { return moneyType; }
|
||||
set { moneyType = value; }
|
||||
}
|
||||
public String MoneyTypeAsString { get { return MoneyType.ToString(); } }
|
||||
public int DaysToExpiration
|
||||
{
|
||||
get
|
||||
{
|
||||
return new DateGenerator().DaysBetween(Expiration, DateTime.Now);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
23
MarketData/MarketDataLib/MarketDataModel/ParityElement.cs
Executable file
23
MarketData/MarketDataLib/MarketDataModel/ParityElement.cs
Executable 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
107
MarketData/MarketDataLib/MarketDataModel/Portfolio.cs
Executable file
107
MarketData/MarketDataLib/MarketDataModel/Portfolio.cs
Executable 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
172
MarketData/MarketDataLib/MarketDataModel/PortfolioTrade.cs
Executable file
172
MarketData/MarketDataLib/MarketDataModel/PortfolioTrade.cs
Executable file
@@ -0,0 +1,172 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
using MarketData.DataAccess;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class LotAggregator
|
||||
{
|
||||
private LotAggregator()
|
||||
{
|
||||
}
|
||||
// combine multipe trades that share a common date, side, and price
|
||||
// This is used specifically for the trade indicators in the Bollinger bands.
|
||||
public static PortfolioTrades CombineLots(List<PortfolioTrade> portfolioTrades)
|
||||
{
|
||||
Dictionary<String,PortfolioTrade> lots=new Dictionary<String,PortfolioTrade>();
|
||||
if (null == portfolioTrades||0==portfolioTrades.Count) return null;
|
||||
for(int index=0;index<portfolioTrades.Count;index++)
|
||||
{
|
||||
PortfolioTrade portfolioTrade=portfolioTrades[index];
|
||||
String key="";
|
||||
if(portfolioTrade.BuySell.Equals("B"))key=portfolioTrade.BuySell+portfolioTrade.TradeDate.Date.ToShortDateString()+"-"+Utility.FormatNumber(portfolioTrade.Price,3);
|
||||
else key=portfolioTrade.BuySell+portfolioTrade.TradeDate.Date.ToShortDateString()+"-"+Utility.FormatNumber(portfolioTrade.SellPrice,3);
|
||||
if(!lots.ContainsKey(key)){lots.Add(key,portfolioTrade);}
|
||||
else
|
||||
{
|
||||
PortfolioTrade tradeLot=lots[key];
|
||||
tradeLot.Shares+=portfolioTrade.Shares;
|
||||
}
|
||||
}
|
||||
PortfolioTrades combinedLots=new PortfolioTrades(lots.Values.OrderBy(x=>x.TradeDate).ToList());
|
||||
return combinedLots;
|
||||
}
|
||||
}
|
||||
// *********************************************************************************************************************************************************
|
||||
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; }
|
||||
}
|
||||
|
||||
public virtual NVPCollection ToNVPCollection()
|
||||
{
|
||||
NVPCollection nvpCollection=new NVPCollection();
|
||||
nvpCollection.Add(new NVP("TradeId",TradeId.ToString()));
|
||||
if(null!=Symbol)nvpCollection.Add(new NVP("Symbol",Symbol.ToString()));
|
||||
nvpCollection.Add(new NVP("TradeDate",TradeDate.ToString()));
|
||||
nvpCollection.Add(new NVP("Shares",Shares.ToString()));
|
||||
nvpCollection.Add(new NVP("Commission",Commission.ToString()));
|
||||
if(null!=BuySell)nvpCollection.Add(new NVP("BuySell",BuySell.ToString()));
|
||||
if(null!=Account)nvpCollection.Add(new NVP("Account",Account.ToString()));
|
||||
if(null!=Status)nvpCollection.Add(new NVP("Status",Status.ToString()));
|
||||
nvpCollection.Add(new NVP("SellPrice",SellPrice.ToString()));
|
||||
nvpCollection.Add(new NVP("SellDate",SellDate.ToString()));
|
||||
nvpCollection.Add(new NVP("Price",Price.ToString()));
|
||||
return nvpCollection;
|
||||
}
|
||||
|
||||
public static PortfolioTrade FromNVPCollection(NVPCollection nvpCollection)
|
||||
{
|
||||
PortfolioTrade portfolioTrade=new PortfolioTrade();
|
||||
|
||||
NVPDictionary nvpDictionary=nvpCollection.ToDictionary();
|
||||
portfolioTrade.TradeId=nvpDictionary["TradeId"].Get<int>();
|
||||
portfolioTrade.Symbol=nvpDictionary["Symbol"].Get<String>();
|
||||
portfolioTrade.TradeDate=nvpDictionary["TradeDate"].Get<DateTime>();
|
||||
portfolioTrade.Shares=nvpDictionary["Shares"].Get<double>();
|
||||
portfolioTrade.Commission=nvpDictionary["Commission"].Get<double>();
|
||||
if(nvpDictionary.ContainsKey("BuySell"))portfolioTrade.BuySell=nvpDictionary["BuySell"].Get<String>();
|
||||
if(nvpDictionary.ContainsKey("Account"))portfolioTrade.Account=nvpDictionary["Account"].Get<String>();
|
||||
if(nvpDictionary.ContainsKey("Status"))portfolioTrade.Status=nvpDictionary["Status"].Get<String>();
|
||||
portfolioTrade.SellPrice=nvpDictionary["SellPrice"].Get<double>();
|
||||
portfolioTrade.SellDate=nvpDictionary["SellDate"].Get<DateTime>();
|
||||
portfolioTrade.Price=nvpDictionary["Price"].Get<double>();
|
||||
return portfolioTrade;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
297
MarketData/MarketDataLib/MarketDataModel/PortfolioTrades.cs
Executable file
297
MarketData/MarketDataLib/MarketDataModel/PortfolioTrades.cs
Executable file
@@ -0,0 +1,297 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
using MarketData.DataAccess;
|
||||
using MarketData.Generator;
|
||||
|
||||
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 double GetWeightAdjustedDividendYield()
|
||||
{
|
||||
PortfolioTrades portfolioTrades=new PortfolioTrades((from PortfolioTrade portfolioTrade in this where portfolioTrade.IsOpen select portfolioTrade).ToList());
|
||||
double totalExposure=portfolioTrades.Sum(x=>x.Exposure());
|
||||
double weightAdjustedYield=double.NaN;
|
||||
foreach(PortfolioTrade portfolioTrade in portfolioTrades)
|
||||
{
|
||||
Price price=new Price();
|
||||
price.Close=portfolioTrade.Price;
|
||||
price.Date=DateTime.Now;
|
||||
double dividendYield=DividendHistoryGenerator.GetDividendYield(portfolioTrade.Symbol,price);
|
||||
if(double.IsNaN(dividendYield))continue;
|
||||
if(double.IsNaN(weightAdjustedYield))weightAdjustedYield=0.00;
|
||||
weightAdjustedYield+=dividendYield*((portfolioTrade.Exposure()/totalExposure));
|
||||
}
|
||||
return weightAdjustedYield;
|
||||
}
|
||||
public List<String> Symbols
|
||||
{
|
||||
get
|
||||
{
|
||||
List<String> symbols=new List<String>();
|
||||
foreach(PortfolioTrade portfolioTrade in this) symbols.Add(portfolioTrade.Symbol);
|
||||
symbols=symbols.Distinct().ToList();
|
||||
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()
|
||||
{
|
||||
return this.Min(x => x.TradeDate);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
// Get trades that are open "asof" this date. This does not mean trades that were purchased on this date. This means trades that were in an open status on this date.
|
||||
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;
|
||||
}
|
||||
// Get trades that were sold ON THIS DATE
|
||||
public PortfolioTrades GetClosedTradesOn(DateTime date)
|
||||
{
|
||||
PortfolioTrades closedTrades=new PortfolioTrades();
|
||||
foreach(PortfolioTrade portfolioTrade in this)
|
||||
{
|
||||
if(!Utility.Epoch.Equals(portfolioTrade.SellDate) && portfolioTrade.SellDate.Equals(date))
|
||||
{
|
||||
closedTrades.Add(portfolioTrade);
|
||||
}
|
||||
}
|
||||
return closedTrades;
|
||||
}
|
||||
public static List<DateTime> GetOpenTradeDates()
|
||||
{
|
||||
List<DateTime> openTradeDates = new List<DateTime>();
|
||||
try
|
||||
{
|
||||
PortfolioTrades portfolioTrades = PortfolioDA.GetTrades();
|
||||
DateGenerator dateGenerator = new DateGenerator();
|
||||
DateTime minTradeDate = PortfolioDA.GetMinTradeDate();
|
||||
DateTime maxTradeDate = PricingDA.GetLatestDate(); // use the latest date for which we have pricing information
|
||||
List<DateTime> historicalDates = PricingDA.GetPricingDates(minTradeDate);
|
||||
foreach (DateTime historicalDate in historicalDates)
|
||||
{
|
||||
PortfolioTrades trades = portfolioTrades.GetOpenTradesOn(historicalDate);
|
||||
if (null == trades || 0 == trades.Count) continue;
|
||||
openTradeDates.Add(historicalDate);
|
||||
}
|
||||
return openTradeDates;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
MDTrace.WriteLine(LogLevel.DEBUG, exception);
|
||||
return openTradeDates;
|
||||
}
|
||||
finally
|
||||
{
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
public bool CheckPricingOn(DateTime date)
|
||||
{
|
||||
return PricingDA.CheckPricingOn(Symbols, date);
|
||||
}
|
||||
|
||||
// Returns a simple gain/loss which does not include any dividend distributions.
|
||||
// portfolio trades should be a collection of distinct symbols
|
||||
public double? GetGainLoss(Price price)
|
||||
{
|
||||
double? gainLoss=null;
|
||||
List<String> symbols=(from PortfolioTrade portfolioTrade in this select portfolioTrade.Symbol).Distinct().ToList();
|
||||
PortfolioTrades openTrades=this.GetOpenTradesOn(DateTime.Now);
|
||||
if(1!=symbols.Count) return null;
|
||||
foreach(PortfolioTrade portfolioTrade in this)
|
||||
{
|
||||
if(null==gainLoss)
|
||||
{
|
||||
gainLoss=GetMarketValue(price,portfolioTrade)-GetExposure(price,portfolioTrade);
|
||||
}
|
||||
else
|
||||
{
|
||||
gainLoss+=(GetMarketValue(price,portfolioTrade)-GetExposure(price,portfolioTrade));
|
||||
}
|
||||
}
|
||||
return gainLoss;
|
||||
}
|
||||
private static double? GetMarketValue(Price price,PortfolioTrade portfolioTrade)
|
||||
{
|
||||
if(null==price) return null;
|
||||
if(price.Date<portfolioTrade.TradeDate) return null;
|
||||
if(!portfolioTrade.SellDate.Equals(Utility.Epoch)&&price.Date>portfolioTrade.SellDate) return null;
|
||||
return portfolioTrade.Shares*price.Close;
|
||||
}
|
||||
private static double? GetExposure(Price price,PortfolioTrade portfolioTrade)
|
||||
{
|
||||
if(null==price) return null;
|
||||
if(price.Date<portfolioTrade.TradeDate) return null;
|
||||
if(!portfolioTrade.SellDate.Equals(Utility.Epoch)&&price.Date>portfolioTrade.SellDate) return null;
|
||||
return portfolioTrade.Shares*portfolioTrade.Price;
|
||||
}
|
||||
|
||||
// Collections
|
||||
|
||||
public NVPCollections ToNVPCollections()
|
||||
{
|
||||
NVPCollections nvpCollections=new NVPCollections();
|
||||
foreach(PortfolioTrade portfolioTrade in this)
|
||||
{
|
||||
nvpCollections.Add(portfolioTrade.ToNVPCollection());
|
||||
}
|
||||
return nvpCollections;
|
||||
}
|
||||
public static PortfolioTrades FromNVPCollections(NVPCollections nvpCollections)
|
||||
{
|
||||
PortfolioTrades portfolioTrades=new PortfolioTrades();
|
||||
foreach(NVPCollection nvpCollection in nvpCollections)
|
||||
{
|
||||
portfolioTrades.Add(PortfolioTrade.FromNVPCollection(nvpCollection));
|
||||
}
|
||||
return portfolioTrades;
|
||||
}
|
||||
}
|
||||
}
|
||||
25
MarketData/MarketDataLib/MarketDataModel/PositionWithDescription.cs
Executable file
25
MarketData/MarketDataLib/MarketDataModel/PositionWithDescription.cs
Executable file
@@ -0,0 +1,25 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
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;}
|
||||
}
|
||||
}
|
||||
22
MarketData/MarketDataLib/MarketDataModel/PremarketElement.cs
Executable file
22
MarketData/MarketDataLib/MarketDataModel/PremarketElement.cs
Executable file
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
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()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
24
MarketData/MarketDataLib/MarketDataModel/PriceIndex.cs
Executable file
24
MarketData/MarketDataLib/MarketDataModel/PriceIndex.cs
Executable file
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
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()
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
462
MarketData/MarketDataLib/MarketDataModel/Prices.cs
Executable file
462
MarketData/MarketDataLib/MarketDataModel/Prices.cs
Executable file
@@ -0,0 +1,462 @@
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
// 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 DateTime MaxDate()
|
||||
{
|
||||
return this.Max(x=>x.Date);
|
||||
}
|
||||
public DateTime MinDate()
|
||||
{
|
||||
return this.Min(x=>x.Date);
|
||||
}
|
||||
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 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[] GetVolume()
|
||||
{
|
||||
float[] volumeArray=new float[Count];
|
||||
for(int index=0;index<Count;index++)
|
||||
{
|
||||
volumeArray[index]=(float)this[index].Volume;
|
||||
}
|
||||
return volumeArray;
|
||||
}
|
||||
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 + 5)) // pad the months by 5
|
||||
{
|
||||
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);
|
||||
if(startDate>asof)startDate = dateGenerator.GetPrevMonthStart(asof); // if start date winds up > asof on account of a weekend or holiday then fall back a further month
|
||||
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
|
||||
{
|
||||
public enum PriceSource{Other=0,BigCharts=1,Yahoo=2,Fidelity=3,Google=4};
|
||||
private String symbol;
|
||||
private DateTime date;
|
||||
private double open;
|
||||
private double high;
|
||||
private double low;
|
||||
private double close;
|
||||
private long volume;
|
||||
private double adjClose;
|
||||
private double prevClose; // !!IMPORTANT we don't store this nor do we consider this when evaluating a valid price.
|
||||
private PriceSource source;
|
||||
public Price()
|
||||
{
|
||||
}
|
||||
public Price(Price price)
|
||||
{
|
||||
this.Symbol=price.Symbol;
|
||||
this.Date=price.Date;
|
||||
this.Open=price.Open;
|
||||
this.High=price.High;
|
||||
this.Low=price.Low;
|
||||
this.Close=price.Close;
|
||||
this.Volume=price.Volume;
|
||||
this.AdjClose=price.AdjClose;
|
||||
this.PrevClose=price.PrevClose;
|
||||
this.Source=price.Source;
|
||||
}
|
||||
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;
|
||||
clonePrice.PrevClose=PrevClose;
|
||||
clonePrice.Source=Source;
|
||||
return clonePrice;
|
||||
}
|
||||
public PriceSource Source
|
||||
{
|
||||
get{return source;}
|
||||
set{source=value;}
|
||||
}
|
||||
public String SourceAsString()
|
||||
{
|
||||
switch(Source)
|
||||
{
|
||||
case PriceSource.Other :
|
||||
return "Other";
|
||||
case PriceSource.BigCharts :
|
||||
return "BigCharts";
|
||||
case PriceSource.Yahoo :
|
||||
return "Yahoo";
|
||||
case PriceSource.Fidelity :
|
||||
return "Fidelity";
|
||||
case PriceSource.Google :
|
||||
return "Google";
|
||||
default :
|
||||
return Constants.CONST_QUESTION;
|
||||
}
|
||||
}
|
||||
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 double PrevClose
|
||||
{
|
||||
get { return prevClose; }
|
||||
set { prevClose = 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 "Symbol,Date,Open,High,Low,Close,Volume,Adj Close,Source"; } // ,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)).Append(",");
|
||||
sb.Append(SourceAsString());
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
454
MarketData/MarketDataLib/MarketDataModel/Prices.cs.bak
Executable file
454
MarketData/MarketDataLib/MarketDataModel/Prices.cs.bak
Executable file
@@ -0,0 +1,454 @@
|
||||
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 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);
|
||||
}
|
||||
}
|
||||
// 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 DateTime MaxDate()
|
||||
{
|
||||
return this.Max(x=>x.Date);
|
||||
}
|
||||
public DateTime MinDate()
|
||||
{
|
||||
return this.Min(x=>x.Date);
|
||||
}
|
||||
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 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[] GetVolume()
|
||||
{
|
||||
float[] volumeArray=new float[Count];
|
||||
for(int index=0;index<Count;index++)
|
||||
{
|
||||
volumeArray[index]=(float)this[index].Volume;
|
||||
}
|
||||
return volumeArray;
|
||||
}
|
||||
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 + 5)) // pad the months by 5
|
||||
{
|
||||
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);
|
||||
if(startDate>asof)startDate = dateGenerator.GetPrevMonthStart(asof); // if start date winds up > asof on account of a weekend or holiday then fall back a further month
|
||||
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
|
||||
{
|
||||
public enum PriceSource{Other=0,BigCharts=1,Yahoo=2,Fidelity=3,Google=4};
|
||||
private String symbol;
|
||||
private DateTime date;
|
||||
private double open;
|
||||
private double high;
|
||||
private double low;
|
||||
private double close;
|
||||
private long volume;
|
||||
private double adjClose;
|
||||
private PriceSource source;
|
||||
public Price()
|
||||
{
|
||||
}
|
||||
public Price(Price price)
|
||||
{
|
||||
this.Symbol=price.Symbol;
|
||||
this.Date=price.Date;
|
||||
this.Open=price.Open;
|
||||
this.High=price.High;
|
||||
this.Low=price.Low;
|
||||
this.Close=price.Close;
|
||||
this.Volume=price.Volume;
|
||||
this.AdjClose=price.AdjClose;
|
||||
this.Source=price.Source;
|
||||
}
|
||||
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;
|
||||
clonePrice.Source=Source;
|
||||
return clonePrice;
|
||||
}
|
||||
public PriceSource Source
|
||||
{
|
||||
get{return source;}
|
||||
set{source=value;}
|
||||
}
|
||||
public String SourceAsString()
|
||||
{
|
||||
switch(Source)
|
||||
{
|
||||
case PriceSource.Other :
|
||||
return "Other";
|
||||
case PriceSource.BigCharts :
|
||||
return "BigCharts";
|
||||
case PriceSource.Yahoo :
|
||||
return "Yahoo";
|
||||
case PriceSource.Fidelity :
|
||||
return "Fidelity";
|
||||
case PriceSource.Google :
|
||||
return "Google";
|
||||
default :
|
||||
return Constants.CONST_QUESTION;
|
||||
}
|
||||
}
|
||||
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 "Symbol,Date,Open,High,Low,Close,Volume,Adj Close,Source"; } // ,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)).Append(",");
|
||||
sb.Append(SourceAsString());
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
39
MarketData/MarketDataLib/MarketDataModel/PricesByDate.cs
Executable file
39
MarketData/MarketDataLib/MarketDataModel/PricesByDate.cs
Executable file
@@ -0,0 +1,39 @@
|
||||
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)
|
||||
{
|
||||
if(Utility.IsEpoch(key))return;
|
||||
base.Add(key,price);
|
||||
if(key>maxDate) maxDate=key;
|
||||
// if(!Utility.IsEpoch(minDate) && key<minDate)minDate=key;
|
||||
if(Utility.IsEpoch(minDate))minDate=key;
|
||||
else if(key<minDate)minDate=key;
|
||||
//else if(Utility.IsEpoch(minDate)) minDate=key;
|
||||
//else if(key<minDate && !Utility.IsEpoch(key)) minDate=key;
|
||||
}
|
||||
public DateTime MaxDate
|
||||
{
|
||||
get { return maxDate; }
|
||||
}
|
||||
public DateTime MinDate
|
||||
{
|
||||
get { return minDate; }
|
||||
}
|
||||
}
|
||||
}
|
||||
95
MarketData/MarketDataLib/MarketDataModel/RSICollection.cs
Executable file
95
MarketData/MarketDataLib/MarketDataModel/RSICollection.cs
Executable file
@@ -0,0 +1,95 @@
|
||||
using MarketData.MarketDataModel;
|
||||
using MarketData.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class RSIDictionary : Dictionary<DateTime,RSIElement>
|
||||
{
|
||||
}
|
||||
public class RSICollection : List<RSIElement>
|
||||
{
|
||||
public RSICollection()
|
||||
{
|
||||
}
|
||||
public RSICollection(List<RSIElement> rsiElements)
|
||||
{
|
||||
foreach(RSIElement rsiElement in rsiElements)Add(rsiElement);
|
||||
}
|
||||
public RSICollection Top(int count,int offset=0)
|
||||
{
|
||||
if (count > Count) return null;
|
||||
RSICollection rsiCollection = new RSICollection();
|
||||
for (int index = 0+offset; index<Count&&rsiCollection.Count<count; index++)
|
||||
{
|
||||
rsiCollection.Add(this[index]);
|
||||
}
|
||||
return rsiCollection;
|
||||
}
|
||||
public RSICollection Bottom(int count,int offset=0)
|
||||
{
|
||||
if (count > Count) return null;
|
||||
RSICollection rsiCollection = new RSICollection();
|
||||
for (int index = Count-1-offset; index>=0 && rsiCollection.Count<count; index--)
|
||||
{
|
||||
rsiCollection.Add(this[index]);
|
||||
}
|
||||
return rsiCollection;
|
||||
}
|
||||
public RSIDictionary ToDictionary()
|
||||
{
|
||||
RSIDictionary dictionary=new RSIDictionary();
|
||||
foreach(RSIElement rsiElement in this)dictionary.Add(rsiElement.Date,rsiElement);
|
||||
return dictionary;
|
||||
}
|
||||
public double AverageGain()
|
||||
{
|
||||
double averageGain=(from RSIElement rsiElement in this select rsiElement.Gain).ToList().Sum()/(double)Count;
|
||||
return averageGain;
|
||||
}
|
||||
public double AverageLoss()
|
||||
{
|
||||
double averageLoss=(from RSIElement rsiElement in this select rsiElement.Loss).ToList().Sum()/(double)Count;
|
||||
return averageLoss;
|
||||
}
|
||||
}
|
||||
public class RSIElement
|
||||
{
|
||||
public String Symbol{get;set;}
|
||||
public DateTime Date{get;set;}
|
||||
public double Close{get;set;}
|
||||
public double Change{get;set;}
|
||||
public double Gain{get;set;}
|
||||
public double Loss{get;set;}
|
||||
public double AverageGain{get;set;}
|
||||
public double AverageLoss{get;set;}
|
||||
public double RS{get;set;}
|
||||
public double RSI{get;set;}
|
||||
public int RSIDays{get;set;}
|
||||
public static String Header()
|
||||
{
|
||||
return "Symbol,Date,Close,Change,Gain,Loss,AverageGain,AverageLoss,RS,RSI,RSIDays";
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.Append(Utility.AddQuotes(Symbol)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.DateTimeToStringMMHDDHYYYY(Date))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(Close))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(Change))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(Gain))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(Loss))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(AverageGain))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatCurrency(AverageLoss))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatNumber(RS,3))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatNumber(RSI,3))).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Utility.FormatNumber(RSIDays)));
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
103
MarketData/MarketDataLib/MarketDataModel/ResistanceSupport.cs
Executable file
103
MarketData/MarketDataLib/MarketDataModel/ResistanceSupport.cs
Executable file
@@ -0,0 +1,103 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class ResistanceSupport
|
||||
{
|
||||
private Price price;
|
||||
private double resistance1;
|
||||
private double support1;
|
||||
private double resistance2;
|
||||
private double support2;
|
||||
private double resistance3;
|
||||
private double support3;
|
||||
|
||||
public ResistanceSupport(Price price)
|
||||
{ // calculate pivot points
|
||||
this.price = price;
|
||||
double pivot=(price.Low+price.Close+price.High)/3.00;
|
||||
resistance1=(2.00*pivot)-price.Low;
|
||||
support1=(2.00*pivot)-price.High;
|
||||
resistance2 = pivot + (price.High - price.Low);
|
||||
support2 = pivot - (price.High - price.Low);
|
||||
resistance3 = price.High + 2.00*(pivot-price.Low);
|
||||
support3 = price.Low - 2.00*(price.High - pivot);
|
||||
}
|
||||
public double Resistance1
|
||||
{
|
||||
get { return resistance1; }
|
||||
}
|
||||
public double Support1
|
||||
{
|
||||
get { return support1; }
|
||||
}
|
||||
public double Resistance2
|
||||
{
|
||||
get { return resistance2; }
|
||||
}
|
||||
public double Support2
|
||||
{
|
||||
get { return support2; }
|
||||
}
|
||||
public double Resistance3
|
||||
{
|
||||
get { return resistance3; }
|
||||
}
|
||||
public double Support3
|
||||
{
|
||||
get { return support3; }
|
||||
}
|
||||
public double High
|
||||
{
|
||||
get { return price.High; }
|
||||
}
|
||||
public double Low
|
||||
{
|
||||
get { return price.Low; }
|
||||
}
|
||||
public double Close
|
||||
{
|
||||
get { return price.Close; }
|
||||
}
|
||||
public DateTime Date
|
||||
{
|
||||
get { return price.Date; }
|
||||
}
|
||||
public static string Header
|
||||
{
|
||||
get { return "Symbol,Date,R1,S1,R2,S2,R3,S3,High,Low,Close"; }
|
||||
}
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(price.Symbol).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMHDDHYYYY(price.Date)).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(resistance1)).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(support1)).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(resistance2)).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(support2)).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(resistance3)).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(support3)).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(price.High)).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(price.Low)).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(price.Close));
|
||||
return sb.ToString();
|
||||
}
|
||||
public string ToStringLong()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("******** R E S I S T A N C E A N D S U P P O R T ****").Append("\n");
|
||||
sb.Append("R3:").Append(Utility.FormatCurrency(resistance3)).Append("\n");
|
||||
sb.Append("R2:").Append(Utility.FormatCurrency(resistance2)).Append("\n");
|
||||
sb.Append("R1:").Append(Utility.FormatCurrency(resistance1)).Append("\n");
|
||||
sb.Append("***************************************").Append("\n");
|
||||
sb.Append("S1:").Append(Utility.FormatCurrency(support1)).Append("\n");
|
||||
sb.Append("S2:").Append(Utility.FormatCurrency(support2)).Append("\n");
|
||||
sb.Append("S3:").Append(Utility.FormatCurrency(support3)).Append("\n");
|
||||
sb.Append("*************************************************************");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
72
MarketData/MarketDataLib/MarketDataModel/ReturnItem.cs
Executable file
72
MarketData/MarketDataLib/MarketDataModel/ReturnItem.cs
Executable file
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class ReturnItemComparerDesc : IComparer<ReturnItem>
|
||||
{
|
||||
public int Compare(ReturnItem r1, ReturnItem r2)
|
||||
{
|
||||
if (r1.Date > r2.Date) return -1;
|
||||
else if (r1.Date < r2.Date) return 1;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
public class ReturnItems : List<ReturnItem>
|
||||
{
|
||||
public ReturnItems()
|
||||
{
|
||||
}
|
||||
public ReturnItems(TimeSeriesCollection timeSeriesCollection)
|
||||
{
|
||||
for (int index = 0; index < timeSeriesCollection.Count; index++)
|
||||
{
|
||||
TimeSeriesElement timeSeriesElement = timeSeriesCollection[index];
|
||||
ReturnItem returnItem = new ReturnItem();
|
||||
returnItem.Date = timeSeriesElement.AsOf;
|
||||
returnItem.Value = timeSeriesElement.Value;
|
||||
Add(returnItem);
|
||||
}
|
||||
CalculateReturns();
|
||||
}
|
||||
public void CalculateReturns()
|
||||
{
|
||||
Sort(new ReturnItemComparerDesc());
|
||||
for (int index = Count - 2; index >= 0; index--)
|
||||
{
|
||||
ReturnItem returnItem = this[index];
|
||||
double currentPrice = this[index].Value;
|
||||
double prevPrice = this[index + 1].Value;
|
||||
if (prevPrice == 0.00) returnItem.Return = 0.00;
|
||||
else returnItem.Return = ((currentPrice - prevPrice) / Math.Abs(prevPrice));
|
||||
}
|
||||
}
|
||||
public void SortItems()
|
||||
{
|
||||
Sort(new ReturnItemComparerDesc());
|
||||
}
|
||||
public float[] ToFloat()
|
||||
{
|
||||
List<float> list = new List<float>();
|
||||
for (int index = 0; index < Count-1; index++) // the last item will always be zero
|
||||
{
|
||||
list.Add((float)this[index].Return);
|
||||
}
|
||||
return list.ToArray();
|
||||
}
|
||||
}
|
||||
public class ReturnItem
|
||||
{
|
||||
public ReturnItem()
|
||||
{
|
||||
}
|
||||
public ReturnItem(DateTime date, double value)
|
||||
{
|
||||
Date = date;
|
||||
Value = value;
|
||||
}
|
||||
public DateTime Date { get; set; }
|
||||
public double Value { get; set; }
|
||||
public double Return { get; set; }
|
||||
}
|
||||
}
|
||||
104
MarketData/MarketDataLib/MarketDataModel/SECFiling.cs
Executable file
104
MarketData/MarketDataLib/MarketDataModel/SECFiling.cs
Executable file
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class SEC13Info
|
||||
{
|
||||
public SEC13Info()
|
||||
{
|
||||
SEC13=false;
|
||||
}
|
||||
public String Symbol{get;set;}
|
||||
public bool SEC13{get;set;}
|
||||
public DateTime MostRecentFilingDate{get;set;}
|
||||
public int Filings{get;set;}
|
||||
}
|
||||
public class SECFilings : List<SECFiling>
|
||||
{
|
||||
public SECFilings()
|
||||
{
|
||||
}
|
||||
public SECFilings(List<SECFiling> secFilings)
|
||||
{
|
||||
foreach(SECFiling secFiling in secFilings)Add(secFiling);
|
||||
}
|
||||
public SECFilings Distinct()
|
||||
{
|
||||
Dictionary<String,SECFiling> uniqueSECFilings=new Dictionary<String,SECFiling>();
|
||||
foreach(SECFiling secFiling in this)
|
||||
{
|
||||
String key=secFiling.Symbol+secFiling.SECAccessionNumber+secFiling.Sequence.ToString()+secFiling.FilingDate.ToShortDateString();
|
||||
if(!uniqueSECFilings.ContainsKey(key))uniqueSECFilings.Add(key,secFiling);
|
||||
}
|
||||
return new SECFilings(new List<SECFiling>(uniqueSECFilings.Values));
|
||||
}
|
||||
}
|
||||
public class SECFiling
|
||||
{
|
||||
private int sequence;
|
||||
private String secAccessionNumber;
|
||||
private String symbol;
|
||||
private DateTime filingDate;
|
||||
private String form;
|
||||
private String formText;
|
||||
private String description;
|
||||
private String fileNumber;
|
||||
private String secFilingUrl;
|
||||
|
||||
public SECFiling()
|
||||
{
|
||||
}
|
||||
public String SECAccessionNumber
|
||||
{
|
||||
get { return secAccessionNumber; }
|
||||
set { secAccessionNumber = value; }
|
||||
}
|
||||
public int Sequence
|
||||
{
|
||||
get { return sequence; }
|
||||
set { sequence = value; }
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public String Form
|
||||
{
|
||||
get { return form; }
|
||||
set { form = value; }
|
||||
}
|
||||
public String FormText
|
||||
{
|
||||
get { return formText; }
|
||||
set { formText = value; }
|
||||
}
|
||||
public int FormTextLength
|
||||
{
|
||||
get { return formText.Length; }
|
||||
}
|
||||
public String Description
|
||||
{
|
||||
get { return description; }
|
||||
set { description = value; }
|
||||
}
|
||||
public DateTime FilingDate
|
||||
{
|
||||
get { return filingDate; }
|
||||
set { filingDate = value; }
|
||||
}
|
||||
public String FileNumber
|
||||
{
|
||||
get { return fileNumber; }
|
||||
set { fileNumber = value; }
|
||||
}
|
||||
public String SecFilingUrl
|
||||
{
|
||||
get { return secFilingUrl; }
|
||||
set { secFilingUrl = value; }
|
||||
}
|
||||
}
|
||||
}
|
||||
84
MarketData/MarketDataLib/MarketDataModel/Securities.cs
Executable file
84
MarketData/MarketDataLib/MarketDataModel/Securities.cs
Executable file
@@ -0,0 +1,84 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
class SecurityList : List<Security>
|
||||
{
|
||||
public SecurityList()
|
||||
{
|
||||
}
|
||||
public bool LoadSecurities(String strPathFileName)
|
||||
{
|
||||
StreamReader streamReader = File.OpenText(strPathFileName);
|
||||
String strLine;
|
||||
|
||||
while (null != (strLine = streamReader.ReadLine()))
|
||||
{
|
||||
String symbol;
|
||||
String name;
|
||||
char ch;
|
||||
char leadChar;
|
||||
int index = 0;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (index = 0; index < strLine.Length; index++)
|
||||
{
|
||||
ch = strLine[index];
|
||||
if (ch == ',') break;
|
||||
sb.Append(ch);
|
||||
}
|
||||
index++;
|
||||
symbol = sb.ToString();
|
||||
sb = new StringBuilder();
|
||||
leadChar = ch = strLine[index];
|
||||
if (leadChar == '"')
|
||||
{
|
||||
index++;
|
||||
while (index < strLine.Length && leadChar != (ch = strLine[index]))
|
||||
{
|
||||
sb.Append(ch);
|
||||
index++;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
while (index < strLine.Length)
|
||||
{
|
||||
ch = strLine[index++];
|
||||
sb.Append(ch);
|
||||
}
|
||||
}
|
||||
name = sb.ToString();
|
||||
Security security = new Security(symbol, name);
|
||||
Add(security);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
class Security
|
||||
{
|
||||
private String symbol;
|
||||
private String name;
|
||||
|
||||
public Security()
|
||||
{
|
||||
}
|
||||
public Security(String symbol, String name)
|
||||
{
|
||||
this.symbol = symbol;
|
||||
this.name = name;
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public String Name
|
||||
{
|
||||
get { return name; }
|
||||
set { name = value; }
|
||||
}
|
||||
}
|
||||
}
|
||||
43
MarketData/MarketDataLib/MarketDataModel/Sentiment.cs
Executable file
43
MarketData/MarketDataLib/MarketDataModel/Sentiment.cs
Executable file
@@ -0,0 +1,43 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class HeadlinesSentiment : List<HeadlineSentiment>
|
||||
{
|
||||
public HeadlinesSentiment()
|
||||
{
|
||||
}
|
||||
public HeadlinesSentiment(List<HeadlineSentiment> headlinesSentiment)
|
||||
{
|
||||
foreach(HeadlineSentiment headlineSentiment in headlinesSentiment)Add(headlineSentiment);
|
||||
}
|
||||
}
|
||||
public class HeadlineSentiment : Headline
|
||||
{
|
||||
public HeadlineSentiment(Headline headline,String sentiment)
|
||||
: base(headline)
|
||||
{
|
||||
Sentiment=sentiment;
|
||||
}
|
||||
public HeadlineSentiment(String headline,String sentiment)
|
||||
: base(new Headline())
|
||||
{
|
||||
Sentiment=sentiment;
|
||||
this.Entry=headline;
|
||||
}
|
||||
public String Sentiment{get;set;}
|
||||
//public Brush CurrentPriceColor
|
||||
//{
|
||||
// get
|
||||
// {
|
||||
// if(!IsActivePosition)return BrushCollection.GetContextBrush(BrushCollection.BrushColor.Blue);
|
||||
// if(priceChangeDirection>0)return BrushCollection.GetContextBrush(BrushCollection.BrushColor.Green);
|
||||
// else if(priceChangeDirection<0)return BrushCollection.GetContextBrush(BrushCollection.BrushColor.Red);
|
||||
// else return BrushCollection.GetContextBrush(BrushCollection.BrushColor.Black);
|
||||
// }
|
||||
//}
|
||||
}
|
||||
}
|
||||
97
MarketData/MarketDataLib/MarketDataModel/SharpeRatioModel.cs
Executable file
97
MarketData/MarketDataLib/MarketDataModel/SharpeRatioModel.cs
Executable file
@@ -0,0 +1,97 @@
|
||||
using MarketData.Numerical;
|
||||
using MarketData.ValueAtRisk;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class PortfolioHoldingsWithSharpeRatio : List<PortfolioHoldingWithSharpeRatio>
|
||||
{
|
||||
private PortfolioHoldingsWithSharpeRatio()
|
||||
{
|
||||
}
|
||||
public PortfolioHoldingsWithSharpeRatio(List<PortfolioHoldingWithSharpeRatio> portfolioHoldingsWithSharpeRatio)
|
||||
{
|
||||
TotalSharpeRatio = 0.00;
|
||||
if (null == portfolioHoldingsWithSharpeRatio) return;
|
||||
foreach (PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in portfolioHoldingsWithSharpeRatio) Add(portfolioHoldingWithSharpeRatio);
|
||||
Exposure = (from PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this select portfolioHoldingWithSharpeRatio.Exposure).Sum();
|
||||
TotalSharpeRatio = (from PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this select portfolioHoldingWithSharpeRatio.WeightAdjustedSharpeRatio).Sum();
|
||||
}
|
||||
public PortfolioHoldingsWithSharpeRatio(PortfolioHoldings portfolioHoldings,DateTime analysisDate)
|
||||
{
|
||||
TotalSharpeRatio = 0.00;
|
||||
if (null == portfolioHoldings) return;
|
||||
foreach (PortfolioHolding portfolioHolding in portfolioHoldings) Add(new PortfolioHoldingWithSharpeRatio(portfolioHolding));
|
||||
Exposure = (from PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this select portfolioHoldingWithSharpeRatio.Exposure).Sum();
|
||||
foreach (PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this)
|
||||
{
|
||||
SharpeRatioGenerator.GenerateSharpeRatio(portfolioHoldingWithSharpeRatio, analysisDate, 12);
|
||||
}
|
||||
foreach (PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this)
|
||||
{
|
||||
portfolioHoldingWithSharpeRatio.WeightExp = portfolioHoldingWithSharpeRatio.Exposure / Exposure;
|
||||
portfolioHoldingWithSharpeRatio.WeightAdjustedSharpeRatio = portfolioHoldingWithSharpeRatio.WeightExp * portfolioHoldingWithSharpeRatio.SharpeRatio;
|
||||
}
|
||||
TotalSharpeRatio = (from PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this select portfolioHoldingWithSharpeRatio.WeightAdjustedSharpeRatio).Sum();
|
||||
foreach (PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this)
|
||||
{
|
||||
portfolioHoldingWithSharpeRatio.SharpeRatioContribution = portfolioHoldingWithSharpeRatio.WeightAdjustedSharpeRatio / TotalSharpeRatio;
|
||||
}
|
||||
}
|
||||
//public PortfolioHoldingsWithSharpeRatio(PortfolioTrades portfolioTrades, DateTime? analysisDate = null)
|
||||
//{
|
||||
// TotalSharpeRatio = 0.00;
|
||||
|
||||
// if (null == analysisDate) analysisDate = DateTime.Now;
|
||||
// List<MarketDataModel.Position> positions = portfolioTrades.GetPositions(analysisDate.Value);
|
||||
// foreach (MarketDataModel.Position position in positions) Add(new PortfolioHoldingWithSharpeRatio(position));
|
||||
|
||||
// Exposure = (from PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this select portfolioHoldingWithSharpeRatio.Exposure).Sum();
|
||||
// foreach (PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this)
|
||||
// {
|
||||
// SharpeRatioGenerator.GenerateSharpeRatio(portfolioHoldingWithSharpeRatio, analysisDate.Value, 12);
|
||||
// }
|
||||
// foreach (PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this)
|
||||
// {
|
||||
// portfolioHoldingWithSharpeRatio.WeightExp = portfolioHoldingWithSharpeRatio.Exposure / Exposure;
|
||||
// portfolioHoldingWithSharpeRatio.WeightAdjustedSharpeRatio = portfolioHoldingWithSharpeRatio.WeightExp * portfolioHoldingWithSharpeRatio.SharpeRatio;
|
||||
// }
|
||||
// TotalSharpeRatio = (from PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this select portfolioHoldingWithSharpeRatio.WeightAdjustedSharpeRatio).Sum();
|
||||
// foreach (PortfolioHoldingWithSharpeRatio portfolioHoldingWithSharpeRatio in this)
|
||||
// {
|
||||
// portfolioHoldingWithSharpeRatio.SharpeRatioContribution = portfolioHoldingWithSharpeRatio.WeightAdjustedSharpeRatio / TotalSharpeRatio;
|
||||
// }
|
||||
//}
|
||||
public double TotalSharpeRatio { get; set; } // This is the total Sharpe Ration for all positions
|
||||
public double Exposure { get; set; }
|
||||
}
|
||||
public class PortfolioHoldingWithSharpeRatio
|
||||
{
|
||||
private PortfolioHoldingWithSharpeRatio()
|
||||
{
|
||||
}
|
||||
public PortfolioHoldingWithSharpeRatio(MarketDataModel.Position position)
|
||||
{
|
||||
Symbol = position.Symbol;
|
||||
Exposure = position.Exposure;
|
||||
}
|
||||
public PortfolioHoldingWithSharpeRatio(PortfolioHolding portfolioHolding)
|
||||
{
|
||||
Symbol = portfolioHolding.Symbol;
|
||||
Exposure = portfolioHolding.Exposure;
|
||||
}
|
||||
public String Symbol { get; set; }
|
||||
public double Exposure { get; set; }
|
||||
public double WeightExp { get; set; }
|
||||
public double AverageReturn { get; set; }
|
||||
public double RiskPremium { get; set; }
|
||||
public double Volatility { get; set; }
|
||||
public double SharpeRatio { get; set; }
|
||||
public double WeightAdjustedSharpeRatio { get; set; }
|
||||
public double SharpeRatioContribution { get; set; }
|
||||
}
|
||||
}
|
||||
171
MarketData/MarketDataLib/MarketDataModel/Signal.cs
Executable file
171
MarketData/MarketDataLib/MarketDataModel/Signal.cs
Executable file
@@ -0,0 +1,171 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class Signals : List<Signal>
|
||||
{
|
||||
public Signals()
|
||||
{
|
||||
}
|
||||
public Signals(List<Signal> signals)
|
||||
{
|
||||
foreach(Signal signal in signals)Add(signal);
|
||||
}
|
||||
public Signals WeakBuySignals
|
||||
{
|
||||
get
|
||||
{
|
||||
IEnumerable<Signal> list=(from Signal signal in this where signal.SignalIndicator.Equals(Signal.Indicator.WeakBuy) select signal);
|
||||
if(0==list.Count())return new Signals();
|
||||
return new Signals(list.ToList());
|
||||
}
|
||||
}
|
||||
public Signals WeakSellSignals
|
||||
{
|
||||
get
|
||||
{
|
||||
IEnumerable<Signal> list=(from Signal signal in this where signal.SignalIndicator.Equals(Signal.Indicator.WeakSell) select signal);
|
||||
if(0==list.Count())return new Signals();
|
||||
return new Signals(list.ToList());
|
||||
}
|
||||
}
|
||||
public Signals StrongBuySignals
|
||||
{
|
||||
get
|
||||
{
|
||||
IEnumerable<Signal> list=(from Signal signal in this where signal.SignalIndicator.Equals(Signal.Indicator.StrongBuy) select signal);
|
||||
if(0==list.Count())return new Signals();
|
||||
return new Signals(list.ToList());
|
||||
}
|
||||
}
|
||||
public Signals StrongSellSignals
|
||||
{
|
||||
get
|
||||
{
|
||||
IEnumerable<Signal> list=(from Signal signal in this where signal.SignalIndicator.Equals(Signal.Indicator.StrongSell) select signal);
|
||||
if(0==list.Count())return new Signals();
|
||||
return new Signals(list.ToList());
|
||||
}
|
||||
}
|
||||
public Signals CondenseSignals()
|
||||
{
|
||||
Signal currentSignal=null;
|
||||
Signals condensedSignals=new Signals();
|
||||
for(int index=0;index<Count;index++)
|
||||
{
|
||||
Signal signal=this[index];
|
||||
if(0==index)
|
||||
{
|
||||
currentSignal=signal;
|
||||
condensedSignals.Add(signal);
|
||||
}
|
||||
else
|
||||
{
|
||||
if(signal.SignalIndicator.Equals(currentSignal.SignalIndicator))continue;
|
||||
condensedSignals.Add(signal);
|
||||
currentSignal=signal;
|
||||
}
|
||||
}
|
||||
return condensedSignals;
|
||||
}
|
||||
}
|
||||
// *****************************************************************************************************************************************************************
|
||||
public class SignalComparatorByDateDescending:IComparer<Signal>
|
||||
{
|
||||
public int Compare(Signal v1,Signal v2)
|
||||
{
|
||||
return v2.SignalDate.CompareTo(v1.SignalDate);
|
||||
}
|
||||
}
|
||||
// *****************************************************************************************************************************************************************
|
||||
public class Signal
|
||||
{
|
||||
public enum Indicator { StrongBuy, WeakBuy, WeakSell, StrongSell,Neutral };
|
||||
private String ticker;
|
||||
private Indicator indicator;
|
||||
private DateTime signalDate;
|
||||
private String reason;
|
||||
|
||||
public Signal()
|
||||
{
|
||||
}
|
||||
public Signal(String ticker, DateTime signalDate, Indicator indicator)
|
||||
{
|
||||
this.ticker = ticker;
|
||||
this.signalDate = signalDate;
|
||||
this.indicator = indicator;
|
||||
}
|
||||
public String Ticker
|
||||
{
|
||||
get { return ticker; }
|
||||
set { ticker = value; }
|
||||
}
|
||||
public Signal.Indicator SignalIndicator
|
||||
{
|
||||
get { return indicator; }
|
||||
set { indicator = value; }
|
||||
}
|
||||
public String SignalIndicatorString
|
||||
{
|
||||
get
|
||||
{
|
||||
if (indicator == Indicator.StrongBuy) return "SB";
|
||||
else if (indicator == Indicator.WeakBuy) return "WB";
|
||||
else if (indicator == Indicator.WeakSell) return "WS";
|
||||
else if (indicator == Indicator.StrongSell) return "SS";
|
||||
else if (indicator == Indicator.Neutral) return "NE";
|
||||
else return "??";
|
||||
}
|
||||
}
|
||||
public DateTime SignalDate
|
||||
{
|
||||
get { return signalDate; }
|
||||
set { signalDate = value; }
|
||||
}
|
||||
public bool IsWeakBuy()
|
||||
{
|
||||
return Indicator.WeakBuy == indicator;
|
||||
}
|
||||
public bool IsWeakSell()
|
||||
{
|
||||
return Indicator.WeakSell == indicator;
|
||||
}
|
||||
public bool IsStrongBuy()
|
||||
{
|
||||
return Indicator.StrongBuy == indicator;
|
||||
}
|
||||
public bool IsStrongSell()
|
||||
{
|
||||
return Indicator.StrongSell == indicator;
|
||||
}
|
||||
public bool IsSell()
|
||||
{
|
||||
if (IsStrongSell() || IsWeakSell()) return true;
|
||||
return false;
|
||||
}
|
||||
public bool IsBuy()
|
||||
{
|
||||
if (IsStrongBuy() || IsWeakBuy()) return true;
|
||||
return false;
|
||||
}
|
||||
public bool IsNeutral()
|
||||
{
|
||||
return Indicator.Neutral == indicator;
|
||||
}
|
||||
public String Reason
|
||||
{
|
||||
get { return reason; }
|
||||
set { reason = value; }
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(ticker).Append(",").Append(Utility.DateTimeToStringMMSDDSYYYY(signalDate)).Append(",").Append(SignalIndicatorString);
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
52
MarketData/MarketDataLib/MarketDataModel/SignalHolder.cs
Executable file
52
MarketData/MarketDataLib/MarketDataModel/SignalHolder.cs
Executable file
@@ -0,0 +1,52 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class SignHolder
|
||||
{
|
||||
public enum SignValue { Positive, Negative, Undefined };
|
||||
private double currentValue;
|
||||
private double previousValue;
|
||||
|
||||
public SignHolder()
|
||||
{
|
||||
currentValue = previousValue = 0.00;
|
||||
}
|
||||
public void SetValue(double value)
|
||||
{
|
||||
if (value == 0.00)
|
||||
{
|
||||
previousValue = currentValue;
|
||||
return;
|
||||
}
|
||||
previousValue = currentValue;
|
||||
currentValue = value;
|
||||
}
|
||||
public bool SignChange
|
||||
{
|
||||
get
|
||||
{
|
||||
if (previousValue < 0.00 && currentValue > 0.00) return true;
|
||||
if (previousValue > 0.00 && currentValue < 0.00) return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public double PreviousValue
|
||||
{
|
||||
get { return previousValue; }
|
||||
}
|
||||
public double CurrentValue
|
||||
{
|
||||
get { return currentValue; }
|
||||
}
|
||||
public String GetValueString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("[").Append(previousValue).Append("->").Append(currentValue).Append("]");
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
44
MarketData/MarketDataLib/MarketDataModel/Splits.cs
Executable file
44
MarketData/MarketDataLib/MarketDataModel/Splits.cs
Executable file
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class Splits : List<Split>
|
||||
{
|
||||
public Splits()
|
||||
{
|
||||
}
|
||||
public Splits(List<Split> splits)
|
||||
{
|
||||
foreach(Split split in splits)Add(split);
|
||||
}
|
||||
}
|
||||
public class Split
|
||||
{
|
||||
public Split()
|
||||
{
|
||||
Applied=false;
|
||||
}
|
||||
public String Exchange{get;set;}
|
||||
public String Symbol{get;set;}
|
||||
public DateTime EffectiveDate{get;set;}
|
||||
public String StrRatio{get;set;}
|
||||
public double Ratio
|
||||
{
|
||||
get
|
||||
{
|
||||
if(null==StrRatio||!StrRatio.Contains('-'))return double.NaN;
|
||||
String[] elements=StrRatio.Split('-');
|
||||
return double.Parse(elements[1])/double.Parse(elements[0]);
|
||||
}
|
||||
}
|
||||
public bool Applied{get;set;}
|
||||
public DateTime AppliedLeastRecent{get;set;}
|
||||
public DateTime AppliedMostRecent{get;set;}
|
||||
public DateTime Modified{get;set;}
|
||||
public DateTime Created{get;set;}
|
||||
}
|
||||
}
|
||||
75
MarketData/MarketDataLib/MarketDataModel/Statistic.cs
Executable file
75
MarketData/MarketDataLib/MarketDataModel/Statistic.cs
Executable file
@@ -0,0 +1,75 @@
|
||||
//using System;
|
||||
//using System.Collections;
|
||||
//using System.Collections.Generic;
|
||||
//using System.Text;
|
||||
//using MarketData.Numerical;
|
||||
|
||||
//namespace MarketData.MarketDataModel
|
||||
//{
|
||||
// public class Statistic
|
||||
// {
|
||||
// private double meanReturn;
|
||||
// private double volatility;
|
||||
// private double meanPrice;
|
||||
// private double beta;
|
||||
|
||||
// public Statistic()
|
||||
// {
|
||||
// }
|
||||
// public double MeanReturn
|
||||
// {
|
||||
// get { return meanReturn; }
|
||||
// set { meanReturn = value; }
|
||||
// }
|
||||
// public double Volatility
|
||||
// {
|
||||
// get { return volatility; }
|
||||
// set { volatility = value; }
|
||||
// }
|
||||
// public double MeanPrice
|
||||
// {
|
||||
// get { return meanPrice; }
|
||||
// set { meanPrice = value; }
|
||||
// }
|
||||
// public double Beta
|
||||
// {
|
||||
// get { return beta; }
|
||||
// set { beta = value; }
|
||||
// }
|
||||
// public static Statistic GetStatistic(Prices prices, Prices benchmarkPrices)
|
||||
// {
|
||||
// try
|
||||
// {
|
||||
// Statistic statistic = new Statistic();
|
||||
// if (0 == prices.Count || 0 == benchmarkPrices.Count) return null;
|
||||
// float[] returns = prices.GetReturns();
|
||||
// float[] pricesArray = prices.GetPrices();
|
||||
// float[] benchmarkPricesArray = benchmarkPrices.GetPrices();
|
||||
// statistic.MeanReturn = Numerics.Mean(ref returns);
|
||||
// statistic.Volatility = Numerics.Volatility(ref returns);
|
||||
// statistic.MeanPrice = Numerics.Mean(ref pricesArray);
|
||||
// statistic.Beta = Numerics.Beta(ref pricesArray, ref benchmarkPricesArray);
|
||||
// return statistic;
|
||||
// }
|
||||
// catch (Exception exception)
|
||||
// {
|
||||
// MDTrace.WriteLine(LogLevel.DEBUG, exception.ToString());
|
||||
// return null;
|
||||
// }
|
||||
// }
|
||||
|
||||
// public static String Header
|
||||
// {
|
||||
// get { return "AverageReturn,Volatility,MeanPrice,Beta"; }
|
||||
// }
|
||||
// public override String ToString()
|
||||
// {
|
||||
// StringBuilder sb = new StringBuilder();
|
||||
// sb.Append(String.Format("{0:0.00000}", MeanReturn)).Append(",");
|
||||
// sb.Append(String.Format("{0:0.00000}", Volatility)).Append(",");
|
||||
// sb.Append(String.Format("{0:0.00000}", MeanPrice)).Append(",");
|
||||
// sb.Append(String.Format("{0:0.00000}", Beta)); ;
|
||||
// return sb.ToString();
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
115
MarketData/MarketDataLib/MarketDataModel/StickerPrice.cs
Executable file
115
MarketData/MarketDataLib/MarketDataModel/StickerPrice.cs
Executable file
@@ -0,0 +1,115 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
using MySql.Data.MySqlClient;
|
||||
using MarketData.DataAccess;
|
||||
using MarketData.Numerical;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class StickerPrice
|
||||
{
|
||||
private double marginOfSafety = double.NaN;
|
||||
private double marginOfSafety80Pcnt = double.NaN;
|
||||
private double lowPE = double.NaN;
|
||||
private double trailingPE = double.NaN;
|
||||
private double averageLowTrailing = double.NaN;
|
||||
private double currentStockEstimatePrice = double.NaN;
|
||||
private double priceEstimate10y = double.NaN;
|
||||
private double todaysPriceForRequiredReturn = double.NaN;
|
||||
private double averageBVPSGrowth = double.NaN;
|
||||
private ReturnItems bvpsItems = null;
|
||||
|
||||
// public StickerPrice(String symbol, int growthYears = -1)
|
||||
public StickerPrice(String symbol,double bvpsGrowthOverride)
|
||||
{
|
||||
try
|
||||
{
|
||||
double requiredReturn = 15.00 / 100.00;
|
||||
// TimeSeriesCollection bookValuePerShareCollection = HistoricalDA.GetTimeSeries(symbol, TimeSeriesElement.ElementType.BVPS);
|
||||
Fundamental fundamental = FundamentalDA.GetFundamental(symbol);
|
||||
// bvpsItems = new ReturnItems();
|
||||
// averageBVPSGrowth = Numerics.AverageReturnWithSpline(bookValuePerShareCollection,bvpsItems);
|
||||
averageBVPSGrowth=bvpsGrowthOverride;
|
||||
lowPE = fundamental.EPS * 2.00;
|
||||
trailingPE = fundamental.TrailingPE;
|
||||
averageLowTrailing = (lowPE + trailingPE) / 2.00;
|
||||
currentStockEstimatePrice = fundamental.EPS * averageLowTrailing;
|
||||
priceEstimate10y = currentStockEstimatePrice * Math.Pow((1.00 + averageBVPSGrowth), 10.00);
|
||||
todaysPriceForRequiredReturn = priceEstimate10y / Math.Pow((1.00 + requiredReturn), 10.00);
|
||||
marginOfSafety = todaysPriceForRequiredReturn * .50;
|
||||
marginOfSafety80Pcnt = todaysPriceForRequiredReturn * .80;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
public StickerPrice(String symbol)
|
||||
{
|
||||
try
|
||||
{
|
||||
double requiredReturn = 15.00 / 100.00;
|
||||
TimeSeriesCollection bookValuePerShareCollection = HistoricalDA.GetTimeSeries(symbol, TimeSeriesElement.ElementType.BVPS);
|
||||
Fundamental fundamental = FundamentalDA.GetFundamental(symbol);
|
||||
bvpsItems = new ReturnItems();
|
||||
averageBVPSGrowth = Numerics.AverageReturnWithSpline(bookValuePerShareCollection,bvpsItems);
|
||||
//if (-1 == growthYears) averageGrowth = Numerics.AverageReturn(ref bookValuesPerShareSeries);
|
||||
//else averageGrowth = Numerics.AverageReturnTop(ref bookValuesPerShareSeries, growthYears);
|
||||
lowPE = fundamental.EPS * 2.00;
|
||||
trailingPE = fundamental.TrailingPE;
|
||||
averageLowTrailing = (lowPE + trailingPE) / 2.00;
|
||||
currentStockEstimatePrice = fundamental.EPS * averageLowTrailing;
|
||||
priceEstimate10y = currentStockEstimatePrice * Math.Pow((1.00 + averageBVPSGrowth), 10.00);
|
||||
todaysPriceForRequiredReturn = priceEstimate10y / Math.Pow((1.00 + requiredReturn), 10.00);
|
||||
marginOfSafety = todaysPriceForRequiredReturn * .50;
|
||||
marginOfSafety80Pcnt = todaysPriceForRequiredReturn * .80;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
public ReturnItems BVPSItems
|
||||
{
|
||||
get
|
||||
{
|
||||
return bvpsItems;
|
||||
}
|
||||
}
|
||||
public double AverageBVPSGrowth
|
||||
{
|
||||
get { return averageBVPSGrowth; }
|
||||
}
|
||||
public double MarginOfSafety
|
||||
{
|
||||
get { return marginOfSafety; }
|
||||
}
|
||||
public double MarginOfSafety80Pcnt
|
||||
{
|
||||
get { return marginOfSafety80Pcnt; }
|
||||
}
|
||||
public double LowPE
|
||||
{
|
||||
get { return lowPE; }
|
||||
}
|
||||
public double TrailingPE
|
||||
{
|
||||
get { return trailingPE; }
|
||||
}
|
||||
public double AverageLowTrailing
|
||||
{
|
||||
get { return averageLowTrailing; }
|
||||
}
|
||||
public double CurrentStockEstimatePrice
|
||||
{
|
||||
get { return currentStockEstimatePrice; }
|
||||
}
|
||||
public double PriceEstimate10y
|
||||
{
|
||||
get { return priceEstimate10y; }
|
||||
}
|
||||
public double TodaysPriceForRequiredReturn
|
||||
{
|
||||
get { return todaysPriceForRequiredReturn; }
|
||||
}
|
||||
}
|
||||
}
|
||||
138
MarketData/MarketDataLib/MarketDataModel/Stochastic.cs
Executable file
138
MarketData/MarketDataLib/MarketDataModel/Stochastic.cs
Executable file
@@ -0,0 +1,138 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
// Filename: Stochastic.cs
|
||||
// Author:Sean Kessler
|
||||
// Date:08/2013
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class StochasticElementsByDate : Dictionary<DateTime, StochasticElement>
|
||||
{
|
||||
public StochasticElementsByDate()
|
||||
{
|
||||
}
|
||||
}
|
||||
public class Stochastics : List<StochasticElement>
|
||||
{
|
||||
public static String GetHeader()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("Date,Symbol,Open,High,Low,Close,LN,HN,HX,LX,%K,%D");
|
||||
return sb.ToString();
|
||||
}
|
||||
public StochasticElementsByDate GetBollingerBandElementsByDate()
|
||||
{
|
||||
StochasticElementsByDate stochasticElementsByDate = new StochasticElementsByDate();
|
||||
for (int index = 0; index < Count; index++)
|
||||
{
|
||||
StochasticElement stochasticElement = this[index];
|
||||
if (!stochasticElementsByDate.ContainsKey(stochasticElement.Date)) stochasticElementsByDate.Add(stochasticElement.Date, stochasticElement);
|
||||
}
|
||||
return stochasticElementsByDate;
|
||||
}
|
||||
}
|
||||
public class StochasticElement
|
||||
{
|
||||
private DateTime date;
|
||||
private String symbol;
|
||||
private double open;
|
||||
private double high;
|
||||
private double low;
|
||||
private double close;
|
||||
private double ln;
|
||||
private double hn;
|
||||
private double hx;
|
||||
private double lx;
|
||||
private double pd; // %D
|
||||
private double pk; // %K
|
||||
public StochasticElement()
|
||||
{
|
||||
}
|
||||
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 LN
|
||||
{
|
||||
get { return ln; }
|
||||
set { ln = value; }
|
||||
}
|
||||
public double HN
|
||||
{
|
||||
get { return hn; }
|
||||
set { hn = value; }
|
||||
}
|
||||
public double HX
|
||||
{
|
||||
get { return hx; }
|
||||
set { hx = value; }
|
||||
}
|
||||
public double LX
|
||||
{
|
||||
get { return lx; }
|
||||
set { lx = value; }
|
||||
}
|
||||
public double PD
|
||||
{
|
||||
get { return pd; }
|
||||
set { pd = value; }
|
||||
}
|
||||
public double PK
|
||||
{
|
||||
get { return pk; }
|
||||
set { pk = value; }
|
||||
}
|
||||
public bool PKInRange(double lowRange, double highRange)
|
||||
{
|
||||
if (PK >= lowRange && PK <= highRange) return true;
|
||||
return false;
|
||||
}
|
||||
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(LN).Append(",");
|
||||
sb.Append(HN).Append(",");
|
||||
sb.Append(HX).Append(",");
|
||||
sb.Append(LX).Append(",");
|
||||
sb.Append(PK).Append(",");
|
||||
sb.Append(PD);
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
109
MarketData/MarketDataLib/MarketDataModel/StopLimit.cs
Executable file
109
MarketData/MarketDataLib/MarketDataModel/StopLimit.cs
Executable file
@@ -0,0 +1,109 @@
|
||||
using MarketData.Utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
/// <summary>
|
||||
/// This StopLimit class is used for database persistence
|
||||
/// </summary>
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class StopLimitConstants
|
||||
{
|
||||
public static readonly String STOP_QUOTE="Stop Quote";
|
||||
}
|
||||
|
||||
public class StopLimits:List<StopLimit>
|
||||
{
|
||||
public StopLimits()
|
||||
{
|
||||
}
|
||||
public StopLimits(List<StopLimit> stopLimits)
|
||||
{
|
||||
foreach(StopLimit stopLimit in stopLimits) Add(stopLimit);
|
||||
}
|
||||
public NVPCollections ToNVPCollections()
|
||||
{
|
||||
NVPCollections nvpCollections=new NVPCollections();
|
||||
foreach(StopLimit stopLimit in this)
|
||||
{
|
||||
nvpCollections.Add(stopLimit.ToNVPCollection());
|
||||
}
|
||||
return nvpCollections;
|
||||
}
|
||||
public static StopLimits FromNVPCollections(NVPCollections nvpCollections)
|
||||
{
|
||||
StopLimits stopLimits=new StopLimits();
|
||||
foreach(NVPCollection nvpCollection in nvpCollections)
|
||||
{
|
||||
stopLimits.Add(StopLimit.FromNVPCollection(nvpCollection));
|
||||
}
|
||||
return stopLimits;
|
||||
}
|
||||
public void AddFromNVPCollection(NVPCollection nvpCollection)
|
||||
{
|
||||
Add(StopLimit.FromNVPCollection(nvpCollection));
|
||||
}
|
||||
public void Add(StopLimits stopLimits)
|
||||
{
|
||||
foreach(StopLimit stopLimit in stopLimits)this.Add(stopLimit);
|
||||
}
|
||||
}
|
||||
|
||||
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;}
|
||||
public DateTime EffectiveDate{get;set;} // if the EffectiveDate is Epoch then the StopLimit is taken to be in effect and is the most recent. Otherwise it is considered an historical stop limit
|
||||
|
||||
public StopLimit()
|
||||
{
|
||||
}
|
||||
public StopLimit(String symbol,double stopPrice,int shares,String stopType,int active)
|
||||
{
|
||||
this.Symbol=symbol;
|
||||
this.StopPrice=stopPrice;
|
||||
this.Shares=shares;
|
||||
this.StopType=stopType;
|
||||
this.Active=active;
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
sb.Append(Symbol).Append(",");
|
||||
sb.Append(Utility.FormatCurrency(StopPrice)).Append(",");
|
||||
sb.Append(Utility.FormatNumber(Shares,3)).Append(",");
|
||||
sb.Append(StopType).Append(",");
|
||||
sb.Append(Active.ToString()).Append(",");
|
||||
sb.Append(EffectiveDate.ToShortDateString());
|
||||
return sb.ToString();
|
||||
}
|
||||
public virtual NVPCollection ToNVPCollection()
|
||||
{
|
||||
NVPCollection nvpCollection=new NVPCollection();
|
||||
nvpCollection.Add(new NVP("Symbol",Symbol.ToString()));
|
||||
nvpCollection.Add(new NVP("StopPrice",StopPrice.ToString()));
|
||||
nvpCollection.Add(new NVP("Shares",Shares.ToString()));
|
||||
nvpCollection.Add(new NVP("StopType",StopType.ToString()));
|
||||
nvpCollection.Add(new NVP("Active",Active.ToString()));
|
||||
nvpCollection.Add(new NVP("EffectiveDate",EffectiveDate.ToShortDateString()));
|
||||
return nvpCollection;
|
||||
}
|
||||
public static StopLimit FromNVPCollection(NVPCollection nvpCollection)
|
||||
{
|
||||
StopLimit stopLimit=new StopLimit();
|
||||
|
||||
NVPDictionary nvpDictionary=nvpCollection.ToDictionary();
|
||||
stopLimit.Symbol=nvpDictionary["Symbol"].Get<String>();
|
||||
stopLimit.StopPrice=nvpDictionary["StopPrice"].Get<double>();
|
||||
stopLimit.Shares=nvpDictionary["Shares"].Get<double>();
|
||||
stopLimit.StopType=nvpDictionary["StopType"].Get<String>();
|
||||
stopLimit.EffectiveDate=nvpDictionary["EffectiveDate"].Get<DateTime>();
|
||||
return stopLimit;
|
||||
}
|
||||
}
|
||||
}
|
||||
108
MarketData/MarketDataLib/MarketDataModel/SwingTrade.cs
Executable file
108
MarketData/MarketDataLib/MarketDataModel/SwingTrade.cs
Executable file
@@ -0,0 +1,108 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class SwingTrades : List<SwingTrade>
|
||||
{
|
||||
public SwingTrades()
|
||||
{
|
||||
}
|
||||
public bool HasEntryOn(DateTime date)
|
||||
{
|
||||
if(0==Count)return false;
|
||||
return 0==this.Select(x => x.EntryDate.Date.Equals(date.Date)).Count()?false:true;
|
||||
}
|
||||
}
|
||||
// *********************************************************************************************************************************************************************************************************
|
||||
public class SwingTrade
|
||||
{
|
||||
public enum TypeOfSwing { Long, Short, LongBand, ShortBand };
|
||||
private String symbol;
|
||||
private DateTime candleDate;
|
||||
private double candleHigh;
|
||||
private double stopPrice;
|
||||
private DateTime closeDate;
|
||||
private DateTime entryDate;
|
||||
private TypeOfSwing swingType;
|
||||
|
||||
public SwingTrade()
|
||||
{
|
||||
}
|
||||
public String Symbol
|
||||
{
|
||||
get { return symbol; }
|
||||
set { symbol = value; }
|
||||
}
|
||||
public DateTime CandleDate
|
||||
{
|
||||
get { return candleDate; }
|
||||
set { candleDate = value; }
|
||||
}
|
||||
public double CandleHigh
|
||||
{
|
||||
get { return candleHigh; }
|
||||
set { candleHigh = value; }
|
||||
}
|
||||
public double StopPrice
|
||||
{
|
||||
get { return stopPrice; }
|
||||
set { stopPrice = value; }
|
||||
}
|
||||
public DateTime EntryDate
|
||||
{
|
||||
get { return entryDate; }
|
||||
set { entryDate = value; }
|
||||
}
|
||||
public DateTime CloseDate
|
||||
{
|
||||
get { return closeDate; }
|
||||
set { closeDate = value; }
|
||||
}
|
||||
public SwingTrade.TypeOfSwing SwingType
|
||||
{
|
||||
get { return swingType; }
|
||||
set { swingType = value; }
|
||||
}
|
||||
public static String Header
|
||||
{
|
||||
get { return "Symbol,SwingType,CandleDate,CandleHigh,StopPrice,CloseDate,EntryDate"; }
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(symbol).Append(",");
|
||||
switch (swingType)
|
||||
{
|
||||
case TypeOfSwing.Long:
|
||||
sb.Append("Long").Append(",");
|
||||
break;
|
||||
case TypeOfSwing.LongBand:
|
||||
sb.Append("LongBand").Append(",");
|
||||
break;
|
||||
case TypeOfSwing.Short:
|
||||
sb.Append("Short").Append(",");
|
||||
break;
|
||||
case TypeOfSwing.ShortBand:
|
||||
sb.Append("ShortBand").Append(",");
|
||||
break;
|
||||
default:
|
||||
sb.Append("?,");
|
||||
break;
|
||||
}
|
||||
sb.Append(Utility.DateTimeToStringMMHDDHYYYY(candleDate)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00000}", candleHigh)).Append(",");
|
||||
sb.Append(String.Format("{0:0.00000}", stopPrice)).Append(",");
|
||||
if (Utility.IsEpoch(entryDate)) sb.Append("?,?");
|
||||
else
|
||||
{
|
||||
sb.Append(Utility.DateTimeToStringMMHDDHYYYY(closeDate)).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMHDDHYYYY(entryDate));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
166
MarketData/MarketDataLib/MarketDataModel/TimeSeriesElement.cs
Executable file
166
MarketData/MarketDataLib/MarketDataModel/TimeSeriesElement.cs
Executable file
@@ -0,0 +1,166 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using MarketData.Numerical;
|
||||
using MarketData.Utils;
|
||||
|
||||
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());
|
||||
}
|
||||
public override String ToString()
|
||||
{
|
||||
StringBuilder sb=new StringBuilder();
|
||||
if(0==this.Count)return null;
|
||||
sb.Append(TimeSeriesElement.StringForType(this[0].Type));
|
||||
sb.Append(",");
|
||||
for(int index=0;index<this.Count;index++)
|
||||
{
|
||||
TimeSeriesElement timeSeriesElement=this[index];
|
||||
String strValue=Utility.AddQuotes(Utility.FormatNumber(timeSeriesElement.Value,2,true));
|
||||
String strAsOf=timeSeriesElement.AsOf.ToShortDateString();
|
||||
String strItem=String.Format("{0}({1})",strAsOf,strValue);
|
||||
sb.Append(strItem);
|
||||
if(index<this.Count-1)sb.Append(",");
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
public class TimeSeriesElement
|
||||
{
|
||||
public enum ElementType { INVALID, OTHER,BVPS, EPS, OperatingCashflow,FreeCashflow,Revenue,QuarterlyRevenue,Inventory,QuarterlyInventory,ROIC,OperatingIncome,WorkingCapital,ROA,NetIncomeAvailableToCommonShareholders,TaxRate,InterestExpense,COGS,AccountsReceivable,SGA};
|
||||
private String symbol;
|
||||
private DateTime asof;
|
||||
private ElementType elementType;
|
||||
private double value;
|
||||
private String otherType;
|
||||
private DateTime modified;
|
||||
|
||||
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 DateTime Modified
|
||||
{
|
||||
get{ return modified;}
|
||||
set{modified=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";
|
||||
case ElementType.Inventory :
|
||||
return "inventory";
|
||||
case ElementType.SGA :
|
||||
return "sg&a";
|
||||
case ElementType.AccountsReceivable :
|
||||
return "accounts receivable";
|
||||
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;}
|
||||
}
|
||||
}
|
||||
80
MarketData/MarketDataLib/MarketDataModel/TradeResult.cs
Executable file
80
MarketData/MarketDataLib/MarketDataModel/TradeResult.cs
Executable file
@@ -0,0 +1,80 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class TradeResult : IComparable
|
||||
{
|
||||
public TradeResult()
|
||||
{
|
||||
}
|
||||
public int CompareTo(Object obj)
|
||||
{
|
||||
if (obj == null || !obj.GetType().IsInstanceOfType(this)) throw new Exception("Expected TradeResult"); ;
|
||||
TradeResult otherTradeResult = (TradeResult)obj;
|
||||
return otherTradeResult.TotalGainLoss.CompareTo(TotalGainLoss);
|
||||
// return TotalGainLoss.CompareTo(otherTradeResult.TotalGainLoss);
|
||||
}
|
||||
public double InitialCash { get; set; }
|
||||
public MACDSetup MACDSetup { get; set; }
|
||||
public double StopLossThreshold { get; set; }
|
||||
public int StopLossDays { get; set; }
|
||||
public String Symbol { get; set; }
|
||||
public String Company { get; set; }
|
||||
public DateTime StartDate { get; set; }
|
||||
public DateTime HistoricalDate { get; set; }
|
||||
public double AvailableCash { get; set; }
|
||||
public double TotalPortfolioValue { get; set; }
|
||||
public double TotalGainLoss { get; set; }
|
||||
public double ROI { get; set; }
|
||||
public double AverageGainLoss { get; set; }
|
||||
public int AverageHoldingDays { get; set; }
|
||||
public int MinimumHoldingDays { get; set; }
|
||||
public int MaximumHoldingDays { get; set; }
|
||||
public List<ModelTrade> Trades { get; set; }
|
||||
public override string ToString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append("Company:'" + Company + "'").Append("\n");
|
||||
sb.Append("Using " + Utility.AddQuotes(MACDSetup.ToString())).Append("\n");
|
||||
sb.Append("Using StopLoss:" + (StopLossThreshold * 100) + "%").Append("\n");
|
||||
sb.Append("Using StopLossDays:" + StopLossDays).Append("\n");
|
||||
sb.Append("Using initial cash " + String.Format("{0:C}", InitialCash)).Append("\n");
|
||||
sb.Append("Latest date for '" + Symbol + "' is " + Utility.DateTimeToStringMMSDDSYYYY(StartDate)).Append("\n");
|
||||
sb.Append("Historical date is " + Utility.DateTimeToStringMMSDDSYYYY(HistoricalDate)).Append("\n");
|
||||
sb.Append("Available Cash (Cash Available For Trading)=" + Utility.AddQuotes(String.Format("{0:C}", AvailableCash))).Append("\n");
|
||||
sb.Append("Total Portfolio Value (Cash+Stock)=" + Utility.AddQuotes(String.Format("{0:C}", TotalPortfolioValue))).Append("\n");
|
||||
sb.Append("Total Gain/Loss=" + Utility.AddQuotes(String.Format("{0:C}", TotalGainLoss))).Append("\n");
|
||||
sb.Append("Return On Investment:" + String.Format("{0:P}", ROI)).Append("\n");
|
||||
sb.Append("").Append("\n");
|
||||
sb.Append("********* T R A D I N G D E T A I L *********").Append("\n");
|
||||
sb.Append(ModelTrade.Header).Append("\n");
|
||||
for (int index = 0; index < Trades.Count; index++)
|
||||
{
|
||||
sb.Append(Trades[index].ToString()).Append("\n");
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
public static String GetShortHeader()
|
||||
{
|
||||
return "Symbol,Company,MACD,Initial Cash,Start Date,Historical Date,Total Gain/Loss,Trade Count,Min Holding Days,Max Holding Days";
|
||||
}
|
||||
public string ToShortString()
|
||||
{
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.Append(Symbol).Append(",");
|
||||
sb.Append(Utility.AddQuotes(Company)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(MACDSetup.ToString())).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", InitialCash))).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMHDDHYYYY(StartDate)).Append(",");
|
||||
sb.Append(Utility.DateTimeToStringMMHDDHYYYY(HistoricalDate)).Append(",");
|
||||
sb.Append(Utility.AddQuotes(String.Format("{0:C}", TotalGainLoss))).Append(",");
|
||||
sb.Append(Trades.Count).Append(",");
|
||||
sb.Append(MinimumHoldingDays).Append(",");
|
||||
sb.Append(MaximumHoldingDays);
|
||||
return sb.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
11
MarketData/MarketDataLib/MarketDataModel/User/User.cs
Executable file
11
MarketData/MarketDataLib/MarketDataModel/User/User.cs
Executable file
@@ -0,0 +1,11 @@
|
||||
using System;
|
||||
|
||||
namespace MarketData.MarketDataModel.User
|
||||
{
|
||||
public class User
|
||||
{
|
||||
public String Username { get; set; }
|
||||
public String Hash { get; set; }
|
||||
public String Salt { get; set; }
|
||||
}
|
||||
}
|
||||
164
MarketData/MarketDataLib/MarketDataModel/Valuations.cs
Executable file
164
MarketData/MarketDataLib/MarketDataModel/Valuations.cs
Executable file
@@ -0,0 +1,164 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.IO;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
|
||||
// ********************************************************* V A L U A T I O N S ****************************************************
|
||||
public class Valuations : List<Valuation>
|
||||
{
|
||||
public Valuations()
|
||||
{
|
||||
ValuationDate = DateTime.Now;
|
||||
}
|
||||
public Valuations(List<Valuation> valuations)
|
||||
{
|
||||
foreach(Valuation valuation in valuations)Add(valuation);
|
||||
}
|
||||
public DateTime ValuationDate{get;set;}
|
||||
}
|
||||
public class Valuation
|
||||
{
|
||||
public String Symbol { get; set; }
|
||||
public String Company { get; set; }
|
||||
public double Beta90 { get; set; }
|
||||
public double Beta720 { get; set; }
|
||||
public DateTime NextEarningsDate { get; set; }
|
||||
public double LongTermDebt { get; set; }
|
||||
public double Revenue { get; set; }
|
||||
public String DebtLoad { get; set; }
|
||||
public double AverageROIC { get; set; }
|
||||
public double LatestROIC { get; set; }
|
||||
public double LatestROC{get;set;} // Return on Capital = EBIT / (Net Fixed Assets + Working Capital) where Net Fixed Assets = Net Property, Plant, and Equipment
|
||||
public double ROICSlope{get;set;}
|
||||
public String ROICDates{get;set;}
|
||||
public DateTime LatestROICDate{get{return null==ROICDates?DateTime.MinValue:DateTime.Parse(Utility.BetweenString(ROICDates,"-",null));}}
|
||||
public String BVPSDates { get; set; }
|
||||
public double AverageEquityGrowth { get; set; }
|
||||
public double AverageEquityGrowth2Y { get; set; }
|
||||
public double AverageEquityGrowth4Y { get; set; }
|
||||
public String EPSDates { get; set; }
|
||||
public double AverageEPSGrowth { get; set; }
|
||||
public double AverageEPSGrowth2Y { get; set; }
|
||||
public double AverageEPSGrowth4Y { get; set; }
|
||||
public String RevenueDates { get; set; }
|
||||
public double AverageBVPSGrowth { get; set; }
|
||||
public double AverageRevenueGrowth { get; set; }
|
||||
public double AverageRevenueGrowth2Y { get; set; }
|
||||
public double AverageRevenueGrowth4Y { get; set; }
|
||||
public double AverageFreeCashflowGrowth { get; set; }
|
||||
public double AverageOperatingCashflow { get; set; }
|
||||
public double AverageWorkingCapital { get; set; }
|
||||
public double BVPS { get; set; }
|
||||
public double PBVPS { get; set; } // price to book
|
||||
public double EPS { get; set; }
|
||||
public double PE { get; set; }
|
||||
public double PExPBVPS
|
||||
{
|
||||
get{if(PE<0||PBVPS<0)return double.NaN; else return PE*PBVPS;}
|
||||
}
|
||||
public double PCF(double price=double.NaN)
|
||||
{
|
||||
if(double.IsNaN(price))price=LatestPrice;
|
||||
if(0==LatestPrice)return 0.00;
|
||||
if(0==SharesOutstanding||double.IsNaN(OperatingCashflow)||0==OperatingCashflow||double.IsNaN(SharesOutstanding))return double.NaN;
|
||||
return LatestPrice/(OperatingCashflow/SharesOutstanding);
|
||||
}
|
||||
//public double PCF
|
||||
//{
|
||||
// get
|
||||
// {
|
||||
// if(0==LatestPrice)return 0.00;
|
||||
// if(0==SharesOutstanding||double.IsNaN(OperatingCashflow)||0==OperatingCashflow||double.IsNaN(SharesOutstanding))return double.NaN;
|
||||
// return LatestPrice/(OperatingCashflow/SharesOutstanding);
|
||||
// }
|
||||
//}
|
||||
public double PEG { get; set; }
|
||||
public double ImpliedEarningsGrowth { get; set; } // derived from (PE/PEG)/100.00
|
||||
public double LowPE { get; set; }
|
||||
public double TrailingPE { get; set; }
|
||||
public double AverageLowTrailing { get; set; }
|
||||
public double CurrentStockEstimatePrice { get; set; }
|
||||
public double PriceEstimate10Y { get; set; }
|
||||
public double TodaysPriceForRequiredReturn { get; set; }
|
||||
public double MOS { get; set; }
|
||||
public double MOS80 { get; set; }
|
||||
public double IntrinsicValue { get; set; } // Benjamin Graham original intrinsic value
|
||||
public double FundamentalValue{get;set;} // Benjamin Graham fundamental value
|
||||
public double NetCurrentAssetValuePerShare{get;set;} // Benjamin Graham's net current asset value per share
|
||||
public double RGV { get; set; }
|
||||
public double LatestPrice { get; set; }
|
||||
public double UpsidePcnt { get; set; }
|
||||
public double DownsidePcnt { get; set; }
|
||||
public double MeanTargetPrice { get; set; }
|
||||
public double LowTargetPrice { get; set; }
|
||||
public double HighTargetPrice { get; set; }
|
||||
public double MarketCap{get;set;}
|
||||
public double EarningsYield{get;set;} // derived from EBIT/EnterpriseValue
|
||||
public double EBIT{get;set;}
|
||||
public double DebtToEquity{get;set;}
|
||||
public double EnterpriseValue{get;set;}
|
||||
public double TLBRankROIC{get;set;}
|
||||
public double TLBRankROC{get;set;}
|
||||
public double AMRank{get;set;} // AcquirersMultiple Rank
|
||||
public double OperatingEarnings{get;set;} // Revenue-(CostOfGoodsSold+Selling, General, and Administrative+Depreciation and Amortization)
|
||||
public double AcquirersMultiple{get;set;} // in the book "The Acquirers Multiple" Carlisle divides Enterprise Value by Operating Earnings to arrive at this value and then ranks (lowest best). I do opposite, operating earnings / enterprise value and then rank highest
|
||||
public bool Bargain { get; set; }
|
||||
public bool Bargain80 { get; set; }
|
||||
public bool SEC13{get;set;}
|
||||
public DateTime SEC13FilingDate{get;set;}
|
||||
public String Sector{get;set;}
|
||||
public String Industry{get;set;}
|
||||
public ReturnItems BVPSItems { get; set; }
|
||||
public double DividendYield{get;set;}
|
||||
public double OperatingCashflow{get;set;}
|
||||
public double SharesOutstanding{get;set;}
|
||||
public DateTime Modified { get; set; }
|
||||
}
|
||||
public class ValuationsByROIC : IComparer<Valuation>
|
||||
{
|
||||
public int Compare(Valuation v1,Valuation v2)
|
||||
{
|
||||
if(double.IsNaN(v1.LatestROIC)&&double.IsNaN(v2.LatestROIC))return 0;
|
||||
else if(double.IsNaN(v1.LatestROIC))return -1;
|
||||
else if(double.IsNaN(v2.LatestROIC))return 1;
|
||||
return v1.LatestROIC.CompareTo(v2.LatestROIC);
|
||||
}
|
||||
}
|
||||
public class ValuationsByROC : IComparer<Valuation>
|
||||
{
|
||||
public int Compare(Valuation v1,Valuation v2)
|
||||
{
|
||||
if(double.IsNaN(v1.LatestROC)&&double.IsNaN(v2.LatestROC))return 0;
|
||||
else if(double.IsNaN(v1.LatestROC))return -1;
|
||||
else if(double.IsNaN(v2.LatestROC))return 1;
|
||||
return v1.LatestROC.CompareTo(v2.LatestROC);
|
||||
}
|
||||
}
|
||||
public class ValuationsByEarningsYield : IComparer<Valuation>
|
||||
{
|
||||
public int Compare(Valuation v1,Valuation v2)
|
||||
{
|
||||
if(double.IsNaN(v1.EarningsYield)&&double.IsNaN(v2.EarningsYield))return 0;
|
||||
else if(double.IsNaN(v1.EarningsYield))return -1;
|
||||
else if(double.IsNaN(v2.EarningsYield))return 1;
|
||||
return v1.EarningsYield.CompareTo(v2.EarningsYield);
|
||||
}
|
||||
}
|
||||
public class ValuationsByAcquirersMultiple : IComparer<Valuation>
|
||||
{
|
||||
public int Compare(Valuation v1,Valuation v2)
|
||||
{
|
||||
if(double.IsNaN(v1.AcquirersMultiple)&&double.IsNaN(v2.AcquirersMultiple))return 0;
|
||||
else if(double.IsNaN(v1.AcquirersMultiple))return -1;
|
||||
else if(double.IsNaN(v2.AcquirersMultiple))return 1;
|
||||
if(v1.AcquirersMultiple.Equals(v2.AcquirersMultiple))return 0;
|
||||
if(v1.AcquirersMultiple<v2.AcquirersMultiple)return 1;
|
||||
else return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
13
MarketData/MarketDataLib/MarketDataModel/WatchListItem.cs
Executable file
13
MarketData/MarketDataLib/MarketDataModel/WatchListItem.cs
Executable file
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class WatchListItem
|
||||
{
|
||||
public String WatchListName{get;set;}
|
||||
public int WatchListId{get;set;}
|
||||
}
|
||||
}
|
||||
72
MarketData/MarketDataLib/MarketDataModel/WordDictionary.cs
Executable file
72
MarketData/MarketDataLib/MarketDataModel/WordDictionary.cs
Executable file
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class WordDictionary : Dictionary<String,Dictionary<String,DictionaryElement>>
|
||||
{
|
||||
public WordDictionary()
|
||||
{
|
||||
}
|
||||
public DictionaryCollection ToList()
|
||||
{
|
||||
DictionaryCollection dictionaryCollection=new DictionaryCollection();
|
||||
List<String> outerKeys=new List<String>(this.Keys);
|
||||
foreach(String outerKey in outerKeys)
|
||||
{
|
||||
Dictionary<String,DictionaryElement> innerDictionary=this[outerKey];
|
||||
DictionaryCollection items=new DictionaryCollection(innerDictionary.Values.ToList());
|
||||
dictionaryCollection.AddRange(items);
|
||||
}
|
||||
return dictionaryCollection;
|
||||
}
|
||||
public bool ContainsKeyAs(String word,String partOfSpeech)
|
||||
{
|
||||
if(!ContainsKey(word))return false;
|
||||
Dictionary<String,DictionaryElement> items=this[word];
|
||||
if(!items.ContainsKey(partOfSpeech))return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
public class DictionaryElement
|
||||
{
|
||||
public DictionaryElement()
|
||||
{
|
||||
}
|
||||
public DictionaryElement(String word,String partOfSpeech)
|
||||
{
|
||||
Word=word;
|
||||
PartOfSpeech=partOfSpeech;
|
||||
}
|
||||
public String Word{get;set;}
|
||||
public String PartOfSpeech{get;set;}
|
||||
}
|
||||
public class DictionaryCollection : List<DictionaryElement>
|
||||
{
|
||||
public DictionaryCollection()
|
||||
{
|
||||
}
|
||||
public DictionaryCollection(List<DictionaryElement> dictionaryCollection)
|
||||
{
|
||||
foreach(DictionaryElement dictionaryElement in dictionaryCollection)Add(dictionaryElement);
|
||||
}
|
||||
public WordDictionary ToDictionary()
|
||||
{
|
||||
WordDictionary wordDictionary=new WordDictionary();
|
||||
foreach(DictionaryElement dictionaryElement in this)
|
||||
{
|
||||
if(!wordDictionary.ContainsKey(dictionaryElement.Word))
|
||||
{
|
||||
wordDictionary.Add(dictionaryElement.Word,new Dictionary<String,DictionaryElement>());
|
||||
}
|
||||
Dictionary<String,DictionaryElement> items=wordDictionary[dictionaryElement.Word];
|
||||
if(items.ContainsKey(dictionaryElement.PartOfSpeech))continue;
|
||||
items.Add(dictionaryElement.PartOfSpeech,dictionaryElement);
|
||||
}
|
||||
return wordDictionary;
|
||||
}
|
||||
}
|
||||
}
|
||||
354
MarketData/MarketDataLib/MarketDataModel/YieldCurve.cs
Executable file
354
MarketData/MarketDataLib/MarketDataModel/YieldCurve.cs
Executable file
@@ -0,0 +1,354 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Linq;
|
||||
using MarketData.Generator;
|
||||
using MarketData.Utils;
|
||||
using MarketData.Generator.MovingAverage;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class YieldCurve : List<YieldCurveData>
|
||||
{
|
||||
public enum CurveType{Mo1,Mo2,Mo3,Mo6,Yr1,Yr2,Yr3,Yr5,Yr7,Yr10,Yr20,Yr30}
|
||||
public YieldCurve()
|
||||
{
|
||||
}
|
||||
public YieldCurve(List<YieldCurveData> yieldCurveData)
|
||||
{
|
||||
if(null==yieldCurveData)return;
|
||||
for(int index=0;index<yieldCurveData.Count;index++)Add(yieldCurveData[index]);
|
||||
}
|
||||
public List<DateTime> GetDistinctDates()
|
||||
{
|
||||
Dictionary<DateTime, DateTime> uniqueDates = new Dictionary<DateTime, DateTime>();
|
||||
foreach (YieldCurveData yieldData in this)
|
||||
{
|
||||
if (!uniqueDates.ContainsKey(yieldData.Date)) uniqueDates.Add(yieldData.Date, yieldData.Date);
|
||||
}
|
||||
List<DateTime> uniqueDatesList = new List<DateTime>(uniqueDates.Values);
|
||||
uniqueDatesList.Sort();
|
||||
return uniqueDatesList;
|
||||
}
|
||||
public static CurveType CurveTypeFromString(String strCurveType)
|
||||
{
|
||||
if(strCurveType.Equals("Mo1",StringComparison.InvariantCultureIgnoreCase))return CurveType.Mo1;
|
||||
if(strCurveType.Equals("Mo2",StringComparison.InvariantCultureIgnoreCase))return CurveType.Mo2;
|
||||
if(strCurveType.Equals("Mo3",StringComparison.InvariantCultureIgnoreCase))return CurveType.Mo3;
|
||||
if(strCurveType.Equals("Mo6",StringComparison.InvariantCultureIgnoreCase))return CurveType.Mo6;
|
||||
if(strCurveType.Equals("Yr1",StringComparison.InvariantCultureIgnoreCase))return CurveType.Yr1;
|
||||
if(strCurveType.Equals("Yr2",StringComparison.InvariantCultureIgnoreCase))return CurveType.Yr2;
|
||||
if(strCurveType.Equals("Yr3",StringComparison.InvariantCultureIgnoreCase))return CurveType.Yr3;
|
||||
if(strCurveType.Equals("Yr5",StringComparison.InvariantCultureIgnoreCase))return CurveType.Yr5;
|
||||
if(strCurveType.Equals("Yr7",StringComparison.InvariantCultureIgnoreCase))return CurveType.Yr7;
|
||||
if(strCurveType.Equals("Yr10",StringComparison.InvariantCultureIgnoreCase))return CurveType.Yr10;
|
||||
if(strCurveType.Equals("Yr20",StringComparison.InvariantCultureIgnoreCase))return CurveType.Yr20;
|
||||
if(strCurveType.Equals("Yr30",StringComparison.InvariantCultureIgnoreCase))return CurveType.Yr30;
|
||||
throw new Exception(String.Format("'{0}' is not a known curve type",strCurveType));
|
||||
}
|
||||
public static String CurveTypeToString(CurveType curveType)
|
||||
{
|
||||
switch(curveType)
|
||||
{
|
||||
case CurveType.Mo1 :
|
||||
return "Mo1";
|
||||
case CurveType.Mo2 :
|
||||
return "Mo2";
|
||||
case CurveType.Mo3 :
|
||||
return "Mo3";
|
||||
case CurveType.Mo6 :
|
||||
return "Mo6";
|
||||
case CurveType.Yr1 :
|
||||
return "Yr1";
|
||||
case CurveType.Yr2 :
|
||||
return "Yr2";
|
||||
case CurveType.Yr3 :
|
||||
return "Yr3";
|
||||
case CurveType.Yr10 :
|
||||
return "Yr10";
|
||||
case CurveType.Yr20 :
|
||||
return "Yr20";
|
||||
default :
|
||||
throw new Exception(String.Format("Unknown curve type enumeration EnumValue:{0}",(int)curveType));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Return the data for specified tenor. The data is ordered with the earliest date in the lowest index
|
||||
public double[] GetYieldCurveDataOrderByDateAscending(CurveType curveType)
|
||||
{
|
||||
double[] array=null;
|
||||
switch (curveType)
|
||||
{
|
||||
case CurveType.Mo1 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Mo1).ToArray();
|
||||
break;
|
||||
case CurveType.Mo2 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Mo2).ToArray();
|
||||
break;
|
||||
case CurveType.Mo3 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Mo3).ToArray();
|
||||
break;
|
||||
case CurveType.Mo6 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Mo6).ToArray();
|
||||
break;
|
||||
case CurveType.Yr1 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Yr1).ToArray();
|
||||
break;
|
||||
case CurveType.Yr2 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Yr2).ToArray();
|
||||
break;
|
||||
case CurveType.Yr3 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Yr3).ToArray();
|
||||
break;
|
||||
case CurveType.Yr5 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Yr5).ToArray();
|
||||
break;
|
||||
case CurveType.Yr7 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Yr7).ToArray();
|
||||
break;
|
||||
case CurveType.Yr10 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Yr10).ToArray();
|
||||
break;
|
||||
case CurveType.Yr20 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Yr20).ToArray();
|
||||
break;
|
||||
case CurveType.Yr30:
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date ascending select yieldCurveData.Yr30).ToArray();
|
||||
break;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
// Return the data for specified tenor. The data is ordered with the earliest date in the highest index. Thus the most recent date is in the lowest index
|
||||
public double[] GetYieldCurveDataOrderByDateDescending(CurveType curveType)
|
||||
{
|
||||
double[] array=null;
|
||||
switch (curveType)
|
||||
{
|
||||
case CurveType.Mo1 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Mo1).ToArray();
|
||||
break;
|
||||
case CurveType.Mo2 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Mo2).ToArray();
|
||||
break;
|
||||
case CurveType.Mo3 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Mo3).ToArray();
|
||||
break;
|
||||
case CurveType.Mo6 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Mo6).ToArray();
|
||||
break;
|
||||
case CurveType.Yr1 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Yr1).ToArray();
|
||||
break;
|
||||
case CurveType.Yr2 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Yr2).ToArray();
|
||||
break;
|
||||
case CurveType.Yr3 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Yr3).ToArray();
|
||||
break;
|
||||
case CurveType.Yr5 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Yr5).ToArray();
|
||||
break;
|
||||
case CurveType.Yr7 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Yr7).ToArray();
|
||||
break;
|
||||
case CurveType.Yr10 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Yr10).ToArray();
|
||||
break;
|
||||
case CurveType.Yr20 :
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Yr20).ToArray();
|
||||
break;
|
||||
case CurveType.Yr30:
|
||||
array=(from YieldCurveData yieldCurveData in this orderby yieldCurveData.Date descending select yieldCurveData.Yr30).ToArray();
|
||||
break;
|
||||
}
|
||||
return array;
|
||||
}
|
||||
public DMAValues GetMovingAverage(CurveType curveType,int dayCount)
|
||||
{
|
||||
DMAValues dmaValues = new DMAValues();
|
||||
foreach (YieldCurveData yieldCurveData in this)
|
||||
{
|
||||
DMAValue dmaValue = new DMAValue();
|
||||
dmaValue.Date = yieldCurveData.Date;
|
||||
switch (curveType)
|
||||
{
|
||||
case CurveType.Mo1 :
|
||||
dmaValue.Value = yieldCurveData.Mo1;
|
||||
break;
|
||||
case CurveType.Mo2 :
|
||||
dmaValue.Value = yieldCurveData.Mo2;
|
||||
break;
|
||||
case CurveType.Mo3 :
|
||||
dmaValue.Value = yieldCurveData.Mo3;
|
||||
break;
|
||||
case CurveType.Mo6 :
|
||||
dmaValue.Value = yieldCurveData.Mo6;
|
||||
break;
|
||||
case CurveType.Yr1 :
|
||||
dmaValue.Value = yieldCurveData.Yr1;
|
||||
break;
|
||||
case CurveType.Yr2 :
|
||||
dmaValue.Value = yieldCurveData.Yr2;
|
||||
break;
|
||||
case CurveType.Yr3 :
|
||||
dmaValue.Value = yieldCurveData.Yr3;
|
||||
break;
|
||||
case CurveType.Yr5 :
|
||||
dmaValue.Value = yieldCurveData.Yr5;
|
||||
break;
|
||||
case CurveType.Yr7 :
|
||||
dmaValue.Value = yieldCurveData.Yr7;
|
||||
break;
|
||||
case CurveType.Yr10 :
|
||||
dmaValue.Value = yieldCurveData.Yr10;
|
||||
break;
|
||||
case CurveType.Yr20 :
|
||||
dmaValue.Value = yieldCurveData.Yr20;
|
||||
break;
|
||||
case CurveType.Yr30:
|
||||
dmaValue.Value = yieldCurveData.Yr30;
|
||||
break;
|
||||
}
|
||||
dmaValues.Add(dmaValue);
|
||||
}
|
||||
return MovingAverageGenerator.GenerateMovingAverage(dmaValues, dayCount);
|
||||
}
|
||||
}
|
||||
public class YieldCurveData
|
||||
{
|
||||
private DateTime date;
|
||||
private double mo1;
|
||||
private double mo2;
|
||||
private double mo3;
|
||||
private double mo6;
|
||||
private double yr1;
|
||||
private double yr2;
|
||||
private double yr3;
|
||||
private double yr5;
|
||||
private double yr7;
|
||||
private double yr10;
|
||||
private double yr20;
|
||||
private double yr30;
|
||||
|
||||
public YieldCurveData()
|
||||
{
|
||||
}
|
||||
public DateTime Date
|
||||
{
|
||||
get { return date; }
|
||||
set { date = value; }
|
||||
}
|
||||
|
||||
public bool IsValid()
|
||||
{
|
||||
if(Utility.IsEpoch(date))return false;
|
||||
if(double.IsNaN(mo1))return false;
|
||||
if(double.IsNaN(mo2))return false;
|
||||
if(double.IsNaN(mo3))return false;
|
||||
if(double.IsNaN(mo6))return false;
|
||||
if(double.IsNaN(yr1))return false;
|
||||
if(double.IsNaN(yr2))return false;
|
||||
if(double.IsNaN(yr3))return false;
|
||||
if(double.IsNaN(yr5))return false;
|
||||
if(double.IsNaN(yr7))return false;
|
||||
if(double.IsNaN(yr10))return false;
|
||||
if(double.IsNaN(yr20))return false;
|
||||
if(double.IsNaN(yr30))return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
public double GetRate(String rateType)
|
||||
{
|
||||
if (rateType.Equals("1 Month Treasury")) return Mo1;
|
||||
else if (rateType.Equals("3 Month Treasury")) return Mo3;
|
||||
else if (rateType.Equals("2 Month Treasury")) return Mo2;
|
||||
else if (rateType.Equals("6 Month Treasury")) return Mo6;
|
||||
else if (rateType.Equals("1 Year Treasury")) return Yr1;
|
||||
else if (rateType.Equals("2 Year Treasury")) return Yr2;
|
||||
else if (rateType.Equals("3 Year Treasury")) return Yr3;
|
||||
else if (rateType.Equals("5 Year Treasury")) return Yr5;
|
||||
else if (rateType.Equals("7 Year Treasury")) return Yr7;
|
||||
else if (rateType.Equals("10 Year Treasury")) return Yr10;
|
||||
else if (rateType.Equals("20 Year Treasury")) return Yr20;
|
||||
else return 0.00;
|
||||
}
|
||||
public static List<String> GetRateTypesString()
|
||||
{
|
||||
List<String> riskFreeRateTypes = new List<String>();
|
||||
riskFreeRateTypes.Add("1 Month Treasury");
|
||||
riskFreeRateTypes.Add("2 Month Treasury");
|
||||
riskFreeRateTypes.Add("3 Month Treasury");
|
||||
riskFreeRateTypes.Add("6 Month Treasury");
|
||||
riskFreeRateTypes.Add("1 Year Treasury");
|
||||
riskFreeRateTypes.Add("2 Year Treasury");
|
||||
riskFreeRateTypes.Add("3 Year Treasury");
|
||||
riskFreeRateTypes.Add("5 Year Treasury");
|
||||
riskFreeRateTypes.Add("7 Year Treasury");
|
||||
riskFreeRateTypes.Add("10 Year Treasury");
|
||||
riskFreeRateTypes.Add("20 Year Treasury");
|
||||
return riskFreeRateTypes;
|
||||
}
|
||||
public double Mo1
|
||||
{
|
||||
get { return mo1; }
|
||||
set { mo1 = value; }
|
||||
}
|
||||
public double Mo2
|
||||
{
|
||||
get { return mo2; }
|
||||
set { mo2 = value; }
|
||||
}
|
||||
public double Mo3
|
||||
{
|
||||
get { return mo3; }
|
||||
set { mo3 = value; }
|
||||
}
|
||||
public double Mo6
|
||||
{
|
||||
get { return mo6; }
|
||||
set { mo6 = value; }
|
||||
}
|
||||
public double Yr1
|
||||
{
|
||||
get { return yr1; }
|
||||
set { yr1 = value; }
|
||||
}
|
||||
public double Yr2
|
||||
{
|
||||
get { return yr2; }
|
||||
set { yr2 = value; }
|
||||
}
|
||||
public double Yr3
|
||||
{
|
||||
get { return yr3; }
|
||||
set { yr3 = value; }
|
||||
}
|
||||
public double Yr5
|
||||
{
|
||||
get { return yr5; }
|
||||
set { yr5 = value; }
|
||||
}
|
||||
public double Yr7
|
||||
{
|
||||
get { return yr7; }
|
||||
set { yr7 = value; }
|
||||
}
|
||||
public double Yr10
|
||||
{
|
||||
get { return yr10; }
|
||||
set { yr10 = value; }
|
||||
}
|
||||
public double Yr20
|
||||
{
|
||||
get { return yr20; }
|
||||
set { yr20 = value; }
|
||||
}
|
||||
public double Yr30
|
||||
{
|
||||
get { return yr30; }
|
||||
set { yr30 = value; }
|
||||
}
|
||||
}
|
||||
}
|
||||
14
MarketData/MarketDataLib/MarketDataModel/ZacksRank.cs
Executable file
14
MarketData/MarketDataLib/MarketDataModel/ZacksRank.cs
Executable file
@@ -0,0 +1,14 @@
|
||||
using System;
|
||||
using System.Text;
|
||||
using MarketData.Utils;
|
||||
|
||||
namespace MarketData.MarketDataModel
|
||||
{
|
||||
public class ZacksRank
|
||||
{
|
||||
public String Symbol{get;set;}
|
||||
public DateTime Date{get;set;}
|
||||
public String Rank{get;set;}
|
||||
public String Type{get;set;}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user