Cum insori programarea cu domeniul financiar for profit & fun?

Parca am citit aici despre un membru care a implementat un trade bot.
Imi mai amintesc si scena din “The Social Network”, unde Mark ii spune prietenei sale cum un amic a facut cateva sute k intepretand weather patterns ptr. a prezice pretul petrolului (parca).

Ce stiti despre combinatia acestor 2 domenii (financiar, programare)?

Pe mine mă pasionează economia de câțiva ani. Totuși sunt încă surprins după atâția ani de cât de reactivă este piața la orice știre ar avea legătură directă cu asseturile.

Încă învăț, deocamdată n-am apelat la niciun algoritm sau automatizare. Dar nu exclud atunci când vine momentul, mai ales că acum este agitație și volatilitate oriunde vezi cu ochii.

Sunt boți care folosesc Reddit si alte surse de informații financiare pentru a evalua sentimentul legat de diverse actiuni.
Persoana care detine boții face apoi investiții in baza informațiilor.
Speculă.

Bineînțeles că asta e rețeta de bază, însă se pot adăuga ingrediente.

Depinde de cât de multe cunoștințe financiare are dezvoltatorul botilor.
In general sunt oameni care au cunoștințe financiare bune si conjunctura ii pune in preajma unor programatori buni, iar succesul crește.

1 Like

In SUA politicienii sunt imuni de la legile de insider trading.
Daca le poti urmari trade-urile poti sa faci trade-uri cu o profitabilitate de 100%.

Adica ei decid ceva si dupa investesc fara sa poata fi monitorizati. Asa ajungi sa faci boti buni, in rest e random.

Mai sunt ciudatenii, de exemplu in UE nu ai insider trading si quiet period, e.g bursa de la Bucuresti iti permite sa le spui prietenilor/familiei daca stii ca Hidroelectrica va fi vandut la pret dublu… Senatorii si deputatii, presedintele, militarii iarasi sunt imuni si pe langa asta trade-urile sunt secrete.

Beating the Odds: Machine Learning for Horse Racing | Teddy Koker

( The Gambler Who Cracked the Horse-Racing Code - Bloomberg)

Exista strategii care pot functiona ca la Blackjack, de ce crezi ca exista site-uri de trading fara comisioane precum Robinhood sau Trading212 ? Fiindca numara trade-urile si are tot contextul.

Dupa anumite companii sunt shorted in public sau nu, bancile de investitii stiu bine de ce si cum. Ei au destui bani (sau credit) incat ori castiga la short ori cumpara actiuni pana pot sa scape de pozitia de short. Pierd doar daca cineva mult mai mare ca ei decide sa investeasca in ceva ce e shorted.

Castigi bine pur si simplu daca te angajezi ca programator la ceva fonduri de investitii, asigurari, banci, big 4, dar cele din SUA au legi ciudate, precum preclearing daca vrei sa faci si tu trading.

3 Likes

Eu am facut un bot pt trade crypto cu API-ul binance. Tot ce face e sa vanda/cumpere automat cand se indeplinesc anumite reguli. Regulile sunt deocamdata foarte simple si am testat cu un total de aproape $1000. Partea buna e ca am incasat in vreo 40 zile 8% profit, partea proasta e ca acum sunt cu toti banii blocati in trade-uri neprofitabile care nu stiu cand sau daca vor mai reveni profitabile (daca as vinde tot in pierdere as fi pe la -25%).

Daca as vrea sa fac ceva mai complex mi-as pune problema de unde sa extrag informatii de incredere (sentiment,istoric, analiza tehnica etc) si ce sistem as folosi pentru plasarea de trade-uri (API-ul binance e unul de tip REST si ma gandesc ca ceva de tip socket ar fi mai indicat).

PS: la binance deocamdata pe BTC/BUSD e comision de tranzactionare 0 deci e un moment bun de testat boti

2 Likes

In general, cei care au facut in trecut bani folosind boti pe pierele de crypto profitau de unele exchange-uri sau monede care aveau lichiditate mica + spread-uri mari sau faceau arbitraj (propriu zis profitau de faptul ca piata nu era inca asa eficienta).

Sansele sa fii profitabil pe termen lung cu un bot simplu (doar sentiment, istoric si TA) mi se par minuscule.

Gandeste-te ca pana la urma concurezi cu firme de quant care au acces la o gramada de date si echipe intregi de devi.

Pai si daca ei fac asa usor 100% de ce nu se regleaza asta gen, lumea le urmareste trade-urile si le copiaza reducand in final profitul asimptotic spre zero.

1 Like

Pentru ca nu e chiar asa. E celebru cazul cu Nancy Pelosi si cu sotul ei. Dar chiar anul asta parca a cumparat de exemplu Roblox care dupa s-a dus in cap.
Cum ai zis si tu, nu exista free lunch, intr-un timp scurt piata rezolva ineficientele de genul.

