Skip to content

Instantly share code, notes, and snippets.

@e96031413
Last active May 16, 2023 03:31
Show Gist options
  • Save e96031413/1a22fa6b4d6b335b24a725d1d45ccbba to your computer and use it in GitHub Desktop.
Save e96031413/1a22fa6b4d6b335b24a725d1d45ccbba to your computer and use it in GitHub Desktop.
DCA-MultiAsset: A Python Code for Dollar-Cost Averaging Multiple Assets
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import datetime
import pandas as pd
from pycoingecko import CoinGeckoAPI
import yfinance as yf
def get_monthly_prices_stock(symbol, date):
today = datetime.date.today()
first_day = date
dates = pd.date_range(first_day, today, freq='MS')
# Fetch historical prices from Yahoo Finance
data = yf.download(symbol, start=first_day, end=today, interval='1mo', progress=False)
prices = data['Adj Close'].tolist()
return dates, prices
def get_monthly_prices(crypto_id, date):
cg = CoinGeckoAPI()
today = datetime.date.today()
first_day = date
dates = pd.date_range(first_day, today, freq='MS')
# Fetch all historical data for the asset
historical_data = cg.get_coin_market_chart_by_id(crypto_id, 'usd', 'max')['prices']
historical_data_df = pd.DataFrame(historical_data, columns=['timestamp', 'price'])
historical_data_df['date'] = pd.to_datetime(historical_data_df['timestamp'], unit='ms').dt.date
# Extract prices for the first day of each month
prices = []
for date in dates:
price = historical_data_df.loc[historical_data_df['date'] == pd.Timestamp(date).date()]['price'].values[0]
prices.append(price)
return dates, prices
def dollar_cost_average(prices, monthly_investment):
total_investment = 0
total_coins = 0
for price in prices:
coins_bought = monthly_investment / price
total_investment += monthly_investment
total_coins += coins_bought
average_cost_price = total_investment / total_coins # Calculate average cost price
return total_investment, total_coins, average_cost_price
def calculate_roi(investment, final_value):
return (final_value - investment) / investment * 100
assets = ['bitcoin', 'ethereum', 'VTI', 'VT', 'QQQ']
monthly_investment = 100
date = datetime.date(2023, 1, 1) # Set the first_day to a specific date
for asset_name in assets:
if asset_name == 'VTI' or asset_name == 'VT' or asset_name == 'QQQ':
dates, prices = get_monthly_prices_stock(asset_name, date)
else:
dates, prices = get_monthly_prices(asset_name, date)
total_investment, total_coins, average_cost_price = dollar_cost_average(prices, monthly_investment)
final_value = total_coins * prices[-1]
profit = final_value - total_investment
final_roi = calculate_roi(total_investment, final_value)
print(f"{asset_name.capitalize()} Results:")
print(f"Total Investment: ${total_investment:.2f}")
print(f"Final Value: ${final_value:.2f}")
print(f"Profit: ${profit:.2f}")
print(f"Final ROI: {final_roi:.2f}%")
print(f"Average Cost Price: ${average_cost_price:.2f}")
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment