Category: python

  • Data science in investing 102

    Since mostly I play with financial data and data science concepts, I think it’s a good idea to create a series called Data science in investing in which I share the small things I learn.

    For today we have Data science in investing 102 at this link, enjoy: https://medium.com/@sorin.tudor/data-science-in-investing-102-54dd5b0550e3

  • Guide: How to Run Gemini in OpenBB Workspace (Local Setup)

    Prerequisites

    • Python 3.10 or 3.11 (Strictly required; 3.12+ is incompatible).
    • Google AI Studio API Key (Free tier works).
    • Conda or a virtual environment manager.

    1. Architecture Overview

    Because OpenBB Agents are hardcoded for OpenAI’s SDK, we cannot connect Gemini directly. We use a “Bridge” architecture:

    OpenBB Workspace → Local Agent Server (Port 8095) → LiteLLM Bridge (Port 4000) → Google Gemini API

    2. Environment Setup (The “Bridge”)

    First, we set up LiteLLM, a tool that translates OpenAI HTTP requests into Google Gemini requests.

    1. Install LiteLLM:
      Bash
      pip install litellm
    2. Run the Bridge:
      Open a dedicated terminal window (keep this running) and start the proxy. We use the Flash model because it supports the large context windows required for analyzing financial datasets.
      Bash
      # Replace with your actual model name if different
      export GEMINI_API_KEY=your_google_key_here
      litellm –model gemini/gemini-latest-flash –port 4000

      Result: You now have an “OpenAI-compatible” server running at http://127.0.0.1:4000.

    3. Agent Installation (The “Brain”)

    The official openbb-agents package on PyPI is often outdated. We must install the agent server from the source to avoid dependency conflicts.

    1. Create a Clean Environment:
      Bash
      conda create -n bb-agents python=3.11 -y
      conda activate bb-agents
    2. Install the Core Library (Editable Mode):
      Clone the library repository and install it so Python can find the base modules.
      Bash
      git clone https://github.com/OpenBB-finance/openbb-agents.git
      cd openbb-agents
      pip install -e . (there are some dependencies to be fixed, it will want pydantic = “==2.7.1” and you need to update it under [home_dir]/OpenBB/openbb-agents/pyproject.toml to pydantic = “>=2.7.1”)
    3. Get the Runnable Examples:
      Clone the secondary repository that contains the actual server implementations.
      Bash
      cd .. # Go back to your root folder
      git clone https://github.com/OpenBB-finance/agents-for-openbb.git
      cd agents-for-openbb

    4. Configuration & Launch

    We will run the “Vanilla Agent” (Agent #30), which can read widgets from your dashboard. We must configure it to talk to our local Bridge (Port 4000) instead of OpenAI servers.

    1. Navigate to the Agent:
      Bash
      cd 30-vanilla-agent-raw-widget-data
    2. Install Dependencies:
      Bash
      pip install langchain-openai fastapi uvicorn python-dotenv
    3. Launch with Redirection:
      Run this command block to inject the configuration and start the server.
    • OPENAI_BASE_URL: Points the agent to our local LiteLLM bridge.
    • OPENAI_API_KEY: A dummy key (required to pass validation checks).

    Bash
    export OPENAI_BASE_URL=”http://127.0.0.1:4000″
    export OPENAI_API_KEY=”sk-fake-key”

    uvicorn main:app –host 127.0.0.1 –port 8095 –reload
    Success Indicator: You will see Uvicorn running on http://127.0.0.1:8095.


    5. Connecting to OpenBB

    1. Open OpenBB Workspace (Web or Desktop).
    2. Open the Copilot Menu (Sidebar).
    3. Click (+) to Add Copilot.
    4. Enter the URL: http://127.0.0.1:8095.
    5. Click Add.

    Verification: You should see a green indicator next to “Vanilla Agent.”

    6. How to Use It

    The Vanilla Agent does not have internet access; it relies on context.

    1. Add a widget to your dashboard (e.g., Stock Price for AAPL).
    2. Click the @ (Add to Chat) button on the widget header.
    3. Ask the chat: “Summarize the price trend in this widget.”

    Result: The agent retrieves the JSON data from the widget, sends it to Gemini (via LiteLLM), and returns the analysis.

  • Checking if STOXX 50 is historically overvalued

    This is not my script, but I needed to share this because it’s impressive.

    Here is the generated script by Gemini to check if the index is overvalued

    import requests
    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    import os
    
    # ==========================================
    # 1. CONFIGURATION
    # ==========================================
    API_KEY = os.environ.get('FMP_KEY')  # <--- REPLACE THIS
    BASE_URL = 'https://financialmodelingprep.com/api/v3'
    
    # Top STOXX 50 Heavyweights (approx 60-70% of index weight)
    # We use a representative subset to keep the script fast.
    # For production, use the full 50 list.
    stoxx_tickers = [
        # --- FRANCE (approx. 18) ---
        "MC.PA",     # LVMH Moet Hennessy Louis Vuitton
        "OR.PA",     # L'Oreal
        "RMS.PA",    # Hermes International
        "TTE.PA",    # TotalEnergies
        "SAN.PA",    # Sanofi (Note: Do not confuse with SAN.MC)
        "AIR.PA",    # Airbus
        "SU.PA",     # Schneider Electric
        "AI.PA",     # Air Liquide
        "BNP.PA",    # BNP Paribas
        "CS.PA",     # AXA
        "DG.PA",     # Vinci
        "EL.PA",     # EssilorLuxottica
        "SAF.PA",    # Safran
        "KER.PA",    # Kering
        "RI.PA",     # Pernod Ricard
        "BN.PA",     # Danone
        "SGO.PA",    # Saint-Gobain
        "GLE.PA",    # Societe Generale (Often on the edge of inclusion)
    
        # --- GERMANY (approx. 15) ---
        "SAP.DE",    # SAP SE
        "SIE.DE",    # Siemens AG
        "ALV.DE",    # Allianz SE
        "DTE.DE",    # Deutsche Telekom
        "MBG.DE",    # Mercedes-Benz Group
        "BMW.DE",    # BMW
        "VOW3.DE",   # Volkswagen (Preferred)
        "MUV2.DE",   # Munich Re
        "BAS.DE",    # BASF
        "BAYN.DE",   # Bayer
        "ADS.DE",    # Adidas
        "DHL.DE",    # DHL Group (formerly Deutsche Post DPW.DE)
        "DB1.DE",    # Deutsche Boerse
        "IFX.DE",    # Infineon Technologies
        "ENR.DE",    # Siemens Energy (Recent addition candidate)
        # "DBK.DE",  # Deutsche Bank (Check if re-added in Sep 2025 rebalance)
        
        # --- NETHERLANDS (approx. 6) ---
        "ASML.AS",   # ASML Holding
        "ADYEN.AS",  # Adyen
        "INGA.AS",   # ING Groep
        "AD.AS",     # Ahold Delhaize
        "PHIA.AS",   # Philips
        "PRX.AS",    # Prosus
    
        # --- SPAIN (approx. 4) ---
        "ITX.MC",    # Inditex
        "IBE.MC",    # Iberdrola
        "SAN.MC",    # Banco Santander (Note: Suffix .MC)
        "BBVA.MC",   # BBVA
    
        # --- ITALY (approx. 4) ---
        "ISP.MI",    # Intesa Sanpaolo
        "ENEL.MI",   # Enel
        "ENI.MI",    # Eni
        "STLAM.MI",  # Stellantis (Listed in Milan and Paris, .MI often used for index)
        "RACE.MI",   # Ferrari (Recent addition)
        # "UCG.MI",  # UniCredit (Often rotates in/out)
    
        # --- BELGIUM (1) ---
        "ABI.BR",    # Anheuser-Busch InBev
    
        # --- FINLAND (2) ---
        "KNEBV.HE",  # Kone
        "NOKIA.HE"   # Nokia
    ]
    
    # ==========================================
    # 2. HELPER FUNCTIONS
    # ==========================================
    def get_json(endpoint):
        """Helper to handle FMP API requests"""
        url = f"{BASE_URL}/{endpoint}"
        if '?' in endpoint:
            url += f"&apikey={API_KEY}"
        else:
            url += f"?apikey={API_KEY}"
        
        try:
            response = requests.get(url)
            response.raise_for_status()
            return response.json()
        except Exception as e:
            print(f"Error fetching {endpoint}: {e}")
            return []
    
    def get_aggregated_pe(tickers, lookback_years=5):
        """
        Calculates the aggregate P/E of a list of tickers over time.
        (Sum of Market Caps) / (Sum of Net Income)
        """
        print(f"--- Building Index P/E for {len(tickers)} companies ---")
        
        df_earnings = pd.DataFrame()
        df_mcap = pd.DataFrame()
        
        # Limit data to keep script snappy
        limit_q = lookback_years * 4 + 4 
        limit_d = lookback_years * 365
        
        for ticker in tickers:
            # A. Fetch Earnings (Quarterly)
            inc_stmt = get_json(f"income-statement/{ticker}?period=quarter&limit={limit_q}")
            if inc_stmt:
                df = pd.DataFrame(inc_stmt)
                df['date'] = pd.to_datetime(df['date'])
                df.set_index('date', inplace=True)
                df = df.sort_index()
                # Calculate TTM Net Income (Sum last 4 quarters)
                ttm = df['netIncome'].rolling(4).sum()
                # Resample to daily (forward fill)
                df_earnings[ticker] = ttm.resample('D').ffill()
    
            # B. Fetch Market Cap (Daily)
            mcap = get_json(f"historical-market-capitalization/{ticker}?limit={limit_d}")
            if mcap:
                df = pd.DataFrame(mcap)
                df['date'] = pd.to_datetime(df['date'])
                df.set_index('date', inplace=True)
                df_mcap[ticker] = df['marketCap']
    
        # C. Aggregate
        # Align dates
        common_idx = df_earnings.index.intersection(df_mcap.index)
        df_earnings = df_earnings.loc[common_idx]
        df_mcap = df_mcap.loc[common_idx]
        
        # Sum components
        total_earnings = df_earnings.sum(axis=1)
        total_mcap = df_mcap.sum(axis=1)
        
        # Calculate P/E
        # Filter out potential data glitches (negative or zero sums)
        idx_pe = total_mcap / total_earnings
        idx_pe = idx_pe[idx_pe > 0] 
        
        return idx_pe
    
    
    # ==========================================
    # 3. MAIN EXECUTION
    # ==========================================
    
    # A. Compute STOXX 50 P/E
    stoxx_pe = get_aggregated_pe(stoxx_tickers)
    
    # B. (Optional) Get Benchmark. 
    # Since S&P 500 P/E is hard to get via free/basic calls, 
    # let's generate a synthetic line for comparison based on market averages if API fails,
    # or plot just the STOXX history.
    # For this script, we will focus on the STOXX Mean Reversion.
    
    # C. Calculate Statistics
    current_pe = stoxx_pe.iloc[-1]
    avg_pe_3y = stoxx_pe.rolling(window=365*3).mean().iloc[-1]
    min_pe = stoxx_pe.min()
    max_pe = stoxx_pe.max()
    
    print(f"\nRESULTS:")
    print(f"Current STOXX 50 P/E: {current_pe:.2f}")
    print(f"3-Year Average P/E:   {avg_pe_3y:.2f}")
    print(f"Min P/E (Period):     {min_pe:.2f}")
    print(f"Max P/E (Period):     {max_pe:.2f}")
    
    if current_pe < avg_pe_3y:
        print("CONCLUSION: UNDERVALUED relative to recent history.")
    else:
        print("CONCLUSION: OVERVALUED relative to recent history.")
    
    # ==========================================
    # 4. PLOTTING
    # ==========================================
    sns.set_style("darkgrid")
    plt.figure(figsize=(12, 6))
    
    # Plot Historical P/E
    plt.plot(stoxx_pe.index, stoxx_pe, label='STOXX 50 P/E (Calculated)', color='#003399', linewidth=2)
    
    # Plot Average Line
    plt.axhline(y=stoxx_pe.mean(), color='r', linestyle='--', label=f'Historical Mean ({stoxx_pe.mean():.1f}x)')
    
    # Add formatting
    plt.title('STOXX 50 Historical Valuation (P/E Ratio)', fontsize=16)
    plt.ylabel('Price / Earnings Ratio')
    plt.xlabel('Year')
    plt.legend()
    
    # Highlight Current Valuation
    plt.annotate(f'Current: {current_pe:.1f}x', 
                 xy=(stoxx_pe.index[-1], current_pe), 
                 xytext=(stoxx_pe.index[-1] - pd.Timedelta(weeks=20), current_pe + 2),
                 arrowprops=dict(facecolor='black', shrink=0.05))
    
    plt.tight_layout()
    plt.show()

    And the fact is that it works.

    This is impressive to say the least.

  • Adding schema to BigQuery table

    I am currently working on a bigger article for Medium but until I can put it words so that it’s really something really worth sharing, just wanted to add on one of the steps that I learned while working.

    Normally I wanted to load some info that was stored in CSV to BigQuery for analysis and filtering.

    I though that you can just add the header to CSV file and it will automatically recognize it and load it.

    Turns out that it’s a little bit more complicated.

    Normally it should work, and since it did with my first CSV, couldn’t really understand what was wrong.

    Now, there are two parts to this story:

    • How can you add the Table schema manually, and it will reveal the actual issue.
    • What do you need to be aware of and why this happens

    How can you add the table schema manually

    The data that is written to CSV is actually a Dataframe, so you have info about the types of the columns directly from code

    dtype_mapping = {
        'object': 'STRING',
        'int64': 'FLOAT',
        'float64': 'FLOAT'
    }
    
    schema = []
    for column, dtype in df.dtypes.items():
        schema.append({
            'name': column,
            'type': dtype_mapping.get(str(dtype), 'STRING') # Default to STRING if type is not in map
        })
    
    import json
    print(json.dumps(schema, indent=2))

    Yes, I know, int64 should be mapped to INTEGER, but it turns out that for my case some columns even if in Python are market as int64, in BigQuery they need to be FLOAT. I know there is more memory allocated but the dataset is quite small.

    So you can easily use so that you can exclude the header.

    df.to_csv(f"df.csv", index=False, mode='a')

    The above piece of code will help you create a SCHEMA from a Dataframe header

    What do you need to be aware of and why this happens

    The actually reason why this happened is because I was not aware that somewhere in my csv file a line with the header definition still remained (yes, I actually wrote multiple dataframes with header and filtered with a Linux command, and it did not work)

    And when the file loaded, I actually saw this:

    Normally if that line was missing and no header, that it should had looked like

    Things to be learned from this exercise:

    • If you have to write multiple dataframes in a CSV file, don’t add the header and use the above code to generate a specific definition of the schema
    • Properly check the CSV not to have rogue lines that don’t match the rest of the structure of the data, otherwise you will find out that everything is converted to string and you don’t understand why.

    And now you know.

    Sorin

  • Data science in investing 101

    I recently wrote a piece on Medium about a quick analysis of the correlation of multiple indexes in China, Korea and Japan, really hope you enjoy it

    https://medium.com/@sorin.tudor/data-science-in-investing-101-51a40281f28a

    Cheers,

    Sorin

  • Setting an environment variable in Jupyter

    Short one. I wanted to setup an API key env variable in such a way that it’s easily available to Jupyter.

    It turns out that the easiest way is by adding it to IPython startup directly.

    You can find the path under, ~/.ipython/profile_default/startup/00-startup.py and if it’s not present, create it.

    The code that you add in this file is Python and can look in the following format:

    import os
    os.environ['MY_VAR'] = 'my_value'

    After you saved the edited file, don’t forget to restart the kernel.

    Cheers

  • Transforming from dict to separate columns

    I queried, some time ago, trace route info for IP’s in a list and took the wrong decision to save it in the following form.

    At first sight it’s not really an issue but if you want to retrieve it and create a dataframe it will look not as expected.

    Here is the actual code to separate the payload column to column defined by keys in dictionary

    import pandas as pd
    
    # Assuming 'df' is your DataFrame and 'payload' is the column containing dictionaries
    df_expanded = pd.json_normalize(trace_rt_df['payload'])
    
    # Rename columns to match original keys (optional)
    df_expanded.columns = df_expanded.columns.map(lambda x: x.split('.')[-1])
    
    # Concatenate the expanded columns with the original DataFrame
    df_final = pd.concat([trace_rt_df, df_expanded], axis=1)
    
    # Drop the original 'payload' column (optional)
    df_final.drop('payload', axis=1, inplace=True)

    After the processing the dataframe will look like

    That’s all.

    Sorin

  • Powerlifting play ground

    It’s true that I switched a little bit from this blog to Medium in hope of a larger audience but I will leave the link also here:

    https://medium.com/@sorin.tudor/powerlifting-play-ground-582c7e4da17d

    Hopefully even more analysis will come.

    Cheers!

  • Plotting unique values in a dataframe column

    Today, I began experimenting with a Kaggle dataframe for the first time. Here is the link to it: https://www.kaggle.com/datasets/open-powerlifting/powerlifting-database

    To make a long story short, if you want to plot the count for each individual column and capture the unique values of a particular column inside that dataframe, you can simply achieve it by using the following command:

    mycategory = powerlifting[powerlifting['Best3DeadliftKg'] == 140.0]
    mycategory.dropna(subset=['Country'], inplace=True)

    This allows you to filter the records that you are interested in, as well as remove the columns that have the value NAN.

    The last step involves the counting of the values for the country column and also creating a barplot:

    country_series =mycategory['Country'].value_counts()
    country_series.head(10).plot(kind='bar')

    We will select the first 10 countries in the series since the actual number of unique countries in the dataset is actually 118.

    And the plot looks like this.

    I wanted to document it because it’s an operation that I have done before, and the actual feedback from the chatbot when asked what is the solution was quite a bit more complex.

    First of all it consisted of the code to filter the values and save the definition of the bar plot to a JSON file, using vega-altair library (subject for exploration at one moment in time – https://altair-viz.github.io/) and parsing the data to create the plot.

    The first part worked without any issues, with the following piece of code:

    import altair as alt
    import pandas as pd
    
    # Assuming df is your DataFrame (from the previous example)
    
    # 1. Filter to column 'Country' and calculate unique value counts
    value_counts = mycategory['Country'].value_counts()
    
    # 2. Convert to DataFrame for plotting
    value_counts_df = pd.DataFrame({'Value': value_counts.index, 'Count': value_counts.values})
    
    # 3. Create bar plot
    chart = alt.Chart(value_counts_df).mark_bar().encode(
        x=alt.X('Value:N', axis=alt.Axis(title='Value')),
        y=alt.Y('Count:Q', axis=alt.Axis(title='Count')),
        tooltip=['Value', 'Count']
    ).properties(
        title='Value Counts for Column Country'
    )
    
    # Save the chart
    chart.save('value_counts_column_a_bar_chart.json')

    But the second part was a little bit tricky since the chatbot didn’t have a read idea of how the structure of the file was formed, suggesting:

    import plotly.graph_objects as go
    import json
    
    # Load JSON data
    with open('value_counts_column_a_bar_chart.json', 'r') as f:
        chart_data = json.load(f)
    
    # Extract data for plotting correctly, handling both nominal and quantitative data
    if 'Column Name' in chart_data['datasets'][0]['data'][0]:
        # Nominal data (e.g., categories like 'A', 'B', 'C')
        x = [d['Column Name'] for d in chart_data['datasets'][0]['data']]
        y = [d['Unique Value Count'] for d in chart_data['datasets'][0]['data']]
    else:
        # Quantitative data (e.g., numeric values)
        x = [d['Value'] for d in chart_data['datasets'][0]['data']]
        y = [d['Count'] for d in chart_data['datasets'][0]['data']]
    
    # Create Plotly bar chart
    fig = go.Figure([go.Bar(x=x, y=y)])
    
    # Customize layout (optional)
    fig.update_layout(
        title='Value Counts for Column A',
        xaxis_title='Value',
        yaxis_title='Count'
    )
    
    # Show the chart
    fig.show()
    

    If you try to compile that it will return a KeyError:0 which is cause by the index of the chart_data[datasets][0] which is not correct.

    Taking a look in the actual JSON structure you quickly find that the right key is data-85d48ef46f547bd16ab0f88b32c209fb, which bring us to the correct version:

    import plotly.graph_objects as go
    import json
    
    # Load JSON data
    with open('value_counts_column_a_bar_chart.json', 'r') as f:
        chart_data = json.load(f)
    
    # Extract data for plotting correctly, handling both nominal and quantitative data
    if 'Column Name' in chart_data['datasets']['data-85d48ef46f547bd16ab0f88b32c209fb']:
        # Nominal data (e.g., categories like 'A', 'B', 'C')
        x = [d['Column Name'] for d in chart_data['datasets']['data-85d48ef46f547bd16ab0f88b32c209fb']]
        y = [d['Unique Value Count'] for d in chart_data['datasets']['data-85d48ef46f547bd16ab0f88b32c209fb']]
    else:
        # Quantitative data (e.g., numeric values)
        x = [d['Value'] for d in chart_data['datasets']['data-85d48ef46f547bd16ab0f88b32c209fb']]
        y = [d['Count'] for d in chart_data['datasets']['data-85d48ef46f547bd16ab0f88b32c209fb']]
    
    # Create Plotly bar chart
    fig = go.Figure([go.Bar(x=x, y=y)])
    
    # Customize layout (optional)
    fig.update_layout(
        title='Value Counts for Country',
        xaxis_title='Value',
        yaxis_title='Count'
    )
    
    # Show the chart
    fig.show()

    Or even a more elegant one suggested by the LLM:

    mport plotly.graph_objects as go
    import json
    
    # Load JSON data
    with open('value_counts_column_a_bar_chart.json', 'r') as f:
        chart_data = json.load(f)
    
    # Find the correct data key within 'datasets'
    data_key = list(chart_data['datasets'].keys())[0]
    
    # Extract data for plotting correctly, handling both nominal and quantitative data
    if 'Column Name' in chart_data['datasets'][data_key][0]:
        # Nominal data (e.g., categories like 'A', 'B', 'C')
        x = [d['Column Name'] for d in chart_data['datasets'][data_key][:10]]
        y = [d['Unique Value Count'] for d in chart_data['datasets'][data_key][:10]]
    else:
        # Quantitative data (e.g., numeric values)
        x = [d['Value'] for d in chart_data['datasets'][data_key][:10]]
        y = [d['Count'] for d in chart_data['datasets'][data_key][:10]]
    
    # Create Plotly bar chart
    fig = go.Figure([go.Bar(x=x, y=y)])
    
    # Customize layout (optional)
    fig.update_layout(
        title='Value Counts for Country',
        xaxis_title='Value',
        yaxis_title='Count'
    )
    
    # Show the chart
    fig.show()

    Somewhere in the code is also a trim of the first 10 values in order to have similar outcomes. But the final plot looks like it should.

    And that my friends is a small “pill” of working with Data Analysis, assisted by a LLM.

    Cheers

  • Getting unique IP from mongoDB and use it for traceroute query

    Hi,

    Some time ago, I tried to write some python code in order to grab each unique IP from my traffic logs and trying to trace it so that We can find similar nodes which were used for the jumps.

    This is also a good exercise in order to improve the basic dataframe information and a good baseline for some explorations.

    I will put here the code so that it is available for me as reference and also maybe for you if you want to take pieces of it.

    I know that it is not optimised, but you can modify it or maybe use a chatbot to improve it.

    import pymongo
    import scapy.all as scapy
    
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    db = myclient["mydatabase"]
    read_col = db["unique_ip"]
    write_col = db["unique_ip_trace_tcp"]
    lastid = 0
    index_last_ip = write_col.find().sort([('_id', -1)]).limit(1)
    for doc in index_last_ip:
        doc['source_ip']
        index_id = read_col.find({"payload":doc['source_ip']})
        for elem in index_id:
            lastid=elem['id']
    print(lastid)
    for i in range(lastid, read_col.count_documents({})):
        mydoc = read_col.find({ "id": i })
        for x in mydoc:
            try:  
                for element in x['payload']:
                    response = {}
                    ans, unans = scapy.traceroute(element)    
                    response['source_ip'] = element
                    payload = {}
                    for sdr,rcv in ans:
                        payload[str(sdr.ttl)]= rcv.src
                    response['payload'] = payload    
                    write_col.insert_one(response)
            except Exception as e:
                print(e)
                continue

    That would be all.

    Cheers!