zoukankan      html  css  js  c++  java
  • 股票分析

    #  tushare 财经数据接口包

    使用tushare包获取某股票的历史行情数据。
    import pandas as pd
    from pandas import Series,DataFrame
    import numpy as np
    import tushare as ts 
    df = ts.get_k_data(code='600519',start='2000-01-01') #获取k线数据
    df.head()  #显示前5行
    df.to_csv('./maotai.csv') #数据写入 csv
    #将date列的数据转成时间序列,然后将该列作为整个数据源的行索引   某一列作为行索引
    data = pd.read_csv('./maotai.csv',index_col='date',parse_dates=['date']) #读数据 出来df 
    data.drop(labels='Unnamed: 0',axis=1,inplace=True)#标签  0行 1列
    data.head(5) #前5行
    data.index[0] #Timestamp('2001-08-27 00:00:00')

    #输出该股票所有收盘比开盘上涨3%以上的日期
    # (收盘-开盘)/开盘 > 0.03
    indexs = (data['close']-data['open'])/data['open'] > 0.03
    data.loc[indexs].index #拿到具体时间

    #输出该股票所有开盘比前日收盘跌幅超过2%的日期。
    indexs = (data['open'] - data['close'].shift(1))/data['close'].shift(1) < -0.02
    data.loc[indexs].index

    #假如我从2010年1月1日开始,每月第一个交易日买入1手股票,每年最后一个交易日卖出所有股票,到今天为止,我的收益如何?

    price_last = data['open'][-1] #最后一个交易日的开盘价
    df = data['2010':'2019'] #剔除首尾无用的数据
    #Pandas提供了resample函数用便捷的方式对时间序列进行重采样,根据时间粒度的变大或者变小分为降采样和升采样:
    df_monthly = df.resample("M").first()
    df_yearly = df.resample("A").last()[:-1] #去除最后一年  Y
    cost_money = 0 #起始资金
    hold = 0 #每年持有的股票
    for year in range(2010, 2020):
      cost_money -= df_monthly.loc[str(year)]['open'].sum()*100
      hold += len(df_monthly[str(year)]['open']) * 100
      if year != 2019:
        cost_money += df_yearly.loc[str(year)]['open'][0] * hold
        hold = 0 #每年持有的股票
    cost_money += hold * price_last

    print(cost_money)

  • 相关阅读:
    二叉树相关题目
    二叉树的遍历
    mysql获取某个表中除了某个字段名外的所有字段名
    设计模式之原型模式
    设计模式之工厂方法模式
    设计模式之代理模式
    设计模式之装饰模式
    设计模式之策略模式
    设计模式之简单工厂模式
    Redis的使用及参考代码
  • 原文地址:https://www.cnblogs.com/zhangchen-sx/p/11116596.html
Copyright © 2011-2022 走看看