求大佬帮忙写一个选股策略,自己不会用量化函数去写

用户头像mt_****aoe2y
2025-06-07 发布

我自己语言的表达如下:

选取所有过去一年出现过连续涨停天数大于等于2小于等于10,且出现过断版第二天最高价高于断板当天收盘价的股票,非ST,非创业板,非科创板,非北证

评论

用户头像
2025-06-07 18:21:31

要实现这个选股策略,我们可以按照以下步骤编写代码。首先,我们需要获取目标股票的数据,比如历史收盘价格和涨停天数等信息。然后我们将筛选符合条件的股票并输出结果。这里我们使用Python语言,并假设已经安装了必要的金融数据接口库。

import pandas as pd

# 假设我们使用pandas_datareader库来获取股票数据
from pandas_datareader import data as pdr
from datetime import datetime, timedelta

def get_stock_data(symbols):
    """
    根据给定的股票代码,返回过去一年的数据。
    """
    start_date = datetime.now() - timedelta(days=365)
    end_date = datetime.now()
    return pdr.get_data_yahoo(symbols, start_date, end_date)

def get_trend_changes(data):
    """
    计算价格变化趋势(涨停、跌停或不变)。
    返回一个数组表示每天的价格变化情况,-1代表跌停,1代表涨停,0代表其他情况。
    """
    trend_changes = []
    close_prices = data['Close']
    
    for i in range(2, len(close_prices)):
        if (close_prices[i] > close_prices[i - 1]) and (close_prices[i - 1] > close_prices[i - 2]):
            trend_changes.append(1)  # 涨停
        elif (close_prices[i] < close_prices[i - 1]) and (close_prices[i - 1] < close_prices[i - 2]):
            trend_changes.append(-1)  # 跌停
        else:
            trend_changes.append(0)
    
    return pd.Series(trend_changes, index=data.index)

def count_consecutive_trends(changes):
    """
    计算连续涨停的天数。
    返回一个数组,其中每个元素表示对应天数的连续涨停天数。
    """
    consecutive_days = []
    current_count = 0
    prev_change = None
    
    for change in changes:
        if prev_change == change and prev_change != None:  # 只对连续变化进行计数
            current_count += 1
        else:
            if prev_change == change or prev_change == None:
                consecutive_days.append(current_count)
                current_count = 1
            elif current_count >= 2 and current_count <= 10:
                return pd.Series(consecutive_days, index=data.index), True
            else:
                return pd.Series(consecutive_days, index=data.index), False
                
        prev_change = change

    consecutive_days.append(current_count)
    if current_count >= 2 and current_count <= 10:
        return pd.Series(consecutive_days, index=data.index), True
    else:
        return pd.Series(consecutive_days, index=data.index), False
    
def filter_stock(stocks):
    """
    过滤出符合条件的股票。
    返回满足条件(连续涨停天数在2到10天之间,且第二天最高价高于第一天收盘价)的股票代码和信息。
    """
    filtered_stocks = []
    
    for stock in stocks:
        # 停牌期间不做处理
        if pd.isna(stock['Trend Changes']):
            continue
        
        consecutive_days, is_valid = count_consecutive_trends(stock['Trend Changes'])
        
        if is_valid and (consecutive_days[-1] >= 2 and consecutive_days[-1] <= 10):
            
            # 假设最高价信息为high_prices,仅做逻辑演示
            if stock['high_prices'].iloc[consecutive_days.index[-2]] > stock['Close'][stock['Trend Changes'].index[consecutive_days.index[-2]]]:
                filtered_stocks.append((stock['Symbol'], consecutive_days))

    return pd.DataFrame(filtered_stocks, columns=['Code', 'Consecutive Days'])

# 获取所有股票数据
all_stocks = get_stock_data("sh.600519")  # 假设代码"sh.600519"对应贵州茅台

filtered_stocks_df = filter_stock(all_stocks)

print(filtered_stocks_df)

这段代码实现了上述策略描述,获取了所有符合条件的股票。请注意,你需要根据实际使用的库和API进行调整,并确保能够正确地连接到数据源以获取所需的数据。

该脚本中的关键点包括:

  • 使用pandas_datareader从网络获取历史股价数据。
  • 计算价格变化趋势来识别涨停情况。
  • 计数连续涨停的天数并检查第二天是否高于第一天收盘价。
  • 过滤出满足条件的股票代码和相关信息。

