public IActionResult Dashboard()
        {
            string investmentDataRetrieved = HttpContext.Session.GetString("InvestmentDataRetrieved");

            if (string.IsNullOrEmpty(investmentDataRetrieved))
            {
                IAvapiConnection connection = AvapiConnection.Instance;
                connection.Connect("BXGO930UI9P053HT");

                string stockDataRetrieved = HttpContext.Session.GetString("StockDataRetrieved");
                if (string.IsNullOrEmpty(stockDataRetrieved))
                {
                    RetrieveStockData(connection);
                }

                string cryptoDataRetrieved = HttpContext.Session.GetString("CryptoDataRetrieved");
                if (string.IsNullOrEmpty(cryptoDataRetrieved))
                {
                    RetrieveCryptoData(connection);
                }

                HttpContext.Session.SetString("InvestmentDataRetrieved", "true");
            }

            return(View());
        }
        private void RetrieveStockData(IAvapiConnection connection)
        {
            Int_TIME_SERIES_DAILY time_series_daily = connection.GetQueryObject_TIME_SERIES_DAILY();

            List <Stock> stocks = _stockRepo.Stocks.ToList();

            foreach (var stock in stocks)
            {
                try
                {
                    IAvapiResponse_TIME_SERIES_DAILY time_series_dailyResponse = time_series_daily.Query(
                        stock.Ticker,
                        Const_TIME_SERIES_DAILY.TIME_SERIES_DAILY_outputsize.compact
                        );

                    Dictionary <DateTime, double> stockData = new Dictionary <DateTime, double>();

                    foreach (var d in time_series_dailyResponse.Data.TimeSeries)
                    {
                        stockData.Add(Convert.ToDateTime(d.DateTime), Convert.ToDouble(d.open ?? d.close));
                    }

                    string stockDataString = JsonConvert.SerializeObject(stockData);
                    HttpContext.Session.SetString(stock.Ticker, stockDataString);
                }
                catch (Exception e)
                {
                }
            }

            HttpContext.Session.SetString("StockDataRetrieved", "true");
        }
Exemple #3
0
        public Ativo CotarPrecoAtivo(string ativoString)
        {
            var    config = System.Configuration.ConfigurationManager.AppSettings;
            string apiKey = config.Get("apikeyAV");
            // Creating the connection object
            IAvapiConnection connection = AvapiConnection.Instance;

            // Set up the connection and pass the API_KEY provided by alphavantage.co
            connection.Connect(apiKey);

            // Get the TIME_SERIES_DAILY query object
            Int_TIME_SERIES_DAILY time_series_daily =
                connection.GetQueryObject_TIME_SERIES_DAILY();

            ativoString += ".SA";
            // Perform the TIME_SERIES_DAILY request and get the result
            IAvapiResponse_TIME_SERIES_DAILY time_series_dailyResponse =
                time_series_daily.Query(
                    ativoString, //Work SA prices
                    Const_TIME_SERIES_DAILY.TIME_SERIES_DAILY_outputsize.compact);



            var ativo    = MapeamentoServico.MapearParaAtivo(time_series_dailyResponse.Data.MetaData);
            var cotacoes = MapeamentoServico.MapearParaCotacoes(time_series_dailyResponse.Data.TimeSeries);

            ativo.Cotacoes = cotacoes;

            return(ativo);
        }
        private void RetrieveCryptoData(IAvapiConnection connection)
        {
            Int_DIGITAL_CURRENCY_DAILY time_series_daily = connection.GetQueryObject_DIGITAL_CURRENCY_DAILY();

            List <CryptoCurrency> stocks = _cryptoRepo.CryptoCurrencies.ToList();

            foreach (var stock in stocks)
            {
                try
                {
                    IAvapiResponse_DIGITAL_CURRENCY_DAILY time_series_dailyResponse = time_series_daily.QueryPrimitive(
                        stock.Ticker,
                        "USD"
                        );

                    Dictionary <DateTime, double> stockData = new Dictionary <DateTime, double>();

                    foreach (var d in time_series_dailyResponse.Data.TimeSeries)
                    {
                        stockData.Add(Convert.ToDateTime(d.DateTime), Convert.ToDouble(d.OpenUSD ?? d.CloseUSD));
                    }

                    string stockDataString = JsonConvert.SerializeObject(stockData);
                    HttpContext.Session.SetString(stock.Ticker, stockDataString);
                }
                catch (Exception e)
                {
                }
            }

            HttpContext.Session.SetString("CryptoDataRetrieved", "true");
        }
