xamarin 我正在使用Alpha Vantage API来尝试提取每日股票信息,我真的是新使用API,不知道我做错了什么

icomxhvb  于 2022-12-07  发布在  Vant
关注(0)|答案(3)|浏览(227)

所以我用c# xamarin做了一个基本的股票应用程序,可以用Alpha Vantage API拉股票报价。我有我认为可能会工作,但它根本不工作。是的,这是一个学校项目,所以我不希望人们只是做它。此应用程序的目的是使用API,我需要显示用户从第一页输入股票代码后它提供的数据我需要使用api发送该符号,但我不确定是否拉入了JSON对象,也不知道在正确检索JSON时如何到达对象中的每个字段。这段代码是我正在尝试的,但我没有将任何信息填充到任何textView中。

namespace Stock_Quote
{
    [Activity(Label = "StockInfoActivity1")]
    public class StockInfoActivity1 : Activity
    {
        private ISharedPreferences prefs = Application.Context.GetSharedPreferences("APP_DATA", FileCreationMode.Private);
        TextView txtSymbol, txtOpen, txtClose, txtHigh, txtLow, txtVolume;
        string webservice_url = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=";

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Create your application here
            SetContentView(Resource.Layout.activity_stock_info);
            txtSymbol = FindViewById<TextView>(Resource.Id.txtSymbol);
            txtOpen = FindViewById<TextView>(Resource.Id.txtOpen);
            txtClose = FindViewById<TextView>(Resource.Id.txtClose);
            txtHigh = FindViewById<TextView>(Resource.Id.txtHigh);
            txtLow = FindViewById<TextView>(Resource.Id.txtLow);
            txtVolume = FindViewById<TextView>(Resource.Id.txtVolume);
            string current = prefs.GetString("current", "no stok symbol found");

            //txtSymbol.Text = current;

            try
            {
                webservice_url = webservice_url + current + "&apikey=AVALIDAPIKEY";
                Uri url = new Uri(webservice_url);
                var webRequest = WebRequest.Create(url);

                if (webRequest != null)
                {

                    webRequest.Method = "GET";
                    webRequest.ContentType = "application/json";

                    //Get the response 
                    WebResponse wr = webRequest.GetResponseAsync().Result;
                    Stream receiveStream = wr.GetResponseStream();
                    StreamReader reader = new StreamReader(receiveStream);

                    Stock currentStockInfo = JsonConvert.DeserializeObject<Stock>(reader.ReadToEnd());

                    if (currentStockInfo.RestResponse.result == null)
                    {
                        txtSymbol.Text = "No stock found";
                    }
                    else
                    {                        
                        txtSymbol.Text = current;
                        txtOpen.Text = currentStockInfo.RestResponse.stockInfo.Open;
                        txtClose.Text = currentStockInfo.RestResponse.stockInfo.Close;
                        txtHigh.Text = currentStockInfo.RestResponse.stockInfo.High;
                        txtLow.Text = currentStockInfo.RestResponse.stockInfo.Low;
                        txtVolume.Text = currentStockInfo.RestResponse.stockInfo.Volume;
                    }

                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    }
    public class Result
    {
        public string Information { get; set; }
        public string Symbol { get; set; }
        public string Last { get; set; }
        public string Size { get; set; }
        public string TimeZone { get; set; }
    }

    public class StockInfo
    {
        public string Open { get; set; }
        public string High { get; set; }
        public string Low { get; set; }
        public string Close { get; set; }
        public string Volume { get; set; }
    }

    public class RestResponse
    {       
        public Result result { get; set; }
        public StockInfo stockInfo { get; set; }
    }

    public class Stock
    {
        public RestResponse RestResponse { get; set; }
    }
}
u0sqgete

u0sqgete1#

从该端点返回的JSON与您的模型不完全匹配。
下面这一行告诉程序如何解析响应:
股票当前股票信息= jsonConvert.DeserializeObject(读取器.读取到结束());
...但响应如下所示:

{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2018-12-10 16:00:02",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2018-12-10": {
            "1. open": "104.8000",
            "2. high": "107.9800",
            "3. low": "103.8900",
            "4. close": "107.5900",
            "5. volume": "39050766"
        },
        "2018-12-07": {
            "1. open": "108.3800",
            "2. high": "109.4500",
            "3. low": "104.3000",
            "4. close": "104.8200",
            "5. volume": "45044937"
        }...
    ...
    ...
    ...

}
你试图把整个响应变成一个Stock对象,这是行不通的。这个响应不是一个Stock,它是一个有两个对象的响应,其中一个有很多Stock对象。
您 * 可以 * 尝试为此创建一个模型 ,但我建议将整个响应转换为JObject(NewtonSoftJSON .NET中的另一个对象)。
下面是一个DotNetFiddle,我将它放在一起来演示它是如何工作的。
https://dotnetfiddle.net/Iz8UsD
如果我能补充更多有用的信息,请告诉我。
编辑:
您可能可以在这里使用强类型模型,问题是每个Stock都有不同的JSON名称。我不知道如何让解析器将每个Stock解析为Stock,同时仍然保留数据。今晚我将不得不使用它。

egdjgwm8

egdjgwm82#

Joe解释的问题是,返回的JSON的形状不允许轻松Map到C#对象。
下面是一个使用C#从AlphaVantage检索股票价格的更简单/更快捷的方法。
它涉及到调用标准的API价格端点,但添加'&datatype=csv'作为URL参数。响应的格式使它很容易Map到C# Poco对象。在下面的示例中,我只是将它Map到AlphaVantageData对象。
下面是示例代码。您可以在Gystlin here中实时运行此代码

using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack;
using ServiceStack.Text;

public class AlphaVantageData
{
     public DateTime Timestamp { get; set; }
     public decimal Open { get; set; }