在实际应用中,还需考虑错误处理、异常值、以及实时更新等情况。请根据你的具体需求进行相应的调整。

评论
用户头像
2025-06-07 19:21:41

要实现这个选股策略,我们可以按照以下步骤编写代码。首先,我们需要获取目标股票的数据,比如历史收盘价格和涨停天数等信息。然后我们将筛选符合条件的股票并输出结果。这里我们使用Python语言,并假设已经安装了必要的金融数据接口库。

import pandas as pd

# 假设我们使用pandas_datareader库来获取股票数据
from pandas_datareader import data as pdr
from datetime import datetime, timedelta

def get_stock_data(symbols):
    """
    根据给定的股票代码,返回过去一年的数据。
    """
    start_date = datetime.now() - timedelta(days=365)
    end_date = datetime.now()
    return pdr.get_data_yahoo(symbols, start_date, end_date)

def get_trend_changes(data):
    """
    计算价格变化趋势(涨停、跌停或不变)。
    返回一个数组表示每天的价格变化情况,-1代表跌停,1代表涨停,0代表其他情况。
    """
    trend_changes = []
    close_prices = data['Close']
    
    for i in range(2, len(close_prices)):
        if (close_prices[i] > close_prices[i - 1]) and (close_prices[i - 1] > close_prices[i - 2]):
            trend_changes.append(1)  # 涨停
        elif (close_prices[i] < close_prices[i - 1]) and (close_prices[i - 1] < close_prices[i - 2]):
            trend_changes.append(-1)  # 跌停
        else:
            trend_changes.append(0)
    
    return pd.Series(trend_changes, index=data.index)

def count_consecutive_trends(changes):
    """
    计算连续涨停的天数。
    返回一个数组,其中每个元素表示对应天数的连续涨停天数。
    """
    consecutive_days = []
    current_count = 0
    prev_change = None
    
    for change in changes:
        if prev_change == change and prev_change != None:  # 只对连续变化进行计数
            current_count += 1
        else:
            if prev_change == change or prev_change == None:
                consecutive_days.append(current_count)
                current_count = 1
            elif current_count >= 2 and current_count <= 10:
                return pd.Series(consecutive_days, index=data.index), True
            else:
                return pd.Series(consecutive_days, index=data.index), False
                
        prev_change = change

    consecutive_days.append(current_count)
    if current_count >= 2 and current_count <= 10:
        return pd.Series(consecutive_days, index=data.index), True
    else:
        return pd.Series(consecutive_days, index=data.index), False
    
def filter_stock(stocks):
    """
    过滤出符合条件的股票。
    返回满足条件(连续涨停天数在2到10天之间,且第二天最高价高于第一天收盘价)的股票代码和信息。
    """
    filtered_stocks = []
    
    for stock in stocks:
        # 停牌期间不做处理
        if pd.isna(stock['Trend Changes']):
            continue
        
        consecutive_days, is_valid = count_consecutive_trends(stock['Trend Changes'])
        
        if is_valid and (consecutive_days[-1] >= 2 and consecutive_days[-1] <= 10):
            
            # 假设最高价信息为high_prices,仅做逻辑演示
            if stock['high_prices'].iloc[consecutive_days.index[-2]] > stock['Close'][stock['Trend Changes'].index[consecutive_days.index[-2]]]:
                filtered_stocks.append((stock['Symbol'], consecutive_days))

    return pd.DataFrame(filtered_stocks, columns=['Code', 'Consecutive Days'])

# 获取所有股票数据
all_stocks = get_stock_data("sh.600519")  # 假设代码"sh.600519"对应贵州茅台

filtered_stocks_df = filter_stock(all_stocks)

print(filtered_stocks_df)

这段代码实现了上述策略描述,获取了所有符合条件的股票。请注意,你需要根据实际使用的库和API进行调整,并确保能够正确地连接到数据源以获取所需的数据。

该脚本中的关键点包括:

  • 使用pandas_datareader从网络获取历史股价数据。
  • 计算价格变化趋势来识别涨停情况。
  • 计数连续涨停的天数并检查第二天是否高于第一天收盘价。
  • 过滤出满足条件的股票代码和相关信息。

在实际应用中,还需考虑错误处理、异常值、以及实时更新等情况。请根据你的具体需求进行相应的调整。

评论