Exemple #5
0
        public IViewComponentResult Invoke()
        {
            double netWorth = _saveRepo.Accounts.Sum(x => x.Amount);
            netWorth -= _payRepo.PaymentMethods.Where(x => x.IsCredit).Sum(x => x.CreditBalance.Amount);

            IAvapiConnection connection = AvapiConnection.Instance;
            connection.Connect("BXGO930UI9P053HT");

            Int_TIME_SERIES_DAILY time_series_daily = connection.GetQueryObject_TIME_SERIES_DAILY();
            List<Share> shares = _sharesRepo.Shares.ToList();
            List<Stock> stocks = _stockRepo.Stocks.ToList();

            try
            {
                foreach (var stock in stocks)
                {
                    Dictionary<DateTime, double> stockData =
                        JsonConvert.DeserializeObject<Dictionary<DateTime, double>>(HttpContext.Session.GetString(stock.Ticker));

                    var sData = stockData.First();

                    List<Share> listOfShares = shares.Where(e => e.StockID == stock.ID).ToList();
                    int totalShares = listOfShares.Select(e => e.NumOfShares).Sum();
                    netWorth += Convert.ToDouble(sData.Value) * (double)totalShares;
                }
            }
            catch(Exception e)
            {

            }

            Int_DIGITAL_CURRENCY_DAILY crypto_series_daily = connection.GetQueryObject_DIGITAL_CURRENCY_DAILY();

            List<CryptoCurrency> cryptos = _cryptoRepo.CryptoCurrencies.ToList();
            List<Coin> coins = _coinRepo.Coins.ToList();

            try
            {
                foreach (var crypto in cryptos)
                {
                    Dictionary<DateTime, double> cryptoData =
                        JsonConvert.DeserializeObject<Dictionary<DateTime, double>>(HttpContext.Session.GetString(crypto.Ticker));

                    var sData = cryptoData.First();

                    List<Coin> coinList = coins.Where(e => e.CryptoCurrencyID == crypto.ID).ToList();
                    decimal totalCoins = coinList.Select(e => e.NumOfCoins).Sum();
                    netWorth += Convert.ToDouble(sData.Value) * (double)totalCoins;
                }
            }
            catch (Exception e)
            {

            }

            netWorth = Math.Round(netWorth);

            return View(netWorth);
        }
Exemple #6
0
        public void ConnectAlphaVantageApi()
        {
            // Creating the connection object
            this.connection = AvapiConnection.Instance;

            // Set up the connection and pass the API_KEY provided by alphavantage.co
            this.connection.Connect(apiKey);
        }
Exemple #7
0
        public IActionResult EditStock(StockFormViewModel model)
        {
            if (ModelState.IsValid)
            {
                Boolean shouldAddToSession = model.Stock.ID == 0;

                _stockRepo.Save(model.Stock);
                TempData["message"] = $"{model.Stock.Company} has been saved";

                if (shouldAddToSession)
                {
                    IAvapiConnection connection = AvapiConnection.Instance;
                    connection.Connect("BXGO930UI9P053HT");

                    Int_TIME_SERIES_DAILY time_series_daily = connection.GetQueryObject_TIME_SERIES_DAILY();

                    try
                    {
                        IAvapiResponse_TIME_SERIES_DAILY time_series_dailyResponse = time_series_daily.Query(
                            model.Stock.Ticker,
                            Const_TIME_SERIES_DAILY.TIME_SERIES_DAILY_outputsize.compact
                            );

                        Dictionary <DateTime, double> stockData = new Dictionary <DateTime, double>();

                        foreach (var d in time_series_dailyResponse.Data.TimeSeries)
                        {
                            stockData.Add(Convert.ToDateTime(d.DateTime), Convert.ToDouble(d.open ?? d.close));
                        }

                        string stockDataString = JsonConvert.SerializeObject(stockData);
                        HttpContext.Session.SetString(model.Stock.Ticker, stockDataString);
                    }
                    catch (Exception e)
                    {
                    }
                }

                return(RedirectToAction("Stocks"));
            }
            else
            {
                if (model.Stock.ID == 0)
                {
                    ViewBag.FormTitle = "Create Stock";
                }
                else
                {
                    ViewBag.FormTitle = "Edit Stock";
                }

                model.Sectors = new SelectList(_sectorRepo.Sectors.ToList(), "ID", "Name");
                return(View(model));
            }
        }
