Sébastien De Greef commited on
Commit
1e1b538
1 Parent(s): 491a75a

Add scripts to create indicators and sequences, and download crypto data

Browse files
Files changed (4) hide show
  1. create_indicators.py +40 -0
  2. create_sequences.py +64 -0
  3. crypto_data.py +69 -0
  4. download.py +12 -9
create_indicators.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+
4
+ df = pd.read_csv('candles.csv')
5
+
6
+
7
+ from talib import RSI, BBANDS, MACD, ATR, EMA, SMA
8
+
9
+
10
+ # group by market
11
+ grouped = df.groupby('market')
12
+
13
+ # for each market calculate the indicators and add them to the dataframe
14
+ for market, group in grouped:
15
+ # calculate the indicators
16
+ print('Calculating indicators for', market)
17
+ df.loc[group.index,'rsi'] = RSI(group['close'], timeperiod=14)
18
+
19
+ upper, middle, lower = BBANDS(group['close'], timeperiod=20)
20
+ df.loc[group.index,'bb_upper'] = upper
21
+ df.loc[group.index,'bb_middle'] = middle
22
+ df.loc[group.index,'bb_lower'] = lower
23
+
24
+ macd, macdsignal, macdhist = MACD(group['close'], fastperiod=12, slowperiod=26, signalperiod=9)
25
+ df.loc[group.index,'macd'] = macd
26
+ df.loc[group.index,'macdsignal'] = macdsignal
27
+ df.loc[group.index,'macdhist'] = macdhist
28
+
29
+ df.loc[group.index,'atr'] = ATR(group['high'], group['low'], group['close'], timeperiod=14)
30
+
31
+ df.loc[group.index,'ema'] = EMA(group['close'], timeperiod=30)
32
+ df.loc[group.index,'sma'] = SMA(group['close'], timeperiod=30)
33
+
34
+ # drop the rows with NaN values
35
+ df = df.dropna()
36
+
37
+
38
+ # save the dataframe to a new file
39
+ print(df.tail())
40
+ df.to_csv('indicators.csv', index=False)
create_sequences.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ # data = data[['market', 'time', 'open', 'high', 'low', 'close', 'volume']]
4
+ # transform this dataset so to 'market', 'start', 'column', 'value1', 'value2', 'value3', 'value(n)'
5
+ import pandas as pd
6
+ import numpy as np
7
+ from tqdm import tqdm
8
+
9
+ columns = ['open','close','volume', 'rsi', 'sma']
10
+ window_size = 10
11
+
12
+ def create_sequences(df, columns=columns, window_size=window_size):
13
+ # group by market
14
+ grouped = df.groupby('market')
15
+
16
+ # create a list of dataframes
17
+ dfs = []
18
+
19
+ for name, group in tqdm(grouped):
20
+ # create a new dataframe
21
+ new_df = pd.DataFrame()
22
+ new_df['market'] = name
23
+ # create a list of lists
24
+ sequences = []
25
+ # only include the close column
26
+ # iterate over the rows of the dataframe
27
+ for i in range(len(group) - window_size):
28
+ # create a sequence
29
+ sequence = group.iloc[i:i+window_size][columns].values
30
+ # transpose the sequence so that it is a column
31
+ sequence = sequence.T
32
+
33
+ # create a dataframe from the sequence
34
+ sequence = pd.DataFrame(sequence)
35
+
36
+ # add the market, time, column_name to the sequence
37
+ sequence['market'] = name
38
+ sequence['time'] = group.iloc[i+window_size]['time']
39
+ sequence['column'] = columns
40
+
41
+ # set market, time as the first columns and index
42
+ sequence = sequence.set_index(['market', 'time', 'column'])
43
+
44
+ # add the sequence to the list of sequences
45
+ sequences.append(sequence)
46
+ if len(sequences) == 0:
47
+ continue
48
+ # create a dataframe from the list of lists
49
+ new_df = pd.concat(sequences)
50
+ # add the dataframe to the list of dataframes
51
+ dfs.append(new_df)
52
+
53
+ # concatenate the list of dataframes
54
+ final_df = pd.concat(dfs)
55
+
56
+ return final_df
57
+
58
+ df = pd.read_csv('indicators.csv')
59
+
60
+ # create the sequences
61
+ sequences = create_sequences(df, columns=columns, window_size=15)
62
+
63
+ # save the sequences to a new file
64
+ sequences.to_csv('sequences.csv')
crypto_data.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datasets import DatasetBuilder, DownloadManager, DatasetInfo, BuilderConfig, SplitGenerator, Split, Features, Value
2
+ import pandas as pd
3
+
4
+ # Define custom configurations for the dataset
5
+ class CryptoDataConfig(BuilderConfig):
6
+ def __init__(self, features, **kwargs):
7
+ super().__init__(**kwargs)
8
+ self.features = features
9
+
10
+ class CryptoDataDataset(DatasetBuilder):
11
+ # Define different dataset configurations here
12
+ BUILDER_CONFIGS = [
13
+ CryptoDataConfig(
14
+ name="candles",
15
+ description="This configuration includes open, high, low, close, and volume.",
16
+ features=Features({
17
+ "date": Value("string"),
18
+ "open": Value("float"),
19
+ "high": Value("float"),
20
+ "low": Value("float"),
21
+ "close": Value("float"),
22
+ "volume": Value("float")
23
+ })
24
+ ),
25
+ CryptoDataConfig(
26
+ name="indicators",
27
+ description="This configuration extends basic CryptoDatas with RSI, SMA, and EMA indicators.",
28
+ features=Features({
29
+ "date": Value("string"),
30
+ "open": Value("float"),
31
+ "high": Value("float"),
32
+ "low": Value("float"),
33
+ "close": Value("float"),
34
+ "volume": Value("float"),
35
+ "rsi": Value("float"),
36
+ "sma": Value("float"),
37
+ "ema": Value("float")
38
+ })
39
+ ),
40
+ ]
41
+
42
+ def _info(self):
43
+ return DatasetInfo(
44
+ description=f"CryptoData dataset for {self.config.name}",
45
+ features=self.config.features,
46
+ supervised_keys=None,
47
+ homepage="https://hub.huggingface.co/datasets/sebdg/crypto_data",
48
+ citation="No citation for this dataset."
49
+ )
50
+
51
+ def _split_generators(self, dl_manager: DownloadManager):
52
+ # Here, you can define how to split your dataset (e.g., into training, validation, test)
53
+ # This example assumes a single CSV file without predefined splits.
54
+ # You can modify this method if you have different needs.
55
+ return [
56
+ SplitGenerator(
57
+ name=Split.TRAIN,
58
+ gen_kwargs={"filepath": "indicators.csv"},
59
+ ),
60
+ ]
61
+
62
+ def _generate_examples(self, filepath):
63
+ # Here, we open the provided CSV file and yield each row as a single example.
64
+ with open(filepath, encoding="utf-8") as csv_file:
65
+ data = pd.read_csv(csv_file)
66
+ for id, row in data.iterrows():
67
+ # Select features based on the dataset configuration
68
+ features = {feature: row[feature] for feature in self.config.features if feature in row}
69
+ yield id, features
download.py CHANGED
@@ -41,15 +41,18 @@ print('Data downloaded and saved to assets.csv and markets.csv')
41
  if not os.path.exists('candles'):
