
Every research agent you build in this course depends on a stable foundation. If your Python setup changes from one day to the next, results that looked correct yesterday may quietly differ today. In this opening lecture you will check that your environment is reproducible, so that every later experiment can be repeated by you and by anyone else.
You will begin by inspecting the Python interpreter that is running. You will print its version and location, and confirm whether you are inside a virtual environment. This simple check prevents a very common beginner problem, where packages are installed in one place and the code runs in another.
Next you will look at the packages installed in the environment and compare them with a pinned requirements file that lists exact versions. You will write a short script that reads the requirements, compares them with what is actually installed and reports anything missing or different. This is a small piece of code that will save you time whenever you move the project to a new machine.
You will also discuss why reproducibility matters especially in research work. When you evaluate a trading idea, you want to know that a changed number comes from the idea and not from a library update.
The course uses synthetic and sample data only, and nothing in it is investment advice.
By the end of this lecture you will be able to inspect your interpreter, verify installed packages against pinned versions and prepare a clean workbench for building research agents.
Research agents often need credentials, such as an API key for a language model or a market data service. Handling those secrets carelessly is one of the easiest ways to cause a serious problem. In this lecture you will learn to read API keys from environment variables so that they never appear in your source code.
You will begin with the reason. Code is copied, shared and committed to version control, and a key written directly into it can spread widely. Environment variables keep secrets outside the code, so the same program can run on different machines with different credentials.
Next you will use the os module to read a variable with environ and with the get method, and you will see the difference between them. You will write a small helper that returns a required setting and raises a clear error that names the missing variable, without ever printing its value. You will also provide safe defaults for harmless settings, such as a log level.
You will learn how to set variables for a session in a terminal and how a local environment file can be used during development, as long as it is excluded from version control. You will discuss masking a key when it must appear in a log, showing only a few characters.
You will test the helper with harmless placeholder values only.
By the end of this lecture you will be able to read configuration from the environment, fail clearly when it is missing and keep secrets out of your code and logs.
Language models produce free text, but a research workflow needs predictable data. If an agent returns a recommendation in a different shape each time, the rest of your program cannot rely on it. In this lecture you will define a structured output schema with Pydantic so that every result has the same fields and types.
You will begin with what Pydantic offers. You describe the shape of your data as a class with typed fields, and the library checks values for you, converting them where it can and raising a detailed error where it cannot. This gives you a strong contract between the model and your code.
Next you will define a schema for a small research finding. It will contain a ticker symbol, a short summary, a sentiment label limited to a fixed set of values, a confidence number between zero and one and a list of source references. You will add constraints such as minimum lengths and numeric ranges, and you will use an enumeration for the allowed labels.
You will create valid instances and then try invalid ones on purpose, reading the error messages to see which field failed and why. You will also export a schema as JSON, which you can later include in a prompt so that the model knows the expected format.
All examples use made-up symbols and values for learning purposes.
By the end of this lecture you will be able to define typed, validated schemas with Pydantic and use them as the contract for agent output.
A schema is only useful if you can turn the model's reply into an object that follows it. Replies may contain extra text, missing fields or values of the wrong type. In this lecture you will parse a model response into validated output and handle the cases where it does not fit.
You will begin with a sample response held in a string, since you will use mock outputs rather than a paid service. It looks like JSON but may arrive wrapped in explanatory text or in a fenced code block. You will write a helper that extracts the JSON portion by locating the first opening brace and the matching closing brace.
Next you will parse the text with the json module and pass the resulting dictionary to your Pydantic model. When validation succeeds, you receive a typed object that is safe to use. When it fails, you will catch the validation error and turn it into a short, readable message that could be sent back to the model in a repair prompt.
You will practise with several synthetic replies: a perfect one, one with a missing field, one with an out-of-range confidence and one that is not JSON at all. You will check that each is handled correctly and that failures never crash the program.
You will also discuss a simple retry strategy with a limited number of attempts.
By the end of this lecture you will be able to extract JSON from model text, validate it against a schema and handle malformed replies in a controlled way.
Every research workflow starts with data. Before an agent can analyse a market, you need to load prices into your program in a form you can work with. In this lecture you will load raw price data from a local CSV file using pandas.
You will begin by looking at the file itself. It is a small sample with columns for the date, open, high, low, close and volume, created for this course and not taken from any live market. You will open it in a text editor first so that you know exactly what pandas will see.
Next you will use read_csv to create a DataFrame. You will learn about useful options, such as parsing the date column as dates, setting the date as the index and choosing which columns to read. You will inspect the result with head, info and describe, and learn to read the data types so that numbers that were loaded as text are noticed early.
You will discuss why loading from a local file is a good starting point. It is fast, free and repeatable, and the same code structure can later read from a different source.
You will also see what happens with a bad path or a malformed file, and how to handle those errors with a clear message.
By the end of this lecture you will be able to load price data from CSV, set a date index and inspect the structure and types of a DataFrame.
Raw data often looks fine at a glance but hides rows that make no sense, such as a negative price or a high value that is lower than the low. If these rows enter your analysis, every later result is affected. In this lecture you will validate price rows with a Pydantic model.
You will begin by thinking about what a valid row means. The date must be a real date, prices must be positive, the high must be at least as large as the low and the volume must not be negative. These are rules you can write down clearly and test automatically.
Next you will define a Pydantic model for one price row with typed fields and constraints. You will add a model-level validator that compares the high and low values and rejects rows where the relationship is wrong. You will then loop through the DataFrame, convert each row into a dictionary and validate it.
Rather than stopping at the first problem, you will collect the failures in a list that records the row number and the reason. You will produce a short report that shows how many rows passed and how many failed, which is a useful habit for any data pipeline.
You will test with a sample file that contains a few deliberately broken synthetic rows.
By the end of this lecture you will be able to express data rules as a model, validate rows in bulk and report problems clearly.
Real datasets are rarely complete. Values go missing, rows are repeated and gaps appear in the calendar. Deciding what to do about them is a research decision as well as a technical one. In this lecture you will clean missing values and duplicates in a price dataset.
You will begin by finding the problems. You will use isna and sum to count missing values in each column, and duplicated to find repeated rows or repeated dates. You will print a short summary before you change anything, so you have a record of what the data looked like.
Next you will remove duplicates with drop_duplicates, choosing which copy to keep and explaining why. For missing values, you will compare strategies. Dropping rows is simple but loses information, forward filling carries the last known price into the gap, and interpolation estimates a value between neighbours. You will discuss the risks of each. For example, filling can hide the fact that no trading happened, and a careless fill can leak future information into the past.
You will also sort by date, check that the index is unique and look for unexpected jumps in the calendar. You will write the cleaning steps as a function that returns a new DataFrame and a log of what it changed, rather than altering the original.
You will test with synthetic data that has known gaps and repeated rows.
By the end of this lecture you will be able to detect and handle missing values and duplicates and document each cleaning choice.
In practice, data arrives from more than one place, and each source uses its own names and formats. One file may call a column Close while another calls it price, and one may use dates written differently from another. In this lecture you will normalise multiple sources into one common schema.
You will begin with two small sample files that describe the same kind of information but in different layouts. You will compare them side by side and list the differences in column names, date formats, units and ordering.
Next you will write a mapping for each source that renames columns, converts dates to a single format and adjusts units where necessary. You will build a function that takes a DataFrame and a source description and returns data in the shared layout. You will then reuse the Pydantic row model from earlier to confirm that the output of each source conforms.
You will combine the normalised pieces with concat, add a column that records which source each row came from and handle overlapping dates by choosing a clear rule for which source wins. You will also think about time zones and why they should be settled early.
You will test the result with synthetic samples and check that the final table has consistent columns, types and a unique, sorted date index.
By the end of this lecture you will be able to map different layouts to one schema, combine sources safely and keep track of where each row came from.
Cleaning and normalising data takes time, and there is no reason to repeat the work every time you run an experiment. In this lecture you will cache cleaned datasets to Parquet, a compact and fast file format that keeps column types intact.
You will begin by comparing formats. A CSV file is simple and readable, but it stores everything as text, so types and dates must be guessed again on every load. Parquet is a binary columnar format that stores types with the data, compresses well and loads quickly, which makes it a good choice for working datasets.
Next you will write the cleaned DataFrame to a Parquet file with to_parquet and read it back with read_parquet. You will install the supporting engine, check that the data types and the index survive the round trip and compare the file size and load time with the CSV version.
You will then build a small caching helper. Before cleaning, it checks whether a cached file exists and is newer than the source file. If so, it loads the cache. Otherwise it runs the cleaning steps and saves the result. You will discuss how to name cache files so that a change in settings creates a new file instead of reusing an old one.
You will test by running the helper twice with synthetic data and observing that the second run is faster.
By the end of this lecture you will be able to save and load Parquet files and avoid repeating expensive data preparation.
An agent can only use a tool if it understands what the tool does and what it needs. In this lecture you will describe a tool using a typed Python function signature, which becomes the foundation for tool calling in the rest of the course.
You will begin with the idea of tool calling. A language model does not run code itself. It proposes a call, with a name and arguments, and your program decides whether to run it. For that to work well, each tool needs a clear name, a description and a precise list of arguments.
Next you will write a simple tool as an ordinary function, such as one that returns the average closing price of a sample dataset over a number of days. You will add type hints for each parameter and for the return value, and you will write a docstring that explains the purpose in plain language.
You will then use the inspect module to read the function's signature and annotations automatically. You will extract the parameter names, types, default values and which parameters are required, and gather them into a small structure that describes the tool.
You will see why good descriptions matter, since the model relies on them to choose and call tools correctly. You will compare a vague docstring with a clear one.
By the end of this lecture you will be able to write typed tool functions and read their signatures programmatically to describe them to an agent.
Models and tool frameworks usually describe tool arguments using JSON Schema. In this lecture you will turn the typed signature from the previous lesson into a JSON Schema document that can be given to a model.
You will begin with a short introduction to JSON Schema. It is a standard way to describe the shape of JSON data, with a type for each property, a list of required properties and optional details such as descriptions, minimum and maximum values and allowed choices.
Next you will write a function that converts Python types into schema types, mapping int to integer, float to number, str to string, bool to boolean and lists to arrays. You will mark arguments without defaults as required and include defaults for the others. You will also handle enumerations and literal types by listing the allowed values.
As an alternative, you will see how Pydantic can generate a schema from a model class, and you will compare that approach with your hand-written converter. You will decide when each is more convenient.
You will then wrap the schema together with the tool name and description in the structure that many model APIs expect. You will print the result and check it by reading it carefully.
You will test the converter with several example functions that have different parameter styles.
By the end of this lecture you will be able to generate JSON Schemas from function signatures and package them as tool definitions.
A model may propose a tool call with arguments that are missing, misspelled or of the wrong type. Running such a call blindly can cause confusing failures or unsafe behaviour. In this lecture you will validate tool call arguments before executing anything.
You will begin by looking at a proposed call, which is a name and a dictionary of arguments, usually produced by parsing the model's output. You will list the kinds of mistakes you should expect: a required argument is absent, an unknown argument appears, a number arrives as text or a value falls outside the permitted range.
Next you will build a validator from the tool's schema. You will check that all required arguments are present, reject unknown ones and confirm that each value has the expected type. Where it is sensible, you will convert values, such as the string 5 to the integer 5, and where it is not, you will report an error. You will also enforce limits, such as a maximum number of days.
Rather than raising a bare exception, you will return a structured result that contains either the cleaned arguments or a list of error messages. These messages can be returned to the model so that it can correct its next attempt.
You will test using synthetic proposed calls, both valid and invalid.
By the end of this lecture you will be able to validate tool calls against schemas, report precise errors and refuse to run anything that does not meet the contract.
By now you can describe tools and validate calls to them. The remaining piece is the machinery that finds the right function and runs it. In this lecture you will dispatch tool calls with a tool registry.
You will begin with the problem a registry solves. As the number of tools grows, a long chain of conditions becomes hard to maintain. A registry is a dictionary-like object that maps tool names to their functions and descriptions, so that adding a tool does not require changing the dispatching code.
Next you will write a registry class with a decorator that registers a function, builds its schema automatically from the signature and stores everything under its name. You will add methods to list the available tools, which provides the definitions to send to a model, and to look up a tool by name.
You will then write the dispatch method. It receives a proposed call, finds the tool, validates the arguments with the validator from the previous lecture, runs the function and returns a structured result. You will wrap the execution so that exceptions inside a tool become error results instead of crashing the agent, and you will return a clear message for an unknown tool name.
You will test by registering several small tools that work on synthetic data and sending valid and invalid calls through the dispatcher.
By the end of this lecture you will be able to build a registry, register tools with a decorator and dispatch calls safely.
An agent that works step by step needs somewhere to keep track of what has happened so far. That record is its state. In this lecture you will define the state of an agent loop, which is the foundation for the research workflows you will build in this section.
You will begin by asking what an agent must remember while it works on a question. It needs the original task, the history of its reasoning steps, the tools it has called, the observations those tools returned and a counter of how many steps it has taken. It also needs a way to know when to stop.
Next you will define the state as a Python dataclass or a Pydantic model. You will create fields for the question, a list of step records, a list of collected sources, a step counter, a maximum step limit and a status that is one of running, finished or failed. You will write a small structure for a single step that contains the thought, the action, the arguments and the observation.
You will add helper methods that append a step, check whether the limit has been reached and produce a short text summary of the history that can be placed in a prompt. You will think about keeping this history compact so that prompts do not grow without bound.
You will test the state with synthetic steps and confirm that limits and status changes behave correctly.
By the end of this lecture you will be able to model agent state clearly, track steps and observations and enforce a maximum number of steps.
The ReAct pattern asks a model to alternate between reasoning about a problem and taking an action, then to read the result before continuing. How well it works depends heavily on the prompt. In this lecture you will write a ReAct prompt template for a research agent.
You will begin with the shape of a ReAct exchange. The model writes a thought explaining what it plans to do, then an action naming a tool and its arguments, and it then waits for an observation produced by your program. The cycle repeats until the model writes a final answer.
Next you will write the template as a Python string with placeholders. It will contain a short role description for a financial research assistant, a list of the available tools with their descriptions, the exact output format that the model must follow, the question and the history so far. You will make the format strict, with labelled lines such as Thought, Action, Action Input and Final Answer, so that it can be parsed reliably.
You will include clear rules in the prompt. The agent must use only information obtained from tools, must say when evidence is missing and must not give investment advice. You will fill the template with synthetic values and read the resulting prompt as the model would see it.
By the end of this lecture you will be able to write a clear ReAct template, describe tools inside it and set rules that keep the agent grounded and cautious.
A prompt is only half of the conversation. Your program must also understand what the model wrote back. In this lecture you will parse the thought and action out of model output so that the agent loop knows what to do next.
You will begin with several sample outputs, held as strings so that no paid service is needed. A good one has a Thought line, an Action line and an Action Input line containing JSON. Others are less tidy, with extra text, a missing label or an action that is not a known tool.
Next you will write a parser using regular expressions. It will look for the labelled lines, capture their contents and handle multi-line thoughts. It will then decode the action input with the json module. You will also detect a Final Answer, which tells the loop to stop and returns the answer text.
You will define a small result type with three possibilities: an action to run, a final answer or a parse error. When parsing fails, you will produce a clear message that can be returned to the model as an observation so that it can fix its format on the next step.
You will think about safety too. The parser should never execute anything. It only produces data that the dispatcher will validate afterwards.
You will test with a range of synthetic outputs, both valid and broken.
By the end of this lecture you will be able to parse structured reasoning text, detect final answers and report format problems helpfully.
You now have a state, a prompt template and a parser. In this lecture you will connect them in the plan, act and observe loop that gives an agent its behaviour.
You will begin by walking through one cycle. The loop builds a prompt from the current state, asks the model for its next output, parses it and, if it is an action, validates and runs the tool through your registry. The result becomes an observation, which is added to the state, and the cycle begins again. If the model produces a final answer, the loop ends.
To keep everything testable and free of cost, you will use a scripted mock model that returns a prepared sequence of outputs. This lets you check the exact path the loop takes, and the same loop code will work with a real model later by swapping one function.
You will add important controls. A maximum step count prevents endless loops, repeated identical actions are detected and stopped and unknown tools or invalid arguments produce error observations rather than crashes. You will record each step in the state so that the full run can be inspected afterwards.
You will run the loop on a small task that uses a tool to compute a summary statistic on synthetic price data, and print the full trace of thoughts, actions and observations.
By the end of this lecture you will be able to implement an agent loop, supply a mock model for testing and protect it with sensible limits.
A research agent is only valuable if people can check what it says. A note that makes claims without showing where they came from cannot be trusted. In this lecture you will produce a sourced research note from the results of an agent run.
You will begin by reviewing what the loop has collected: observations, the tools that produced them and the sources attached to them. You will decide how these should appear in the final note, with each claim linked to the evidence that supports it.
Next you will design the note as a structured object with a title, a short summary, a list of findings, each with a statement and a list of source identifiers, and a section that lists limitations and open questions. You will use Pydantic to keep the structure valid, and you will write a function that checks that every finding refers to at least one source that really exists in the run.
You will then render the note as readable text, using numbered references such as bracketed numbers that match a source list at the end. You will include a plain statement that the note is for research and education and is not investment advice.
You will think about wording. Claims should be as strong as the evidence, and uncertainty should be stated rather than hidden.
You will test with synthetic observations, including a case where a finding lacks a source and should be rejected.
By the end of this lecture you will be able to assemble evidence into a structured, cited research note and enforce that claims are traceable.
Financial documents such as filings and earnings transcripts are long, and a model cannot read all of one at once. The usual solution is to split documents into smaller pieces, called chunks, and retrieve only the relevant ones. In this lecture you will split text into overlapping chunks.
You will begin with the reasons. Models have limited context, and smaller pieces make retrieval more precise. But cutting text at arbitrary points can split a sentence or separate a statement from its context. Overlap, where the end of one chunk is repeated at the start of the next, reduces the chance that important information falls on a boundary.
Next you will write a chunking function with parameters for chunk size and overlap, measured in characters or words. You will start with a simple sliding window, then improve it by moving boundaries to the nearest sentence end or paragraph break so that chunks read naturally. You will handle short documents, empty text and an overlap that is too large.
You will use a short synthetic document written for this course, rather than a real filing, and print the chunks with their lengths and positions so you can see the overlaps. You will discuss how to choose sizes by considering the kind of question you expect.
You will test the function for properties such as full coverage and the absence of empty chunks.
By the end of this lecture you will be able to split documents into overlapping chunks and choose sensible size and overlap settings.
A retrieved chunk is only useful if you know where it came from. When your agent writes a claim, a reader must be able to trace it back to a document, a section and a date. In this lecture you will attach source metadata to chunks.
You will begin by deciding what a source record needs. Typical fields are a document identifier, a title, a document type such as a filing or news item, a date, a section name and the position of the chunk in the document. A stable chunk identifier built from these values makes citations precise.
Next you will define a Pydantic model for the metadata and another for a chunk that combines text with its metadata. You will update the chunking function from the previous lecture so that it returns these objects, filling in the position and section for each piece. You will generate identifiers that are deterministic, so that running the process twice gives the same result.
You will also store derived information, such as the character offsets, which later allows you to show the exact passage that supports a claim. You will think about what should not be stored, avoiding sensitive details that are not needed.
You will test with two synthetic documents, a filing-style text and a news-style text, and check that every chunk has complete metadata and a unique identifier.
By the end of this lecture you will be able to model chunks with rich metadata, create stable identifiers and prepare your data for traceable citations.
To search by meaning rather than by exact words, you turn text into vectors, which are lists of numbers where similar meanings sit close together. In this lecture you will turn chunks into vectors and learn how embeddings work in a retrieval system.
You will begin with the idea. An embedding model reads a piece of text and returns a vector of fixed length. Two passages about the same topic produce vectors that point in similar directions, even if they use different words. This is what allows semantic search.
To keep the course self-contained and free of cost, you will build a simple deterministic embedding function. It will use hashed word counts into a fixed number of dimensions, with normalisation so that every vector has the same length. You will understand that real embedding models are far more capable, but the interface is the same: text in, vector out. Because the interface is the same, you can replace your function with a real model later without changing the rest of the code.
You will embed all the chunks from the previous lecture and store the vectors alongside their identifiers in a simple in-memory index, using NumPy arrays. You will check the shapes and the lengths of the vectors.
You will also think about batching and about caching vectors so that unchanged text is not embedded twice.
By the end of this lecture you will be able to create vectors from chunks, store them in an index and explain the role of embeddings in retrieval.
Once chunks are vectors, finding the most relevant ones for a question becomes a matter of comparing vectors. The most common measure is cosine similarity. In this lecture you will rank chunks with cosine similarity and return the best matches.
You will begin with the mathematics, kept simple. Cosine similarity measures the angle between two vectors. A value near one means they point the same way, a value near zero means they are unrelated and a negative value means they point apart. It ignores length, which is why normalised vectors are convenient.
Next you will implement the calculation with NumPy as a dot product divided by the product of the lengths, and check it on small vectors where you can work out the answer by hand. You will then extend it to compare one query vector against the whole matrix of chunk vectors at once, which is far faster than a loop.
You will write a search function that embeds the question, scores every chunk, sorts the scores and returns the top results with their metadata and scores. You will add a minimum score so that weak matches are not returned, because an honest no result is better than an irrelevant one.
You will test with synthetic questions about the sample documents and check that the expected chunks appear at the top. You will also look at a question with no good match and see how the threshold helps.
By the end of this lecture you will be able to compute cosine similarity, rank chunks efficiently and filter weak matches.
Retrieval finds the evidence, but the answer must stay faithful to it. In this lecture you will answer questions with grounded citations, so that every statement your agent makes points back to a retrieved chunk.
You will begin with the structure of a grounded answer. The prompt includes the question and the retrieved chunks, each labelled with an identifier. The instructions tell the model to use only the supplied text, to cite the identifiers for each statement and to say that the answer is not available when the evidence does not contain it.
Next you will write a function that builds this prompt from the top-ranked chunks, keeping within a size limit. You will use a mock model that returns prepared answers with citations, so no paid service is required. You will then parse the answer, extract the cited identifiers with a regular expression and check that each one corresponds to a chunk that was actually provided.
You will add a check that rejects answers with no citations at all and flags citations to unknown identifiers, which are a sign of invention. You will display the final answer with the cited passages listed underneath, so that a reader can verify each claim quickly.
You will discuss the limits of this approach. A citation shows where a claim came from, but it does not prove that the claim matches the source, which you will address later with checks for hallucinated claims.
By the end of this lecture you will be able to build grounded prompts, parse and verify citations and present answers with their evidence.
Financial news is full of opinion, and turning it into a number is a common first step in research. The simplest approach is a sentiment lexicon, a list of words with scores. In this lecture you will score headlines with a lexicon you write yourself.
You will begin with the idea. Each word in a small dictionary has a positive or negative value, such as plus one for words like gain or beat and minus one for words like loss or miss. The score of a headline is derived from the words it contains. It is crude, but it is transparent, fast and easy to explain, which makes it a valuable baseline.
Next you will write the lexicon as a Python dictionary and a function that lowercases a headline, splits it into words, removes punctuation and adds up the scores. You will handle negations, so that a phrase such as not strong flips the meaning of the following word, and you will normalise the total by the number of words or clip it to a fixed range.
You will score a set of synthetic headlines written for this course and print each with its score and label. You will examine cases where the lexicon fails, such as sarcasm, mixed statements and words that change meaning with context.
You will also compare the lexicon with the idea of using a language model, and discuss why a simple baseline is useful for checking it.
By the end of this lecture you will be able to build a lexicon scorer, handle simple negation and recognise its limitations.
When a language model scores sentiment, you cannot assume the answer is well formed or sensible. A score of seven on a scale from minus one to one, or a label that is not in your list, would quietly damage later calculations. In this lecture you will validate agent sentiment output before using it.
You will begin by defining what valid output looks like. The agent should return a label from a fixed set, a numeric score within a range and a short rationale, and the label and score should agree with each other. A positive label with a strongly negative score is a sign of a problem.
Next you will write a Pydantic model for the sentiment result with a literal type for the label, a bounded float for the score and a validator that checks consistency. You will also check that the rationale is not empty and not excessively long.
You will then compare the agent's score with the lexicon score from the previous lecture as a sanity check. When the two disagree strongly, you will mark the result for review instead of accepting it silently. You will write a function that processes a batch of synthetic results and returns accepted, rejected and flagged groups with reasons.
This kind of cross-checking is a core habit in reliable AI systems.
By the end of this lecture you will be able to validate model sentiment output, enforce consistency rules and use a simple baseline to flag suspicious results.
Individual headline scores are noisy. A research process needs something steadier, such as one value for each day. In this lecture you will aggregate sentiment scores into a daily signal that can later be compared with market behaviour.
You will begin with a table of synthetic headlines with timestamps, tickers and sentiment scores. You will convert the timestamps to dates and group the rows by ticker and day using pandas groupby.
Next you will compute summary statistics for each group, such as the mean score, the number of headlines and the share that are positive. You will see why the count matters. An average based on one headline is much less reliable than one based on twenty, so you will add a rule that reduces or removes the signal when too few items are available.
You will consider timing carefully. News published after a market closes should not be assigned to that same trading day if you plan to compare it with that day's return, because that would use information before it was known. You will implement a simple cut-off rule and discuss lookahead bias, which is one of the most common errors in research.
You will also smooth the series with a rolling average and fill days with no news in a way that does not invent information.
You will test with a small dataset and check each step by hand.
By the end of this lecture you will be able to group and aggregate scores, handle sparse days and avoid lookahead bias.
Momentum is one of the best known ideas in quantitative research: assets that have recently risen are sometimes studied for whether they continue to rise, and the reverse for falling assets. In this lecture you will compute a momentum factor signal from price data, purely as a research exercise on synthetic prices.
You will begin with the definition. A simple momentum measure looks at the return over a past window, such as the previous sixty trading days, and often skips the most recent few days to avoid short-term reversals. You will write down the formula and compute it by hand for a tiny example.
Next you will load a cleaned synthetic price table and calculate returns with pct_change and shift. You will compute the lookback return for each day and each ticker, taking care that every value uses only information available at that date. You will check this by confirming that the first rows are empty rather than filled with guessed values.
You will then turn the raw values into a signal that is comparable across assets. You will rank each ticker against the others on each day or standardise the values with a z-score, and you will discuss how outliers can distort a result and how clipping can help.
You will plot or print the signal for a few dates and read it critically. A number that looks convincing is not evidence that it works.
This course is educational, and nothing here is investment advice.
By the end of this lecture you will be able to compute a momentum factor, standardise it across assets and avoid lookahead errors.
A signal is just an idea until it is tested against what happened next. In this lecture you will backtest a signal against forward returns, which is the simplest way to ask whether a signal had any relationship with later price moves in your sample data.
You will begin with the concept of a forward return. For each day, it is the return over the following period, such as one or five days. You will calculate it with shift using a negative value, and you will understand carefully why this is allowed here. It is the outcome you are trying to relate to the signal, not information you may use to produce it.
Next you will align the signal and the forward return in one table and drop the rows where either value is missing. You will compute the correlation between them, often called an information coefficient, and group the data into buckets, such as the lowest and highest thirds of the signal, to compare their average forward returns.
You will discuss why results from small or synthetic samples should be treated with caution. A single number can arise by chance, so you will look at how it varies across time periods and how many observations support it. You will also consider overfitting, where trying many ideas on the same data produces a result that does not hold up.
You will print a short, honest report that includes the sample size.
By the end of this lecture you will be able to align signals with forward returns, compute simple evaluation measures and describe the limits of a backtest.
Multi-agent systems divide a research task between specialists, such as an analyst who gathers facts, a risk reviewer who challenges them and an editor who writes the result. To make such a team manageable, you can treat each agent as a pure state transformer. In this lecture you will build specialist agents in that style.
You will begin with the idea. A pure state transformer is a function that takes the current workflow state and returns a new state, without hidden side effects. Because it depends only on its input, it is easy to test, easy to replay and easy to combine with others.
Next you will define the shared state as a typed structure with fields such as the question, collected findings, a risk assessment, a draft and a log of messages. You will then write three agents as functions. The analyst adds findings using your tools and retrieval, the risk reviewer examines them and produces a verdict with reasons, and the editor turns approved findings into a draft.
You will make each function return a copy of the state with its additions, rather than changing the original, and you will record which agent made which change. You will use mock model calls so that behaviour is repeatable.
You will test every agent separately, giving it a prepared state and checking the output, before they are ever connected.
By the end of this lecture you will be able to design specialist agents as pure functions, share state between them and test each one in isolation.
Once you have several agents, you need a way to say who runs, in what order and under what conditions. A graph is a natural way to describe this. In this lecture you will wire your agents into a graph with nodes and edges.
You will begin with the vocabulary. A node is a step in the workflow, which in your case is an agent function. An edge is a connection that says which node runs next. Together they form a map of the process that can be read at a glance and changed without rewriting the agents.
Next you will write a small graph class. It will let you add nodes by name, add edges between names and set a start node and an end marker. You will then write a runner that begins at the start, calls each node with the current state, replaces the state with the result and follows the edge to the next node until it reaches the end.
You will add safeguards, such as checking that every edge points to a real node, detecting cycles that could run forever by limiting the number of steps and recording the path taken. You will print the path for a run and view the graph as a simple text diagram.
You will test with the analyst, risk reviewer and editor from the previous lecture connected in a straight line.
By the end of this lecture you will be able to define nodes and edges, run a graph of agents and validate its structure.
A straight line of agents is only the beginning. Real research teams make decisions along the way: if the risk reviewer is not satisfied, the work should go back for more evidence rather than move on to the editor. In this lecture you will add conditional routing based on risk verdicts.
You will begin by defining the verdict. The risk reviewer will return one of a few values, such as approve, needs more evidence or reject, together with reasons. You will store the verdict in the shared state as a typed field so that it can be inspected by other parts of the workflow.
Next you will extend the graph with conditional edges. Instead of naming a single next node, an edge can hold a routing function that reads the state and returns the name of the next node. You will write a router that sends approved work to the editor, sends work that needs more evidence back to the analyst and ends the run on a rejection with an explanation.
You will think about loops. Sending work back creates a cycle, so you will track the number of revisions in the state and stop after a fixed limit, ending with a clear message that the evidence was insufficient. This prevents an endless back and forth.
You will test every route using prepared synthetic states and confirm that the path taken matches the verdict.
By the end of this lecture you will be able to write routing functions, build conditional edges and bound revision loops safely.
Agents that forget everything between runs repeat work and cannot build on earlier results. In this lecture you will give your research team memory that persists across workflow runs.
You will begin by separating two kinds of memory. Working memory is the state inside a single run, which you already have. Long-term memory is information saved after a run and loaded in later ones, such as past findings, source lists and decisions about what was checked.
Next you will design a simple memory store. It will save entries as records with a topic, a ticker, a summary, the sources, a timestamp and the run identifier that created it. You will use a JSON lines file or a small SQLite database from the standard library, and you will write functions to add entries and to search them by ticker and topic.
You will then connect the memory to the workflow. Before the analyst starts, it loads relevant earlier entries and includes them as context. After the editor finishes, the run saves its new findings. You will discuss the risks. Old information can become stale or wrong, so each entry carries a date and the workflow should treat older items with caution and prefer fresh evidence.
You will also add a limit on how many entries are loaded, so that prompts remain small, and a way to delete or expire entries.
You will test with two consecutive synthetic runs and show that the second can see the first.
By the end of this lecture you will be able to store and retrieve agent memory and use it responsibly in later runs.
Now you can bring the whole team together. In this lecture you will run the full research team on a question and trace the run so that you can see exactly what each agent did.
You will begin by assembling the pieces from this section: the shared state, the analyst, risk reviewer and editor, the graph with conditional routing and the memory store. You will build the full graph and prepare a synthetic question about a made-up company, with sample data, documents and headlines.
Next you will add tracing. Each time a node runs, the runner records the node name, the time it started and finished, a summary of the changes it made to the state and any errors. You will collect these into a trace object that can be printed as a readable timeline or saved as JSON.
You will run the workflow with mock models, once on a path where the evidence is sufficient and once where the reviewer asks for more. You will read both traces and confirm that the routing, the revision count and the final output match what you expect.
You will learn how a trace helps with debugging, evaluation and accountability. When an answer is wrong, the trace shows where the mistake entered. You will also check the final report for citations and for the statement that it is not investment advice.
By the end of this lecture you will be able to run a multi-agent workflow end to end and use traces to understand and verify what happened.
Agents can propose research ideas, but ideas need to be tested in a consistent way. In this lecture you will backtest an agent's idea using a simple signal-to-position rule, turning a signal into holdings and measuring what would have happened on historical sample data.
You will begin by defining the rule. A signal above a threshold means a long position of one unit, below a negative threshold means a short position and anything in between means no position. You will write this as a function that maps a signal series to a position series with values of one, minus one and zero.
Next you will deal with timing, which is the most important detail. A signal calculated at the close of one day can only be traded afterwards, so the position must be shifted by one day before it is multiplied by the next day's return. You will implement the shift explicitly and show what happens to the results if you forget it, so that the effect of lookahead bias is clear.
You will calculate the daily strategy return as position times return, then the cumulative return with a cumulative product. You will compare it with a simple buy and hold baseline on the same synthetic data, because a result means little without a comparison.
This is a learning exercise, and no result here predicts real performance or constitutes advice.
By the end of this lecture you will be able to convert signals into positions, align them correctly in time and compute strategy returns against a baseline.
A cumulative return curve can look attractive while hiding how painful the journey was or how much trading cost along the way. In this lecture you will score a backtest more honestly, using maximum drawdown and transaction costs.
You will begin with drawdown. It measures the fall from a previous peak in the equity curve. You will compute the running maximum with cummax, divide the curve by it and subtract one to get the drawdown series. The minimum of that series is the maximum drawdown, which describes the worst peak-to-trough loss in the sample and helps you judge whether a strategy would have been bearable.
Next you will add transaction costs. Every change in position has a cost, so you will compute the absolute change in position each day and multiply it by a cost rate, such as a number of basis points. You will subtract this from the daily return and compare the result with the version without costs. You will see how a strategy that trades frequently can lose its apparent edge once costs are included.
You will also compute a few simple summary measures, including the annualised return, the annualised volatility and a return-to-risk ratio, and discuss what each does and does not tell you.
You will present the results in a small report that states the sample length, the assumptions and the limitations.
By the end of this lecture you will be able to calculate drawdown, include trading costs and report backtest results with appropriate caution.
Language models can state things that sound right but are not supported by the evidence. In a research setting, those hallucinated claims are especially harmful. In this lecture you will detect hallucinated claims by checking them against the source chunks they cite.
You will begin by breaking an agent's answer into individual claims, usually one sentence at a time, and linking each to the chunk identifiers it cites. You will use a regular expression to extract the citations and a simple sentence splitter to separate the claims.
Next you will write a support check. For each claim, you will compare it with the cited chunk text. A basic version looks at the overlap of important words and at whether any numbers in the claim also appear in the source. You will write a function that extracts numbers and checks them, since a wrong figure is one of the most serious kinds of error in financial writing.
You will classify each claim as supported, weakly supported or unsupported, and produce a report with the reasons. Claims with no citation or with a citation to a missing chunk are marked unsupported immediately.
You will discuss the limits of such a check. Word overlap cannot judge meaning, so in practice it works as a first filter, to be combined with a model-based judge and human review for important outputs.
You will test with synthetic answers that contain correct and invented statements.
By the end of this lecture you will be able to split answers into claims, check them against sources and flag unsupported statements.
Agents can fail in expensive ways: they may loop, call tools too often or produce output that should never be shown. In this lecture you will add guardrails and cost controls to agent runs so that they stay safe and within budget.
You will begin with cost. Every model call consumes tokens, and tokens cost money. You will write a budget tracker that records the tokens used in each call, converts them to an estimated cost using a price table with the Decimal type and compares the total with a limit. When the limit is reached, the run stops with a clear message instead of continuing.
Next you will add limits on behaviour. You will cap the number of steps, the number of calls to each tool and the total run time, using an injected clock so that tests are quick. You will also detect repeated identical actions and stop them.
You will then add content guardrails. On input, you will reject questions that ask for something outside the scope of the agent, such as personal financial advice. On output, you will check that the report includes its sources and the required disclaimer and that it does not contain restricted wording, such as guaranteed returns.
Each guardrail returns a decision with a reason, and the runner records every decision in the trace.
You will test each control with synthetic runs designed to break it.
By the end of this lecture you will be able to enforce budgets and limits, apply input and output guardrails and record guardrail decisions for review.
The capstone brings together everything you have built into one product: an automated daily research briefing. In this lecture you will compose the briefing pipeline as a sequence of stages, each with a clear input and output.
You will begin by listing the stages. First, load and validate the cleaned data. Then retrieve relevant document chunks, score the news sentiment, compute the signals, run the research team, check claims against sources, apply the guardrails and finally produce the report. Each stage receives a shared context and returns an updated one.
Next you will define a stage interface as a function that takes a context object and returns a context object, along with a name. You will write a pipeline runner that executes the stages in order, records how long each took and handles failure policy. Some stages are essential, so a failure stops the run, while others are optional, so a failure is logged and the briefing is marked as partial.
You will build the context as a typed structure that carries the date, the tickers, the datasets, the findings, the signals, the draft and a list of warnings. You will connect the earlier pieces from the course using mock models and synthetic data.
You will run the pipeline for one made-up trading day and print the stage timings and warnings.
By the end of this lecture you will be able to compose a multi-stage pipeline, define failure policy for each stage and run it end to end.
The final product of the pipeline is a report that a person will read. It must be clear, well organised and honest about its evidence. In this lecture you will render the briefing as a Markdown report.
You will begin by designing the layout. A good briefing has a title with the date, a short summary of the main points, a section for each ticker with signals and sentiment, a section of findings with numbered citations, a list of sources, a section on limitations and checks and a clear disclaimer that the content is for research and education and is not investment advice.
Next you will write rendering functions that turn the structured data into Markdown text. You will create headings, bullet lists and tables with helper functions, format numbers consistently with sensible rounding and escape characters that could break the formatting. You will write the signal table with aligned columns, and you will include the results of the claim checks and any warnings from the pipeline, because hiding problems would defeat the purpose.
You will use a template approach that keeps the text of the report separate from the logic, which makes changes easier. You will save the file with a name that includes the date and then read it back to confirm that it looks right.
You will test by rendering reports for complete, partial and empty data cases.
By the end of this lecture you will be able to build a structured Markdown report with tables, citations and disclaimers and handle incomplete data gracefully.
A briefing agent is most useful when it runs by itself every day. Unattended jobs need to be observable and safe to run more than once. In this final lecture you will schedule runs with structured logging and idempotent reruns.
You will begin with scheduling. You will write an entry point that takes a date, runs the pipeline and writes the report, which any scheduler can then call, such as cron, a task scheduler or a workflow tool. You will also write a small loop using the standard library that shows how a daily trigger works, with an injected clock so that it can be tested quickly.
Next you will add structured logging. Each log entry is a JSON object with the run identifier, stage name, status, duration and counts such as the number of chunks retrieved and claims flagged. You will never log secrets, and you will keep the entries consistent so that they can be searched.
Then you will make runs idempotent. Running the job twice for the same date should not duplicate reports or memory entries. You will create a run key from the date and configuration, write output to a temporary file and move it into place only when complete, and check for an existing finished report before starting. You will also add a force option for deliberate reruns.
You will test with synthetic dates, simulating a crash halfway through and a repeated run.
By the end of this lecture you will be able to run the pipeline on a schedule, log structured events and make reruns safe and repeatable.
This course contains the use of artificial intelligence.
Are you ready to explore the intersection of Artificial Intelligence, Agentic AI, Python Programming, Financial Technology, and Quantitative Trading? Learn how to build intelligent AI agents that automate financial research, analyze market data, evaluate trading signals, and generate evidence-based financial insights.
Build AI-Powered Trading Research Agents with Python is a comprehensive, hands-on course designed for developers, financial professionals, data scientists, and AI enthusiasts who want to build intelligent financial research applications using modern AI Engineering techniques.
Throughout this course, you will progress through 9 comprehensive modules and 40 practical lessons, developing the technical skills needed to build sophisticated AI-Powered Financial Research Systems from scratch.
You will begin by setting up a reproducible Python development environment, managing API keys securely, and implementing structured data validation using Pydantic. Next, you will explore Financial Data Engineering, Market Data Processing, data normalization, data cleaning, and efficient dataset caching using Pandas and Apache Parquet.
Discover how Large Language Models (LLMs) interact with external tools through Function Calling, AI Tool Calling, structured outputs, JSON schemas, and custom tool registries. Build intelligent Autonomous AI Agents using the ReAct Framework, combining planning, reasoning, actions, observations, and iterative execution.
Dive into Retrieval-Augmented Generation (RAG) and learn how to transform financial documents, SEC filings, earnings transcripts, and financial news into searchable knowledge bases. Explore Vector Embeddings, Semantic Search, Cosine Similarity, document chunking, metadata management, and citation-based information retrieval to generate grounded financial research.
Take your financial analysis skills further by implementing Financial Sentiment Analysis, Natural Language Processing (NLP), sentiment scoring, momentum indicators, quantitative factor analysis, and historical market signal evaluation. Learn how Artificial Intelligence in Finance can support systematic financial research and data-driven analysis.
Explore the power of Multi-Agent AI Systems by building specialized research agents that collaborate as financial analysts, risk reviewers, and editors. Implement Agent Orchestration, graph-based workflows, conditional routing, shared state management, persistent AI Agent Memory, and automated execution pipelines.
You will also develop practical skills in Algorithmic Trading Research, Quantitative Finance, Trading Strategy Backtesting, historical performance evaluation, transaction cost analysis, maximum drawdown calculation, and risk assessment.
Understand the importance of Responsible AI, AI Governance, LLM Evaluation, hallucination detection, evidence validation, AI Guardrails, execution monitoring, and token cost management when developing financial AI applications.
Finally, bring everything together in a comprehensive capstone project by building an Automated Daily Financial Research Briefing Agent. Combine market data ingestion, financial document retrieval, quantitative signals, sentiment analysis, multi-agent collaboration, scheduled execution, structured logging, and automated report generation into one integrated research pipeline.
Whether you are pursuing a career in AI Engineering, FinTech, Data Science, Machine Learning, Quantitative Research, Financial Analytics, or Generative AI Development, this course provides practical experience building intelligent financial research solutions.
No real-money trading or brokerage account is required. This course focuses on educational financial research, historical strategy evaluation, and AI application development rather than investment advice or guaranteed trading returns.
By the end of this course, you will have developed valuable skills in Python Automation, Agentic AI Development, Financial AI Applications, and intelligent research workflow automation.
Enroll today and start building the next generation of AI-Powered Trading Research Agents with Python!