Bachelor thesis · 2024 · Swiss Life Asset Managers Recognition Award 2025

Alpha through sentiment analysisAward

Can the sentiment of Swiss newspaper articles be used to adjust the stock weights of a portfolio and beat the SMI?

Read the award announcement →

newspaper articles on SMI companies, published 2010–⁠2023
30,993
different companies in the SMI over 2010–⁠2023, across 15 index changes
29
language models, GermanFinBERT and GPT-3.5, scored every article and headline
2
annual outperformance over the SMI, out of sample and before costs, Model 1
+80 bps

In short

Classification trees, trained to forecast from article sentiment whether a stock rises the next day, steered the weights of an SMI portfolio. Out of sample and before costs, both strategies beat the SMI on absolute and risk-adjusted returns. Their daily forecasts, however, were less accurate than always answering “no gain”: article polarity alone does not predict the next day’s move reliably enough to steer the allocation on its own.

(01) · Business understanding

Question

Studies of news sentiment and Swiss stocks are rare, and transformer models had barely been tried on them.

Can transformer-based sentiment analysis of local media articles be used to manage the single-stock allocation of a Swiss equity portfolio tactically and earn an excess return over a benchmark?

Research question, translated from the German

Whether news can beat the market is an open question. The efficient-market hypothesis says public information is priced at once; behavioural finance finds sentiment and herding effects (Shiller 2003); the literature has no consensus (Malkiel 2003).

For the US, Fazlija and Harder (2022) report one to two percent a year over the S&P 500, 2011–2016, from a long-short strategy on BERT-classified news. For Switzerland, Schlaubitz (2021) found a significant correlation between the sentiment of cash.ch news and the price moves of Swiss small and mid caps. This thesis asks whether local German-language dailies carry a signal for the blue chips.

The finance is kept simple, so that the signal is the only variable: daily prices, the SMI’s own weights as the neutral position, no costs or liquidity modelled.

T−1 is a control target: if today’s sentiment “predicts” yesterday’s move as well as tomorrow’s, the news is already in the price.

(02) · Data understanding

Data

Three sources, none of them clean: index membership from SIX, articles exported as RTF, prices with 8 gaps.

  1. Index membership

    1. SIX monthly statistical reports, 2010–2023, provided on request
    2. A custom parser, adapted as the report layout changed; it ran fully automatically

    33 listings

    29 companies, 15 index changes

  2. Articles

    1. Factiva: NZZ, Tages-Anzeiger and Der Bund
    2. 30,993 articles in RTF batches of up to 100, split by regular expression and cleaned

    30,055 articles

    after cleaning

  3. Prices

    1. Yahoo Finance, with investing.com, sharecast and macrotrends as fallbacks
    2. 8 ISINs without Yahoo data: 4 filled from other sites, 3 from another listing, Synthes dropped

    7 of 8 gaps filled

    Daily price: the mean of the day's open and close, forward-filled over weekends and holidays

Company mapping

41,066 rows

One row for every company an article names

  • 29,934 kept
  • 9,435 out of scope: the company was outside the SMI on the publication day
  • 1,697 dropped: a feature missing

Analytics base table

29,934 rows

Sentiment, coverage and calendar features, and 8 candidate targets: the price change to T−1, T+1, T+2, T+3, T+4, T+5, T+14, T+30. The best horizon wasn’t known yet, so all of them were carried; T−1 is a control.

Figure 1. From three sources to the analytics base table. Index membership from SIX, articles from Factiva, prices from Yahoo Finance.
Show data
StepCount
Index listings33
Articles exported30,993
Articles after cleaning30,055
ISINs without Yahoo data8
Rows after the company mapping41,066
out of scope: the company was outside the SMI on the publication day9,435
dropped: a feature missing1,697
Analytics base table29,934
  • Index membership. The SMI’s detailed index constituents history is not public. SIX provided monthly statistical reports on request; their layout changed several times, so the custom parser was adapted to each layout and ran fully automatically. Every change was checked against SIX’s published index changes.
  • Company replaced (11)
  • Same company, new listing (4)