Exemple #8
0
        private async void DisplayPricingData(string ticker)
        {
            List <double> priceslastyear = new List <double>();
            List <string> dateslastyear  = new List <string>();
            // Creating the connection object
            IAvapiConnection connection = AvapiConnection.Instance;
            IAvapiResponse_TIME_SERIES_MONTHLY_ADJUSTED m_time_series_monthly_adjustedResponse;

            // Set up the connection and pass the API_KEY provided by alphavantage.co
            connection.Connect("7NIMRBR8G8UB7P8C");

            // Get the TIME_SERIES_MONTHLY_ADJUSTED query object
            Int_TIME_SERIES_MONTHLY_ADJUSTED time_series_monthly_adjusted =
                connection.GetQueryObject_TIME_SERIES_MONTHLY_ADJUSTED();

            // Perform the TIME_SERIES_MONTHLY_ADJUSTED request and get the result
            m_time_series_monthly_adjustedResponse = await time_series_monthly_adjusted.QueryPrimitiveAsync(
                ticker);

            var data = m_time_series_monthly_adjustedResponse.Data;

            if (data.Error)
            {
                Console.WriteLine(data.ErrorMessage);
            }
            else
            {
                int counter = 0;
                foreach (var timeseries in data.TimeSeries)
                {
                    //Grab 1 year worth of months data
                    if (counter < 12)
                    {
                        //add raw prices and dates to arrays
                        priceslastyear.Add(double.Parse(timeseries.adjustedclose, CultureInfo.InvariantCulture.NumberFormat));
                        Debug.WriteLine(float.Parse(timeseries.adjustedclose, CultureInfo.InvariantCulture.NumberFormat));
                        Debug.WriteLine(timeseries.DateTime);
                        Microcharts.Entry tempEntry = new Microcharts.Entry(float.Parse(timeseries.adjustedclose, CultureInfo.InvariantCulture.NumberFormat))
                        {
                            Label      = timeseries.DateTime,
                            ValueLabel = timeseries.adjustedclose//Color = investmentList[i].color.ToSKColor()
                        };
                        entries.Add(tempEntry);
                    }
                    counter = counter + 1;
                }
            }
            var chart = new LineChart()
            {
                Entries = entries, LineMode = LineMode.Straight, LineSize = 8, PointSize = 18, LabelTextSize = 25
            };

            this.chartView.Chart = chart;
        }
Exemple #9
0
        static void Main()
        {
            // Creating the connection object
            IAvapiConnection connection = AvapiConnection.Instance;

            // Set up the connection and pass the API_KEY provided by alphavantage.co
            connection.Connect("391C9AJGB8WP0FO5");

            // Get the TIME_SERIES_DAILY query object
            Int_TIME_SERIES_DAILY time_series_daily =
                connection.GetQueryObject_TIME_SERIES_DAILY();

            // Perform the TIME_SERIES_DAILY request and get the result
            IAvapiResponse_TIME_SERIES_DAILY time_series_dailyResponse =
                time_series_daily.Query(
                    "SPY",
                    Const_TIME_SERIES_DAILY.TIME_SERIES_DAILY_outputsize.compact,
                    Const_TIME_SERIES_DAILY.TIME_SERIES_DAILY_datatype.json);

            // Printout the results
            Console.WriteLine("******** RAW DATA TIME_SERIES_DAILY ********");
            Console.WriteLine(time_series_dailyResponse.RawData);

            Console.WriteLine("******** STRUCTURED DATA TIME_SERIES_DAILY ********");
            var data = time_series_dailyResponse.Data;

            if (data.Error)
            {
                Console.WriteLine(data.ErrorMessage);
            }
            else
            {
                Console.WriteLine("Information: " + data.MetaData.Information);
                Console.WriteLine("Symbol: " + data.MetaData.Symbol);
                Console.WriteLine("LastRefreshed: " + data.MetaData.LastRefreshed);
                Console.WriteLine("OutputSize: " + data.MetaData.OutputSize);
                Console.WriteLine("TimeZone: " + data.MetaData.TimeZone);
                Console.WriteLine("========================");
                Console.WriteLine("========================");
                foreach (var timeseries in data.TimeSeries)
                {
                    Console.WriteLine("open: " + timeseries.open);
                    Console.WriteLine("high: " + timeseries.high);
                    Console.WriteLine("low: " + timeseries.low);
                    Console.WriteLine("close: " + timeseries.close);
                    Console.WriteLine("volume: " + timeseries.volume);
                    Console.WriteLine("DateTime: " + timeseries.DateTime);
                    Console.WriteLine("========================");
                }
            }
        }
Exemple #10
0
        static async Task <int> FetchandUpdateCurrentPriceDataforCompany(string ticker)
        {
            IAvapiConnection connection  = AvapiConnection.Instance;
            float            recentprice = 0;
            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED m_time_series_daily_adjustedResponse;

            // Set up the connection and pass the API_KEY provided by alphavantage.co
            connection.Connect("7NIMRBR8G8UB7P8C");

            // Get the TIME_SERIES_MONTHLY_ADJUSTED query object
            Int_TIME_SERIES_DAILY_ADJUSTED time_series_daily_adjusted =
                connection.GetQueryObject_TIME_SERIES_DAILY_ADJUSTED();

            // Perform the TIME_SERIES_MONTHLY_ADJUSTED request and get the result
            m_time_series_daily_adjustedResponse = await time_series_daily_adjusted.QueryAsync(
                ticker);

            var data = m_time_series_daily_adjustedResponse.Data;

            WebClient client = new WebClient();
            Uri       uri    = new Uri("http://web.engr.oregonstate.edu/~jonesty/UpdateCompanyInfo.php");

            NameValueCollection parameters = new NameValueCollection();

            if (data.Error)
            {
                Console.WriteLine(data.ErrorMessage);
                return(0);
            }
            else
            {
                int counter = 0;
                foreach (var timeseries in data.TimeSeries)
                {
                    if (counter < 1)
                    {
                        recentprice = float.Parse(timeseries.adjustedclose, CultureInfo.InvariantCulture.NumberFormat);
                    }
                    counter = counter + 1;
                }
            }
            Console.WriteLine(recentprice);
            Console.WriteLine(ticker);
            parameters.Add("tickersymbol", ticker);
            parameters.Add("currentprice", recentprice.ToString());

            client.UploadValuesAsync(uri, parameters);
            return(1);
        }
        private async Task <Finance[]> parseFinance()
        {
            IAvapiConnection connection = AvapiConnection.Instance;

            connection.Connect($"{BadAPI.Startup.Configuration["APIKeys:AlphaVantage"]}");

            // Get the Int_TIME_SERIES_INTRADAY query object
            Int_TIME_SERIES_INTRADAY time_intraday =
                connection.GetQueryObject_TIME_SERIES_INTRADAY();

            // Perform the Int_TIME_SERIES_INTRADAY request and get the result
            IAvapiResponse_TIME_SERIES_INTRADAY time_series_intradayResponse =
                time_intraday.Query(
                    "MS",
                    Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_interval.n_1min,
                    Const_TIME_SERIES_INTRADAY.TIME_SERIES_INTRADAY_outputsize.compact);



            List <Finance[]> financeResults = new List <Finance[]>();
            var data = time_series_intradayResponse.Data;

            foreach (var timeseries in data.TimeSeries)
            {
                Finance[] finance = new Finance[1];
                finance[0] = new Finance();
                if (finance[0] != null)
                {
                    finance[0].symbol = data.MetaData.Symbol;
                    finance[0].date   = timeseries.DateTime.ToString();
                    finance[0].open   = timeseries.open;
                    finance[0].close  = timeseries.close;
                    finance[0].high   = timeseries.high;
                    finance[0].low    = timeseries.low;
                    finance[0].volume = timeseries.volume;
                    financeResults.Add(finance);
                }
            }

            return(CombineResponses(financeResults));
        }
Exemple #12
0
        private void testLib()
        {
            // Creating the connection object
            IAvapiConnection connection = AvapiConnection.Instance;

            // Set up the connection and pass the API_KEY provided by alphavantage.co
            connection.Connect(API_KEYS.AVAPI_API_KEY);

            Int_DIGITAL_CURRENCY_DAILY digital_cur_daily = connection.GetQueryObject_DIGITAL_CURRENCY_DAILY();

            IAvapiResponse_DIGITAL_CURRENCY_DAILY apiResponse = digital_cur_daily.QueryPrimitive("BTC", "CNY");


            // Printout the results
            Console.WriteLine("******** RAW DATA TIME_SERIES_DAILY ********");
            Console.WriteLine(apiResponse.RawData);

            /*Console.WriteLine("******** STRUCTURED DATA TIME_SERIES_DAILY ********");
             * var data = apiResponse.Data;
             * if (data.Error)
             * {
             *  Console.WriteLine(data.ErrorMessage);
             * }
             * else
             * {
             *  Console.WriteLine("Information: " + data.MetaData.Information);
             *  Console.WriteLine("Symbol: " + data.MetaData.DigitalCurrencyCode);
             *  Console.WriteLine("LastRefreshed: " + data.MetaData.LastRefreshed);
             *  Console.WriteLine("OutputSize: " + data.MetaData.DigitalCurrencyName);
             *  Console.WriteLine("TimeZone: " + data.MetaData.TimeZone);
             *  Console.WriteLine("========================");
             *  Console.WriteLine("========================");
             *  foreach (var timeseries in data.TimeSeries)
             *  {
             *
             *      Console.WriteLine("DateTime: " + timeseries.DateTime);
             *      Console.WriteLine("========================");
             *  }
             * }*/
        }
