Package: tradesim
tradesimA stock market site simulator for collecting data on stocks carried out by the trader.This simulation takes stock market data for a given period and presents it in an interface that evolves with time and the user's actions.The interface allows you to make buy or sell requests on a company's shares, view the company's share price and earnings per year via graphs, know your stock portfolio and consult the news.
It's currently available in English and French, and we'd be delighted to extend it to more languages (see thecontributingsection).The user's actions are recorded throughout the simulation in a data file in .csv format, enabling you to study the trader's behavior during the simulation.Table of contentsRequirementsInstallingUsageUsing the command line toolUsing it as a libraryHandling the applicationModify default configurationModify running applicationDash object below app objectThe Setup toolboxStructure of dataThe generated data: interface-logsNews fileMarket data fileRevenue fileWhy was this project created?ContributingRequirementsPython== 3.10 (Has not been tested for more recent versions)dash>= 2.10.2 : Low-code framework for rapidly building data apps in Python.Pandas>= 2.0.2 : Fast, powerful, flexible and easy to use open source data analysis and manipulation toolOptional (if you want to usetradesim.setuptools)yahooquery>= 2.3.1 : Python wrapper for an unofficial Yahoo Finance APIThe complete list is inrequirements.txtInstallingDownload the latest version of the repository and install the package locally with pip:# Clone the repository or download the latest version on the corresponding pagecdtrading_simulator# Move to project rootpipinstallsetuptools.# Don't forget the dot at the end to install tradesim from local filesIf you need theSetuptoolkit, also install the additional dependencies:pipinstallsetuptools.[extra]UsageUsing the command lineSimply use the command line tool.tradesim<data_directory>For more information on the command line :tradesim-hIntegrating it into your programIf you want to integrate it into your program, here's a simple example:# main.pyfromtradesimimportappfromtradesim.Setupimportdownload_market_datadownload_market_data()# Prepare the minimum necessary for interface operation# [Your program...]app.set_layout()# Import the layout before starting the serverapp.run_server()# Server startup blocks the next instruction until the user presses ctrl-c in the terminal.For a more realistic example, have a look at themain.pyfile in this repository.For more complex use, with other instructions during server operation, it's best to put your program in a different thread. Like this:# main.pyfromthreadingimportThreadfromtradesimimportappdownload_market_data()# Prepare the minimum necessary for interface operation# [A few instructions before getting started...]th=Thread(target=your_program)th.start()app.set_layout()# Import the layoutapp.run_server()# Starts the server and blocks the following instructions.Handling the applicationThe application can be fully manipulated using theappobject available fromtradesim.Default configurationThe default values are available fromapp.defaultsor its abbreviated versionapp.d. It is strongly recommended not to modify them after callingapp.set_layout()and/orapp.run_server().Here is a description of the default values used:# Period of time used to update data on the dashboardapp.d.update_time=60*1000# in milliseconds# Maximum number of requests the user can make on the dashboardapp.d.max_requests=10# Initial money the user hasapp.d.initial_money=100000# Path to the data folderapp.d.data_path="Data"# Stocks used in the interface# They are also used to download data with the download_market_data setup tool# The key is the ticker and the value is the name of the company# So the data provided in the Data folder must have the same name as the symbolapp.d.companies={"MC.PA":"LVMH MOËT HENNESSY LOUIS VUITTON SE (MC)","OR.PA":"L'ORÉAL (OR)","RMS.PA":"HERMÈS INTERNATIONAL (RMS)","TTE.PA":"TOTALENERGIES SE (TTE)","SAN.PA":"SANOFI (SAN)","AIR.PA":"AIRBUS SE (AIR)","SU.PA":"SCHNEIDER ELECTRIC SE (SU)","AI.PA":"AIR LIQUIDE (AI)","EL.PA":"ESSILORLUXOTTICA (EL)","BNP.PA":"BNP PARIBAS (BNP)","KER.PA":"KERING (KER)","DG.PA":"VINCI (DG)","CS.PA":"AXA (CS)","SAF.PA":"SAFRAN (SAF)","RI.PA":"PERNOD RICARD (RI)","DSY.PA":"DASSAULT SYSTÈMES SE (DSY)","STLAM.MI":"STELLANTIS N.V. (STLAM)","BN.PA":"DANONE (BN)","STMPA.PA":"STMICROELECTRONICS N.V. (STMPA)","ACA.PA":"CRÉDIT AGRICOLE S.A. (ACA)"}# Indexes used in the interface# Same use as the companies variableapp.d.indexes={"^GSPC":"S&P 500","^DJI":"Dow Jones Industrial Average","^FCHI":"CAC 40","^SPGSGC":"S&P GSCI Gold Index",}Modify application status during operationTheappobject also provides variables for manipulating the interface and/or finding out the state of an element while the interface is running.These variables and their default values are described below:# Enables or disables the start button on the home page.# Takes a Boolean as inputapp.home_start_button_disabled=false# Describe the state of the application,# i.e. whether the dashboard is displayed or not.# This variable is set when the user arrives on a page.# It is therefore undefined until this happens.app.dashboardIsRunningDash object below app objectTheappobject we provide is actually aDashobject, taken from thedashlibrary, to which we have added our own functionalities, and therefore contains all the features of this object. Please refer to the correspondingdocumentationfor more information on all the features of this object.TheSetuptoolboxThetradesim.Setuptoolbox provides additional functions for creating an interface environment.
Here's a list:defdownload_market_data():""" Download daily stock market data for companies and indexesdefined respectively by `app.d.companies` and `app.d.indexes`over the last two years, then save them in the folder definedby `app.d.data_path`."""passdefanalyse_news_data(data_path='Data'):""" Opens a jupyter notebook at the locationdefined by the data_path argumentto analyze the data it contains in the form of graphs."""passFor legal reasons, we do not provide a way to generate the news.csv file. It is up to you to obtain this file and place it in the folder defined byapp.d.data_path. It must contain the columnstitle;content;ticker;datewith the separator ";".Structure of dataAll the data used and generated is stored in a specific folder defined by theapp.d.data_pathvariable. This data has a constant structure, as explained below.The data generatedOnce launched, the interface generates aninterface-logs.csvfile in the same folder as the other data (by default:Data), containing all the activity on the dashboard page. This file is structured so that there is only one item of data per column, with :thehost-timestampcolumn gives the timestamp of the host machine, which allows this data to be synchronised with other data.themarket-timestampcolumn gives the timestamp of the data displayed on the interface.the<TICKER>-sharescolumns contain the shares owned by the user.the<TICKER>-totalcolumns contain the value of all the shares owned at a given time.thecashflowcolumn corresponds to the money that the user can use.theselected-companycolumn indicates the ticker of the share displayed on the charts at a given time.therequest <N>columns contain the Nth request in the list of requests waiting to be completed.thenbr-news-displayedandlast-newscolumns respectively designate the number of news items displayed in the news table and the most recent news item displayed.thenews-modeandselected-graphcolumns respectively designate what is displayed in the news part and the graph part.theselected-newscolumn is empty whennews-modeis equal tonews-tableand gives the title of the news displayed whennews-modeis equal tonews-description.Structure of the news fileTo display news in the news table, the interface needs anews.csvfile containing at least these three columns separated by a semicolon:titleorarticlewhich contains the title of the article to be displayed, and which is used in the news table when displaying the list or at the top when displaying the article description.contentcontains the article content, which will be displayed when the user clicks on the article title.datewhich contains the date and time (optional) of the news item. The date must be formalized with the day first, i.e. {day}/{month}/{year}.Market data file structureIf you'd like to use your own market data instead of that generated by thedownload_market_datasetup tool, or if you'd like to understand the structure of themarket_data.csvfile, this file has two header lines, the first of which contains the ticker and the second the data type, for each of the companies and indexes you wish to display. This file uses a date column as index and a comma separator.
The data types required areOpen,High,Low,Close,long_MAandshort_MA.
Here's an example to help you understand:symbol,MC.PA,MC.PA,MC.PA,MC.PA,MC.PA,MC.PA,^SPGSGC,^SPGSGC,^SPGSGC,^SPGSGC,^SPGSGC,^SPGSGC,^SPGSGC
      ,Open,High,Low,Close,long_MA,short_MA,Open,High,Low,Close,long_MA,short_MA                   [...]