Jun 2010Swiss Life → Transocean
May 2011Swiss Re new listing
Sep 2011Lonza → Givaudan
Jun 2012Synthes → Geberit
Sep 2013Richemont new listing
Nov 2014UBS Group new listing
Mar 2016Transocean → Swiss Life
May 2017Syngenta → Sika
May 2017Actelion → Lonza
Jun 2018Sika new listing
Apr 2019Julius Bär → Alcon
Sep 2020Adecco → Partners Group
Sep 2021Swatch → Logitech
Sep 2022SGS → Sonova
Jun 2023Credit Suisse → Kühne + Nagel
Figure 2. The 15 changes to the SMI over 2010–2023, from SIX’s monthly statistical reports: 11 replaced one company with another, 4 moved the same company to a new listing. Credit Suisse’s removal is dated June 2023, not December 2023 as the reports had it.
Show data
MonthOutInChange
Jun 2010Swiss LifeTransoceancompany replaced
May 2011Swiss ReSwiss Renew listing
Sep 2011LonzaGivaudancompany replaced
Jun 2012SynthesGeberitcompany replaced
Sep 2013RichemontRichemontnew listing
Nov 2014UBSUBS Groupnew listing
Mar 2016TransoceanSwiss Lifecompany replaced
May 2017SyngentaSikacompany replaced
May 2017ActelionLonzacompany replaced
Jun 2018SikaSikanew listing
Apr 2019Julius BärAlconcompany replaced
Sep 2020AdeccoPartners Groupcompany replaced
Sep 2021SwatchLogitechcompany replaced
Sep 2022SGSSonovacompany replaced
Jun 2023Credit SuisseKühne + Nagelcompany replaced
  • Articles. The academic Factiva account couldn’t export structured data, only RTF batches of up to 100 articles. RegEx was also used to extract information from the texts, such as date, title and category. Because of the unstructured data and varying layouts, some information, such as category, proved to be unreliable. 239 extracted categories were later remapped to 20 plus “Other” (Figures A1 and A2).
  • NZZ
  • Tages-Anzeiger
  • Der Bund
Credit Suisse
6,096
UBS
5,887
Novartis
2,826
Swisscom
2,677
Roche
1,394
Nestlé
1,343
Swiss Life
1,086
Holcim
1,081
Julius Bär
981
Swatch
893
Swiss Re
871
Syngenta
741
Figure 3. Articles per company and newspaper, 2010–2023, from Factiva. The two big banks alone make up 39% of the corpus; 5 companies have fewer than a hundred articles.
Show data
CompanyNZZTages-AnzeigerDer BundTotal
Credit Suisse2,1372,2421,7176,096
UBS2,4581,9971,4325,887
Novartis9539788952,826
Swisscom7329499962,677
Roche4665004281,394
Nestlé5394623421,343
Swiss Life5763002101,086
Holcim5882602331,081
Julius Bär423324234981
Swatch349261283893
Swiss Re431235205871
Syngenta342226173741
Zurich353253111717
Sika251235178664
Actelion303121104528
ABB252158111521
Lonza187169135491
Logitech2118984384
Geberit2345156341
Adecco1786494336
Kühne + Nagel2384644328
Richemont1245848230
Sonova873521143
Transocean952410129
Givaudan6716689
SGS588773
Partners Group478762
Alcon2512845
Synthes272736
  • Prices. Yahoo Finance returned nothing for 8 ISINs: 4 were filled from investing.com, sharecast or macrotrends, 3 from another listing of the same company, and Synthes had no usable prices anywhere and was dropped. The daily price is the mean of the day's open and close. Weekends and holidays were forward-filled with the last price, because articles also appear while the exchange is closed.

    Some series had errors that only showed in the returns.

    Flag
    Every daily return beyond ±40%: 5 moves.
    Check
    Each move was checked by hand against the price series.
    Fix
    Actelion (+1,396,100%) and Sonova (+64.2%) were errors at the start of their series; the prices before the jump were set to the first plausible one.
    Keep
    The other 3, Transocean’s two jumps in June 2020 and Credit Suisse’s fall in March 2023, were real and stayed.
  • Analytics base table. Joining the three sources needed one key per company, but a company could appear under several names and ISINs: the name or share class might have changed over the years. Each name was therefore mapped to the ISIN whose prices were used (Figure 4). The result holds one row per article and company it names, 29,934 rows once the out-of-scope and incomplete ones were dropped (Figure 1).
  • One to one
  • Several names or listings
  • Prices from a secondary source
  • No price data