2 Likes

bursa este un mediu complex. botii sunt limitati si trebuie sa aiba o logica simpla. trebuie sa intelegi regimul economic si factorii cu ponderea cea mai mare in luarea deciziilor. si acesti factori determinanti NU sunt aceeasi. trebuie sa faci diferenta intre investitie si trading, sa intelegi cand iesi si cu cat, daca faci swing. trebuie sa alegi o zona favorabila(optiuni, commod, fx sau Eq si bonds la care sa te pricepi bine) si o economie favorabila. iti ia o viata
ps: posibil ca platforma tradingview sa ajute la teste fara sa investesti neaparat, are o parte de scripting foarte buna

4 Likes

Unde crezi ca poti intalni/socializa cu asemenea oameni? (cu cunostinte financiare)

1 Like

chiar pe forum :slight_smile:

2 Likes

In general pe reddit sunt multe comunități.

Sunt sigur ca membrii acestui forum pot bate toti oamenii cu doctorate in finante care lucreaza pentru companii de trading si fac algoritmi de 20 de ani pentru asta printr-o simpla strategie de a cumpara actiuni la companiile care par sa aiba succes! /s

Mai in gluma, mai in serios, orice bot ai face rezultatul pe care il vei obtine e aleatoriu pe termen scurt, pun pariu cu tine pe orice suma ca nu poti face un bot care sa aiba succes pe termen mediu sau lung. Random walk hypothesis - Wikipedia

Si cand ma refer la succes sa zic si o cifra, e imposibil sa faci un bot care castiga constant +20% fata de un indice major precum s&p 500 fara o groaza de leverage si chiar si cu leverage la un moment dat riscul pe care ti-l asumi va face ca valoarea pozitiei tale pe termen lung sa tinda spre 0

1 Like

E destul de ambiguu partea cu “bot care să aibă succes pe termen mediu sau lung”.

Mă gândesc că tot trebuie făcută si o mentenanță ocazională.

Depinde de strategie.
Am lucrat într-un cazino cu 20 de ani in urmă și am învățat din pasiune despre probabilități.
Probabilitatea in jocurile de cazino a fost introdusă tot de cineva din domeniul investițiilor la bursă, pentru că era mai ușor de verificat teorii.

Partea bună cu boții e că poți valida strategia înainte de a o pune in aplicare.

Cred că as putea gasi o formulă din blackjack care să poată fi adaptată si investițiilor financiare.

1 Like

Am mai auzit asta si din alte surse, cica traderii care faceau mai putine tranzactii castigau mai mult (Thinking Fast and slow parca).

Dar nu ma gandeam la un model matematic ptr. a prezice.

Mai curand la algoritmi si diverse metode oferite de programare care sa dea un edge.
Tragi informatii de undeva programatic, le parsezi, apoi faci trading tot programatic. La ceva de genul asta ma gandeam.

Cica recomandat sa se citeasca resursele astea.
Papers ptr. mathematical finance.
image

Uhm… :sleepy:

Si am citit ceva interesant pe Quora referitor la asta (din care inteleg mai putin decat as vrea) , las aici ptr. posteritate :smiley:

1


Ok, as a person designing my own automated trading system, I’ll take a crack at it. When someone says algorithmic trading, it covers a VAST subject. This is an incomplete but a long answer. So, grab a soda or cup of coffee, sit down, get comfortable, and read on.

There are four major types of trading algorithms. There are:

  • Execution algorithms
  • Behavior exploitative algorithms
  • Scalping algorithms
  • Predictive algorithms

Let me try to describe these four.

  1. Trade execution algorithms

Many larger funds need to re-allocate their money from one asset to another. Prime brokers like Goldman Sachs market execution level trading algos to their customers promising best cost basis (or at least consistent cost basis) for establishing their positions. Simplest of these are TWAP (time weighted average pricing) and VWAP (volume weighted average pricing). There are many others that serve this function, with Goldman Sachs’ Port-X being one example. Go here for their full offering example (I don’t work for GS because I am not 1337 enough): Goldman Sachs Electronic Trading.

These algorithms generally work by figuring out the capacity of asset market a given time and intelligently spacing out the order executions. You need to figure out whether you can buy multiple smaller blocks of what you want in total without having a price impact or suffering too much from price drift over time. If you have to fill an order for $100 mil worth of a asset A where average daily volume is $1 mil, you will have a huge price impact if you don’t space your orders out intelligently over a long period of time. In other words, if you have a swimming pool of water that you need to pour into a series of wash buckets (representing a market capacity at a given time), you can’t do it without water overflowing out of one bucket.


At the other extreme, in the realm of HFT, you have the algorithms that generally fall into two categories (categories I use are not standard terms, just ones that help me clarify the subject):

  1. Behavior exploitative algorithms

