public string GetReport(Portfolio portfolio, IEnumerable<Category> categories, IEnumerable<CategoryWeight> weights)
        {
            var reportBuilder = new StringBuilder();
            var quotes = GetQuotes(portfolio);
            var valuesDict = CalculateValues(portfolio, quotes);
            var weightsList = weights.ToList();

            //DebugPrint(reportBuilder, valuesDict);

            var total = valuesDict.Values.Where(v => v > 0M).Sum();
            reportBuilder.AppendLine(string.Format("Portfolio: {0}", portfolio.Name));
            foreach (var category in categories)
            {
                Dictionary<string, decimal> calculations = new Dictionary<string, decimal>();

                foreach (var kvpair in valuesDict)
                {
                    var weight = weightsList.Single(w => w.Security.Symbol.Equals(kvpair.Key) && w.Value.Category == category);
                    if (calculations.ContainsKey(weight.Value.Name))
                        calculations[weight.Value.Name] += kvpair.Value;
                    else
                        calculations.Add(weight.Value.Name, kvpair.Value);
                }

                reportBuilder.AppendLine(string.Format("\r\n{0}", category.Name));
                foreach (var kvpair in calculations.OrderByDescending(kv => kv.Value))
                {
                    reportBuilder.AppendLine(String.Format("{0}: {1:N1}%", kvpair.Key, kvpair.Value / total * 100M));
                }
            }

            return reportBuilder.ToString();
        }
        public static Portfolio GenerateDefaultPortfolio()
        {
            Security goog = new Security {Symbol = "goog"};
            Security msft = new Security {Symbol = "msft"};
            Security aapl = new Security {Symbol = "aapl"};

            Portfolio portfolio = new Portfolio
            {
                Name = "po' boy"
            };

            Account mandingo = new Account
            {
                Name = "mandingo",
                Portfolio = portfolio
            };
            AddPosition(mandingo, goog, 100M, 12.34M);
            AddPosition(mandingo, aapl, 200M, 23.45M);
            portfolio.Accounts.Add(mandingo);

            Account took = new Account
            {
                Name = "took",
                Portfolio = portfolio
            };
            AddPosition(took, msft, 100M, 34.56M);
            portfolio.Accounts.Add(took);

            return portfolio;
        }
        private static IDictionary<string, decimal> CalculateValues(Portfolio portfolio, IDictionary<string, decimal> quotes)
        {
            var results = new Dictionary<string, decimal>();

            foreach (var account in portfolio.Accounts)
            {
                foreach (var position in account.Positions)
                {
                    try
                    {
                        var price = quotes[position.Security.Symbol];
                        var value = price * position.Shares;
                        if (results.ContainsKey(position.Security.Symbol))
                            results[position.Security.Symbol] += value;
                        else
                            results.Add(position.Security.Symbol, value);
                    }
                    catch (KeyNotFoundException)
                    {
                        results.Add(position.Security.Symbol, -1M);
                    }
                }
            }

            return results;
        }
        public VMEditingPortfolio(Portfolio portfolio,  int userId, List<Project> projectCatalog = null)
        {
            Title = portfolio.Title;
            Description = portfolio.Description;
            Projects = new List<VMProject>();
            if (portfolio.Projects != null && portfolio.Projects.Count > 0)
            {
                foreach (Project u in portfolio.Projects)
                {
                    Projects.Add(new VMProject(u, portfolio.UserId));
                }
            }
            ProjectCatalog = new List<VMProject>();
            if (projectCatalog != null && projectCatalog.Count > 0)
            {
                foreach (Project u in projectCatalog)
                {
                    //Projects.Add(new VMProject(u, userId));
                    ProjectCatalog.Add(new VMProject(u, userId));
                }
            }
            Visibility = (VisibilityType)portfolio.Visibility;

            UserId = portfolio.UserId;
            Id = portfolio.Id;
            IsMainPortfolio = portfolio.IsMainPortfolio;
        }
        private static IDictionary<DateTime, IDictionary<IDomainEntity, decimal>> GetValues(Portfolio portfolio, IDictionary<DateTime, IDictionary<string, decimal>> priceDates)
        {
            var results = new Dictionary<DateTime, IDictionary<IDomainEntity, decimal>>();

            foreach (var date in priceDates.Keys)
            {
                var values = new Dictionary<IDomainEntity, decimal>();
                results[date] = values;
                var prices = priceDates[date];

                foreach (var account in portfolio.Accounts)
                {
                    foreach (var position in account.Positions)
                    {
                        try
                        {
                            var price = prices[position.Security.Symbol];
                            var value = price*position.Shares;
                            values.Add(position, value);
                        }
                        catch (KeyNotFoundException)
                        {
                            values.Add(position, -1M);
                        }
                    }
                }
            }

            return results;
        }
 public void LoadPortfolio(int pPortfolioId)
 {
     Portfolio portfolio = new Portfolio(pPortfolioId);
     txtProjectName.Text = portfolio.ProjectName;
     txtProjectDescription.Text = portfolio.ProjectDescription;
     String toolsAndTechnique = portfolio.ToolsAndTechniques;
     String[] toolsAndTechniquesArr = toolsAndTechnique.Split(new Char[] {','}, StringSplitOptions.RemoveEmptyEntries);
     //Int32[] tools = toolsAndTechniquesArr.ToArray<Int32>();
     //for (int i = 0; i < toolsAndTechnique.Length; i++)
     //{
     //    tools[i] = Int32.Parse(toolsAndTechniquesArr[i]);
     //}
     BindToolsAndTechniques();
     ArrayList l = new ArrayList();
     for (int i = 0; i < toolsAndTechniquesArr.Length; i++)
     {
         l.Add(Int32.Parse(toolsAndTechniquesArr[i]));
     }
     foreach (ListItem item in chkBoxList1.Items)
     {
         if(l.Contains(Int32.Parse(item.Value)))
         {
             item.Selected = true;
         }
     }
     txtProjectURL.Text = portfolio.ProjectURL;
 }
