当前位置: 首页 > news >正文

Pandas应用-股票分析实战

股票时间序列

时间序列:
金融领域最重要的数据类型之一
股价、汇率为常见的时间序列数据
趋势分析:
主要分析时间序列在某一方向上持续运动
在量化交易领域,我们通过统计手段对投资品的收益率进行时间序列建模,以此来预测未来的收益率并产生交易信
序列相关性:
金融时间序列的一个最重要特征是序列相关性
以投资品的收益率序列为例,我们会经常观察到一段时间内的收益率之间存在正相关或者负相关

Pandas时间序列函数

datetime:
时间序列最常用的数据类型
方便进行各种时间类型运算
loc:
Pandas中对DateFrame进行筛选的函数,相当于SQL中的where
groupby:
Pandas中对数据分组函数,相当于SQL中的GroupBy
读取数据

    def testReadFile(self):file_name = r"D:\lhjytest\demo.csv"df = pd.read_csv(file_name)print(df.info())print("-------------")print(df.describe())

image.png
image.png
时间处理

    def testTime(self):file_name = r"D:\lhjytest\demo.csv"df = pd.read_csv(file_name)df.columns = ["stock_id","date","close","open","high","low","volume"]df["date"] = pd.to_datetime(df["date"])df["year"] = df["date"].dt.yeardf["month"] = df["date"].dt.monthprint(df)

image.png
最低收盘价

    def testCloseMin(self):file_name = r"D:\lhjytest\demo.csv"df = pd.read_csv(file_name)df.columns = ["stock_id","date","close","open","high","low","volume"]print("""close min : {}""".format(df["close"].min()))print("""close min index : {}""".format(df["close"].idxmin()))print("""close min frame : {}""".format(df.loc[df["close"].idxmin()]))

image.png
每月平均收盘价与开盘价

    def testMean(self):file_name = r"D:\lhjytest\demo.csv"df = pd.read_csv(file_name)df.columns = ["stock_id","date","close","open","high","low","volume"]df["date"] = pd.to_datetime(df["date"])df["month"] = df["date"].dt.monthprint("""month close mean : {}""".format(df.groupby("month")["close"].mean()))print("""month open mean : {}""".format(df.groupby("month")["open"].mean()))

image.png
算涨跌幅

# 涨跌幅今日收盘价减去昨日收盘价def testRipples_ratio(self):file_name = r"D:\lhjytest\demo.csv"df = pd.read_csv(file_name)df.columns = ["stock_id","date","close","open","high","low","volume"]df["date"] = pd.to_datetime(df["date"])df["rise"] = df["close"].diff()df["rise_ratio"] = df["rise"] / df.shift(-1)["close"]print(df)

image.png
计算股价移动平均

def testMA(self):file_name = r"D:\lhjytest\demo.csv"df = pd.read_csv(file_name)df.columns = ["stock_id","date","close","open","high","low","volume"]df['ma_5'] = df.close.rolling(window=5).mean()df['ma_10'] = df.close.rolling(window=10).mean()df = df.fillna(0)print(df)

image.png

K线图

K线图
K线图蕴含大量信息,能显示股价的强弱、多空双方的力量对比,是技术分析最常见的工具

K线图实现

Matplotlib
一个Python 的 2D绘图库,窗以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形
matplotlib finance
python 中可以用来画出蜡烛图线图的分析工具,目前已经从 matplotlib 中独立出来
读取股票数据,画出K线图

    def testKLineChart(self):file_name = r"D:\lhjytest\demo.csv"df = pd.read_csv(file_name)df.columns = ["stock_id","date","close","open","high","low","volume"]fig = plt.figure()axes = fig.add_subplot(111)candlestick2_ochl(ax=axes,opens=df["open"].values,closes=df["close"].values,highs=df["high"].values,lows=df["low"].values,width=0.75,colorup='red',colordown='green')plt.xticks(range(len(df.index.values)),df.index.values,rotation=30)axes.grid(True)plt.title("K-Line")plt.show()

image.png

 def testKLineByVolume(self):file_name = r"D:\lhjytest\demo.csv"df = pd.read_csv(file_name)df.columns = ["stock_id","date","close","open","high","low","volume"]df = df[["date","close","open","high","low","volume"]]df["date"] = pd.to_datetime(df["date"])df = df.set_index('date')my_color = mpf.make_marketcolors(up = 'red',down = 'green',wick = 'i',volume = {'up':'red','down':'green'},ohlc = 'i')my_style  = mpf.make_mpf_style(marketcolors = my_color,gridaxis = 'both',gridstyle = '-.',rc = {'font.family':'STSong'})mpf.plot(df,type = 'candle',title = 'K-LineByVolume',ylabel = 'price',style = my_style,show_nontrading = False,volume = True,ylabel_lower = 'volume',datetime_format = '%Y-%m-%d',xrotation = 45,linecolor = '#00ff00',tight_layout = False)

image.png
K线图带交易量及均线

   def testKLineByMA(self):file_name = r"D:\lhjytest\demo.csv"df = pd.read_csv(file_name)df.columns = ["stock_id","date","close","open","high","low","volume"]df = df[["date","close","open","high","low","volume"]]df["date"] = pd.to_datetime(df["date"])df = df.set_index('date')my_color = mpf.make_marketcolors(up = 'red',down = 'green',wick = 'i',volume = {'up':'red','down':'green'},ohlc = 'i')my_style  = mpf.make_mpf_style(marketcolors = my_color,gridaxis = 'both',gridstyle = '-.',rc = {'font.family':'STSong'})mpf.plot(df,type = 'candle',mav = [5,10],title='K-LineByVolume',ylabel='price',style=my_style,show_nontrading=False,volume=True,ylabel_lower='volume',datetime_format='%Y-%m-%d',xrotation=45,linecolor='#00ff00',tight_layout=False)

image.png

http://www.lryc.cn/news/288230.html

相关文章:

  • Database history tablesupgraded
  • Dify学习笔记-应用发布(四)
  • 优化用户体验测试应用领域:提升产品质量与用户满意度
  • 顶顶通呼叫中心中间件机器人压力测试配置(mod_cti基于FreeSWITCH)
  • Debezium发布历史87
  • Leetcode131.分割回文串-Palindrome Patitioning-Python-回溯法
  • Java面试——基础篇
  • C++——结构体
  • C++技术要点总结, 面试必备, 收藏起来慢慢看
  • VR数字展厅,平面静态跨越到3D立体化时代
  • Linux中LVM实验
  • 外包干了一个月,技术退步明显。。。。。
  • gitlab.rb主要配置
  • 网络协议基础
  • Mac使用adb调试安卓手机
  • Web 开发 1: Flask 框架介绍和使用
  • Centos7.6之禅道开源版17.6.1安装记录
  • 有趣的代码(简单)
  • Java和Redis实现一个简单的热搜功能
  • 超越传统,想修哪里就修哪里,SUPIR如何通过文本提示实现智能图像修复
  • 《如何画好架构图》学习笔记
  • redis整合
  • 开循环低温样品架节约液氦操作技巧
  • 年薪30W+,待遇翻倍,我的经历值得每个测试人借鉴
  • DEB方式安装elastic search7以及使用
  • [Tomcat] [最全] 目录和文件详解
  • 微信小程序元素/文字在横向和纵向实现居中对齐、两端对齐、左右对齐、上下对齐
  • 兼容树莓派扩展模块,专注工业产品开发的瑞米派强势来袭
  • 云原生 - 微信小程序 COS 对象存储图片缓存强制更新解决方案
  • 设计公司设计ppt的优势—南京梵构广告