Techy Guy
Techy Guy

Reputation: 33

How to Convert Tick by Tick Data to OHLC Candlestick Data with Python?

How can I resample my tick by tick data to get Candlesticks OHLC data.

Here's how my data looks with pandas DataFrame.

    Timestamp       Price
0  1626459705  278.989978
1  1626459695  279.437975
2  1626459486  279.866868
3  1626459317  280.225627
4  1626459149  280.469473
5  1626458918  280.845010
6  1626458886  282.348605
7  1626458866  281.976074
8  1626458380  280.420801
9  1626458056  280.838577

How can I get OHLC Candlestick data for say 1 minute by resampling with pandas?

Upvotes: 3

Views: 5737

Answers (2)

rhug123
rhug123

Reputation: 8768

Below is another solution:

df = df.assign(Timestamp = pd.to_datetime(df['Timestamp'],unit='s')).set_index('Timestamp')
df.resample('10min')['Price'].ohlc()

Upvotes: 7

Ben.T
Ben.T

Reputation: 29635

one way is to convert the Timestamp column to a datetime column with to_datetime and set_index it. then select the Price column, resample with the frequency you want and agg with the different first-max-min-last.

nb_minutes = 10 # change to 1 for your real case
res = (
    df.set_index(pd.to_datetime(df['Timestamp'], unit='s'))
      .sort_index() # to ensure the chronological order
      ['Price'].resample(f'{nb_minutes}T') 
      .agg( {'open':'first', 'high':max, 'low':min, 'close':'last'} )
      .unstack(level=0) # to make it a dataframe
)
print(res)
                           open        high         low       close
Timestamp                                                          
2021-07-16 17:50:00  280.838577  280.838577  280.420801  280.420801
2021-07-16 18:00:00  281.976074  282.348605  280.845010  280.845010
2021-07-16 18:10:00  280.469473  280.469473  279.866868  279.866868
2021-07-16 18:20:00  279.437975  279.437975  278.989978  278.989978

Upvotes: 3

Related Questions