有关如何快速、免费、稳定获得股票行情数据,一直是个人投资者的希望。遗憾,基本不太可能兼顾快速、免费和稳定。网上有SAS通过读取同花顺/大智慧等行情软件的临时文件夹获得行情数据,也可以用Matlab的DataFeed通过yahoo接口获得延迟行情数据。
而Mathematica的FinancialData函数能获得全球60多个交易所等多个交易品种的历史日度数据和主要交易所上市公司的基本面数据,如利润、PE等财务指标。
另外,新浪也提供了股票行情接口,根据我的观测,新浪提供的访问接口,稳定且可靠,基本上在Level1的基准上不丢数据,所以是可靠的获取股票行情准实时数据的好地方。
下面我给出了在VC控制台应用程序下写访问新浪行情接口的类,并把行情实时写到外部的TXT文件中,如果从开盘一直打开到闭市,数据相当的完好,对于获得所有证券的实时数据,可以在这个基础上做一些修改。
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include "afxinet.h"
#include <string>
using namespace std;
class stkquote
{
public:
stkquote(string& stkcode,string& exchange,string &outputfile);
stkquote::~stkquote();
string m_stockcode;
string m_exchange;
string m_outputfile;
void getquote();
private:
char m_prequote[300];
char m_buffer[300];
size_t m_recordcount;
};
stkquote::stkquote(string& stkcode,string& exchange,string &outputfile)
:m_stockcode(stkcode),m_exchange(exchange),m_outputfile(outputfile),m_recordcount(0)
{
memset(m_prequote,0,300);
memset(m_buffer,0,300);
}
stkquote::~stkquote(){}
void stkquote::getquote(){
CInternetSession session((LPCTSTR)"by_dreamcatcher"); //"建立会话"
CStdioFile* sessionfile=NULL;
const string sinaurl("http://hq.sinajs.cn/list="+m_exchange+m_stockcode);
try{
sessionfile=session.OpenURL((LPCTSTR)sinaurl.c_str());
}
catch(CInternetException& ex){
cout<<"error"<<" open request faile:"
<<"dwcontext:"<<ex.m_dwContext<<"\tdwErrorCode:"<<ex.m_dwError<<endl;
ex.Delete();
}
ofstream output(m_outputfile.c_str(),ios_base::app); //打开文件写
if(!output.is_open())
{ cout<<"can't open the outputfile,please check the filepath is ok.";
return ;
}
size_t getlen;
if(sessionfile==NULL)
{
cout<<"Error,can't read the stdiofile"<<endl;
}
else
{
getlen=sessionfile->Read(m_buffer,300);
if(strncmp(m_prequote,m_buffer,100)!=0)
{
for(size_t i=0;i<getlen;++i)
output<<m_buffer[i];
if(m_recordcount==0)
cout<<"Security "<< m_stockcode<<" will be output ot:\t"<<m_outputfile<<endl;
cout<<++m_recordcount<<endl;
strcpy_s(m_prequote,m_buffer);
}
}
}
int main(int argc, char* argv[])
{
stkquote aquote(string("600000"),string("sh"),string("f:\\60000_20120611.txt"));
for(size_t i=0;i<50000;++i)
{
aquote.getquote();
Sleep(1000); //level 1行情5秒刷一次,这里避免漏数据,设为1秒
}
}