Пример #1
0
        internal IList <IPosition> LoadPositions(IPortfolio p)
        {
            List <IPosition> lst = new List <IPosition>();

            InstrumentMapper      im         = new InstrumentMapper(mapperHelper.context);
            List <IDataParameter> parameters = new List <IDataParameter>();

            parameters.Add(new SqlParameter("@id", p.name));
            using (IDataReader rd = mapperHelper.ExecuteReader("select isin, name, quantity from Position where name=@id", parameters))
            {
                while (rd.Read())
                {
                    Position pos = new Position
                    {
                        quantity                                    = rd.IsDBNull(2) ? default : rd.GetInt32(2),
                                                 name               = rd.IsDBNull(1) ? default : rd.GetString(1),
                                                               isin = rd.IsDBNull(0) ? default : rd.GetString(0),
                                                                      Instrument = im.Read(rd.IsDBNull(0) ? default : rd.GetString(0)),
                                                                      Portfolio  = p
                    };
                    lst.Add(pos);
                }
            }
            return(lst);
        }
Пример #2
0
 public bool Delete(IPortfolio entity)
 {
     return(mapperHelper.Delete(entity,
                                (cmd, portfolio) => DeleteParameters(cmd, portfolio),
                                "delete from Portfolio where name=@id"
                                ));
 }
Пример #3
0
        public void createPortfolioTest()
        {
            ctx().createPortfolio(555555555);
            IPortfolio P = ctx().Portfolios.Find("555555555_portfolio");

            Assert.AreEqual(P.name, "555555555_portfolio");
        }
Пример #4
0
 public void Portfolio_Ctor_NoThrow()
 {
     _uut = new Portfolio("Name", _portfolioDisplay);
     Assert.That(_uut.Name, Is.EqualTo(_uut.Name));
     Assert.That(_uut.PortfolioDisplay, Is.EqualTo(_portfolioDisplay));
     Assert.IsEmpty(_uut.Stocks);
 }
Пример #5
0
        public static IPortfolio CalculateMinVariancePortfolio(this IPortfolio portfolio)
        {
            var minvar = new MVOMinVariance(portfolio);
            var portf  = minvar.Calculate();

            return(portf);
        }
Пример #6
0
        private ITrade FindMinWeightedCoveringTrade(IPortfolio portfolio, HashSet <string> nonCoveredDependencies, Dictionary <string, int> tradeCosts, out int minTradeCost)
        {
            double minTradeCostFactor = int.MaxValue;
            int    minTradeIndex      = -1;

            for (int i = 0; i < portfolio.Trades.Count; i++)
            {
                ITrade trade     = portfolio.Trades[i];
                int    tradeCost = tradeCosts[trade.TCN];

                int dependenciesCoveredByThisTrade = nonCoveredDependencies.Intersect(trade.MarketDependencies).Count();
                if (dependenciesCoveredByThisTrade > 0)
                {
                    double costFactor = tradeCost / dependenciesCoveredByThisTrade;
                    if (costFactor < minTradeCostFactor)
                    {
                        minTradeCostFactor = costFactor;
                        minTradeIndex      = i;
                    }
                }
            }

            minTradeCost = tradeCosts[portfolio.Trades[minTradeIndex].TCN];
            return(portfolio.Trades[minTradeIndex]);
        }
Пример #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OrderTicketHandlerBase"/> class.
        /// </summary>
        /// <param name="portfolio">The portfoliomanager.</param>
        public virtual void Initialize(IPortfolio portfolio)
        {
            //Check if we are already initialized
            if (Portfolio != null)
            {
                return;
            }

            //Set portfolio
            Portfolio = portfolio;

            //Set events
            BrokerConnection.OrderStateChange += (sender, orderticketevent) =>
            {
                if (!portfolio.IsBacktesting)
                {
                    _log.Trace($"Order Ticket Event received: {orderticketevent}");
                }
                HandleOrderTicketEvent(orderticketevent);
            };

            BrokerConnection.BalanceChange += (sender, accountaction) => HandleAccountEvent(accountaction);

            //Get current funds
            _log.Debug($"Performing initial sync of funds");
            SyncbrokerageFunds();
            _log.Debug($"Known Funds: ");
            portfolio.CashManager.GetCashPositions().ForEach(pos => _log.Debug($"\t {pos.Key}: {pos.Value.TotalCash}"));
        }