Exemple #13
0
        public string GetPrices()
        {
            string csv = string.Empty;

            try
            {
                IAvapiConnection connection = AvapiConnection.Instance;
                connection.Connect(ApiKey);

                Int_TIME_SERIES_DAILY time_series_daily =
                    connection.GetQueryObject_TIME_SERIES_DAILY();

                IAvapiResponse_TIME_SERIES_DAILY time_series_dailyResponse =
                    time_series_daily.Query(
                        Symbol,
                        Const_TIME_SERIES_DAILY.TIME_SERIES_DAILY_outputsize.compact);

                var data = time_series_dailyResponse.Data;
                if (data.Error)
                {
                    Console.WriteLine(data.ErrorMessage);
                }
                else
                {
                    csv = "open;high;low;close;volume;date" + Environment.NewLine;
                    foreach (var timeseries in data.TimeSeries)
                    {
                        csv += timeseries.open + ";" + timeseries.high + ";" + timeseries.low + ";" + timeseries.close + ";" + timeseries.volume + ";" + timeseries.DateTime + Environment.NewLine;
                    }
                }
            }
            catch (Exception ex)
            {
                csv = "ERROR";
                Console.WriteLine("Get Prices API error" + ex.Message);
            }
            return(csv);
        }
        public void AlphaVantageDownloader(ProgramContext programContext, string symbol)
        {
            // Creating the connection object
            IAvapiConnection connection = AvapiConnection.Instance;

            // Set up the connection and pass the API_KEY provided by alphavantage.co
            connection.Connect(programContext.AlphaVantageKey);

            // Get the TIME_SERIES_DAILY query object
            Int_TIME_SERIES_DAILY_ADJUSTED time_series_daily_adjusted =
                connection.GetQueryObject_TIME_SERIES_DAILY_ADJUSTED();

            // Perform the TIME_SERIES_DAILY request and get the result
            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED time_series_dailyResponse =
                time_series_daily_adjusted.Query(
                    symbol,
                    Const_TIME_SERIES_DAILY_ADJUSTED.TIME_SERIES_DAILY_ADJUSTED_outputsize.full);

            // Printout the results
            Console.WriteLine("******** RAW DATA TIME_SERIES_DAILY ********");
            Console.WriteLine(time_series_dailyResponse.RawData);

            Console.WriteLine("******** STRUCTURED DATA TIME_SERIES_DAILY ********");
            var data = time_series_dailyResponse.Data;

            if (data.Error)
            {
                Console.WriteLine(data.ErrorMessage);
            }
            else
            {
                Console.WriteLine("Information: " + data.MetaData.Information);
                Console.WriteLine("Symbol: " + data.MetaData.Symbol);
                Console.WriteLine("LastRefreshed: " + data.MetaData.LastRefreshed);
                Console.WriteLine("OutputSize: " + data.MetaData.OutputSize);
                Console.WriteLine("TimeZone: " + data.MetaData.TimeZone);
                Console.WriteLine("========================");
                Console.WriteLine("========================");

                //data.TimeSeries.OrderBy(x => x.DateTime);   //testing this out
                foreach (var timeseries in data.TimeSeries)
                {
                    DailyStockRecord tempDailyStockRecord = new DailyStockRecord();

                    Console.WriteLine("open: " + timeseries.open);
                    Console.WriteLine("high: " + timeseries.high);
                    Console.WriteLine("low: " + timeseries.low);
                    Console.WriteLine("close: " + timeseries.close);
                    Console.WriteLine("volume: " + timeseries.volume);
                    Console.WriteLine("DateTime: " + timeseries.DateTime);
                    Console.WriteLine("Dividend: " + timeseries.dividendamount);
                    Console.WriteLine("========================");



                    tempDailyStockRecord.Symbol        = data.MetaData.Symbol;
                    tempDailyStockRecord.Open          = Convert.ToDecimal(timeseries.open);
                    tempDailyStockRecord.High          = Convert.ToDecimal(timeseries.high);
                    tempDailyStockRecord.Low           = Convert.ToDecimal(timeseries.low);
                    tempDailyStockRecord.Close         = Convert.ToDecimal(timeseries.close);
                    tempDailyStockRecord.Volume        = Convert.ToDecimal(timeseries.volume);
                    tempDailyStockRecord.Date          = Convert.ToDateTime(timeseries.DateTime);
                    tempDailyStockRecord.Dividend      = Convert.ToDecimal(timeseries.dividendamount);
                    tempDailyStockRecord.AdjustedClose = Convert.ToDecimal(timeseries.adjustedclose);


                    programContext.DailyRecordList.Add(tempDailyStockRecord);


                    //tempDailyStockRecord.VolitilityRating = calculations.CalcVolitilityRating(dailyRecordList);
                }
            }
        }