date,,,,,,,,,,,,
[...]If this still isn't clear to you. Use thedownload_market_datasetup tool to generate a complete file. I hope this helps.Revenue file structureIf you wish to use your own revenue data instead of that generated by thedownload_market_datasetup tool, or if you want to understand the structure of therevenue.csvfile, this file contains a line for:asOfDatewhich contains the data datethesymbolcontains the company identifier or index and must be identical to that supplied by theapp.d.companiesandapp.d.indexesvariables respectively.NetIncomeandTotal revenueeach contain the value associated with it for each ticker and date.
Here's an example to help you understand:symbol,ACA.PA,ACA.PA,ACA.PA,ACA.PA [...]
asOfDate,2019-12-31 00:00:00,2020-12-31 00:00:00,2021-12-31 00:00:00,2022-12-31 00:00:00 [...]
NetIncome,4844000000.0,2692000000.0,5844000000.0,5437000000.0 [...]
TotalRevenue,19123000000.0,18061000000.0,21397000000.0,21955000000.0 [...]If this still isn't clear to you. Use thedownload_market_datasetup tool to generate a complete file. I hope this helps.Why was this project created?In the financial laboratories of the University of Mons, a study has been launched to analyse the reactions of traders to the stock markets. To better understand which factors are most important in their choices, what is the "human" part of this equation, and many other questions. To improve their results, the researchers needed to create a controlled, automated data-gathering environment.tradesimis an independent part of this environment, to which several sensors have been added. To find out more, have a look at the corresponding repositoryhere.ContributingFeel free to create an issue/PR if you want to see anything else implemented.Legal Stufftradesimis distributed under the Apache License 2.0. See theLICENSEfile in the release for details.