%%capture
!pip install talib%%capture
!pip install ccxt%%capture
!pip install ta%%capture
!pip install mplfinance%%capture
pip install fancyimputeimport ccxt
import csv
from datetime import datetime
# Initialize the exchange object
exchange = ccxt.kraken()
# Specify the trading pair and the timeframe
symbol = 'BTC/USD'
timeframe = '1d'
# Fetch historical data
ohlcv = exchange.fetch_ohlcv(symbol, timeframe)
# Write the data to a CSV file
with open('crypto_data.csv', mode='w') as file:
writer = csv.writer(file)
writer.writerow(["date","open","high","low","close","volume"])
for i in range(len(ohlcv)):
timestamp = datetime.fromtimestamp(ohlcv[i][0]/1000).strftime("%Y-%m-%d %H:%M:%S")
writer.writerow([timestamp,ohlcv[i][1],ohlcv[i][2],ohlcv[i][3],ohlcv[i][4],ohlcv[i][5]])
print("Data saved to crypto_data.csv")
import pandas as pd
import numpy as np
import talib
import ta
# Load historical data
data = pd.read_csv("crypto_data.csv")
# Calculate moving averages
data["50_MA"] = data["close"].rolling(window=50).mean()
data["200_MA"] = data["close"].rolling(window=200).mean()
# Calculate relative strength index
data["RSI"] = talib.RSI(data["close"], timeperiod=14)
# Calculate Bollinger Bands
data["upper_band"], data["middle_band"], data["lower_band"] = talib.BBANDS(data["close"])
# Calculate Kaufman Adaptive Moving Average
data["kama"] = talib.KAMA(data["close"], timeperiod=30)
# Calculate Fibonacci retracement
#data["fib_retracement"] = ta.fibonacci_retracement(data["high"], data["low"])
# Print the dataframe
print(data)
import matplotlib.pyplot as plt
# Plot the close prices
plt.plot(data["close"])
# Plot the 50-day moving average
plt.plot(data["50_MA"])
# Plot the 200-day moving average
plt.plot(data["200_MA"])
# Add a legend to the chart
plt.legend(["Close","50-day MA","200-day MA"])
# Show the chart
plt.show()
import matplotlib.pyplot as plt
# Plot the close prices
plt.plot(data["close"])
# Plot the 50-day moving average
plt.plot(data["50_MA"])
# Plot the 200-day moving average
plt.plot(data["200_MA"])
# Plot the relative strength index
plt.plot(data["RSI"])
# Plot the Bollinger Bands
plt.plot(data["upper_band"])
plt.plot(data["middle_band"])
plt.plot(data["lower_band"])
# Plot the Kaufman Adaptive Moving Average
plt.plot(data["kama"])
# Plot the Fibonacci retracement
#plt.plot(data["fib_retracement"])
# Add a legend to the chart
plt.legend(["Close","50-day MA","200-day MA", "RSI", "Upper Band", "Middle Band", "Lower Band", "KAMA", "Fibonacci Retracement"])
# Show the chart
plt.show()
import pandas as pd
import talib
import mplfinance as mpf
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from fancyimpute import KNN
import requests
from datetime import datetime, timedelta
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler
from sklearn.impute import IterativeImputer
# Importing the data
data = pd.read_csv("crypto_data.csv", parse_dates=["date"])
# Dropping the "date" column
data.drop("date", axis=1, inplace=True)
# Scaling the data
scaler = MinMaxScaler()
data = pd.DataFrame(scaler.fit_transform(data), columns=data.columns)
# Replacing missing values with the mean of the column
imputer = IterativeImputer()
data = pd.DataFrame(imputer.fit_transform(data), columns=data.columns)
# Defining the kmeans function with initialization as k-means++
kmeans = KMeans(n_clusters=3, init='k-means++')
# Fitting the k means algorithm on scaled data
kmeans.fit(data.values)
# Convert date column to timestamp
data["date"] = pd.to_datetime(data["date"])
# Store the "date" column in a separate variable
date_col = data["date"]
# Remove the "date" column from the dataframe
data = data.drop("date", axis=1)
# Replace missing values with the KNN imputed values
imputer = KNN(k=3)
data = pd.DataFrame(imputer.fit_transform(data), columns=data.columns)
# Add the "date" column back into the dataframe
data["date"] = date_col
# Calculate moving averages
data["50_MA"] = data["close"].rolling(window=50).mean()
data["200_MA"] = data["close"].rolling(window=200).mean()
# Calculate relative strength index
data["RSI"] = talib.RSI(data["close"], timeperiod=14)
# Calculate Bollinger Bands
data["upper_band"], data["middle_band"], data["lower_band"] = talib.BBANDS(data["close"])
# Calculate Kaufman Adaptive Moving Average
data["kama"] = talib.KAMA(data["close"], timeperiod=30)
# Create an array of the indicators
X = data[["50_MA", "200_MA", "RSI", "upper_band", "middle_band", "lower_band", "kama"]].values
# Initialize the KMeans model
kmeans = KMeans(n_clusters=3)
# Fit the model to the data
kmeans.fit(X)
# Assign each observation to a cluster
data["cluster"] = kmeans.predict(X)
# Plot the data using mplfinance
mpf.plot(data,type='candle',style='charles',title='Crypto Market', ylabel='Price in USD', mav=(50,200), indicators={'sma': [50,200]})
plt.show()
# Print the dataframe
print(data)
dng stratyegiesrimport pandas as pd import numpy as np from sklearn.cluster import KMeans from sklearn.impute import IterativeImputer
from sklearn.impute import SimpleImputer
Load historical data
data = pd.read_csv("crypto_data.csv")
Convert date column to timestamp
data["date"] = pd.to_datetime(data["date"])
Store the "date" column in a separate variable
date_col = data["date"]
Remove the "date" column from the dataframe
data = data.drop("date", axis=1)
Replace missing values with the KNN imputed values
imputer = IterativeImputer(random_state=0) data = pd.DataFrame(imputer.fit_transform(data), columns=data.columns)
Add the "date" column back into the dataframe
data["date"] = date_col
Calculate moving averages
data["50_MA"] = data["close"].rolling(window=50).mean() data["200_MA"] = data["close"].rolling(window=200).mean()
Calculate relative strength index
data["RSI"] = talib.RSI(data["close"], timeperiod=14)
Calculate Bollinger Bands
data["upper_band"], data["middle_band"], data["lower_band"] = talib.BBANDS(data["close"])
Calculate Kaufman Adaptive Moving Average
data["kama"] = talib.KAMA(data["close"], timeperiod=30)
Remove any rows with missing values
data = data.dropna()
Create an array of the indicators
X = data[["50_MA", "200_MA", "RSI", "upper_band", "middle_band", "lower_band", "kama"]].values
Initialize the KMeans model
kmeans = KMeans(n_clusters=3)
X = X[~np.isnan(X).any(axis=1)]
Fit the model to the data
kmeans.fit(X)
Assign each observation to a cluster
data["cluster"] = kmeans.predict(X)
Reset the index of the dataframe
data = data.reset_index(drop=True)
data = data.set_index("date")
Plot the data using mplfinance
mpf.plot(data,type='candle',style='charles',title='Crypto Market', ylabel='Price in USD',xlabel='Date', mav=(50,200)) plt.show()
Print the dataframe
data