Coder Social home page Coder Social logo

trump2cash's Introduction

Trump2Cash

This bot watches Donald Trump's tweets and waits for him to mention any publicly traded companies. When he does, it uses sentiment analysis to determine whether his opinions are positive or negative toward those companies. The bot then automatically executes trades on the relevant stocks according to the expected market reaction. It also tweets out a summary of its findings in real time at @Trump2Cash.

You can read more about the background story here.

Trump2Cash

The code is written in Python and is meant to run on a Google Compute Engine instance. It uses the Twitter Streaming APIs to get notified whenever Trump tweets. The entity detection and sentiment analysis is done using Google's Cloud Natural Language API and the Wikidata Query Service provides the company data. The TradeKing API does the stock trading.

The main module defines a callback where incoming tweets are handled and starts streaming Trump's feed:

def twitter_callback(tweet):
    companies = analysis.find_companies(tweet)
    if companies:
        trading.make_trades(companies)
        twitter.tweet(companies, tweet)

if __name__ == '__main__':
    twitter.start_streaming(twitter_callback)

The core algorithms are implemented in the analysis and trading modules. The former finds mentions of companies in the text of the tweet, figures out what their ticker symbol is, and assigns a sentiment score to them. The latter chooses a trading strategy, which is either buy now and sell at close or sell short now and buy to cover at close. The twitter module deals with streaming and tweeting out the summary.

Follow these steps to run the code yourself:

1. Create VM instance

Check out the quickstart to create a Cloud Platform project and a Linux VM instance with Compute Engine, then SSH into it for the steps below. Pick a predefined machine type matching your preferred price and performance.

Container

Alternatively, you can use the Dockerfile to build a Docker container and run it on Compute Engine or other platforms.

docker build -t trump2cash .
docker tag trump2cash gcr.io/<YOUR_GCP_PROJECT_NAME>/trump2cash
docker push gcr.io/<YOUR_GCP_PROJECT_NAME>/trump2cash:latest

2. Set up auth

The authentication keys for the different APIs are read from shell environment variables. Each service has different steps to obtain them.

Twitter

Log in to your Twitter account and create a new application. Under the Keys and Access Tokens tab for your app you'll find the Consumer Key and Consumer Secret. Export both to environment variables:

export TWITTER_CONSUMER_KEY="<YOUR_CONSUMER_KEY>"
export TWITTER_CONSUMER_SECRET="<YOUR_CONSUMER_SECRET>"

If you want the tweets to come from the same account that owns the application, simply use the Access Token and Access Token Secret on the same page. If you want to tweet from a different account, follow the steps to obtain an access token. Then export both to environment variables:

export TWITTER_ACCESS_TOKEN="<YOUR_ACCESS_TOKEN>"
export TWITTER_ACCESS_TOKEN_SECRET="<YOUR_ACCESS_TOKEN_SECRET>"

Google

Follow the Google Application Default Credentials instructions to create, download, and export a service account key.

export GOOGLE_APPLICATION_CREDENTIALS="/path/to/credentials-file.json"

You also need to enable the Cloud Natural Language API for your Google Cloud Platform project.

TradeKing

Log in to your TradeKing account and create a new application. Behind the Details button for your application you'll find the Consumer Key, Consumer Secret, OAuth (Access) Token, and Oauth (Access) Token Secret. Export them all to environment variables:

export TRADEKING_CONSUMER_KEY="<YOUR_CONSUMER_KEY>"
export TRADEKING_CONSUMER_SECRET="<YOUR_CONSUMER_SECRET>"
export TRADEKING_ACCESS_TOKEN="<YOUR_ACCESS_TOKEN>"
export TRADEKING_ACCESS_TOKEN_SECRET="<YOUR_ACCESS_TOKEN_SECRET>"

Also export your TradeKing account number, which you'll find under My Accounts:

export TRADEKING_ACCOUNT_NUMBER="<YOUR_ACCOUNT_NUMBER>"

