想研究一下股票,作为一个程序员,找到了一个很好的可以下载金融数据的网站,tushare.pro。由于tushare是一个python类库,网上一大把怎么用python获取股票信息的代码
然而作为一个c#开发人员,想找一些用c#获取tushare数据的代码做参考,无果。只有自己动手了,结果一番摸索,终于成功调用tushare的HTTP方法。给有类似需要的朋友做参考。
首先,vs2019新建一个window窗体项目,名称随便
image
在窗体上放一个button,改名为"下载日线数据"
image
引入Newtonsoft.Json和Microsoft.AspNet.WebApi.Client包
添加文件夹helpers和Models
image
新建一个类,APIHelper,用来发起请求
{
public static HttpClient ApiClient { get; set; }
public static void InitClient()
{
ApiClient = new HttpClient();
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
在Models文件夹下新建类:StockType
/// <summary>
/// 股票类别,根据自己的需要扩展
/// </summary>
public enum StockType
{
/// <summary>
/// 股票基本信息
/// </summary>
stock_basic,
/// <summary>
/// 交易日期
/// </summary>
trade_cal,
/// <summary>
/// 日线行情
/// </summary>
daily
}
StockPara 类:
` /// <summary>
/// 调用tushare http接口的参数类
/// </summary>
public class StockPara
{
public StockType stockType { get; set; }
public string api_name { get; set; }
public string token { get; set; }
public Dictionary<string,string> sparams{get;set;}
public string fields { get; set; }
}
StockData 类:
/// <summary>
/// 具体的股票数据,根据获取的类型不同,fields,items的数据不一样
/// </summary>
public class StockData
{
public string[] fields { get; set; }
public string[][] items { get; set; }
}
StockAllInfo 类:
/// <summary>
/// 所有http接口返回的信息
/// </summary>
public class StockAllInfo
{
public string request_id { get; set; }
public int code { get; set; }
public string msg { get; set; }
public StockData data { get; set; }
}
在helpers文件夹下新建 StockProcessor类:
public class StockProcessor
{
static string Url = "http://api.tushare.pro";
static string Token = "你注册后的Token";
/// <summary>
/// 根据参数获取股票信息,在根据业务逻辑进行处理
/// </summary>
/// <param name="stockType"></param>
/// <param name="sparams"></param>
/// <param name="fields"></param>
/// <returns></returns>
public static async Task<StockData> GetStockInfo(StockType stockType, Dictionary<string, string> sparams, string fields = "")
{
StockPara para = new StockPara();
para.api_name = stockType.ToString();
para.token = Token;
para.sparams = sparams;
para.fields = fields;
var json = JsonConvert.SerializeObject(para);
var data = new StringContent(json, Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await APIHelper.ApiClient.PostAsync(Url, data))
{
if (response.IsSuccessStatusCode)
{
var msg = await response.Content.ReadAsAsync<StockAllInfo>();
return msg.data;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
我用的是sql2008数据库,新建一个数据库,名为stock,执行下面的sql语句:
USE [Stock]
GO
/****** Object: Table [dbo].[stock_dayly] Script Date: 2019/12/31 12:31:20 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[stock_dayly](
[ts_code] [varchar](50) NOT NULL,
[trade_date] [varchar](50) NOT NULL,
[open] [float] NULL,
[high] [float] NULL,
[low] [float] NULL,
[close] [float] NULL,
[pre_close] [float] NULL,
[change] [float] NULL,
[pct_chg] [float] NULL,
[vol] [float] NULL,
[amount] [float] NULL
) ON [PRIMARY]
GO
最后,更改Form1的代码如下:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
APIHelper.InitClient();
}
/// <summary>
/// 获取日线行情
/// </summary>
/// <returns></returns>
private async Task GetStock_Daily()
{
Dictionary<string, string> paras = new Dictionary<string, string>();
paras.Add("start_date", "20191230");
paras.Add("end_date", "20191230");
var objs = await StockProcessor.GetStockInfo(StockType.daily, paras);
DataTable dt = new DataTable();
dt.Columns.Add("ts_code", typeof(string));
dt.Columns.Add("trade_date", typeof(string));
dt.Columns.Add("open", typeof(float));
dt.Columns.Add("high", typeof(float));
dt.Columns.Add("low", typeof(float));
dt.Columns.Add("close", typeof(float));
dt.Columns.Add("pre_close", typeof(float));
dt.Columns.Add("change", typeof(float));
dt.Columns.Add("pct_chg", typeof(float));
dt.Columns.Add("vol", typeof(float));
dt.Columns.Add("amount", typeof(float));
for (int i = 0; i < objs.items.Length; i++)
{
DataRow row = dt.NewRow();
for (int j = 0; j < objs.fields.Length; j++)
{
row[j] = objs.items[i][j];
}
dt.Rows.Add(row);
}
string connectionString = @" Server = localhost; Database = Stock; Trusted_Connection = True;";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))
{
try
{
bulkCopy.DestinationTableName = "stock_dayly";
bulkCopy.WriteToServer(dt);
}
catch (System.Exception ex)
{
throw ex;
}
}
}
}
private async void button1_Click(object sender, EventArgs e)
{
await GetStock_Daily();
MessageBox.Show("下载日线数据成功");
}
}
点击按钮
image.png
以上就是我简单的示例代码,我的类都写了注释,不懂的可以看注释。其中的亮点,插入代码用了SqlBulkCopy类,示例中,4000行数据插入花了不到1秒时间。
网友评论