有人知道如何在 ASP.NET 中免费获取历史股票数据吗?

发布于 2024-09-15 15:05:09 字数 1539 浏览 6 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

以为你会在 2024-09-22 15:05:09

我的博客上有几个C# 示例,用于获取历史数据来自雅虎。这真的很简单...

更新

关于我的例子...我没有将数据保存到任何东西,我只是在控制台中打印。您必须以最适合您的格式或数据结构保存数据。

// A dictionary with tags where the key is the tag
// and the value is the description of the tag
private Dictionary<string, string> _tags = new Dictionary<string, string>();

private void DownloadData(String symbol)
{
    string url = String.Format(
        "http://finance.yahoo.com/d/quotes.csv?s={0}&f=", symbol);

    //Get page showing the table with the chosen indices
    HttpWebRequest request = null;
    DFDataSet ds = new DFDataSet();
    Random rand = new Random(DateTime.Now.Millisecond);
    try
    {
        while (_running)
        {
            foreach (String key in _tags.Keys)
            {
                lock (_sync)
                {
                    request = (HttpWebRequest)WebRequest.CreateDefault(
                        new Uri(url + key));
                    request.Timeout = 30000;

                    using (var response = (HttpWebResponse)request.GetResponse())
                    using (StreamReader input = new StreamReader(
                        response.GetResponseStream()))
                    {
                        Console.WriteLine(String.Format("{0} {1} = {2}",
                            symbol, _tags[key], input.ReadLine());
                    }
                }
            }
            Console.WriteLine(Thread.CurrentThread.Name + " running.");
            Thread.Sleep(60*1000); // 60 seconds
        }
    }
    catch (Exception exc)
    {
        Console.WriteLine(exc.Message);
    }
}

请注意,您可以在同一个 csv 文件中请求多个标签,而不是一次一个标签...为此,只需将所有感兴趣的标签串在一起并将它们添加到 URL,就像添加单个标签一样。标签的值将以逗号分隔。

更新 2.0

以下是如何从 yahoo 获取日终 (EOD) 历史数据的方法:

void DownloadDataFromWeb(string symbol)
{
    DateTime startDate = DateTime.Parse("1900-01-01");

    string baseURL = "http://ichart.finance.yahoo.com/table.csv?";
    string queryText = BuildHistoricalDataRequest(symbol, startDate, DateTime.Today);
    string url = string.Format("{0}{1}", baseURL, queryText);

    //Get page showing the table with the chosen indices
    HttpWebRequest request = null;
    HttpWebResponse response = null;
    StreamReader stReader = null;

    //csv content
    string docText = string.Empty;
    string csvLine = null;
    try
    {
        request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
        request.Timeout = 300000;

        response = (HttpWebResponse)request.GetResponse();

        stReader = new StreamReader(response.GetResponseStream(), true);

        stReader.ReadLine();//skip the first (header row)
        while ((csvLine = stReader.ReadLine()) != null)
        {
            string[] sa = csvLine.Split(new char[] { ',' });

            DateTime date = DateTime.Parse(sa[0].Trim('"'));
            Double open =  double.Parse(sa[1]);
            Double high = double.Parse(sa[2]);
            Double low = double.Parse(sa[3]);
            Double close = double.Parse(sa[4]);
            Double volume = double.Parse(sa[5]);
            Double adjClose = double.Parse(sa[6]);
            // Process the data (e.g. insert into DB)
        }
    }
    catch (Exception e)
    {
        throw e;
    }
}

string BuildHistoricalDataRequest(string symbol, DateTime startDate, DateTime endDate)
{
    // We're subtracting 1 from the month because yahoo
    // counts the months from 0 to 11 not from 1 to 12.
    StringBuilder request = new StringBuilder();
    request.AppendFormat("s={0}", symbol);
    request.AppendFormat("&a={0}", startDate.Month-1);
    request.AppendFormat("&b={0}", startDate.Day);
    request.AppendFormat("&c={0}", startDate.Year);
    request.AppendFormat("&d={0}", endDate.Month-1);
    request.AppendFormat("&e={0}", endDate.Day);
    request.AppendFormat("&f={0}", endDate.Year);
    request.AppendFormat("&g={0}", "d"); //daily

    return request.ToString();
}

上面的代码将遍历 CSV 文件中的每个数据实例,因此您只需将数据实例保存到数组中即可。从那时起,计算回报应该是直接的。

// Create your data lists
List<DateTime> date = new List<DateTime>();
List<Double> open = new List<Double>();
List<Double> high = new List<Double>();
List<Double> low = new List<Double>();
List<Double> close = new List<Double>();
List<Double> volume = new List<Double>();
List<Double> adjClose = new List<Double>();

//
// ...
//

// inside the DownloadDataFromWeb function:

// Add the data points as you're going through the loop
date.Add(DateTime.Parse(sa[0].Trim('"')));
open.Add(double.Parse(sa[1]));
high.Add(double.Parse(sa[2]));
low.Add(double.Parse(sa[3]));
close.Add(double.Parse(sa[4]));
volume.Add(double.Parse(sa[5]));
adjClose.Add(double.Parse(sa[6]));

//
// ...
//

// Calculate the return after you've downloaded all the data...

我希望这有帮助:)。