Exemple #15
0
        static async Task <double> CalculateSharpeRatioForCompany(string ticker)


        {
            List <double> priceslastyear           = new List <double>();
            List <double> monthlyreturnpercentages = new List <double>();
            // Creating the connection object
            IAvapiConnection connection = AvapiConnection.Instance;
            IAvapiResponse_TIME_SERIES_MONTHLY_ADJUSTED m_time_series_monthly_adjustedResponse;

            // Set up the connection and pass the API_KEY provided by alphavantage.co
            connection.Connect("7NIMRBR8G8UB7P8C");

            // Get the TIME_SERIES_MONTHLY_ADJUSTED query object
            Int_TIME_SERIES_MONTHLY_ADJUSTED time_series_monthly_adjusted =
                connection.GetQueryObject_TIME_SERIES_MONTHLY_ADJUSTED();

            // Perform the TIME_SERIES_MONTHLY_ADJUSTED request and get the result
            m_time_series_monthly_adjustedResponse = await time_series_monthly_adjusted.QueryPrimitiveAsync(
                ticker);

            Console.WriteLine("******** STRUCTURED DATA TIME_SERIES_MONTHLY_ADJUSTED ********");
            var data = m_time_series_monthly_adjustedResponse.Data;

            if (data.Error)
            {
                Console.WriteLine(data.ErrorMessage);
                return(0);
            }
            else
            {
                int counter = 0;
                foreach (var timeseries in data.TimeSeries)
                {
                    //Grab 5 years worth of months data
                    if (counter < 60)
                    {
                        //add raw prices to array
                        priceslastyear.Add(double.Parse(timeseries.adjustedclose, CultureInfo.InvariantCulture.NumberFormat));

                        if (counter > 0)
                        {
                            //take pricing data and calculate percent change between each pair of months
                            //Console.Write(((priceslastyear[counter] / priceslastyear[counter - 1]) - 1) * 100);
                            monthlyreturnpercentages.Add(((priceslastyear[counter] / priceslastyear[counter - 1]) - 1) * 100);
                        }
                        counter = counter + 1;
                    }
                }

                double HistAvgMonthlyReturn = 0;

                for (var i = 0; i < monthlyreturnpercentages.Count; i++)
                {
                    //Console.WriteLine(monthprice);
                    HistAvgMonthlyReturn = HistAvgMonthlyReturn + monthlyreturnpercentages[i];
                }


                //Calculate the average monthly return
                HistAvgMonthlyReturn = HistAvgMonthlyReturn / monthlyreturnpercentages.Count;

                //Console.WriteLine(HistAvgMonthlyReturn);


                //Here we need to calculate the Historical Monthly standard deviation based on the Std dev
                // of the monthlyreturnpercentages
                double Summation = 0;

                for (var i = 0; i < monthlyreturnpercentages.Count; i++)
                {
                    Summation = Summation + Math.Pow(monthlyreturnpercentages[i] - HistAvgMonthlyReturn, 2);
                }
                Summation = Summation / monthlyreturnpercentages.Count;

                double HistAvgMonthlyStdDev = Math.Sqrt(Summation);

                //Annualize our standard deviation
                double AnnualStdDev = HistAvgMonthlyStdDev * Math.Sqrt(12);
                double AnnualReturn = ((Math.Pow((100 + HistAvgMonthlyReturn), 12)) - 100);

                double Riskfreerate = 3;

                //Console.WriteLine(HistAvgMonthlyReturn);
                Console.WriteLine(ticker);
                Console.WriteLine(AnnualReturn);
                //Console.WriteLine(Riskfreerate);
                //Console.WriteLine(AnnualStdDev);

                //Calculate the SharpeRatio for the Company
                double SharpeRatioforCompany = (AnnualReturn - Riskfreerate) / AnnualStdDev;

                //Console.WriteLine(SharpeRatioforCompany);

                return(AnnualReturn);
            }
        }