3. Install dependencies

There are a few library dependencies, which you can install using pip:

pip install -r requirements.txt

4. Run the tests

Verify that everything is working as intended by running the tests with pytest using this command:

export USE_REAL_MONEY=NO && pytest *.py -vv

5. Run the benchmark

The benchmark report shows how the current implementation of the analysis and trading algorithms would have performed against historical data. You can run it again to benchmark any changes you may have made. You'll need a Polygon account:

export POLYGON_API_KEY="<YOUR_POLYGON_API_KEY>"
python benchmark.py > benchmark.md

6. Start the bot

Enable real orders that use your money:

export USE_REAL_MONEY=YES

Have the code start running in the background with this command:

nohup python main.py &

trump2cash's People

Contributors

dependabot[bot] avatar maxbbraun 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

trump2cash's Issues

Ally / Tradeking Forex

Again another issue/enhancement @maxbbraun , wanting to inject Forex in to the equation, not seeing any documentation bar talk of adding forex, is there any specific areas this has been added but not showing or finished, and if not where would you recommend, and how would you recommend tying in to your current set up.

Improve Wikidata query

The current Wikidata query, for example, takes chains of ownership and subsidiaries into account, but doesn't mix those chains.

There are also probably additional relationships between companies that should be taken into account.

Get working in Google App Engine

This would be great to run in App Engine. I'll try getting it working and submit a PR with the requisite configs if I do. I believe using dotenv for configs would be mandatory #26

Enable other trading platform APIs

TradeKing is only available to customers within within the US.
It would be great if it was possible to replace the TradeKing API with one from another trading platform which is available in Europe/UK.
I'll take a look at the code myself to investigate but I'm very much a beginner with Python.

Tests failing

`E assert [{'exchange':...cker': 'BLK'}] == [{'exchange': ...cker': 'PNC'}]
E At index 0 diff: {'root': u'PNC Financial Services', 'ticker': u'PNC', 'name': u'Bayer', 'exchange': u'New York Stock Exchange'} != {'ticker': 'BLK', 'root': 'BlackRock', 'name': 'Bayer', 'exchange': 'New York Stock Exchange'}
E Full diff:
E - [{'exchange': u'New York Stock Exchange',
E ? -
E + [{'exchange': 'New York Stock Exchange',
E - 'name': u'Bayer',
E ? -
E + 'name': 'Bayer',
E - 'root': u'PNC Financial Services',
E Detailed information truncated (17 more lines), use "-vv" to show

analysis_tests.py:86: AssertionError`

and

`E assert [{'exchange':...t': 0.4, ...}] == [{'exchange': ...t': 0.4, ...}]
E At index 0 diff: {'root': u'PNC Financial Services', 'ticker': u'PNC', 'name': u'Bayer', 'sentiment': 0.4, 'exchange': u'New York Stock Exchange'} != {'ticker': 'BLK', 'root': 'BlackRock', 'name': 'Bayer', 'sentiment': 0.4, 'exchange': 'New York Stock Exchange'}
E Full diff:
E - [{'exchange': u'New York Stock Exchange',
E ? -
E + [{'exchange': 'New York Stock Exchange',
E - 'name': u'Bayer',
E ? -
E + 'name': 'Bayer',
E - 'root': u'PNC Financial Services',
E Detailed information truncated (19 more lines), use "-vv" to show

analysis_tests.py:312: AssertionError
===================== 2 failed, 46 passed in 41.57 seconds =====================
`

,

.

Ethics & Responsibility

I understand might be an interesting experiment in some context. But I have huge ethical concerns. By doing this you basically support and amplify the ( IMHO already way to high ) power of trump. Do you really want this? I think this app should come with a big red warning sign - I would even be a bit more radical as greedy people might still use it despite this warning sign.

Need help for /1.1/users/lookup request

I am trying to do request on users/lookup route of Twitter API using params of Email/Phone. In the result I am getting error
Could not authenticate you. in response

