我正在使用 Alpha Vantage API 来尝试获取每日股票信息。我对使用 APIs 很陌生,不知道我做错了什么
I am using Alpha Vantage API to try and pull daily stock info. I am really new to using APIs and don't know what I am doing wrong
所以我正在使用 c# xamarin 并制作一个基本的股票应用程序,它可以使用 Alpha Vantage API 提取股票报价。我有我认为可能有用的东西,但它根本不起作用。是的,这是一个学校项目,所以我不希望人们直接去做。这个应用程序的目的是使用 API,我需要在用户从应用程序的第一页输入股票代码后显示它提供的数据。我需要用 api 发送那个符号,我不确定我是否在拉入 JSON 对象,而且当我检索 [= 时我不知道如何到达对象中的每个字段18=] correctly.This 代码是我正在尝试的,我没有将任何信息填充到我的任何 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; }
}
}
从该端点返回的 JSON 与您的模型不完全匹配。
这是您告诉程序如何解析响应的行:
股票 currentStockInfo = JsonConvert.DeserializeObject(reader.ReadToEnd());
...但响应如下所示:
{
"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
,而是包含 2 个对象的响应,其中一个对象有很多 Stock
个对象。
您可以尝试为此创建一个模型*,但我建议将整个响应转换为 JObject
(NewtonSoft 中的另一个对象 JSON.Net).
这是我放在一起的 DotNetFiddle 来演示它是如何工作的。
https://dotnetfiddle.net/Iz8UsD
如果我可以添加更有帮助的内容,请告诉我。
编辑:* 您或许可以在这里使用强类型模型,问题是每个 Stock
都有不同的 JSON 名称。我不知道如何让解析器将每个解析为 Stock
,同时仍保留数据。今晚我得玩那个。
Joe 解释的问题是返回的 JSON 的形状不允许轻松映射到 C# 对象。
这里是 easier/quicker 使用 C# 从 AlphaVantage 检索股票价格的方法。
它涉及调用标准 API 价格端点,但添加“&datatype=csv”作为 URL 参数。响应的格式可以轻松映射到 C# Poco 对象。在下面的示例中,我只是将其映射到 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);
所以我正在使用 c# xamarin 并制作一个基本的股票应用程序,它可以使用 Alpha Vantage API 提取股票报价。我有我认为可能有用的东西,但它根本不起作用。是的,这是一个学校项目,所以我不希望人们直接去做。这个应用程序的目的是使用 API,我需要在用户从应用程序的第一页输入股票代码后显示它提供的数据。我需要用 api 发送那个符号,我不确定我是否在拉入 JSON 对象,而且当我检索 [= 时我不知道如何到达对象中的每个字段18=] correctly.This 代码是我正在尝试的,我没有将任何信息填充到我的任何 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; }
}
}
从该端点返回的 JSON 与您的模型不完全匹配。
这是您告诉程序如何解析响应的行:
股票 currentStockInfo = JsonConvert.DeserializeObject(reader.ReadToEnd());
...但响应如下所示:
{
"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
,而是包含 2 个对象的响应,其中一个对象有很多 Stock
个对象。
您可以尝试为此创建一个模型*,但我建议将整个响应转换为 JObject
(NewtonSoft 中的另一个对象 JSON.Net).
这是我放在一起的 DotNetFiddle 来演示它是如何工作的。
https://dotnetfiddle.net/Iz8UsD
如果我可以添加更有帮助的内容,请告诉我。
编辑:* 您或许可以在这里使用强类型模型,问题是每个 Stock
都有不同的 JSON 名称。我不知道如何让解析器将每个解析为 Stock
,同时仍保留数据。今晚我得玩那个。
Joe 解释的问题是返回的 JSON 的形状不允许轻松映射到 C# 对象。
这里是 easier/quicker 使用 C# 从 AlphaVantage 检索股票价格的方法。
它涉及调用标准 API 价格端点,但添加“&datatype=csv”作为 URL 参数。响应的格式可以轻松映射到 C# Poco 对象。在下面的示例中,我只是将其映射到 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);