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());
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
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);
        }
Exemplo n.º 4
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));
            }
        }
Exemplo n.º 5
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;
        }
Exemplo n.º 6
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("========================");
                }
            }
        }
Exemplo n.º 7
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);
        }
        public DigitalCurrencyHisotryTrendind()
        {
            InitializeComponent();

            temp = new LineSeries();

            _added = false;

            var gradientBrush = new LinearGradientBrush
            {
                StartPoint = new Point(0, 0),
                EndPoint   = new Point(0, 1)
            };

            gradientBrush.GradientStops.Add(new GradientStop(Color.FromRgb(64, 224, 208), 0));
            gradientBrush.GradientStops.Add(new GradientStop(Colors.Transparent, 1));

            _connection.Connect("5XQ6Y6JJKEOQ7JRU");
            _args = new FetchArgs
            {
                DefaultCurrency = Configuration.Instance.DefaultCurrency,
                Symbol          = Configuration.Instance.Symbol,
                FullName        = Configuration.Instance.FullName,
                RefreshRate     = Configuration.Instance.RefreshRate
            };

            XFormatter = val => new DateTime((long)val).ToString("dd MMM yyyy");
            YFormatter = val => val.ToString("0.##") + " " + _args.DefaultCurrency;

            SeriesCollection = new SeriesCollection
            {
                new LineSeries
                {
                    Values            = GetData(),
                    Fill              = gradientBrush,
                    StrokeThickness   = 1,
                    PointGeometrySize = 0,
                    Title             = _args.FullName,
                }
            };

            ZoomingMode = ZoomingOptions.Xy;

            Title = _args.FullName;

            DataContext = this;
        }
Exemplo n.º 9
0
        public RealtimeViewer()
        {
            InitializeComponent();
            addRefreshRates();
            _connection.Connect("5XQ6Y6JJKEOQ7JRU");

            _args = new FetchArgs
            {
                DefaultCurrency = Configuration.Instance.DefaultCurrency,
                Symbol          = Configuration.Instance.Symbol,
                FullName        = Configuration.Instance.FullName,
                RefreshRate     = Configuration.Instance.RefreshRate,
                Type            = Configuration.Instance.Type
            };


            Init();
            DataContext = this;
        }
Exemplo n.º 10
0
        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));
        }
Exemplo n.º 11
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("========================");
             *  }
             * }*/
        }
Exemplo n.º 12
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);
        }
Exemplo n.º 13
0
        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);
                }
            }
        }
Exemplo n.º 14
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);
            }
        }
Exemplo n.º 15
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())
            }));
        }
