簡體   English   中英

使用 datetimeindex 時間序列數據源創建 dataframe 用於股票分析

[英]Create a dataframe for stock analysis using a datetimeindex timeseries data source

我有一個數據源,它給了我以下 dataframe, pricehistory

+---------------------+------------+------------+------------+------------+----------+------+
|         time        |   close    |    high    |    low     |    open    |  volume  | red  |
+---------------------+------------+------------+------------+------------+----------+------+
|                     |            |            |            |            |          |      |
| 2020-01-02 10:14:00 | 321.336177 | 321.505186 | 321.286468 | 321.505186 | 311601.0 | True |
| 2020-01-02 11:16:00 | 321.430623 | 321.465419 | 321.395827 | 321.465419 | 42678.0  | True |
| 2020-01-02 11:17:00 | 321.425652 | 321.445536 | 321.375944 | 321.440565 | 39827.0  | True |
| 2020-01-02 11:33:00 | 321.137343 | 321.261614 | 321.137343 | 321.261614 | 102805.0 | True |
| 2020-01-02 12:11:00 | 321.256643 | 321.266585 | 321.241731 | 321.266585 | 25629.0  | True |
| 2020-01-02 12:12:00 | 321.246701 | 321.266585 | 321.231789 | 321.266585 | 40869.0  | True |
| 2020-01-02 13:26:00 | 321.226818 | 321.266585 | 321.226818 | 321.261614 | 44011.0  | True |
| 2020-01-03 10:18:00 | 320.839091 | 320.958392 | 320.828155 | 320.958392 | 103351.0 | True |
| 2020-01-03 10:49:00 | 320.988217 | 321.077692 | 320.988217 | 321.057809 | 84492.0  | True |
| etc...              | etc...     | etc...     | etc...     | etc...     | etc...   | etc. |
+---------------------+------------+------------+------------+------------+----------+------+

pricehistory.dtypes的 Output :

close     float64
high      float64
low       float64
open      float64
volume    float64
red          bool
dtype: object

pricehistory.index.dtype的 Output : dtype dtype('<M8[ns]')

注意:這個 dataframe 很大,每行是 1 分鍾的數據,跨越數月,所以有很多時間框架需要迭代。

我有一些我想使用的特定標准將成為新 dataframe 中的列。

  1. 整個dataframe每天的高價和時間(分鍾)
  2. 第一次出現的 4 個下降趨勢分鍾open < close在一天中及其各自的時間

到目前為止,我不確定如何從pricehistory中提取時間(datetimeindex 值)和高價格。

對於上面的(1),我使用pd.DataFrame(pricehistory.high.groupby(pd.Grouper(freq='D')).max())這給了我:

+------------+------------+
|    time    |    high    |
+------------+------------+
|            |            |
| 2020-01-02 | 322.956677 |
| 2020-01-03 | 321.753729 |
| 2020-01-04 | NaN        |
| 2020-01-05 | NaN        |
| 2020-01-06 | 321.843204 |
| etc...     | etc...     |
+------------+------------+

但這不起作用,因為它只給我一天而不是分鍾,並且使用min作為Grouper freq 不起作用,因為它只是每個 min 的最大值,即high

期望的結果(注:包括分鍾):

+---------------------+------------+
|    time             |    high    |
+---------------------+------------+
|                     |            |
| 2020-01-02 9:31:00  | 322.956677 |
| 2020-01-03 10:13:11 | 321.753729 |
| 2020-01-04 15:33:12 | 320.991231 |
| 2020-01-06 12:01:23 | 321.843204 |
| etc...              | etc...     |
+---------------------+------------+

對於上面的(2),我使用以下內容:

pricehistory['red'] = pricehistory['close'].lt(pricehistory['open'])

pricehistory中創建一個新列,顯示連續 4 個紅色分鍾。

然后,使用new_pricehistory = pricehistory.loc[pricehistory[::-1].rolling(4)['red'].sum().eq(4)] ,這給出了一個新的 dataframe 僅包含 4 個紅色分鍾的行連續發生,最好我只希望第一次出現,而不是全部。

當前 output:

+---------------------+------------+------------+------------+------------+--------+------+
|        time         |   close    |    high    |    low     |    open    | volume | red  |
+---------------------+------------+------------+------------+------------+--------+------+
|                     |            |            |            |            |        |      |
| 2020-01-02 10:14:00 | 321.336177 | 321.505186 | 321.286468 | 321.505186 | 311601 | TRUE |
| 2020-01-03 10:18:00 | 320.839091 | 320.958392 | 320.828155 | 320.958392 | 103351 | TRUE |
| 2020-01-06 10:49:00 | 320.520956 | 320.570665 | 320.501073 | 320.550781 |  71901 | TRUE |
+---------------------+------------+------------+------------+------------+--------+------+

謝謝!

鑒於您沒有提供數據,我創建了一些虛擬數據。 根據 SO 政策,您應該針對每個問題提出不同的問題。 現在我回答第一個。

生成數據

import pandas as pd
import numpy as np

times = pd.date_range(start="2020-06-01", end="2020-06-10", freq="1T")
df = pd.DataFrame({"time":times,
                  "high":np.random.randn(len(times))})

問題 1

在這里,我只查找每天出現最大值的索引並相應地過濾df

idx = df.groupby(df["time"].dt.date)["high"].idxmax().values

df[df.index.isin(idx)]

更新:如果您有時間作為 df 中的索引,則解決方案將是

df = df.set_index("time")

idx = df.groupby(pd.Grouper(freq='D'))["high"].idxmax().values
df[df.index.isin(idx)]

問題2

import pandas as pd
import numpy as np

# generate data
times = pd.date_range(start="2020-06-01", end="2020-06-10", freq="1T")
df = pd.DataFrame({"time":times,
                   "open":np.random.randn(len(times))})

df["open"] = np.where(df["open"]<0, -1 * df["open"], df["open"])
df["close"] = df["open"] + 0.01 *np.random.randn(len(times))
df = df.set_index("time")
df["red"] = df['close'].lt(df['open'])

# this function return the first time 
# when there are 4 consecutive red

def get_first(ts):
    idx = ts.loc[ts[::-1].rolling(4)['red'].sum().ge(4)].index
    if idx.empty:
        return pd.NaT
    else:
        return idx[0]

# get first time within group and drop nan
grp = df.groupby(pd.Grouper(freq='D'))\
        .apply(get_first).dropna()



df[df.index.isin(grp.values)]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM