tushare+mplfinance+pandas 画K线图

人狠话不多,直接上代码+注释

tips:

要用mplfinance库,不能用 mpl_finance(会提示使用新版)

tushare官网Tushare数据

# 导入tushare
import tushare as ts
import mplfinance as mpf  # 导入mpf
import pandas as pd
from pandas import Timestamp   # 时间戳转化函数

offset = 1  # 偏置
limit = 1000  # 限制


def get_info(code, ex_name, start_date, end_date, api_string):
    pro = ts.pro_api(api_string)
    code = str(code)
    ts_code = code + "." + ex_name
    '''tushare 给的接口代码'''
    df = pro.daily(**{
        "ts_code": ts_code,
        "trade_date": "",
        "start_date": start_date,
        "end_date": end_date,
        "offset": offset,
        "limit": limit
    }, fields=[
        "ts_code",
        "trade_date",
        "open",
        "high",
        "low",
        "close",
        "pre_close",
        "change",
        "pct_chg",
        "vol",
        "amount"
    ])
    return df


def drawk(data, style='up-r-down-g', ):  # 画k线图 data 为从tushare得到的pandasframe对象
    pd1 = pd.DataFrame(data)
    pd1 = pd1.iloc[::-1]   # 翻转date顺序,使时间顺序排列
    # print(pd1['Date'])
    # print(pd1)
    pd1['Date'] = pd1['trade_date'].apply(Timestamp)  # 把tradedate转化为时间戳
    pd1.set_index('Date', inplace=True)  # 把时间戳设置为索引
    # pd1=pd.DatetimeIndex()  #另一种转换时间戳索引的方法,不会用
    # print(pd1)

    # k线图绘制
    if style == 'up-r-down-g':  # 设置红涨还是绿涨
        my_color = mpf.make_marketcolors(up='r', down='g')
    else:
        my_color = mpf.make_marketcolors(up='g', down='r')
    my_style = mpf.make_mpf_style(marketcolors=my_color)  # 设置k线 style
    mpf.plot(pd1, type="candle", style=my_style, mav=(5, 10))  # 画图


if __name__ == '__main__':
    api_key = 'your key'
    pd_data = get_info('000001', 'SZ', '20221001', '20230220', api_key)  # 股票代码 、股票类别简称(SZ为深证) 、开始日期、终止日期
    drawk(pd_data)  # 画图
    pass

1. 这里需要把api_key换成自己的api

2. 修改get_info的传入值    【 股票代码(只含数字) 、股票类别简称(SZ为深圳,以此类推) 、开始日期(不加横杠)、终止日期】

3. 运行程序

4. 浅浅地点个赞qwq

猜你喜欢

转载自blog.csdn.net/weixin_52013159/article/details/129827447