分级基金折溢价WinForm网络计算器
通过子/母基金代码,从 [ 东方财富网,天天基金网,新浪 ] 抓取分级基金的子母基金数据(代码,名称,净值,价格),
并计算出子基金(A基金,B基金)以及母基金的溢价率与折价率,
便于投资/投机客从中套利。
数据通过网站获取,使用基金净值,非估值,一般晚间网站会更新当天基金净值,不可用于实时计算。
------
效果图:
----
代码:
1.窗体如效果图
2.常用变量与数据抓取代码:
namespace fundGetAndCal
{
public static class CONST
{
//获取母子基金代码
public static string fundF10Url = "http://fund.eastmoney.com/f10/jbgk_{%fundCode%}.html";
//获取净值
public static string fundValUrl = "http://fund.eastmoney.com/{%fundCode%}.html";
//获取价格
public static string fundPriceUrl = "http://hq.sinajs.cn/?list={%fundAllCode%}";
//母子基金列表
public static List<string[]> allFunCodeLst;
//读取完了
public static bool okFlg = false;
//状态显示文字
public static string show = "就绪";
public static int barMax = ;
public static int barNow = ; public static string GetHtml(string url, Encoding encode)
{
string strBuff = "";//定义文本字符串,用来保存下载的html
try
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
//若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理
Stream reader = webResponse.GetResponseStream();
///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8)
StreamReader respStreamReader = new StreamReader(reader,/*Encoding.UTF8*/encode); strBuff = respStreamReader.ReadToEnd();
}
catch (Exception e)
{
Console.Write(url+"\n"+e.Message);
}
return strBuff;
}
}
}
3.窗体按钮等事件代码:
namespace fundGetAndCal
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
getFundCode();
}
private void btnFundCodeRead_Click(object sender, EventArgs e)
{
getFundCode();
}
private void getFundCode()
{
string waitFuncCodes = ConfigurationManager.AppSettings.Get("fundCode");
waitFuncCodes = waitFuncCodes.Replace(",", "\r\n");
fundCodeLst.Text = waitFuncCodes;
}
private string delStr(string org, string other)
{
if (!other.Equals(""))
org = org.Replace(other, "");
return Regex.Replace(org, @"<.*?>", "");
}
private void btnStart_Click(object sender, EventArgs e)
{
Thread thread = new Thread(getData);
thread.IsBackground = true;
CONST.barMax = ;
CONST.barNow = ; btnStart.Enabled = false;
btnStop.Enabled = true;
CONST.okFlg = false; thread.Start();
timer1.Start();
} private void getData()
{
/// 提取母子基金代码 // 提取母基金正则
Regex regMJJ = new Regex(@"母子基金.*?<\/td>");
// 提取基金净值正则
Regex regJZ = new Regex(@"<span class=\'left12\'>.*?<\/span>");
// 提取基金名称正则
Regex regMC = new Regex(@"<title.*?<\/title>");
string[] fcl = fundCodeLst.Text.Replace("\r\n", ",").Split(',');
List<string[]> allFCLst = new List<string[]>();
List<string> geted = new List<string>(); foreach (string fc in fcl)
{
CONST.show = "开始获取[" + fc + "]子母基金代码";
if (geted.Contains(fc.Substring(, fc.Length - )))
continue;
string html = CONST.GetHtml(CONST.fundF10Url.Replace("{%fundCode%}", fc.Substring(, fc.Length - )), Encoding.GetEncoding("gb2312")); var result = regMJJ.Match(html).Groups;
if (result.Count > )
{
// 1-3 代码,4-6 净值 7-9 价格 10 sz/ss 11-13 名称
string[] allFC = new string[] { "", "", "", "", "", "", "", "", "", "", "", "", "" };
var r = delStr(result[].Value, "母子基金");
string[] t1 = Regex.Split(r, "(母)", RegexOptions.IgnoreCase);
geted.Add(t1[]);
allFC[] = t1[];
if (t1.Length > )
{
string[] t2 = t1[].Split(' ');
for (int i = ; i < t2.Length; i++)
{
geted.Add(t2[i].Replace("(子)", ""));
allFC[i + ] = t2[i].Replace("(子)", "");
}
if (t2.Length == )
{
allFC[] = fc.Substring(, );
allFCLst.Add(allFC);
}
}
}
//Thread.Sleep(1000);
}
CONST.barNow = CONST.barNow + (int)Math.Floor((decimal)CONST.barMax / );
CONST.allFunCodeLst = allFCLst; // 获取净值,名称
foreach (string[] allFC in CONST.allFunCodeLst)
{
for (int i = ; i < ; i++)
{
CONST.show = "开始获取[" + allFC[i] + "]净值与名称";
string html = CONST.GetHtml(CONST.fundValUrl.Replace("{%fundCode%}", allFC[i]), Encoding.GetEncoding("gb2312")); var result = regJZ.Match(html).Groups;
if (result.Count > )
{
allFC[ + i] = delStr(result[].Value, "");
}
result = regMC.Match(html).Groups;
string[] a = delStr(result[].Value, "").Split('(');
if (a.Length > )
{
allFC[ + i] = a[];
} //Thread.Sleep(1000);
}
}
CONST.barNow = CONST.barNow + (int)Math.Floor((decimal)CONST.barMax / ); // 获取价格
foreach (string[] allFC in CONST.allFunCodeLst)
{
for (int i = ; i < ; i++)
{
CONST.show = "开始获取[" + allFC[i] + "]价格";
string html = CONST.GetHtml(CONST.fundPriceUrl.Replace("{%fundAllCode%}", allFC[] + allFC[i]), Encoding.GetEncoding("gb2312")); string[] result = html.Split(',');
if (result.Length > )
{
allFC[ + i] = result[];
}
//Thread.Sleep(1000);
}
}
CONST.barNow = CONST.barNow + (int)Math.Floor((decimal)CONST.barMax / );
CONST.okFlg = true; } private void timer1_Tick(object sender, EventArgs e)
{
if (CONST.okFlg)
{
CONST.show = "开始获取计算溢折价,并输出";
// 计算A,B基金溢折价,母基金溢折价
dataGridView1.Rows.Clear();
dataGridView1.Columns.Clear();
dataGridView1.Columns.Add("code1", "母代码");
dataGridView1.Columns.Add("name1", "母名称");
dataGridView1.Columns.Add("val1", "母净值");
dataGridView1.Columns.Add("yzj1", "母溢折价");
dataGridView1.Columns.Add("code2", "A代码");
dataGridView1.Columns.Add("name2", "A名称");
dataGridView1.Columns.Add("val2", "A净值");
dataGridView1.Columns.Add("price2", "A价格");
dataGridView1.Columns.Add("yzj2", "A溢折价");
dataGridView1.Columns.Add("code3", "B代码");
dataGridView1.Columns.Add("name3", "B名称");
dataGridView1.Columns.Add("val3", "B净值");
dataGridView1.Columns.Add("price3", "B价格");
dataGridView1.Columns.Add("yzj3", "B溢折价");
foreach (string[] allFC in CONST.allFunCodeLst)
{
DataGridViewRow dgvr = new DataGridViewRow();
dataGridView1.Rows.Add(dgvr);
dgvr = dataGridView1.Rows[dataGridView1.Rows.Count - ];
dgvr.Cells["code1"].Value = allFC[];
dgvr.Cells["code2"].Value = allFC[];
dgvr.Cells["code3"].Value = allFC[];
dgvr.Cells["name1"].Value = allFC[];
dgvr.Cells["name2"].Value = allFC[];
dgvr.Cells["name3"].Value = allFC[];
dgvr.Cells["val1"].Value = allFC[];
dgvr.Cells["val2"].Value = allFC[];
dgvr.Cells["val3"].Value = allFC[];
dgvr.Cells["price2"].Value = allFC[];
dgvr.Cells["price3"].Value = allFC[];
if (allFC[] != "" && allFC[] != "")
{
dgvr.Cells["yzj1"].Value = Math.Round((
(double.Parse(allFC[]) + double.Parse(allFC[])) * 0.5 - double.Parse(allFC[])) / double.Parse(allFC[]) * , ) + "%"; ;
dgvr.Cells["yzj2"].Value = Math.Round((double.Parse(allFC[]) - double.Parse(allFC[])) / double.Parse(allFC[]) * , ) + "%";
dgvr.Cells["yzj3"].Value = Math.Round((double.Parse(allFC[]) - double.Parse(allFC[])) / double.Parse(allFC[]) * , ) + "%"; if (dgvr.Cells["yzj1"].Value.ToString().StartsWith("-"))
{
dgvr.Cells["yzj1"].Style.ForeColor = Color.Green;
}
else
{
dgvr.Cells["yzj1"].Style.ForeColor = Color.Red;
}
if (dgvr.Cells["yzj2"].Value.ToString().StartsWith("-"))
{
dgvr.Cells["yzj2"].Style.ForeColor = Color.Green;
}
else
{
dgvr.Cells["yzj2"].Style.ForeColor = Color.Red;
}
if (dgvr.Cells["yzj3"].Value.ToString().StartsWith("-"))
{
dgvr.Cells["yzj3"].Style.ForeColor = Color.Green;
}
else
{
dgvr.Cells["yzj3"].Style.ForeColor = Color.Red;
}
}
}
StatusLabel.Text = "就绪";
ProgressBar.Value = CONST.barMax;
CONST.okFlg = false;
timer1.Stop();
btnStart.Enabled = true;
btnStop.Enabled = false;
}
else
{
StatusLabel.Text = CONST.show;
ProgressBar.Maximum = CONST.barMax;
ProgressBar.Value = CONST.barNow > CONST.barMax ? CONST.barMax : CONST.barNow;
}
} private void btnFundCodeSave_Click(object sender, EventArgs e)
{
// 写入参数设置
string fundCode = fundCodeLst.Text.Replace("\r\n", ",");
Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings["fundCode"].Value = fundCode;
configuration.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
MessageBox.Show("保存成功");
} private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
if (e.Column.HeaderText.EndsWith("溢折价"))
{
// 按数字排序
if (e.CellValue1 == null || "".equals(e.CellValue1))//附件此处有错
{
e.SortResult = -1;//附件此处有错
}
else if (e.CellValue2 == null || "".equals(e.CellValue2))//附件此处有错
{
e.SortResult = ;//附件此处有错
}
else
{
e.SortResult = double.Parse(e.CellValue1.ToString().Replace("%", "")) - double.Parse(e.CellValue1.ToString().Replace("%", "")) > ? : double.Parse(e.CellValue1.ToString().Replace("%", "")) - double.Parse(e.CellValue1.ToString().Replace("%", "")) < ? -1 : ;//附件此处有错
}
}
else
{
// 按字符串排序
e.SortResult = String.Compare(Convert.ToString(e.CellValue1), Convert.ToString(e.CellValue2));
}e.Handled = true;//附件此处有错,如此才能反映到winform上去
}
}
}
---
源码及程序下载地址: