Skip to content

Instantly share code, notes, and snippets.

View pythonlessons's full-sized avatar
🏠
Working from home

Rokas Liuberskis pythonlessons

🏠
Working from home
View GitHub Profile
@pythonlessons
pythonlessons / BTC_trading_bot_4_reward.py
Last active December 31, 2020 10:46
BTC_trading_bot_4_reward
# Calculate reward
def get_reward(self):
self.punish_value += self.net_worth * 0.00001
if self.episode_orders > 1 and self.episode_orders > self.prev_episode_orders:
self.prev_episode_orders = self.episode_orders
if self.trades[-1]['type'] == "buy" and self.trades[-2]['type'] == "sell":
reward = self.trades[-2]['total']*self.trades[-2]['current_price'] - self.trades[-2]['total']*self.trades[-1]['current_price']
reward -= self.punish_value
self.punish_value = 0
self.trades[-1]["Reward"] = reward
@pythonlessons
pythonlessons / BTC_trading_bot_4_rendering_0.py
Last active December 31, 2020 11:40
BTC_trading_bot_4_rendering_0
# sort sell and buy orders, put arrows in appropiate order positions
for trade in trades:
trade_date = mpl_dates.date2num([pd.to_datetime(trade['Date'])])[0]
if trade_date in Date_Render_range:
if trade['type'] == 'buy':
high_low = trade['Low']-10
self.ax1.scatter(trade_date, high_low, c='green', label='green', s = 120, edgecolors='none', marker="^")
else:
high_low = trade['High']+10
self.ax1.scatter(trade_date, high_low, c='red', label='red', s = 120, edgecolors='none', marker="v")
@pythonlessons
pythonlessons / BTC_trading_bot_4_rendering_1.py
Created December 31, 2020 11:40
BTC_trading_bot_4_rendering_1
minimum = np.min(np.array(self.render_data)[:,1:])
maximum = np.max(np.array(self.render_data)[:,1:])
RANGE = maximum - minimum
# sort sell and buy orders, put arrows in appropiate order positions
for trade in trades:
trade_date = mpl_dates.date2num([pd.to_datetime(trade['Date'])])[0]
if trade_date in Date_Render_range:
if trade['type'] == 'buy':
high_low = trade['Low'] - RANGE*0.02
@pythonlessons
pythonlessons / BTC_trading_bot_4_test_results.py
Created January 5, 2021 11:19
BTC_trading_bot_4_test_results
print("average {} episodes agent net_worth: {}, orders: {}".format(test_episodes, average_net_worth/test_episodes, average_orders/test_episodes))
print("No profit episodes: {}".format(no_profit_episodes))
# save test results to test_results.txt file
with open("test_results.txt", "a+") as results:
results.write(f'{datetime.now().strftime("%Y-%m-%d %H:%M")}, {name}, test episodes:{test_episodes}')
results.write(f', net worth:{average_net_worth/(episode+1)}, orders per episode:{average_orders/test_episodes}')
results.write(f', no profit episodes:{no_profit_episodes}, comment: {comment}\n')
@pythonlessons
pythonlessons / BTC_trading_bot_4_save.py
Last active January 12, 2021 10:47
BTC_trading_bot_4_save
def save(self, name="Crypto_trader", score="", args=[]):
# save keras model weights
self.Actor.Actor.save_weights(f"{self.log_name}/{score}_{name}_Actor.h5")
self.Critic.Critic.save_weights(f"{self.log_name}/{score}_{name}_Critic.h5")
# log saved model arguments to file
if len(args) > 0:
with open(f"{self.log_name}/log.txt", "a+") as log:
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log.write(f"{current_time}, {args[0]}, {args[1]}, {args[2]}, {args[3]}, {args[4]}\n")
@pythonlessons
pythonlessons / BTC_trading_bot_4_dense_training.py
Created January 12, 2021 13:51
BTC_trading_bot_4_dense_training
if __name__ == "__main__":
df = pd.read_csv('./pricedata.csv')
df = df.sort_values('Date')
lookback_window_size = 50
test_window = 720 # 30 days
train_df = df[:-test_window-lookback_window_size]
test_df = df[-test_window-lookback_window_size:]
# Create our custom Neural Networks model
@pythonlessons
pythonlessons / BTC_trading_bot_4_testing.py
Created January 12, 2021 19:40
BTC_trading_bot_4_testing
if __name__ == "__main__":
df = pd.read_csv('./pricedata.csv')
df = df.sort_values('Date')
lookback_window_size = 50
test_window = 720 # 30 days
train_df = df[:-test_window-lookback_window_size]
test_df = df[-test_window-lookback_window_size:]
agent = CustomAgent(lookback_window_size=lookback_window_size, lr=0.00001, epochs=1, optimizer=Adam, batch_size = 32, model="Dense")
@pythonlessons
pythonlessons / BTC_trading_bot_5_Plot_OHCL.py
Created January 17, 2021 15:42
BTC_trading_bot_5_Plot_OHCL
import matplotlib.pyplot as plt
from mplfinance.original_flavor import candlestick_ohlc
import matplotlib.dates as mpl_dates
def Plot_OHCL(df, ax1_indicators=[], ax2_indicators=[]):
df_original = df.copy()
# necessary convert to datetime
df["Date"] = pd.to_datetime(df.Date)
df["Date"] = df["Date"].apply(mpl_dates.date2num)
@pythonlessons
pythonlessons / BTC_trading_bot_5_Plot_SMA.py
Last active January 18, 2021 08:15
BTC_trading_bot_5_Plot_SMA
import pandas as pd
from ta.trend import SMAIndicator
def AddIndicators(df):
# Add Simple Moving Average (SMA) indicators
df["sma7"] = SMAIndicator(close=df["Close"], window=7, fillna=True).sma_indicator()
df["sma25"] = SMAIndicator(close=df["Close"], window=25, fillna=True).sma_indicator()
df["sma99"] = SMAIndicator(close=df["Close"], window=99, fillna=True).sma_indicator()
return df
@pythonlessons
pythonlessons / BTC_trading_bot_5_Plot_Bollinger_Bands.py
Last active January 18, 2021 08:26
BTC_trading_bot_5_Plot_Bollinger_Bands
import pandas as pd
from ta.volatility import BollingerBands
def AddIndicators(df):
# Add Bollinger Bands indicator
indicator_bb = BollingerBands(close=df["Close"], window=20, window_dev=2)
df['bb_bbm'] = indicator_bb.bollinger_mavg()
df['bb_bbh'] = indicator_bb.bollinger_hband()
df['bb_bbl'] = indicator_bb.bollinger_lband()