示例#1
0
        public async static Task <HttpResponseMessage> GetStockSummaryData([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req, ILogger log)
        {
            log.LogInformation("New request received");
            string symbol = req.Query["symbol"];

            if (symbol == null || symbol == "")
            {
                log.LogInformation("Symbol not present as part of request. Ending.");
                HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.BadRequest);
                hrm.Content = new StringContent("Fatal failure. Parameter 'symbol' not provided. You must provide a stock symbol to return data for.");
                return(hrm);
            }



            try
            {
                log.LogInformation("Downloading data for " + symbol);
                Equity e = Equity.Create(symbol);
                await e.DownloadSummaryAsync();

                log.LogInformation("Serializing");
                string json = JsonConvert.SerializeObject(e.Summary);
                log.LogInformation("Returning");

                HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.OK);
                hrm.Content = new StringContent(json, Encoding.UTF8, "application/json");
                return(hrm);
            }
            catch (Exception e)
            {
                string err_msg = "Fatal failure while accessing summary data for stock '" + symbol.ToUpper() + "'. Internal error message: " + e.Message;
                log.LogInformation(err_msg);
                HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.BadRequest);
                hrm.Content = new StringContent(err_msg);
                return(hrm);
            }
        }
        public async Task <string[]> PrepareTweetsFromTranscriptAsync(Transcript trans, int include_highlight_count)
        {
            //Sentence Value Pairs
            TextValuePair[] SVPs = null;
            try
            {
                SVPs = trans.RankSentences();
            }
            catch (Exception e)
            {
                throw new Exception("Fatal error while ranking transcript sentences. Internal error message: " + e.Message);
            }

            List <string> ToTweet = new List <string>();

            #region "First Tweet (Intro)"

            string Tweet1Text = "Earnings Call Highlights"; //The value here should be replaced anyway.

            //Get company symbol
            if (trans.Title.Contains("(") && trans.Title.Contains(")"))
            {
                int    loc1   = trans.Title.LastIndexOf("(");
                int    loc2   = trans.Title.IndexOf(")", loc1 + 1);
                string symbol = trans.Title.Substring(loc1 + 1, loc2 - loc1 - 1);
                Equity eq     = Equity.Create(symbol);
                await eq.DownloadSummaryAsync();

                Tweet1Text = eq.Summary.Name + " $" + symbol.ToUpper().Trim() + " held an earnings call on " + trans.CallDateTimeStamp.ToShortDateString() + ". Here are the highlights:";
            }
            else
            {
                Tweet1Text = trans.Title.Replace(" Transcript", "") + " highlights: ";
            }

            ToTweet.Add(Tweet1Text);

            #endregion

            #region "Highlights"

            int t = 0;

            for (t = 0; t < include_highlight_count; t++)
            {
                if (SVPs.Length >= (t + 1))
                {
                    try
                    {
                        //Find the speaker
                        CallParticipant speaker = trans.WhoSaid(SVPs[t].Text);

                        //Get the sentence
                        string sen = SVPs[t].Text;

                        //write the tweet
                        string ThisTweet = speaker.Name + ": \"" + sen + "\"";

                        //Trim it down (if it goes past 280 characters)
                        if (ThisTweet.Length > 280)
                        {
                            ThisTweet = ThisTweet.Substring(0, 276);
                            ThisTweet = ThisTweet + "...\"";
                        }

                        //Add it
                        ToTweet.Add(ThisTweet);
                    }
                    catch
                    {
                    }
                }
            }

            #endregion


            return(ToTweet.ToArray());
        }
        public async Task <string> PrepareNewForm4TweetAsync(StatementOfBeneficialOwnership form4)
        {
            string ToReturn = null;

            foreach (NonDerivativeTransaction ndt in form4.NonDerivativeTransactions)
            {
                if (ndt.AcquiredOrDisposed == AcquiredDisposed.Acquired)                        //They acquired
                {
                    if (ndt.TransactionCode != null)                                            //It is indeed a transaction, not just a holding report
                    {
                        if (ndt.TransactionCode == TransactionType.OpenMarketOrPrivatePurchase) //Open market purchase
                        {
                            //Get the equity cost
                            Equity e = Equity.Create(form4.IssuerTradingSymbol);
                            await e.DownloadSummaryAsync();

                            //Get the name to use
                            string TraderNameToUse = form4.OwnerName;
                            try
                            {
                                TraderNameToUse = Aletheia.AletheiaToolkit.NormalizeAndRearrangeForm4Name(form4.OwnerName);
                            }
                            catch
                            {
                            }

                            //Start
                            ToReturn = "*INSIDER BUY ALERT*" + Environment.NewLine;
                            ToReturn = ToReturn + form4.OwnerName;

                            //Is there an officer title? If so, loop it in
                            if (form4.OwnerOfficerTitle != null && form4.OwnerOfficerTitle != "")
                            {
                                ToReturn = ToReturn + ", " + form4.OwnerOfficerTitle + ", ";
                            }
                            else
                            {
                                ToReturn = ToReturn + " ";
                            }

                            //Continue
                            ToReturn = ToReturn + "purchased " + ndt.TransactionQuantity.Value.ToString("#,##0") + " shares of $" + form4.IssuerTradingSymbol.Trim().ToUpper();

                            //Was a transaction price supplied?
                            if (ndt.TransactionPricePerSecurity.HasValue)
                            {
                                ToReturn = ToReturn + " at $" + ndt.TransactionPricePerSecurity.Value.ToString("#,##0.00");
                            }

                            //Add a period
                            ToReturn = ToReturn + "." + Environment.NewLine;

                            //How much they own following transaction
                            float worth = e.Summary.Price * ndt.SecuritiesOwnedFollowingTransaction;
                            ToReturn = ToReturn + form4.OwnerName + " now owns " + ndt.SecuritiesOwnedFollowingTransaction.ToString("#,##0") + " shares worth $" + worth.ToString("#,##0") + " of " + form4.IssuerName + " stock.";
                        }
                    }
                }
            }

            //Throw an error if ToReturn is still null (the above process did not satisfy anything)
            if (ToReturn == null)
            {
                throw new Exception("The Form 4 type is not supported for tweeting.");
            }

            return(ToReturn);
        }
        public async Task TradeEquityAsync(string symbol, int quantity, TransactionType order_type)
        {
            Equity e = Equity.Create(symbol);

            try
            {
                await e.DownloadSummaryAsync();
            }
            catch
            {
                throw new Exception("Critical error while fetching equity '" + symbol + "'.  Does this equity exist?");
            }


            if (order_type == TransactionType.Buy)
            {
                //Be sure we have enough cash to buy
                float cash_needed = e.Summary.Price * quantity;
                if (Cash < cash_needed)
                {
                    throw new Exception("You do not have enough cash to execute this buy order of " + symbol.ToUpper() + ".  Cash needed: $" + cash_needed.ToString("#,##0.00") + ".  Cash balance: $" + Cash.ToString("#,##0.00"));
                }


                AddSharesAndCalculateNewAverageCostBasis(symbol.ToUpper().Trim(), quantity, e.Summary.Price, DateTimeOffset.Now);

                //Edit cash and add the shares we are buying to the balane
                Cash = Cash - cash_needed;
            }
            else if (order_type == TransactionType.Sell)
            {
                //Find our holding
                EquityHolding eh = null;
                foreach (EquityHolding ceh in EquityHoldings)
                {
                    if (ceh.Symbol.ToUpper() == symbol.ToUpper())
                    {
                        eh = ceh;
                    }
                }

                //Throw an error if we do not have any of those shares.
                if (eh == null)
                {
                    throw new Exception("You do not have any shares of " + symbol.ToUpper() + " to sell.");
                }

                //Throw an error if we do not have enough shares
                if (eh.Quantity < quantity)
                {
                    throw new Exception("You do not have " + quantity.ToString() + " shares to sell!  You only have " + eh.Quantity.ToString() + " shares.");
                }

                //Execute the transaction
                Cash        = Cash + (quantity * e.Summary.Price);
                eh.Quantity = eh.Quantity - quantity;

                //Save the transaction log
                EquityTransaction et = new EquityTransaction();
                et.UpdateTransactionTime();
                et.StockSymbol     = symbol.ToUpper().Trim();
                et.OrderType       = TransactionType.Sell;
                et.Quantity        = quantity;
                et.PriceExecutedAt = e.Summary.Price;
                EquityTransactionLog.Add(et);

                //Remove the holding if it now 0
                if (eh.Quantity == 0)
                {
                    EquityHoldings.Remove(eh);
                }
            }

            //Take out the commission (if any)
            if (TradeCost > 0)
            {
                EditCash(TradeCost * -1, CashTransactionType.TradingRelatedCharge);
            }
        }
