Whoever holds their breath the longest is the winner

R&Python



Candle-stick chart shows

Plotlyというインタラクティブなローソク足チャートを生成できるpackageがあったのでそれを使用。期間を選択してズームすることも可能。



Gather data

こちらが実際のデータの一部

DATE time
2024/2/22 0:01:03
2024/2/22 0:01:13
2024/2/22 0:01:40
2024/2/23 0:01:47
2024/2/23 0:01:42
2024/2/23 0:01:38
2024/2/23 0:01:18
2024/2/23 0:01:47
2024/2/23 0:01:35
2024/2/23 0:02:08
2024/2/24 0:01:18
2024/2/24 0:01:27
2024/2/24 0:01:55
2024/2/24 0:01:18

左が測定した日。右が息を止めていた時間。 これを使って、ローソク足チャートに必要な四本値を算出していく。



Create 4value

必要なパッケージやライブラリーを用意

import plotly.graph_objects as go
import pandas as pd

Pythonで四本値を作成

# read an excel file
df = pd.read_excel("breathe.xlsx")

# create columns which needed candle-stick
open=df.groupby("DATE").head(1)
high=df.groupby("DATE").max()
low=df.groupby("DATE").min()
close=df.groupby("DATE").tail(1)
volume=df["DATE"].value_counts()


Display 4value

output

表やチャートはRで出力。

Rのほうがplotlyを使用しやすいため。

ti <- tribble(
  ~date,~open,~high,~low,~close,~volume,
  "2024-02-22",63.0,100.0,63.0,100.0,7,
  "2024-02-23",107.0,128.0,78.0,128.0,4,
  "2024-02-24",78.0,115.0,78.0,78.0,3,  
)
ti
# A tibble: 3 × 6
  date        open  high   low close volume
  <chr>      <dbl> <dbl> <dbl> <dbl>  <dbl>
1 2024-02-22    63   100    63   100      7
2 2024-02-23   107   128    78   128      4
3 2024-02-24    78   115    78    78      3
ti = pd.DataFrame({
    "date": open["DATE"].values,
    "open": open["seconds"].values,
    "high": high["seconds"].values,
    "low": low["seconds"].values,
    "close": close["seconds"].values,
    "volume": volume.values
})

# volumeの表示なし 


Candle stick chart

fig <- ti %>% plot_ly(x = ~date, type="candlestick",
                      open = ~open, close = ~close,
                      high = ~high, low = ~low, name = "me") 
fig <- fig %>% layout(title = "Hold my breath",
                     xaxis=list(rangeslider=list(visible=F)))

# plot volume bar chart
fig2 <- ti 
fig2 <- fig2 %>% plot_ly(x=~date, y=~volume, type='bar', name = "Volume") 
fig2 <- fig2 %>% layout(yaxis = list(title = "Volume"))

# subplot with shared x axis
fig <- subplot(fig, fig2, heights = c(0.7,0.2), nrows=2,
               shareX = TRUE, titleY = TRUE)
fig <- fig %>% layout(xaxis = list(rangeselector = list(visible=F)),
                      legend = list(orientation = 'h', x = 0.5, y = 1,
                                    xanchor = 'center', yref = 'paper',
                                    font = list(size = 10),
                                    bgcolor = 'transparent'))
fig
Figure 1: breath holding time (sec)
# plotly の Figure インスタンスを作成
fig = go.Figure(data=[go.Candlestick(x=candle_df["Date"], open=candle_df["Open"], high=candle_df["High"], low=candle_df["Low"], close=candle_df["Close"])])
fig.update_layout(xaxis_rangeslider_visible=False)
# プロットを表示
fig.show()