DAY 24
0

## Day24 - 如何盤中計算技術指標且發送訊號到line: 不同頻率分K計算

``````kbars = api.kbars(api.Contracts.Stocks['2330'], start='2021-10-04', end='2021-10-06')
df = pd.DataFrame({**kbars})
df.ts = pd.to_datetime(df.ts)
df.set_index('ts',inplace=True) ##將時間設為index
df
``````
ts Volume Low High Close Amount Open
2021-10-04 09:01:00 2094 573 575 575 1.20199e+09 574
2021-10-04 09:02:00 155 574 575 574 8.9051e+07 574
2021-10-04 09:03:00 91 574 575 575 5.2296e+07 575
2021-10-04 09:04:00 157 574 575 575 9.0233e+07 574
2021-10-04 09:05:00 141 574 575 575 8.1055e+07 575

``````from datetime import timedelta
def kbars_set_interval(kbars_df,interval='5Min'):
return_df=pd.DataFrame()
kbars_df.index = kbars_df.index + timedelta(minutes = -1)  #api的一分K是從9:01開始，調成9:00開盤
if  interval=='1Min': #如果輸入的引數是'1Min'則直接回傳
return kbars_df
else:
return_df['Open'] = kbars_df['Open'].resample(interval).first()
return_df['High'] = kbars_df['High'].resample(interval).max()
return_df['Low'] = kbars_df['Low'].resample(interval).min()
return_df['Close'] = kbars_df['Close'].resample(interval).last()
return_df.dropna(inplace=True)
return return_df
``````

``````kbars_set_interval(df,'5Min').head()
``````
ts Open High Low Close
2021-10-04 09:00:00 574 575 573 575
2021-10-04 09:05:00 575 575 572 572
2021-10-04 09:10:00 572 574 572 574
2021-10-04 09:15:00 573 574 573 573
2021-10-04 09:20:00 574 574 572 573

``````kbars_set_interval(df,'30Min').head()
``````
ts Open High Low Close
2021-10-04 08:30:00 574 575 573 575
2021-10-04 09:00:00 574 575 572 572
2021-10-04 09:30:00 573 573 569 571
2021-10-04 10:00:00 570 573 570 572
2021-10-04 10:30:00 573 573 570 570

``````kbars_set_interval(df,'D').head()
``````
ts Open High Low Close
2021-10-04 00:00:00 574 575 569 572
2021-10-05 00:00:00 562 572 560 572
2021-10-06 00:00:00 573 574 565 571