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線圖上