示例#5
0
        public async static Task <HttpResponseMessage> GetStockData([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req, ILogger log)
        {
            //Get symbol
            log.LogInformation("New request received");
            string symbol = req.Query["symbol"];

            if (symbol == null || symbol == "")
            {
                log.LogInformation("Parameter 'symbol' not present as part of request. Ending.");
                HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.BadRequest);
                hrm.Content = new StringContent("Fatal failure. Parameter 'symbol' not provided. You must provide a stock symbol to return data for.");
                return(hrm);
            }
            symbol = symbol.Trim().ToUpper();
            log.LogInformation("Symbol requested: '" + symbol + "'");


            //Get Data
            bool   SummaryData            = false;
            bool   StatisticalData        = false;
            int    TryCount               = 1;
            string SummaryData_String     = req.Query["summary"];
            string StatisticalData_String = req.Query["statistics"];
            string TryCount_String        = req.Query["trycount"];

            if (SummaryData_String != null)
            {
                if (SummaryData_String.ToLower() == "true")
                {
                    SummaryData = true;
                }
            }
            if (StatisticalData_String != null)
            {
                if (StatisticalData_String.ToLower() == "true")
                {
                    StatisticalData = true;
                }
            }
            if (TryCount_String != null)
            {
                if (TryCount_String != "")
                {
                    try
                    {
                        TryCount = Convert.ToInt32(TryCount_String);
                    }
                    catch
                    {
                        string errormsg = "Unable to convert TryCount '" + TryCount_String + "' to integer.";
                        log.LogError(errormsg);
                        HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.BadRequest);
                        hrm.Content = new StringContent(errormsg);
                        return(hrm);
                    }
                }
            }

            //Log data
            log.LogInformation("Summary request: " + SummaryData.ToString());
            log.LogInformation("Statistics request: " + StatisticalData.ToString());
            log.LogInformation("Try count: " + TryCount.ToString());

            Equity e = Equity.Create(symbol);

            //Try to download summary data (if wanted)
            if (SummaryData)
            {
                int SummaryDataTimesTried = 0;
                do
                {
                    try
                    {
                        log.LogInformation("Downloading summary data...");
                        await e.DownloadSummaryAsync();

                        log.LogInformation("Successfully downloaded summary data.");
                    }
                    catch
                    {
                        SummaryDataTimesTried = SummaryDataTimesTried + 1;
                        log.LogInformation("Summary data download attempt " + SummaryDataTimesTried.ToString() + " failed.");
                    }
                } while (e.Summary == null && SummaryDataTimesTried < TryCount);

                if (e.Summary == null)
                {
                    string error_message = "Fatal failure while downloading equity summary data.";
                    log.LogError(error_message);
                    HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                    hrm.Content = new StringContent(error_message);
                    return(hrm);
                }
            }

            //Try to download statistical data (if wanted)
            if (StatisticalData)
            {
                int StatisticalDataTimesTried = 0;

                do
                {
                    try
                    {
                        log.LogInformation("Downloading statistical data...");
                        await e.DownloadStatisticsAsync();

                        log.LogInformation("Successfully downloaded statistics data.");
                    }
                    catch
                    {
                        StatisticalDataTimesTried = StatisticalDataTimesTried + 1;
                        log.LogInformation("Statistical data download attempt " + StatisticalDataTimesTried.ToString() + " failed.");
                    }
                } while (e.Statistics == null && StatisticalDataTimesTried < TryCount);

                if (e.Statistics == null)
                {
                    string error_message = "Fatal failure while downloading equity statistical data.";
                    log.LogError(error_message);
                    HttpResponseMessage hrm = new HttpResponseMessage(HttpStatusCode.InternalServerError);
                    hrm.Content = new StringContent(error_message);
                    return(hrm);
                }
            }

            log.LogInformation("Converting to JSON...");
            string ToReturnJson          = JsonConvert.SerializeObject(e);
            HttpResponseMessage ToReturn = new HttpResponseMessage(HttpStatusCode.OK);

            ToReturn.Content = new StringContent(ToReturnJson, Encoding.UTF8, "application/json");
            log.LogInformation("Returning");
            return(ToReturn);
        }