While using the same credentials when i do request for screen_name, user_id lookup I am getting perfect Response. Not only that all other api requests like home_timeline, followers_ids, friends_ids, etc are working fine with same credentials but on that specific request, I am getting this error. My Request is:

import requests

url = "https://api.twitter.com/1.1/users/lookup.json?map=true&phone=1234567890"

payload = {}

headers = {
    'Authorization': 'OAuth realm="http%3A%2F%2Fapi.twitter.com",oauth_consumer_key="<consumer_key>",oauth_token="<outh_token>",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1595318479",oauth_nonce="<nonce>",oauth_version="1.0",oauth_signature="<sig>"'
}

response = requests.request("GET", url, headers=headers, data = payload)
print(response.text.encode('utf8'))

In Response I am getting this Error:

{
    "errors": [
        {
            "code": 32,
            "message": "Could not authenticate you."
        }
    ]
}

What are the reasons and suggestions on this ?
Will appreciate the positive feedback.

Error following recent tweet

TweepError: [{u'message': u'Status is over 140 characters.', u'code': 186}]
at execute (/usr/local/lib/python2.7/dist-packages/tweepy/binder.py:229)
at _call (/usr/local/lib/python2.7/dist-packages/tweepy/binder.py:245)
at update_status (/usr/local/lib/python2.7/dist-packages/tweepy/api.py:194)
at tweet (/home/czxm/trump2cash/twitter.py:89)
at twitter_callback (./main.py:24)
at handle_data (/home/czxm/trump2cash/twitter.py:276)
at process_queue (/home/czxm/trump2cash/twitter.py:219)

Use limit orders

Seems risky to always buy at market rate. Should use some reasonable range around the expected price.

NameError: global name 'logger' is not defined

Traceback (most recent call last):
  File "/home/max_braun/trump-correction/twitter.py", line 129, in safe_handle_data
    self.handle_data(logs, data)
  File "/home/max_braun/trump-correction/twitter.py", line 166, in handle_data
    self.callback(text, link)
  File "/home/max_braun/trump-correction/main.py", line 18, in twitter_callback
    logger.log_text("Using companies: %s" % companies, severity="DEBUG")
NameError: global name 'logger' is not defined

Decreasing return

I notice benchmark.md hasn't been updated lately. But I'm just curious why the algorithm is not as effective after January. Is it because of the accuracy of the sentiment analysis or the correlation between share prices and trump's tweets has gone down? Could also be taking too much risk? But that's hard to tell w/o looking at the sentiment scores...

tweeperror

        except Exception as e:
          raise TweepError('Failed to send request: %s' % e)

E TweepError: Failed to send request: Only unicode objects are escapable. Got None of type <type 'NoneType'>.

Note for others i believe this will resolve this as this application is undocumented, and (our end) full or errors.

requests/requests-oauthlib#11

Document which direction you are trading in based on sentiment

It's not clear from the current docs whether you buy or sell stock for a company that Trump complains about.

You should state your bias about your expectation about Trump's tweets effect on stock prices. (Note that Nordstorm stock went up after Trump complained about them).

InternalServerError: 500 Internal error encountered. (POST https://logging.googleapis.com/v2/entries:write)

Happening occasionally.

Traceback (most recent call last):
  File "/home/max_braun/trump2cash/twitter.py", line 174, in process_queue
    self.handle_data(logs, data)
  File "/home/max_braun/trump2cash/twitter.py", line 226, in handle_data
    (screen_name, user_id_str))
  File "/home/max_braun/trump2cash/logs.py", line 38, in debug
    self.logger.log_text(text, severity="DEBUG")
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/logging/logger.py", line 192, in log_text
    client.logging_api.write_entries([entry_resource])
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/logging/_http.py", line 165, in write_entries
    data=data)
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/_http.py", line 335, in api_request
    error_info=method + ' ' + url)
