Krypto1 / app.py
KatGaw's picture
adding new reddit group
315f997
raw
history blame
6.46 kB
from langchain_core.messages import BaseMessage, HumanMessage
from langchain_openai import ChatOpenAI
from typing import Annotated
import operator
from typing import Sequence, TypedDict
import numpy as np
import pandas as pd
from dotenv import load_dotenv
import os
from typing import Annotated
import operator
from typing import Sequence, TypedDict
import matplotlib.pyplot as plt
from langchain.schema.output_parser import StrOutputParser
import app_crypto_rf_model as rf
import app_crypto_scrape as sa
import app_crypto_arima_model as arima
import streamlit as st
import requests
from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
st.set_page_config(page_title="LangChain Agent", layout="wide")
load_dotenv()
COINGECKO_API_KEY=os.environ["COINGECKO_API_KEY"]
OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
llm = ChatOpenAI(model="gpt-3.5-turbo")
#======================== AGENTS ==================================
# The agent state is the input to each node in the graph
class AgentState(TypedDict):
# The annotation tells the graph that new messages will always
# be added to the current states
messages: Annotated[Sequence[BaseMessage], operator.add]
# The 'next' field indicates where to route to next
next: str
tool=data_analyst.data_analyst_tools()
from langchain_core.runnables import RunnableConfig
st.title("πŸ’¬ Krypto")
#@st.cache_data
#@st.cache_resource
#def initialize_session_state():
if "chat_history" not in st.session_state:
st.session_state["messages"] = [{"role":"system", "content":"""
How can I help you?
"""}]
#initialize_session_state()
# Streamlit UI elements
st.image('crypto_image.png')
#st.text("Start by entering the currency.")
sideb = st.sidebar
with st.sidebar:
#st.subheader("This is the LangGraph workflow visualization of this application rendered in real-time.")
#st.image(create_graph_image())
title = st.text_input("Start by entering the currency name:")
check1 = sideb.button(f"analyze {title}")
results=[]
if check1:
st.write(f"I am now producing analysis for {title}")
model = ChatOpenAI(temperature=0.7, api_key=OPENAI_API_KEY)
chain= model | StrOutputParser()
result=chain.invoke(f"You are a cryptocurrency data analyst.\
Provide correct cryptocurrency ticker from Coingecko website for cryptocurrency: {title}.\
Expected output: ticker.\
Provide it in the following format: >>cryptocurrencyticker>> \
for example: >>BTC>>")
# for s in graph_data.stream(inputs):
# for key, value in s.items():
# print(f"Finished running: {value}:")
# result = value["messages"][-1].content
# results.append(value["messages"][-1].content)
print(result)
print('ticker',str(result).split(">>")[0])
if len(str(result).split(">>")[1])<10:
cryptocurrencyticker=(str(result).split(">>")[1])
else:
cryptocurrencyticker=(str(result).split(">>")[0])
cryptocurrency=title
print(cryptocurrency,cryptocurrencyticker)
print('here')
# # 1. Scrape historical Price and Volume currency data
# from datetime import date
# today = date.today()
# Day_end = today.strftime("%d")
# Month_end = today.strftime("%m")
# Year_end = today.strftime("%Y")
# from datetime import date
# from datetime import timedelta
# past=today-timedelta(days=200)
# Day_start = past.strftime("%d")
# Month_start = past.strftime("%m")
# Year_start = past.strftime("%Y")
# date_start=[Year_start,Month_start,Day_start]
# date_end=[Year_end,Month_end,Day_end]
# import datetime
# import time
# #DATE definitions
# date_time = datetime.datetime(int(date_start[0]),int(date_start[1]),int(date_start[2]))
# date_time_now = datetime.datetime(int(date_end[0]),int(date_end[1]),int(date_end[2]))
# unix_past=time.mktime(date_time.timetuple()) #change the date format into unix for scraping
# unix_now=time.mktime(date_time_now.timetuple())
# past=datetime.datetime(int(date_start[0]),int(date_start[1]),int(date_start[2])).strftime('%Y-%m-%d')
# now=datetime.datetime(int(date_end[0]),int(date_end[1]),int(date_end[2])).strftime('%Y-%m-%d')
# datum_range=pd.date_range(start=past,end=now, freq='D')
# #empty lists
# unix_all=[]
# coins_names=[]
# #create date variable
# for val in datum_range:
# unix_all=np.append(unix_all,time.mktime(val.timetuple()))
# #from utils import slice
# # Get API for CoinGecko
# #cg = CoinGeckoAPI()
# url = f"https://api.coingecko.com/api/v3/coins/{cryptocurrency.lower()}/market_chart/range?vs_currency=usd&from={unix_past}&to={unix_now}"
# headers = {
# "accept": "application/json",
# "x-cg-demo-api-key": COINGECKO_API_KEY
# }
# response = ''
# while response == '':
# try:
# response = requests.get(url, headers=headers, proxies={"http": "http://111.233.225.166:1234"})
# break
# except:
# print("Connection refused by the server..")
# print("Let me sleep for 5 seconds")
# print("ZZzzzz...")
# time.sleep(5)
# print("Was a nice sleep, now let me continue...")
# continue
# data=response.json()
#This example uses Python 2.7 and the python-request library.
url = 'https://sandbox-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
parameters = {
'start':'1',
'limit':'5000',
'convert':'USD'
}
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c',
}
session = Session()
session.headers.update(headers)
try:
response = session.get(url, params=parameters)
data = json.loads(response.text)
print(data)
except (ConnectionError, Timeout, TooManyRedirects) as e:
print(e)
#data=cg.get_coin_market_chart_range_by_id(id=cryptocurrency.lower(),vs_currency='usd',include_market_cap='true', include_24hr_vol='true', from_timestamp=unix_past,to_timestamp=unix_now)
#df_ts_coins=su.scrape_historical_series([currency],date_start,date_end)
#================== Scrape Current/Historical Price ====================
st.write(data)