working on gdp

This commit is contained in:
Isaak Buslovich 2023-11-19 19:22:03 +01:00
parent e5b7709ce3
commit df744a2410
Signed by: Isaak
GPG Key ID: EEC31D6437FBCC63

179
main.py
View File

@ -79,98 +79,90 @@ class Market:
The market is updated every turn. The market is updated every turn.
""" """
def __init__(self): def __init__(self):
self.current_turn = 0 self.current_turn = 0
self.companies = {} self.companies = {}
self.products = {'Coal': 10.0, 'Copper': 15.0, 'Conductor': 20.0} self.products = {'Coal': 10.0, 'Copper': 15.0, 'Conductor': 20.0}
self.starting_prices = self.products.copy() self.starting_prices = self.products.copy()
self.events = load_json('market_events.json')["events"] self.events = load_json('market_events.json')["events"]
self.event_effects = {
"double": lambda x: x * 2,
"halve": lambda x: x / 2,
"increase": lambda x: x + 3.0,
"decrease": lambda x: max(1, x - 3.0),
"tech_boost": self.tech_boost_effect,
"resource_scarcity": self.resource_scarcity_effect,
"recession": self.recession_effect
}
self.stock_ledger = {} self.stock_ledger = {}
self.inflation_rate = 0.05 # Initial inflation rate self.inflation_rate = 0.05
self.inflation_growing = True # Start with inflation growing self.inflation_growing = True
self.inflation_change = random.uniform(0.0001, 0.001) # Initial change rate self.unemployment_rate = 0.05 self.inflation_change = random.uniform(0.0001, 0.001)
self.gdp = 500000 self.gdp = 500000
self.unemployment_rate = 0.04 self.unemployment_rate = 0.04
self.trade_volume = 0 self.trade_volume = 0
self.total_bought = {'Coal': 0, 'Copper': 0, 'Conductor': 0} self.total_bought = {product: 0 for product in self.products}
self.total_sold = {'Coal': 0, 'Copper': 0, 'Conductor': 0} self.total_sold = {product: 0 for product in self.products}
self.previous_prices = self.products.copy() self.previous_prices = self.products.copy()
self.last_event_name = None self.last_event_name = None
self.trend_factor = 1.01
def print_market_events(self): def update_market(self):
console = Console() self.current_turn += 1
panel_text = Text() self.previous_prices = self.products.copy()
self.update_prices()
self.reset_trade_volumes()
self.trend_factor = self.generate_market_trend()
self.update_economic_indicators()
self.handle_market_events()
# Event information def update_prices(self):
panel_text.append(f"Last Market Event: {self.last_event_name}\n") for product in self.products:
demand_factor = self.total_bought[product] - self.total_sold[product]
self.products[product] *= (1 + demand_factor * 0.05)
# Economic indicators def reset_trade_volumes(self):
panel_text.append(f"Inflation Rate: {self.inflation_rate:.2f}%\n", style="grey70") self.total_bought = dict.fromkeys(self.total_bought, 0)
panel_text.append(f"Unemployment Rate: {self.unemployment_rate:.2f}%\n", style="grey70") self.total_sold = dict.fromkeys(self.total_sold, 0)
panel_text.append(f"GDP: {self.gdp:.2f}", style="grey70")
# Display in a panel def generate_market_trend(self):
console.print(Panel(panel_text, title="[bold]Market Events and Indicators", border_style="grey50")) trend_change = random.uniform(-0.02, 0.02)
return max(0.5, min(self.trend_factor + trend_change, 1.5))
def update_economic_indicators(self):
"""Updates key economic indicators like inflation and unemployment rates."""
# Update inflation_rate
self.inflation_rate += self.inflation_change if self.inflation_growing else -self.inflation_change
self.inflation_rate = max(0.0001, min(self.inflation_rate, 0.05)) # Clamp the inflation_rate
# Update GDP
self.gdp *= (1 + (self.inflation_rate / 2))
# Update unemployment_rate
self.unemployment_rate = min(max(self.unemployment_rate + random.uniform(-0.005, 0.005), 0), 1)
# Optional: Print statements for debugging
print(f"Inflation Rate: {self.inflation_rate}")
print(f"GDP: {self.gdp}")
print(f"Unemployment Rate: {self.unemployment_rate}")
def update_inflation_rate(self):
lower_bound = 0.0001
upper_bound = 0.049
if self.inflation_rate <= lower_bound:
self.inflation_growing = True
elif self.inflation_rate >= upper_bound:
self.inflation_growing = False
self.inflation_rate += self.inflation_change if self.inflation_growing else -self.inflation_change
def update_unemployment_rate(self):
fluctuation = random.uniform(-0.005, 0.005)
self.unemployment_rate = max(0, min(self.unemployment_rate + fluctuation, 1))
def handle_market_events(self):
event = random.choices(self.events, weights=[e["probability"] for e in self.events], k=1)[0]
self.last_event_name = event["name"]
getattr(self, event["effect"])() if event["effect"] in dir(self) else None
def tech_boost_effect(self): def tech_boost_effect(self):
""" self.products['Conductor'] *= 1.2
Handles the effect of a technological boost in the market.
This can increase the price of high-tech products.
"""
self.products['Conductor'] *= 1.2 # Example: Increase by 20%
def resource_scarcity_effect(self): def resource_scarcity_effect(self):
"""
Handles the effect of resource scarcity in the market.
This can increase the price of a random basic resource.
"""
random_resource = random.choice(['Coal', 'Copper']) random_resource = random.choice(['Coal', 'Copper'])
self.products[random_resource] *= 1.5 # Example: Increase by 50% self.products[random_resource] *= 1.5
def regulatory_change_effect(self):
"""
Handles the effect of a regulatory change in the market.
This can either increase or decrease the price of all products.
"""
change_factor = random.uniform(0.9, 1.1) # Example: Change between -10% to +10%
for product in self.products:
self.products[product] *= change_factor
def innovation_breakthrough_effect(self):
"""
Handles the effect of an innovation breakthrough.
This can drastically reduce the production cost of a random product.
"""
breakthrough_product = random.choice(list(self.products.keys()))
self.products[breakthrough_product] *= 0.8 # Example: Reduce by 20%
def global_event_effect(self):
"""
Handles the effect of a global event (like a pandemic or economic crisis).
This can significantly affect all market prices.
"""
impact_factor = random.uniform(0.7, 1.3) # Example: Change between -30% to +30%
for product in self.products:
self.products[product] *= impact_factor
def tech_boost_effect(self, price):
"""Handles the effect of a technology boost event on product prices."""
# Example: Increases the price of high-tech products like 'Conductor'
return price * 1.2 # Increase by 20%
def resource_scarcity_effect(self, price):
"""Handles the effect of a resource scarcity event on product prices."""
# Example: Increase the price of a resource due to scarcity
return price * 1.5 # Increase by 50%
def trade_agreement_effect(self, price): def trade_agreement_effect(self, price):
"""Handles the effect of a new trade agreement event.""" """Handles the effect of a new trade agreement event."""
@ -184,6 +176,25 @@ class Market:
"""Handles the effect of a recession event on product prices.""" """Handles the effect of a recession event on product prices."""
return price * 0.7 return price * 0.7
def print_market_events(self):
"""
Prints the latest market events and key economic indicators in a formatted panel.
"""
# Prepare the console and panel text for printing
console = Console()
event_info = f"Last Market Event: {self.last_event_name}\n"
economic_indicators = (
f"Inflation Rate: {self.inflation_rate:.2f}%\n"
f"Unemployment Rate: {self.unemployment_rate:.2f}%\n"
f"GDP: {self.gdp:.2f}"
)
# Create a formatted panel text
panel_text = Text(event_info + economic_indicators)
# Print the panel with styling
console.print(Panel(panel_text, title="[bold]Market Events and Indicators", border_style="grey50"))
def update_stock_ledger(self, company_id, owner_id, amount): def update_stock_ledger(self, company_id, owner_id, amount):
"""Updates the stock ledger for a given company and owner based on the transaction amount.""" """Updates the stock ledger for a given company and owner based on the transaction amount."""
self.stock_ledger[company_id, owner_id] = self.stock_ledger.get((company_id, owner_id), 0) + amount self.stock_ledger[company_id, owner_id] = self.stock_ledger.get((company_id, owner_id), 0) + amount
@ -200,26 +211,30 @@ class Market:
self.current_turn += 1 self.current_turn += 1
self.previous_prices = self.products.copy() self.previous_prices = self.products.copy()
# Adjust prices based on demand # Update prices based on supply and demand
for product in self.products: for product in self.products:
supply_chain_impact = self.simulate_supply_chain_impact(product)
demand_factor = self.total_bought[product] - self.total_sold[product] demand_factor = self.total_bought[product] - self.total_sold[product]
self.products[product] *= (1 + demand_factor * 0.05) self.products[product] *= (1 + demand_factor * 0.05) * supply_chain_impact
self.reset_trade_volumes() self.reset_trade_volumes()
# Update inflation rate with random fluctuation # Procedural generation of market trends
self.inflation_rate = random.uniform(-0.001, 0.05) self.trend_factor = self.generate_market_trend()
# GDP update logic - refined for more controlled growth # Update economic indicators
self.gdp *= (1 + self.inflation_rate / 2) self.update_economic_indicators()
# Handle market events # Handle market events
event = random.choices(self.events, weights=[e["probability"] for e in self.events], k=1)[0] self.handle_market_events()
self.last_event_name = event["name"]
self.products = {k: self.event_effects[event["effect"]](v) for k, v in self.products.items()}
# Update other economic indicators after processing the event def simulate_supply_chain_impact(self, product):
self.update_economic_indicators() return random.uniform(0.9, 1.1)
def generate_market_trend(self):
trend_change = random.uniform(-0.02, 0.02)
new_trend = self.trend_factor + trend_change
return max(0.5, min(new_trend, 1.5))
def reset_trade_volumes(self): def reset_trade_volumes(self):
for product in self.total_bought.keys(): for product in self.total_bought.keys():