我是Yahoo Finance API难民(他们停止了他们的API服务),试图切换到Alpha Vantage。 我修改了以前用于Yahoo Finance的以下代码,但我在Excel中收到了#VALUE错误。
下面的URL单独工作(如果你在网页浏览器中输入它会打开一个CSV),所以我想我的真正问题在于从CSV中将正确的数据提取到我的Excel电子表格中。有人能帮忙吗?
我正在尝试从CSV中提取第2行第5列(最后一个收盘价)中的数据。非常感谢提前!
Function StockClose(Ticker As String)
Dim URL As String, CSV As String, apikey As String, SCRows() As String, SCColumns() As String, pxClose As Double
apikey = "*censored*"
URL = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=" & Ticker & "&outputsize=full&" & apikey & "&datatype=csv"
Set xmlhttp = CreateObject("MSXML2.XMLHTTP")
xmlhttp.Open "GET", URL, False
xmlhttp.Send
CSV = xmlhttp.responseText
'split the CSV into rows
SCRows() = Split(CSV, Chr(10))
'split the relevant row into columns. 0 means 1st row, starting at index 0
SCColumns() = Split(SCRows(1), ",")
'6 means: 5th column; starting at index 0 - price close is in the 5th column
pxClose = SCColumns(6)
StockClose = pxClose
Set http = Nothing
End Function
如果我提取json而不是csv:
,则返回数据样本{ “元数据”:{ “1.信息”:“每日价格(开盘价,最高价,最低价,收盘价和收盘价”), “2.符号”:“SGD = X”, “3.最后更新”:“2017-11-10”, “4.输出尺寸”:“全尺寸”, “5.时区”:“美国/东方” }, “时间序列(每日)”:{ “2017-11-13”:{ “1.开放”:“1.3588”, “2.高”:“1.3612”, “3.低”:“1.3581”, “4.关闭”:“1.3587”, “5.音量”:“0” }, “2017-11-10”:{ “1.开放”:“1.3588”, “2.高”:“1.3612”, “3.低”:“1.3581”, “4.关闭”:“1.3587”, “5.音量”:“0” },
答案 0 :(得分:2)
网站上的“CSV”选项是可下载的文件,而不是像这样解析的文本文档。一个更简单的解决方案是使用站点的JSON选项,它可以轻松加载到字符串中。
由于您只需要一个值,因此最简单的方法就是搜索字符串“Close”,并在其后面返回值。
这是一个快速解决方案,您可以根据需要进行调整:
Option Explicit
Function StockClose(Ticker As String) As Double
Dim URL As String, json As String, apiKey As String, xmlHTTP As Object
Dim posStart As Integer, posEnd As Integer, strClose As String
apiKey = "demo"
URL = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=" & Ticker & "&outputsize=full&apikey=" & apikey
Set xmlHTTP = CreateObject("MSXML2.XMLHTTP")
xmlHTTP.Open "GET", URL, False
xmlHTTP.Send
json = xmlHTTP.responseText
Set xmlHTTP = Nothing
posStart = InStr(json, "4. close") + 12
posEnd = InStr(posStart, json, """") - 1
strClose = Mid(json, posStart, posEnd - posStart)
StockClose = Val(strClose)
End Function