import matplotlib.pyplot as plt
import pandas as pd
from mpl_finance import candlestick2_ochl
import mplfinance as mpf
from unittest import TestCaseclass TestPandasKline(TestCase):#读取股票数据,画出K线图def testKLineChart(self):file_name = "./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()#K线图带交易量def testKLineByVolume(self):file_name = "./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)# K线图带交易量及均线def testKLineByMA(self):file_name = "./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)
-
该视频主要讲述了股票时间序列的实战应用及pandas库中相关函数的使用。首先介绍了时间序列在金融领域的重要性,包括趋势分析和相关性分析。接着,详细阐述了pandas中处理时间序列的常用函数,如datetime、loc等,以及如何使用它们进行数据筛选和分组。最后,通过实战案例,展示了如何使用pandas读取股票数据,并对数据进行基本的描述性统计分析,包括非空值、数据类型以及每列的基本统计量等。
-
分段总结
折叠
00:01股票时间序列分析介绍
1.股票时间序列是金融领域最重要的数据类型,包括股价、汇率等。 2.时间序列数据按年月季度周日甚至小时分钟tick(毫秒级)进行记录。 3.时间序列分析主要包括趋势分析和相关性分析。
02:19pandas在时间序列分析中的常见函数
1.datetime是pandas中表示时间的数据结构,方便进行各种时间运算。 2.loc函数用于筛选时间或列数据。 3.groupby函数用于按时间或股票ID对数据进行分组。
03:48股票时间序列实战环节
1.读取数据函数df.read_csv()等,与单派使用方式相似。 2.describe函数用于描述dataframe的基本信息,如count、mean、std、min、max等。 3.处理时间列,将其转换为datetime类型,并进行年、月、日的提取。 4.计算最低收盘价、最小值索引等。
11:27每月平均收盘价与开盘价计算
1.先计算月份,然后按月分组计算平均开盘价和收盘价。 2.使用groupby和mean函数进行计算。
14:34涨跌幅计算
1.涨跌幅为今日收盘价减去昨日收盘价。 2.使用diff函数计算涨跌幅。
17:46本章小结
1.股票时间序列是金融数据最重要的数据结构。 2.时间序列分析包括趋势分析和相关性分析。 3.pandas在时间序列分析中的常见函数包括datetime、loc和groupby。
-
-
k线图的正常实现
-
代码
-
import matplotlib.pyplot as plt import pandas as pd from mpl_finance import candlestick2_ochl import mplfinance as mpf from unittest import TestCase #pip install mplfinance -i https://pypi.tuna.tsinghua.edu.cn/simpleclass TestPandasKline(TestCase):#读取股票数据,画出K线图def testKLineChart(self):file_name = "./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()#K线图带交易量def testKLineByVolume(self):file_name = "./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)# K线图带交易量及均线def testKLineByMA(self):file_name = "./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)
这段代码是一个用于 绘制股票K线图(蜡烛图) 的Python单元测试类,使用了
matplotlib
、pandas
和mplfinance
库。它包含三个测试方法,分别演示了不同的K线图绘制方式: -
import matplotlib.pyplot as plt # 基础绘图库 import pandas as pd # 数据处理 from mpl_finance import candlestick2_ochl # 旧版K线图绘制(已弃用,推荐用mplfinance) import mplfinance as mpf # 新版专业金融图表库 from unittest import TestCase # 单元测试
-
mplfinance
是专门用于金融数据可视化的库,比mpl_finance
更强大且维护更好。 -
pandas
用于读取和处理股票数据(CSV格式)。 -
unittest
用于组织测试用例。
2. 三个测试方法
(1) testKLineChart
:基础K线图
python
复制
下载
def testKLineChart(self):df = pd.read_csv("./demo.csv") # 读取数据df.columns = ["stock_id", "date", "close", "open", "high", "low", "volume"] # 设置列名# 使用 matplotlib + mpl_finance 绘制K线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) # X轴标签旋转30度axes.grid(True) # 显示网格plt.title("K-Line") # 标题plt.show() # 显示图表
功能:
-
使用
matplotlib
+mpl_finance
(旧版)绘制 基本K线图。 -
红色表示上涨(收盘价 > 开盘价),绿色表示下跌(收盘价 < 开盘价)。
-
显示网格、调整X轴标签角度。
(2) testKLineByVolume
:K线图 + 成交量
python
复制
下载
def testKLineByVolume(self):df = pd.read_csv("./demo.csv")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') # 设置日期为索引(mplfinance要求)# 自定义颜色风格my_color = mpf.make_marketcolors(up='red', # 上涨颜色down='green', # 下跌颜色wick='i', # 影线颜色(i表示继承up/down颜色)volume={'up': 'red', 'down': 'green'}, # 成交量颜色ohlc='i' # K线主体颜色继承)my_style = mpf.make_mpf_style(marketcolors=my_color, # 应用颜色gridaxis='both', # 显示网格gridstyle='-.', # 网格线样式(虚线)rc={'font.family': 'STSong'} # 字体(宋体))# 使用 mplfinance 绘制K线 + 成交量mpf.plot(df,type='candle', # 蜡烛图类型title='K-LineByVolume', # 标题ylabel='price', # Y轴标签style=my_style, # 应用自定义样式show_nontrading=False, # 不显示非交易日volume=True, # 显示成交量ylabel_lower='volume', # 成交量Y轴标签datetime_format='%Y-%m-%d', # 日期格式xrotation=45, # X轴标签旋转45度linecolor='#00ff00', # 辅助线颜色tight_layout=False # 不自动调整布局)
功能:
-
使用
mplfinance
绘制 K线图 + 成交量。 -
自定义颜色(红涨绿跌)。
-
成交量柱状图也用红/绿区分涨跌。
-
支持中文显示(
STSong
宋体)。
(3) testKLineByMA
:K线图 + 成交量 + 均线
python
复制
下载
def testKLineByMA(self):# 数据预处理(同上)df = pd.read_csv("./demo.csv")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'})# 使用 mplfinance 绘制K线 + 成交量 + 均线mpf.plot(df,type='candle',mav=[5, 10], # 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)
功能:
-
在
testKLineByVolume
基础上,增加 移动平均线(MA)。 -
mav=[5, 10]
表示计算 5日均线 和 10日均线,并叠加在K线图上