Article nameSIX nameSIX ISINPrice ISINActelion: one name, one ISIN; prices from a secondary sourceActelionACTELION NCH0010532478CH0010532478Credit Suisse: one name, one ISIN; prices from a secondary sourceCredit SuisseCS GROUP NCH0012138530CH0012138530Holcim: renamed, one ISINHolcimHOLCIM NLAFARGEHOLCIM NCH0012214059CH0012214059Richemont: two listings, merged onto the current ISINRichemontRICHEMONTRICHEMONT NCH0045039655CH0210483332CH0210483332Sika: share class changed, merged onto the current ISINSikaSIKA ISIKA NCH0000587979CH0418792922CH0418792922Swiss Life: renamed, one ISINSwiss LifeSWISS LIFE HOLDING AG NSWISS LIFE HOLDING NCH0014852781CH0014852781Swiss Re: holding restructure, merged onto the holding's ISINSwiss ReSWISS RE HLDG NSWISS RE NCH0126881561CH0012332372CH0126881561Syngenta: one name, one ISIN; prices from a secondary sourceSyngentaSYNGENTA NCH0011037469CH0011037469Synthes: no price data anywhere, droppedSynthesSYNTHES NUS87162M4096no dataUBS: prices for both listings, kept apartUBSUBS GROUP NUBS NCH0244767585CH0024899483CH0244767585CH0024899483Zurich: renamed, one ISINZurichZURICH FINANCIAL NZURICH INSURANCE NCH0011075394CH0011075394
Figure 4. How the three sources line up. 11 of the 29 companies needed a decision: a rename, a second listing, prices from a secondary source, or no prices at all. Names as in the SIX statistical reports.
Show data
CompanySIX nameSIX ISINPrice ISINNote
ABBABB LTD NCH0012221716CH0012221716one name, one ISIN
ActelionACTELION NCH0010532478CH0010532478one name, one ISIN; prices from a secondary source
AdeccoADECCO NCH0012138605CH0012138605one name, one ISIN
AlconALCON NCH0432492467CH0432492467one name, one ISIN
Credit SuisseCS GROUP NCH0012138530CH0012138530one name, one ISIN; prices from a secondary source
GeberitGEBERIT NCH0030170408CH0030170408one name, one ISIN
GivaudanGIVAUDAN NCH0010645932CH0010645932one name, one ISIN
HolcimHOLCIM N · LAFARGEHOLCIM NCH0012214059CH0012214059renamed, one ISIN
Julius BärJULIUS BAER NCH0102484968CH0102484968one name, one ISIN
Kühne + NagelKUEHNE+NAGEL INT NCH0025238863CH0025238863one name, one ISIN
LogitechLOGITECH NCH0025751329CH0025751329one name, one ISIN
LonzaLONZA NCH0013841017CH0013841017one name, one ISIN
NestléNESTLE NCH0038863350CH0038863350one name, one ISIN
NovartisNOVARTIS NCH0012005267CH0012005267one name, one ISIN
Partners GroupPARTNERS GROUP NCH0024608827CH0024608827one name, one ISIN
RichemontRICHEMONT · RICHEMONT NCH0045039655 · CH0210483332CH0210483332two listings, merged onto the current ISIN
RocheROCHE GSCH0012032048CH0012032048one name, one ISIN
SGSSGS NCH0002497458CH0002497458one name, one ISIN
SikaSIKA I · SIKA NCH0000587979 · CH0418792922CH0418792922share class changed, merged onto the current ISIN
SonovaSONOVA NCH0012549785CH0012549785one name, one ISIN
SwatchSWATCH GROUP ICH0012255151CH0012255151one name, one ISIN
Swiss LifeSWISS LIFE HOLDING AG N · SWISS LIFE HOLDING NCH0014852781CH0014852781renamed, one ISIN
Swiss ReSWISS RE HLDG N · SWISS RE NCH0126881561 · CH0012332372CH0126881561holding restructure, merged onto the holding's ISIN
SwisscomSWISSCOM NCH0008742519CH0008742519one name, one ISIN
SyngentaSYNGENTA NCH0011037469CH0011037469one name, one ISIN; prices from a secondary source
SynthesSYNTHES NUS87162M4096noneno price data anywhere, dropped
TransoceanTRANSOCEAN NCH0048265513CH0048265513one name, one ISIN
UBSUBS GROUP N · UBS NCH0244767585 · CH0024899483CH0244767585 · CH0024899483prices for both listings, kept apart
ZurichZURICH FINANCIAL N · ZURICH INSURANCE NCH0011075394CH0011075394renamed, one ISIN
  • One row per article. With the mapping in place, the analytics base table became the project’s single store for prediction. Every row is one article about one company and carries everything the models were given: the article’s form, its sentiment scores, the company’s recent coverage and the calendar, next to the price changes to predict. The models read nothing else, so every step downstream starts from this table. Figure 5 lists its columns by group.

Article

What the text looks like and when it appeared.

  • length
  • content_numeric_rate
  • source
  • category
  • is_trading_day

Sentiment

Polarity of content and headline from both models, and days since the last positive or negative score.

  • content_gpt_score
  • title_gpt_score
  • content_finbert_score
  • title_finbert_score
  • days_since_{gpt|finbert}_{pos|neg}_{c|t}

Coverage

How much attention the company is getting.

  • articles_last_7D
  • articles_last_30D

Calendar

Whether the target day is a trading day.

  • trading_day_in_t+x

Targets

Price change from today to the horizon, continuous and as a positive/not-positive flag.

  • T−1
  • T+1 … T+5
  • T+14
  • T+30
  • …_is_pos
Figure 5. The analytics base table, 29,934 rows, its features in groups. Neither the company nor the date is a feature, on purpose.
MethodsPython ·pandas ·Regular expressions ·Entity mapping across three sources ·Data cleaning

(03) · Modelling

Sentiment

Two architectures scored every article and headline. They gave the same label to 35% of articles.

GermanFinBERT_SC_Sentiment

A BERT pre-trained from scratch on German financial text, fine-tuned for sentiment on a German translation of the Financial PhraseBank (Scherrmann 2023)

Architecture
encoder-only (BERT)
Output
positive / neutral / negative
Input limit
512 tokens
Run
locally; long articles via a sliding window

GPT-3.5 Turbo

OpenAI’s gpt-3.5-turbo-0125, through the paid API (OpenAI n.d.)

Architecture
decoder-only LLM
Output
zero-shot prompt returning 1 / 0 / −1
Input limit
16,385-token context, 4,096 output tokens
Run
API, temperature 0, several articles per call
Table 1. The two sentiment models: an encoder that classifies, and a decoder that answers a prompt.

FinBERT reads at most 512 tokens, and about 13,000 articles were longer, so they were scored with a custom sliding window approach, after Longformer (Beltagy et al. 2020) and Big Bird (Zaheer et al. 2021), and the window scores averaged (Figure A3).

GPT-3.5 got a zero-shot prompt adapted from Zhang et al. (2023), with several articles per call to keep cost and rate limits down (Cheng et al. 2023; Figure A4).

Batching had a cost: the answers did not always carry a label for every ID sent (Figure A5).

Check
Every answer was matched against the IDs sent with it.
Flag
No label for about 10% of articles and 1.5% of headlines; their IDs went into a second pass.
Result
Still missing after the second pass: under 0.1%, dropped.
FinBERT →
negative
neutral
positive
GPT-3.5 ↓negative
neutral
positive
0%
42% of items

Hover or focus a cell. The diagonal is where the two models agree.

Same label from both models
35%
FinBERT called neutral
69%
GPT-3.5 called neutral
19%
GPT-3.5 scored lower than FinBERT
about 48%
Figure 6. Each cell is the share of all items that received that pair of labels; the diagonal is where the models agree. FinBERT calls most things neutral; GPT-3.5 rarely does, and leans negative.
Show data
GPT-3.5 ↓ · FinBERT →negativeneutralpositive
negative14%42%4%
neutral2%15%2%
positive2%12%6%

There was no labelled Swiss data set to judge the two against, so neither could be declared right. Likely causes of the gap: imperfectly transcribed text with typos, which GPT models cope with better (Cao et al. 2023, tested on GPT-4), and special characters that were deliberately left in. So both scores went into the table as features, four polarity scores per article for content and headline, and the predictive models were left to weigh them.

MethodsTransformers ·Zero-shot prompting ·Batch inference with ID reconciliation ·Sliding-window inference

(04) · Modelling

Prediction

Next day looked like the best horizon. The first tuned tree, Model 1, showed why: it split on the calendar, not the news, so Model 2 was trained on trading days only.

  • Logistic regression
  • Classification tree
0.000.250.500.751.00T−1 *0.690.69T+1 *T+2T+3T+4T+5T+14T+30

* T−1 and T+1 are inflated by non-trading days: forward-filled prices give a zero return that a model can learn from the calendar alone.

Figure 7. Two classifiers at eight horizons, each the average over five random 80/20 train/test splits on all calendar days, the data Model 1 was trained on. T−1 is the control: today's sentiment “predicting” yesterday's move. On AUC, 0.50 is chance; accuracy and F1 were scored on test splits that kept the classes’ real shares.
Show data
HorizonAccuracy · LogisticF1 · LogisticAUC · LogisticAccuracy · ClassificationF1 · ClassificationAUC · Classification
T−10.600.590.630.600.590.63
T+10.690.650.780.690.650.79
T+20.610.590.650.620.600.66
T+30.520.530.540.510.550.54
T+40.520.540.540.510.600.53
T+50.520.550.530.520.610.53
T+140.530.540.550.540.470.55
T+300.530.550.550.540.520.55

Two classifiers, a logistic regression and a classification tree, learned at each horizon to tell a gain from no gain (Figure 7). Both scored best one day ahead and drifted towards chance, an AUC near 0.50, beyond T+2. The choice fell on the classification tree, which edged out logistic regression by less than a percentage point at T+1 and stays readable. Like every score in Figure 7, it was measured on all calendar days, weekends and holidays included.

