You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

68 lines
1.8 KiB

1 month ago
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import sys
  4. sys.path.append("../")
  5. from model import Kronos, KronosTokenizer, KronosPredictor
  6. def plot_prediction(kline_df, pred_df):
  7. pred_df.index = kline_df.index[-pred_df.shape[0]:]
  8. sr_close = kline_df['close']
  9. sr_pred_close = pred_df['close']
  10. sr_close.name = 'Ground Truth'
  11. sr_pred_close.name = "Prediction"
  12. close_df = pd.concat([sr_close, sr_pred_close], axis=1)
  13. fig, ax = plt.subplots(1, 1, figsize=(8, 4))
  14. ax.plot(close_df['Ground Truth'], label='Ground Truth', color='blue', linewidth=1.5)
  15. ax.plot(close_df['Prediction'], label='Prediction', color='red', linewidth=1.5)
  16. ax.set_ylabel('Close Price', fontsize=14)
  17. ax.legend(loc='lower left', fontsize=12)
  18. ax.grid(True)
  19. plt.tight_layout()
  20. plt.show()
  21. # 1. Load Model and Tokenizer
  22. tokenizer = KronosTokenizer.from_pretrained("NeoQuasar/Kronos-Tokenizer-base")
  23. model = Kronos.from_pretrained("NeoQuasar/Kronos-small")
  24. # 2. Instantiate Predictor
  25. predictor = KronosPredictor(model, tokenizer, device="cuda:0", max_context=512)
  26. # 3. Prepare Data
  27. df = pd.read_csv("./data/XSHG_5min_600977.csv")
  28. df['timestamps'] = pd.to_datetime(df['timestamps'])
  29. lookback = 400
  30. pred_len = 120
  31. x_df = df.loc[:lookback-1, ['open', 'high', 'low', 'close']]
  32. x_timestamp = df.loc[:lookback-1, 'timestamps']
  33. y_timestamp = df.loc[lookback:lookback+pred_len-1, 'timestamps']
  34. # 4. Make Prediction
  35. pred_df = predictor.predict(
  36. df=x_df,
  37. x_timestamp=x_timestamp,
  38. y_timestamp=y_timestamp,
  39. pred_len=pred_len,
  40. T=1.0,
  41. top_p=0.9,
  42. sample_count=1,
  43. verbose=True
  44. )
  45. # 5. Visualize Results
  46. print("Forecasted Data Head:")
  47. print(pred_df.head())
  48. # Combine historical and forecasted data for plotting
  49. kline_df = df.loc[:lookback+pred_len-1]
  50. # visualize
  51. plot_prediction(kline_df, pred_df)