GithubHelp home page GithubHelp logo

arbuzovv / rusquant Goto Github PK

View Code? Open in Web Editor NEW
40.0 2.0 20.0 3.19 MB

Official version of rusquant package for R

Home Page: http://rusquant.ru

License: GNU General Public License v3.0

R 100.00%
r datasource finance trading investing-api finam investing cryptocurrency dividends ipo

rusquant's Introduction

Rusquant

CRAN_Status_Badge CRAN_Downloads CRAN_Ago

Intro

Rusquant is a package for interaction with alternative data, trading API of different exchanges and brokers. Package provides access to market data for storage, analysis, algorithmic trading, strategy backtesting. Also this is data downloader from different data sources starting from close price to order book and tradelog.

Current available brokers - tinkoff.ru, finam.ru, alorbroker.ru. Current available datasources - previous brokers + MOEX, MFD.RU, Poloniex, MarketWatch, Investing, AlgoPack

Supporting rusquant development

If you are interested in supporting the ongoing development and maintenance of rusquant, please consider becoming a sponsor.

Installation

The current release (1.0.5) is available on CRAN, which you can install via:

install.packages("rusquant")

To install the development version (1.0.5), you need to clone the repository and build from source, or run one of:

# lightweight
remotes::install_github("arbuzovv/rusquant")
# or
devtools::install_github("arbuzovv/rusquant")

Getting Started

It is possible to import data from a variety of sources with one rusquant function: getSymbols(). For example:

library(rusquant)
getSymbolList('Finam') # download all available symbols in finam.ru 
getSymbols('LKOH',src='Finam') # default = main market
getSymbols('LKOH',src = 'Finam') # main market
getSymbols.Moex('SBER')

# type period
getSymbols('LKOH',src='Finam',period='day') # day bars - default parameter
getSymbols('LKOH',src='Finam',period='5min') # 5 min bar 
getSymbols('LKOH',src='Finam',period='15min') # 15 min bar
getSymbols.Moex('SBER',period = '1min',from=Sys.Date()-20) # 1 min bar 

Get data from Mfd.ru

getSymbolList('Mfd') # see the availible assets
getSymbols('Сбербанк',src='Mfd')

Get fundamental data from Investing

getEarnings(from = Sys.Date(),to = Sys.Date()+3,country='Belgium')
getEconomic(from = Sys.Date() - 10, to = Sys.Date(), country = "United States")
getIPO(from='2023-01-23',to='2023-01-25')
getDividends(from = Sys.Date(),to = Sys.Date()+2,country = "Australia")
getDividends(from = '2023-08-01',to = '2023-08-05',country = 'United States')

Get microstructure data from AlgoPack

getSymbols.Algopack('SBER',from = '2023-10-24',to='2023-11-04')
getSymbols.Algopack('ROSN',from = '2023-10-24',to='2023-11-04',type = 'obstats')

Live trading using broker account Finam

finam_token = 'mytoken'
finam_account = 'accountid'

#get portfolio info
finam_portfolio = getPortfolio(src = 'Finam',api.key = finam_token,clientId = finam_account)
current_balance = finam_portfolio$equity
finam_universe = data.table(getSymbolList(src = 'Finam',api.key = finam_token))
#change positions
trade_symbol = 'SBER'
last_price = try(tail((getSymbols.Finam(trade_symbol,period = '1min',from=Sys.Date()-2))[,4],1),silent = T)
size_order = 1
trade_side = ifelse(size_order>0,'Buy','Sell')
board = 'TQBR'

myorder = placeOrder(src = 'finam',
                     symbol = trade_symbol,
                     board = board,
                     action = trade_side,
                     totalQuantity = size_order,
                     lmtPrice = as.numeric(last_price),
                     api.key = finam_token,
                     clientId = finam_account)
print(myorder)

my_orders_status = getOrders(src = 'finam',api.key = finam_token,clientId = finam_account)$orders
print(my_orders_status)

Author

Vyacheslav Arbuzov

rusquant's People

Contributors

arbuzovv avatar peter-pogorelov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

rusquant's Issues

Ошибка в `[.data.frame`(fr, , (5:9)) :undefined columns selected

install.packages("rusquant", repos="http://R-Forge.R-project.org")
library("rusquant")

Загрузка требуемого пакета: quantmod
Загрузка требуемого пакета: xts
Загрузка требуемого пакета: zoo

Присоединяю пакет: ‘zoo’

Следующие объекты скрыты от ‘package:base’:

    as.Date, as.Date.numeric

