首页 > 解决方案 > 如何过滤掉连续3天涨价的股票

问题描述

我想通过连续3天涨价的属性,在一堆公司中筛选出表现强劲的股票。到目前为止的代码下方。感谢您的帮助。

换句话说,我想获得过去 3 天价格持续上涨的股票名称列表。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pandas_datareader as web

tick = ['AMZN', 'AAPL', 'NFLX', 'XOM', 'T']
df = web.get_data_yahoo(tick,
                           start = '2020-01-01',
                           end = '2020-12-16')['Adj Close']

标签: pythonpandasdata-analysis

解决方案


尝试这个:

def compute_consecutive_increase(tick_data, window_size=3):
    
    # Make sure the time series is sorted by date (assuming that date is the index)
    tick_data = tick_data.sort_index()
    
    # Put side-by-side the comparison of current day ('t-0') with previous day ('t-1'),
    # then 't-1' with 't-2', etc.
    shifted_comparison = pd.concat({f't-{i}': tick_data.shift(i) > tick_data.shift(i+1) \
        for i in range(window_size)}, axis=1)
    
    # Collapse horizontally (by date) and return True for each row where all values
    # are True, i.e. all last 'window_size' days have positive increases
    return shifted_comparison.all(axis=1)

df.transform(compute_consecutive_increase)

# To collapse for each tick, if there's at least one 3-day sequence with increases
df.transform(compute_consecutive_increase).any()


推荐阅读