Two regressions, a linear one and a regression tree, were also fitted to the price change itself. They explained at most 3.8% of its variance at any horizon. The thesis therefore kept to the binary targets: a gain or no gain leaves out how far the price moves, which the regressions could not capture, while the classifiers reached an AUC well above chance one and two days ahead.

Short-horizon targets were skewed towards “no gain”, so model selection ran on downsampled data. A grid search over 432 combinations tuned the tree, and it landed on the deepest tree the grid allowed (Figure A6).

Model 1 is that tree, trained on all days without resampling. Its first split is on whether tomorrow is a trading day: forward-filled prices make the return over a weekend or holiday exactly zero, so those rows are all “no gain”, and the tree learns them from the calendar alone. The same effect flatters every short horizon in Figure 7.

Model 2 removes it. It keeps trading days only, so a prediction is never made for a day without a price, rebalances the classes and is tuned again. Its in-sample accuracy drops to 0.55, from 0.73 for Model 1, once the calendar no longer helps.

all days, no resampling

  • no gain at t+1
  • gain at t+1

trading_day_in_t+1 ≤ 0.5

gini 0.413 · 19,157 rows

13,576 no gain · 5,581 gain

leaf

gini 0.000 · 7,550 rows

7,550 no gain · 0 gain

days_since_finbert_pos_t ≤ 4.5

gini 0.499 · 11,607 rows

6,026 no gain · 5,581 gain

Model 1: 7,550 rows where the next day is not a trading day, and every one of them is “no gain”. The first split is the calendar, not the news, and the reason Model 2 drops non-trading days.

In sample: accuracy 0.73 · F1 0.51 · AUC 0.81

Figure 8. The top two levels of each tuned tree. Both were tuned by grid search to the same settings (Figure A6).
Methodsscikit-learn ·Logistic regression ·Decision trees ·Class rebalancing ·Grid search with cross-validation ·Control targets

(05) · Evaluation

Backtest

Each predicted gain tilted its stock above the SMI’s own weight for the next day, out of sample from August 2020.

The strategy only ever raises weights. A stock the model expects to gain the next day goes above its weight in the SMI; no stock is sold short or dropped, and the others give up weight only because the total stays at 100%. What these tilts earn against the index is the active return (Figure 9).

rA = Σi (wP,i − wB,i) · (ri − rB)

Figure 9. Active return, after Mondello (2015): it comes from holding a stock above or below its benchmark weight while it beats or trails the benchmark. The strategy sets only the portfolio weights wP,i.

The base weights replicate the SMI’s internal weights, so that only the tilts set the portfolios apart from their benchmark. The official historical weights of the SMI are not publicly available, so they were rebuilt from SIX data.

How the SMI was approximated →

Each day, the weights were set in five steps (Figure 10).

Base
Every stock starts at its weight in the rebuilt SMI.
Signal
Every article from day t for which the model predicts a gain at t+1 is one positive forecast for its stock.
Tilt
The first positive forecast adds the stock’s base weight again, doubling it. Each further one adds 0.9 times what the one before added (Figure A7).
Rescale
The weights are scaled back to 100%, so every other stock gives up weight in proportion.
Hold
The tilted weights hold for day t+1 only. The next day starts again from the base weights and that day’s forecasts.
Figure 10. The five steps that set every stock’s weight on each day of the test window.

A stock’s weight for the next day therefore depends on two things: its weight in the SMI and the number of positive forecasts its articles drew that day. Figure 11 shows how the two play out on an illustrative day.

Base

rebuilt SMI weights, %

  • Stock A10%
  • Stock B25%
  • Stock C25%
  • Stock D40%

Tilt

base × multiplier, ● = one positive forecast

  • Stock A ●●●37.1
  • Stock B ●50
  • Stock C25
  • Stock D40

Rescale

back to 100%, held for t+1

  • Stock A24.4%
  • Stock B32.9%
  • Stock C16.4%
  • Stock D26.3%
Figure 11. One day of the strategy, with illustrative weights. Stock A has 3 positive forecasts, which multiply its weight by 3.71 (1 + 1 + 0.9 + 0.81); Stock B has one, which doubles it. Rescaled to 100%, the two untilted stocks give up weight in proportion. The tilted weights hold for the next day only.

Why a decay factor of 0.9: Credit Suisse and UBS had about 6,000 articles each over the period, Givaudan 89. Without decay, a day with many positive forecasts for one bank would swamp the portfolio; with 0.9, the eighth adds 48% of what the first did (Figure A7). The factor is a setting of the strategy, and the result moves with it.

MethodsActive-return framework ·Decay weighting ·Backtesting