Exemple #16
0
        public ViewResult YearlyReport(DateTime?date)
        {
            if (date == null)
            {
                date = DateTime.Now;
            }

            IAvapiConnection connection = AvapiConnection.Instance;

            connection.Connect("BXGO930UI9P053HT");

            Int_TIME_SERIES_MONTHLY time_series_monthly = connection.GetQueryObject_TIME_SERIES_MONTHLY();

            List <Share>          shares = _repo.Shares.Where(e => e.Date.Year == date.Value.Year).ToList();
            List <PieChartData>   data   = new List <PieChartData>();
            List <StockViewModel> svm    = new List <StockViewModel>();
            List <Stock>          stocks = _stockRepo.Stocks.ToList();

            Dictionary <int, IAvapiResponse_TIME_SERIES_MONTHLY> stockData = new Dictionary <int, IAvapiResponse_TIME_SERIES_MONTHLY>();

            foreach (var stock in stocks)
            {
                try
                {
                    IAvapiResponse_TIME_SERIES_MONTHLY time_series_monthlyResponse = time_series_monthly.QueryPrimitive(
                        stock.Ticker
                        );

                    stockData.Add(stock.ID, time_series_monthlyResponse);

                    var sData = time_series_monthlyResponse.Data.TimeSeries.First();

                    List <Share> listOfShares = shares.Where(e => e.StockID == stock.ID).ToList();
                    int          totalShares  = listOfShares.Select(e => e.NumOfShares).Sum();

                    svm.Add(new StockViewModel()
                    {
                        Stock            = stock,
                        TotalNumOfShares = totalShares,
                        CurrentValue     = Convert.ToDouble(sData.close),
                        TotalValue       = Convert.ToDouble(sData.close) * (double)totalShares
                    });
                }
                catch (Exception e)
                {
                }
            }

            List <LineChartData> lineData = new List <LineChartData>();

            int    month        = 1;
            double currentValue = 0;

            while (month <= date.Value.Month)
            {
                double total = 0;
                foreach (var stock in stocks)
                {
                    IAvapiResponse_TIME_SERIES_MONTHLY time_series_monthlyResponse = stockData.GetValueOrDefault(stock.ID);

                    var sData = time_series_monthlyResponse.Data.TimeSeries.Where(x => Convert.ToDateTime(x.DateTime).Month == month &&
                                                                                  Convert.ToDateTime(x.DateTime).Year == date.Value.Year).FirstOrDefault();
                    if (sData != null)
                    {
                        List <Share> listOfShares = shares.Where(e => e.StockID == stock.ID && (e.Date.Year < date.Value.Year || (e.Date.Year == date.Value.Year && e.Date.Month <= month))).ToList();
                        int          totalShares  = listOfShares.Select(e => e.NumOfShares).Sum();
                        total += Convert.ToDouble(sData.close) * (double)totalShares;
                    }
                }

                currentValue = total;

                lineData.Add(new LineChartData
                {
                    XData = DateTimeFormatInfo.CurrentInfo.GetMonthName(month).Substring(0, 3),
                    YData = currentValue.ToString()
                });

                month++;
            }

            List <int> sectors = _stockRepo.Stocks.Select(x => x.SectorID).Distinct().ToList();

            foreach (var sector in sectors)
            {
                List <Share> sectorShares = shares.Where(e => e.Date.Year == date.Value.Year ? (e.Date.Month <= date.Value.Month)
                    : e.Date.Year <= date.Value.Year).ToList();
                int totalShares = sectorShares.Where(e => e.Stock.SectorID == sector).Select(e => e.NumOfShares).Sum();
                data.Add(new PieChartData
                {
                    Category = _sectorRepo.Sectors.Where(x => x.ID == sector).FirstOrDefault().Name,
                    Data     = Convert.ToString(totalShares)
                });
            }

            double amountInvested = 0;

            foreach (var s in shares)
            {
                amountInvested += (double)s.PurchasePrice * (double)s.NumOfShares;
            }

            List <IncomeEntry> incomes = _incomeRepo.IncomeEntries.Where(i => i.Date.Month == date.Value.Month && i.Date.Year == date.Value.Year).ToList();
            int    daysInMonth         = DateTime.DaysInMonth(date.Value.Year, date.Value.Month);
            double sum = 0;

            for (int j = 1; j <= daysInMonth; j++)
            {
                sum += incomes.Where(i => i.Date.Day == j).Select(e => e.Amount).Sum();
            }

            return(View(new StockListViewModel
            {
                Stocks = svm,
                Date = date.Value,
                PieChartData = data,
                LineChartData = lineData,
                AmountInvested = Convert.ToDecimal(shares.Select(e => e.NumOfShares * e.PurchasePrice).Sum())
            }));
        }
Exemple #17
0
        static async Task <Tuple <double, double, List <double> > > SR_FetchPricingDataandExpectedReturn(string ticker)
        {
            //******************************************************************************************
            //The purpose of this function is to do all calculations related to sharperatio that involve pricing data
            // for a single company. This includes STDdev, and expected return. These will be stored in a dictionary
            //******************************************************************************************


            List <double> priceslastyear           = new List <double>();
            List <double> monthlyreturnpercentages = new List <double>();
            // Creating the connection object
            IAvapiConnection connection = AvapiConnection.Instance;
            IAvapiResponse_TIME_SERIES_MONTHLY_ADJUSTED m_time_series_monthly_adjustedResponse;

            // Set up the connection and pass the API_KEY provided by alphavantage.co
            connection.Connect("7NIMRBR8G8UB7P8C");

            // Get the TIME_SERIES_MONTHLY_ADJUSTED query object
            Int_TIME_SERIES_MONTHLY_ADJUSTED time_series_monthly_adjusted =
                connection.GetQueryObject_TIME_SERIES_MONTHLY_ADJUSTED();

            // Perform the TIME_SERIES_MONTHLY_ADJUSTED request and get the result
            m_time_series_monthly_adjustedResponse = await time_series_monthly_adjusted.QueryPrimitiveAsync(
                ticker);

            Console.WriteLine("******** STRUCTURED DATA TIME_SERIES_MONTHLY_ADJUSTED ********");
            var data = m_time_series_monthly_adjustedResponse.Data;

            if (data.Error)
            {
                Console.WriteLine(data.ErrorMessage);
                return(null);
            }
            else
            {
                Console.WriteLine("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");
                int counter = 0;
                foreach (var timeseries in data.TimeSeries)
                {
                    //Grab 5 years worth of months data
                    if (counter < 60)
                    {
                        //add raw prices to array
                        priceslastyear.Add(double.Parse(timeseries.adjustedclose, CultureInfo.InvariantCulture.NumberFormat));

                        if (counter > 0)
                        {
                            //take pricing data and calculate percent change between each pair of months
                            //Console.Write(((priceslastyear[counter] / priceslastyear[counter - 1]) - 1) * 100);
                            monthlyreturnpercentages.Add(((priceslastyear[counter] / priceslastyear[counter - 1]) - 1) * 100);
                        }
                        counter = counter + 1;
                    }
                }

                //Setup counter to average pricing data
                double running_average = 0;
                //Calculate STDDev of data
                double std_dev = StdDev(monthlyreturnpercentages, true);

                //Sum all the values in our list
                for (var i = 0; i < monthlyreturnpercentages.Count(); i++)
                {
                    running_average = monthlyreturnpercentages[i] + running_average;
                }

                //Finishing taking average by dividing by the number of entries
                running_average = running_average / monthlyreturnpercentages.Count();

                //Annualize the average (multiply by 12 since monthly)
                running_average = running_average * 12;

                //Add the values to the tuple and print!
                Console.Write(ticker + ", ");
                Console.Write(std_dev + ", ");
                Console.Write(running_average + ", ");

                var pricingdata = Tuple.Create(std_dev, running_average, monthlyreturnpercentages);
                //Return this value
                return(pricingdata);
            }
        }
Exemple #18
0
        // dataSize must be "full" or "compact"
        public void RetrieveData(String dataSize)
        {
            /*
             *   *******Init Objects for StockExchange ********
             *
             */


            IAvapiConnection connection = AvapiConnection.Instance;

            connection.Connect("CJ7QO45PVDJ8371Q");
            Int_TIME_SERIES_DAILY_ADJUSTED TSD = connection.GetQueryObject_TIME_SERIES_DAILY_ADJUSTED();

            //ASX
            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED ASXResponse =
                TSD.QueryPrimitive(
                    "^AXJO",
                    dataSize
                    );

            this.ASX = ASXResponse.Data;
            //ESTOX
            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED ESTOXResponse =
                TSD.QueryPrimitive(
                    "^STOXX50E",
                    dataSize
                    );

            this.ESTOX = ESTOXResponse.Data;

            //FTSE
            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED FTSEResponse =
                TSD.QueryPrimitive(
                    "^FTSE",
                    dataSize
                    );

            this.FTSE = FTSEResponse.Data;

            //SP500
            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED SP500Response =
                TSD.QueryPrimitive(
                    "^GSPC",
                    dataSize
                    );

            this.SP500 = SP500Response.Data;

            //N225
            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED N225Response =
                TSD.QueryPrimitive(
                    "^N225",
                    dataSize
                    );

            this.N225 = N225Response.Data;

            //HANG
            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED HangResponse =
                TSD.QueryPrimitive(
                    "^HSI",
                    dataSize
                    );

            this.HANG = HangResponse.Data;



            /*
             *   ******* CurrencyExchange ********
             *
             *   Possible to request only 1 value, see currency_exchange_rate
             */

            //EURUSD
            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED EURUSDResponse =
                TSD.QueryPrimitive(
                    "EURUSD=X",
                    dataSize
                    );

            this.EURUSD = EURUSDResponse.Data;

            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED EURGBPResponse =
                TSD.QueryPrimitive(
                    "EURGBP=X",
                    dataSize
                    );

            this.EURGBP = EURGBPResponse.Data;

            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED EURJPYResponse =
                TSD.QueryPrimitive(
                    "EURJPY=X",
                    dataSize
                    );

            this.EURJPY = EURJPYResponse.Data;

            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED AUDUSDResponse =
                TSD.QueryPrimitive(
                    "AUDUSD=X",
                    dataSize
                    );

            this.AUDUSD = AUDUSDResponse.Data;

            IAvapiResponse_TIME_SERIES_DAILY_ADJUSTED USDHKDResponse =
                TSD.QueryPrimitive(
                    "USDHKD=X",
                    dataSize
                    );

            this.USDHKD = USDHKDResponse.Data;
        }