Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,102 +1,89 @@
|
|
| 1 |
-
from smolagents import CodeAgent,
|
| 2 |
import datetime
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
|
|
|
| 6 |
from tools.final_answer import FinalAnswerTool
|
| 7 |
-
|
| 8 |
from Gradio_UI import GradioUI
|
| 9 |
|
| 10 |
-
#
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
| 13 |
"""
|
| 14 |
-
|
| 15 |
-
Args:
|
| 16 |
-
period: Number of periods to use for RSI calculation (default is 14).
|
| 17 |
-
Returns:
|
| 18 |
-
The current RSI value as an integer.
|
| 19 |
"""
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
data = response.json()
|
| 26 |
-
prices = [price_point[1] for price_point in data["prices"]]
|
| 27 |
-
|
| 28 |
-
if len(prices) < period + 1:
|
| 29 |
-
raise ValueError("Not enough data to calculate RSI.")
|
| 30 |
-
|
| 31 |
-
# Calculate price changes (deltas)
|
| 32 |
-
deltas = [prices[i+1] - prices[i] for i in range(len(prices) - 1)]
|
| 33 |
-
gains = [delta if delta > 0 else 0 for delta in deltas]
|
| 34 |
-
losses = [-delta if delta < 0 else 0 for delta in deltas]
|
| 35 |
-
|
| 36 |
-
# Initial average gain and loss
|
| 37 |
-
avg_gain = sum(gains[:period]) / period
|
| 38 |
-
avg_loss = sum(losses[:period]) / period
|
| 39 |
-
|
| 40 |
-
# Smooth averages over the remaining data
|
| 41 |
-
for i in range(period, len(gains)):
|
| 42 |
-
gain = gains[i]
|
| 43 |
-
loss = losses[i]
|
| 44 |
-
avg_gain = (avg_gain * (period - 1) + gain) / period
|
| 45 |
-
avg_loss = (avg_loss * (period - 1) + loss) / period
|
| 46 |
-
|
| 47 |
-
if avg_loss == 0:
|
| 48 |
-
rsi = 100
|
| 49 |
-
else:
|
| 50 |
-
rs = avg_gain / avg_loss
|
| 51 |
-
rsi = 100 - (100 / (1 + rs))
|
| 52 |
-
|
| 53 |
-
return int(rsi)
|
| 54 |
-
except Exception as e:
|
| 55 |
-
# Returning a negative value signals an error in this example.
|
| 56 |
-
return -1
|
| 57 |
|
| 58 |
-
|
| 59 |
-
@tool
|
| 60 |
-
def rsi_signal(period: int = 14) -> str:
|
| 61 |
"""
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
period: The RSI period to use (default 14).
|
| 65 |
-
Returns:
|
| 66 |
-
A string with the RSI value and a recommendation:
|
| 67 |
-
- "Buy" if RSI < 30 (oversold)
|
| 68 |
-
- "Sell" if RSI > 70 (overbought)
|
| 69 |
-
- "Hold" otherwise.
|
| 70 |
"""
|
| 71 |
-
|
| 72 |
-
if rsi_value == -1:
|
| 73 |
-
return "Error calculating RSI. Please try again later."
|
| 74 |
-
|
| 75 |
-
if rsi_value < 30:
|
| 76 |
-
signal = "Buy"
|
| 77 |
-
elif rsi_value > 70:
|
| 78 |
-
signal = "Sell"
|
| 79 |
-
else:
|
| 80 |
-
signal = "Hold"
|
| 81 |
-
|
| 82 |
-
return f"Current RSI: {rsi_value}. Recommendation: {signal}."
|
| 83 |
|
| 84 |
@tool
|
| 85 |
-
def
|
| 86 |
"""
|
| 87 |
-
|
|
|
|
| 88 |
Args:
|
| 89 |
-
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
"""
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
@tool
|
| 95 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 96 |
"""
|
| 97 |
-
|
|
|
|
| 98 |
Args:
|
| 99 |
-
timezone: A
|
| 100 |
"""
|
| 101 |
try:
|
| 102 |
tz = pytz.timezone(timezone)
|
|
@@ -105,6 +92,17 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 105 |
except Exception as e:
|
| 106 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
final_answer = FinalAnswerTool()
|
| 109 |
|
| 110 |
model = HfApiModel(
|
|
@@ -114,15 +112,12 @@ model = HfApiModel(
|
|
| 114 |
custom_role_conversions=None,
|
| 115 |
)
|
| 116 |
|
| 117 |
-
# Import tool from Hub
|
| 118 |
-
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 119 |
-
|
| 120 |
with open("prompts.yaml", 'r') as stream:
|
| 121 |
prompt_templates = yaml.safe_load(stream)
|
| 122 |
|
| 123 |
agent = CodeAgent(
|
| 124 |
model=model,
|
| 125 |
-
tools=[final_answer,
|
| 126 |
max_steps=6,
|
| 127 |
verbosity_level=1,
|
| 128 |
grammar=None,
|
|
|
|
| 1 |
+
from smolagents import CodeAgent, tool, load_tool, HfApiModel
|
| 2 |
import datetime
|
| 3 |
import requests
|
| 4 |
import pytz
|
| 5 |
import yaml
|
| 6 |
+
import math
|
| 7 |
from tools.final_answer import FinalAnswerTool
|
|
|
|
| 8 |
from Gradio_UI import GradioUI
|
| 9 |
|
| 10 |
+
# Disclaimer: This agent is for educational purposes only.
|
| 11 |
+
# It uses a very simple model (based on the Kelly Criterion) to recommend an investment amount.
|
| 12 |
+
# It does NOT guarantee profitability and should not be used as a sole basis for any real trading decision.
|
| 13 |
+
|
| 14 |
+
def get_btc_price() -> float:
|
| 15 |
"""
|
| 16 |
+
Fetches the current BTC price (USD) from CoinGecko.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
"""
|
| 18 |
+
url = "https://api.coingecko.com/api/v3/simple/price"
|
| 19 |
+
params = {"ids": "bitcoin", "vs_currencies": "usd"}
|
| 20 |
+
response = requests.get(url, params=params)
|
| 21 |
+
data = response.json()
|
| 22 |
+
return data["bitcoin"]["usd"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
+
def calculate_kelly(prob: float, reward_ratio: float) -> float:
|
|
|
|
|
|
|
| 25 |
"""
|
| 26 |
+
Calculate the Kelly fraction.
|
| 27 |
+
Formula: (prob * (reward_ratio + 1) - 1) / reward_ratio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
"""
|
| 29 |
+
return (prob * (reward_ratio + 1) - 1) / reward_ratio
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
@tool
|
| 32 |
+
def btc_investment_advice(total_capital: float, risk_tolerance: float, target_profit_ratio: float, probability_edge: float) -> str:
|
| 33 |
"""
|
| 34 |
+
Provides an investment recommendation for Bitcoin.
|
| 35 |
+
|
| 36 |
Args:
|
| 37 |
+
total_capital: Total available capital in USD.
|
| 38 |
+
risk_tolerance: Fraction of capital you're willing to risk (e.g., 0.05 for 5%).
|
| 39 |
+
target_profit_ratio: Your target reward ratio (e.g., 2 means you aim for 2:1 reward-to-risk).
|
| 40 |
+
probability_edge: Your estimated probability of a favorable outcome (0 to 1).
|
| 41 |
+
|
| 42 |
+
Returns:
|
| 43 |
+
A string with:
|
| 44 |
+
- Current BTC price,
|
| 45 |
+
- Recommended investment amount (USD),
|
| 46 |
+
- Calculated Kelly fraction,
|
| 47 |
+
- Risk/Profit target ratio,
|
| 48 |
+
- A final recommendation (Invest / Hold / Caution).
|
| 49 |
"""
|
| 50 |
+
try:
|
| 51 |
+
current_price = get_btc_price()
|
| 52 |
+
# Calculate the optimal fraction using Kelly's formula.
|
| 53 |
+
kelly_fraction = calculate_kelly(probability_edge, target_profit_ratio)
|
| 54 |
+
# Limit the fraction by your risk tolerance.
|
| 55 |
+
recommended_fraction = min(kelly_fraction, risk_tolerance)
|
| 56 |
+
recommended_investment = recommended_fraction * total_capital
|
| 57 |
+
|
| 58 |
+
# Generate a simple decision based on your probability edge.
|
| 59 |
+
if probability_edge < 0.5:
|
| 60 |
+
decision = "Caution: Your edge is below 50%; consider holding off."
|
| 61 |
+
else:
|
| 62 |
+
decision = "Invest" if recommended_investment > 0 else "Hold"
|
| 63 |
+
|
| 64 |
+
result = (
|
| 65 |
+
f"Current BTC Price: ${current_price:.2f}\n"
|
| 66 |
+
f"Total Capital: ${total_capital:.2f}\n"
|
| 67 |
+
f"Risk Tolerance: {risk_tolerance*100:.1f}%\n"
|
| 68 |
+
f"Target Profit Ratio (Reward-to-Risk): {target_profit_ratio}:1\n"
|
| 69 |
+
f"Estimated Probability Edge: {probability_edge*100:.1f}%\n"
|
| 70 |
+
f"Calculated Kelly Fraction: {kelly_fraction*100:.1f}%\n"
|
| 71 |
+
f"Recommended Investment (limited by risk tolerance): ${recommended_investment:.2f}\n"
|
| 72 |
+
f"Decision: {decision}\n\n"
|
| 73 |
+
"Note: This is a simplified simulation and not financial advice. "
|
| 74 |
+
"Always do your own research and consider multiple factors before investing."
|
| 75 |
+
)
|
| 76 |
+
return result
|
| 77 |
+
except Exception as e:
|
| 78 |
+
return f"Error: {str(e)}"
|
| 79 |
|
| 80 |
@tool
|
| 81 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 82 |
"""
|
| 83 |
+
Returns the current local time in the specified timezone.
|
| 84 |
+
|
| 85 |
Args:
|
| 86 |
+
timezone: A valid timezone string (e.g., 'America/New_York').
|
| 87 |
"""
|
| 88 |
try:
|
| 89 |
tz = pytz.timezone(timezone)
|
|
|
|
| 92 |
except Exception as e:
|
| 93 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 94 |
|
| 95 |
+
@tool
|
| 96 |
+
def my_custom_tool(arg1: str, arg2: int) -> str:
|
| 97 |
+
"""
|
| 98 |
+
A placeholder tool.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
arg1: The first argument.
|
| 102 |
+
arg2: The second argument.
|
| 103 |
+
"""
|
| 104 |
+
return "What magic will you build?"
|
| 105 |
+
|
| 106 |
final_answer = FinalAnswerTool()
|
| 107 |
|
| 108 |
model = HfApiModel(
|
|
|
|
| 112 |
custom_role_conversions=None,
|
| 113 |
)
|
| 114 |
|
|
|
|
|
|
|
|
|
|
| 115 |
with open("prompts.yaml", 'r') as stream:
|
| 116 |
prompt_templates = yaml.safe_load(stream)
|
| 117 |
|
| 118 |
agent = CodeAgent(
|
| 119 |
model=model,
|
| 120 |
+
tools=[final_answer, btc_investment_advice, get_current_time_in_timezone, my_custom_tool],
|
| 121 |
max_steps=6,
|
| 122 |
verbosity_level=1,
|
| 123 |
grammar=None,
|