42
  os.makedirs('candles')
43
 
44
- # for market in markets['market']:
45
- # print('Downloading', market)
46
- # url = f'https://api.bitvavo.com/v2/{market}/candles?interval=1d&limit=1440'
47
- # response = requests.get(url)
48
- # data = response.json()
49
- # #print(data)
50
- # data = pd.DataFrame(data, columns=['time', 'open', 'high', 'low', 'close', 'volume'])
51
- # data.to_csv(f'candles/{market}.csv', index=False)
52
- # time.sleep(0.5)
 
 
 
53
 
54
  # print('Ticker data downloaded')
55
 
 
41
  if not os.path.exists('candles'):
42
  os.makedirs('candles')
43
 
44
+ for market in markets['market']:
45
+ print('Downloading', market)
46
+ url = f'https://api.bitvavo.com/v2/{market}/candles?interval=1d&limit=1440'
47
+ response = requests.get(url)
48
+ data = response.json()
49
+ #print(data)
50
+ data = pd.DataFrame(data, columns=['time', 'open', 'high', 'low', 'close', 'volume'])
51
+ data['market'] = market
52
+ # set market as the first column
53
+ data = data[['market', 'time', 'open', 'high', 'low', 'close', 'volume']]
54
+ data.to_csv(f'candles/{market}.csv', index=False)
55
+ time.sleep(0.5)
56
 
57
  # print('Ticker data downloaded')
58