Загрузка требуемого пакета: TTR
Version 0.4-0 included new data defaults. See ?getSymbols.
Learn from a quantmod author: https://www.datacamp.com/courses/importing-and-managing-financial-data-in-r
Загрузка требуемого пакета: lubridate

Присоединяю пакет: ‘lubridate’

Следующий объект скрыт от ‘package:base’:

    date

Загрузка требуемого пакета: data.table
data.table 1.10.4
  The fastest way to learn (by data.table authors): https://www.datacamp.com/courses/data-analysis-the-data-table-way
  Documentation: ?data.table, example(data.table) and browseVignettes("data.table")
  Release notes, videos and slides: http://r-datatable.com

Присоединяю пакет: ‘data.table’

Следующие объекты скрыты от ‘package:lubridate’:

    hour, isoweek, mday, minute, month, quarter, second, wday, week, yday, year

Следующие объекты скрыты от ‘package:xts’:

    first, last

Загрузка требуемого пакета: curl
Было 11 предупреждений (введите warnings() чтобы их просмотреть)

getSymbols("SBER", from=Sys.Date()-1, src="Finam", period="5min")


Ошибка в `[.data.frame`(fr, , (5:9)) :undefined columns selected
Вдобавок: Предупреждение:
В read.table(file = file, header = header, sep = sep, quote = quote,  :
  incomplete final line found by readTableHeader on '/tmp/RtmplJQmZ9/file1f1a796a0ecc'

Error message from getSymbols.MarketWatch

Hello,

I have been trying to use the function "getSymbols.MarketWatch" to retrieve data on CBOE VIX Futures contracts (symbols: "VX.1", "VXF24"), but I get the following error message after inserting the command below:

getSymbols.MarketWatch("VXF24", env = globalenv(), from = "2020-01-01", to = "2023-12-27")

Downloaded 99085 bytes...Error in curl::curl_download(input, tmpFile, mode = "wb", quiet = !showProgress) : HTTP error 404.

Any idea of why this is happening and how to deal with it so that the data can be obtained?

Many thanks,
rabarros01

Features

Hi,

I have several questions:

  1. It seems there is a limit on how much data I can retrieve. What is the limit I can download in one shot?
  2. Is the oldest data for intraday USA stock May of 2007?
  3. Is it possible to download split and dividend-adjusted intraday data?

Ошибка в `[.data.frame`(fr, , (5:6)) :undefined columns selected

Добрый день.

При использовании примера

library(rusquant)
getSymbols("SBER", from=Sys.Date()-2, src="Finam", period="tick")

Выдаёт ошибку: Ошибка в [.data.frame(fr, , (5:6)) :undefined columns selected
Я смотрел похожий закрытый issues, там вы указывали на то что это был выходной день, но сейчас это получается понедельник и там данные у финама за 21.01 есть.

Traceback

9. stop("undefined columns selected") 
8. `[.data.frame`(fr, , (5:6)) at getSymbols.R#449
7. fr[, (5:6)] at getSymbols.R#449
6. as.matrix(fr[, (5:6)]) at getSymbols.R#449
5. apply(as.matrix(fr[, (5:6)]), 2, as.numeric) at getSymbols.R#449
4. xts(apply(as.matrix(fr[, (5:6)]), 2, as.numeric), as.POSIXct(strptime(paste(fr[, 
    3], fr[, 4]), "%Y%m%d %H%M%S")), src = "finam", updated = Sys.time()) at getSymbols.R#449
3. getSymbols.Finam(Symbols = "SBER", env = <environment>, verbose = FALSE, 
    warnings = TRUE, auto.assign = TRUE, from = structure(17916, class = "Date"), 
    period = "tick") 
2. do.call(paste("getSymbols.", symbol.source, sep = ""), list(Symbols = current.symbols, 
    env = env, verbose = verbose, warnings = warnings, auto.assign = auto.assign, 
    ...)) 
1. getSymbols("SBER", from = Sys.Date() - 2, src = "Finam", period = "tick") 

Ругается на 449 строку в файле getSymbols.R

Версия пакета rusquant 0.4.0, установлена из вашего гита, версия на r-forge выдаёт такую же ошибку :(

Спасибо.

R CMD CHECK: file edit_for_rusquant.R

There's a non-standard file edit_for_rusquant.R in the top-level directory. What's its' status?
It should be either removed or incorporated into source files before submitting to CRAN.

API Error

APIError(code=-1021): Timestamp for this request was 1000ms ahead of the server's time.

Solution in code?

Increase timeout in download.file function

Hi,

When I tried to get tick data for one date and one symbol, I got an warning:

Warning message:
In download.file(stock.URL, destfile = tmp, quiet = !verbose) :
  URL 'http://export.finam.ru/table.csv?d=d&f=table&e=.csv&dtf=1&tmf=1&MSOR=0&sep=1&sep2=1&at=1&p=1&market=25&em=21053&df=28&mf=1&yf=2020&dt=28&mt=1&yt=2020&datf=6': Timeout of 60 seconds was reached

Could you increase the timeout to higher number, or make it an argument of the function?

Bonus question: Is there any other source in your package (except Finam) that have US tick trades or quotes?

API data from Investing.com

Thanks for authoring the rusquant package.
I get this message:
Error in getInvesting_id(Symbol) : object 'json_data' not found
What am I doing wrong?

Error in sub("var .*?= \\[", "", fr[2]) : input string 1 is invalid

Issue

getSymbolList("Finam") downloads file with original "WINDOWS-1251" encoding. The function readLines(encoding = 'UTF-8') does not help since fun doc contains: "it is not used to re-encode the input. ". So, after R update up to:

R version 4.3.1 (2023-06-16)
Platform: aarch64-apple-darwin20 (64-bit)

getSymbolList() started to throw error:

Error in sub("var .*?= \\[", "", fr[2]) : input string 1 is invalid
In addition: Warning message:
In sub("var .*?= \\[", "", fr[2]) :
  unable to translate 'var aEmitentNames = ['SPFB.Eu-12.22','SPFB.BR-9.22','SPFB.Eu-3.23','SPFB.BR-10.22','SPFB.BR-11.22','US1.LOGM_disappeared_2835723','SPFB.MXI-12.22','SPFB.RUON-12.22','US1.TPG','SPFB.BR-3.22-4.22','SPFB.FNI-9.22','SPFB.AFLT-12.22','SPFB.GAZR-3.23','SPFB....' to a wide string

Fix

Error could be easily fixed by forcing convert from "WINDOWS-1251" to "UTF8" via iconv() function.

Caveats

  • I've tested on MacOS(ARM) and MacOS(Intel) and everything looks fine. I assume probability to face issue for Windows. Therefore it's better to test on Windows before fork merge .
  • Other sources also could use unwanted "WINDOWS-1251", so other fixes might be considered the same way

Полностью пропали котировки с финама

image

Сегодня в середине дня полностью перестали загружаться данные с финама с ошибкой которая приложена на изображении. Утром работало на любых временных интервалах. Сейчас даже дневки не дает. Видел похожую проблему в вопросах , но сегодня не выходной. Не могу понять в чем сейчас проблема

Finam moved to https from http

getSymbols("SPFB.BR",src="Finam",from=Sys.Date()-7,to=Sys.Date(),period="day")
    As of 0.4-0, ‘getSymbols’ uses env=parent.frame() and
 auto.assign=TRUE by default.

 This  behavior  will be  phased out in 0.5-0  when the call  will
 default to use auto.assign=FALSE. getOption("getSymbols.env") and 
 getOptions("getSymbols.auto.assign") are now checked for alternate defaults

 This message is shown once per session and may be disabled by setting 
 options("getSymbols.warning4.0"=FALSE). See ?getSymbols for more details.
Error in download.file(stocklist.URL, destfile = tmp, quiet = !verbose) : 
  cannot open URL 'http://www.finam.ru/cache/icharts/icharts.js'

URL 'http://www.finam.ru/cache/icharts/icharts.js' redirects to the 'httpS://www.finam.ru/cache/icharts/icharts.js' in the browsers

getDividends() throws error

simple request getDividends() throws error :

unique(Records_result) : object 'Records_result' not found

digging deeper to issue I found out investing.com returns 403 status for any request. It seems like issue related to case

Eventually, seems like investing.com technically prohibits getting data programmatically :(

Error in readLines when test sample code from readme

Hello,

I have tried to execute sample code from readme:

getSymbols('LKOH',src='Finam',period='day')

but it returns an error:

trying URL 'https://www.finam.ru/cache/N72Hgd54/icharts/icharts.js'
downloaded 1003 KB

Error in readLines(con = tmp, warn = FALSE, encoding = "UTF-8") : 
  error reading from the connection
In addition: Warning message:
In readLines(con = tmp, warn = FALSE, encoding = "UTF-8") :
  invalid or incomplete compressed data

Could you please confirm the error?
I have just installed dev version from GitHub.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.