These try to analyze the major opponents in the same securities space. In a smaller liquidity stocks, you often have one large player and everyone else. In those spaces, intelligently figuring out the opponent’s behavior becomes a bit easier than if you had 10000 other traders in the same symbol. Figuring out how the opponent trades, their rules, and edge cases that break it, allows these types of algorithms to exploit the opponent’s system and profit from it.

  1. Scalping algorithms

HFT firms compete by having the “Fastest Guns in the West.” At market micro-structure level, you have essentially the opportunity of price arbitrage. If orderbook at a given instance has someone bidding at $10 and someone asking at $10.1, you have no profit there. Spread is $0.1 and this happens all the time in macro scale. But in order for a transaction to be initiated and settled, you have to have someone either bidding equal or higher amount than what someone is asking. Every so often (and I suspect a lot more often as you compress the time scale) you have situation where someone is bidding $10.0001 and some is asking $10. That’s where having the fastest connections, fastest computers can net you $0.0001 minus the transaction cost basis. You buy from someone selling at $10 and sell it to another person buying at $10.0001. Scalping algos are really small, and needs to be really fast and efficient. More often than not, these algos are prototyped, tested, and then deployed on ASICs or FPGAs.

However, because everyone else is looking for the same type of opportunity, it’s a really crowded space. So you need to design a graceful failover where liquidation leg of the trade needs to incur the least loss possible.

HFT firms, in general, create lower spread and higher liquidity for the market they operate in, great for retail traders like myself.


Most of the time when someone talks about trading algorithm, they are talking about predictive algorithms.

  1. Predictive algorithms

There is a whole class of algorithms that try to predict the future behavior or stocks based on combination of past information, new information, and other second order information. These are called predictive algorithms, and one where most of the lay people are looking into.

Predictive algorithms fall into couple subcategories:

  • Mean reversion
  • Trend following
  • Chart pattern recognition
  • Fundamental analysis
  • Portfolio re-balancing algorithms

I’ll go into each of these.
4.1 Mean reversion is based on the idea that a stock will revert to its mean trading price. Mean reversion algorithms try to establish normalized price patterns compared to either its peer, benchmark, or its own past history. Pairs trading is a very simple example where correlation and cointegration values are calculated for two stocks to figure out whether one can buy one, short other to establish a position and then close the positions when the stocks again trade in tandem. Some chart pattern recognition algorithms are supposed to take advantage of mean reversion behavior.

4.2 Trend following algorithms try to figure out whether there is a long term trend being developed in a particular asset class. Success of such algorithms rely on figuring out who is establishing the positions. Stock market is a extremely large multi-player game and makes it difficult to perform credit assignment for a price behavior, but others have contended that second order information of net money flow from one asset to another asset by closely watching ALL asset space can yield better results in figuring out trend establishments. To put it simply, at least in short term, where accounting information hasn’t changed, the asset prices are established purely based on supply-demand equilibria.

