| import os |
| import streamlit as st |
| import google.generativeai as genai |
| import random |
| import time |
| import pandas as pd |
| from datetime import date |
| import plotly.express as px |
|
|
| |
| st.set_page_config( |
| page_title="Elementary Stock Market Game (US Stocks)", |
| page_icon="π°", |
| layout="wide", |
| initial_sidebar_state="expanded", |
| ) |
|
|
| |
| st.markdown( |
| """ |
| <style> |
| /* μ 체 ν°νΈ λ³κ²½ (Nanum Gothic, Google Fonts CDN μ¬μ©) */ |
| @import url('https://fonts.googleapis.com/css2?family=Nanum+Gothic:wght@400;700&display=swap'); |
| body { |
| font-family: 'Nanum Gothic', sans-serif !important; |
| } |
| |
| /* ν λ©λ΄ μ€νμΌ */ |
| .stTabs [data-baseweb="tab-list"] button[aria-selected="true"] { |
| background-color: #007bff !important; |
| color: white !important; |
| font-weight: bold; |
| } |
| .stTabs [data-baseweb="tab-list"] button { |
| background-color: #f0f2f6; |
| color: #333; |
| border-radius: 8px 8px 0 0; |
| padding: 0.75em 1em; |
| margin-bottom: -1px; /* border overlap */ |
| } |
| |
| /* μ¬μ΄λλ° μ€νμΌ */ |
| [data-testid="stSidebar"] { |
| width: 350px !important; |
| background-color: #f8f9fa; /* Light gray sidebar background */ |
| padding: 20px; |
| } |
| [data-testid="stSidebar"] h1, [data-testid="stSidebar"] h3 { |
| color: #212529; /* Dark gray sidebar headings */ |
| } |
| [data-testid="stSidebar"] hr { |
| border-top: 1px solid #e0e0e0; /* Lighter sidebar hr */ |
| } |
| |
| /* Metric μ€νμΌ */ |
| .streamlit-metric-label { |
| font-size: 16px; |
| color: #4a4a4a; |
| } |
| .streamlit-metric-value { |
| font-size: 28px; |
| font-weight: bold; |
| } |
| |
| /* λ²νΌ μ€νμΌ */ |
| div.stButton > button { |
| background-color: #007bff; |
| color: white; |
| padding: 12px 24px; |
| font-size: 16px; |
| border-radius: 8px; |
| border: none; |
| box-shadow: 2px 2px 5px rgba(0,0,0,0.1); /* Soft shadow */ |
| transition: background-color 0.3s ease; |
| } |
| div.stButton > button:hover { |
| background-color: #0056b3; |
| box-shadow: 2px 2px 7px rgba(0,0,0,0.15); /* Slightly stronger shadow on hover */ |
| } |
| |
| /* 보쑰 λ²νΌ μ€νμΌ */ |
| div.stButton > button.secondary-button { |
| background-color: #6c757d; |
| color: white; |
| padding: 10px 20px; |
| font-size: 14px; |
| border-radius: 6px; |
| border: none; |
| transition: background-color 0.3s ease; |
| } |
| div.stButton > button.secondary-button:hover { |
| background-color: #5a6268; |
| } |
| |
| /* Expander μ€νμΌ */ |
| .streamlit-expanderHeader { |
| font-weight: bold; |
| color: #212529; |
| border-bottom: 1px solid #e0e0e0; |
| padding-bottom: 8px; |
| margin-bottom: 15px; |
| } |
| |
| /* Dataframe μ€νμΌ */ |
| .dataframe { |
| border: 1px solid #e0e0e0; |
| border-radius: 8px; |
| padding: 12px; |
| box-shadow: 2px 2px 5px rgba(0,0,0,0.05); /* Very subtle shadow */ |
| } |
| |
| /* Info, Success, Error, Warning Box μ€νμΌ (λ λΆλλ¬μ΄ μ€νμΌ) */ |
| div.stInfo, div.stSuccess, div.stError, div.stWarning { |
| border-radius: 8px; |
| padding: 15px; |
| margin-bottom: 15px; |
| box-shadow: 2px 2px 5px rgba(0,0,0,0.05); |
| } |
| div.stInfo { |
| background-color: #e7f3ff; |
| border-left: 5px solid #007bff; |
| } |
| div.stSuccess { |
| background-color: #e6f7ec; |
| border-left: 5px solid #28a745; |
| } |
| div.stError { |
| background-color: #fdeded; |
| border-left: 5px solid #dc3545; |
| } |
| div.stWarning { |
| background-color: #fffbe6; |
| border-left: 5px solid #ffc107; |
| } |
| |
| /* Toast message μ€νμΌ */ |
| div.streamlit-toast-container { |
| z-index: 10000; /* Toastλ₯Ό νμ 맨 μμ νμ */ |
| } |
| div[data-testid="stToast"] { |
| border-radius: 8px; |
| padding: 15px; |
| box-shadow: 2px 2px 5px rgba(0,0,0,0.1); |
| } |
| |
| </style> |
| """, |
| unsafe_allow_html=True, |
| ) |
|
|
|
|
| |
| if "GEMINI_API_KEY" not in os.environ: |
| st.error( |
| "GEMINI_API_KEY environment variable is not set. Please set your API key in Hugging Face Secrets or environment variables." |
| ) |
| st.stop() |
|
|
| genai.configure(api_key=os.environ["GEMINI_API_KEY"]) |
|
|
| |
| generation_config = { |
| "temperature": 0.7, |
| "top_p": 0.95, |
| "top_k": 64, |
| "max_output_tokens": 25000, |
| "response_mime_type": "text/plain", |
| } |
| model = genai.GenerativeModel( |
| model_name="gemini-2.0-flash-exp", |
| generation_config=generation_config, |
| ) |
|
|
| |
| if "chat_session" not in st.session_state: |
| st.session_state["chat_session"] = model.start_chat(history=[]) |
| if "portfolio" not in st.session_state: |
| st.session_state["portfolio"] = {"cash": 10000.00, "stocks": {}} |
| if "stocks" not in st.session_state: |
| st.session_state["stocks"] = { |
| "Technology": { |
| "AAPL": { |
| "current_price": round(random.uniform(170, 250), 2), |
| "price_history": [], |
| "description": "Apple is the company that makes iPhones, iPads, Mac computers, and Apple Watches! They are famous for making products that are easy to use, look super cool, and work really well together. Think about all the apps and games you play on your phone β many of them are made for Apple devices. Apple is one of the most valuable companies in the world because so many people love their products!", |
| }, |
| "MSFT": { |
| "current_price": round(random.uniform(420, 550), 2), |
| "price_history": [], |
| "description": "Microsoft is the company behind Windows computers that many people use at home and school. They also make the Xbox gaming console for fun video games and lots of software programs like Microsoft Word and PowerPoint that help people do work and school projects. Microsoft is a giant in the tech world, helping people be productive and entertained with technology!", |
| }, |
| "GOOGL": { |
| "current_price": round(random.uniform(170, 280), 2), |
| "price_history": [], |
| "description": "Google is how you search for things on the internet! Their search engine helps you find information about anything you're curious about. Google also owns YouTube, where you watch videos, and Android, the system that powers many smartphones. Plus, they are working on cool new things like self-driving cars and making computers smarter with artificial intelligence. Google's mission is to organize all the information in the world and make it useful for everyone!", |
| }, |
| "NVDA": { |
| "current_price": round(random.uniform(90, 180), 2), |
| "price_history": [], |
| "description": "NVIDIA makes super powerful graphics cards that make video games look incredibly realistic and movies have amazing special effects. But it's not just for games! NVIDIA's technology is also super important for artificial intelligence (AI), which is making computers think more like humans, and for self-driving cars to see and understand the road. NVIDIA's chips are like the brains behind many of the newest and coolest technologies!", |
| }, |
| "TSM": { |
| "current_price": round(random.uniform(160, 220), 2), |
| "price_history": [], |
| "description": "Taiwan Semiconductor Manufacturing Company, or TSMC, is like a factory for computer chips. They don't design their own chips, but they make them for lots of other big tech companies like Apple and NVIDIA. Think of them as the world's best chip-making experts! Without TSMC, many of the smartphones, computers, and game consoles we use wouldn't be possible. They are super important to the global technology industry!", |
| }, |
| "INTC": { |
| "current_price": round(random.uniform(30, 50), 2), |
| "price_history": [], |
| "description": "Intel is famous for making computer processors, which are like the brains inside most computers. If you have a laptop or desktop, it probably has an Intel chip inside that makes it run. Intel has been making chips for a very long time and is a pioneer in computer technology. They are always working on making chips faster and more powerful so computers can do even more!", |
| }, |
| }, |
| "Automotive": { |
| "TSLA": { |
| "current_price": round(random.uniform(170, 280), 2), |
| "price_history": [], |
| "description": "Tesla is all about electric cars and clean energy! They make cars that run on electricity instead of gasoline, which is better for the environment. Tesla cars are known for being super fast, having cool technology like self-driving features, and looking very modern. Tesla also makes solar panels to power homes with sunlight and batteries to store energy. They are leading the way in changing how we drive and use energy!", |
| }, |
| "GM": { |
| "current_price": round(random.uniform(50, 70), 2), |
| "price_history": [], |
| "description": "General Motors, or GM, makes lots of different kinds of cars under brands like Chevrolet, Cadillac, Buick, and GMC. You've probably seen Chevy trucks or Cadillac SUVs on the road! GM has been making cars for over 100 years and sells them all over the world. They are now also working hard to make more electric cars and develop self-driving technology for the future of driving.", |
| }, |
| "F": { |
| "current_price": round(random.uniform(12, 20), 2), |
| "price_history": [], |
| "description": "Ford is another really old and famous car company, known for making Ford cars and trucks and luxury Lincoln cars. The Ford Mustang and Ford F-150 truck are American icons! Ford is building electric versions of their popular trucks and SUVs and is investing in new technologies to make cars safer and more connected. Ford is a big part of American history and is still shaping the future of cars.", |
| }, |
| "TM": { |
| "current_price": round(random.uniform(190, 250), 2), |
| "price_history": [], |
| "description": "Toyota Motor is a Japanese company that makes Toyota and Lexus cars. Toyota is famous for making cars that are very reliable and last a long time. The Toyota Camry and Corolla are some of the best-selling cars in the world. Toyota is also a leader in hybrid cars that use both gasoline and electricity to save fuel and reduce pollution. Toyota is known for quality and making cars that people can depend on.", |
| }, |
| "HMC": { |
| "current_price": round(random.uniform(35, 50), 2), |
| "price_history": [], |
| "description": "Honda Motor is another Japanese company that makes Honda cars, motorcycles, and even robots! Honda cars are known for being fuel-efficient and fun to drive. The Honda Civic and Accord are very popular cars. Honda also makes robots and is exploring new technologies like flying cars. Honda is known for its engineering and making vehicles that are both practical and exciting.", |
| }, |
| }, |
| "Energy": { |
| "XOM": { |
| "current_price": round(random.uniform(110, 150), 2), |
| "price_history": [], |
| "description": "ExxonMobil is one of the biggest oil and gas companies in the world. They find oil and gas underground and under the sea, then they refine it to make gasoline for cars, fuel for airplanes, and heating oil for homes. Oil and gas are still a major source of energy for the world, and ExxonMobil plays a huge role in providing it. They are also starting to invest in cleaner energy technologies for the future.", |
| }, |
| "CVX": { |
| "current_price": round(random.uniform(160, 220), 2), |
| "price_history": [], |
| "description": "Chevron is another giant oil and gas company, similar to ExxonMobil. They explore for oil and gas, refine it into gasoline and other fuels, and sell it at gas stations and to industries. Chevron provides energy that powers transportation, industries, and homes around the globe. They are also working on developing cleaner energy sources alongside their traditional oil and gas business.", |
| }, |
| "NEE": { |
| "current_price": round(random.uniform(70, 100), 2), |
| "price_history": [], |
| "description": "NextEra Energy is different from oil companies because they focus on clean, renewable energy like solar and wind power. They build and operate solar farms and wind turbines that generate electricity without burning fossil fuels. As people want cleaner energy, companies like NextEra are becoming more and more important. They are helping to power our world in a way that's better for the planet.", |
| }, |
| "SHEL": { |
| "current_price": round(random.uniform(65, 90), 2), |
| "price_history": [], |
| "description": "Shell is a global energy company that's been around for a long time. They are involved in oil and gas, but they are also investing more and more in renewable energy like wind and solar power. Shell provides fuel for cars and airplanes, and energy for homes and businesses worldwide. As the world changes, Shell is trying to become a cleaner energy company for the future.", |
| }, |
| "BP": { |
| "current_price": round(random.uniform(35, 60), 2), |
| "price_history": [], |
| "description": "BP, or British Petroleum, is another major energy company, similar to ExxonMobil and Chevron. They find, produce, and sell oil and gas. Like other big energy companies, BP is also investing in renewable energy and trying to reduce their impact on the environment. BP gas stations are familiar to many drivers, and they are a big part of the global energy supply.", |
| }, |
| }, |
| "Internet & E-commerce": { |
| "AMZN": { |
| "current_price": round(random.uniform(3100, 4500), 2), |
| "price_history": [], |
| "description": "Amazon started as a place to buy books online, but now you can buy almost anything on Amazon! They are the biggest online store in the world, selling everything from toys to clothes to groceries. Amazon is also a huge technology company with cloud computing services that power many websites and apps. And they have their own delivery service to get your orders to you fast. Amazon has changed the way people shop and use the internet!", |
| }, |
| "META": { |
| "current_price": round(random.uniform(470, 650), 2), |
| "price_history": [], |
| "description": "Meta is the company that owns Facebook, Instagram, and WhatsApp β apps that billions of people use to connect with friends and family, share photos and videos, and chat. Meta is all about connecting people through social media. They are also exploring new technologies like virtual reality and the metaverse, which could change how we interact online in the future. Meta's apps are a big part of how people communicate and share their lives today.", |
| }, |
| "EBAY": { |
| "current_price": round(random.uniform(50, 80), 2), |
| "price_history": [], |
| "description": "eBay is like a giant online auction and marketplace where people can buy and sell almost anything. You can find used or new items, collectibles, clothes, electronics, even cars on eBay. It's a place where individuals and businesses can connect to buy and sell goods. eBay was one of the first big online marketplaces and is still a popular place to find deals and unique items.", |
| }, |
| "MELI": { |
| "current_price": round(random.uniform(1600, 2500), 2), |
| "price_history": [], |
| "description": "MercadoLibre is often called the 'Amazon of Latin America' because it's the biggest online marketplace in South America. People in countries like Brazil and Argentina use MercadoLibre to buy and sell products online, just like people use Amazon in the US. MercadoLibre also has a payment service called Mercado Pago, similar to PayPal, and a shipping service. They are making online shopping easier and more popular in Latin America.", |
| }, |
| "PDD": { |
| "current_price": round(random.uniform(90, 150), 2), |
| "price_history": [], |
| "description": "Pinduoduo is a huge online shopping company in China. It's a bit different from Amazon because it focuses on group buying and social shopping. People can get discounts by buying together with friends or sharing deals on social media. Pinduoduo is especially popular in China for buying groceries and agricultural products directly from farmers. They have made online shopping more social and affordable for many", |
| }, |
| "JD": { |
| "current_price": round(random.uniform(45, 70), 2), |
| "price_history": [], |
| "description": "JD.com is another massive online retailer in China, competing with companies like Alibaba and Pinduoduo. JD.com is known for its fast and reliable delivery service, and for selling high-quality products, especially electronics and appliances. They have their own warehouses and delivery network to make sure orders arrive quickly. JD.com is a major force in online retail in China and is expanding its reach globally.", |
| }, |
| }, |
| "Consumer Goods": { |
| "PG": { |
| "current_price": round(random.uniform(140, 190), 2), |
| "price_history": [], |
| "description": "Procter & Gamble, or P&G, makes tons of everyday products that families use all the time! Think of brands like Pampers diapers, Tide laundry detergent, Crest toothpaste, and Gillette razors. P&G makes products for cleaning, personal care, and health. Their brands are found in homes around the world, making them a very stable and reliable company.", |
| }, |
| "KO": { |
| "current_price": round(random.uniform(55, 80), 2), |
| "price_history": [], |
| "description": "Coca-Cola is famous for its fizzy drinks like Coca-Cola, Sprite, and Fanta. The red and white Coca-Cola logo is recognized everywhere! Coca-Cola drinks are sold in almost every country in the world. They also own lots of other drink brands, including juices and bottled water. Coca-Cola is a classic and iconic brand that brings refreshment to billions of people.", |
| }, |
| "PEP": { |
| "current_price": round(random.uniform(160, 220), 2), |
| "price_history": [], |
| "description": "PepsiCo is a food and beverage giant that makes Pepsi soda, but also lots of snacks like Lay's potato chips, Doritos, and Quaker Oats oatmeal. PepsiCo has a huge range of drinks and food products that people enjoy every day. They compete directly with Coca-Cola in drinks and with companies like Frito-Lay in snacks. PepsiCo is a major player in the food and beverage industry.", |
| }, |
| "CL": { |
| "current_price": round(random.uniform(70, 100), 2), |
| "price_history": [], |
| "description": "Colgate-Palmolive makes products for your mouth, body, and home! They are most famous for Colgate toothpaste and toothbrushes, but they also make Palmolive soap, Softsoap, and Hill's pet food for cats and dogs. Colgate-Palmolive focuses on making products that help people stay clean, healthy, and take care of their pets. Their brands are trusted by families worldwide.", |
| }, |
| "UL": { |
| "current_price": round(random.uniform(50, 75), 2), |
| "price_history": [], |
| "description": "Unilever is another huge consumer goods company, similar to Procter & Gamble. They make food, drinks, cleaning products, and personal care items. Brands like Dove soap, Lipton tea, Ben & Jerry's ice cream, and Hellmann's mayonnaise are all owned by Unilever. They have a massive portfolio of brands that people use and eat every day around the world.", |
| }, |
| "KHC": { |
| "current_price": round(random.uniform(35, 55), 2), |
| "price_history": [], |
| "description": "Kraft Heinz is a food company that makes many well-known food brands you might have in your kitchen. Think of Heinz ketchup, Kraft Mac & Cheese, Oscar Mayer hot dogs, and Jell-O. Kraft Heinz focuses on packaged foods that are convenient and popular with families. They are one of the largest food companies in North America.", |
| }, |
| }, |
| "Finance": { |
| "JPM": { |
| "current_price": round(random.uniform(150, 200), 2), |
| "price_history": [], |
| "description": "JPMorgan Chase is one of the biggest banks in the United States. They help people manage their money by offering bank accounts, credit cards, loans for houses and cars, and investment services. JPMorgan Chase also works with big businesses, helping them raise money and manage their finances. Banks like JPMorgan Chase are essential to how money flows in the economy.", |
| }, |
| "BAC": { |
| "current_price": round(random.uniform(30, 50), 2), |
| "price_history": [], |
| "description": "Bank of America is another giant bank in the US, just like JPMorgan Chase. They provide similar services to individuals and businesses, including bank accounts, loans, credit cards, and investment advice. Bank of America has branches and ATMs all over the country, making it easy for people to access their money. Banks like Bank of America are a key part of the financial system.", |
| }, |
| "V": { |
| "current_price": round(random.uniform(220, 300), 2), |
| "price_history": [], |
| "description": "Visa is a credit card company, but they don't lend you money directly. Instead, Visa's network processes payments when you use a Visa credit or debit card at stores or online. When you swipe or tap your card, Visa makes sure the money goes from your bank to the store's bank. Visa's payment network is used all over the world, making it easy to pay for things with cards.", |
| }, |
| "BRK-B": { |
| "current_price": round(random.uniform(300, 450), 2), |
| "price_history": [], |
| "description": "Berkshire Hathaway is not a typical company because it owns many other companies! It's like a holding company run by the famous investor Warren Buffett. Berkshire Hathaway owns companies in insurance (like GEICO), energy, railroads, food (like Dairy Queen), and many other industries. They are known for making smart investments and owning great businesses.", |
| }, |
| "GS": { |
| "current_price": round(random.uniform(350, 500), 2), |
| "price_history": [], |
| "description": "Goldman Sachs is a big investment bank. They work with large companies and governments, helping them with things like mergers (when companies join together), acquisitions (when one company buys another), and raising money by selling stocks or bonds. Investment banks like Goldman Sachs play a key role in helping businesses grow and the economy develop.", |
| }, |
| "MS": { |
| "current_price": round(random.uniform(80, 120), 2), |
| "price_history": [], |
| "description": "Morgan Stanley is another major investment bank, similar to Goldman Sachs. They also provide investment banking services to companies and governments, but they also have a big wealth management business that helps individuals manage their investments. Morgan Stanley helps both big organizations and individual people with their financial needs and investments.", |
| }, |
| }, |
| "Home Improvement & Construction": { |
| "HD": { |
| "current_price": round(random.uniform(300, 400), 2), |
| "price_history": [], |
| "description": "Home Depot is the biggest home improvement store in the US. If you need tools, paint, lumber, appliances, or anything to fix up your house or garden, Home Depot is the place to go. They sell products to homeowners and also to professional builders. Home Depot stores are huge and have almost everything you need for home projects.", |
| }, |
| "LOW": { |
| "current_price": round(random.uniform(200, 280), 2), |
| "price_history": [], |
| "description": "Lowe's is another big home improvement store, competing directly with Home Depot. They sell similar products for home ΡΠ΅ΠΌΠΎΠ½ΡΠ° and construction, including tools, building materials, garden supplies, and appliances. Homeowners and contractors shop at Lowe's for their project needs. Lowe's and Home Depot are the two biggest players in the home improvement retail market.", |
| }, |
| "CAT": { |
| "current_price": round(random.uniform(230, 350), 2), |
| "price_history": [], |
| "description": "Caterpillar makes giant machines used for construction, mining, and farming. Think of bulldozers, excavators, tractors, and big trucks. Caterpillar's heavy machinery is used to build roads, dig mines, construct buildings, and farm land all over the world. They are a leader in heavy equipment and their machines are essential for big projects.", |
| }, |
| "SHW": { |
| "current_price": round(random.uniform(250, 380), 2), |
| "price_history": [], |
| "description": "Sherwin-Williams is all about paint and coatings! They make paints for houses, buildings, cars, and lots of other things. If you see a house being painted, it could very well be with Sherwin-Williams paint. They are a leader in paint technology and have stores where you can get paint mixed to just the right color. Sherwin-Williams helps make the world more colorful and protected.", |
| }, |
| "LEN": { |
| "current_price": round(random.uniform(110, 180), 2), |
| "price_history": [], |
| "description": "Lennar Corporation is one of the biggest home builders in the United States. They build new houses and communities for people to live in. If you drive through a new neighborhood being built, Lennar might be the company building those houses. Home builders like Lennar play a big role in providing housing for families and shaping how cities grow.", |
| }, |
| "DHI": { |
| "current_price": round(random.uniform(100, 160), 2), |
| "price_history": [], |
| "description": "D.R. Horton is another very large home building company in the US, competing with Lennar. They also build new houses and communities across the country. D.R. Horton builds homes for different types of buyers, from first-time homeowners to people looking for larger houses. Home building companies like D.R. Horton are important for the housing market and the economy.", |
| }, |
| }, |
| "Retail": { |
| "WMT": { |
| "current_price": round(random.uniform(140, 200), 2), |
| "price_history": [], |
| "description": "Walmart is the biggest retailer in the world! They have huge stores where you can buy almost anything β groceries, clothes, toys, electronics, furniture, and much more. Walmart is known for having low prices and lots of locations, making it a convenient place for people to shop for everyday needs. Millions of people shop at Walmart every day.", |
| }, |
| "COST": { |
| "current_price": round(random.uniform(550, 750), 2), |
| "price_history": [], |
| "description": "Costco is a membership warehouse store. To shop at Costco, you need to pay a yearly membership fee. But once you're a member, you can buy items in bulk at lower prices than regular stores. Costco sells groceries, electronics, furniture, and even tires! They are known for their large sizes and good deals, especially for families and businesses.", |
| }, |
| "TGT": { |
| "current_price": round(random.uniform(170, 250), 2), |
| "price_history": [], |
| "description": "Target is a popular store that sells clothes, home goods, groceries, and toys, but with a focus on trendy styles and designs. Target is known for being a bit more stylish than Walmart, with exclusive designer collaborations and a fun shopping experience. Many people like to shop at Target for clothes, home decor, and gifts because it's fashionable and affordable.", |
| }, |
| "HD": { |
| "current_price": round(random.uniform(300, 450), 2), |
| "price_history": [], |
| "description": "Home Depot, besides being a home improvement store, is also a big retailer of appliances, garden supplies, and even some home decor items. Many people shop at Home Depot not just for ΡΠ΅ΠΌΠΎΠ½ΡΠ° projects, but also for things like refrigerators, washing machines, grills, and plants. Their retail side makes them a major player in the overall retail market.", |
| }, |
| "AMZN": { |
| "current_price": round(random.uniform(3100, 4500), 2), |
| "price_history": [], |
| "description": "Amazon, while being a tech company, is also the largest online retailer in the world. Most of Amazon's business comes from selling products online to customers. They are a massive force in retail, changing how people shop and delivering products directly to homes. Amazon's e-commerce platform is a dominant part of the retail landscape.", |
| }, |
| "KR": { |
| "current_price": round(random.uniform(45, 70), 2), |
| "price_history": [], |
| "description": "Kroger is one of the largest supermarket chains in the United States. They operate grocery stores under different names like Kroger, Ralphs, and Fred Meyer. Kroger stores sell groceries, produce, meat, dairy, and household items. They are a major provider of food and essential goods for communities across the country. Supermarkets like Kroger are where many people buy their groceries each week.", |
| }, |
| }, |
| "Telecom & Media": |
| { |
| "VZ": { |
| "current_price": round(random.uniform(50, 70), 2), |
| "price_history": [], |
| "description": "Verizon is a telecommunications company that provides cell phone service and home internet to millions of people in the US. When you use your smartphone to make calls, text, or use the internet, you might be using Verizon's network. Verizon is one of the biggest wireless carriers in the country, keeping people connected.", |
| }, |
| "T": { |
| "current_price": round(random.uniform(25, 40), 2), |
| "price_history": [], |
| "description": "AT&T is another major telecommunications company, similar to Verizon. They also provide cell phone service, home internet, and TV services. AT&T has been around for a very long time and is one of the oldest telecom companies in the US. They keep people connected through phone calls, internet access, and entertainment.", |
| }, |
| "CMCSA": { |
| "current_price": round(random.uniform(45, 65), 2), |
| "price_history": [], |
| "description": "Comcast is a media and telecommunications company. They own NBCUniversal, which makes movies and TV shows, and Xfinity, which provides cable TV, internet, and phone services. If you watch NBC on TV or use Xfinity internet, you are using Comcast's services. They bring entertainment and communication to homes across the country.", |
| }, |
| "DIS": { |
| "current_price": round(random.uniform(170, 250), 2), |
| "price_history": [], |
| "description": "Disney is a huge entertainment and media company, famous for Disney movies, Disney+ streaming, Disneyland theme parks, and TV channels like ESPN and ABC. Disney creates movies like Frozen and Toy Story, theme parks where you can meet Mickey Mouse, and TV shows for all ages. Disney is all about creating magical experiences and entertainment for families around the world.", |
| }, |
| "NFLX": { |
| "current_price": round(random.uniform(500, 750), 2), |
| "price_history": [], |
| "description": "Netflix is the biggest streaming service for movies and TV shows. Instead of watching TV on cable, you can watch thousands of shows and movies on Netflix over the internet. Netflix also makes its own original shows like Stranger Things and The Crown. Streaming services like Netflix have changed how people watch TV and movies.", |
| }, |
| "TMUS": { |
| "current_price": round(random.uniform(140, 200), 2), |
| "price_history": [], |
| "description": "T-Mobile is a wireless carrier that provides cell phone service in the United States. They are known for their 'Un-carrier' approach and competitive prices. T-Mobile is one of the top wireless providers in the US, competing with Verizon and AT&T to keep people connected on their smartphones.", |
| }, |
| }, |
| "Healthcare & Pharma": |
| { |
| "JNJ": { |
| "current_price": round(random.uniform(170, 250), 2), |
| "price_history": [], |
| "description": "Johnson & Johnson, or J&J, is a healthcare giant that makes a wide range of products for health and well-being. They makeBand-Aids and Tylenol that you might have in your medicine cabinet, prescription medicines to treat diseases, and medical devices used by doctors and hospitals. J&J's products help people stay healthy and treat illnesses.", |
| }, |
| "PFE": { |
| "current_price": round(random.uniform(45, 70), 2), |
| "price_history": [], |
| "description": "Pfizer is a pharmaceutical company that makes medicines and vaccines to prevent and treat diseases. They develop drugs for many conditions, from infections to cancer. Vaccines like the COVID-19 vaccine are also made by Pfizer. Pharmaceutical companies like Pfizer are essential for developing new treatments and improving people's health.", |
| }, |
| "UNH": { |
| "current_price": round(random.uniform(480, 650), 2), |
| "price_history": [], |
| "description": "UnitedHealth Group is a health insurance and healthcare services company. They provide health insurance plans to people and also operate hospitals and clinics. Health insurance helps people pay for medical care when they get sick or need to see a doctor. UnitedHealth is a major player in the healthcare system, helping people access medical services.", |
| }, |
| "MRK": { |
| "current_price": round(random.uniform(110, 180), 2), |
| "price_history": [], |
| "description": "Merck & Co is a pharmaceutical company that discovers and makes medicines and vaccines. They research and develop new drugs to treat various diseases and improve health. Merck is known for its long history of innovation in medicine and for producing important vaccines and treatments. Pharmaceutical companies like Merck are vital for medical progress.", |
| }, |
| "ABBV": { |
| "current_price": round(random.uniform(150, 230), 2), |
| "price_history": [], |
| "description": "AbbVie is a pharmaceutical company that focuses on developing medicines for complex diseases, like arthritis, Crohn's disease, and cancer. They make drugs that help people with serious illnesses live better lives. AbbVie is known for its research and development of specialized medicines.", |
| }, |
| "LLY": { |
| "current_price": round(random.uniform(700, 1000), 2), |
| "price_history": [], |
| "description": "Eli Lilly and Company, or Lilly, is a pharmaceutical company that makes medicines for diseases like diabetes, cancer, and depression. They have been making medicines for a very long time and are known for their research and innovation in healthcare. Lilly's drugs help treat millions of people around the world.", |
| }, |
| }, |
| "Chemicals & Materials": |
| { |
| "DOW": { |
| "current_price": round(random.uniform(55, 80), 2), |
| "price_history": [], |
| "description": "Dow Chemical makes chemicals and materials that are used to make many products we use every day. Their chemicals go into plastics, packaging, paints, adhesives, and agricultural products. Dow is a major manufacturer of chemicals and materials that are essential for many industries. They are a key supplier for companies that make everyday goods.", |
| }, |
| "LIN": { |
| "current_price": round(random.uniform(300, 450), 2), |
| "price_history": [], |
| "description": "Linde is an industrial gas company that provides gases to industries like healthcare, manufacturing, and energy. They supply gases like oxygen, nitrogen, and argon that are used in hospitals, factories, and other industries. Industrial gases are essential for many processes, and Linde is a global leader in providing them.", |
| }, |
| "DD": { |
| "current_price": round(random.uniform(70, 110), 2), |
| "price_history": [], |
| "description": "DuPont makes specialty chemicals and materials that are used in advanced technologies and industries. They create materials for electronics, automotive, construction, and safety. DuPont is known for its science and innovation in developing high-performance materials that make products better and safer.", |
| }, |
| "NUE": { |
| "current_price": round(random.uniform(120, 180), 2), |
| "price_history": [], |
| "description": "Nucor is a steel company and also a major recycler of steel. They make steel products for construction, μλμ°¨, and manufacturing. Steel is a fundamental material for building and infrastructure, and Nucor is the largest steel producer in the United States. They are also focused on recycling and sustainable steel production.", |
| }, |
| "SHW": { |
| "current_price": round(random.uniform(250, 400), 2), |
| "price_history": [], |
| "description": "Sherwin-Williams, in addition to retail paint stores, is also a major manufacturer of paints and coatings used in many industries. Their paints and coatings protect and color buildings, cars, and industrial equipment. Paints are chemical products, and Sherwin-Williams is a leader in paint and coating technology and manufacturing.", |
| }, |
| "ECL": { |
| "current_price": round(random.uniform(200, 300), 2), |
| "price_history": [], |
| "description": "Ecolab provides cleaning, sanitation, and water treatment solutions for businesses. They help restaurants, hotels, hospitals, and factories stay clean and safe. Ecolab's products and services are essential for hygiene and safety in many industries, especially in food safety and healthcare.", |
| }, |
| }, |
| "Transportation & Logistics": |
| { |
| "UNP": { |
| "current_price": round(random.uniform(220, 300), 2), |
| "price_history": [], |
| "description": "Union Pacific Railroad operates a huge network of railroads across the western United States. They transport goods like cars, Π·Π΅ΡΠ½ΠΎ, chemicals, and consumer products by train. Railroads are a vital way to move large amounts of freight across long distances, and Union Pacific is one of the biggest railroads in North America.", |
| }, |
| "FDX": { |
| "current_price": round(random.uniform(250, 350), 2), |
| "price_history": [], |
| "description": "FedEx is a global delivery company that ships packages and documents around the world quickly and reliably. If you order something online and need it delivered fast, FedEx is often the company that brings it to your door. They use airplanes, trucks, and delivery vans to move packages across countries and continents. FedEx is a leader in express delivery.", |
| }, |
| "UPS": { |
| "current_price": round(random.uniform(160, 250), 2), |
| "price_history": [], |
| "description": "UPS, or United Parcel Service, is another major package delivery company, competing with FedEx. They also deliver packages and provide logistics services worldwide. UPS is known for its brown trucks and global delivery network. Both UPS and FedEx are essential for e-commerce and global trade, moving goods from businesses to customers.", |
| }, |
| "LSTR": { |
| "current_price": round(random.uniform(190, 280), 2), |
| "price_history": [], |
| "description": "Landstar System is a trucking and logistics company that helps businesses transport freight across North America. They use a network of independent truck drivers to move goods. Trucking is a major way to transport goods within countries, and Landstar helps businesses manage their shipping and logistics.", |
| }, |
| "JBHT": { |
| "current_price": round(random.uniform(170, 250), 2), |
| "price_history": [], |
| "description": "J.B. Hunt Transport Services is another large trucking and logistics company in the US. They provide trucking services to businesses to move goods across the country. J.B. Hunt uses a large fleet of trucks and trailers to transport freight. Trucking companies like J.B. Hunt are a critical part of the supply chain, moving products from factories to stores.", |
| }, |
| "CSX": { |
| "current_price": round(random.uniform(35, 60), 2), |
| "price_history": [], |
| "description": "CSX Corporation is a railroad company that operates a large rail network in the eastern United States. They transport freight like coal, chemicals, and consumer goods by train. Railroads are an efficient way to transport bulk goods, and CSX is a major railroad in the eastern US, connecting industries and markets.", |
| }, |
| }, |
| "Food & Beverage": |
| { |
| "MCD": { |
| "current_price": round(random.uniform(250, 350), 2), |
| "price_history": [], |
| "description": "McDonald's is the biggest fast-food restaurant chain in the world! They are famous for burgers like the Big Mac, french fries, and Happy Meals. McDonald's restaurants are found in almost every country, serving millions of customers every day. Fast food chains like McDonald's are a popular and convenient way for people to get meals quickly.", |
| }, |
| "SBUX": { |
| "current_price": round(random.uniform(110, 180), 2), |
| "price_history": [], |
| "description": "Starbucks is the largest coffee shop chain globally. They sell coffee, tea, pastries, and snacks. Starbucks coffee shops are popular places to meet friends, work, or grab a coffee on the go. They are known for their coffee drinks and comfortable atmosphere. Coffee chains like Starbucks are a big part of the coffee culture.", |
| }, |
| "MDLZ": { |
| "current_price": round(random.uniform(70, 110), 2), |
| "price_history": [], |
| "description": "Mondelez International makes snacks and confectionery β yummy treats like Oreo cookies, Cadbury chocolate, Ritz crackers, and Trident gum. Mondelez has a huge portfolio of snack brands that people enjoy around the world. Snack food companies like Mondelez provide popular treats and snacks for people of all ages.", |
| }, |
| "GIS": { |
| "current_price": round(random.uniform(60, 90), 2), |
| "price_history": [], |
| "description": "General Mills makes packaged foods, especially breakfast cereals and snacks. Brands like Cheerios cereal, Yoplait yogurt, Pillsbury baking products, and Nature Valley granola bars are all from General Mills. They have many familiar food brands that families eat for breakfast, snacks, and meals. Packaged food companies like General Mills provide convenient and shelf-stable food products.", |
| }, |
| "YUM": { |
| "current_price": round(random.uniform(120, 190), 2), |
| "price_history": [], |
| "description": "Yum! Brands owns several famous fast-food restaurant chains β Taco Bell, KFC (Kentucky Fried Chicken), and Pizza Hut. If you eat tacos at Taco Bell, chicken at KFC, or pizza at Pizza Hut, you are eating at restaurants owned by Yum! Brands. They are one of the largest fast-food companies, with restaurants all over the world.", |
| }, |
| "CPB": { |
| "current_price": round(random.uniform(45, 70), 2), |
| "price_history": [], |
| "description": "Campbell Soup Company is famous for making Campbell's soup, but they also make other foods like Pepperidge Farm cookies, Goldfish crackers, and V8 juice. Campbell's soup is a classic and convenient meal, and their other brands are also popular snacks and foods. Packaged food companies like Campbell Soup provide convenient and recognizable food products.", |
| }, |
| }, |
| } |
| for sector in st.session_state["stocks"]: |
| for stock_name in st.session_state["stocks"][sector]: |
| st.session_state["stocks"][sector][stock_name]["price_history"].append( |
| st.session_state["stocks"][sector][stock_name]["current_price"] |
| ) |
|
|
| if "news_analysis_results" not in st.session_state: |
| st.session_state["news_analysis_results"] = {} |
| if "messages" not in st.session_state: |
| st.session_state["messages"] = [] |
| if "daily_news" not in st.session_state: |
| st.session_state["daily_news"] = None |
| if "previous_daily_news" not in st.session_state: |
| st.session_state["previous_daily_news"] = None |
| if "news_date" not in st.session_state: |
| st.session_state["news_date"] = None |
| if "news_meanings" not in st.session_state: |
| st.session_state["news_meanings"] = {} |
| if ( |
| "ai_news_analysis_output" not in st.session_state |
| ): |
| st.session_state["ai_news_analysis_output"] = {} |
| if "day_count" not in st.session_state: |
| st.session_state["day_count"] = 1 |
| if "sector_news_impact" not in st.session_state: |
| st.session_state["sector_news_impact"] = {} |
| if 'buy_confirm' not in st.session_state: |
| st.session_state['buy_confirm'] = False |
| if 'sell_confirm' not in st.session_state: |
| st.session_state['sell_confirm'] = False |
|
|
|
|
| |
| def generate_news(): |
| day_count = st.session_state["day_count"] |
| prompt = f""" |
| Instructions: |
| Generate 5 news articles about the stock market and economy, suitable for a 6th-grade elementary school student. |
| Each article should be detailed with about 12-15 sentences, and do not directly mention specific company names or stock tickers. |
| Create news about general economic situations or industry trends so that students can infer which companies might be promising or declining by reading the news. |
| Generate a variety of news, including positive, negative, and neutral news. (Do not explicitly label them as positive, negative, or neutral.) |
| Stock prices may rise or fall depending on the news. |
| Start each news article with "## News [Number]" (e.g., ## News 1, ## News 2...). |
| |
| **Generated News Articles:** |
| """ |
| chat_session = st.session_state["chat_session"] |
| response = chat_session.send_message(prompt) |
| news_text = response.text.strip() |
|
|
| news_articles = [] |
| if news_text: |
| news_articles = [ |
| article.strip() for article in news_text.split("## News ") if article.strip() |
| ] |
|
|
| return news_articles[:5] |
|
|
|
|
| def explain_daily_news_meanings(daily_news): |
| if daily_news is None: |
| return {} |
|
|
| meanings = {} |
| for i, news_article in enumerate(daily_news): |
| prompt = f""" |
| **News Article:** |
| {news_article} |
| |
| **Instructions:** |
| Summarize the key meaning of the news article above in a way that is easy for a 6th-grade elementary school student to understand within 3 sentences after "Explanation: ". |
| And tell me 1-2 stock sectors related to this news, separated by commas, after "Related Sectors: ". If there are no related sectors, please say "Related Sectors: None". |
| |
| News Meaning Explanation: |
| """ |
| chat_session = st.session_state["chat_session"] |
| try: |
| response = chat_session.send_message(prompt) |
| meaning_text = response.text.strip() |
|
|
| explanation = "" |
| related_sectors = [] |
|
|
| if "Explanation:" in meaning_text: |
| explanation_start_index = meaning_text.find("Explanation:") + len("Explanation:") |
| explanation_end_index = meaning_text.find("Related Sectors:") |
| if explanation_end_index != -1: |
| explanation = meaning_text[explanation_start_index:explanation_end_index].strip() |
| else: |
| explanation = meaning_text[explanation_start_index:].strip() |
|
|
| if "Related Sectors:" in meaning_text: |
| related_sectors_str = meaning_text.split("Related Sectors:")[1].strip() |
| if related_sectors_str.lower() != "none": |
| related_sectors = [sector.strip() for sector in related_sectors_str.split(',')] |
| else: |
| related_sectors = [] |
|
|
| meanings[str(i + 1)] = {"explanation": explanation, "sectors": related_sectors} |
|
|
|
|
| except google.api_core.exceptions.ResourceExhausted as e: |
| st.error( |
| f"API quota exceeded error occurred. Please try again later. Error message: {e}" |
| ) |
| return None |
| time.sleep(1) |
| return meanings |
|
|
|
|
| def buy_stock(stock_name, quantity, sector): |
| if ( |
| sector not in st.session_state["stocks"] |
| or stock_name not in st.session_state["stocks"][sector] |
| ): |
| st.session_state["messages"].append( |
| {"type": "error", "text": "Stock ticker does not exist."} |
| ) |
| return |
|
|
| if quantity <= 0: |
| st.session_state["messages"].append( |
| {"type": "error", "text": "Buy quantity must be at least 1 share."} |
| ) |
| return |
|
|
| stock_price = st.session_state["stocks"][sector][stock_name]["current_price"] |
| max_quantity = st.session_state["portfolio"]["cash"] // stock_price |
| if quantity > max_quantity: |
| st.session_state["messages"].append( |
| { |
| "type": "error", |
| "text": f"Exceeded maximum buyable quantity. (Maximum {int(max_quantity)} shares)", |
| } |
| ) |
| st.toast( |
| f"Exceeded maximum buyable quantity. (Maximum {int(max_quantity)} shares)", icon="β" |
| ) |
| st.error(f"Insufficient balance. (Maximum {int(max_quantity)} shares)") |
| return |
|
|
| total_price = stock_price * quantity |
|
|
| if st.session_state["portfolio"]["cash"] >= total_price: |
| st.session_state["portfolio"]["cash"] -= total_price |
| portfolio_stocks = st.session_state["portfolio"]["stocks"] |
| if ( |
| stock_name in portfolio_stocks |
| ): |
| portfolio_stocks[stock_name]["quantity"] += quantity |
| portfolio_stocks[stock_name]["purchase_price"] = ( |
| portfolio_stocks[stock_name]["purchase_price"] |
| * (portfolio_stocks[stock_name]["quantity"] - quantity) |
| + total_price |
| ) / portfolio_stocks[stock_name]["quantity"] |
| else: |
| portfolio_stocks[stock_name] = { |
| "quantity": quantity, |
| "purchase_price": total_price / quantity, |
| } |
| st.session_state["messages"].append( |
| { |
| "type": "success", |
| "text": f"Successfully bought {quantity} shares of {stock_name}. Total cost ${total_price:,.2f}.", |
| } |
| ) |
| st.success(f"Successfully bought {quantity} shares of {stock_name}. Total cost ${total_price:,.2f}.") |
| st.toast( |
| f"Successfully bought {quantity} shares of {stock_name}. Total cost ${total_price:,.2f}.", icon="β
" |
| ) |
| st.session_state['buy_confirm'] = False |
| else: |
| st.session_state["messages"].append( |
| {"type": "error", "text": "Insufficient balance."} |
| ) |
| st.toast("Insufficient balance.", icon="β") |
| st.error(f"Insufficient balance. (Maximum {int(max_quantity)} shares)") |
| st.session_state['buy_confirm'] = False |
|
|
|
|
| def sell_stock(stock_name, quantity): |
| if stock_name not in st.session_state["portfolio"]["stocks"]: |
| st.session_state["messages"].append( |
| {"type": "error", "text": "You do not own this stock."} |
| ) |
| st.error("You do not own this stock.") |
| st.toast("You do not own this stock.", icon="β") |
| return |
|
|
| owned_quantity = st.session_state["portfolio"]["stocks"][stock_name]["quantity"] |
|
|
| if owned_quantity < quantity: |
| st.session_state["messages"].append( |
| {"type": "error", "text": "Sell quantity exceeds owned stock count."} |
| ) |
| st.error("Sell quantity exceeds owned stock count.") |
| st.toast("Sell quantity exceeds owned stock count.", icon="β") |
| return |
|
|
| if quantity <= 0: |
| st.session_state["messages"].append( |
| {"type": "error", "text": "Invalid sell quantity."} |
| ) |
| st.error("Invalid sell quantity.") |
| st.toast("Invalid sell quantity.", icon="β") |
| return |
|
|
| stock_price = 0 |
| stock_sector = "" |
| for sector, stocks in st.session_state["stocks"].items(): |
| if stock_name in stocks: |
| stock_price = stocks[stock_name]["current_price"] |
| stock_sector = sector |
| break |
|
|
| if stock_price == 0: |
| st.session_state["messages"].append( |
| {"type": "error", "text": "Could not find stock information."} |
| ) |
| return |
|
|
| sell_price = stock_price * quantity |
| st.session_state["portfolio"]["cash"] += sell_price |
| st.session_state["portfolio"]["stocks"][stock_name]["quantity"] -= quantity |
| if st.session_state["portfolio"]["stocks"][stock_name]["quantity"] == 0: |
| del st.session_state["portfolio"]["stocks"][stock_name] |
|
|
| st.session_state["messages"].append( |
| { |
| "type": "success", |
| "text": f"Successfully sold {quantity} shares of {stock_name}. Total proceeds ${sell_price:,.2f}.", |
| } |
| ) |
| st.toast( |
| f"Successfully sold {quantity} shares of {stock_name}. Total proceeds ${sell_price:,.2f}.", icon="β
" |
| ) |
| st.success(f"Successfully sold {quantity} shares of {stock_name}. Total proceeds ${sell_price:,.2f}.") |
| st.session_state['sell_confirm'] = False |
|
|
|
|
| def update_stock_prices(): |
| if not st.session_state["daily_news"]: |
| return |
|
|
| sector_impacts = {sector: 0 for sector in st.session_state["stocks"]} |
|
|
| for i, news_article in enumerate(st.session_state["daily_news"]): |
| news_meaning = st.session_state["news_meanings"].get(str(i + 1)) |
| if news_meaning: |
| related_sectors = news_meaning.get("sectors", []) |
| news_explanation = news_meaning.get("explanation", "") |
|
|
| news_sentiment = 0 |
| if "rise" in news_article or "growth" in news_article or "positive" in news_article or "promising" in news_article or "boom" in news_article: |
| news_sentiment = 1 |
| elif "fall" in news_article or "decrease" in news_article or "negative" in news_article or "difficulty" in news_article or "recession" in news_article or "crisis" in news_article: |
| news_sentiment = -1 |
| else: |
| news_sentiment = 0 |
|
|
| for sector in related_sectors: |
| if sector in sector_impacts: |
| sector_impacts[sector] += news_sentiment * 0.05 |
|
|
| for sector in st.session_state["stocks"]: |
| sector_impact = sector_impacts[sector] |
| for stock_name in st.session_state["stocks"][sector]: |
| change_rate = random.uniform(-0.02, 0.02) + sector_impact |
| change_rate = max(-0.3, min(0.3, change_rate)) |
| st.session_state["stocks"][sector][stock_name]["current_price"] *= ( |
| 1 + change_rate |
| ) |
| st.session_state["stocks"][sector][stock_name]["current_price"] = max( |
| 0.01, st.session_state["stocks"][sector][stock_name]["current_price"] |
| ) |
| st.session_state["stocks"][sector][stock_name]["current_price"] = round(st.session_state["stocks"][sector][stock_name]["current_price"], 2) |
| st.session_state["stocks"][sector][stock_name]["price_history"].append( |
| st.session_state["stocks"][sector][stock_name]["current_price"] |
| ) |
| st.session_state["messages"].append({"type": "info", "text": "Stock prices have changed."}) |
| st.toast("Stock prices have changed.", icon="π") |
| st.info("Stock prices have changed.") |
| st.session_state["sector_news_impact"] = sector_impacts |
|
|
|
|
| def display_portfolio(): |
| portfolio = st.session_state["portfolio"] |
| cash = portfolio["cash"] |
| total_value = cash |
| total_purchase_value = 0 |
| for stock_name, stock_info in portfolio["stocks"].items(): |
| quantity = stock_info["quantity"] |
| purchase_price = stock_info["purchase_price"] |
| current_price = 0 |
| stock_sector = "" |
| for sector, stocks in st.session_state["stocks"].items(): |
| if stock_name in stocks: |
| current_price = stocks[stock_name]["current_price"] |
| stock_sector = sector |
| break |
| if current_price != 0: |
| stock_value = current_price * quantity |
| total_value += stock_value |
| purchase_value = purchase_price * quantity |
| total_purchase_value += purchase_value |
|
|
| initial_cash = 10000 |
| total_profit_loss = total_value - initial_cash |
| total_profit_rate = ( |
| (total_profit_loss / initial_cash) * 100 if initial_cash != 0 else 0 |
| ) |
|
|
| return cash, total_value, total_profit_rate |
|
|
|
|
| def display_stock_prices(): |
| stocks_data = [] |
| for sector, sector_stocks in st.session_state["stocks"].items(): |
| for stock_name, stock_info in sector_stocks.items(): |
| price_history = stock_info["price_history"] |
| daily_change_rate_str = " - " |
| if len(price_history) >= 2: |
| previous_day_price = price_history[-2] |
| current_price = price_history[-1] |
| daily_change_rate = (current_price - previous_day_price) / previous_day_price * 100 |
| daily_change_rate_str = f"{daily_change_rate:.2f}%" |
|
|
| stocks_data.append( |
| { |
| "Ticker": stock_name, |
| "Sector": sector, |
| "Current Price": f"${stock_info['current_price']:.2f}", |
| "Daily Change": daily_change_rate_str, |
| "price_history": stock_info["price_history"], |
| "description": stock_info["description"], |
| } |
| ) |
| stocks_df = pd.DataFrame(stocks_data) |
| st.dataframe(stocks_df[["Sector", "Ticker", "Current Price", "Daily Change"]], hide_index=True) |
|
|
| selected_stock_all_info = st.selectbox( |
| "Select a Stock (Company Info & Price Chart)", stocks_df["Ticker"].tolist() |
| ) |
| if selected_stock_all_info: |
| selected_stock_sector = stocks_df[ |
| stocks_df["Ticker"] == selected_stock_all_info |
| ]["Sector"].iloc[0] |
| col1_info, col2_graph = st.columns([1, 2]) |
|
|
| with col1_info: |
| st.subheader("Company Information") |
| st.info( |
| f"**{selected_stock_all_info} ({selected_stock_sector})**\n\n{st.session_state['stocks'][selected_stock_sector][selected_stock_all_info]['description']}" |
| ) |
|
|
| with col2_graph: |
| st.subheader("Price Chart") |
| price_history_df = pd.DataFrame( |
| { |
| "Day": range( |
| 1, |
| len( |
| st.session_state["stocks"][selected_stock_sector][ |
| selected_stock_all_info |
| ]["price_history"] |
| ) |
| + 1, |
| ), |
| "Price": st.session_state["stocks"][selected_stock_sector][ |
| selected_stock_all_info |
| ]["price_history"], |
| } |
| ) |
| fig = px.line( |
| price_history_df, |
| x="Day", |
| y="Price", |
| title=f"{selected_stock_all_info} ({selected_stock_sector}) Price Trend", |
| ) |
| st.plotly_chart(fig) |
| else: |
| st.info("Select a stock to view company information and price chart.") |
|
|
|
|
| def display_portfolio_table(): |
| portfolio = st.session_state["portfolio"] |
| if portfolio["stocks"]: |
| portfolio_data = [] |
| total_value = portfolio["cash"] |
| total_purchase_value = 0 |
| total_profit_loss = 0 |
| total_profit_rate = 0.0 |
| for stock_name, stock_info in portfolio["stocks"].items(): |
| quantity = stock_info["quantity"] |
| purchase_price = stock_info["purchase_price"] |
| current_price = 0 |
| stock_sector = "" |
| for sector, stocks in st.session_state["stocks"].items(): |
| if stock_name in stocks: |
| current_price = stocks[stock_name]["current_price"] |
| stock_sector = sector |
| break |
|
|
| if current_price == 0: |
| continue |
|
|
| stock_value = current_price * quantity |
| purchase_value = purchase_price * quantity |
| profit_loss = stock_value - purchase_value |
| profit_rate = ( |
| (profit_loss / purchase_value) * 100 if purchase_value != 0 else 0 |
| ) |
| total_value += stock_value |
| total_purchase_value += purchase_value |
| total_profit_loss += profit_loss |
|
|
| portfolio_data.append( |
| { |
| "Ticker": stock_name, |
| "Sector": stock_sector, |
| "Shares Held": quantity, |
| "Purchase Price": f"${purchase_price:.2f}", |
| "Current Price": f"${current_price:.2f}", |
| "Value": f"${stock_value:.2f}", |
| "Profit/Loss": f"${profit_loss:.2f}", |
| "Return Rate": f"{profit_rate:.2f}%", |
| } |
| ) |
| portfolio_data.append( |
| { |
| "Ticker": "Cash", |
| "Sector": "-", |
| "Shares Held": "-", |
| "Purchase Price": "-", |
| "Current Price": "-", |
| "Value": f"${portfolio['cash']:.2f}", |
| "Profit/Loss": "-", |
| "Return Rate": "-", |
| } |
| ) |
| portfolio_df = pd.DataFrame(portfolio_data) |
| st.dataframe(portfolio_df, hide_index=True, height=350) |
| st.markdown( |
| f"""**Cash Balance:** ${portfolio['cash']:.2f} |
| **π Total Portfolio Value:** ${total_value:.2f} |
| **π Total Purchase Value:** ${total_purchase_value:.2f} |
| **ππ Total Profit/Loss:** ${total_profit_loss:.2f} (π Return Rate: {total_profit_rate:.2f}%) |
| """ |
| ) |
| else: |
| st.info("No stocks held in your portfolio.") |
|
|
|
|
| |
| def display_stock_glossary(): |
| glossary = { |
| "Stock": "Represents a share of ownership in a company. Buying stock makes you a part-owner of the company.", |
| "Stock Price": "The price of one share of stock. It changes as people buy and sell stocks.", |
| "Buy (Purchase)": "To purchase stocks.", |
| "Sell (Dispose)": "To sell stocks.", |
| "Portfolio": "A list of stocks and cash you own.", |
| "Return Rate": "The percentage of profit you made compared to your initial investment. (Profit / Initial Investment) X 100", |
| "Rise (Increase)": "Stock prices going up.", |
| "Fall (Decrease)": "Stock prices going down.", |
| "Volatility": "How much stock prices go up and down.", |
| "Investment": "Putting money into something to make a profit.", |
| "Sector": "A group of companies that do similar business (e.g., Technology Sector, Automotive Sector)", |
| "Daily Change Rate": "The percentage change in today's stock price compared to yesterday's price. + means increase, - means decrease.", |
| } |
| with st.sidebar.expander("π Stock Glossary", expanded=False): |
| for term, definition in glossary.items(): |
| st.markdown(f"**{term}:** {definition}") |
| st.markdown("---") |
|
|
|
|
| |
| def main(): |
| col_news, col_main_ui = st.columns([1, 2]) |
|
|
| with col_news: |
| st.header(f"π° Day {st.session_state['day_count']} News") |
| if st.button("Generate News", use_container_width=True, key="news_gen_button"): |
| with st.spinner(f"Generating Day {st.session_state['day_count']} News..."): |
| current_daily_news = generate_news() |
| st.session_state["daily_news"] = current_daily_news |
|
|
| if st.session_state["daily_news"]: |
| st.subheader(f"Day {st.session_state['day_count']} News") |
| for i, news in enumerate(st.session_state["daily_news"]): |
| with st.expander(f"News {i+1}", expanded=False): |
| st.write(news) |
|
|
| if st.session_state["previous_daily_news"] and st.session_state[ |
| "news_meanings" |
| ]: |
| st.subheader(f"Day {st.session_state['day_count'] - 1} News Explanation") |
| st.info("AI analysis of yesterday's news.") |
| with st.expander(f"View Day {st.session_state['day_count'] - 1} News Explanation", expanded=False): |
| if st.session_state["news_meanings"]: |
| for i, meaning_data in st.session_state["news_meanings"].items(): |
| st.markdown(f"**News {i}**:") |
| st.markdown(f"**AI Explanation:** {meaning_data['explanation']}") |
| if meaning_data['sectors']: |
| st.markdown(f"**Related Sectors:** {', '.join(meaning_data['sectors'])}") |
| else: |
| st.markdown("**Related Sectors:** None") |
| else: |
| st.info("No explanation for yesterday's news.") |
|
|
| elif not st.session_state["daily_news"]: |
| st.info("Click 'Generate News' button to get today's news.") |
|
|
| with col_main_ui: |
| menu = st.tabs( |
| ['Current Prices', 'My Portfolio', 'Buy Stocks', 'Sell Stocks', 'Yesterday\'s News Explanation'] |
| ) |
|
|
| with menu[0]: |
| st.subheader("π Current Stock Prices & Company Info") |
| st.markdown("Check current stock market prices and company information.") |
| display_stock_prices() |
|
|
| with menu[1]: |
| st.subheader("π My Portfolio") |
| st.markdown("Check your current stock holdings and assets.") |
| display_portfolio_table() |
|
|
| with menu[2]: |
| st.subheader("π° Buy Stocks") |
| st.markdown("Buy stocks based on AI predictions and news analysis.") |
| sector_names = list(st.session_state["stocks"].keys()) |
| selected_sector_buy = st.selectbox("Select Sector to Buy:", sector_names) |
| stock_names_in_sector = list( |
| st.session_state["stocks"][selected_sector_buy].keys() |
| ) |
| selected_stock_buy = st.selectbox("Select Stock to Buy:", stock_names_in_sector) |
|
|
| stock_price_buy = st.session_state["stocks"][selected_sector_buy][ |
| selected_stock_buy |
| ]["current_price"] |
| st.info(f"**{selected_stock_buy}** Current Price: ${stock_price_buy:.2f}") |
| quantity_buy = st.number_input( |
| "Quantity to Buy (Shares):", min_value=1, value=1, step=1 |
| ) |
|
|
| if not st.session_state['buy_confirm']: |
| if st.button("Buy Stock", use_container_width=True, key='buy_button_confirm'): |
| st.session_state['buy_confirm'] = True |
| else: |
| st.warning("Confirm Buy Order?") |
| col_confirm, col_cancel = st.columns([1, 1]) |
| with col_confirm: |
| if st.button("β
Confirm Buy", use_container_width=True, key='buy_confirm_button'): |
| buy_stock(selected_stock_buy, quantity_buy, selected_sector_buy) |
|
|
| with col_cancel: |
| if st.button("β Cancel Buy", use_container_width=True, key='buy_cancel_button', type='secondary'): |
| st.session_state['buy_confirm'] = False |
| st.info("Buy order cancelled.") |
|
|
| with menu[3]: |
| st.subheader("π Sell Stocks") |
| st.markdown("Sell your holdings and realize profits.") |
| if st.session_state["portfolio"]["stocks"]: |
| stock_names_sell = list(st.session_state["portfolio"]["stocks"].keys()) |
| selected_stock_sell = st.selectbox("Select Stock to Sell:", stock_names_sell) |
| stock_price_sell = 0 |
| for sector, stocks in st.session_state["stocks"].items(): |
| if selected_stock_sell in stocks: |
| stock_price_sell = stocks[selected_stock_sell]["current_price"] |
| break |
|
|
| st.info(f"**{selected_stock_sell}** Current Price: ${stock_price_sell:.2f}") |
| max_sell_quantity = st.session_state["portfolio"]["stocks"][ |
| selected_stock_sell |
| ]["quantity"] |
| quantity_sell = st.number_input( |
| "Quantity to Sell (Shares):", |
| min_value=1, |
| max_value=max_sell_quantity, |
| value=1, |
| step=1, |
| ) |
| if not st.session_state['sell_confirm']: |
| if st.button("Sell Stock", use_container_width=True, key='sell_button_confirm'): |
| st.session_state['sell_confirm'] = True |
| else: |
| st.warning("Confirm Sell Order?") |
| col_confirm, col_cancel = st.columns([1, 1]) |
| with col_confirm: |
| if st.button("β
Confirm Sell", use_container_width=True, key='sell_confirm_button'): |
| sell_stock(selected_stock_sell, quantity_sell) |
| with col_cancel: |
| if st.button("β Cancel Sell", use_container_width=True, key='sell_cancel_button', type='secondary'): |
| st.session_state['sell_confirm'] = False |
| st.info("Sell order cancelled.") |
| else: |
| st.info("No stocks held in your portfolio. Check 'My Portfolio' tab.") |
|
|
| with menu[4]: |
| if st.session_state["previous_daily_news"] and st.session_state[ |
| "news_meanings" |
| ]: |
| st.subheader(f"Day {st.session_state['day_count'] - 1} News Explanation") |
| st.info("AI analysis of yesterday's news.") |
| for i in range(len(st.session_state["previous_daily_news"])): |
| with st.expander(f"News {i+1}", expanded=False): |
| news_content = st.session_state["previous_daily_news"][i] |
| st.markdown("**News Article:**") |
| st.write(news_content) |
| meaning_data = st.session_state["news_meanings"].get(str(i+1)) |
| if meaning_data: |
| st.markdown("**AI Explanation:**") |
| st.info(meaning_data['explanation']) |
| if meaning_data['sectors']: |
| st.markdown("**Related Sectors:**") |
| st.info(', '.join(meaning_data['sectors'])) |
| else: |
| st.info("**Related Sectors:** None") |
| else: |
| st.warning("Failed to generate news explanation.") |
| else: |
| st.info( |
| "No previous news explanation available. Click 'Pass the Day' button to get news explanations." |
| ) |
|
|
| with st.sidebar: |
| st.markdown("# π° Elementary Stock Market Game (US)") |
| st.markdown(f"### Day {st.session_state['day_count']}") |
| st.markdown("---") |
| st.markdown("Easy and Fun Stock Investing π") |
| st.markdown("π° Read News Articles and Predict the Future!") |
| cash, total_value, profit_rate = display_portfolio() |
| st.metric(label="π° Cash Balance", value=f"${cash:,.2f}") |
| st.metric(label="π Total Portfolio Value", value=f"${total_value:,.2f}") |
| st.metric(label="π Total Return Rate", value=f"{profit_rate:.2f}%") |
| st.markdown("---") |
|
|
| if st.button("Pass the Day", use_container_width=True, key="day_pass_button"): |
| if st.session_state["daily_news"]: |
| with st.spinner(f"Updating Day {st.session_state['day_count']} Stock Prices & Analyzing Previous News..."): |
| st.session_state["previous_daily_news"] = st.session_state["daily_news"] |
| meanings = explain_daily_news_meanings( |
| st.session_state["previous_daily_news"] |
| ) |
| if meanings: |
| st.session_state["news_meanings"] = meanings |
| update_stock_prices() |
| st.session_state["daily_news"] = generate_news() |
| st.session_state["day_count"] += 1 |
| st.rerun() |
| st.info("Check AI-analyzed news explanations in 'Yesterday's News Explanation' tab.") |
| else: |
| st.warning("Please generate today's news first.") |
| st.markdown("***") |
|
|
| display_stock_glossary() |
|
|
| with st.expander("π App Usage Guide", expanded=False): |
| st.markdown( |
| """ |
| **Step 1: Generate News** |
| - Click the 'Generate News' button in the 'Today's News' area on the left. |
| - AI will create 5 stock market news articles. |
| |
| **Step 2: Read News & Make Predictions** |
| - Carefully read the news articles under 'Today's News'. |
| - For each news, think 'π€ Which companies might make more money because of this news?' or 'π₯ Which companies might lose money?'. |
| - Practice predicting the future in an easy and fun way for elementary school students. |
| |
| **Step 3: Check Stock Prices & Company Info** |
| - Select the 'π Current Prices' tab from the menu. |
| - You can see your current stock holdings, cash balance, total portfolio value, and return rate at a glance. |
| - Check your investment results and see how much profit/loss you made. |
| |
| **Step 4: Buy Stocks** |
| - Select the 'π° Buy Stocks' tab from the menu. |
| - Choose a company you want to buy from the 'Select Stock to Buy' menu. |
| - Enter the 'Quantity to Buy' and click the 'Buy Stock' button to buy stocks. |
| - **Tip:** Choose stocks based on your news predictions! |
| |
| **Step 5: Check Portfolio** |
| - Select the 'π My Portfolio' tab from the menu. |
| - You can see your current stock holdings, cash balance, total portfolio value, and return rate at a glance. |
| - Check your investment results and see how much profit/loss you made. |
| |
| **Step 6: Sell Stocks** |
| - Select the 'π Sell Stocks' tab from the menu. |
| - Choose a stock you want to sell from the 'Select Stock to Sell' menu. |
| - Enter the 'Quantity to Sell' and click the 'Sell Stock' button to sell stocks and get cash. |
| - **Tip:** Sell stocks when prices go up to make a profit! |
| |
| **Step 7: Pass the Day & View Previous News Explanation** |
| - Click the 'Pass the Day' button in the sidebar menu. |
| - Stock prices will change, and a new day begins. |
| - Check the 'Yesterday's News Explanation' tab to see 'News Meaning' explanations added to each news article. |
| - AI will easily explain the key meanings of previous news (yesterday's news) at an elementary school level. |
| |
| **Keep Learning and Growing! π±** |
| - Use the mock stock trading app regularly to learn about the news-stock price relationship and develop your investment sense. |
| - Even if it's difficult at first, stock investing will become more fun and easier with continuous practice! π |
| """ |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |