首页 > 解决方案 > 如何通过匹配我创建的 max_min 变量中的索引来使用字典创建数据框

问题描述

如何使用字典转换为该字典值来自索引的变量 max_min 的数据帧,我希望它可以匹配 max_min 的索引并创建我需要的数据帧。

下面的示例代码来自这个网站:

https://medium.com/automation-generation/algorithmically-detecting-and-trading-technical-chart-patterns-with-python-c577b3a396ed

示例图像

def max_min(smoothing=5, window_range=10,parse_dates=[0]):
smooth_prices = df['Price'].rolling(window=smoothing).mean().dropna()
local_max = argrelextrema(smooth_prices.values, np.greater)[0]
local_min = argrelextrema(smooth_prices.values, np.less)[0]
price_local_max_dt = []
for i in local_max:
    if (i>window_range) and (i<len(df)-window_range):
        price_local_max_dt.append(df.iloc[i-window_range:i+window_range]['Price'].idxmax())
price_local_min_dt = []
for i in local_min:
    if (i>window_range) and (i<len(df)-window_range):
        price_local_min_dt.append(df.iloc[i-window_range:i+window_range]['Price'].idxmin())  
maxima = pd.DataFrame(df.loc[price_local_max_dt])
minima = pd.DataFrame(df.loc[price_local_min_dt])
max_min = pd.concat([maxima, minima]).sort_index()
return max_min

max_min = max_min()

def find_patterns1(max_min):
patterns1 = defaultdict(list)

# Window range is 5 units
for i in range(5, len(max_min)):  
    window = max_min.iloc[i-5:i]

    a = window.iloc[0]
    b = window.iloc[1]
    c = window.iloc[2]
    d = window.iloc[3]
    e = window.iloc[4]           
    # IHS
    if c.Price<d.Price and a.Price<c.Price and a.Price<b.Price and a.Price<e.Price and b.Price<e.Price and abs(d.Price-e.Price)<=np.mean([d.Price,e.Price])*0.03:
           patterns1['IHS'].append((window.index[0], window.index[-1]))
return patterns1
patterns1 = find_patterns1(max_min)

标签: pythondataframe

解决方案


在此处阅读文档。取决于您希望如何构建 DataFrame,您可以使用以下orient参数:

df = pd.DataFrame.from_dict(patterns, orient = 'index')

将为您提供:字典中所有键的第一列和值的第二列。

还有一个columns参数,您可以通过将它们放在列表中来为预期的列命名。

希望这可以帮助 :))。欢迎来到社区。


推荐阅读