Exemplo n.º 16
0
        public RealTimeTrending()
        {
            InitializeComponent();

            var dayConfig = Mappers.Xy <DateTimePoint>()
                            .X(dayModel => (double)dayModel.DateTime.Ticks / TimeSpan.FromMilliseconds(1000).Ticks)
                            .Y(dayModel => dayModel.Value);

            _connection.Connect("5XQ6Y6JJKEOQ7JRU");
            _args = new FetchArgs {
                DefaultCurrency = "RSD", Symbol = "MSFT", RefreshRate = 5
            };
            LastHourSeries = new SeriesCollection
            {
                new LineSeries
                {
                    Configuration = dayConfig,
                    AreaLimit     = -10,
                    //Values = GetData(),
                    Values = new ChartValues <DateTimePoint>
                    {
                        new DateTimePoint {
                            Value = 1, DateTime = DateTime.Now
                        },
                        new DateTimePoint {
                            Value = 5, DateTime = DateTime.Now.AddSeconds(1)
                        },
                        new DateTimePoint {
                            Value = 3, DateTime = DateTime.Now.AddSeconds(2)
                        },
                        new DateTimePoint {
                            Value = 4, DateTime = DateTime.Now.AddSeconds(3)
                        },
                        new DateTimePoint {
                            Value = 7, DateTime = DateTime.Now.AddSeconds(4)
                        },
                        new DateTimePoint {
                            Value = 2, DateTime = DateTime.Now.AddSeconds(5)
                        },
                        new DateTimePoint {
                            Value = 11, DateTime = DateTime.Now.AddSeconds(6)
                        },
                        new DateTimePoint {
                            Value = 6, DateTime = DateTime.Now.AddSeconds(7)
                        },
                        new DateTimePoint {
                            Value = 9, DateTime = DateTime.Now.AddSeconds(8)
                        },
                        new DateTimePoint {
                            Value = 1, DateTime = DateTime.Now.AddSeconds(9)
                        },
                        new DateTimePoint {
                            Value = 3, DateTime = DateTime.Now.AddSeconds(10)
                        },
                        new DateTimePoint {
                            Value = 9, DateTime = DateTime.Now.AddSeconds(11)
                        },
                    }
                },
            };
            Step        = 0;
            LastLecture = 0;

            //timer = new DispatcherTimer();
            //timer.Tick += new EventHandler(SetValues);
            //timer.Interval = new TimeSpan(0, 0, _args.RefreshRate);
            //timer.Start();

            Task.Run(() =>
            {
                ChartValues <DateTimePoint> values = new ChartValues <DateTimePoint>();
                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
                while (true)
                {
                    Thread.Sleep(4000);
                    _backgroindWork = Task.Factory.StartNew(() =>
                    {
                        values = GetData();
                    }, TaskCreationOptions.LongRunning);

                    //Dispatcher.Invoke(() => {
                    //    if (values.Count != 0)
                    //    {
                    //        LastHourSeries[0].Values = values;
                    //        Step = ((ChartValues<DateModel>)LastHourSeries[0].Values).Last().Value -
                    //                    ((ChartValues<DateModel>)LastHourSeries[0].Values).ElementAt(
                    //                        ((ChartValues<DateModel>)LastHourSeries[0].Values).Count - 2).Value;
                    //        if (Step > 0)
                    //            ForegroundColor = Brushes.Green;
                    //        else if (Step < 0)
                    //            ForegroundColor = Brushes.Red;
                    //        else
                    //            ForegroundColor = Brushes.Black;
                    //        LastLecture = ((ChartValues<DateModel>)LastHourSeries[0].Values).Last().Value;
                    //    }
                    //    MessageBox.Show("Refresh", "Refrash");
                    //});

                    _backgroindWork.ContinueWith(x =>
                    {
                        Dispatcher.Invoke(() =>
                        {
                            using (Dispatcher.DisableProcessing())
                            {
                                LastHourSeries[0].Values.Add(values.Last());
                                LastHourSeries[0].Values.RemoveAt(0);
                                //LastHourSeries[0].Values = values;
                            }
                        }, DispatcherPriority.ContextIdle);
                        Step = ((ChartValues <DateTimePoint>)LastHourSeries[0].Values).Last().Value -
                               ((ChartValues <DateTimePoint>)LastHourSeries[0].Values).ElementAt(
                            ((ChartValues <DateTimePoint>)LastHourSeries[0].Values).Count - 2).Value;
                        if (Step > 0)
                        {
                            ForegroundColor = Brushes.Green;
                        }
                        else if (Step < 0)
                        {
                            ForegroundColor = Brushes.Red;
                        }
                        else
                        {
                            ForegroundColor = Brushes.Black;
                        }
                        LastLecture = ((ChartValues <DateTimePoint>)LastHourSeries[0].Values).Last().Value;


                        //MessageBox.Show("Refresh", "Refrash");
                    }, TaskScheduler.FromCurrentSynchronizationContext());
                }



                //while (true)
                //{
                //    Thread.Sleep(5000);
                //    Dispatcher.BeginInvoke(new Action(()=> {
                //        values = GetData();
                //    }), DispatcherPriority.Background);

                //    Application.Current.Dispatcher.Invoke(() => {
                //        if(values.Count != 0)
                //        {
                //            LastHourSeries[0].Values = values;
                //            Step = ((ChartValues<DateModel>)LastHourSeries[0].Values).Last().Value -
                //                        ((ChartValues<DateModel>)LastHourSeries[0].Values).ElementAt(
                //                            ((ChartValues<DateModel>)LastHourSeries[0].Values).Count - 2).Value;
                //            if (Step > 0)
                //                ForegroundColor = Brushes.Green;
                //            else if (Step < 0)
                //                ForegroundColor = Brushes.Red;
                //            else
                //                ForegroundColor = Brushes.Black;
                //            LastLecture = ((ChartValues<DateModel>)LastHourSeries[0].Values).Last().Value;
                //        }

                //    });

                //}
            });

            //Task.Run(() =>
            //{
            //    var r = new Random();
            //    while (true)
            //    {
            //        Thread.Sleep(5000);
            //        //var values = GetData();
            //        //foreach (var temp in GetData())
            //        //{
            //        //    Console.WriteLine(temp.Value + "     " + temp.DateTime.ToLongTimeString());
            //        //}

            //        //foreach( var temp in values)
            //        //{
            //        //    Thread.Sleep(1000);
            //        //    _trend = temp.Value;
            //        //    Application.Current.Dispatcher.Invoke(() =>
            //        //    {
            //        //        if (_trend > ((ChartValues<DateModel>)LastHourSeries[0].Values).Last().Value)
            //        //            ForegroundColor = Brushes.Green;
            //        //        else if (_trend < ((ChartValues<DateModel>)LastHourSeries[0].Values).Last().Value)
            //        //            ForegroundColor = Brushes.Red;
            //        //        else
            //        //            ForegroundColor = Brushes.Black;
            //        //        LastHourSeries[0].Values.Add(temp);
            //        //        LastHourSeries[0].Values.RemoveAt(0);
            //        //        SetLecture();
            //        //    });
            //        //}
            //        //Thread.Sleep(1000);
            //        _trend += (r.NextDouble() > 0.3 ? 1 : -1) * r.Next(0, 5);

            //        Application.Current.Dispatcher.Invoke(() =>
            //        {


            //            //LastHourSeries[0].Values.Add(new DateModel { Value = _trend, DateTime = DateTime.Now });
            //            //LastHourSeries[0].Values.RemoveAt(0);
            //            LastHourSeries[0].Values = new ChartValues<DateModel>
            //            {
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 1 : -1) * r.Next(0, 5), DateTime = DateTime.Now},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 2 : -2) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(1)},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 3 : -3) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(2)},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 4 : -4) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(3)},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 5 : -5) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(4)},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 6 : -6) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(5)},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 7 : -7) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(6)},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 8 : -8) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(7)},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 9 : -9) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(8)},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 10 : -10) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(9)},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 11 : -11) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(10)},
            //            new DateModel{Value = (r.NextDouble() > 0.3 ? 12 : -12) * r.Next(0, 5), DateTime = DateTime.Now.AddSeconds(11)},
            //            };
            //            Step = ((ChartValues<DateModel>)LastHourSeries[0].Values).Last().Value -
            //                        ((ChartValues<DateModel>)LastHourSeries[0].Values).ElementAt(
            //                            ((ChartValues<DateModel>)LastHourSeries[0].Values).Count - 2).Value;
            //            if (_trend > 0)
            //                ForegroundColor = Brushes.Green;
            //            else if (_trend < 0)
            //                ForegroundColor = Brushes.Red;
            //            else
            //                ForegroundColor = Brushes.Black;
            //            LastLecture = ((ChartValues<DateModel>)LastHourSeries[0].Values).Last().Value;
            //            //SetLecture();
            //        });
            //    }
            //});

            Formatter = value => new DateTime((long)(value * TimeSpan.FromMilliseconds(1000).Ticks)).ToString("T");
            //Formatter = value => new DateTime((long)value).ToString("T");
            DataContext = this;
        }
Exemplo n.º 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);
            }
        }
Exemplo n.º 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;
        }