使用NSE(国家证券交易所)的股票报价更新excel单元格

时间:2016-04-11 22:19:17

标签: excel vba excel-vba

问题与excel的VBA有关。我在Mac上运行MS Excel 2011。

使用http://finance.google.com/finance/info?client=ig&q=NSE:INFY我可以获得股票价格详情。这是来自Google财经的旧API仍然有效。

正在寻找一些帮助来更新excel单元格,其中包含从此API数据集返回的价格。

返回类似

的内容
▶ curl http://finance.google.com/finance/info\?client\=ig\&q\=NSE:INFY

// [
{
"id": "675530"
,"t" : "INFY"
,"e" : "NSE"
,"l" : "1,184.10"
,"l_fix" : "1184.10"
,"l_cur" : "Rs.1,184.10"
,"s": "0"
,"ltt":"3:40PM GMT+5:30"
,"lt" : "Apr 11, 3:40PM GMT+5:30"
,"lt_dts" : "2016-04-11T15:40:45Z"
,"c" : "+18.35"
,"c_fix" : "18.35"
,"cp" : "1.57"
,"cp_fix" : "1.57"
,"ccol" : "chg"
,"pcls_fix" : "1165.75"
}
]

我可以使用shell脚本解压缩,但我想在excel

中使用它

CLI:

curl --silent http://finance.google.com/finance/info\?client\=ig\&q\=NSE:INFY\ > /tmp/ChangeIsInevitable && cat /tmp/ChangeIsInevitable | grep l_fix | sed 's/[",]//g' | awk '{print $3}'
1184.10

2 个答案:

答案 0 :(得分:0)

没有找到使用VBA进行EXCEL MAC的直接方式。 所以写了一个小的shell脚本来获取CSV。然后将其导入excel

我只想按需获得少量股票价格的最新价格。 为了使用它,你应该有一个名为" stocklist"在你家〜 与你想要的股票 默认搜索适用于NSE,您可以将索引的变量值更改为 BSE

#!/bin/bash
index=NSE
filename=~/latestPrice.txt

#Cleanup temp files
cp /dev/null $filename

echo "Stock,Price" >> $filename
for i in `cat ~/stocklist`
do
  curl --silent "http://finance.google.com/finance/info?client=ig&q=${index}:${i}" > /tmp/tmpfile
  stockPrice=`cat /tmp/tmpfile | grep l_fix | sed 's/[",]//g' | awk '{print $3}'`
  echo "$i : $stockPrice"
  echo "$i,$stockPrice" >> $filename
done

编辑:

因为我已经开始使用python,所以这是一个提供CSV输出的python版本。

import requests
import json


stocks = [
'NSE:AXISBANK',
'NSE:BAJAJ-AUTO'
]

r = requests.get("http://finance.google.com/finance/info?client=ig&q=%s" % (','.join(stocks)))

result = r.content

result = result.replace("// ","")
data = json.loads(result)
for stock in data:
    print "%s,%s" % (stock['t'], stock['pcls_fix'])

答案 1 :(得分:0)

使用VBA-JSON Git库(您直接保存到独立模块并引用Microsft Runtime引用),Excel VBA可以解析json对象:

Dim jsonStr As String, strPath As String, URL As String
Dim p As Object, element As Variant
Dim i As Integer, j As Integer
Dim wb As Workbook 
Dim jsondata As New Collection

strPath = ActiveWorkbook.Path

' DOWNLOAD JSON 
Dim objhttp As Object

URL = "http://finance.google.com/finance/info?client=ig&q=MSFT"
Set objhttp = CreateObject("Microsoft.XMLHTTP") 
With objhttp 
   .Open "GET", URL, False 
   .send 
   jsonStr = Replace(.responseText, "/", "")
End With 

Set p = ParseJson(jsonStr)

' OPEN EXTERNAL WORKBOOK
Set wb = Workbooks.Add 
wb.Activate

' ITERATE DATA ROWS
i = 1
For Each element In p
    If i = 1 Then
        ' HEADERS
        j = 1
        For Each k in element.keys
             wb.Sheets(1).Cells(i, j) = k
             j = j + 1
        Next k
    Else
        ' DATA ROWS
        j = 1
        For Each k in element.keys
             wb.Sheets(1).Cells(i, j) = element(k)
             j = j + 1
        Next k
    End if
    i = i + 1
Next element

Set objhttp = Nothing
Set element = Nothing
Set p = Nothing
Set wb = Nothing