Пример #8
0
        /// <summary>
        /// The record rule breach.
        /// </summary>
        /// <param name="lastTrade">
        /// The last trade.
        /// </param>
        /// <param name="alignedSentiment">
        /// The aligned sentiment.
        /// </param>
        /// <param name="opposingSentiment">
        /// The opposing sentiment.
        /// </param>
        private void RecordRuleBreach(Order lastTrade, IPortfolio alignedSentiment, IPortfolio opposingSentiment)
        {
            this.logger.LogInformation($"rule breach detected for {lastTrade.Instrument?.Identifiers}");

            var tradingPosition  = new TradePosition(alignedSentiment.Ledger.FullLedger().ToList());
            var opposingPosition = new TradePosition(opposingSentiment.Ledger.FullLedger().ToList());

            // wrong but should be a judgement anyway
            var ruleBreach = new SpoofingRuleBreach(
                this.OrganisationFactorValue,
                this.ruleContext.SystemProcessOperationContext(),
                this.ruleContext.CorrelationId(),
                this.equitiesParameters.Windows?.BackwardWindowSize ?? TimeSpan.FromMinutes(30),
                tradingPosition,
                opposingPosition,
                lastTrade.Instrument,
                lastTrade,
                this.equitiesParameters,
                null,
                null,
                this.UniverseDateTime);

            var alert = new UniverseAlertEvent(Rules.Spoofing, ruleBreach, this.ruleContext);

            this.alertStream.Add(alert);
        }
Пример #9
0
 public bool Update(IPortfolio entity)
 {
     return(mapperHelper.Update(entity,
                                (cmd, portfolio) => UpdateParameters(cmd, portfolio),
                                "update Portfolio set totalval=@total where name=@id"
                                ));
 }
Пример #10
0
 public static void AssertSensibleValue(IPortfolio portfolio)
 {
     Assert.NotNull(portfolio);
     Assert.NotNull(portfolio.UniqueId);
     Assert.NotNull(portfolio.Name);
     AssertSensibleValue(portfolio.Root);
 }
Пример #11
0
 public Network(
     IPortfolio portfolio,
     INodeSimulator nodeSimulator
     )
 {
     Portfolio      = portfolio;
     _nodeSimulator = nodeSimulator;
 }
Пример #12
0
 public CompiledViewDefinitionImpl(ViewDefinition viewDefinition, IPortfolio portfolio, DateTimeOffset latestValidity, DateTimeOffset earliestValidity, Dictionary<string, ICompiledViewCalculationConfiguration> compiledCalculationConfigurations)
 {
     _viewDefinition = viewDefinition;
     _compiledCalculationConfigurations = compiledCalculationConfigurations;
     _earliestValidity = earliestValidity;
     _latestValidity = latestValidity;
     _portfolio = portfolio;
 }
Пример #13
0
        public void SetUp()
        {
            _mockBroker    = Substitute.For <IStockbroker>();
            _mockSignal    = Substitute.For <ISignal>();
            _mockPortfolio = Substitute.For <IPortfolio>();

            _trader = new Trader(_mockBroker, _mockPortfolio);
        }
        public static IPortfolio Create(IPortfolio samplePortfolio, string name, double mean, double variance)
        {
            Portfolio portf = new Portfolio(name, mean, variance);

            portf.AddRange(samplePortfolio);
            portf.SetConstraints(samplePortfolio.Constraints);
            return(portf);
        }
Пример #15
0
        public void removePortfolioTest()
        {
            IPortfolio p = ctx().Portfolios.Find("555555555_portfolio");

            ctx().DeletePortfolio(p);
            p = ctx().Portfolios.Find("555555555_portfolio");
            Assert.AreEqual(null, p);
        }
Пример #16
0
        public void UpdatePortfolioQuantity(IPortfolio entity)
        {
            Portfolio dbportfolio = dbContext.Portfolios.Where(s => s.UserId == entity.UserId && s.StockSymbol == entity.StockSymbol).FirstOrDefault();

            dbportfolio.Quantity = entity.Quantity;

            dbContext.SaveChanges();
        }
Пример #17
0
 private static int CountRows(IPortfolio portfolio)
 {
     if (portfolio == null)
     {
         return(0);
     }
     return(CountRows(portfolio.Root));
 }
Пример #18
0
 public PortfolioProxy(IPortfolio p, IContext ctx) : base()
 {
     context       = ctx;
     base.client   = p.client;
     base.name     = p.name;
     base.Position = null;
     base.totalval = p.totalval;
 }
