import time
import requests
import pandas as pd
def get_bitcoin_price_history(start_date):
url = 'https://api.coingecko.com/api/v3/coins/bitcoin/market_chart/range'
params = {
'vs_currency': 'usd',
'from': start_date.timestamp(),
'to': pd.Timestamp.now().timestamp()
}
response = requests.get(url, params=params)
data = pd.json_normalize(response.json())
return {sub_arr[0]: sub_arr[1] for sub_arr in data['prices'][0]}
def backtest(start_date):
start_date = pd.Timestamp(start_date)
bitcoin_price_history = get_bitcoin_price_history(start_date)
investment = 50
bitcoin_num = 0
week_num = 0
for i in range(0, len(bitcoin_price_history), 7):
week_num += 1
date = list(bitcoin_price_history.keys())[i]
price = list(bitcoin_price_history.values())[i]
bitcoin_num += investment / price
date = pd.Timestamp(date, unit='ms').strftime('%Y-%m-%d')
#print(f'On {date} the price was {price:.2f}')
print(f'You would own {bitcoin_num:.2f} bitcoin')
print(f'Your investment would be worth ${bitcoin_num * price:.2f}')
print(f'You invested ${investment * week_num:.2f}')
# 从2013 到 2023年 每年一月一日 回测一次
for year in range(2013, 2023):
s = f'{year}-01-01'
print(f'Backtesting {s}')
backtest(s)
#休眠30秒
time.sleep(30)
贴一下从2013-2023定投的回测结果
Backtesting 2013-01-01
You would own 35.11 bitcoin
Your investment would be worth $1519290.60
You invested $28100.00
Backtesting 2014-01-01
You would own 22.81 bitcoin
Your investment would be worth $971230.04
You invested $26350.00
Backtesting 2015-01-01
You would own 17.46 bitcoin
Your investment would be worth $697474.36
You invested $23700.00
Backtesting 2016-01-01
You would own 7.58 bitcoin
Your investment would be worth $302683.10
You invested $21100.00
Backtesting 2017-01-01
You would own 2.65 bitcoin
Your investment would be worth $111606.17
You invested $18500.00
Backtesting 2018-01-01
You would own 1.32 bitcoin
Your investment would be worth $55658.68
You invested $15900.00
Backtesting 2019-01-01
You would own 0.95 bitcoin
Your investment would be worth $40937.64
You invested $13300.00
Backtesting 2020-01-01
You would own 0.53 bitcoin
Your investment would be worth $22604.93
You invested $10700.00
Backtesting 2021-01-01
You would own 0.26 bitcoin
Your investment would be worth $10452.90
You invested $8050.00
Backtesting 2022-01-01
You would own 0.20 bitcoin
Your investment would be worth $8551.09
You invested $5450.00