Example #7
0
        private TradingResult PerformBackTesting( SystemResult systemResult )
        {
            if ( systemResult.Prices.Empty() || systemResult.Signals.Empty() )
            {
                return null;
            }

            const int InitialCash = 10000;
            var tradingLog = new TradingLog();
            var portfolio = new Portfolio( InitialCash, Broker, tradingLog );

            foreach ( var signal in systemResult.Signals )
            {
                if ( signal.Value.Type == SignalType.Buy )
                {
                    var price = systemResult.Prices[ signal.Time ];
                    portfolio.Buy( signal.Time, price.Value );
                }
                else if ( signal.Value.Type == SignalType.Sell )
                {
                    var price = systemResult.Prices[ signal.Time ];
                    portfolio.Sell( signal.Time, price.Value );
                }
            }

            return new TradingResult( systemResult )
            {
                TradingTimeSpan = systemResult.Prices.Last().Time - systemResult.Prices.First().Time,
                TradingLog = tradingLog,
                InitialCash = InitialCash,
                PortfolioValue = portfolio.GetValue( systemResult.Prices.Last().Value )
            };
        }
        public void UpdatePortfolio(Portfolio.Portfolio portfolio, Ranking[] previousRankings, Ranking[] currentRankings)
        {
            // check whether we should sell the stock
            Ranking previousTop = previousRankings.First();
            Ranking currentTop = currentRankings.First();

            // let's give ourselves some money
            portfolio.Cash += portfolio.MonthlyIncrease;

            if (String.Equals(previousTop.Stock.Ticker, currentTop.Stock.Ticker, StringComparison.OrdinalIgnoreCase))
            {
                // same stock so just buy
                portfolio.BuyStock(currentTop.Stock, portfolio.MonthlyIncrease);
            }
            else
            {
                // have to sell first
                // we look for the stock to sell
                Stock previousTopRightNow = currentRankings.
                    First(ranking => String.Equals(ranking.Stock.Ticker, previousTop.Stock.Ticker, StringComparison.OrdinalIgnoreCase))
                    .Stock;

                // sell all of it
                portfolio.SellStock(previousTopRightNow, portfolio.GetStockShares(previousTopRightNow));

                // time to buy all
                portfolio.BuyStock(currentTop.Stock, portfolio.TotalValue);
            }
        }