(06) · Conclusion

Answer

Both portfolios beat the SMI out of sample, also on the Sharpe ratio; the thesis answered yes, with a caveat.

Yes. The empirical analysis showed that an investment strategy based on the sentiment of local media articles, used to steer the short-term single-stock allocation, can earn absolute and risk-adjusted excess returns over the benchmark.

These results have to be put into perspective, however, given the models’ out-of-sample accuracy and F1 scores.

They suggest that sentiment analysis alone, at least with the data and methods used in this study, is not enough to deliver reliable forecasts for managing equity portfolios strategically.

The thesis’s answer, May 2024, translated from the German
PortfolioPer yearOver the SMIVolatilitySharpe
Model 14.62%+80 bps13.60%0.309
Model 24.24%+42 bps13.48%0.284
SMI · benchmark3.82%–13.35%0.256
Table 2. Out of sample, 8 August 2020 to 31 December 2023. All three at closing prices, on the SMI’s trading days. Annualised returns and volatility; Sharpe ratios use a 0.4085% risk-free rate, the Swiss 10-year government bond yield.

Both portfolios ran close to the index’s volatility, 13.60% and 13.48% against 13.35%, and both beat it on the Sharpe ratio.

  • Model 1
  • Model 2
  • SMI
90100110120130202120222023SMI 110.37Model 2 111.87Model 1 113.23
Figure 12. Both portfolios and the SMI over the test window, indexed to 100 at the close of 10 August 2020, the first trading day, to 29 December 2023, the last. All at closing prices, one point a week; SMI data from Yahoo Finance.
Show data
DateModel 1Model 2SMI
10 Aug 2020100.00100.00100.00
25 Sep 2020102.64101.89101.24
30 Dec 2020106.44105.71106.07
26 Mar 2021110.23109.87110.17
25 Jun 2021116.92117.41118.92
24 Sep 2021112.12112.99117.11
30 Dec 2021123.92125.65127.60
25 Mar 2022121.62121.98120.12
24 Jun 2022106.42107.07107.26
30 Sep 202298.2398.97101.75
30 Dec 2022104.11104.50106.33
31 Mar 2023108.59109.55110.06
30 Jun 2023110.23110.02111.79
29 Sep 2023112.26111.04108.65
29 Dec 2023113.23111.87110.37
ModelAccuracy in sampleF1 in sampleAccuracy out of sampleF1 out of sample
Model 1 · all days, no resampling0.730.510.490.44
Model 2 · trading days only, classes rebalanced0.550.550.480.50
Always “no gain”––0.53–
Table 3. In sample, the tuned trees on their tuning data; out of sample, on trading days from 8 August 2020 to 31 December 2023. The last row always answers “no gain”.

The thesis named its limits. The in-sample scores were inflated by non-trading days, whose forward-filled prices give a zero return that short-horizon models learn from the calendar alone. The excess return depends on the settings of the strategy and on the horizon. Both portfolios spent spells behind the SMI, about six index points at the deepest, in late 2021, so a different test window could give a different result. And the gap between the approximated and the actual index weights may account for a small part of the variance.

For further work, the thesis proposed four directions:

  • Newer language models such as Llama 3 or GPT-4o, benchmarked against earlier studies.
  • Aspect-based sentiment classification, for a more precise label for each part of an article.
  • Several languages, to compare domestic and foreign sources, and channels beyond newspapers, such as social media, forums and television.
  • Macro and company data next to sentiment: GDP forecasts, unemployment, inflation and consumer spending; market capitalisation, quarterly results, sector and sales markets.
(07) · Under the hoodAppendixThe original title, scope and stack, the detail behind each section, and the references.Show
Original title
Alpha durch Sentiment-Analyse: Eine empirische Untersuchung der Einsatzfähigkeit von Natural Language Processing zur Steuerung der Einzeltitel-Allokation eines Schweizer Aktienportfolios
Institution
Bachelor thesis, HWZ Hochschule für Wirtschaft Zürich, May 2024
Stack
Python 3.11 · pandas · scikit-learn · GermanFinBERT · GPT-3.5 Turbo (OpenAI API) · yfinance · Factiva · Jupyter · RegEx · CRISP-DM

In scope

  • SMI constituents, refreshed monthly
  • NZZ, Tages-Anzeiger and Der Bund
  • German-language articles only
  • 1 January 2010 to 31 December 2023
  • Daily prices in CHF, no intraday view

Left out on purpose

  • Multilingual sources
  • Intraday data
  • Transaction costs and liquidity
  • Diversification across asset classes, regions or sectors
  • Lexicon-based and vector-based classifiers