4.3 Chart pattern recognition algorithms try to follow the old maxim (possibly false maxim) of “picture never lies.” This is also called technical analysis. Technical analysis relies on seeing some aggregate chart patterns, like double top, head and shoulders, and so on. Some recent papers do talk about how chart pattern recognition can tell something about the underlying asset pricing behavior and possibly profiting from them ( http://www.cis.upenn.edu/~mkearns/teaching/cis700/lo.pdf )

4.4 Fundamental analysis algorithms try to parse accounting data (essentially) to figure out whether a stock is under/overpriced compared to its peers. Larger firms with more research analysts can do this much better than retail investors like myself, since I don’t have time to figure out exactly how many jeans Gap sold, for an example. Also, macroeconomic data are fed into the system to establish a sort of business cycle based models in some algorithms.

4.5 Portfolio rebalancing algorithms try to take advantage of couple different idea about the asset market pricing behaviors. There are Smart Beta type of portfolio rebalancing algorithms, which try to take advantage of “free lunch” that one see in portfolio constructed only of low volatility assets, and On-line portfolio rebalancing type of algorithms where one tries to take advantage of hypothesis on money-flow and/or mean-reverting behaviors in a universe of assets.


I’m sorry this answer is rather incomplete. I didn’t even go into market microstructures. There are another whole class of sentiment analysis algorithms that I am just not educated enough about to make a guess. I also didn’t cover news based algorithms because I think they are largely voodoo science (feel free to disagree and let me know if I am wrong). I also didn’t include trading algorithms based on completely unsupervised learning algorithms because I think frequent regime changes ensure that they don’t work properly over a longer period of time. I hope my incomplete answer helped you on the right path to understand trading algorithms.

Thanks for reading.

2


An algorithm is a specific set of clearly defined instructions aimed to carry out a task or process.

Algorithmic Trading (automated trading, black-box trading, or simply algo-trading) is the process of using computers programmed to follow a defined set of instructions for placing a trade in order to generate profits at a speed and frequency that is impossible for a human trader. The defined sets of rules are based on timing, price, quantity or any mathematical model. Apart from profit opportunities for the trader, algo-trading makes markets more liquid and makes trading more systematic by ruling out emotional human impacts on trading activities.

Suppose a trader follows these simple trade criteria:

  • Buy 50 shares of a stock when its 50-day moving average goes above the 200-day moving average
  • Sell shares of the stock when its 50-day moving average goes below the 200-day moving average

Using this set of two simple instructions, it is easy to write a computer program which will automatically monitor the stock price (and the moving average indicators) and place the buy and sell orders when the defined conditions are met. The trader no longer needs to keep a watch for live prices and graphs, or put in the orders manually. The algorithmic trading system automatically does it for him, by correctly identifying the trading opportunity.

Benefits of Algorithmic Trading

Algo-trading provides the following benefits:

  • Trades executed at the best possible prices
  • Instant and accurate trade order placement (thereby high chances of execution at desired levels)
  • Trades timed correctly and instantly, to avoid significant price changes
  • Reduced Transaction costs(see the implementation shortfall example below)
  • Simultaneous automated checks on multiple market conditions
  • Reduced risk of manual errors in placing the trades
  • Reduced possibility of mistakes by human traders based on emotional and psychological factors

The greatest portion of present day algo-trading is (HFT), which attempts to capitalize on placing a large number of orders at very fast speeds across multiple markets and multiple decision parameters, based on pre-programmed instructions.

Algorithmic Trading Strategies

Any strategy for algorithmic trading requires an identified opportunity which is profitable in terms of improved earnings or cost reduction. The following are common trading strategies used in algo-trading:

  1. Trend Following Strategies
  2. Arbitrage Opportunities
  3. Mathematical Model Based Strategies
  4. Trading Range (Mean Reversion)
  5. Volume Weighted Average Price (VWAP)
  6. Time Weighted Average Price (TWAP)
  7. Percentage of Volume (POV)
  8. Implementation Shortfall
  9. Beyond the Usual Trading Algorithms

Technical Requirements for Algorithmic Trading

Implementing the algorithm using a computer program is the last part, clubbed with backtesting. The challenge is to transform the identified strategy into an integrated computerized process that has access to a trading account for placing orders. The following are needed:

  • Computer programming knowledge to program the required trading strategy, hired programmers or pre-made trading software.
  • Network connectivity and access to trading platform for placing the orders
  • Access to market data feeds that will be monitored by the algorithm for opportunities to place orders
  • The ability and infrastructure to backtest the system once built, before it goes live on real markets
  • Available historical data for backtesting, depending upon the complexity of rules implemented in algorithm

The computer program should perform the following:

  • Read the incoming price feed of RDS stock from both exchanges
  • Using the available foreign exchange rates, convert the price of one currency to another
  • If there exists a large enough price discrepancy (discounting the brokerage costs) leading to a profitable opportunity, then place the buy order on lower priced exchange and sell order on higher priced exchange
  • If the orders are executed as desired, the arbitrage profit will follow

Simple and easy! However, the practice of algorithmic trading is not that simple to maintain and execute. Remember, if you can place an algo-generated trade, so can the other market participants. Consequently, prices fluctuate in milli- and even microseconds. In the above example, what happens if your buy trade gets executed, but sell trade doesn’t as the sell prices change by the time your order hits the market?

There are additional risks and challenges: for example, system failure risks, network connectivity errors, time-lags between trade orders and execution, and, most important of all, imperfect algorithms. The more complex an algorithm, the more stringent backtesting is needed before it is put into action.

The Bottom Line

Quantitative Analysis of an algorithm’s performance plays an important role and should be examined critically. It’s exciting to go for automation aided by computers with a notion to make money effortlessly. But one must make sure the system is thoroughly tested and required limits are set. Analytical traders should consider learning programming and building systems on their own, to be confident about implementing the right strategies in foolproof manner. Cautious use and thorough testing of algo-trading can create profitable opportunities.

2 Likes

inveti solidity / python sau un limbaj din sfera web3 si faci boti pentru arbitrage trading pe crypto :smiley: majoritatea exchange-urile de crypto care se respecta au API-uri publice. in plus, pe Binance poti face un sub-cont separat de cel principal, dar administrat de cel principal. asa functioneaza spre exemplu bot-ul stoic.

de asemenea, acum cateva luni se faceau bani in draci din smart contracts pe ethereum pentru proiecte nft sau nft vending machines care sunt de fapt node-uri de blockchain (spre exemplu pe cardano), care more or less erau super asemanatoare de la proiect la proiect; aproape puteai spune ca lucrezi waterfall. gasiti exemple pe github din ambele (smart contracts pe eth si nft vending machines pe cardano).

2 Likes