Example #9
0
 public Position(Portfolio portfolio, Instrument instrument)
 {
     Portfolio = portfolio;
     Instrument = instrument;
     PortfolioId = portfolio.Id;
     InstrumentId = instrument.Id;
 }
 public ActionResult PortfolioCreateEdit(int id = -1)
 {
     if (RouteData.Values["id"] != null)
     {
         if (int.TryParse(RouteData.Values["id"].ToString(), out id)) { }
     }
     Portfolio p = new Portfolio();
     if (id != -1)
     {
         p = db.retrievePortfolio(id);
         if (p == null)
         {
             string error1 = "The Portfolio you tried to edit either does not exist or could not be found.";
             string error2 = "Portfolio Id: " + id;
             TempData["ErrorMessages"] = new string[] { error1, error2 };
             return RedirectToAction("Http404", "Error");
         }
     }
     int userId = WebSecurity.CurrentUserId;
     List<Project> projects = db.retrieveAllProjectsByUserID(userId);
     VMEditingPortfolio vmEdit;
     if (projects != null)
     {
         vmEdit = new VMEditingPortfolio(p, userId, projects);
     }
     else
     {
         vmEdit = new VMEditingPortfolio(p, userId);
     }
     return View(vmEdit);
 }
Example #11
0
		private void Init(string name, Portfolio portfolio, bool reportEnabled, List<Parameter> parameters)
		{
			this.Name = name;
			this.Portfolio = portfolio;
			this.Performance = new Performance(portfolio);
			this.ReportEnabled = reportEnabled;
			this.Parameters = new ParameterSet(parameters);
		}
Example #12
0
 public void OnPositionOpened(Portfolio portfolio, Position position, bool queued)
 {
     var e = new OnPositionOpened(portfolio, position);
     if (queued)
         this.queue.Enqueue(e);
     else
         OnEvent(e);
 }
        /// <summary>
        /// Just buy stock that ranks first
        /// </summary>
        /// <param name="portfolio"></param>
        /// <param name="rankings"></param>
        public void SetUpPortFolio(Portfolio.Portfolio portfolio, Ranking[] rankings)
        {
            // top ranked
            Ranking topRanked = rankings.First();

            // buy the stock that rank first
            portfolio.BuyStock(topRanked.Stock, portfolio.Cash);
        }
Example #14
0
 public Portfolio getDeltaPortfolio(DateTime t)
 {
     List<IAsset> list_asset = new List<IAsset>();
     list_asset.Add(underlying);
     Portfolio port = new Portfolio(list_asset);
     port.addAsset(underlying, this.getDelta(t));
     return port;
 }
 private IDictionary<string, decimal> GetQuotes(Portfolio portfolio)
 {
     var securities = new List<Security>();
     foreach (var account in portfolio.Accounts)
     {
         securities.AddRange(account.Positions.Select(p => p.Security));
     }
     return _quoter.GetQuotes(securities.Distinct());
 }
        void Download13F(object args)
        {
            this.portfolio = new Portfolio();
            foreach (Form13F form in Edgar.FetchForm13Fs(args as string, 6))
            {
                portfolio.Add(form);
            }

            this.Invoke(new EnableDelegate(this.Enable));
        }
 private void Init(Portfolio portfolio)
 {
     portfolio.IsLoaded = true;
     portfolio.Init(this.framework);
     this.framework.PortfolioManager.Add(portfolio, true);
     foreach (Portfolio p in portfolio.Children)
     {
         Init(p);
         p.Parent = portfolio;
     }
 }