RuleThresholdActionWhy
Article lengthunder 50 charactersdroppedpicture captions and teasers for other pages, no information
Numeric share of the textabove 0.15droppedtables and figures rather than prose; the cut-off was set by inspecting the outliers
Article categories239 distinct valuesremapped to 20 plus “Other”title and category were read by position, and the metadata layout varies, so many values were spurious
Index removal dateCredit Suissecorrected to June 2023the statistical reports said December 2023; the SIX release and the press said June
Non-trading daysweekends and holidaysforward-filledarticles are published while the exchange is closed
Table A1. The cleaning rules. Each threshold was set after reading the outliers it removes, and each is a judgement call.

Wirtschaft

Hedge Funds lancieren Sammelklage gegen Novartis

394 words

12 January 2010

Tages Anzeiger

TANZ

German

(c) 2010 Tages Anzeiger Homepage Address: http://www.tages-anzeiger.ch

Document TANZ000020100112e61c0003v

  1. Metadata

    Category, title, word count, date and source. The date is found by regular expression because its line moves. Title and category are read by position, which the varying layouts made unreliable; that is why the categories later needed a remap.

  2. Content

    Cleaned before scoring: repeated whitespace and line breaks removed, special characters dropped except punctuation, brackets and signs.

  3. Document ID

    Every article ends with an ID. It is the split point: one regular expression cuts an RTF batch of up to 100 articles into rows.

Figure A1. The three parts of a Factiva article. The header lines are from a real Tages-Anzeiger article of 12 January 2010 as Factiva delivered it, without the author and page lines; the body is blurred.

Python

PATTERN_ID = r'Document\s[A-Za-z0-9]{20,30}' # find end of article
...
articles_ids = find_pattern(content, PATTERN_ID) # get long IDs as they are deleted in next step

# Check if 100 IDs are detected (most files should have 100)
if len(articles_ids) != 100:
    print('[!] ATTENTION | articles detected: {:<4}'.format(str(len(articles_ids))))

    additional_tests.append(filepath)
    print('[!] ATTENTION | logged for manual testing')

articles = re.split(PATTERN_ID, content)  # Divide between articles
articles.pop(-1)  # delete rest of .rtf file after last article
Figure A2. The split, as written in the code: one regular expression finds each document ID, and the batch is cut there. A batch that doesn’t yield 100 IDs is logged for a manual check.
DateCompanyMoveTreatment
5 Jan 2010Actelion+1,396,100%corrected
8 Feb 2010Sonova+64.2%corrected
17 Jun 2020Transocean+50.6%kept
18 Jun 2020Transocean+50%kept
20 Mar 2023Credit Suisse−53%kept
Table A2. Five daily moves stood out on inspection. Two were data errors and were corrected; three were real and stayed.
token 0end of article
window 1 → positive
window 2 → neutral
window 3 → neutral

Combined label for this article: (+1 + 0 + 0) / 3 = 0.33, rounded to 0, neutral.

Figure A3. Sliding-window scoring, a schematic, after Longformer (Beltagy et al. 2020) and Big Bird (Zaheer et al. 2021). About 13,000 articles were longer than FinBERT's 512-token limit. Windows overlap by 20%. Each window is scored on its own and the average is rounded to −1, 0 or +1, which pulls long articles toward neutral; a check found no correlation between length and polarity.
Sentiment Analysis Task

Analyze the sentiment of the following German newspaper articles and predict
the sentiment label for each article individually from the predefined label
space: "positive", "neutral", "negative"

Article Format:
The articles are provided in a JSON format with the following structure:
{{id: article content}}

Your Task:
Please respond with a JSON object in the same format, using the same IDs as
provided in the input.
For each article, assign a sentiment label based on the language and tone used.
If the label is "positive", return 1. If the label is "neutral", return 0.
If the label is "negative", return -1.

Articles to Analyze:
{batch}
Figure A4. The zero-shot prompt for articles, as written in the code, adapted from Zhang et al. (2023). Headlines use the same structure.

Python

batch_scores = perform_api_call(prompt=final_prompt, articles_list=batch)

# get the IDs of sent vs returned
id_list_sent = [triplet[0] for triplet in batch]
id_list_returned = [pair[0] for pair in batch_scores]

# 1: Check for missing IDs
for sent_id in id_list_sent:
    if sent_id not in id_list_returned:
        ids_to_retry.append(sent_id)

# 2: Filter scores for IDs present in both sent and returned lists
for pair in batch_scores:
    if pair[0] in id_list_sent:
        chatgpt_scores.append(pair)
Figure A5. The second pass, as written in the code: IDs sent but not returned are queued again, and answers for IDs never sent are dropped.

Python

