大飞

大飞 关注TA

挑战一切!

大飞

大飞

关注TA

挑战一切!

  • 加入社区3,268天
  • 写了333,609字

该文章投稿至Nemo社区   Python  板块 复制链接


Python选取最优股票

发布于 2018/03/05 14:08 2,101浏览 0回复 7,526

1.从Tushare平台抓取股票信息,主要包括股票code,名称,存储到本地

##获取股票基本列表
def get_stock_list():
    df = ts.get_stock_basics()
    return df

## 保存股票数据到指定路径
def save_csv(df, path):
    today = datetime.date.today().strftime('%Y-%m-%d')
    df.to_csv(path +'stock_list.csv')

2.根据股票code拉取最新N天的交易信息,使用talib算出KDJ、MACD、RSI等信息

## 获取MACD
def get_MADC(df, code):
    close = [float(x) for x in df['close']]
    df['MACD'], df['MACDsignal'], df['MACDhist'] = ta.MACD(np.array(close), fastperiod=6, slowperiod=12, signalperiod=9)
    print('---------------------MACD---------------------')
    print(df.tail(1))
    ## 存储数据到文档
    sava_data(df, code, 'MACD')
    sava_data(df, code, 'MACDsignal')
    sava_data(df, code, 'MACDhist')
    print('---------------------MACD---------------------')