Example #18
0
        public static void LoadOMSTrades(object[,] objArray, Portfolio pf)
        {
            Dictionary<string, OMSTrade> omsTrades = new Dictionary<string, OMSTrade>();
            ReflectionFactory.LoadObjArrayByReflection<OMSTrade>(objArray, omsTrades);

            foreach (OMSTrade omsTrade in omsTrades.Values)
            {
                omsTrade.PostConstruct();
                pf.Trades.Add(omsTrade.Dnum, omsTrade); // you cannot do List<ParentClass> x = new List<DerivedClassA> bec. then you cannot add any DerivedClassB objects anymore... makes sense 
            }
        }
Example #19
0
		private void Init(string name, Portfolio portfolio, DateTime startDate, DateTime stopDate, double cash, bool reportEnabled, List<Project> projects)
		{
			this.Name = name;
			this.Portfolio = portfolio;
			this.Performance = new Performance(portfolio);
			this.StartDate = startDate;
			this.StopDate = stopDate;
			this.Cash = cash;
			this.ReportEnabled = reportEnabled;
			this.Projects = new ProjectList(projects);
		}
        public string Get2DReport(Portfolio portfolio, Category x, Category y, IEnumerable<CategoryWeight> weights)
        {
            var reportBuilder = new StringBuilder();
            var quotes = GetQuotes(portfolio);
            var valuesDict = CalculateValues(portfolio, quotes);
            var weightsList = weights.ToList();

            var total = valuesDict.Values.Where(v => v > 0M).Sum();

            return reportBuilder.ToString();
        }
 public ActionResult AddDummyPortfolio()
 {
     int ID = int.Parse(RouteData.Values["id"].ToString());
     Portfolio p = new Portfolio
     {
         Title = RandomTitle(),
         Visibility = (int)VisibilityType.Public,
         Description = RandomDescription(),
     };
     data.addPortfolio(p, ID);
     return RedirectToAction("AllUsers", "Admin");
 }
Example #22
0
 public static Portfolio GetOrCreatePortfolio(this Framework framework, string name, bool emitEvent = true)
 {
     Portfolio portfolio;
     if (framework.PortfolioManager.Portfolios.Contains(name))
         portfolio  = framework.PortfolioManager.Portfolios.GetByName(name);
     else
     {
         portfolio = new Portfolio(framework, name);
         framework.PortfolioManager.Add(portfolio, emitEvent);
     }
     return portfolio;
 }
Example #23
0
 public void OnInit(string name, Portfolio portfolioControl)
 {
   this.name = name;
   this.portfolioControl = portfolioControl;
   this.portfolio = Framework.Current.PortfolioManager[name];
   this.PositionViewItems.Clear();
   this.ltvPositions.Items.Clear();
   this.TransactionsViewItems.Clear();
   this.ltvTransactions.VirtualListSize = this.TransactionsViewItems.Count;
   this.ltvPortfolio.Items.Clear();
   this.ltvPortfolio.Items.Add(new ListViewItem(new string[this.ltvPortfolio.Columns.Count]));
 }
        public Portfolio.Portfolio BackTest(Indicator.GenericIndicator indicator, HistoricalDataSet dataSet, Portfolio.Portfolio portfolio)
        {
            Ranking[][] rankingTable = dataSet.GetRankingTable(indicator);

            SetUpPortFolio(portfolio, rankingTable[0]);

            for(int i = 1; i < rankingTable.Length; i += 1)
            {
                UpdatePortfolio(portfolio, rankingTable[i-1], rankingTable[i]);
            }

            return portfolio;
        }