param_grid = {
    'max_depth': [3, 4, 5, 6, 7, 8],
    'min_samples_split': [500, 1000, 2000, 3000, 4000, 5000],
    'min_samples_leaf': [250, 500, 750, 1000, 1500, 2000],
    'criterion': ['gini', 'entropy']
}
Figure A6. The grid search, 432 combinations, cross-validated and scored on accuracy. Both models landed on max_depth 8, min_samples_leaf 250, min_samples_split 500: the edge of the grid.
  • factor used, f = 0.9
  • other factors compared in the thesis
1×4×7×10×13×16×02468101214positive forecasts on one day (n)weight multiplierf = 1.0f = 0.8f = 0.7f = 0.6f = 0.9 · 8.7×

m(n) = 1 + Σk=0n−1 fk

Figure A7. The weight multiplier of a stock with n positive forecasts on one day. The first doubles its weight; each further one adds 0.9 times what the one before added, so with 0.9 fourteen forecasts on one day lift a stock to 8.7 times its base weight. The grey lines are the other decay factors the thesis compared, from 0.5 to 1.0.
Show data
nf = 0.5f = 0.6f = 0.7f = 0.8f = 0.9 (used)f = 1.0
01.001.001.001.001.001.00
12.002.002.002.002.002.00
22.502.602.702.802.903.00
32.752.963.193.443.714.00
42.883.183.533.954.445.00
52.943.313.774.365.106.00
62.973.383.944.695.697.00
72.983.434.064.956.228.00
82.993.464.145.166.709.00
93.003.474.205.337.1310.00
103.003.484.245.467.5111.00
113.003.494.275.577.8612.00
123.003.494.295.668.1813.00
133.003.504.305.738.4614.00
143.003.504.315.788.7115.00

Model 1 · accuracy 0.49 · F1 0.44

predicted
no gaingain
actual no gain1,154993
actual gain1,065825

Model 2 · accuracy 0.48 · F1 0.50

predicted
no gaingain
actual no gain9001,247
actual gain8561,034
Figure A8. Out of sample. Rows are what happened the next day, columns what the model said. Model 1 is shown on trading days only; with weekends and holidays included, its accuracy read 0.66. Always answering “no gain” would have scored 0.53 on the same rows.

References

  • Beltagy, I., Peters, M. E. & Cohan, A. (2020). Longformer: The Long-Document Transformer (arXiv:2004.05150). arXiv. arxiv.org→
  • Cao, Q., Kojima, T., Matsuo, Y. & Iwasawa, Y. (2023). Unnatural Error Correction: GPT-4 Can Almost Perfectly Handle Unnatural Scrambled Text (arXiv:2311.18805). arXiv. arxiv.org→
  • Cheng, Z., Kasai, J. & Yu, T. (2023). Batch Prompting: Efficient Inference with Large Language Model APIs (arXiv:2301.08721). arXiv. arxiv.org→
  • Fazlija, B. & Harder, P. (2022). Using Financial News Sentiment for Stock Price Direction Prediction. Mathematics, 10(13), 2156. doi.org→
  • Malkiel, B. G. (2003). The Efficient Market Hypothesis and Its Critics. Journal of Economic Perspectives, 17(1), 59–82. doi.org→
  • Mondello, E. (2015). Portfoliomanagement: Theorie und Anwendungsbeispiele (2., aktualisierte Auflage). Springer Gabler.
  • OpenAI. (n.d.). Models—GPT-3.5 Turbo. OpenAI Documentation. Retrieved 12 February 2024. platform.openai.com→
  • Scherrmann, M. (2023). German FinBERT: A German Pre-trained Language Model (arXiv:2311.08793). arXiv. arxiv.org→
  • Schlaubitz, A. (2021). Natural Language Processing in finance: Analysis of sentiment and complexity of news and earnings reports of swiss SMEs and their relevance for stock returns. doi.org→
  • Shearer, C. (2000). The CRISP-DM Model: The New Blueprint for Data Mining. Journal of Data Warehousing, 5(4).
  • Shiller, R. J. (2003). From Efficient Markets Theory to Behavioral Finance. Journal of Economic Perspectives, 17(1), 83–104. doi.org→
  • Zaheer, M., Guruganesh, G., Dubey, A., Ainslie, J., Alberti, C., Ontanon, S., Pham, P., Ravula, A., Wang, Q., Yang, L. & Ahmed, A. (2021). Big Bird: Transformers for Longer Sequences (arXiv:2007.14062). arXiv. arxiv.org→
  • Zhang, W., Deng, Y., Liu, B., Pan, S. J. & Bing, L. (2023). Sentiment Analysis in the Era of Large Language Models: A Reality Check (arXiv:2305.15005). arXiv. arxiv.org→