Пример #19
0
        public void Init()
        {
            _portfolioDisplay = Substitute.For <IPortfolioDisplay>();
            _stock            = Substitute.For <Stock>("Name", 1.0M);

            _uut      = new Portfolio("Name", _portfolioDisplay);
            _observer = Substitute.For <IObserver>();
        }
 public CompiledViewDefinitionImpl(ViewDefinition viewDefinition, IPortfolio portfolio, DateTimeOffset latestValidity, DateTimeOffset earliestValidity, Dictionary <string, ICompiledViewCalculationConfiguration> compiledCalculationConfigurations)
 {
     _viewDefinition = viewDefinition;
     _compiledCalculationConfigurations = compiledCalculationConfigurations;
     _earliestValidity = earliestValidity;
     _latestValidity   = latestValidity;
     _portfolio        = portfolio;
 }
        /// <summary>
        /// Calculates the portolio Sharpe ratio, i.e. the mean return of the portfolio above that of the risk-free rate divided by the portfolio's risk (standard deviation)
        /// </summary>
        /// <param name="portfolio">Portfolio definition</param>
        /// <param name="riskFreeRate">Risk-free rate of return specified as a fractional value, e.g. 0.05 for 5%</param>
        /// <returns></returns>
        public static double SharpeRatio(IPortfolio portfolio, double riskFreeRate = 0)
        {
            if (riskFreeRate >= 1 || riskFreeRate < 0)
            {
                throw new ArgumentException("The risk-free rate should be a value between 0 and 1");
            }

            return(Math.Round((portfolio.Mean - riskFreeRate) / Math.Sqrt(portfolio.Covariance[portfolio.Name]), DecimalDigits));
        }
Пример #22
0
        public PortfolioViewModel MapPortfolioToViewModel(IPortfolio portfolio)
        {
            var viewModel = new PortfolioViewModel();

            viewModel.Statistics           = _statisticMapper.MapStatisticToViewModel(portfolio.Statistics);
            viewModel.Histogram            = portfolio.Histogram;
            viewModel.SuccessProbabilities = portfolio.SuccessProbabilities;
            return(viewModel);
        }
Пример #23
0
        private IList <INode> SetPortfolio(IList <INode> portfolioNodes, IPortfolio portfolio)
        {
            foreach (var node in portfolioNodes)
            {
                node.Portfolio = portfolio;
            }

            return(portfolioNodes);
        }
Пример #24
0
        string GetPortfolioMemo(IPortfolio portfolio)
        {
            var s = "Position Value:";

            s += portfolio.PositionCapital.ToString();
            s += ",Capital:";
            s += portfolio.CurrentCapital.ToString();
            return(s);
        }
Пример #25
0
        public void Init()
        {
            _portfolio = Substitute.For <IPortfolio>();
            _stock     = Substitute.For <IStock>();

            _portfolio.Name.Returns("Folder1");
            _portfolio.Total.Returns(1);
            _stock.Name.Returns("stock1");
            _stock.Value.Returns(1M);
        }
        /// <summary>
        /// Calculate the Global Minimum Variance Portfolio using the universe of assets and constraints defined in <paramref name="portfolio"/>
        /// </summary>
        /// <param name="portfolio">The portfolio definition</param>
        /// <param name="riskFreeRate">The risk-free rate specified as a fractional decimal value e.g. 0.05 for 5%</param>
        /// <returns>The Global Minimum Variance portfolio as an instance that implements <typeparamref name="IPortfolio"/></returns>
        public static IPortfolio CalcMinimumVariance(IPortfolio portfolio, double riskFreeRate)
        {
 #if RDEP
            if (!_initialized)
            {
                Initialize();
            }
#endif
            return(portfolio.CalculateMinVariancePortfolio());
        }
Пример #27
0
 public bool Apply(IPortfolio p, ITrade t)
 {
     IPosition pos = p.Positions.Where(x => x.symbol.name == t.symbol.name).FirstOrDefault();
     if (pos == null) return false;
     if ((t.value + pos.price) / p.Value > MaxAllocation)
     {
         throw new AllocationViolation();
     }
     return true;
 }
Пример #28
0
        protected void InsertParameters(IDbCommand cmd, IPortfolio p)
        {
            SqlParameter id = new SqlParameter("@id", p.name);
            SqlParameter tv = new SqlParameter("@total", p.totalval);

            id.Direction = ParameterDirection.InputOutput;

            cmd.Parameters.Add(id);
            cmd.Parameters.Add(tv);
        }
