Power of DCA via code

Power of DCA via code 




See also: DCABTC DCA via code

Dollar-cost averaging (DCA) is an investment strategy to reduce the impact of volatility of price.

Assume that we want to DCA Bitcoin with a budget BB dollars in nn weeks. Suppose that the close price of week ii is fif_i. Now, we use B/nB/n dollars to buy BTC. So we can buy 1fiBn\frac{1}{f_i} \cdot \frac{B}{n} BTC. Thus, in nn weeks, the average price we accumulate is
Bi=1n1fiBn=1i=1n1fi1n\frac{B}{ \sum_{i=1}^n \frac{1}{f_i} \cdot \frac{B}{n} }=\frac{1}{ \sum_{i=1}^n \frac{1}{f_i} \cdot \frac{1}{n} }

Note. If we DCA “continuously”, then the average price is
1ab1f(x)dx\frac{1}{\int_a^b \frac{1}{f(x)} dx}

Experiment. In the following we provide a DCA experiment for BTC. The time period is taken 2018-2021 when BTC is about 19 000$ falls down to 3 000$ and up to 60 000$. If we apply DCA strtegy, then the weekly DCA price is 6 000$ and the mean price is 3 000$.


code

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style("whitegrid") 

# 1. load price data 
link = "YOUR DATA LINK"
link = 'https://raw.githubusercontent.com/Tran-Thu-Le/share/main/Time_Series/coins/coin_Bitcoin.csv'
data = pd.read_csv(link)
price = data["Close"].values

# 2. result of DCA
def get_mean(price):
   n = len(price)
   mean = price[0]
   mean_list = [mean]
   for k in range(n-1):
       mean = (k+1)/(k/mean + 1/price[k+1])
       mean_list += [mean]

   mean_np = np.array(mean_list) 
   return mean_np 

def weekly_DCA(time_range, price):
   my_price = price[time_range]
   nb_weeks = len(my_price)//7
   id_weeks = np.arange(nb_weeks)*7 
   my_price = my_price[id_weeks]
   mean = get_mean(my_price) 
   time = time_range[id_weeks][:]
   return time, mean 

time_full = np.arange(len(price))
time_1 = np.arange(240, 1650) 
time_2 = np.arange(500, 1000)
time_3 = np.arange(1650, len(price))
time_4 = np.arange(2000, 2500)

time_1, mean_1 = weekly_DCA(time_1, price)
time_2, mean_2 = weekly_DCA(time_2, price)
time_3, mean_3 = weekly_DCA(time_3, price)
time_4, mean_4 = weekly_DCA(time_4, price)

print(len(time_1), len(mean_1))

f, ax = plt.subplots()
ax.plot(time_full, price, label="price", color="blue")
ax.plot(time_1, mean_1, label="DCA 1", color="red")
ax.plot(time_2, mean_2, label="DCA 2", color="orange")

ax.plot(time_3, mean_3, label="DCA 3", color="gray")
ax.plot(time_4, mean_4, label="DCA 4", color="black")

ax.set_yscale("log")
ax.set_title("DCA strategies for BTC")
ax.legend()
plt.show()
f.savefig('DCA.png', format='png', dpi=1200)

Nhận xét

Bài đăng phổ biến từ blog này

Meta Links

IBC v2