     public decimal High { get; set; }
     public decimal Low { get; set; }

     public decimal Close { get; set; }
     public decimal Volume { get; set; }
}

 // retrieve monthly prices for Microsoft
 var symbol = "MSFT";
 var monthlyPrices = $"https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol={symbol}&apikey=demo&datatype=csv"
            .GetStringFromUrl().FromCsv<List<AlphaVantageData>>();

 monthlyPrices.PrintDump();

 // some simple stats
 var maxPrice = monthlyPrices.Max(u => u.Close);
 var minPrice = monthlyPrices.Min(u => u.Close);
siv3szwd

siv3szwd3#

我发布这个回复是因为我有一个工作代码,它可以从AlphaVantage Time Series(Daily)解析出一个股票报价列表。然后它会对报价进行一些比较,寻找枢轴点。这部分需要工作,但列表可以从每日提要中正确获取。

using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;

namespace StockQuotes
{
    public class Program
    {
        static void Main(string[] args)
        {

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

            if (args.Length < 1)
            { quoteTickerSymbols.Add("msft"); }
            else
            {
                string[] data = args[0].Split(',');
                quoteTickerSymbols.Add(data.ToString());
            }

            //please use your own API key.
            string APIKey = "";
            string response = "";
            string nameOfStock = "";
            HttpClient client = new HttpClient();
            StringBuilder sb = new StringBuilder();
            List<StockQuote> quotes = new List<StockQuote>();

            for (int i = 0; i < quoteTickerSymbols.Count;)
            {
                sb.Append($"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=");
                sb.Append(quoteTickerSymbols[i]);
                sb.Append("&apikey=");
                sb.Append(APIKey);

                string request = sb.ToString();

                response = client.GetStringAsync(request).Result;
                JObject jsonData = JObject.Parse(response);

                nameOfStock = quoteTickerSymbols[i];
                try
                {
                    foreach (JToken item in jsonData.SelectTokens("['Time Series (Daily)']"))
                    {
                        foreach (var datedCollection in item.Children().Children())
                        {
                            sb.Clear();
                            string[] pathArray = datedCollection.Path.Split('.');

                            // the date that's after the Time Series (Daily) part of the path
                            sb.Append(pathArray[1]);

                            DataSetByDay dataSet = datedCollection.ToObject<DataSetByDay>();

                            var quote = datedCollection.Select(x => new StockQuote()
                            {
                                Name = nameOfStock,
                                date = Convert.ToDateTime(sb.ToString()),
                                open = dataSet.open,
                                high = dataSet.high,
                                low = dataSet.low,
                                close = dataSet.close,
                                volume = dataSet.volume
                            });

                            quotes.Add(quote.First());
                            dataSet = null;
                        }
                    }
                }
                catch (Exception err)
                {

                    // write out the issue and then skip the entry.
                    Console.WriteLine(err.Message, err.InnerException, err.Source);
                    i++;
                }

                // move to next token
                i++;

                // at the end, compare the quotes.
                for (int j = 0; j < quotes.Count() - 4; j++)
                {
                    if (quotes[j].open > quotes[j + 1].high && quotes[j].close < quotes[j + 1].low)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("{0}", quotes[j].Name);
                        Console.WriteLine("Pivot downside {0}", quotes[j].date);
                    }
                    if (quotes[j].open < quotes[j + 1].low && quotes[j].close > quotes[j + 1].high)
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("{0}", quotes[j].Name);
                        Console.WriteLine("Pivot upside {0}", quotes[j].date);
                    }
                }
            }
        }
    }
}

这也是需要的。存储信息。

using Newtonsoft.Json;
using System;

namespace StockQuotes
{
    // each daily record from the website
    internal class DataSetByDay
    {
        [JsonProperty("1. open")]
        public decimal open { get; set; }

        [JsonProperty("2. high")]
        public decimal high { get; set; }

        [JsonProperty("3. low")]
        public decimal low { get; set; }

        [JsonProperty("4. close")]
        public decimal close { get; set; }
        [JsonProperty("5. volume")]
        public long volume { get; set; }
    }

    //this would append the date and the name of the stock to the time series.
    internal class StockQuote : DataSetByDay
    {
       public string Name { get; set; }
        public DateTime date { get; set; }
    }
}

相关问题