InternalServerError: 500 Internal error encountered. (POST https://logging.googleapis.com/v2/entries:write)

InvalidArgument: 400 The language pl is not supported for entity analysis

Stack trace:

Traceback (most recent call last):
  File "/app/twitter.py", line 298, in process_queue
    self.handle_data(logs, data)
  File "/app/twitter.py", line 364, in handle_data
    self.callback(tweet)
  File "main.py", line 92, in twitter_callback
    companies = analysis.find_companies(tweet)
  File "/app/analysis.py", line 121, in find_companies
    entities = self.language_client.analyze_entities(document).entities
  File "/usr/local/lib/python2.7/site-packages/google/cloud/language_v1/gapic/language_service_client.py", line 225, in analyze_entities
    return self._analyze_entities(request, retry=retry, timeout=timeout)
  File "/usr/local/lib/python2.7/site-packages/google/api_core/gapic_v1/method.py", line 139, in __call__
    return wrapped_func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/google/api_core/retry.py", line 260, in retry_wrapped_func
    on_error=on_error,
  File "/usr/local/lib/python2.7/site-packages/google/api_core/retry.py", line 177, in retry_target
    return target()
  File "/usr/local/lib/python2.7/site-packages/google/api_core/timeout.py", line 206, in func_with_timeout
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/google/api_core/grpc_helpers.py", line 56, in error_remapped_callable
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "/usr/local/lib/python2.7/site-packages/six.py", line 737, in raise_from
    raise value
InvalidArgument: 400 The language pl is not supported for entity analysis.

Additional logs:

2018-09-18 14:20:47.816 PDT
Examining tweet: {u'quote_count': 0, u'contributors': None, u'truncated': False, u'text': u'Today, it was my great honor to welcome @prezydentpl Andrzej Duda of Poland to the @WhiteHouse! https://t.co/VdsTYdq9MN', u'is_quote_status': False, u'in_reply_to_status_id': None, u'reply_count': 0, u'id': 1042161534603063301, u'favorite_count': 0, u'entities': {u'user_mentions': [{u'id': 43932737, u'indices': [40, 52], u'id_str': u'43932737', u'screen_name': u'prezydentpl', u'name': u'Kancelaria Prezydenta'}, {u'id': 822215673812119553, u'indices': [83, 94], u'id_str': u'822215673812119553', u'screen_name': u'WhiteHouse', u'name': u'The White House'}], u'symbols': [], u'hashtags': [], u'urls': [], u'media': [{u'expanded_url': u'https://twitter.com/realDonaldTrump/status/1042161534603063301/photo/1', u'display_url': u'pic.twitter.com/VdsTYdq9MN', u'url': u'https://t.co/VdsTYdq9MN', u'media_url_https': u'https://pbs.twimg.com/media/DnaAWfhWwAUdk11.jpg', u'id_str': u'1042161487689728005', u'sizes': {u'small': {u'h': 453, u'resize': u'fit', u'w': 680}, u'large': {u'h': 1364, u'resize': u'fit', u'w': 2048}, u'medium': {u'h': 799, u'resize': u'fit', u'w': 1200}, u'thumb': {u'h': 150, u'resize': u'crop', u'w': 150}}, u'indices': [96, 119], u'type': u'photo', u'id': 1042161487689728005, u'media_url': u'http://pbs.twimg.com/media/DnaAWfhWwAUdk11.jpg'}]}, u'retweeted': False, u'coordinates': None, u'timestamp_ms': u'1537305646931', u'source': u'<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>', u'in_reply_to_screen_name': None, u'id_str': u'1042161534603063301', u'display_text_range': [0, 95], u'retweet_count': 0, u'in_reply_to_user_id': None, u'favorited': False, u'user': {u'follow_request_sent': None, u'profile_use_background_image': True, u'default_profile_image': False, u'id': 25073877, u'default_profile': False, u'verified': True, u'profile_image_url_https': u'https://pbs.twimg.com/profile_images/874276197357596672/kUuht00m_normal.jpg', u'profile_sidebar_fill_color': u'C5CEC0', u'profile_text_color': u'333333', u'followers_count': 54518410, u'profile_sidebar_border_color': u'BDDCAD', u'id_str': u'25073877', u'profile_background_color': u'6D5C18', u'listed_count': 93751, u'profile_background_image_url_https': u'https://abs.twimg.com/images/themes/theme1/bg.png', u'utc_offset': None, u'statuses_count': 39013, u'description': u'45th President of the United States of America\U0001f1fa\U0001f1f8', u'friends_count': 47, u'location': u'Washington, DC', u'profile_link_color': u'1B95E0', u'profile_image_url': u'http://pbs.twimg.com/profile_images/874276197357596672/kUuht00m_normal.jpg', u'following': None, u'geo_enabled': True, u'profile_banner_url': u'https://pbs.twimg.com/profile_banners/25073877/1535689655', u'profile_background_image_url': u'http://abs.twimg.com/images/themes/theme1/bg.png', u'name': u'Donald J. Trump', u'lang': u'en', u'profile_background_tile': True, u'favourites_count': 25, u'screen_name': u'realDonaldTrump', u'notifications': None, u'url': u'http://www.Instagram.com/realDonaldTrump', u'created_at': u'Wed Mar 18 13:46:38 +0000 2009', u'contributors_enabled': False, u'time_zone': None, u'protected': False, u'translator_type': u'regular', u'is_translator': False}, u'geo': None, u'in_reply_to_user_id_str': None, u'possibly_sensitive': False, u'lang': u'en', u'created_at': u'Tue Sep 18 21:20:46 +0000 2018', u'filter_level': u'low', u'in_reply_to_status_id_str': None, u'place': None, u'extended_entities': {u'media': [{u'expanded_url': u'https://twitter.com/realDonaldTrump/status/1042161534603063301/photo/1', u'display_url': u'pic.twitter.com/VdsTYdq9MN', u'url': u'https://t.co/VdsTYdq9MN', u'media_url_https': u'https://pbs.twimg.com/media/DnaAWfhWwAUdk11.jpg', u'id_str': u'1042161487689728005', u'sizes': {u'small': {u'h': 453, u'resize': u'fit', u'w': 680}, u'large': {u'h': 1364, u'resize': u'fit', u'w': 2048}, u'medium': {u'h': 799, u'resize': u'fit', u'w': 1200}, u'thumb': {u'h': 150, u'resize': u'crop', u'w': 150}}, u'indices': [96, 119], u'type': u'photo', u'id': 1042161487689728005, u'media_url': u'http://pbs.twimg.com/media/DnaAWfhWwAUdk11.jpg'}, {u'expanded_url': u'https://twitter.com/realDonaldTrump/status/1042161534603063301/photo/1', u'display_url': u'pic.twitter.com/VdsTYdq9MN', u'url': u'https://t.co/VdsTYdq9MN', u'media_url_https': u'https://pbs.twimg.com/media/DnaAWfsVsAAEuXG.jpg', u'id_str': u'1042161487735795712', u'sizes': {u'small': {u'h': 453, u'resize': u'fit', u'w': 680}, u'large': {u'h': 1364, u'resize': u'fit', u'w': 2048}, u'medium': {u'h': 799, u'resize': u'fit', u'w': 1200}, u'thumb': {u'h': 150, u'resize': u'crop', u'w': 150}}, u'indices': [96, 119], u'type': u'photo', u'id': 1042161487735795712, u'media_url': u'http://pbs.twimg.com/media/DnaAWfsVsAAEuXG.jpg'}, {u'expanded_url': u'https://twitter.com/realDonaldTrump/status/1042161534603063301/photo/1', u'display_url': u'pic.twitter.com/VdsTYdq9MN', u'url': u'https://t.co/VdsTYdq9MN', u'media_url_https': u'https://pbs.twimg.com/media/DnaAWfoVAAAQNR6.jpg', u'id_str': u'1042161487718973440', u'sizes': {u'small': {u'h': 454, u'resize': u'fit', u'w': 680}, u'large': {u'h': 1366, u'resize': u'fit', u'w': 2048}, u'medium': {u'h': 800, u'resize': u'fit', u'w': 1200}, u'thumb': {u'h': 150, u'resize': u'crop', u'w': 150}}, u'indices': [96, 119], u'type': u'photo', u'id': 1042161487718973440, u'media_url': u'http://pbs.twimg.com/media/DnaAWfoVAAAQNR6.jpg'}, {u'expanded_url': u'https://twitter.com/realDonaldTrump/status/1042161534603063301/photo/1', u'display_url': u'pic.twitter.com/VdsTYdq9MN', u'url': u'https://t.co/VdsTYdq9MN', u'media_url_https': u'https://pbs.twimg.com/media/DnaAWfqV4AAJ6_q.jpg', u'id_str': u'1042161487727419392', u'sizes': {u'small': {u'h': 454, u'resize': u'fit', u'w': 680}, u'large': {u'h': 1366, u'resize': u'fit', u'w': 2048}, u'medium': {u'h': 800, u'resize': u'fit', u'w': 1200}, u'thumb': {u'h': 150, u'resize': u'crop', u'w': 150}}, u'indices': [96, 119], u'type': u'photo', u'id': 1042161487727419392, u'media_url': u'http://pbs.twimg.com/media/DnaAWfqV4AAJ6_q.jpg'}]}}
2018-09-18 14:20:48.032 PDT
Using mentions: [{u'id': 43932737, u'indices': [40, 52], u'id_str': u'43932737', u'screen_name': u'prezydentpl', u'name': u'Kancelaria Prezydenta'}, {u'id': 822215673812119553, u'indices': [83, 94], u'id_str': u'822215673812119553', u'screen_name': u'WhiteHouse', u'name': u'The White House'}]

More aggressive selling

For negative sentiment: Sell short, then try detecting when the stock recovers and buy to cover instead of waiting until market close.

Buying GM stock when I run Pytest

I was testing the application and ran the Pytest. Only 2 test fail which is the test_get_balance and the test_make_order_request_success. It's normal because I don't have balance in my trade king account. What worries me is that on the order status dashboard in Tradeking is showing the multiple requests exactly with the same timestamp I ran the Pytest:

Buy 23 GM GENERAL MOTORS CO. Market 37.24 37.24 Day 02/14/17 4:17 PM ET SVR-6031544108 Rejected You have not funded your account yet. Please go to the Transfer Money tab to get started funding your account.

I made sure that I ran export USE_REAL_MONEY=NO && pytest *.py --verbose. Even checked through printenv that the variable was set to "NO".

My concern is that if I did had balance in the Tradeking account the order would have been accepted. I looked in the code and it does seem to check if USE_REAL_MONEY is YES or NO, but it seems it's trading with real funds independently.

Place orders even while the market is closed

Placing an order before the markets open or placing one after close for the next day could still pay off.

Just need to make sure the corresponding sell or cover order at close is for the next day.

Should combine this with using limits (#9) to be safe.

Build it as a docker image

This will help shorten the setup process.

Also currently I'm getting some errors during dependency installation as following

/usr/bin/ld: cannot find -lz

collect2: error: ld returned 1 exit status

error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

.

Sorry, wrong window.

Trade test failing after recent change

(Assuming this test isn't failing because the market is closed...)

`_______________________ test_make_order_request_success ________________________

trading = <trading.Trading instance at 0x7f79f369a878>

def test_make_order_request_success(trading):
    assert not USE_REAL_MONEY
  assert trading.make_order_request((
        '<FIXML xmlns="http://www.fixprotocol.org/FIXML-5-0-SP2">'
        '<Order TmInForce="0" Typ="1" Side="1" Acct="%s">'
        '<Instrmt SecTyp="CS" Sym="GM"/>'
        '<OrdQty Qty="23"/>'
        '</Order>'
        '</FIXML>' % TRADEKING_ACCOUNT_NUMBER))

E assert False
E + where False = <bound method Trading.make_order_request of <trading.Trading instance at 0x7f79f369a878>>(('' % '12345678'))
E + where <bound method Trading.make_order_request of <trading.Trading instance at 0x7f79f369a878>> = <trading.Trading instance at 0x7f79f369a878>.make_order_request

trading_tests.py:374: AssertionError`

BadGateway: 502 <!DOCTYPE html> <html lang=en> <meta charset=utf-8> <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width"> <title>Error 502 (Server Error)!!1</title> <style> *{margin:0;padding:0}html,code{font:15px/22px arial,…

Happening occasionally.

Traceback (most recent call last):
  File "/home/max_braun/trump2cash/twitter.py", line 172, in process_queue
    logs.debug("Processing queue of size: %s" % size)
  File "/home/max_braun/trump2cash/logs.py", line 38, in debug
    self.logger.log_text(text, severity="DEBUG")
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/logging/logger.py", line 192, in log_text
    client.logging_api.write_entries([entry_resource])
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/logging/_http.py", line 165, in write_entries
    data=data)
  File "/usr/local/lib/python2.7/dist-packages/google/cloud/_http.py", line 335, in api_request
    error_info=method + ' ' + url)
BadGateway: 502 <!DOCTYPE html>
<html lang=en>
  <meta charset=utf-8>
  <meta name=viewport content="initial-scale=1, minimum-scale=1, width=device-width">
  <title>Error 502 (Server Error)!!1</title>
  <style>
    *{margin:0;padding:0}html,code{font:15px/22px arial,sans-serif}html{background:#fff;color:#222;padding:15px}body{margin:7% auto 0;max-width:390px;min-height:180px;padding:30px 0 15px}* > body{background:url(//www.google.com/images/errors/robot.png) 100% 5px no-repeat;padding-right:205px}p{margin:11px 0 22px;overflow:hidden}ins{color:#777;text-decoration:none}a img{border:0}@media screen and (max-width:772px){body{background:none;margin-top:0;max-width:none;padding-right:0}}#logo{background:url(//www.google.com/images/branding/googlelogo/1x/googlelogo_color_150x54dp.png) no-repeat;margin-left:-5px}@media only screen and (min-resolution:192dpi){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat 0% 0%/100% 100%;-moz-border-image:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) 0}}@media only screen and (-webkit-min-device-pixel-ratio:2){#logo{background:url(//www.google.com/images/branding/googlelogo/2x/googlelogo_color_150x54dp.png) no-repeat;-webkit-background-size:100% 100%}}#logo{display:inline-block;height:54px;width:150px}
  </style>
  <a href=//www.google.com/><span id=logo aria-label=Google></span></a>
  <p><b>502.</b> <ins>That’s an error.</ins>
  <p>The server encountered a temporary error and could not complete your request.<p>Please try again in 30 seconds.  <ins>That’s all we know.</ins>
 (POST https://logging.googleapis.com/v2/entries:write)

ProtocolError: ('Connection broken: IncompleteRead(0 bytes read, XXX more expected)', IncompleteRead(0 bytes read, XXX more expected))

Traceback (most recent call last):
  File "/home/max_braun/trump-correction/main.py", line 35, in <module>
    twitter.start_streaming()
  File "/home/max_braun/trump-correction/twitter.py", line 51, in start_streaming
    self.twitter_stream.filter(follow=[TRUMP_USER_ID])
  File "/usr/local/lib/python2.7/dist-packages/tweepy/streaming.py", line 445, in filter
    self._start(async)
  File "/usr/local/lib/python2.7/dist-packages/tweepy/streaming.py", line 361, in _start
    self._run()
  File "/usr/local/lib/python2.7/dist-packages/tweepy/streaming.py", line 294, in _run
    raise exception
ProtocolError: ('Connection broken: IncompleteRead(0 bytes read, 512 more expected)', IncompleteRead(0 bytes read, 512 more expected))

UnicodeEncodeError

Entering
./benchmark.py > benchmark.md
in a new install returns a Unicode error, apparently due to concatenating unexpected types.
Traceback (most recent call last): File "./benchmark.py", line 191, in <module> print "\n\n".join(lines) UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 144: ordinal not in range(128)

AttributeError: 'NoneType' object has no attribute 'strip'

Seeing this occasionally. Probably the same as tweepy/tweepy#576. Could try using tweepy from head instead of the latest in PyPI (3.5.0).

Traceback (most recent call last):
  File "/home/max_braun/trump2cash/main.py", line 34, in <module>
    twitter.start_streaming(twitter_callback)
  File "/home/max_braun/trump2cash/twitter.py", line 59, in start_streaming
    twitter_stream.filter(follow=[TRUMP_USER_ID])
  File "/usr/local/lib/python2.7/dist-packages/tweepy/streaming.py", line 445, in filter
    self._start(async)
  File "/usr/local/lib/python2.7/dist-packages/tweepy/streaming.py", line 361, in _start
    self._run()
  File "/usr/local/lib/python2.7/dist-packages/tweepy/streaming.py", line 294, in _run
    raise exception
AttributeError: 'NoneType' object has no attribute 'strip'

Sell order when overall trade is above 10$

Does anyone know (i am merging this code with our own) but i am coming unstock trying to work out where the ALLY/Tradeking and this script combine to determine the profit call on a trade, so looking for pointers where in the code this exists if not where it should be tied in and created?

@maxbbraun this is your O/S Baby, i take it you do follow it's uses / issues?

Crash when trying to tweet with too many companies

Traceback (most recent call last):
  File "/home/max_braun/trump2cash/twitter.py", line 219, in process_queue
    self.handle_data(logs, data)
  File "/home/max_braun/trump2cash/twitter.py", line 276, in handle_data
    self.callback(tweet)
  File "/home/max_braun/trump2cash/main.py", line 24, in twitter_callback
    twitter.tweet(companies, tweet)
  File "/home/max_braun/trump2cash/twitter.py", line 89, in tweet
    self.twitter_api.update_status(text)
  File "/usr/local/lib/python2.7/dist-packages/tweepy/api.py", line 194, in update_status
    )(post_data=post_data, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 245, in _call
    return method.execute()
  File "/usr/local/lib/python2.7/dist-packages/tweepy/binder.py", line 229, in execute
    raise TweepError(error_msg, resp, api_code=api_error_code)
TweepError: [{u'message': u'Status is over 140 characters.', u'code': 186}]

Two recent tweets (838862131852369922, 838861512999649286) ran into this issue. Trading was not affected.

The plan is to pick a less verbose format for the tweet text to begin with, then truncate to 140 characters if it's still over.

Consider using loklak for anonymously searching for tweets when you hit a rate limit

Hey @maxbbraun I am one of the core developers of the loklak.org project and what you're doing here is amazing, for similar applications and for research we've built a P2P system which crawls and stores twitter data and provides you an anonymous API without authentication to search for tweets.

Maybe you could consider this API when you hit the rate limits on twitter ?

Here's a link to a sample search query for POTUS twitter account.
http://loklak.org/api/search.json?q=from:POTUS

There's also a huge history of tweets that's saved with loklak which could possibly be useful in some way.

❤️ from the members at @loklak and @fossasia !

Dump Data

Any specific avenue recommended to dump the data (tweets) + (sentiment) and (analysing) results in to live databases ?

How to add main.py to the Linux VM?

I'm at the part where I SSH'd into my linux disk, but now I don't know how to import all the python code from this github. I'm sure its an easy step, that's why it was glossed over?

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.