File size: 2,630 Bytes
5ba6946
 
4e5ca72
 
 
 
5ba6946
4e5ca72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
---

license: llama3.3
datasets:
- HuggingFaceTB/finemath
base_model:
- Datou1111/shou_xin
---

from llama_index import SimpleKeywordTableIndex, Document
from datetime import datetime, timedelta
import requests
import numpy as np
import pandas as pd

# Fetch historical price data
def fetch_price_data(symbol="ETHUSDT", interval="1h", limit=500):
    """
    Fetch historical price data from Binance API.
    """
    url = f"https://api.binance.com/api/v3/klines?symbol={symbol}&interval={interval}&limit={limit}"
    response = requests.get(url)
    data = response.json()

    # Parse to DataFrame
    df = pd.DataFrame(data, columns=[
        "timestamp", "open", "high", "low", "close", "volume", "close_time",
        "quote_asset_volume", "number_of_trades", "taker_buy_base",
        "taker_buy_quote", "ignore"
    ])
    df["timestamp"] = pd.to_datetime(df["timestamp"], unit="ms")
    df["close"] = df["close"].astype(float)
    return df[["timestamp", "close"]]

# Prepare price history as documents
def prepare_documents(df, window_size=5):
    """
    Convert sliding price windows into Llama documents.
    """
    prices = df["close"].values
    timestamps = df["timestamp"].values

    documents = []
    for i in range(len(prices) - window_size):
        time_range = f"{timestamps[i]} to {timestamps[i + window_size]}"
        price_window = prices[i:i + window_size]
        content = f"Price trend from {time_range}: {price_window.tolist()}"
        documents.append(Document(content))
    return documents

# LlamaIndex-based predictive task
def train_with_llama_index(documents):
    """
    Create a Simple Keyword Table Index to simulate trend prediction using LlamaIndex.
    """
    index = SimpleKeywordTableIndex.from_documents(documents)
    
    # Simulating a market prediction
    prompt = (
        "Based on historical trends, what might be the next ETH/USDT price, "
        "assuming consistent linear progression? Focus on patterns."
    )
    response = index.query(prompt)
    return response

# Main pipeline
def main():
    # Step 1: Fetch historical data
    symbol = "ETHUSDT"
    df = fetch_price_data(symbol)
    print("Fetched historical data:")
    print(df.head())

    # Step 2: Prepare documents for LlamaIndex
    window_size = 5
    documents = prepare_documents(df, window_size)

    # Step 3: Train a Simple Keyword Table Index and predict trends
    prediction_response = train_with_llama_index(documents)
    
    # Step 4: Display response
    print(f"\nPrediction response from LlamaIndex:\n{prediction_response}")

# Entry point
if __name__ == "__main__":
    main()