【小白量化机器人】环境提供了全球市场的实时行情和交易接口。我们利用本地大模型进行分析。一般趋势行情选择趋势策略震荡行情选择震荡策略。我们利用爬虫爬取最近2天的财经新闻。再利用大模型进行评分。如果新闻平稳偏向看多就使用趋势交易策略。一、爬取新闻程序演示代码。importrequestsfrombs4importBeautifulSoupimportosfromdatetimeimportdatetime,timedeltaimportreimportsysimportio# 设置系统编码为UTF-8sys.stdoutio.TextIOWrapper(sys.stdout.buffer,encodingutf-8)sys.stderrio.TextIOWrapper(sys.stderr.buffer,encodingutf-8)# 确保文件路径使用UTF-8编码importlocale locale.setlocale(locale.LC_ALL,zh_CN.UTF-8)defcreate_directory():创建最新日期目录# 获取当前日期作为目录名todaydatetime.now().strftime(%Y-%m-%d)directoryos.path.join(os.getcwd(),today)ifnotos.path.exists(directory):os.makedirs(directory)returndirectorydefclean_filename(filename):清理文件名去除非法字符# 去除非法字符filenamere.sub(r[:/\\|?*],,filename)# 限制文件名长度iflen(filename)100:filenamefilename[:100]returnfilenamedefcrawl_financial_news():爬取财经新闻# 爬取新浪财经新闻urlhttps://finance.sina.com.cn/headers{User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36}try:responserequests.get(url,headersheaders,timeout10)response.raise_for_status()# 处理编码确保正确解析GBK内容ifcharsetinresponse.headers:encodingresponse.headers[charset]else:# 尝试自动检测编码encodingresponse.apparent_encoding# 确保使用正确的编码解析内容response.encodingencoding soupBeautifulSoup(response.text,html.parser)# 创建最新日期目录directorycreate_directory()# 提取新闻链接news_links[]# 查找新闻列表forlinkinsoup.find_all(a,hrefTrue):hreflink[href]# 筛选财经新闻链接if(/finance/inhrefor/money/inhref)andhref.startswith(https://):news_links.append(href)# 去重news_linkslist(set(news_links))print(f找到{len(news_links)}条新闻链接)# 计算2天前的日期two_days_ago(datetime.now()-timedelta(days2)).date()# 爬取每条新闻saved_count0fori,news_urlinenumerate(news_links):# 不限制数量爬取所有链接try:news_responserequests.get(news_url,headersheaders,timeout10)news_response.raise_for_status()# 处理编码确保正确解析GBK内容ifcharsetinnews_response.headers:encodingnews_response.headers[charset]else:# 尝试自动检测编码encodingnews_response.apparent_encoding# 确保使用正确的编码解析内容news_response.encodingencoding news_soupBeautifulSoup(news_response.text,html.parser)# 提取标题titlenews_soup.find(h1)ifnottitle:titlenews_soup.find(h2)iftitle:title_texttitle.get_text(stripTrue)else:title_textf新闻{i}# 提取发布时间publish_timeNone# 尝试从meta标签提取发布时间meta_timenews_soup.find(meta,{name:publishdate})ifmeta_time:publish_timemeta_time.get(content)# 尝试从时间标签提取ifnotpublish_time:time_tagsnews_soup.find_all([time,span],class_[time,pubtime,publish_time])fortagintime_tags:time_texttag.get_text(stripTrue)ifre.search(r\d{4}-\d{2}-\d{2},time_text):publish_timetime_textbreak# 尝试从链接中提取日期ifnotpublish_time:date_matchre.search(r/(\d{4}-\d{2}-\d{2})/,news_url)ifdate_match:publish_timedate_match.group(1)# 检查是否在最近2天内ifpublish_time:try:# 解析发布日期ifisinstance(publish_time,str):# 提取日期部分date_strre.search(r\d{4}-\d{2}-\d{2},publish_time)ifdate_str:publish_datedatetime.strptime(date_str.group(0),%Y-%m-%d).date()# 检查是否在最近2天内ifpublish_datetwo_days_ago:# 提取内容content[]content_divnews_soup.find(div,class_[article,content,main-content])ifcontent_div:paragraphscontent_div.find_all(p)forpinparagraphs:textp.get_text(stripTrue)iftext:content.append(text)ifnotcontent:# 尝试其他方式提取内容forpinnews_soup.find_all(p):textp.get_text(stripTrue)iflen(text)50:# 过滤短文本content.append(text)# 保存到文件iftitle_textandcontent:filenameclean_filename(title_text).txtfile_pathos.path.join(directory,filename)withopen(file_path,w,encodingutf-8)asf:f.write(f标题:{title_text}\n)f.write(f链接:{news_url}\n)f.write(f发布时间:{publish_time}\n)f.write(f爬取时间:{datetime.now().strftime(%Y-%m-%d %H:%M:%S)}\n\n)f.write(内容:\n)f.write(\n.join(content))print(f已保存:{filename}(发布时间:{publish_time}))saved_count1exceptExceptionase:print(f解析日期失败:{publish_time}, 错误:{str(e)})exceptExceptionase:print(f爬取新闻失败:{news_url}, 错误:{str(e)})print(f爬取完成共保存{saved_count}条最近2天内的新闻)exceptExceptionase:print(f爬取失败:{str(e)})if__name____main__:crawl_financial_news()二、本地大模型分析代码。##连接本地deepseek##先安装ollama模块:pip install ollama# ollama run deepseek-coder-v2:latestimportollamafromollamaimportchatimportosimportrefromdatetimeimportdatetime,timedelta# 定义分析规则规则 帮我分析下面新闻对明天股市有什么影响。对股市多空评分为1-106以上看多5以下看空。只要一个评分你打多少分不要思考过程只要评分。 defextract_score_from_response(response):从大模型响应中提取评分数字# 使用正则表达式匹配1-10的数字matchre.search(r\b([1-9]|10)\b,response)ifmatch:returnint(match.group(1))returnNonedefanalyze_news_content(content):分析单篇新闻内容# 组合规则和新闻内容ask规则 contenttry:# 调用大模型进行分析streamchat(modelqwen3:8b,messages[{role:user,content:ask}],streamTrue,)# 收集响应内容responseforchunkinstream:responsechunk[message][content]# 提取评分scoreextract_score_from_response(response)returnscore,response.strip()exceptExceptionase:print(f分析新闻时出错:{e})returnNone,Nonedefprocess_news_directory(directory_path):处理新闻目录中的所有txt文件scores[]file_results[]# 检查目录是否存在ifnotos.path.exists(directory_path):print(f目录不存在:{directory_path})returnNone,None# 获取所有txt文件txt_files[fforfinos.listdir(directory_path)iff.endswith(.txt)]print(f找到{len(txt_files)}个新闻文件)ifnottxt_files:print(目录中没有找到txt文件)returnNone,None# 处理每个文件forfilenameintxt_files:file_pathos.path.join(directory_path,filename)print(f\n正在分析:{filename})try:# 读取文件内容withopen(file_path,r,encodingutf-8)asf:contentf.read()# 分析新闻内容score,responseanalyze_news_content(content)ifscoreisnotNone:scores.append(score)file_results.append({filename:filename,score:score,response:response})print(f评分:{score})else:print(f无法提取评分响应:{response})file_results.append({filename:filename,score:None,response:response})exceptExceptionase:print(f处理文件{filename}时出错:{e})file_results.append({filename:filename,score:None,response:f错误:{e}})returnscores,file_resultsdefcalculate_prediction(scores):计算平均评分并给出多空预测ifnotscores:returnNone,没有有效的评分数据avg_scoresum(scores)/len(scores)ifavg_score6:prediction看多elifavg_score5:prediction看空else:prediction中性returnavg_score,predictiondefsave_results_to_file(file_results,avg_score,prediction,output_file分析结果.txt):将分析结果保存到文件try:withopen(output_file,w,encodingutf-8)asf:# 只写入平均评分f.write(f{avg_score:.2f})print(f\n分析结果已保存到:{output_file})returnTrueexceptExceptionase:print(f 保存结果到文件时出错:{e})returnFalse#微17578755056defmain():主函数print(开始分析新闻对股市的影响...)# 新闻目录路径news_directorydatetime.now().strftime(%Y-%m-%d)# 处理新闻目录scores,file_resultsprocess_news_directory(news_directory)ifscores:# 计算平均评分和预测avg_score,predictioncalculate_prediction(scores)print(\n*50)print(分析结果汇总:)print(*50)# 显示每个文件的分析结果forresultinfile_results:print(f\n文件:{result[filename]})ifresult[score]isnotNone:print(f评分:{result[score]})else:print(评分: 无法获取)ifresult[response]:print(f响应:{result[response][:100]}...)print(\n*50)print(f平均评分:{avg_score:.2f})print(f多空预测:{prediction})print(*50)# 详细解释ifprediction看多:print(\n预测说明: 多数新闻对股市有积极影响建议关注投资机会)elifprediction看空:print(\n预测说明: 多数新闻对股市有负面影响建议谨慎操作)else:print(\n预测说明: 新闻影响中性市场可能维持震荡格局)# 保存结果到文件save_results_to_file(file_results,avg_score,prediction)else:print(\n未能获取有效的评分数据)if__name____main__:main()程序分析的最终结果保存到文件【分析结果.txt】中后面我们根据这个文件的评分自动选择合适的交易策略。超越自己是我的每一步我的进步就是你的进步
【小白量化机器人】爬取财经新闻并利用本地大模型评分选择合适交易策略
【小白量化机器人】环境提供了全球市场的实时行情和交易接口。我们利用本地大模型进行分析。一般趋势行情选择趋势策略震荡行情选择震荡策略。我们利用爬虫爬取最近2天的财经新闻。再利用大模型进行评分。如果新闻平稳偏向看多就使用趋势交易策略。一、爬取新闻程序演示代码。importrequestsfrombs4importBeautifulSoupimportosfromdatetimeimportdatetime,timedeltaimportreimportsysimportio# 设置系统编码为UTF-8sys.stdoutio.TextIOWrapper(sys.stdout.buffer,encodingutf-8)sys.stderrio.TextIOWrapper(sys.stderr.buffer,encodingutf-8)# 确保文件路径使用UTF-8编码importlocale locale.setlocale(locale.LC_ALL,zh_CN.UTF-8)defcreate_directory():创建最新日期目录# 获取当前日期作为目录名todaydatetime.now().strftime(%Y-%m-%d)directoryos.path.join(os.getcwd(),today)ifnotos.path.exists(directory):os.makedirs(directory)returndirectorydefclean_filename(filename):清理文件名去除非法字符# 去除非法字符filenamere.sub(r[:/\\|?*],,filename)# 限制文件名长度iflen(filename)100:filenamefilename[:100]returnfilenamedefcrawl_financial_news():爬取财经新闻# 爬取新浪财经新闻urlhttps://finance.sina.com.cn/headers{User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36}try:responserequests.get(url,headersheaders,timeout10)response.raise_for_status()# 处理编码确保正确解析GBK内容ifcharsetinresponse.headers:encodingresponse.headers[charset]else:# 尝试自动检测编码encodingresponse.apparent_encoding# 确保使用正确的编码解析内容response.encodingencoding soupBeautifulSoup(response.text,html.parser)# 创建最新日期目录directorycreate_directory()# 提取新闻链接news_links[]# 查找新闻列表forlinkinsoup.find_all(a,hrefTrue):hreflink[href]# 筛选财经新闻链接if(/finance/inhrefor/money/inhref)andhref.startswith(https://):news_links.append(href)# 去重news_linkslist(set(news_links))print(f找到{len(news_links)}条新闻链接)# 计算2天前的日期two_days_ago(datetime.now()-timedelta(days2)).date()# 爬取每条新闻saved_count0fori,news_urlinenumerate(news_links):# 不限制数量爬取所有链接try:news_responserequests.get(news_url,headersheaders,timeout10)news_response.raise_for_status()# 处理编码确保正确解析GBK内容ifcharsetinnews_response.headers:encodingnews_response.headers[charset]else:# 尝试自动检测编码encodingnews_response.apparent_encoding# 确保使用正确的编码解析内容news_response.encodingencoding news_soupBeautifulSoup(news_response.text,html.parser)# 提取标题titlenews_soup.find(h1)ifnottitle:titlenews_soup.find(h2)iftitle:title_texttitle.get_text(stripTrue)else:title_textf新闻{i}# 提取发布时间publish_timeNone# 尝试从meta标签提取发布时间meta_timenews_soup.find(meta,{name:publishdate})ifmeta_time:publish_timemeta_time.get(content)# 尝试从时间标签提取ifnotpublish_time:time_tagsnews_soup.find_all([time,span],class_[time,pubtime,publish_time])fortagintime_tags:time_texttag.get_text(stripTrue)ifre.search(r\d{4}-\d{2}-\d{2},time_text):publish_timetime_textbreak# 尝试从链接中提取日期ifnotpublish_time:date_matchre.search(r/(\d{4}-\d{2}-\d{2})/,news_url)ifdate_match:publish_timedate_match.group(1)# 检查是否在最近2天内ifpublish_time:try:# 解析发布日期ifisinstance(publish_time,str):# 提取日期部分date_strre.search(r\d{4}-\d{2}-\d{2},publish_time)ifdate_str:publish_datedatetime.strptime(date_str.group(0),%Y-%m-%d).date()# 检查是否在最近2天内ifpublish_datetwo_days_ago:# 提取内容content[]content_divnews_soup.find(div,class_[article,content,main-content])ifcontent_div:paragraphscontent_div.find_all(p)forpinparagraphs:textp.get_text(stripTrue)iftext:content.append(text)ifnotcontent:# 尝试其他方式提取内容forpinnews_soup.find_all(p):textp.get_text(stripTrue)iflen(text)50:# 过滤短文本content.append(text)# 保存到文件iftitle_textandcontent:filenameclean_filename(title_text).txtfile_pathos.path.join(directory,filename)withopen(file_path,w,encodingutf-8)asf:f.write(f标题:{title_text}\n)f.write(f链接:{news_url}\n)f.write(f发布时间:{publish_time}\n)f.write(f爬取时间:{datetime.now().strftime(%Y-%m-%d %H:%M:%S)}\n\n)f.write(内容:\n)f.write(\n.join(content))print(f已保存:{filename}(发布时间:{publish_time}))saved_count1exceptExceptionase:print(f解析日期失败:{publish_time}, 错误:{str(e)})exceptExceptionase:print(f爬取新闻失败:{news_url}, 错误:{str(e)})print(f爬取完成共保存{saved_count}条最近2天内的新闻)exceptExceptionase:print(f爬取失败:{str(e)})if__name____main__:crawl_financial_news()二、本地大模型分析代码。##连接本地deepseek##先安装ollama模块:pip install ollama# ollama run deepseek-coder-v2:latestimportollamafromollamaimportchatimportosimportrefromdatetimeimportdatetime,timedelta# 定义分析规则规则 帮我分析下面新闻对明天股市有什么影响。对股市多空评分为1-106以上看多5以下看空。只要一个评分你打多少分不要思考过程只要评分。 defextract_score_from_response(response):从大模型响应中提取评分数字# 使用正则表达式匹配1-10的数字matchre.search(r\b([1-9]|10)\b,response)ifmatch:returnint(match.group(1))returnNonedefanalyze_news_content(content):分析单篇新闻内容# 组合规则和新闻内容ask规则 contenttry:# 调用大模型进行分析streamchat(modelqwen3:8b,messages[{role:user,content:ask}],streamTrue,)# 收集响应内容responseforchunkinstream:responsechunk[message][content]# 提取评分scoreextract_score_from_response(response)returnscore,response.strip()exceptExceptionase:print(f分析新闻时出错:{e})returnNone,Nonedefprocess_news_directory(directory_path):处理新闻目录中的所有txt文件scores[]file_results[]# 检查目录是否存在ifnotos.path.exists(directory_path):print(f目录不存在:{directory_path})returnNone,None# 获取所有txt文件txt_files[fforfinos.listdir(directory_path)iff.endswith(.txt)]print(f找到{len(txt_files)}个新闻文件)ifnottxt_files:print(目录中没有找到txt文件)returnNone,None# 处理每个文件forfilenameintxt_files:file_pathos.path.join(directory_path,filename)print(f\n正在分析:{filename})try:# 读取文件内容withopen(file_path,r,encodingutf-8)asf:contentf.read()# 分析新闻内容score,responseanalyze_news_content(content)ifscoreisnotNone:scores.append(score)file_results.append({filename:filename,score:score,response:response})print(f评分:{score})else:print(f无法提取评分响应:{response})file_results.append({filename:filename,score:None,response:response})exceptExceptionase:print(f处理文件{filename}时出错:{e})file_results.append({filename:filename,score:None,response:f错误:{e}})returnscores,file_resultsdefcalculate_prediction(scores):计算平均评分并给出多空预测ifnotscores:returnNone,没有有效的评分数据avg_scoresum(scores)/len(scores)ifavg_score6:prediction看多elifavg_score5:prediction看空else:prediction中性returnavg_score,predictiondefsave_results_to_file(file_results,avg_score,prediction,output_file分析结果.txt):将分析结果保存到文件try:withopen(output_file,w,encodingutf-8)asf:# 只写入平均评分f.write(f{avg_score:.2f})print(f\n分析结果已保存到:{output_file})returnTrueexceptExceptionase:print(f 保存结果到文件时出错:{e})returnFalse#微17578755056defmain():主函数print(开始分析新闻对股市的影响...)# 新闻目录路径news_directorydatetime.now().strftime(%Y-%m-%d)# 处理新闻目录scores,file_resultsprocess_news_directory(news_directory)ifscores:# 计算平均评分和预测avg_score,predictioncalculate_prediction(scores)print(\n*50)print(分析结果汇总:)print(*50)# 显示每个文件的分析结果forresultinfile_results:print(f\n文件:{result[filename]})ifresult[score]isnotNone:print(f评分:{result[score]})else:print(评分: 无法获取)ifresult[response]:print(f响应:{result[response][:100]}...)print(\n*50)print(f平均评分:{avg_score:.2f})print(f多空预测:{prediction})print(*50)# 详细解释ifprediction看多:print(\n预测说明: 多数新闻对股市有积极影响建议关注投资机会)elifprediction看空:print(\n预测说明: 多数新闻对股市有负面影响建议谨慎操作)else:print(\n预测说明: 新闻影响中性市场可能维持震荡格局)# 保存结果到文件save_results_to_file(file_results,avg_score,prediction)else:print(\n未能获取有效的评分数据)if__name____main__:main()程序分析的最终结果保存到文件【分析结果.txt】中后面我们根据这个文件的评分自动选择合适的交易策略。超越自己是我的每一步我的进步就是你的进步