Created
March 1, 2025 17:14
-
-
Save Abhayparashar31/b9632587cee82d12c02a1422e14837cf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import pandas as pd | |
from datetime import datetime, timedelta | |
# API Key and URL | |
API_KEY = '0d25bd311d7d68b831ea2c0e952e6a6a' | |
url = "https://api.marketstack.com/v1/eod" | |
# Calculate date range (last 30 days) | |
today = datetime.today().strftime('%Y-%m-%d') | |
last_30_days = (datetime.today() - timedelta(days=30)).strftime('%Y-%m-%d') | |
# Stocks to compare | |
symbols = ["AAPL", "MSFT"] | |
# Store results | |
all_data = [] | |
# Fetch data for both stocks | |
for symbol in symbols: | |
params = { | |
"access_key": API_KEY, | |
"symbols": symbol, | |
"date_from": last_30_days, | |
"date_to": today, | |
"limit": 30 | |
} | |
response = requests.get(url, params=params) | |
if response.status_code == 200: | |
data = response.json().get("data", []) | |
# Extract required fields | |
for item in data: | |
formatted_date = datetime.strptime(item["date"][:10], "%Y-%m-%d").strftime("%d-%b-%Y") # Format: Day-Month-Year | |
all_data.append({ | |
"Date": formatted_date, | |
"Stock": symbol, | |
"Open": item["open"], | |
"Close": item["close"], | |
"Change (%)": round(((item["close"] - item["open"]) / item["open"]) * 100, 2) | |
}) | |
else: | |
print(f"❌ API request failed for {symbol} with status code {response.status_code}") | |
# Create DataFrame | |
df = pd.DataFrame(all_data) | |
# Convert Date column to datetime for sorting | |
df["Date"] = pd.to_datetime(df["Date"], format="%d-%b-%Y") | |
df = df.sort_values(by=["Date", "Stock"], ascending=[False, True]).reset_index(drop=True) | |
# Convert Date back to string in required format | |
df["Date"] = df["Date"].dt.strftime("%d-%b-%Y") | |
# Assign alternating colors based on unique date values | |
unique_dates = df["Date"].unique() | |
date_color_map = {date: "#e0f7fa" if i % 2 == 0 else "#ffffff" for i, date in enumerate(unique_dates)} | |
def highlight_changes(val): | |
"""Color positive change green, negative red""" | |
color = 'green' if val > 0 else 'red' if val < 0 else 'black' | |
return f'color: {color}' | |
def apply_date_based_colors(row): | |
"""Apply background color based on date""" | |
return [f'background-color: {date_color_map[row["Date"]]}' for _ in row] | |
styled_df = df.style \ | |
.set_properties(**{'border': '1px solid black', 'text-align': 'center'}) \ | |
.set_caption("📊 AAPL vs MSFT: 30-Day Performance") \ | |
.applymap(highlight_changes, subset=['Change (%)']) \ | |
.apply(apply_date_based_colors, axis=1) \ | |
.format({"Change (%)": "{:.2f}%"}) | |
# Display styled DataFrame | |
styled_df |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment