基于Times FM模型对稳定币总规模未来5年增长趋势预测(代码)
April 20th, 2025
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import timesfm
from datetime import datetime, timedelta

# 导入必要的库
# pandas用于数据处理
# numpy用于数值计算
# matplotlib用于数据可视化
# timesfm用于时间序列预测
# datetime用于日期时间处理

# 读取CSV文件
# 从iMac的下载文件夹读取
file_path = '/Users/ningli/Downloads/rwa-asset-timeseries-export-1744949365800.csv'  # 替换"你的用户名"为您的Mac用户名
stablecoin_data = pd.read_csv(file_path)

# 将时间戳转换为datetime类型,便于处理
stablecoin_data['Date'] = pd.to_datetime(stablecoin_data['Date'])

# 打印数据集的基本信息
print(f"Dataset shape: {stablecoin_data.shape}")  # 显示行数和列数
print(f"Date range: {stablecoin_data['Date'].min()} to {stablecoin_data['Date'].max()}")  # 显示数据的时间跨度

# 获取所有稳定币列的列表(排除非稳定币列)
stablecoin_columns = [col for col in stablecoin_data.columns 
                      if col not in ['Timestamp', 'Date', 'Measure']]

print(f"Number of stablecoin types: {len(stablecoin_columns)}")
print(f"Stablecoin types: {stablecoin_columns}")

# 计算每日稳定币市场总规模
# 按日期分组并对所有稳定币值求和
daily_totals = stablecoin_data.groupby('Date')[stablecoin_columns].sum().sum(axis=1).reset_index()
daily_totals.columns = ['Date', 'TotalStablecoinSize']  # 重命名列

# 按日期排序
daily_totals = daily_totals.sort_values('Date')

# 显示基本统计数据
print("\nDaily Total Stablecoin Market Size Statistics:")
print(daily_totals['TotalStablecoinSize'].describe())  # 计算均值、标准差、最小值、最大值等统计量

# 显示前几行和后几行记录
print("\nFirst few days of data:")
print(daily_totals.head())
print("\nLast few days of data:")
print(daily_totals.tail())

# 创建TimesFM模型实例,遵循示例代码
tfm = timesfm.TimesFm(
    hparams=timesfm.TimesFmHparams(
        context_len=32,  # 模型的最大上下文长度
        horizon_len=1825,  # 预测5年(365天 × 5)
        input_patch_len=32,  # 固定值
        output_patch_len=128,  # 固定值
        num_layers=20,  # 固定值
        model_dims=1280,  # 固定值
        backend="cpu"  # 可以是 "cpu"、"gpu" 或 "tpu"
    ),
    checkpoint=timesfm.TimesFmCheckpoint(
        huggingface_repo_id="google/timesfm-1.0-200m-pytorch"),  # 加载预训练检查点
)

# 为模型准备输入数据
forecast_input = daily_totals['TotalStablecoinSize'].values.reshape(1, -1)  # 转换为二维数组
frequency_input = [0]  # 使用高频率设置

# 生成预测
point_forecast, experimental_quantile_forecast = tfm.forecast(
    forecast_input, 
    freq=frequency_input,
)

# 获取历史数据的最后一个日期
last_date = daily_totals['Date'].iloc[-1]

# 为预测创建日期序列(5年)
forecast_dates = pd.date_range(start=last_date, periods=len(point_forecast[0]) + 1, inclusive='right')

# 创建用于绘图的DataFrame
forecast_df = pd.DataFrame({
    'Date': forecast_dates, 
    'Forecast': point_forecast[0]
})

# 绘制历史数据和预测数据
plt.figure(figsize=(16, 8))  # 设置图形大小
plt.plot(daily_totals['Date'], daily_totals['TotalStablecoinSize'], label='Historical Stablecoin Market Size')
plt.plot(forecast_df['Date'], forecast_df['Forecast'], label='Forecast (5 Years)')
plt.xlabel('Date')  # X轴标签
plt.ylabel('Total Stablecoin Market Size (USD)')  # Y轴标签
plt.title('Stablecoin Market Size Forecast (5 Years)')  # 图表标题
plt.grid(True, alpha=0.3)  # 添加网格线
plt.legend()  # 显示图例

# 添加关键统计信息的注释
current_size = daily_totals['TotalStablecoinSize'].iloc[-1]  # 当前市场规模
future_size = forecast_df['Forecast'].iloc[-1]  # 5年后的市场规模
growth_pct = ((future_size - current_size) / current_size) * 100  # 增长百分比

# 为当前市场规模添加注释
plt.annotate(f'Current Size: ${current_size/1e9:.2f}B', 
             xy=(last_date, current_size),
             xytext=(10, 30), textcoords='offset points',
             arrowprops=dict(arrowstyle='->'))

# 为5年后市场规模添加注释
plt.annotate(f'Projected Size in 5 Years: ${future_size/1e9:.2f}B\nGrowth: {growth_pct:.2f}%', 
             xy=(forecast_dates[-1], future_size),
             xytext=(-100, 30), textcoords='offset points',
             arrowprops=dict(arrowstyle='->'))

# 优化X轴日期格式,提高可读性
plt.gcf().autofmt_xdate()

# 为主要稳定币单独创建一个图表
# 首先检查哪些稳定币确实存在于我们的数据中
available_stablecoins = [coin for coin in stablecoin_columns if coin in ['USDT', 'USDC', 'BUSD', 'FRAX', 'DAI']]
print(f"Available major stablecoins: {available_stablecoins}")

if available_stablecoins:  # 如果有可用的稳定币
    # 将数据透视为按日期索引的形式
    stablecoin_data_pivoted = stablecoin_data.pivot_table(
        index='Date', 
        values=available_stablecoins,  # 只使用实际存在的稳定币
        aggfunc='sum'
    ).reset_index()

    # 创建新的图形
    plt.figure(figsize=(16, 8))

else:
    print("No major stablecoins found in data. Skipping individual stablecoin chart.")

# 显示所有图表
plt.show()

# 打印预测摘要
print("\nForecast Summary:")
print(f"Current total stablecoin market size: ${current_size/1e9:.2f} billion")
print(f"Projected market size in 5 years: ${future_size/1e9:.2f} billion")
print(f"Projected growth: {growth_pct:.2f}%")
print(f"Compound Annual Growth Rate (CAGR): {((future_size/current_size)**(1/5) - 1) * 100:.2f}%")
Subscribe to NingNing
Receive the latest updates directly to your inbox.
Nft graphic
Mint this entry as an NFT to add it to your collection.
Verification
This entry has been permanently stored onchain and signed by its creator.
More from NingNing

Skeleton

Skeleton

Skeleton