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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Trading Trust Experiment
|
| 3 |
+
A psychology research game studying trust in AI advice under varying conditions.
|
| 4 |
+
Built for Hugging Face Spaces with Gradio + SQLite
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import sqlite3
|
| 9 |
+
import json
|
| 10 |
+
import uuid
|
| 11 |
+
import random
|
| 12 |
+
import time
|
| 13 |
+
from datetime import datetime
|
| 14 |
+
from dataclasses import dataclass, asdict
|
| 15 |
+
from typing import Optional
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
# ============================================================================
|
| 19 |
+
# DATABASE SETUP
|
| 20 |
+
# ============================================================================
|
| 21 |
+
|
| 22 |
+
DB_PATH = "experiment_data.db"
|
| 23 |
+
|
| 24 |
+
def init_database():
|
| 25 |
+
"""Initialize SQLite database with required tables."""
|
| 26 |
+
conn = sqlite3.connect(DB_PATH)
|
| 27 |
+
cursor = conn.cursor()
|
| 28 |
+
|
| 29 |
+
# Participants table
|
| 30 |
+
cursor.execute("""
|
| 31 |
+
CREATE TABLE IF NOT EXISTS participants (
|
| 32 |
+
participant_id TEXT PRIMARY KEY,
|
| 33 |
+
session_start TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 34 |
+
session_end TIMESTAMP,
|
| 35 |
+
final_portfolio_value REAL,
|
| 36 |
+
total_decisions INTEGER,
|
| 37 |
+
ai_reliance_score REAL,
|
| 38 |
+
completed BOOLEAN DEFAULT FALSE
|
| 39 |
+
)
|
| 40 |
+
""")
|
| 41 |
+
|
| 42 |
+
# Decisions table - captures each trading decision
|
| 43 |
+
cursor.execute("""
|
| 44 |
+
CREATE TABLE IF NOT EXISTS decisions (
|
| 45 |
+
decision_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 46 |
+
participant_id TEXT,
|
| 47 |
+
scenario_id TEXT,
|
| 48 |
+
scenario_order INTEGER,
|
| 49 |
+
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
| 50 |
+
|
| 51 |
+
-- AI Tuning Sliders (participant preferences)
|
| 52 |
+
ai_confidence_setting INTEGER,
|
| 53 |
+
ai_explanation_setting INTEGER,
|
| 54 |
+
ai_risk_setting INTEGER,
|
| 55 |
+
|
| 56 |
+
-- Scenario details
|
| 57 |
+
scenario_text TEXT,
|
| 58 |
+
ai_advice_text TEXT,
|
| 59 |
+
ai_advice_direction TEXT,
|
| 60 |
+
ai_advice_accuracy TEXT,
|
| 61 |
+
|
| 62 |
+
-- Participant response
|
| 63 |
+
decision TEXT,
|
| 64 |
+
decision_amount REAL,
|
| 65 |
+
confidence_in_decision INTEGER,
|
| 66 |
+
response_time_ms INTEGER,
|
| 67 |
+
|
| 68 |
+
-- Outcomes
|
| 69 |
+
scenario_outcome TEXT,
|
| 70 |
+
profit_loss REAL,
|
| 71 |
+
portfolio_value_after REAL,
|
| 72 |
+
followed_ai BOOLEAN,
|
| 73 |
+
|
| 74 |
+
FOREIGN KEY (participant_id) REFERENCES participants(participant_id)
|
| 75 |
+
)
|
| 76 |
+
""")
|
| 77 |
+
|
| 78 |
+
conn.commit()
|
| 79 |
+
conn.close()
|
| 80 |
+
|
| 81 |
+
# Initialize DB on startup
|
| 82 |
+
init_database()
|
| 83 |
+
|
| 84 |
+
# ============================================================================
|
| 85 |
+
# SCENARIO DEFINITIONS
|
| 86 |
+
# ============================================================================
|
| 87 |
+
|
| 88 |
+
SCENARIOS = [
|
| 89 |
+
{
|
| 90 |
+
"id": "scenario_1",
|
| 91 |
+
"company": "Meridian Industries",
|
| 92 |
+
"country": "Republic of Valdoria",
|
| 93 |
+
"sector": "Manufacturing",
|
| 94 |
+
"current_price": 47.50,
|
| 95 |
+
"situation": """
|
| 96 |
+
Meridian Industries (MRD) is a mid-sized manufacturing company based in the Republic of Valdoria.
|
| 97 |
+
Their stock has been trading steadily at $47.50 for the past month.
|
| 98 |
+
|
| 99 |
+
**Recent News:**
|
| 100 |
+
- The Valdorian government announced potential new trade tariffs on imported raw materials
|
| 101 |
+
- Meridian's main competitor, Axon Corp, reported lower than expected quarterly earnings
|
| 102 |
+
- Industry analysts are divided on the sector's 6-month outlook
|
| 103 |
+
|
| 104 |
+
The market opens in 10 minutes. You currently hold 100 shares of MRD worth $4,750.
|
| 105 |
+
""",
|
| 106 |
+
"optimal_action": "HOLD", # Hidden - for scoring
|
| 107 |
+
"outcome_if_buy": -8.5, # Price change percentage
|
| 108 |
+
"outcome_if_sell": 3.2, # What they miss/avoid
|
| 109 |
+
"outcome_if_hold": 3.2, # Price actually goes up
|
| 110 |
+
"ai_is_accurate": True, # AI will recommend correct action
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"id": "scenario_2",
|
| 114 |
+
"company": "Northgate Pharmaceuticals",
|
| 115 |
+
"country": "Federation of Carinthia",
|
| 116 |
+
"sector": "Healthcare",
|
| 117 |
+
"current_price": 124.00,
|
| 118 |
+
"situation": """
|
| 119 |
+
Northgate Pharmaceuticals (NGP) is a healthcare company headquartered in the Federation of Carinthia.
|
| 120 |
+
Their stock currently trades at $124.00, up 12% over the past quarter.
|
| 121 |
+
|
| 122 |
+
**Recent News:**
|
| 123 |
+
- NGP's new drug treatment is awaiting regulatory approval (decision expected this week)
|
| 124 |
+
- The company's CEO made optimistic statements in a recent interview
|
| 125 |
+
- Two board members sold significant personal holdings last week
|
| 126 |
+
- Healthcare sector index has been volatile due to policy uncertainty
|
| 127 |
+
|
| 128 |
+
You have $10,000 available to invest. Do you want to buy NGP shares?
|
| 129 |
+
""",
|
| 130 |
+
"optimal_action": "SELL", # The insider selling is a red flag
|
| 131 |
+
"outcome_if_buy": -15.3,
|
| 132 |
+
"outcome_if_sell": 15.3, # Avoided loss
|
| 133 |
+
"outcome_if_hold": -15.3,
|
| 134 |
+
"ai_is_accurate": False, # AI will recommend WRONG action (BUY)
|
| 135 |
+
},
|
| 136 |
+
]
|
| 137 |
+
|
| 138 |
+
# ============================================================================
|
| 139 |
+
# AI ADVICE GENERATION
|
| 140 |
+
# ============================================================================
|
| 141 |
+
|
| 142 |
+
def generate_ai_advice(scenario: dict, confidence: int, explanation: int, risk: int) -> dict:
|
| 143 |
+
"""
|
| 144 |
+
Generate AI advice based on scenario and participant's AI tuning settings.
|
| 145 |
+
|
| 146 |
+
confidence: 0-100 (Cautious to Assertive)
|
| 147 |
+
explanation: 0-100 (Minimal to Detailed)
|
| 148 |
+
risk: 0-100 (Conservative to Aggressive)
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
# Determine what AI recommends (may be accurate or inaccurate based on scenario)
|
| 152 |
+
if scenario["ai_is_accurate"]:
|
| 153 |
+
recommended_action = scenario["optimal_action"]
|
| 154 |
+
else:
|
| 155 |
+
# Give wrong advice
|
| 156 |
+
wrong_actions = ["BUY", "SELL", "HOLD"]
|
| 157 |
+
wrong_actions.remove(scenario["optimal_action"])
|
| 158 |
+
recommended_action = random.choice(wrong_actions)
|
| 159 |
+
|
| 160 |
+
# Frame the confidence level
|
| 161 |
+
if confidence < 33:
|
| 162 |
+
confidence_frame = "might consider"
|
| 163 |
+
certainty_phrase = "There's some possibility that"
|
| 164 |
+
elif confidence < 66:
|
| 165 |
+
confidence_frame = "suggests"
|
| 166 |
+
certainty_phrase = "Analysis indicates that"
|
| 167 |
+
else:
|
| 168 |
+
confidence_frame = "strongly recommends"
|
| 169 |
+
certainty_phrase = "Strong signals suggest that"
|
| 170 |
+
|
| 171 |
+
# Build explanation based on depth setting
|
| 172 |
+
if explanation < 33:
|
| 173 |
+
reasoning = ""
|
| 174 |
+
elif explanation < 66:
|
| 175 |
+
reasoning = f"\n\nKey factor: Recent market movements in the {scenario['sector']} sector."
|
| 176 |
+
else:
|
| 177 |
+
reasoning = f"""
|
| 178 |
+
|
| 179 |
+
**Analysis Summary:**
|
| 180 |
+
- Sector trend: {scenario['sector']} showing mixed signals
|
| 181 |
+
- Geographic factors: {scenario['country']} market conditions considered
|
| 182 |
+
- Price momentum: Current price of ${scenario['current_price']:.2f} evaluated
|
| 183 |
+
- Risk assessment: {'Higher volatility expected' if risk > 50 else 'Moderate stability expected'}
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
# Risk framing affects the strength of recommendation
|
| 187 |
+
if risk < 33:
|
| 188 |
+
risk_note = "Given conservative risk parameters, position sizing should be minimal."
|
| 189 |
+
elif risk < 66:
|
| 190 |
+
risk_note = "Standard position sizing recommended."
|
| 191 |
+
else:
|
| 192 |
+
risk_note = "Aggressive positioning may maximize potential returns."
|
| 193 |
+
|
| 194 |
+
advice_text = f"""
|
| 195 |
+
**AI Trading Assistant Recommendation**
|
| 196 |
+
|
| 197 |
+
{certainty_phrase} you {confidence_frame} to **{recommended_action}** {scenario['company']} ({scenario['current_price']:.2f}).
|
| 198 |
+
{reasoning}
|
| 199 |
+
|
| 200 |
+
{risk_note if explanation > 50 else ''}
|
| 201 |
+
""".strip()
|
| 202 |
+
|
| 203 |
+
return {
|
| 204 |
+
"text": advice_text,
|
| 205 |
+
"direction": recommended_action,
|
| 206 |
+
"accuracy": "accurate" if scenario["ai_is_accurate"] else "inaccurate"
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
# ============================================================================
|
| 210 |
+
# GAME STATE MANAGEMENT
|
| 211 |
+
# ============================================================================
|
| 212 |
+
|
| 213 |
+
def create_new_session():
|
| 214 |
+
"""Create a new participant session."""
|
| 215 |
+
participant_id = str(uuid.uuid4())[:8].upper()
|
| 216 |
+
|
| 217 |
+
conn = sqlite3.connect(DB_PATH)
|
| 218 |
+
cursor = conn.cursor()
|
| 219 |
+
cursor.execute(
|
| 220 |
+
"INSERT INTO participants (participant_id) VALUES (?)",
|
| 221 |
+
(participant_id,)
|
| 222 |
+
)
|
| 223 |
+
conn.commit()
|
| 224 |
+
conn.close()
|
| 225 |
+
|
| 226 |
+
# Randomize scenario order
|
| 227 |
+
scenario_order = list(range(len(SCENARIOS)))
|
| 228 |
+
random.shuffle(scenario_order)
|
| 229 |
+
|
| 230 |
+
return {
|
| 231 |
+
"participant_id": participant_id,
|
| 232 |
+
"current_round": 0,
|
| 233 |
+
"scenario_order": scenario_order,
|
| 234 |
+
"portfolio_value": 10000.0,
|
| 235 |
+
"decisions": [],
|
| 236 |
+
"round_start_time": None,
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
def save_decision(state: dict, scenario: dict, ai_advice: dict,
|
| 240 |
+
decision: str, amount: float, confidence: int,
|
| 241 |
+
ai_conf: int, ai_expl: int, ai_risk: int):
|
| 242 |
+
"""Save a decision to the database."""
|
| 243 |
+
|
| 244 |
+
response_time = int((time.time() - state["round_start_time"]) * 1000)
|
| 245 |
+
|
| 246 |
+
# Calculate outcome
|
| 247 |
+
followed_ai = (decision == ai_advice["direction"])
|
| 248 |
+
|
| 249 |
+
if decision == "BUY":
|
| 250 |
+
outcome_pct = scenario["outcome_if_buy"]
|
| 251 |
+
elif decision == "SELL":
|
| 252 |
+
outcome_pct = scenario["outcome_if_sell"]
|
| 253 |
+
else:
|
| 254 |
+
outcome_pct = scenario["outcome_if_hold"]
|
| 255 |
+
|
| 256 |
+
profit_loss = (amount * outcome_pct / 100) if decision != "HOLD" else (state["portfolio_value"] * outcome_pct / 100)
|
| 257 |
+
new_portfolio = state["portfolio_value"] + profit_loss
|
| 258 |
+
|
| 259 |
+
# Determine outcome text
|
| 260 |
+
if profit_loss > 0:
|
| 261 |
+
outcome_text = f"Profit: +${profit_loss:.2f}"
|
| 262 |
+
elif profit_loss < 0:
|
| 263 |
+
outcome_text = f"Loss: -${abs(profit_loss):.2f}"
|
| 264 |
+
else:
|
| 265 |
+
outcome_text = "No change"
|
| 266 |
+
|
| 267 |
+
conn = sqlite3.connect(DB_PATH)
|
| 268 |
+
cursor = conn.cursor()
|
| 269 |
+
cursor.execute("""
|
| 270 |
+
INSERT INTO decisions (
|
| 271 |
+
participant_id, scenario_id, scenario_order,
|
| 272 |
+
ai_confidence_setting, ai_explanation_setting, ai_risk_setting,
|
| 273 |
+
scenario_text, ai_advice_text, ai_advice_direction, ai_advice_accuracy,
|
| 274 |
+
decision, decision_amount, confidence_in_decision, response_time_ms,
|
| 275 |
+
scenario_outcome, profit_loss, portfolio_value_after, followed_ai
|
| 276 |
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 277 |
+
""", (
|
| 278 |
+
state["participant_id"],
|
| 279 |
+
scenario["id"],
|
| 280 |
+
state["current_round"],
|
| 281 |
+
ai_conf, ai_expl, ai_risk,
|
| 282 |
+
scenario["situation"],
|
| 283 |
+
ai_advice["text"],
|
| 284 |
+
ai_advice["direction"],
|
| 285 |
+
ai_advice["accuracy"],
|
| 286 |
+
decision,
|
| 287 |
+
amount,
|
| 288 |
+
confidence,
|
| 289 |
+
response_time,
|
| 290 |
+
outcome_text,
|
| 291 |
+
profit_loss,
|
| 292 |
+
new_portfolio,
|
| 293 |
+
followed_ai
|
| 294 |
+
))
|
| 295 |
+
conn.commit()
|
| 296 |
+
conn.close()
|
| 297 |
+
|
| 298 |
+
return profit_loss, new_portfolio, outcome_text
|
| 299 |
+
|
| 300 |
+
def complete_session(state: dict):
|
| 301 |
+
"""Mark session as complete and calculate final metrics."""
|
| 302 |
+
|
| 303 |
+
conn = sqlite3.connect(DB_PATH)
|
| 304 |
+
cursor = conn.cursor()
|
| 305 |
+
|
| 306 |
+
# Calculate AI reliance score
|
| 307 |
+
cursor.execute("""
|
| 308 |
+
SELECT COUNT(*) as total, SUM(CASE WHEN followed_ai THEN 1 ELSE 0 END) as followed
|
| 309 |
+
FROM decisions WHERE participant_id = ?
|
| 310 |
+
""", (state["participant_id"],))
|
| 311 |
+
|
| 312 |
+
result = cursor.fetchone()
|
| 313 |
+
total, followed = result
|
| 314 |
+
ai_reliance = (followed / total * 100) if total > 0 else 0
|
| 315 |
+
|
| 316 |
+
cursor.execute("""
|
| 317 |
+
UPDATE participants
|
| 318 |
+
SET session_end = CURRENT_TIMESTAMP,
|
| 319 |
+
final_portfolio_value = ?,
|
| 320 |
+
total_decisions = ?,
|
| 321 |
+
ai_reliance_score = ?,
|
| 322 |
+
completed = TRUE
|
| 323 |
+
WHERE participant_id = ?
|
| 324 |
+
""", (state["portfolio_value"], total, ai_reliance, state["participant_id"]))
|
| 325 |
+
|
| 326 |
+
conn.commit()
|
| 327 |
+
conn.close()
|
| 328 |
+
|
| 329 |
+
return ai_reliance
|
| 330 |
+
|
| 331 |
+
# ============================================================================
|
| 332 |
+
# GRADIO INTERFACE
|
| 333 |
+
# ============================================================================
|
| 334 |
+
|
| 335 |
+
def start_game():
|
| 336 |
+
"""Initialize a new game session."""
|
| 337 |
+
state = create_new_session()
|
| 338 |
+
return (
|
| 339 |
+
state,
|
| 340 |
+
gr.update(visible=False), # Hide welcome
|
| 341 |
+
gr.update(visible=True), # Show game
|
| 342 |
+
gr.update(visible=False), # Hide results
|
| 343 |
+
f"**Participant ID:** {state['participant_id']}\n**Starting Portfolio:** ${state['portfolio_value']:,.2f}",
|
| 344 |
+
gr.update(visible=True), # Show tuning section
|
| 345 |
+
"", # Clear scenario
|
| 346 |
+
"", # Clear AI advice
|
| 347 |
+
gr.update(visible=False), # Hide decision section
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
def submit_tuning(state, ai_conf, ai_expl, ai_risk):
|
| 351 |
+
"""Process AI tuning and show scenario."""
|
| 352 |
+
if state is None:
|
| 353 |
+
return [None] * 7
|
| 354 |
+
|
| 355 |
+
# Get current scenario
|
| 356 |
+
scenario_idx = state["scenario_order"][state["current_round"]]
|
| 357 |
+
scenario = SCENARIOS[scenario_idx]
|
| 358 |
+
|
| 359 |
+
# Generate AI advice based on tuning
|
| 360 |
+
ai_advice = generate_ai_advice(scenario, ai_conf, ai_expl, ai_risk)
|
| 361 |
+
|
| 362 |
+
# Store for later
|
| 363 |
+
state["current_ai_advice"] = ai_advice
|
| 364 |
+
state["current_scenario"] = scenario
|
| 365 |
+
state["ai_settings"] = (ai_conf, ai_expl, ai_risk)
|
| 366 |
+
state["round_start_time"] = time.time()
|
| 367 |
+
|
| 368 |
+
return (
|
| 369 |
+
state,
|
| 370 |
+
gr.update(visible=False), # Hide tuning
|
| 371 |
+
f"## Round {state['current_round'] + 1} of {len(SCENARIOS)}\n\n### {scenario['company']} ({scenario['country']})\n\n{scenario['situation']}",
|
| 372 |
+
f"{ai_advice['text']}",
|
| 373 |
+
gr.update(visible=True), # Show decision section
|
| 374 |
+
gr.update(value=50), # Reset confidence slider
|
| 375 |
+
gr.update(value=5000), # Reset amount
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
def submit_decision(state, decision, amount, confidence):
|
| 379 |
+
"""Process trading decision and show outcome."""
|
| 380 |
+
if state is None or "current_scenario" not in state:
|
| 381 |
+
return [None] * 9
|
| 382 |
+
|
| 383 |
+
scenario = state["current_scenario"]
|
| 384 |
+
ai_advice = state["current_ai_advice"]
|
| 385 |
+
ai_conf, ai_expl, ai_risk = state["ai_settings"]
|
| 386 |
+
|
| 387 |
+
# Save decision and get outcome
|
| 388 |
+
profit_loss, new_portfolio, outcome_text = save_decision(
|
| 389 |
+
state, scenario, ai_advice, decision, amount, confidence,
|
| 390 |
+
ai_conf, ai_expl, ai_risk
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
# Update state
|
| 394 |
+
state["portfolio_value"] = new_portfolio
|
| 395 |
+
state["current_round"] += 1
|
| 396 |
+
|
| 397 |
+
# Check if game is over
|
| 398 |
+
if state["current_round"] >= len(SCENARIOS):
|
| 399 |
+
ai_reliance = complete_session(state)
|
| 400 |
+
|
| 401 |
+
return (
|
| 402 |
+
state,
|
| 403 |
+
gr.update(visible=False), # Hide game
|
| 404 |
+
gr.update(visible=True), # Show results
|
| 405 |
+
f"""
|
| 406 |
+
## Experiment Complete!
|
| 407 |
+
|
| 408 |
+
**Final Portfolio Value:** ${new_portfolio:,.2f}
|
| 409 |
+
|
| 410 |
+
**Your Results:**
|
| 411 |
+
- Starting Value: $10,000.00
|
| 412 |
+
- Final Value: ${new_portfolio:,.2f}
|
| 413 |
+
- Net Change: ${new_portfolio - 10000:+,.2f}
|
| 414 |
+
- AI Reliance Score: {ai_reliance:.1f}%
|
| 415 |
+
|
| 416 |
+
**Thank you for participating!**
|
| 417 |
+
|
| 418 |
+
Your Participant ID: **{state['participant_id']}**
|
| 419 |
+
|
| 420 |
+
*Please record this ID if requested by the researcher.*
|
| 421 |
+
""",
|
| 422 |
+
"", # Clear status
|
| 423 |
+
"", # Clear scenario
|
| 424 |
+
"", # Clear AI advice
|
| 425 |
+
gr.update(visible=False), # Hide decision
|
| 426 |
+
gr.update(visible=False), # Hide tuning
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
# Continue to next round
|
| 430 |
+
return (
|
| 431 |
+
state,
|
| 432 |
+
gr.update(visible=True), # Keep game visible
|
| 433 |
+
gr.update(visible=False), # Keep results hidden
|
| 434 |
+
"", # Clear results
|
| 435 |
+
f"**Participant ID:** {state['participant_id']}\n**Portfolio:** ${new_portfolio:,.2f}\n\n**Last Round:** {outcome_text}",
|
| 436 |
+
"", # Clear scenario for now
|
| 437 |
+
"", # Clear AI advice
|
| 438 |
+
gr.update(visible=False), # Hide decision
|
| 439 |
+
gr.update(visible=True), # Show tuning for next round
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
# Build the interface
|
| 443 |
+
with gr.Blocks(title="AI Trading Trust Experiment") as demo:
|
| 444 |
+
|
| 445 |
+
# State management
|
| 446 |
+
game_state = gr.State(None)
|
| 447 |
+
|
| 448 |
+
gr.Markdown("# π AI Trading Experiment")
|
| 449 |
+
|
| 450 |
+
# Welcome screen
|
| 451 |
+
with gr.Column(visible=True) as welcome_section:
|
| 452 |
+
gr.Markdown("""
|
| 453 |
+
## Welcome to the Trading Simulation
|
| 454 |
+
|
| 455 |
+
In this experiment, you will make a series of trading decisions with the help of an AI assistant.
|
| 456 |
+
|
| 457 |
+
**How it works:**
|
| 458 |
+
1. Before each trading scenario, you can adjust how the AI advisor behaves
|
| 459 |
+
2. You'll see market information and receive AI-generated advice
|
| 460 |
+
3. Make your trading decision (Buy, Sell, or Hold)
|
| 461 |
+
4. Rate your confidence in your decision
|
| 462 |
+
|
| 463 |
+
**Your goal:** Maximize your portfolio value through smart trading decisions.
|
| 464 |
+
|
| 465 |
+
*All companies and countries in this simulation are entirely fictional.*
|
| 466 |
+
|
| 467 |
+
---
|
| 468 |
+
|
| 469 |
+
**By clicking Start, you consent to participate in this research study.**
|
| 470 |
+
""")
|
| 471 |
+
start_btn = gr.Button("π Start Experiment", variant="primary", size="lg")
|
| 472 |
+
|
| 473 |
+
# Main game area
|
| 474 |
+
with gr.Column(visible=False) as game_section:
|
| 475 |
+
status_display = gr.Markdown("")
|
| 476 |
+
|
| 477 |
+
# AI Tuning Section
|
| 478 |
+
with gr.Column(visible=True) as tuning_section:
|
| 479 |
+
gr.Markdown("### Configure Your AI Advisor")
|
| 480 |
+
gr.Markdown("*Adjust these settings to customize how the AI presents its advice:*")
|
| 481 |
+
|
| 482 |
+
with gr.Row():
|
| 483 |
+
ai_confidence = gr.Slider(
|
| 484 |
+
minimum=0, maximum=100, value=50, step=1,
|
| 485 |
+
label="AI Confidence Level",
|
| 486 |
+
info="Cautious (0) β Assertive (100)"
|
| 487 |
+
)
|
| 488 |
+
ai_explanation = gr.Slider(
|
| 489 |
+
minimum=0, maximum=100, value=50, step=1,
|
| 490 |
+
label="Explanation Depth",
|
| 491 |
+
info="Minimal (0) β Detailed (100)"
|
| 492 |
+
)
|
| 493 |
+
ai_risk = gr.Slider(
|
| 494 |
+
minimum=0, maximum=100, value=50, step=1,
|
| 495 |
+
label="Risk Tolerance",
|
| 496 |
+
info="Conservative (0) β Aggressive (100)"
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
confirm_tuning_btn = gr.Button("Confirm AI Settings & View Scenario", variant="primary")
|
| 500 |
+
|
| 501 |
+
# Scenario Display
|
| 502 |
+
scenario_display = gr.Markdown("")
|
| 503 |
+
|
| 504 |
+
# AI Advice Display
|
| 505 |
+
ai_advice_display = gr.Markdown("")
|
| 506 |
+
|
| 507 |
+
# Decision Section
|
| 508 |
+
with gr.Column(visible=False) as decision_section:
|
| 509 |
+
gr.Markdown("### Your Decision")
|
| 510 |
+
|
| 511 |
+
with gr.Row():
|
| 512 |
+
decision_choice = gr.Radio(
|
| 513 |
+
choices=["BUY", "HOLD", "SELL"],
|
| 514 |
+
label="What do you want to do?",
|
| 515 |
+
value="HOLD"
|
| 516 |
+
)
|
| 517 |
+
decision_amount = gr.Slider(
|
| 518 |
+
minimum=0, maximum=10000, value=5000, step=100,
|
| 519 |
+
label="Amount ($)",
|
| 520 |
+
info="How much to trade (if buying/selling)"
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
confidence_slider = gr.Slider(
|
| 524 |
+
minimum=0, maximum=100, value=50, step=1,
|
| 525 |
+
label="How confident are you in this decision?",
|
| 526 |
+
info="Not at all confident (0) β Extremely confident (100)"
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
submit_decision_btn = gr.Button("Submit Decision", variant="primary", size="lg")
|
| 530 |
+
|
| 531 |
+
# Results screen
|
| 532 |
+
with gr.Column(visible=False) as results_section:
|
| 533 |
+
results_display = gr.Markdown("")
|
| 534 |
+
restart_btn = gr.Button("Start New Session", variant="secondary")
|
| 535 |
+
|
| 536 |
+
# Event handlers
|
| 537 |
+
start_btn.click(
|
| 538 |
+
start_game,
|
| 539 |
+
inputs=[],
|
| 540 |
+
outputs=[
|
| 541 |
+
game_state, welcome_section, game_section, results_section,
|
| 542 |
+
status_display, tuning_section, scenario_display, ai_advice_display, decision_section
|
| 543 |
+
]
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
confirm_tuning_btn.click(
|
| 547 |
+
submit_tuning,
|
| 548 |
+
inputs=[game_state, ai_confidence, ai_explanation, ai_risk],
|
| 549 |
+
outputs=[
|
| 550 |
+
game_state, tuning_section, scenario_display, ai_advice_display,
|
| 551 |
+
decision_section, confidence_slider, decision_amount
|
| 552 |
+
]
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
submit_decision_btn.click(
|
| 556 |
+
submit_decision,
|
| 557 |
+
inputs=[game_state, decision_choice, decision_amount, confidence_slider],
|
| 558 |
+
outputs=[
|
| 559 |
+
game_state, game_section, results_section, results_display,
|
| 560 |
+
status_display, scenario_display, ai_advice_display, decision_section, tuning_section
|
| 561 |
+
]
|
| 562 |
+
)
|
| 563 |
+
|
| 564 |
+
restart_btn.click(
|
| 565 |
+
start_game,
|
| 566 |
+
inputs=[],
|
| 567 |
+
outputs=[
|
| 568 |
+
game_state, welcome_section, game_section, results_section,
|
| 569 |
+
status_display, tuning_section, scenario_display, ai_advice_display, decision_section
|
| 570 |
+
]
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
# Launch
|
| 574 |
+
if __name__ == "__main__":
|
| 575 |
+
demo.launch()
|