---
# System prepended metadata

title: Python - K-Line and Bollinger Bands
tags: [Technical Analysis, Python]

---

# Python - K-Line and Bollinger Bands

## Time Interval Conversion of K-Line
* Take 1 min K in TXF for example(conversion to 30 min K)

1. import packages and read csv
```python
import pandas as pd
prices = pd.read_csv("TXF-220101-174827.csv")
```

2. **Set index to datetime format in order to use library**
```python
prices = prices.set_index(pd.DatetimeIndex(prices["Date"]))
```

3. extract hours and filter out data in pre-market
- TXF trading time: 08:45 am to 13:45 pm
```python
hours = prices.index.hour
prices = prices.iloc[(hours < 14) & (hours > 7)]
```

4. **Use resample() and agg() method from pandas**
```python
prices_30 = prices.resample(
    "30min", 
    closed="right", 
    label="right",
    offset="15min"
).agg({
    "Open": "first",
    "High": "max",
    "Low": "min",
    "Close": "last",
    "Volume": "sum"
}).dropna()
```
Result:
![](https://hackmd.io/_uploads/H1np6HNyT.png)

## Bollinger Bands
1. import ta packages

- Documentations: https://technical-analysis-library-in-python.readthedocs.io/en/latest/index.html
```python
import ta
```

2. read in 30min K data(created by steps written above)
```python
df = pd.read_csv("output/TXF_30.csv")
```

3. create bollinger bands object
```python
# Create BollingerBands Object
# window -> n period of MA
# window_dec -> nth variance(Band Width)
bb = ta.volatility.BollingerBands(close=df["Close"], window=20, window_dev=2)
```

4. use method inside the object
```python
df["BB_h"] = bb.bollinger_hband()
df["BB_m"] = bb.bollinger_mavg()
df["BB_l"] = bb.bollinger_lband()
```
![](https://hackmd.io/_uploads/rks3RSEJp.png)


By using TA library, it is rather easy to generate all indicators often used in technical analysis by implementing the following code.
```python
all_features = ta.add_all_ta_features(
    df, 
    open="Open", 
    high="High",
    low="Low",
    close="Close",
    volume="Volume",
    fillna=True
)
```