Пример #29
0
 /// <summary>
 /// Initialize new pending order
 /// </summary>
 /// <param name="portfolio"></param>
 /// <param name="fundid"></param>
 /// <param name="order"></param>
 /// <param name="comment"></param>
 /// <param name="createdutc"></param>
 /// <param name="issimulated">If true, order behavior is simulated</param>
 public PendingOrder(IPortfolio portfolio, string fundid, Order order, string comment, DateTime createdutc, bool issimulated = false)
 {
     _portfolio          = portfolio;
     _orderTicketHandler = portfolio.OrderTicketHandler;
     FundId      = fundid;
     Order       = order;
     CreatedUtc  = createdutc;
     IsSimulated = issimulated;
     Comment     = comment;
 }
Пример #30
0
        private void DeletePortfolio()
        {
            Console.WriteLine("DeletePortfolio()");
            Console.WriteLine();
            Console.WriteLine("Please insert a name:");
            IPortfolio portfolio = context.Portfolios.Find(Console.ReadLine());

            context.DeletePortfolio(portfolio);
            Console.WriteLine("Portfolio deleted successfully");
        }
        /// <summary>
        /// Calculate the Efficient Frontier and Minimum Variance locus using the universe of assets and constraints defined in <paramref name="portfolio"/>
        /// </summary>
        /// <param name="portfolio">The portfolio definition</param>
        /// <param name="riskFreeRate">The risk-free rate specified as a fractional decimal value e.g. 0.05 for 5%</param>
        /// <param name="numberOfPortfolios">The number of portfolios in the efficient frontier locus</param>
        /// <returns>A collection of portfolios</returns>
        public static IPortfolioCollection CalcEfficientFrontier(IPortfolio portfolio, double riskFreeRate, uint numberOfPortfolios)
        {
#if RDEP
            if (!_initialized)
            {
                Initialize();
            }
#endif
            PortfolioCollection frontier = new PortfolioCollection("Efficient Frontier", riskFreeRate);
            return(frontier.CalculateMVFrontier(portfolio, numberOfPortfolios));
        }
        // Additional Performance Metrics - Bugs - Still needs some work
        public static Dictionary <string, double> MarginalReturn(IPortfolio portfolio)
        {
            var marr = new Dictionary <string, double>();

            foreach (var p in portfolio)
            {
                marr.Add(p.ID, p.Weight / portfolio.Mean);
            }

            return(marr);
        }
Пример #33
0
 public bool Apply(IPortfolio p, ITrade t)
 {
     if (t.type != tradeTypes.Buy) return true;
     if (t.price * t.quantity > p.Cash)
     {
         InsufficientFunds ex = new InsufficientFunds();
         ex.Data.Add("AvailableFunds", p.Cash);
         ex.Data.Add("TransactionAmount", t.price * t.quantity);
         throw ex;
     }
     return true;
 }
Пример #34
0
 public void BuyPortfolioEntry(IPortfolio entity)
 {
     var existingRecord = dbContext.Portfolios.Where(p => p.StockSymbol == entity.StockSymbol && p.UserId == entity.UserId).FirstOrDefault();
     if(existingRecord == null)
     {
         Create(entity);
     }
     else
     {
         entity.Quantity += existingRecord.Quantity.Value;
         UpdatePortfolioQuantity(entity);
     }
 }
Пример #35
0
 public BackTest(
     IEventBus eventBus,
     IDataHandler bars, 
     IStrategy strategy, 
     IPortfolio portfolio, 
     IExecutionHandler executionHandler)
 {
     this.eventBus = eventBus;
     this.bars = bars;
     this.strategy = strategy;
     this.portfolio = portfolio;
     this.executionHandler = executionHandler;
     this.stopWatch = new Stopwatch();
 }
 public void Create(IPortfolio portfolio, StockAction stockAction)
 {
     var stock = dbContext.Stocks.Where(s => s.Symbol == portfolio.StockSymbol).FirstOrDefault();
     bool purchased = stockAction == StockAction.Bought ? true : false;
     ITransactionLog entity = new Model.TransactionLog
     {
         Price = stock.LastPrice.Value,
         StockId = stock.ID,
         StockSymbol = stock.Symbol,
         Purchased = purchased,
         Quantity = portfolio.Quantity,
         TransactionDate = DateTime.Now
     };
     dbContext.TransactionLogs.Add(Mapper.Map<ITransactionLog, Data.TransactionLog>(entity));
     dbContext.SaveChanges();
 }
Пример #37
0
 public AdmnController(IUser userService,
     IDomain domainService,
     IWebContent webContentService,
     IWebPages webPagesService,
     IECommerce ecommerceService,
     IPOI poiService,
     ITemplate templateService,
     IPortfolio portfolioService,
     IGallery galleryService)
     : base(domainService)
 {
     this.UserService = userService;
     this.DomainService = domainService;
     this.WebContentService = webContentService;
     this.WebPagesService = webPagesService;
     this.ECommerceService = ecommerceService;
     this.POIService = poiService;
     this.TemplateService = templateService;
     this.PortfolioService = portfolioService;
     this.GalleryService = galleryService;
 }
Пример #38
0
 public void SellPortfolioEntry(IPortfolio entity)
 {
     var existingRecord = dbContext.Portfolios.Where(p => p.StockSymbol == entity.StockSymbol && p.UserId == entity.UserId).FirstOrDefault();
     if(existingRecord == null)
     {
         //user tries to sell a stock that he/she doesn't own
         return;
     }
     if(existingRecord.Quantity == entity.Quantity)
     {
         Delete(entity.UserId, entity.StockSymbol);
     }
     else if (existingRecord.Quantity > 0)
     {
         entity.Quantity = existingRecord.Quantity.Value - entity.Quantity;
         UpdatePortfolioQuantity(entity);
     }
     else
     {
         //user tried to sell more than they have
     }
 }
Пример #39
0
 public void Create(IPortfolio entity)
 {
     dbContext.Portfolios.Add(Mapper.Map<IPortfolio, ATF.Data.Portfolio>(entity));
     dbContext.SaveChanges();
 }
Пример #40
0
 public void UpdatePortfolio(IPortfolio portfolio)
 {
     portfolioDAL.AddPortfolio(portfolio);
 }
 private static int CountRows(IPortfolio portfolio)
 {
     if (portfolio == null)
         return 0;
     return CountRows(portfolio.Root);
 }
Пример #42
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="article"></param>
        public static void UpdatePortfolio(IPortfolio portfolio)
        {
            // Create the Database object, using the default database service. The
               // default database service is determined through configuration.
               Database db = DatabaseFactory.CreateDatabase();

               string sqlCommand = "UpdatePortfolio";
               DbCommand commentaryCommand = db.GetStoredProcCommand(sqlCommand);

               db.AddInParameter(commentaryCommand, "StockTransactionId", DbType.Int32, portfolio.StockTransactionId);
               db.AddInParameter(commentaryCommand, "PortfolioId", DbType.Int32, portfolio.PortfolioId);
               db.AddInParameter(commentaryCommand, "CompanyName", DbType.String, portfolio.CompanyName);
               db.AddInParameter(commentaryCommand, "StockTicker", DbType.String, portfolio.StockTicker);
               db.AddInParameter(commentaryCommand, "BuyOrSellId", DbType.Int32, portfolio.BuyOrSellId);
               db.AddInParameter(commentaryCommand, "Qty", DbType.Int32, portfolio.Qty);
               db.AddInParameter(commentaryCommand, "EntryPrice", DbType.Decimal, portfolio.EntryPrice);
               db.AddInParameter(commentaryCommand, "ExitPrice", DbType.Decimal, portfolio.ExitPrice);
               db.AddInParameter(commentaryCommand, "StopLoss", DbType.Decimal, portfolio.StopLoss);
               db.AddInParameter(commentaryCommand, "Updates", DbType.String, portfolio.Updates);
               db.AddInParameter(commentaryCommand, "UpdateDateTime", DbType.String, GlobalFunctions.GetCurrentTimeInEST());
               db.AddInParameter(commentaryCommand, "PortfolioEntryDate", DbType.DateTime, portfolio.PortfolioExitDate);
               db.AddInParameter(commentaryCommand, "PortfolioExitDate", DbType.DateTime, portfolio.PortfolioExitDate);
               db.AddInParameter(commentaryCommand, "CallStatus", DbType.String, portfolio.CallStatus);
               db.AddInParameter(commentaryCommand, "IsPartiallyExited", DbType.Boolean, portfolio.IsPartiallyExited);

               using (DbConnection connection = db.CreateConnection())
               {
               connection.Open();
               db.ExecuteNonQuery(commentaryCommand);
               connection.Close();
               }
        }
Пример #43
0
        public void UpdatePortfolioQuantity(IPortfolio entity)
        {
            Portfolio dbportfolio = dbContext.Portfolios.Where(s => s.UserId == entity.UserId && s.StockSymbol == entity.StockSymbol).FirstOrDefault();

            dbportfolio.Quantity = entity.Quantity;

            dbContext.SaveChanges();
        }