I have a couple of C# examples on my blog for getting historical data from Yahoo. It's really simple...

Update

Regarding my example... I'm not saving the data to anything, I'm just printing in the console. You'd have to save the data in whatever format or data structure is most reasonable for you.

// A dictionary with tags where the key is the tag
// and the value is the description of the tag
private Dictionary<string, string> _tags = new Dictionary<string, string>();

private void DownloadData(String symbol)
{
    string url = String.Format(
        "http://finance.yahoo.com/d/quotes.csv?s={0}&f=", symbol);

    //Get page showing the table with the chosen indices
    HttpWebRequest request = null;
    DFDataSet ds = new DFDataSet();
    Random rand = new Random(DateTime.Now.Millisecond);
    try
    {
        while (_running)
        {
            foreach (String key in _tags.Keys)
            {
                lock (_sync)
                {
                    request = (HttpWebRequest)WebRequest.CreateDefault(
                        new Uri(url + key));
                    request.Timeout = 30000;

                    using (var response = (HttpWebResponse)request.GetResponse())
                    using (StreamReader input = new StreamReader(
                        response.GetResponseStream()))
                    {
                        Console.WriteLine(String.Format("{0} {1} = {2}",
                            symbol, _tags[key], input.ReadLine());
                    }
                }
            }
            Console.WriteLine(Thread.CurrentThread.Name + " running.");
            Thread.Sleep(60*1000); // 60 seconds
        }
    }
    catch (Exception exc)
    {
        Console.WriteLine(exc.Message);
    }
}

Note that you can request multiple tags in the same csv file, instead of one tag at a time... to do that, just string all the tags of interest together and add them to the URL just like you add a single tag. The values for the tags will be comma separated.

Update 2.0

Here is how you can get end of day (EOD) historical data from yahoo:

void DownloadDataFromWeb(string symbol)
{
    DateTime startDate = DateTime.Parse("1900-01-01");

    string baseURL = "http://ichart.finance.yahoo.com/table.csv?";
    string queryText = BuildHistoricalDataRequest(symbol, startDate, DateTime.Today);
    string url = string.Format("{0}{1}", baseURL, queryText);

    //Get page showing the table with the chosen indices
    HttpWebRequest request = null;
    HttpWebResponse response = null;
    StreamReader stReader = null;

    //csv content
    string docText = string.Empty;
    string csvLine = null;
    try
    {
        request = (HttpWebRequest)WebRequest.CreateDefault(new Uri(url));
        request.Timeout = 300000;

        response = (HttpWebResponse)request.GetResponse();

        stReader = new StreamReader(response.GetResponseStream(), true);

        stReader.ReadLine();//skip the first (header row)
        while ((csvLine = stReader.ReadLine()) != null)
        {
            string[] sa = csvLine.Split(new char[] { ',' });

            DateTime date = DateTime.Parse(sa[0].Trim('"'));
            Double open =  double.Parse(sa[1]);
            Double high = double.Parse(sa[2]);
            Double low = double.Parse(sa[3]);
            Double close = double.Parse(sa[4]);
            Double volume = double.Parse(sa[5]);
            Double adjClose = double.Parse(sa[6]);
            // Process the data (e.g. insert into DB)
        }
    }
    catch (Exception e)
    {
        throw e;
    }
}

string BuildHistoricalDataRequest(string symbol, DateTime startDate, DateTime endDate)
{
    // We're subtracting 1 from the month because yahoo
    // counts the months from 0 to 11 not from 1 to 12.
    StringBuilder request = new StringBuilder();
    request.AppendFormat("s={0}", symbol);
    request.AppendFormat("&a={0}", startDate.Month-1);
    request.AppendFormat("&b={0}", startDate.Day);
    request.AppendFormat("&c={0}", startDate.Year);
    request.AppendFormat("&d={0}", endDate.Month-1);
    request.AppendFormat("&e={0}", endDate.Day);
    request.AppendFormat("&f={0}", endDate.Year);
    request.AppendFormat("&g={0}", "d"); //daily

    return request.ToString();
}

The code above will go through each data instance in the CSV file, so you just need to save the data instances to arrays. Calculating the return should be straight forward from then on.

// Create your data lists
List<DateTime> date = new List<DateTime>();
List<Double> open = new List<Double>();
List<Double> high = new List<Double>();
List<Double> low = new List<Double>();
List<Double> close = new List<Double>();
List<Double> volume = new List<Double>();
List<Double> adjClose = new List<Double>();

//
// ...
//

// inside the DownloadDataFromWeb function:

// Add the data points as you're going through the loop
date.Add(DateTime.Parse(sa[0].Trim('"')));
open.Add(double.Parse(sa[1]));
high.Add(double.Parse(sa[2]));
low.Add(double.Parse(sa[3]));
close.Add(double.Parse(sa[4]));
volume.Add(double.Parse(sa[5]));
adjClose.Add(double.Parse(sa[6]));

//
// ...
//

// Calculate the return after you've downloaded all the data...

I hope that's helpful :).

烈酒灼喉 2024-09-22 15:05:09

我同意您可以简单地解析从 Yahoo/Google 或类似网站下载的数据。如果您只对每日 (eod) 数据感兴趣,您可以在您的网站中下载并使用此历史数据提供商的数据。免费申请。提供文档以及即用型 C# 和 VB.NET 示例。

I agree that you can simply parse the data downloaded from Yahoo/Google or similar sites. If you only interested in daily (eod) data, you may download and use data from this historical data provider in your application for free. Documentation and ready-to-use C# and VB.NET examples are available.

£冰雨忧蓝° 2024-09-22 15:05:09

查看 Mergent 历史证券数据 API,网址为 http://www.mergent.com/servius

Take a look at the Mergent Historical Securities Data API at http://www.mergent.com/servius

来世叙缘 2024-09-22 15:05:09

作为一名软件开发人员,我会推荐 Alpha Vantage。他们以 RESTful JSON API 的形式提供实时和历史股票报价(每日、每周、每月等)。

它完全免费,可以无限制地调用 API。只要股票在主要证券交易所上市,它就是实时的。

此处是 MSFT 日报的 API 调用示例价格和数量,通过分割/股息调整而丰富。最新数据点是当前交易日的实时信息。

他们还根据其文档提供基于市场数据的技术分析 API。

As a software developer, I would recommend Alpha Vantage. They offer realtime and historical stock quotes (daily, weekly, monthly, etc.) as RESTful JSON APIs.

It’s completely free with unlimited API calls. It’s realtime as long as the stock is listed on major stock exchanges.

Here is an example API call for the MSFT daily prices and volumes, enriched with split/dividend adjustments. The latest data point is the realtime information for the current trading day.

They also offer technical analysis APIs on top of the market data according to their documentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文