那天找到了讀取股市歷史資料的範例, 今天要來簡單改寫.
private void button6_Click(object sender, EventArgs e)
{
string stock_id = "";
label1.Text = "0";
// 讀取所有股票列表
DataView myDataView = DAL.GetStocksData.GetStocksCode();
// 如果沒有 C:/Stocks/ 目錄, 則建立
if (!Directory.Exists("C:/Stocks/")) Directory.CreateDirectory("C:/Stocks/");
// 所有股票列表
foreach (DataRowView myDRV in myDataView)
{
listBox2.Items.Add(myDRV["code"].ToString());
stock_id = myDRV["code"].ToString();
FileStream fs = new FileStream("C:/Stocks/" + stock_id + ".csv", FileMode.Create);
StreamWriter sw = new StreamWriter(fs, Encoding.GetEncoding(950));
sw.WriteLine("股市代號,日期,收盤價");
var SQLCommand = string.Empty;
// 自1999年到2014年
for (int y = 1999; y <= 2014; y++)
{
// 自1到12月
for (int m = 1; m <= 12; m++)
{
// 讀取 getMonthData
List<string> month_data = getMonthData(stock_id, y, m);
for (int i = 0; i < month_data.Count; i++)
{
// 產生 SQLCommand
SQLCommand = "INSERT INTO stockshistory (StocksCode,Date,Price) VALUES('";
SQLCommand += month_data[i].Replace(",", "','");
SQLCommand += "')";
int intStatus = GetStocksData.RunSQLCommand(SQLCommand);
label1.Text = (Convert.ToDouble(label1.Text) + 1).ToString();
// 寫入資料
sw.WriteLine(month_data[i]);
}
// 秀在Console
Console.WriteLine(y + "/" + m + (month_data.Count == 0 ? " no data." : " download."));
}
}
sw.Close();
fs.Close();
但是我們增加股票代號.
private static List<string> getMonthData(string stock_id, int year, int month)
{
//ref: http://msdn.microsoft.com/zh-tw/library/system.net.webrequest.aspx
// http://www.twse.com.tw/ch/trading/exchange/STOCK_DAY_AVG/STOCK_DAY_AVG2.php?STK_NO=2330&myear=2014&mmon=10&type=csv
// Create a request for the URL.
WebRequest request = WebRequest.Create("http://www.twse.com.tw/ch/trading/exchange/STOCK_DAY_AVG/STOCK_DAY_AVG2.php?STK_NO=" + stock_id + "&myear=" + year + "&mmon=" + month.ToString("0#") + "&type=csv");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream, Encoding.GetEncoding(950));
// Read the content.
List<string> data = new List<string>();
string title1 = reader.ReadLine(); //98年12月 2002 中鋼 日收盤價及月平均收盤價(元)
if (title1 == null) //表示沒資料
{
}
else
{
reader.ReadLine(); //日期 收盤價
while (!reader.EndOfStream)
{
data.Add(stock_id.Trim() + "," + reader.ReadLine().Trim());
}
data.RemoveAt(data.Count - 1); //說明:以上成交資料採市場交易時間之資料計算。
data.RemoveAt(data.Count - 1); //月平均收盤價 31.18
}
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
return data;
}
2.處理抓資料的程式段落, 也是增加股票代號
因為我們將會抓所有上市股票的資料, 所以需要這個欄位加以區分.