用python画股票行情图

import datetime
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.patches as patches
from CAL.PyCAL import *

quotes:行情-Dateframe类型,sec:标题

def plot_k(quotes, sec):
color_balck= ‘#0F0F0F’
color_green= ‘#00FFFF’
color_yellow = ‘#EE9A00’
color_purple = ‘#9900CC’
linewidth = 2

fig = plt.figure(figsize=(11,6))
fig.set_tight_layout(True)

ax1 = fig.add_axes([0, 1, 1, 1])#K线
ax1.set_title(u'K线图', fontproperties=font, fontsize=20)
ax2 = fig.add_axes([0, 0.35, 1, 0.5], axis_bgcolor='w')#成交量
ax1.set_axisbelow(True)
ax2.set_axisbelow(True)

ax1.grid(True, axis='y')
ax2.grid(True, axis='y')
ax1.set_xlim(-1, len(quotes)+1)
ax2.set_xlim(-1, len(quotes)+1)

for i in range(len(quotes)):
    close_price = quotes.ix[i, 'closePrice']
    open_price = quotes.ix[i, 'openPrice']
    high_price = quotes.ix[i, 'highestPrice']
    low_price = quotes.ix[i, 'lowestPrice']
    vol = quotes.ix[i, 'turnoverVol']
    trade_date = quotes.ix[i, 'tradeDate']
    if close_price > open_price:#画阳线
        ax1.add_patch(patches.Rectangle((i-0.2, open_price), 0.4, close_price-open_price, fill=False, color='r'))
        ax1.plot([i, i], [low_price, open_price], 'r')
        ax1.plot([i, i], [close_price, high_price], 'r')
        ax2.add_patch(patches.Rectangle((i-0.2, 0), 0.4, vol, fill=False, color='r'))
    else:#画阴线
        ax1.add_patch(patches.Rectangle((i-0.2, open_price), 0.4, close_price-open_price, color='g'))
        ax1.plot([i, i], [low_price, high_price], color='g')
        ax2.add_patch(patches.Rectangle((i-0.2, 0), 0.4, vol, color='g'))
ax1.set_title(sec, fontproperties=font, fontsize=15, loc='left', color='r')
ax2.set_title(u'成交量', fontproperties=font, fontsize=15, loc='left', color='r')
#设置标签
ax1.set_xticks(range(0,len(quotes), 15))#位置
ax2.set_xticks(range(0,len(quotes), 15)) 
s1 = ax1.set_xticklabels([mdates.num2date(quotes.ix[index, 'tradeDate']).strftime('%Y-%m-%d') for index in ax1.get_xticks()])#标签内容
s1 = ax2.set_xticklabels([mdates.num2date(quotes.ix[index, 'tradeDate']).strftime('%Y-%m-%d') for index in ax2.get_xticks()])
#移动平均线     
ma5 = pd.rolling_mean(np.array(quotes['closePrice'], dtype=float), window=5, min_periods=0)
ma10 = pd.rolling_mean(np.array(quotes['closePrice'], dtype=float), window=10, min_periods=0)
ma20 = pd.rolling_mean(np.array(quotes['closePrice'], dtype=float), window=20, min_periods=0)

ax1.plot(ma5, color='b', linewidth=__linewidth__)
ax1.plot(ma10, color=__color_yellow__, linewidth=__linewidth__)
ax1.plot(ma20, color=__color_purple__, linewidth=__linewidth__)
#图例
ax1.annotate('MA5-', xy=(len(quotes)-30, ax1.get_yticks()[-1]), color='b', fontsize=15)
ax1.annotate('MA10-', xy=(len(quotes)-19, ax1.get_yticks()[-1]), color=__color_yellow__, fontsize=15)
ax1.annotate('MA20-', xy=(len(quotes)-8, ax1.get_yticks()[-1]), color=__color_purple__, fontsize=15)
#交易量均线
vol5 = pd.rolling_mean(np.array(quotes['turnoverVol'], dtype=float), window=5, min_periods=0)
vol10 = pd.rolling_mean(np.array(quotes['turnoverVol'], dtype=float), window=10, min_periods=0)
ax2.plot(vol5, color='b', linewidth=__linewidth__)
ax2.plot(vol10, color=__color_yellow__, linewidth=__linewidth__)

return fig

quotes = DataAPI.MktMFutdGet(mainCon=u”1”, contractObject=u”cf”, startDate=u”20151101”,
endDate=u”20160501”,field=[u”closePrice”, u”openPrice”, u”highestPrice”,
u”lowestPrice”, u”tradeDate”,u”turnoverVol”], pandas=”1”)
quotes[‘tradeDate’] = quotes[‘tradeDate’].map(lambda x:mdates.date2num(datetime.datetime.strptime(x,’%Y-%m-%d’)))
fig2 = plot_k(quotes, u’棉花主力[CFM]’)

好的,我可以帮你用Python出两支股票的时间序列。首先,我们需要用Python获取股票数据,这里我选择使用tushare库来获取数据。请确保你已经安装了tushare库。 以下是代码实现: ```python import tushare as ts import matplotlib.pyplot as plt # 设置tushare pro的token ts.set_token('你的token') # 初始化pro接口 pro = ts.pro_api() # 获取股票代码为'000001.SZ'的日线行情数据 df1 = pro.daily(ts_code='000001.SZ', start_date='20210101', end_date='20211231') # 获取股票代码为'600036.SH'的日线行情数据 df2 = pro.daily(ts_code='600036.SH', start_date='20210101', end_date='20211231') # 将交易日期转化为时间戳 df1['trade_date'] = pd.to_datetime(df1['trade_date']) df2['trade_date'] = pd.to_datetime(df2['trade_date']) # 绘制股票1的收盘价时间序列 plt.plot(df1['trade_date'], df1['close'], label='000001.SZ') # 绘制股票2的收盘价时间序列 plt.plot(df2['trade_date'], df2['close'], label='600036.SH') # 设置例 plt.legend() # 设置横坐标名称 plt.xlabel('Date') # 设置纵坐标名称 plt.ylabel('Close price') # 显示像 plt.show() # 绘制股票1的成交金额时间序列 plt.plot(df1['trade_date'], df1['amount'], label='000001.SZ') # 绘制股票2的成交金额时间序列 plt.plot(df2['trade_date'], df2['amount'], label='600036.SH') # 设置例 plt.legend() # 设置横坐标名称 plt.xlabel('Date') # 设置纵坐标名称 plt.ylabel('Amount') # 显示像 plt.show() ``` 这段代码会获取股票代码为'000001.SZ'和'600036.SH'的日线行情数据,并绘制出这两只股票的收盘价和成交金额的时间序列。你可以根据自己的需要修改代码中的股票代码和时间范围。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值