Example #25
0
 public TradeDetector(TradeDetectionType type, Portfolio portfolio)
 {
     this.portfolio_0 = portfolio;
     if (type == TradeDetectionType.FIFO)
     {
         this.interface0_0 = new QueueFillSet();
     }
     else
     {
         this.interface0_0 = new StackFillSet();
     }
     this.list_0 = new List<TradeInfo>();
     this.timeSeries_0 = new TimeSeries();
 }
        public void Add(Portfolio portfolio, bool emitEvent = true)
        {
            if (portfolio.Id == -1)
                portfolio.Id = this.counter++;
            else
            {
                if (Portfolios.Contains(portfolio.Id))
                    Console.WriteLine($"PortfolioManager::Add portfolio {portfolio.Name} error. Portfolio with Id {portfolio.Id} already added.");
                if (portfolio.Id >= this.counter)
                    this.counter = portfolio.Id + 1;
            }

            Portfolios.Add(portfolio);
            if (emitEvent)
                this.framework.EventServer.OnPortfolioAdded(portfolio);
        }
 public VMPortfolio(Portfolio portfolio)
 {
     Title = portfolio.Title;
     Description = portfolio.Description;
     Projects = new List<VMProject>();
     if (portfolio.Projects != null && portfolio.Projects.Count > 0)
     {
         foreach (Project u in portfolio.Projects)
         {
             Projects.Add(new VMProject(u, portfolio.UserId));
         }
     }
     Visibility = (VisibilityType)portfolio.Visibility;
     Id = portfolio.Id;
     UserId = portfolio.UserId;
 }
 public ActionResult Portfolio(int id=-1)
 {
     if (RouteData.Values["id"] != null)
     {
         if (int.TryParse(RouteData.Values["id"].ToString(), out id)) { }
     }
     Portfolio p = new Portfolio();
     if (id != -1)
     {
         p = db.retrievePortfolio(id);
         if (p == null)
         {
             string error1 = "The Portfolio you tried to view either does not exist or could not be found.";
             string error2 = "Portfolio Id: " + id;
             TempData["ErrorMessages"] = new string[] { error1, error2 };
             return RedirectToAction("Http404", "Error");
         }
     }
     VMPortfolio portfolio = new VMPortfolio(p);
     return View(model: portfolio);
 }
        public string GetReport(Portfolio portfolio, DateTime start, DateTime end, Period period)
        {
            var reportBuilder = new StringBuilder();
            var prices = GetPrices(portfolio, start, end, period);
            var values = GetValues(portfolio, prices);
            var columnOrder = values.Keys.OrderBy(d => d.Date);

            // print header
            reportBuilder.Append("\t\t");
            foreach (var date in columnOrder)
            {
                reportBuilder.AppendFormat("| {0} ", date.ToString("d"));
            }
            reportBuilder.AppendLine();
            reportBuilder.Append("----------------");
            for (var i = 0; i < columnOrder.Count(); ++i)
                reportBuilder.Append("-------------");
            reportBuilder.AppendLine();

            foreach (var account in portfolio.Accounts)
            {
                reportBuilder.AppendLine(string.Format("{0,-16}", account.Name));
                foreach (var position in account.Positions)
                {
                    reportBuilder.AppendFormat("{0,-16}", position.Security.Symbol);
                    foreach (var date in columnOrder)
                    {
                        var rowValues = values[date];
                        var value = rowValues[position];
                        if (value < 0M)
                            reportBuilder.AppendFormat("| {0,10} ", " !*v*! ");
                        else
                            reportBuilder.AppendFormat("| {0,10} ", value.ToString("##.00"));
                    }
                    reportBuilder.AppendLine();
                }
            }

            return reportBuilder.ToString();
        }
        public static Portfolio GenerateEmptyPortfolio()
        {
            Portfolio portfolio = new Portfolio
            {
                Name = "po' boy"
            };
            Account mandingo = new Account
            {
                Name = "mandingo",
                Portfolio = portfolio
            };
            portfolio.Accounts.Add(mandingo);

            Account took = new Account
            {
                Name = "took",
                Portfolio = portfolio
            };
            portfolio.Accounts.Add(took);

            return portfolio;
        }