使用Tushare统计收盘价中位数

使用Tushare统计收盘价中位数

获取交易数据

tushare只能获取一只股票的一段时间成交数据或某一天全部股票成交数据,我选择获取一只股票的历史数据然后存起来再计算

#coding:utf8
import tushare as ts

tushare_token = 'xxxxxxxxxxxxxxxxxxxx'
ts.set_token(tushare_token)
pro = ts.pro_api()

def getStockDaily(ts_code, start_date, end_date):
    '''
    input:
        ts_code str N   股票代码(二选一)
        trade_date  str N   交易日期(二选一)
        start_date  str N   开始日期(YYYYMMDD)
        end_date    str N   结束日期(YYYYMMDD)

    output:
        ts_code str 股票代码
        trade_date  str 交易日期
        open    float   开盘价
        high    float   最高价
        low float   最低价
        close   float   收盘价
        pre_close   float   昨收价
        change  float   涨跌额
        pct_change  float   涨跌幅
        vol float   成交量 (手)
        amount  float   成交额 (千元)
    '''
    return pro.daily(ts_code=ts_code, start_date=start_date, end_date=end_date, fields="ts_code,trade_date,close,vol,amount") #get one stock daily history

保存数据

数据保存在mysql中

class TradeDaily(Base):
    __tablename__ = 'trade_daily'
    DATE_DELIMITER = ","

    id = Column(Integer, Sequence('tradeDaily_id_seq'), primary_key=True)
    ts_code = Column(String(16), nullable=False)
    date = Column(Date, nullable=False)
    closes = Column(String(256))
    vols = Column(String(360))
    amounts = Column(String(400))

    __table_args__ = (
        UniqueConstraint('ts_code', 'date', name='ts_code_date_idx'),
    )
    
class DailyStats(Base):
    __tablename__ = 'daily_stats'

    date = Column(Date, primary_key=True)
    median_close = Column(Float(precision=4), nullable=False)

计算和保存收盘价中位数

def calc_median_close():
    with session_scope() as session:
        ds = session.query(DailyStats).order_by(DailyStats.date.desc()).first()
        if ds is not None:
            from_date = ds.date
        else:
            from_date = datetime(2000, 1, 1).date()
        today = datetime.now().date()
        for year in range(from_date.year, today.year + 1):
            m_f = 1
            m_t = 13
            if from_date.year == today.year:
                m_f = from_date.month
                m_to = today.month + 1
            for m in range(m_f, m_t):
                d = datetime(year, m, 1).date()
                if d > today:
                    print("calc median done")
                    return
                tradeCal = session.query(TradeCal).filter_by(date=d).first()
                if tradeCal is None:
                    print("trade cal %s not found" % d)
                    continue
                month_closes = []
                for tradeDaily in session.query(TradeDaily).filter_by(date=d):
                    prices = [ float(x) if x != '-' else np.nan for x in tradeDaily.closes.split(',') ]
                    month_closes.append(prices)
                if len(month_closes) < 1:
                    print('trade daily %s not found' % d)
                    continue
                df  = pd.DataFrame(np.array(month_closes), columns=tradeCal.getCals())
                median = df.median()
                for col in tradeCal.getCals():
                    close_d = datetime(year, m, int(col)).date()
                    if np.isnan(median[col]) or median[col] < 0.01:
                        print('median %s is unexists' % close_d)
                        continue
                    ds = session.query(DailyStats).filter_by(date=close_d).first()
                    if ds is None:
                        ds = DailyStats(date=close_d)
                    ds.median_close = median[col]
                    session.add(ds)
                session.commit()

画图

最后用matplot画图

def plot_median_close(start_date=None):
    import matplotlib.pyplot as plt
    lst = []
    with session_scope() as session:
        if start_date is not None:
            dss = session.query(DailyStats).filter(DailyStats.date > start_date).order_by(DailyStats.date).all()
        else:
            dss = session.query(DailyStats).order_by(DailyStats.date).all()
        for ds in dss:
            lst.append([ds.date, ds.median_close])
        df = pd.DataFrame(np.array(lst), columns=['date', 'close'])

    df.plot(x = 'date', y = 'close', kind="line", title="median close", grid=True)
    plt.show()

效果展示
使用Tushare统计收盘价中位数_第1张图片
觉得有意思的可以通过下面网址注册一个玩玩
https://tushare.pro/register?reg=136270

ps. 上面策略只是我观察市场的众多工具中的一种,不能作为投资唯一参考。

你可能感兴趣的:(杂七杂八)