##获取jdk
def get_KDJ(df, code):
    # 参数9,3,3
    df['slowk'], df['slowd'] = ta.STOCH(np.array(df['high']), np.array(df['low']), np.array(df['close']),
                                        fastk_period=9,
                                        slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
    print('---------------------KDJ---------------------')
    print(df.tail(1))
    sava_data(df, code, 'slowk')
    sava_data(df, code, 'slowd')
    print('---------------------KDJ---------------------')


def get_RSI(df, code):
    close = [float(x) for x in df['close']]
    # 参数14,5
    df['slowreal'] = ta.RSI(np.array(close), timeperiod=14)
    df['fastreal'] = ta.RSI(np.array(close), timeperiod=5)
    print('---------------------RSI---------------------')
    print(df.tail(1))
    sava_data(df, code, 'slowreal')
    sava_data(df, code, 'fastreal')
    print('---------------------RSI---------------------')


3.写出计算符合相关指标的筛选方法



## 换手率
def judge_turnover(item):
    return item.turnover > 0 and item.turnover > 3 and item.turnover < 10


### 判断MACD 当为正的时候 良好 不是必须
def judge_MACD(item):
    return item.MACD > -3 and item.MACD != 0


### 判断jdk 当k线和d线小于三十 并且k先>d线作为买入依据
def judge_JDK(item):
    if item.slowk == 0 or item.slowd == 0:
        return False
    return item.slowk < 30 and item.slowd < 30 and item.slowk > item.slowd


### 判断RSI
def judge_RSI(item):
    if item.slowreal == 0 or item.fastreal == 0:
        return False
    if item.fastreal > 50 and item.fastreal < 80 and item.slowreal > 50 and item.slowreal < 80:
        return True
    if item.slowreal < 20 or item.fastreal < 20:
        # if item.fastreal > item.slowreal:
        return True
    if item.fastreal < 30 and item.fastreal > item.slowreal:
        return True

    return False

运行结果如下:

潜力股 code:603398 name:邦宝益智
潜力股 code:600804 name:鹏博士
潜力股 code:600512 name:腾达建设
潜力股 code:600241 name:时代万恒
潜力股 code:300325 name:德威新材
潜力股 code:300312 name:邦讯技术
潜力股 code:300064 name:豫金刚石
潜力股 code:300110 name:华仁药业
潜力股 code:300566 name:激智科技

Process finished with exit code 0

全部代码 筛选方法可以根据自己需要修改

import tushare as ts
import pandas as pd
import numpy as np
import talib as ta
import datetime
import time
import sys

code = 600519


## 获取历史数据
def get_k_data(code):
    now_time = datetime.datetime.now()
    # 两个月前
    one_m_time = now_time + datetime.timedelta(days=-60)
    df = ts.get_k_data(str(code), start=one_m_time.strftime('%Y-%m-%d'))
    return df


## 获取历史数据
def get_history_data(code):
    now_time = datetime.datetime.now()
    # 两个月前
    one_m_time = now_time + datetime.timedelta(days=-4)
    df = ts.get_hist_data(str(code), start=one_m_time.strftime('%Y-%m-%d'))
    return df


## 存储数据到文档
def sava_data(df, code, name):
    index = p_pf[(p_pf.code == code)].index.tolist()[0]
    p_pf.loc[index, name] = df.tail(1)[name].values



## 存储数据到文档
def sava_data2(df, code, name):
    index = p_pf[(p_pf.code == code)].index.tolist()[0]
    p_pf.loc[index, name] = df.head(1)[name].values
    print(p_pf.loc[index])


## 获取MACD
def get_MADC(df, code):
    close = [float(x) for x in df['close']]
    df['MACD'], df['MACDsignal'], df['MACDhist'] = ta.MACD(np.array(close), fastperiod=6, slowperiod=12, signalperiod=9)
    print('---------------------MACD---------------------')
    print(df.tail(1))
    ## 存储数据到文档
    sava_data(df, code, 'MACD')
    sava_data(df, code, 'MACDsignal')
    sava_data(df, code, 'MACDhist')
    print('---------------------MACD---------------------')


##获取jdk
def get_KDJ(df, code):
    # 参数9,3,3
    df['slowk'], df['slowd'] = ta.STOCH(np.array(df['high']), np.array(df['low']), np.array(df['close']),
                                        fastk_period=9,
                                        slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0)
    print('---------------------KDJ---------------------')
    print(df.tail(1))
    sava_data(df, code, 'slowk')
    sava_data(df, code, 'slowd')
    print('---------------------KDJ---------------------')


def get_RSI(df, code):
    close = [float(x) for x in df['close']]
    # 参数14,5
    df['slowreal'] = ta.RSI(np.array(close), timeperiod=14)
    df['fastreal'] = ta.RSI(np.array(close), timeperiod=5)
    print('---------------------RSI---------------------')
    print(df.tail(1))
    sava_data(df, code, 'slowreal')
    sava_data(df, code, 'fastreal')
    print('---------------------RSI---------------------')


file_name = '/Users/lyf/test/stock_list.csv'
p_pf = pd.read_csv('/Users/lyf/test/stock_list.csv')


####获取最新数据
def main():
    p_pf['turnover'] = 0.0
    p_pf['MACD'] = 0.0
    p_pf['MACDsignal'] = 0.0
    p_pf['MACDhist'] = 0.0
    p_pf['slowk'] = 0.0
    p_pf['slowd'] = 0.0
    p_pf['fastreal'] = 0.0
    p_pf['slowreal'] = 0.0

    for code in p_pf.code:
        df = get_k_data(code)

        try:
            get_MADC(df, code)
            get_KDJ(df, code)
            get_RSI(df, code)
            time.sleep(0.5)
        except:
            pass

        try:
            h_df = get_history_data(code)
            sava_data2(h_df, code, 'turnover')
        except:
            pass

    p_pf.to_csv(file_name)

## 抓取相关信息绘制macd kdj 等 这是第一步
#main()



## 换手率
def judge_turnover(item):
    return item.turnover > 0 and item.turnover > 3 and item.turnover < 10


### 判断MACD 当为正的时候 良好 不是必须
def judge_MACD(item):
    return item.MACD > -3 and item.MACD != 0


### 判断jdk 当k线和d线小于三十 并且k先>d线作为买入依据
def judge_JDK(item):
    if item.slowk == 0 or item.slowd == 0:
        return False
    return item.slowk < 30 and item.slowd < 30 and item.slowk > item.slowd


### 判断RSI
def judge_RSI(item):
    if item.slowreal == 0 or item.fastreal == 0:
        return False
    if item.fastreal > 50 and item.fastreal < 80 and item.slowreal > 50 and item.slowreal < 80:
        return True
    if item.slowreal < 20 or item.fastreal < 20:
        # if item.fastreal > item.slowreal:
        return True
    if item.fastreal < 30 and item.fastreal > item.slowreal:
        return True

    return False


### 抓取数据后执行选取潜力股
def judge_best():
    for index in p_pf.index:
        if judge_MACD(p_pf.loc[index]) and judge_JDK(p_pf.loc[index]) and judge_RSI(p_pf.loc[index]):
            print('潜力股 code:%s name:%s' % (p_pf.loc[index].code, p_pf.loc[index, 'name']))
        # if judge_JDK(p_pf.loc[index]):
        #     print('code:%s name:%s jdk:%s'%(p_pf.loc[index].code, p_pf.loc[index, 'name'],p_pf.loc[index].slowk))

judge_best()

201709191320064570

本文标签
 {{tag}}
点了个评